react-semaphor 0.1.72 → 0.1.74
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/dashboard-plus-A8a3pEVQ.js +240 -0
- package/dist/chunks/{dashboard-plus-Bx5UNrFG.js → dashboard-plus-CC3NzmwJ.js} +5024 -4912
- package/dist/chunks/index-C_lgt5ew.js +1061 -0
- package/dist/chunks/{index-CqRITkaw.js → index-DVu3gyw9.js} +25014 -24072
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +3 -3
- package/dist/style.css +1 -1
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +1 -1
- package/dist/types/dashboard.d.ts +16 -1
- package/dist/types/main.d.ts +16 -1
- package/dist/types/surfboard.d.ts +16 -1
- package/dist/types/types.d.ts +16 -1
- package/package.json +3 -1
- package/dist/chunks/dashboard-plus-XyaJGT11.js +0 -245
- package/dist/chunks/index-DU-OzSbM.js +0 -1051
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
"use strict";const e=require("react/jsx-runtime"),s=require("./index-C_lgt5ew.js"),S=require("react"),gt=require("react-dom");function jt(t){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(a,n,r.get?r:{enumerable:!0,get:()=>t[n]})}}return a.default=t,Object.freeze(a)}const He=jt(S);/**
|
|
2
|
+
* @license lucide-react v0.453.0 - ISC
|
|
3
|
+
*
|
|
4
|
+
* This source code is licensed under the ISC license.
|
|
5
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
6
|
+
*/const bt=s.createLucideIcon("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]);/**
|
|
7
|
+
* @license lucide-react v0.453.0 - ISC
|
|
8
|
+
*
|
|
9
|
+
* This source code is licensed under the ISC license.
|
|
10
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
11
|
+
*/const vt=s.createLucideIcon("BookOpenText",[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M16 12h2",key:"7q9ll5"}],["path",{d:"M16 8h2",key:"msurwy"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}],["path",{d:"M6 12h2",key:"32wvfc"}],["path",{d:"M6 8h2",key:"30oboj"}]]);/**
|
|
12
|
+
* @license lucide-react v0.453.0 - ISC
|
|
13
|
+
*
|
|
14
|
+
* This source code is licensed under the ISC license.
|
|
15
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
16
|
+
*/const yt=s.createLucideIcon("ChevronsUpDown",[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]]);/**
|
|
17
|
+
* @license lucide-react v0.453.0 - ISC
|
|
18
|
+
*
|
|
19
|
+
* This source code is licensed under the ISC license.
|
|
20
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
21
|
+
*/const Nt=s.createLucideIcon("CirclePlus",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]]);/**
|
|
22
|
+
* @license lucide-react v0.453.0 - ISC
|
|
23
|
+
*
|
|
24
|
+
* This source code is licensed under the ISC license.
|
|
25
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
26
|
+
*/const Es=s.createLucideIcon("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/**
|
|
27
|
+
* @license lucide-react v0.453.0 - ISC
|
|
28
|
+
*
|
|
29
|
+
* This source code is licensed under the ISC license.
|
|
30
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
31
|
+
*/const Ct=s.createLucideIcon("Columns3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
|
|
32
|
+
* @license lucide-react v0.453.0 - ISC
|
|
33
|
+
*
|
|
34
|
+
* This source code is licensed under the ISC license.
|
|
35
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
36
|
+
*/const St=s.createLucideIcon("Component",[["path",{d:"M15.536 11.293a1 1 0 0 0 0 1.414l2.376 2.377a1 1 0 0 0 1.414 0l2.377-2.377a1 1 0 0 0 0-1.414l-2.377-2.377a1 1 0 0 0-1.414 0z",key:"1uwlt4"}],["path",{d:"M2.297 11.293a1 1 0 0 0 0 1.414l2.377 2.377a1 1 0 0 0 1.414 0l2.377-2.377a1 1 0 0 0 0-1.414L6.088 8.916a1 1 0 0 0-1.414 0z",key:"10291m"}],["path",{d:"M8.916 17.912a1 1 0 0 0 0 1.415l2.377 2.376a1 1 0 0 0 1.414 0l2.377-2.376a1 1 0 0 0 0-1.415l-2.377-2.376a1 1 0 0 0-1.414 0z",key:"1tqoq1"}],["path",{d:"M8.916 4.674a1 1 0 0 0 0 1.414l2.377 2.376a1 1 0 0 0 1.414 0l2.377-2.376a1 1 0 0 0 0-1.414l-2.377-2.377a1 1 0 0 0-1.414 0z",key:"1x6lto"}]]);/**
|
|
37
|
+
* @license lucide-react v0.453.0 - ISC
|
|
38
|
+
*
|
|
39
|
+
* This source code is licensed under the ISC license.
|
|
40
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
41
|
+
*/const wt=s.createLucideIcon("DatabaseZap",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 15 21.84",key:"14ibmq"}],["path",{d:"M21 5V8",key:"1marbg"}],["path",{d:"M21 12L18 17H22L19 22",key:"zafso"}],["path",{d:"M3 12A9 3 0 0 0 14.59 14.87",key:"1y4wr8"}]]);/**
|
|
42
|
+
* @license lucide-react v0.453.0 - ISC
|
|
43
|
+
*
|
|
44
|
+
* This source code is licensed under the ISC license.
|
|
45
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
46
|
+
*/const Dt=s.createLucideIcon("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]);/**
|
|
47
|
+
* @license lucide-react v0.453.0 - ISC
|
|
48
|
+
*
|
|
49
|
+
* This source code is licensed under the ISC license.
|
|
50
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
51
|
+
*/const Tt=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 Is=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 kt=s.createLucideIcon("FileJson2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1",key:"fq0c9t"}],["path",{d:"M8 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1",key:"4gibmv"}]]);/**
|
|
62
|
+
* @license lucide-react v0.453.0 - ISC
|
|
63
|
+
*
|
|
64
|
+
* This source code is licensed under the ISC license.
|
|
65
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
66
|
+
*/const Et=s.createLucideIcon("FolderOpen",[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]]);/**
|
|
67
|
+
* @license lucide-react v0.453.0 - ISC
|
|
68
|
+
*
|
|
69
|
+
* This source code is licensed under the ISC license.
|
|
70
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
71
|
+
*/const It=s.createLucideIcon("Fullscreen",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{width:"10",height:"8",x:"7",y:"8",rx:"1",key:"vys8me"}]]);/**
|
|
72
|
+
* @license lucide-react v0.453.0 - ISC
|
|
73
|
+
*
|
|
74
|
+
* This source code is licensed under the ISC license.
|
|
75
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
76
|
+
*/const At=s.createLucideIcon("GitCompareArrows",[["circle",{cx:"5",cy:"6",r:"3",key:"1qnov2"}],["path",{d:"M12 6h5a2 2 0 0 1 2 2v7",key:"1yj91y"}],["path",{d:"m15 9-3-3 3-3",key:"1lwv8l"}],["circle",{cx:"19",cy:"18",r:"3",key:"1qljk2"}],["path",{d:"M12 18H7a2 2 0 0 1-2-2V9",key:"16sdep"}],["path",{d:"m9 15 3 3-3 3",key:"1m3kbl"}]]);/**
|
|
77
|
+
* @license lucide-react v0.453.0 - ISC
|
|
78
|
+
*
|
|
79
|
+
* This source code is licensed under the ISC license.
|
|
80
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
81
|
+
*/const Mt=s.createLucideIcon("Glasses",[["circle",{cx:"6",cy:"15",r:"4",key:"vux9w4"}],["circle",{cx:"18",cy:"15",r:"4",key:"18o8ve"}],["path",{d:"M14 15a2 2 0 0 0-2-2 2 2 0 0 0-2 2",key:"1ag4bs"}],["path",{d:"M2.5 13 5 7c.7-1.3 1.4-2 3-2",key:"1hm1gs"}],["path",{d:"M21.5 13 19 7c-.7-1.3-1.5-2-3-2",key:"1r31ai"}]]);/**
|
|
82
|
+
* @license lucide-react v0.453.0 - ISC
|
|
83
|
+
*
|
|
84
|
+
* This source code is licensed under the ISC license.
|
|
85
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
86
|
+
*/const Lt=s.createLucideIcon("Hammer",[["path",{d:"m15 12-8.373 8.373a1 1 0 1 1-3-3L12 9",key:"eefl8a"}],["path",{d:"m18 15 4-4",key:"16gjal"}],["path",{d:"m21.5 11.5-1.914-1.914A2 2 0 0 1 19 8.172V7l-2.26-2.26a6 6 0 0 0-4.202-1.756L9 2.96l.92.82A6.18 6.18 0 0 1 12 8.4V10l2 2h1.172a2 2 0 0 1 1.414.586L18.5 14.5",key:"b7pghm"}]]);/**
|
|
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 Ft=s.createLucideIcon("LayoutList",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}],["path",{d:"M14 4h7",key:"3xa0d5"}],["path",{d:"M14 9h7",key:"1icrd9"}],["path",{d:"M14 15h7",key:"1mj8o2"}],["path",{d:"M14 20h7",key:"11slyb"}]]);/**
|
|
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 Pt=s.createLucideIcon("Library",[["path",{d:"m16 6 4 14",key:"ji33uf"}],["path",{d:"M12 6v14",key:"1n7gus"}],["path",{d:"M8 8v12",key:"1gg7y9"}],["path",{d:"M4 4v16",key:"6qkkli"}]]);/**
|
|
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 Ot=s.createLucideIcon("Link2",[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]]);/**
|
|
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 Bt=s.createLucideIcon("ListEnd",[["path",{d:"M16 12H3",key:"1a2rj7"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M10 18H3",key:"13769t"}],["path",{d:"M21 6v10a2 2 0 0 1-2 2h-5",key:"ilrcs8"}],["path",{d:"m16 16-2 2 2 2",key:"kkc6pm"}]]);/**
|
|
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 Rt=s.createLucideIcon("ListStart",[["path",{d:"M16 12H3",key:"1a2rj7"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"M10 6H3",key:"lf8lx7"}],["path",{d:"M21 18V8a2 2 0 0 0-2-2h-5",key:"1hghli"}],["path",{d:"m16 8-2-2 2-2",key:"160uvd"}]]);/**
|
|
112
|
+
* @license lucide-react v0.453.0 - ISC
|
|
113
|
+
*
|
|
114
|
+
* This source code is licensed under the ISC license.
|
|
115
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
116
|
+
*/const Vt=s.createLucideIcon("ListX",[["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"m19 10-4 4",key:"1tz659"}],["path",{d:"m15 10 4 4",key:"1n7nei"}]]);/**
|
|
117
|
+
* @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 zt=s.createLucideIcon("Menu",[["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}],["line",{x1:"4",x2:"20",y1:"6",y2:"6",key:"1owob3"}],["line",{x1:"4",x2:"20",y1:"18",y2:"18",key:"yk5zj1"}]]);/**
|
|
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 Gt=s.createLucideIcon("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]);/**
|
|
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 qe=s.createLucideIcon("MoveHorizontal",[["path",{d:"m18 8 4 4-4 4",key:"1ak13k"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}]]);/**
|
|
132
|
+
* @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 Ue=s.createLucideIcon("MoveVertical",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m8 18 4 4 4-4",key:"bh5tu3"}],["path",{d:"m8 6 4-4 4 4",key:"ybng9g"}]]);/**
|
|
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 $t=s.createLucideIcon("Palette",[["circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor",key:"1okk4w"}],["circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor",key:"f64h9f"}],["circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor",key:"fotxhn"}],["circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor",key:"qy21gx"}],["path",{d:"M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z",key:"12rzf8"}]]);/**
|
|
142
|
+
* @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 qt=s.createLucideIcon("PanelLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]);/**
|
|
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 hs=s.createLucideIcon("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/**
|
|
152
|
+
* @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 Ut=s.createLucideIcon("Rows3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M21 9H3",key:"1338ky"}],["path",{d:"M21 15H3",key:"9uk58r"}]]);/**
|
|
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 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"}]]);/**
|
|
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 Ae=s.createLucideIcon("Shapes",[["path",{d:"M8.3 10a.7.7 0 0 1-.626-1.079L11.4 3a.7.7 0 0 1 1.198-.043L16.3 8.9a.7.7 0 0 1-.572 1.1Z",key:"1bo67w"}],["rect",{x:"3",y:"14",width:"7",height:"7",rx:"1",key:"1bkyp8"}],["circle",{cx:"17.5",cy:"17.5",r:"3.5",key:"w3z12y"}]]);/**
|
|
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 Kt=s.createLucideIcon("ShieldX",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m14.5 9.5-5 5",key:"17q4r4"}],["path",{d:"m9.5 9.5 5 5",key:"18nt4w"}]]);/**
|
|
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 As=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 _t=s.createLucideIcon("SquareSplitVertical",[["path",{d:"M5 8V5c0-1 1-2 2-2h10c1 0 2 1 2 2v3",key:"1pi83i"}],["path",{d:"M19 16v3c0 1-1 2-2 2H7c-1 0-2-1-2-2v-3",key:"ido5k7"}],["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}]]);/**
|
|
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 Ht=s.createLucideIcon("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/**
|
|
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 Jt=s.createLucideIcon("Sun",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]]);/**
|
|
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 Ms=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"}]]);/**
|
|
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 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"}]]);/**
|
|
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 Wt=s.createLucideIcon("Terminal",[["polyline",{points:"4 17 10 11 4 5",key:"akl6gq"}],["line",{x1:"12",x2:"20",y1:"19",y2:"19",key:"q2wloq"}]]);/**
|
|
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 Yt=s.createLucideIcon("View",[["path",{d:"M21 17v2a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-2",key:"mrq65r"}],["path",{d:"M21 7V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2",key:"be3xqs"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["path",{d:"M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0",key:"11ak4c"}]]);/**
|
|
212
|
+
* @license lucide-react v0.453.0 - ISC
|
|
213
|
+
*
|
|
214
|
+
* This source code is licensed under the ISC license.
|
|
215
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
216
|
+
*/const Xt=s.createLucideIcon("Wand",[["path",{d:"M15 4V2",key:"z1p9b7"}],["path",{d:"M15 16v-2",key:"px0unx"}],["path",{d:"M8 9h2",key:"1g203m"}],["path",{d:"M20 9h2",key:"19tzq7"}],["path",{d:"M17.8 11.8 19 13",key:"yihg8r"}],["path",{d:"M15 9h.01",key:"x1ddxp"}],["path",{d:"M17.8 6.2 19 5",key:"fd4us0"}],["path",{d:"m3 21 9-9",key:"1jfql5"}],["path",{d:"M12.2 6.2 11 5",key:"i3da3b"}]]);function Ls(t,a={}){const{enabled:n=!0,eventType:r="mousedown"}=a,l=S.useRef(null);return S.useEffect(()=>{const i=c=>{const o=c.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,i),()=>{document.removeEventListener(r,i)}},[t,n,r]),l}function Zt(){const{setTheme:t}=s.useTheme(),a=s.useDashboardStore(n=>n.actions.setDashboardTheme);return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsxs(s.Button,{className:"h-7 p-2",variant:"ghost",size:"sm",children:[e.jsx(Jt,{strokeWidth:1.5,className:"h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(Gt,{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 ze(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 i;return{...l,cards:(i=l.cards)==null?void 0:i.map(c=>Fs(c))}})}})}}function Fs(t){return{...t,customCfg:ea(t.customCfg),data:[]}}function ea(t){var a,n;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(n=(a=t==null?void 0:t.data)==null?void 0:a.datasets)==null?void 0:n.map(r=>({...r,data:[]}))}}:null}async function sa(t,a,n,r,l){if(!l)return null;const i=JSON.stringify(n),c=`${t}/v1/lens`;return await s.postRequest(c,l,{name:a,template:i,filterValues:r,operation:"create"})}async function Je(t,a,n){if(!n)return null;const{id:r,template:l,filterValues:i,isDefault:c,shared:o}=a,d=`${t}/v1/lens`;return await s.postRequest(d,n,{lensId:r,template:l,filterValues:i,isDefault:c,shared:o,operation:"update"})}async function ta(t,a,n){if(!n)return null;const r=`${t}/v1/lens`;return await s.postRequest(r,n,{operation:"delete",lensId:a})}function aa(){const[t,a]=S.useState(""),[n,r]=S.useState(!1),l=s.useDashboardStore(v=>v.lenses),{setLenses:i,setSelectedLensId:c}=s.useDashboardActions(),[o,d]=S.useState(!1),[u,m]=S.useState(!1),x=s.useDashboardStore(v=>v.dashboard),h=s.useDashboardStore(v=>v.filterValues),{authToken:p,tokenProps:j}=s.useSemaphorContext();async function g(){d(!0);const v=ze(x),D=await sa(j.apiServiceUrl,t,v,h,p==null?void 0:p.accessToken);D&&(i([...l||[],D]),c(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 na(){const[t,a]=S.useState(!1),n=s.useDashboardStore(x=>x.lenses),r=s.useDashboardStore(x=>x.selectedLensId),{setLenses:l,setSelectedLensId:i}=s.useDashboardActions(),{authToken:c,tokenProps:o}=s.useSemaphorContext();async function d(x){i(x)}async function u(x){if(await ta(o.apiServiceUrl,x,c==null?void 0:c.accessToken)){const p=n==null?void 0:n.filter(j=>j.id!==x);l(p||[]),i("original")}}async function m(x){const h=n==null?void 0:n.map(g=>g.id===x.id?{...g,isDefault:!x.isDefault}:{...g,isDefault:!1});l(h||[]);const p={...x,isDefault:!x.isDefault};await Je(o.apiServiceUrl,p,c==null?void 0:c.accessToken);const j=n==null?void 0:n.find(g=>g.isDefault);if(j&&j.id!==x.id){const g={...j,isDefault:!1};await Je(o.apiServiceUrl,g,c==null?void 0:c.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:a,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(Mt,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(s.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuRadioGroup,{value:r,onValueChange:d,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),n==null?void 0:n.map(x=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:x.id,children:[e.jsx("p",{children:x.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:h=>{h.preventDefault(),m(x)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!x.isDefault,"text-green-500":x.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:h=>{h.preventDefault(),u(x.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},x.id))]})]})]})}function ra({iconClassName:t}){const[a,n]=S.useState(!1),[r,l]=S.useState(""),[i,c]=S.useState(!1),o=s.useDashboardStore(x=>x.isDownloadingPdf),{tokenProps:d}=s.useSemaphorContext();async function u(){const x=s.ue.loading("Generating PDF... may take up to 60 seconds");try{await s.downloadPdf(d.apiServiceUrl),s.ue.dismiss(x),s.ue.success("PDF downloaded successfully!",{duration:2e3})}catch(h){s.ue.dismiss(x),s.ue.error("Failed to download PDF",{description:"Please try again or contact support.",richColors:!0}),console.error("PDF download error:",h)}}async function m(){if(!r)return;n(!1),l(""),c(!1);const x=s.ue.loading("Generating protected PDF... may take up to 60 seconds");try{await s.downloadPdf(d.apiServiceUrl,r),s.ue.dismiss(x),s.ue.success("Protected PDF downloaded successfully!",{duration:2e3,position:"top-right"})}catch(h){s.ue.dismiss(x),s.ue.error("Failed to download protected PDF. Please try again."),console.error("Protected PDF download error:",h)}}return e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled:o,children:e.jsx(s.Download,{className:s.cn("size-4",t)})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsxs(s.DropdownMenuItem,{onClick:u,children:[e.jsx(s.File,{className:"mr-2 h-4 w-4"}),"Download PDF"]}),e.jsxs(s.DropdownMenuItem,{onClick:()=>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:i?"text":"password",value:r,onChange:x=>l(x.target.value),placeholder:"Enter password",className:"pr-10",onKeyDown:x=>{x.key==="Enter"&&r&&m()}}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent",onClick:()=>c(!i),children:i?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 Ps({triggerButtonClassName:t}){const[a,n]=S.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}),i=s.useDashboardStore(o=>{var d;return(d=o.dashboard)==null?void 0:d.sheets}),c=s.useDashboardStore(o=>o.selectedSheetId);return i==null||i.find(o=>o.id===c),r?e.jsxs(e.Fragment,{children:[e.jsx(s.IconButton,{tooltip:"Schedule Dashboard",className:s.cn("h-7 p-2",t),onClick:()=>n(!0),children:e.jsx(s.Clock,{className:"size-4"})}),e.jsx(s.EmailScheduleDialog,{open:a,onOpenChange:n,dashboardId:r,dashboardName:l})]}):null}const la=async(t,a,n)=>{const r=`${t}/management/v1/groups`;return await s.postRequestRegular(r,a,n)},oa=async(t,a,n)=>{const r=`${t}/management/v1/groups/${n}`,l=await fetch(r,{method:"DELETE",headers:{Authorization:`Bearer ${a}`}});if(!l.ok){const i=await l.text();throw new Error(i||"Failed to delete group")}},ia=async(t,a,n,r)=>{const l=`${t}/management/v1/groups/${n}/members`;return await s.postRequestRegular(l,a,r)},ca=async(t,a,n,r)=>{const l=`${t}/management/v1/groups/${n}/members`,i=await fetch(l,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(r)});if(!i.ok){const c=await i.text();throw new Error(c||"Failed to remove group members")}};function da(){const{authToken:t,tokenProps:a}=s.useSemaphorContext(),n=s.useQueryClient();return s.useMutation({mutationFn:r=>la(a.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),s.ue.success("Group created successfully")},onError:r=>{console.error("Failed to create group:",r),s.ue.error("Failed to create group",{description:r.message})}})}function ua(){const{authToken:t,tokenProps:a}=s.useSemaphorContext(),n=s.useQueryClient();return s.useMutation({mutationFn:r=>oa(a.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r),onSuccess:(r,l)=>{n.invalidateQueries({queryKey:["groups"]}),n.removeQueries({queryKey:["group",l]}),s.ue.success("Group deleted successfully")},onError:r=>{console.error("Failed to delete group:",r),s.ue.error("Failed to delete group",{description:r.message})}})}function ma(){const{authToken:t,tokenProps:a}=s.useSemaphorContext(),n=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>ia(a.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r,l),onSuccess:(r,l)=>{n.invalidateQueries({queryKey:["group",l.groupId]}),n.invalidateQueries({queryKey:["group-members",l.groupId]}),n.invalidateQueries({queryKey:["groups"]}),s.ue.success("Members added successfully")},onError:r=>{console.error("Failed to add group members:",r),s.ue.error("Failed to add members",{description:r.message})}})}function ha(){const{authToken:t,tokenProps:a}=s.useSemaphorContext(),n=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>ca(a.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r,l),onSuccess:(r,l)=>{n.invalidateQueries({queryKey:["group",l.groupId]}),n.invalidateQueries({queryKey:["group-members",l.groupId]}),n.invalidateQueries({queryKey:["groups"]}),s.ue.success("Members removed successfully")},onError:r=>{console.error("Failed to remove group members:",r),s.ue.error("Failed to remove members",{description:r.message})}})}function xa({onSuccess:t,tenantId:a,isTenantUser:n}){const[r,l]=S.useState(""),[i,c]=S.useState(""),[o,d]=S.useState({}),u=da(),m=()=>{const h={};return r.trim()?r.length<3?h.name="Group name must be at least 3 characters":r.length>50&&(h.name="Group name must be less than 50 characters"):h.name="Group name is required",i&&i.length>200&&(h.description="Description must be less than 200 characters"),d(h),Object.keys(h).length===0},x=async h=>{if(h.preventDefault(),!m())return;const p={name:r.trim(),description:i.trim()||void 0,type:n?"TENANT_GROUP":"ORG_GROUP",...n&&a?{tenantId:a}:{}};try{await u.mutateAsync(p),l(""),c(""),d({}),t()}catch(j){console.error("Failed to create group:",j)}};return e.jsxs("form",{onSubmit:x,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"group-name",children:["Group Name ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(s.Input,{id:"group-name",placeholder:"e.g., Marketing Team, Engineering Squad",value:r,onChange:h=>{l(h.target.value),o.name&&d(p=>({...p,name:""}))},className:o.name?"border-destructive":"",disabled:u.isPending}),o.name&&e.jsx("p",{className:"text-sm text-destructive",children:o.name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"group-description",children:["Description",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:"(optional)"})]}),e.jsx(s.Textarea,{id:"group-description",placeholder:"Describe the purpose of this group...",value:i,onChange:h=>{c(h.target.value),o.description&&d(p=>({...p,description:""}))},className:o.description?"border-destructive":"",disabled:u.isPending,rows:3}),o.description&&e.jsx("p",{className:"text-sm text-destructive",children:o.description}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[i.length,"/200 characters"]})]}),e.jsx("div",{className:"rounded-lg border bg-muted/50 p-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(s.CircleAlert,{className:"h-4 w-4 mt-0.5 text-muted-foreground"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"This group will be accessible to users in your workspace. You can add members after creating the group."})]})})]}),e.jsxs("div",{className:"flex justify-end gap-3",children:[e.jsx(s.Button,{type:"button",variant:"outline",onClick:()=>{l(""),c(""),d({})},disabled:u.isPending,children:"Clear"}),e.jsx(s.Button,{type:"submit",disabled:u.isPending||!r.trim(),children:u.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Users,{className:"mr-2 h-4 w-4"}),"Create Group"]})})]})]})}function pa({open:t,onOpenChange:a,group:n,onUpdate:r}){const[l,i]=S.useState("members"),[c,o]=S.useState(""),[d,u]=S.useState([]),[m,x]=S.useState([]),{data:h,isLoading:p,refetch:j}=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=ma(),B=ha(),L=(h==null?void 0:h.members)||[],E=S.useMemo(()=>new Set(L.map(I=>I.userId)),[L]),C=S.useMemo(()=>v.filter(I=>!E.has(I.id)),[v,E]),f=S.useMemo(()=>{if(!c)return C;const I=c.toLowerCase();return C.filter(T=>{var y,M;return((y=T.name)==null?void 0:y.toLowerCase().includes(I))||((M=T.email)==null?void 0:M.toLowerCase().includes(I))})},[C,c]),b=S.useMemo(()=>{if(!c)return L;const I=c.toLowerCase();return L.filter(T=>{var y,M,F,z;return((M=(y=T.user)==null?void 0:y.name)==null?void 0:M.toLowerCase().includes(I))||((z=(F=T.user)==null?void 0:F.email)==null?void 0:z.toLowerCase().includes(I))})},[L,c]),N=async()=>{if(d.length!==0)try{await k.mutateAsync({groupId:n.id,data:{userIds:d,userType:g==="tenant"?"tenant":"org"}}),u([]),i("members"),j(),r==null||r()}catch(I){console.error("Failed to add members:",I)}},A=async()=>{if(m.length!==0)try{await B.mutateAsync({groupId:n.id,data:{userIds:m}}),x([]),j(),r==null||r()}catch(I){console.error("Failed to remove members:",I)}},w=I=>{u(T=>T.includes(I)?T.filter(y=>y!==I):[...T,I])},P=I=>{x(T=>T.includes(I)?T.filter(y=>y!==I):[...T,I])};return e.jsx(e.Fragment,{children:e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"max-w-3xl max-h-[80vh]","aria-describedby":"group-members-description",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:n.name}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[L.length," ",L.length===1?"member":"members"]})}),e.jsxs("p",{id:"group-members-description",className:"sr-only",children:["Add or remove members from the ",n.name," group"]})]}),e.jsxs(s.Tabs,{value:l,onValueChange:I=>{i(I),o(""),x([])},className:"mt-4",children:[e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"members",children:"Current Members"}),e.jsx(s.TabsTrigger,{value:"add",children:"Add Members"})]}),e.jsxs(s.TabsContent,{value:"members",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search members...",value:c,onChange:I=>o(I.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:m.length>0?"h-[300px]":"h-[350px]",children:p?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(I=>e.jsx(s.Skeleton,{className:"h-16 w-full"},I))}):b.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(s.Users,{className:"h-12 w-12 mb-3 opacity-50"}),e.jsx("p",{className:"text-sm font-medium",children:c?"No members found":"No members yet"}),e.jsx("p",{className:"text-xs mt-1",children:c?"Try a different search":'Switch to the "Add Members" tab to add people to this group'})]}):e.jsx("div",{className:"space-y-2",children:b.map(I=>e.jsx(fa,{member:I,selected:m.includes(I.userId),onToggle:()=>P(I.userId)},I.id))})}),m.length>0&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[m.length," member",m.length!==1?"s":""," selected"]}),e.jsx(s.Button,{variant:"destructive",size:"sm",onClick:A,disabled:B.isPending,children:B.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Removing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Trash2,{className:"mr-2 h-4 w-4"}),"Remove Selected"]})})]})]}),e.jsxs(s.TabsContent,{value:"add",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search users to add...",value:c,onChange:I=>o(I.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(I=>e.jsx(s.Skeleton,{className:"h-16 w-full"},I))}):f.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(s.UserPlus,{className:"h-12 w-12 mb-3 opacity-50"}),e.jsx("p",{className:"text-sm font-medium",children:"No available users"}),e.jsx("p",{className:"text-xs mt-1",children:c?"Try a different search":"All eligible users are already members"})]}):e.jsx("div",{className:"space-y-2",children:f.map(I=>e.jsx(ga,{user:I,selected:d.includes(I.id),onToggle:()=>w(I.id)},I.id))})}),d.length>0&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[d.length," user",d.length!==1?"s":""," selected"]}),e.jsx(s.Button,{onClick:N,disabled: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 fa({member:t,selected:a,onToggle:n}){var l,i,c,o;const r=((i=(l=t.user)==null?void 0:l.name)==null?void 0:i.split(" ").map(d=>d[0]).join("").toUpperCase())||"?";return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-card hover:bg-muted/50 cursor-pointer",onClick:n,children:[e.jsx(s.Checkbox,{checked:a}),e.jsx(s.Avatar,{className:"h-8 w-8",children:e.jsx(s.AvatarFallback,{className:"text-xs",children:r})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:((c=t.user)==null?void 0:c.name)||"Unknown User"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(o=t.user)==null?void 0:o.email})]})]})}function ga({user:t,selected:a,onToggle:n}){var l;const r=((l=t.name)==null?void 0:l.split(" ").map(i=>i[0]).join("").toUpperCase())||"?";return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-card hover:bg-muted/50 cursor-pointer",onClick:n,children:[e.jsx(s.Checkbox,{checked:a}),e.jsx(s.Avatar,{className:"h-8 w-8",children:e.jsx(s.AvatarFallback,{className:"text-xs",children:r})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:t.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t.email})]})]})}function ja({open:t,onOpenChange:a}){const[n,r]=S.useState("groups"),[l,i]=S.useState(""),[c,o]=S.useState(null),[d,u]=S.useState(!1),[m,x]=S.useState(null),{tokenProps:h}=s.useSemaphorContext(),{currentUser:p}=s.useCurrentUserInfo(),j=ua(),g=(p==null?void 0:p.type)==="tenant",v=h==null?void 0:h.tenantId,{groups:D,isLoading:k,refetch:B}=s.useGroups({type:g?"TENANT_GROUP":"all",tenantId:g?v:void 0,includeMembers:!1}),L=D.filter(b=>{var N;return b.name.toLowerCase().includes(l.toLowerCase())||((N=b.description)==null?void 0:N.toLowerCase().includes(l.toLowerCase()))}),E=async()=>{if(m)try{await j.mutateAsync(m.id),x(null),B()}catch(b){console.error("Failed to delete group:",b)}},C=b=>{o(b),u(!0)},f=()=>{r("groups"),B()};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:b=>i(b.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(b=>e.jsx(s.Skeleton,{className:"h-24 w-full"},b))}):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(b=>e.jsx(ba,{group:b,onManageMembers:()=>C(b),onDelete:()=>x(b),currentUserId:p==null?void 0:p.id},b.id))})})]})}),e.jsx(s.TabsContent,{value:"create",className:"mt-4",children:e.jsx(xa,{onSuccess:f,tenantId:v,isTenantUser:g})})]})]})}),c&&e.jsx(pa,{open:d,onOpenChange:u,group:c,onUpdate:()=>B()}),e.jsx(s.AlertDialog,{open:!!m,onOpenChange:()=>x(null),children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Group"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',m==null?void 0:m.name,'"? This action cannot be undone and will remove all members from the group.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:E,disabled:j.isPending,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:j.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Deleting..."]}):"Delete Group"})]})]})})]})}function ba({group:t,onManageMembers:a,onDelete:n,currentUserId:r}){const l=t.createdBy===r;return e.jsx("div",{className:"rounded-lg border bg-card p-4 transition-colors hover:bg-muted/50",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium",children:t.name}),t.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:t.description})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(s.Users,{className:"h-3 w-3"}),t.memberCount," ",t.memberCount===1?"member":"members"]}),e.jsxs("span",{children:["Created ",s.format(new Date(t.createdAt),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:a,title:"Manage members",children:e.jsx(s.UserPlus,{className:"h-4 w-4"})}),l&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:n,title:"Delete group",className:"text-destructive hover:text-destructive",children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]})})}function Xe(t){const[a,n]=S.useState(null),[r,l]=S.useState(null);return S.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(c){const o=c instanceof Error?c.message:"Unknown error";console.error("Failed to load remote chart store:",o),l(o),n(null)}})()},[t]),a}function va(t){const a=t.toUpperCase().indexOf("WHERE"),n=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),l=t.toUpperCase().indexOf("ORDER BY");let i=t.length;if(l!==-1&&(i=l),r!==-1&&r<i&&(i=r),a!==-1){const c=t.substring(0,a),o=t.substring(a);return`${c} {{ filters | where }} AND ${o.substring(6)}`}else if(n!==-1){const c=t.substring(0,n),o=t.substring(n);return`${c} {{ filters | where }} ${o}`}else{const c=t.substring(0,i),o=t.substring(i);return console.log("beforeClause",c),console.log("afterClause",o),o?`${c} {{ filters | where }} ${o}`:`${c.replace(/;$/,"")} {{ filters | where }}`}}function ya(t,a){if(t.length===0)return"";if(a){const n=t.find(r=>r.id===a);if(n){const r=n.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const i=r.split("__")[0],c=t.find(o=>o.tabTitle===i);return c?c.id:t[0].id}return a}}return t[0].id}async function xs(t,a,n,r){if(!a||!n)throw new Error("Missing auth token or visual ID");const l=["resource-by-id","visual",n],i=r.getQueryData(l);if(i)return console.log("Using cached visual data for:",n),{data:i,fromCache:!0};console.log("Fetching visual data from network for:",n);const c=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(c),{data:d,fromCache:!1}}catch(o){throw s.ue.dismiss(c),o}}function Os(t){if(typeof t=="string")return JSON.parse(t);if(typeof t=="object")return t;throw new Error("Invalid frame object format")}function Na(t,a){var i,c;const n=(t==null?void 0:t.frameObject)??((i=t==null?void 0:t.visual)==null?void 0:i.frameObject);if(!n)return!1;const r=Os(n);if(!(r!=null&&r.cards)||r.cards.length===0)return!1;const l=(c=r.cards)==null?void 0:c.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 Ca(){var h;const{setCardSql:t}=s.useEditorActions(),a=s.useEditorStore(p=>p.frame),n=s.useEditorStore(p=>p.card),r=Xe(((h=n.customCardPreferences)==null?void 0:h.url)||""),l=s.useEditorStore(p=>p.selectedSchemaName),i=s.useEditorStore(p=>p.selectedDatamodelId),c=s.useEditorStore(p=>p.selectedDatabaseName),o=s.useEditorStore(p=>p.selectedTableName),d=s.useEditorStore(p=>p.selectedConnectionId),u=s.useEditorStore(p=>p.isShowingVisual),m=n.sql;return{getUpdatedFrame:S.useCallback(()=>{var D;let p=m;m&&!m.includes("{{")&&(p=va(m),t(p));const j=(D=r==null?void 0:r.getState())==null?void 0:D.settings,g={...n,dataSource:n.dataSource||{mode:"directSource"},lastSelectedSchema:l,lastSelectedDatamodelId:i,lastSelectedDatabase:c,lastSelectedTable:o,connectionId:d,sql:p,customCfg:u?n.customCfg:null,preferences:n.preferences,...j&&{customCardPreferences:{...n.customCardPreferences,settings:j}}},v=a.cards.map(k=>k.id===n.id?g:k);return{...a,cards:v,activeCardId:ya(v,a.activeCardId)}},[n,a,u,l,i,c,o,d,t,r,m])}}function Te(){const{authToken:t,tokenProps:a}=s.useSemaphorContext(),n=s.useQueryClient(),r=s.useSelectedVisual(),{selectVisual:l}=s.useManagementActions(),{setFrame:i,setCard:c,setIsDevMode:o,setActiveTabCardId:d,updateDataSource:u,setQueryResultColumns:m,setSelectedConnectionId:x,setSelectedDatabaseName:h,setSelectedSchemaName:p,setSelectedTableName:j,setSelectedDatamodelId:g,setFilterValues:v,setApplyFilters:D}=s.useEditorActions(),{setIsDashboardEditing:k,setIsVisualEditing:B,setSelectedFrameId:L,clearSelectedFrameId:E,addFrame:C,setIsDashboardPanelOpen:f}=s.useDashboardActions(),b=s.useDashboardStore(y=>y.selectedSheetId),N=s.useDashboardStore(y=>y.selectedFrameId),A=s.useDashboardStore(y=>y.dashboard),w=s.useDashboardStore(y=>y.filterValues),P=s.useVisualById((r==null?void 0:r.id)||"",{enabled:!!(r!=null&&r.id)&&!!(t!=null&&t.accessToken)}),I=S.useCallback(async y=>{try{l(y),E();const{data:M,fromCache:F}=await xs(a.apiServiceUrl,(t==null?void 0:t.accessToken)||"",y.id,n);if(!Na(M,{setFrame:i,setCard:c,setIsDevMode:o,setActiveTabCardId:d,updateDataSource:u,setQueryResultColumns:m,setSelectedConnectionId:x,setSelectedDatabaseName:h,setSelectedSchemaName:p,setSelectedTableName:j,setSelectedDatamodelId:g,setFilterValues:v,setApplyFilters:D,setIsDashboardEditing:k,setIsVisualEditing:B,dashboard:A,selectedSheetId:b,selectedFrameId:N,filterValues:w}))throw new Error("Failed to setup editor with visual data");return{success:!0,fromCache:F}}catch(M){return console.error("Error editing visual:",M),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,a.apiServiceUrl,n,l,i,c,k,B,o,d,u,m,x,h,p,j,g,v,D,E,A,b,N,w]),T=S.useCallback(async y=>{var M;try{if(l(y),!b)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:F,fromCache:z}=await xs(a.apiServiceUrl,(t==null?void 0:t.accessToken)||"",y.id,n),$=(F==null?void 0:F.frameObject)??((M=F==null?void 0:F.visual)==null?void 0:M.frameObject);if(!$)return{success:!1,error:"Visual has no frame data"};const O=Os($);if(!(O!=null&&O.cards)||O.cards.length===0)return{success:!1,error:"Visual frame is malformed"};const G={...O,id:s.v4(),visualId:y.id};return C(b,G,"end"),k(!0),L(G.id),f(!1),{success:!0,fromCache:z}}catch(F){return console.error("Error adding visual:",F),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,a.apiServiceUrl,n,l,b,C,k,L,f]);return{visual:P.data,isLoading:P.isLoading,isError:P.isError,error:P.error,handleEditLibraryVisual:I,handleAddLibraryVisual:T,getUpdatedFrame:Ca().getUpdatedFrame,refetch:P.refetch}}function Sa({open:t,onOpenChange:a,isLibraryVisual:n,currentVisualName:r,isSaving:l=!1,onConfirm:i}){const[c,o]=S.useState(n&&r?`Copy of ${r}`:r||""),[d,u]=S.useState(""),[m,x]=S.useState(!n),[h,p]=S.useState(!0);S.useEffect(()=>{t&&(o(n&&r?`Copy of ${r}`:r||""),u(""),x(!n),p(!0))},[t,n,r]);const j=()=>{c.trim()&&(!m&&!h||i({name:c.trim(),description:d.trim()||void 0,saveToLibrary:m,saveToCurrentDashboard:h}))},g=c.trim()&&(m||h);return e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Save Visual As"}),e.jsx(s.DialogDescription,{children:n?"Create a copy of this visual with a new name":"Save this visual to make it reusable"})]}),e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"name",children:"Name"}),e.jsx(s.Input$1,{id:"name",value:c,onChange:v=>o(v.target.value),placeholder:"Enter visual name",disabled:l})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"description",children:"Description (optional)"}),e.jsx(s.Textarea,{id:"description",value:d,onChange:v=>u(v.target.value),placeholder:"Enter visual description",rows:3,disabled:l})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Label,{children:"Save to:"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"save-to-dashboard",checked:h,onCheckedChange:v=>p(!!v),disabled:l}),e.jsxs("label",{htmlFor:"save-to-dashboard",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:["Current Dashboard",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children: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=>x(!!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&&!h&&e.jsx("p",{className:"text-sm text-destructive",children:"Please select at least one destination"})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),disabled:l,children:"Cancel"}),e.jsxs(s.Button,{onClick:j,disabled:!g||l,children:[l&&e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),l?"Saving...":"Save"]})]})]})})}function wa({className:t,variant:a="outline"}){var o;const{setCardSql:n}=s.useEditorActions();s.useEditorStore(d=>d.frame);const r=s.useEditorStore(d=>d.card);Xe(((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:i}=Te();function c(){const d=i();l==null||l(d)}return e.jsxs(s.Button,{onClick:c,className:s.cn("h-8",t),size:"sm",variant:a,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function Da({className:t,variant:a="default"}){const n=s.useQueryClient(),[r,l]=S.useState(!1),i=s.useDashboardStore(h=>h.actions.setIsDashboardPanelOpen),{setIsVisualEditing:c}=s.useDashboardActions(),{getUpdatedFrame:o}=Te(),d=s.useSelectedVisual(),u=s.useEditorStore(h=>h.frame),m=s.useUpdateVisualMutation(),x=()=>{const h=o(),p=(u==null?void 0:u.visualId)||(d==null?void 0:d.id);if(!p){s.ue.error("No visual to save");return}l(!0),m.mutate({visualId:p,data:{frameObject:h}},{onSuccess:()=>{l(!1),i(!0),s.ue.success("Visual updated successfully"),n.invalidateQueries({queryKey:["resource-by-id","visual",p],exact:!0})},onError:()=>{l(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:x,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 Ta({className:t}){const a=s.useQueryClient(),[n,r]=S.useState(!1),l=s.useSelectedVisual(),i=s.useEditorStore(h=>h.frame),c=s.useDashboardStore(h=>h.selectedSheetId),{updateFrame:o,setIsVisualEditing:d}=s.useDashboardActions(),{getUpdatedFrame:u}=Te(),m=s.useUpdateVisualMutation(),x=async()=>{if(!c){s.ue.error("No sheet selected");return}const h=(i==null?void 0:i.visualId)||(l==null?void 0:l.id);if(!h){s.ue.error("No visual to update");return}r(!0);try{const p=u();await m.mutateAsync({visualId:h,data:{frameObject:p}});const j={...p,visualId:h};o(c,j),a.invalidateQueries({queryKey:["visuals"]}),a.invalidateQueries({queryKey:["visual",h]}),s.ue.success("Saved to library and applied locally"),setTimeout(()=>{d(!1)},300)}catch(p){console.error("Failed to save and apply:",p),s.ue.error("Failed to save and apply changes")}finally{r(!1)}};return e.jsx(s.Button,{onClick:x,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 ka({className:t}){const{getUpdatedFrame:a}=Te();s.useEditorStore(d=>d.frame);const n=s.useDashboardStore(d=>d.selectedSheetId),{updateFrame:r,setIsVisualEditing:l}=s.useDashboardActions(),[i,c]=S.useState(!1),o=()=>{if(!n){s.ue.error("No sheet selected");return}c(!0);const u={...a(),visualId:void 0};r(n,u),setTimeout(()=>{c(!1),s.ue.success("Changes applied. Visual is now local to this dashboard"),l(!1)},300)};return e.jsxs(s.Button,{onClick:o,className:s.cn("h-8",t),size:"sm",variant:"outline",children:[i&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Applying"]}),!i&&e.jsxs(e.Fragment,{children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Apply Locally"]})]})}function Ea({className:t}){const{setTempQueryData:a,setSqlGen:n}=s.useEditorActions(),r=s.useQueryClient(),l=s.useEditorStore(u=>u.tempQueryData),i=s.useEditorStore(u=>u.onClose),c=s.useEditorStore(u=>u.card),{queryKey:o}=s.useDashboardCardQuery(c);function d(){if(l){const{queryKey:u,queryData:m}=l;u&&m&&r.setQueryData(u,m)}n({}),i==null||i()}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 Ze(){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:i,setSqlGen:c,setCardPython:o,setCardCustomCfg:d,setCardPreferences:u,updateDataSource:m,clearQueryConfig:x,setCardConfig:h,setCardType:p}=s.useEditorActions();function j(){const g=a.getQueryData(l);n!=null&&n.queryData||t({queryKey:l,queryData:g}),a.setQueryData(l,null),a.removeQueries({queryKey:l,exact:!0}),i(""),c({}),x(),h(void 0),o(""),d(""),u({}),p("bar")}return e.jsxs(s.Button,{onClick:j,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(Dt,{className:"mr-2 size-4"}),"Clear"]})}function Ia(){const[t,a]=S.useState(!1),[n,r]=S.useState(!1),[l,i]=S.useState(null),c=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:x}=Te(),{selectVisual:h}=s.useManagementActions(),{addFrame:p,setSelectedFrameId:j,setIsVisualEditing:g}=s.useDashboardActions(),v=!!(c!=null&&c.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(h(L),n&&l&&u){const E={...l,id:s.v4(),visualId:L.id};p(u,E,"end"),j(E.id),r(!1),i(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 E=x();if(L.saveToLibrary){r(L.saveToCurrentDashboard),i(E);const C={title:L.name,description:L.description,frameObject:E,isPrivate:!1};k.mutate(C)}else if(L.saveToCurrentDashboard){const C={...E,id:s.v4(),visualId:void 0,cards:E.cards.map(f=>({...f,title:f.id===o.id?L.name:f.title}))};p(u,C,"end"),j(C.id),s.ue.success("Visual saved to dashboard"),a(!1),g(!1)}},isLibraryVisual:v,currentVisualName:D,isSaving:k.isPending}}function Bs({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),i=s.useDashboardStore(k=>k.selectedSheetId),{setIsVisualEditing:c}=s.useDashboardActions(),o=!!(a!=null&&a.visualId||r!=null&&r.id),d=!!(a!=null&&a.visualId&&l),u=o&&!d,{saveAsDialogOpen:m,setSaveAsDialogOpen:x,handleSaveAs:h,isLibraryVisual:p,currentVisualName:j,isSaving:g}=Ia(),{handleAddLibraryVisual:v}=Te(),D=async()=>{if(!i){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"),c(!1)):s.ue.error(k.error||"Failed to add visual to dashboard")};return e.jsxs(e.Fragment,{children:[!o&&e.jsx(wa,{className:t,variant:"default"}),o&&e.jsxs(e.Fragment,{children:[d&&e.jsx(ka,{className:t}),u&&i&&n&&(n.sql||s.hasValidCardConfig(n.config))&&e.jsxs(s.Button,{onClick:D,className:s.cn(t),size:"sm",variant:"outline",children:[e.jsx(Nt,{className:"mr-2 size-4 font-bold"}),"Add to Dashboard"]}),u&&e.jsx(Da,{className:t,variant:"default"}),d&&e.jsx(Ta,{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(),x(!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:()=>x(!0),children:[e.jsx(Ie,{className:"mr-2 h-4 w-4"}),"Save As..."]})})]}),e.jsx(Ea,{className:t}),e.jsx(Sa,{open:m,onOpenChange:k=>{g||x(k)},isLibraryVisual:p,currentVisualName:j,isSaving:g,onConfirm:h})]})}function Rs({className:t,switchClassName:a}){const n=s.useEditorStore(o=>o.isDevMode),r=s.useDashboardStore(o=>o.isVisualEditing),{setIsDevMode:l}=s.useEditorActions(),{config:i}=S.useContext(s.SemaphorContext).tokenProps,c=(i==null?void 0:i.showAdvancedMode)!==!1;return!r||!c?null:e.jsxs("div",{className:s.cn("flex items-center space-x-2",t),children:[e.jsx(s.DevModeSwitch,{className:s.cn("",a),checked:n,onCheckedChange:()=>l(!n),id:"advanced-mode",icon:e.jsx(s.CodeXml,{className:"h-4 w-4"}),tooltip:n?"Standard Mode":"Advanced Mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:"sr-only",children:"Advanced Mode"})]})}function Aa(){var pe,fe,ce;const{authToken:t,tokenProps:a,id:n}=s.useSemaphorContext(),{isLocalDev:r,isConsoleMode:l}=s.useDashboardPreferences(),{permissions:i}=s.useRoleAwareDisplayPreferences(),c=s.useHasDashboardId(),{isLoading:o}=s.useDashboardQuery();s.useDashboardStore(V=>V.theme);const d=s.useDashboardStore(V=>V.lenses),u=s.useDashboardStore(V=>V.selectedLensId),m=d==null?void 0:d.find(V=>V.id===u),x=s.useDashboardStore(V=>V.dashboard);s.useDashboardStore(V=>V.selectedSheetId);const h=s.useDashboardStore(V=>V.isDashboardEditing),{setDashboardTitle:p}=s.useDashboardStore(V=>V.actions),[j,g]=S.useState(!1),[v,D]=S.useState(!1),[k,B]=S.useState(!1),L=s.useDashboardStore(V=>V.isDashboardPanelOpen),E=s.useDashboardStore(V=>V.actions.setIsDashboardPanelOpen),C=s.useDashboardStore(V=>V.filterValues),f=s.useDashboardStore(V=>V.isVisualEditing);s.useEditorStore(V=>V.card);const b=s.useManagementStore(V=>V.selectedDashboard),N=s.useManagementStore(V=>V.initialDashboard);s.useManagementStore(V=>V.selectedVisual),s.useDashboardStore(V=>V.selectedFrameId),s.useEditorStore(V=>V.frame);const A=b?(fe=b==null?void 0:b.permissions)==null?void 0:fe.canEdit:(pe=N==null?void 0:N.permissions)==null?void 0:pe.canEdit,w=s.useDashboardStore(V=>V.showFilters),P=s.useDashboardStore(V=>V.showDashboardJSON),I=s.useDashboardStore(V=>V.onSaveFunction),T=s.useDashboardStore(V=>V.actions.setShowFilters),{setIsDashboardEditing:y,setShowDashboardJSON:M}=s.useDashboardStore(V=>V.actions),{setInitialDashboard:F,clearSelectedDashboard:z}=s.useManagementStore(V=>V.actions),{resources:$}=s.useResourceManagement(s.ResourceType.DASHBOARD),{currentUser:O}=s.useCurrentUserInfo(),G=s.canUserManageGroups(O),R=b||N,_=R?{id:R.id,title:(x==null?void 0:x.title)||R.title||"Dashboard"}:null,{handleAddNewFrame:J}=s.useAddNewFrame(),[se,Z]=S.useState(!1),ae=s.useUpdateResource(s.ResourceType.DASHBOARD),Y=async(V,ee)=>{if(!(x!=null&&x.id)){console.log("No dashboard ID found");return}console.log("Updating dashboard title:",{dashboardId:x.id,newTitle:V,previousTitle:ee}),ae.mutate({resourceId:x.id,data:{title:V}},{onSuccess:()=>{console.log("Dashboard title updated successfully"),s.ue.success("Dashboard title updated")},onError:X=>{console.error("Failed to update dashboard title:",X),s.ue.error("Failed to update dashboard title"),p(ee)}})};S.useEffect(()=>{if($&&$.length>0){const V=x==null?void 0:x.id;if(V){const ee=$.find(X=>X.id===V);ee&&F(ee)}}},[$,x==null?void 0:x.id,F]);const U=a.orgUserId||a.tenantId,te=h&&!f&&U&&A,H=()=>{y(!0)};async function re(){const V=ze(x);Z(!0);const ee={template:V};ae.mutate({resourceId:V.id,data:ee},{onSuccess:()=>{Z(!1),s.ue.success("Dashboard saved!")},onError:()=>{Z(!1),s.ue.error("Failed to save dashboard")}})}async function ue(){if(g(!0),!u||!m)return;const V=ze(x),ee=JSON.stringify(V),X={...m,template:ee,filterValues:C};await Je(a.apiServiceUrl,X,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),I==null||I(V),g(!1)}const me=(m==null?void 0:m.name)||x.title;ae.isPending&&console.log("Title during update:",{title:me,dashboardStateTitle:x.title,dashboardId:x==null?void 0:x.id,currentLensName:m==null?void 0:m.name});const W=$&&$.length>0&&(a.orgUserId||a.tenantId&&a.endUserId&&a.endUserEmail),de=b&&!(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:[W&&e.jsxs(e.Fragment,{children:[e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:"Manage Dashboards",onClick:()=>{E(!L)},className:"h-7 p-2",children:e.jsx(zt,{className:"h-4 w-4"})}),de&&!f&&e.jsx(s.IconButton,{"aria-label":"Dashboard Hub",tooltip:"Dashboard Hub",onClick:()=>z(),className:"h-7 p-2",children:e.jsx(s.House,{className:"h-4 w-4"})})]}),!f&&c&&(o?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading..."})]}):e.jsx(s.EditableText,{value:me||"Untitled Dashboard",onSave:V=>{console.log("EditableText onSave called:",{newTitle:V,canEditDashboard:A,dashboardId:x==null?void 0:x.id});const ee=(x==null?void 0:x.title)||"";p(V),Y(V,ee)},isEditable:A&&!m,displayClassName:"text-sm font-medium",inputClassName:"text-sm font-medium",placeholder:"Dashboard Title",isPending:ae.isPending}))]}),e.jsxs("div",{className:"flex items-center gap-2",children:[f&&e.jsxs(e.Fragment,{children:[e.jsx(Rs,{className:"mr-2"}),e.jsx(Bs,{className:"h-7"})]}),r&&!f&&e.jsx(s.IconButton,{tooltip:"Invalidate Token",onClick:()=>s.invalidateToken(a.apiServiceUrl),className:"h-7 p-2",children:e.jsx(Kt,{className:"h-4 w-4"})}),!f&&c&&e.jsx(ra,{}),!f&&c&&e.jsx(Ps,{}),!f&&c&&G&&e.jsx(s.IconButton,{tooltip:"Manage Groups",onClick:()=>B(!0),className:"h-7 p-2",children:e.jsx(s.Users,{className:"h-4 w-4"})}),!f&&c&&((ce=R==null?void 0:R.permissions)==null?void 0:ce.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"})}),!w&&!f&&h&&i.canUseFilters&&c&&e.jsx(s.Button,{className:"h-7 p-2",variant:"outline",onClick:()=>T(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),h&&!f&&U&&r&&c&&e.jsx(aa,{}),!f&&U&&r&&c&&e.jsx(na,{}),h&&!f&&U&&m&&r&&c&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:j,onClick:ue,size:"sm",children:[e.jsx(Ie,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),h&&!f&&c&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",size:"sm",disabled:!h,onClick:()=>J(),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Visual"]}),!f&&!h&&i.canEdit&&c&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:H,size:"sm",children:[e.jsx(s.Pencil,{className:"mr-2 h-4 w-4"}),"Edit"]}),te&&c&&e.jsxs(s.Button,{className:"h-7 p-2",disabled:se,onClick:re,size:"sm",children:[se?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Ie,{className:"mr-2 h-4 w-4"}),se?"Saving...":"Save"]}),!f&&h&&r&&c&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(s.Button,{className:"h-7 p-2",onClick:()=>M(!P),size:"sm",variant:"ghost",children:e.jsx(s.Code,{className:"h-4 w-4"})})}),!f&&r&&e.jsx(Zt,{}),h&&!f&&c&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:()=>{y(!1),M(!1)},children:[e.jsx(s.Cross2Icon,{className:"mr-2 h-4 w-4"}),"Close"]}),v&&_&&e.jsx(s.ShareDialog,{resource:_,resourceType:s.ResourceType.DASHBOARD,onClose:()=>D(!1)}),e.jsx(ja,{open:k,onOpenChange:B})]})]})}function es(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 Qe(t,a,n,r,l){if(t!=="kpi"||l.length<3)return;const i=(a==null?void 0:a.groupByColumns)&&a.groupByColumns.length>0,c=(a==null?void 0:a.comparisonType)==="none";!i&&c||n(r,{groupByColumns:[],comparisonType:"none"})}const ss=t=>{var I;const a=(I=t==null?void 0:t.dataSource)==null?void 0:I.semanticDomainId,{data:n}=es(a),{updateCardConfig:r,updateGroupByColumn:l,updateMetricColumn:i,updatePivotByColumn:c,updateSortByColumn:o,removeGroupByColumn:d,removeMetricColumn:u,removePivotByColumn:m,removeSortByColumn:x}=s.useEditorActions(),h=s.useEditorStore(T=>T.card.type),p=t==null?void 0:t.id,j=S.useCallback(T=>{if(!(t!=null&&t.config))return[];switch(T){case"groupBy":return(t.config.groupByColumns||[]).map(y=>({id:y.id,name:y.name,dataType:y.dataType,label:y.label!==void 0?y.label:y.name,qualifiedEntityName:y.qualifiedEntityName,entityId:y.entityId,entityName:y.entityName,entityType:y.entityType,dateFormat:y.dateFormat,customFormat:y.customFormat,granularity:y.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(y=>({id:y.id,name:y.name,dataType:y.dataType,label:y.label!==void 0?y.label:y.name,qualifiedEntityName:y.qualifiedEntityName,entityId:y.entityId,entityName:y.entityName,entityType:y.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(y=>({id:y.id,name:y.name,dataType:y.dataType,label:y.label!==void 0?y.label:y.name,qualifiedEntityName:y.qualifiedEntityName,entityId:y.entityId,entityName:y.entityName,entityType:y.entityType,direction:y.direction}));case"source":return[];default:return[]}},[t]),g=S.useCallback((T,y)=>{if(p)switch(T){case"groupBy":{r(p,{groupByColumns:y});break}case"metrics":{r(p,{metricColumns:y});break}case"pivotBy":{r(p,{pivotByColumns:y});break}case"sortBy":{r(p,{sortByColumns:y});break}}},[p,r]),v=S.useCallback((T,y,M)=>{if(!p)return;const z=j(T)[y];if(z)switch(T){case"groupBy":l(p,z.id,{label:M});break;case"metrics":i(p,z.id,{label:M});break;case"pivotBy":c(p,z.id,{label:M});break;case"sortBy":o(p,z.id,{label:M});break}},[p,j,l,i,c,o]),D=S.useCallback((T,y)=>{if(!p)return;const F=j("metrics")[T];F&&i(p,F.id,{aggregate:y,label:s.getAggregationLabel(F.name,y)})},[p,j,i]),k=S.useCallback((T,y,M)=>{if(!p)return;const z=j("groupBy")[T];if(!z)return;const $={dateFormat:y};y==="custom"&&M?$.customFormat=M:$.customFormat=void 0,l(p,z.id,$)},[p,j,l]),B=S.useCallback((T,y)=>{if(!p)return;const F=j("groupBy")[T];F&&l(p,F.id,{granularity:y})},[p,j,l]),L=S.useCallback((T,y)=>{if(!p)return;const F=j("metrics")[T];F&&i(p,F.id,{aliasTemplate:y})},[p,j,i]),E=S.useCallback((T,y)=>{if(console.log("handleValueAliasesChange",T,y),!p)return;console.log("handleValueAliasesChange",T,y);const F=j("metrics")[T];F&&(console.log("handleValueAliasesChange",y),i(p,F.id,{valueAliases:y}))},[p,j,i]),C=S.useCallback(T=>{if(!p)return;if(j("metrics").length===0){s.ue.error("Add Metric First",{description:"Please add a metric field before selecting a comparison type",position:"top-center",duration:3e3});return}r(p,{comparisonType:T})},[p,r,j]),f=S.useCallback(T=>{p&&r(p,{showTrendline:T})},[p,r]),b=S.useCallback(T=>{p&&r(p,{trendlineWindow:T})},[p,r]),N=S.useCallback(T=>{p&&r(p,{trendlineGranularity:T})},[p,r]),A=S.useCallback(T=>{p&&r(p,{targetValue:T})},[p,r]),w=S.useCallback(T=>{var G;if(!p)return;const y=[...j("groupBy"),...j("pivotBy"),...j("metrics"),...j("sortBy")],M=s.validateEntityConsistency(T,y,{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 F=s.getSmartContainerForField(T,y,h);if(!F){s.ue.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const z=Fe(T,F,h);if(!z.isValid){s.ue.error("Invalid Field Type",{description:z.reason,position:"top-center",duration:3e3});return}const $=j(F);if(s.fieldAlreadyExists(T,$))return;const O=s.getNewField(T,F,$);if(O){const R=[...$,O];g(F,R),F==="metrics"&&Qe(h,t==null?void 0:t.config,r,p,R)}},[p,t==null?void 0:t.config,j,g,a,n,h,r]),P=S.useCallback((T,y)=>{if(!p)return;const F=j(T)[y];if(F){if(T!=="sortBy"){const z=j("sortBy"),$=z.filter(O=>!(O.name===F.name&&O.qualifiedEntityName===F.qualifiedEntityName));$.length!==z.length&&r(p,{sortByColumns:$})}switch(T){case"groupBy":d(p,F.id);break;case"metrics":u(p,F.id);break;case"pivotBy":m(p,F.id);break;case"sortBy":x(p,F.id);break}}},[p,j,d,u,m,x,r]);return{getFieldsForContainer:j,setFieldsForContainer:g,updateLabel:v,handleAggregationChange:D,handleDateFormatChange:k,handleGranularityChange:B,handleAliasTemplateChange:L,handleValueAliasesChange:E,removeField:P,handleFieldClick:w,handleKpiComparisonTypeChange:C,handleKpiShowTrendlineChange:f,handleKpiTrendlineWindowChange:b,handleKpiTrendlineGranularityChange:N,handleKpiTargetValueChange:A,cardType:h}};function Oe(t){return`${t}-${s.v4()}`}function ps(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function Ma(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function ts(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 Vs(t){if(!t||!t.selectedEntities||t.selectedEntities.length===0)return!1;const a=t.selectedEntities[0];return!!(a!=null&&a.name)}function zs(){const t=s.useEditorStore(C=>C.sqlGen),a=s.useEditorStore(C=>C.isDevMode),n=s.useEditorStore(C=>C.card.dataSource),r=s.useEditorStore(C=>{var f,b;return(b=(f=C.card)==null?void 0:f.queryConfig)==null?void 0:b.metricColumns}),{tableName:l,schemaName:i,databaseName:c}=ts(n),o=Vs(n),d=s.useEditorStore(C=>C.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:m,setCardSql:x,setRunSql:h,setSqlGen:p,setIsShowingVisual:j}=s.useEditorActions(),{connectionType:g,modelItems:v,selectedDatamodelName:D}=s.useEditorAside(),k=C=>({column_name:C.name,data_type:C.dataType,label:C.label,description:C.description});return{handleDevModeFieldClick:C=>{var b;if(!a)return;const f=k(C);if(a&&o&&l){const N=s.createSqlGenConfig(f,t);p(N);const A=(b=v==null?void 0:v.find(P=>P.id===d))==null?void 0:b.name,w=s.getSql(N,s.fmt(i||""),s.fmt(l),A||"",g,c||"");w&&(x(w),h(!0))}else if(!a){if(s.isTextDataType(f.data_type))if(r&&r.length>0){const N={...f,role:"groupby",id:Oe(f.column_name),name:f.column_name,type:f.data_type};m(N)}else{const N={...f,role:"metric",id:Oe(f.column_name),name:f.column_name,label:ps(f.column_name,"COUNT"),type:f.data_type,aggregate:"COUNT"};u(N)}if(s.isDateDataType(f.data_type)){const N={...f,role:"groupby",id:Oe(f.column_name),name:f.column_name,type:f.data_type,label:Ma(f.column_name,"month"),granularity:"month"};m(N)}if(s.isNumberDataType(f.data_type)){const N={...f,role:"metric",id:Oe(f.column_name),name:f.column_name,label:ps(f.column_name,"SUM"),type:f.data_type,aggregate:"SUM"};u(N)}}},handleShowSample:()=>{if(!o||!l){console.warn("Cannot generate SQL: missing table metadata");return}const C=s.getFormattedTableNameForQuery({schemaName:i||"",tableName:l,modelName:D,connectionType:g,databaseName:c||""});j(!1);const f=g==="MSSQL"?`SELECT top 10 * FROM ${C}`:`SELECT * FROM ${C} LIMIT 10`;x(f),h(!0)},handleShowCount:()=>{if(!o||!l){console.warn("Cannot generate SQL: missing table metadata");return}const C=s.getFormattedTableNameForQuery({schemaName:i||"",tableName:l,modelName:D,connectionType:g,databaseName:c||""});x(`SELECT COUNT(*) as count FROM ${C}`),h(!0)},isNumberField:C=>s.isNumberDataType(C.dataType)}}function Gs(){const t=s.useEditorStore(j=>j.selectedConnectionId),a=s.useEditorStore(j=>j.selectedDatamodelId),n=s.useEditorStore(j=>j.selectedDatabaseName),r=s.useEditorStore(j=>j.selectedSchemaName),l=s.useEditorStore(j=>j.selectedTableName),i=s.useDashboardStore(j=>j.dashboard.filters)||[],c=s.useDashboardStore(j=>j.selectedSheetId),o=s.useDashboardStore(j=>j.actions.addFilter),d=s.useDashboardStore(j=>j.actions.removeFilter),{removeFilterValues:u}=s.useDashboardActions(),{modelItems:m,tableName:x,connectionType:h}=s.useEditorAside();function p(j,g="sheet",v){var N;const D=s.fmt(j.column_name),k=s.fmt(n||""),B=s.fmt(r||""),L=s.fmt(x);let E=s.getQualifiedTableName({schemaName:B,tableName:L,connectionType:h,databaseName:k}),C=`${E}.${D}`;const f=(N=m==null?void 0:m.find(A=>A.id===a))==null?void 0:N.name;a&&a!=="none"&&(C=`${s.DATAMODEL_NAMESPCACE}.${f}.${D}`,E=`${s.DATAMODEL_NAMESPCACE}.${f}`),v!=null&&v.qualifiedFieldName&&(C=v.qualifiedFieldName),v!=null&&v.entityName&&(E=v.entityName);let b;if(g==="sheet"&&c?b=s.filterExistsInSheet(i,C,L,n||"",k,c):b=i==null?void 0:i.find(A=>A.column===C&&A.table===L&&(A.database===k||A.database===n)),b)u(b.id),d(b.id);else{const A=s.v4(),w=g==="sheet"&&c?[c]:void 0;return x==="api"&&t?(o({location:g,id:A,column:C,title:j.label||j.column_name,dataType:j.data_type,table:"api",database:"",connectionId:t,operation:"in",applyToSheetIds:w,sql:s.getDefaultFilterSql(j.data_type,E,D)}),A):(o({id:A,location:g,column:C,title:j.label||j.column_name,dataType:j.data_type,table:l||"",database:n||"",connectionId:t||"",operation:"in",applyToSheetIds:w,sql:s.getDefaultFilterSql(j.data_type,E,D)}),A)}}return{assignFilter:p}}function La({column:t}){const[a,n]=S.useState(!1),r=s.useEditorStore(D=>D.card.dataSource),{tableName:l,schemaName:i,databaseName:c}=ts(r),o=s.useEditorStore(D=>D.selectedDatamodelId),d=s.useEditorStore(D=>D.sqlGen),{modelItems:u,connectionType:m}=s.useEditorAside(),x=s.useEditorStore(D=>D.actions.setSqlGen),h=s.useEditorStore(D=>D.actions.setCardSql),p=s.useEditorStore(D=>D.actions.setRunSql),j=Vs(r);function g(D,k){var C;if(!j||!l){console.warn("Cannot generate SQL: missing table metadata");return}const B=s.createSqlGenConfig(D,d,k),L=(C=u==null?void 0:u.find(f=>f.id===o))==null?void 0:C.name;x(B);const E=s.getSql(B,s.fmt(i||""),s.fmt(l),L||"",m,c||"");E&&(h(E),p(!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 j?e.jsxs(s.HoverCard,{openDelay:0,open:a,onOpenChange:n,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:v()})]}):null}function Fa({field:t,fieldState:a}){return e.jsxs("div",{className:"w-64 bg-background p-0",children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"text-sm font-medium text-foreground",children:t.label||t.name}),e.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:t.dataType})]}),t.description&&e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:t.description}),a&&a.tooltip&&e.jsx("div",{className:"mb-2 rounded bg-muted/50 p-2",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:a.tooltip})}),e.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:t.name})})]})}function Pa({field:t,context:a="editor",fieldState:n}){const r=s.useEditorStore(R=>R.isDevMode),l=a==="filter",i=r||l||(n==null?void 0:n.state)==="unreachable"&&!l,c=s.useDashboardStore(R=>R.dashboard.filters),o=s.useDashboardStore(R=>R.selectedSheetId),d=s.useDashboardStore(R=>R.actions.removeFilter),{removeFilterValues:u}=s.useDashboardActions(),{assignFilter:m}=Gs(),x=l?s.getSheetScopedFilters(c,o):c,h=l?x==null?void 0:x.find(R=>{var _;return R.title===t.name||((_=R.column)==null?void 0:_.includes(t.name))}):void 0,p=!!h,j=h&&l?c==null?void 0:c.find(R=>R.id===h.id):void 0,g=j&&(j.applyToSheetIds&&j.applyToSheetIds.length>1||j.excludeSheetIds&&j.excludeSheetIds.length>0||!j.applyToSheetIds&&!j.excludeSheetIds&&!j.sheetId);l&&p&&console.log("[SourceField Debug]",{fieldName:t.name,hasActiveFilter:p,activeFilterOnSheet:h?{id:h.id,title:h.title,column:h.column,applyToSheetIds:h.applyToSheetIds,excludeSheetIds:h.excludeSheetIds}:null,activeFilterForField:j?{id:j.id,title:j.title,column:j.column,applyToSheetIds:j.applyToSheetIds,excludeSheetIds:j.excludeSheetIds}:null,isMultiSheetFilter:g,selectedSheetId:o});const[v,D]=S.useState(!1),[k,B]=S.useState(null),{attributes:L,listeners:E,setNodeRef:C,transform:f,transition:b,isDragging:N}=s.useSortable({id:t.id,disabled:i}),[A,w]=S.useState(!1),P=s.useEditorStore(R=>R.card),{handleFieldClick:I}=ss(P),{handleDevModeFieldClick:T,isNumberField:y}=zs(),M=()=>{j&&(console.log("[SourceField] Removing multi-sheet filter:",j.id),u(j.id),d(j.id)),B(null),D(!1)},F=()=>{if(l){const R={column_name:t.name,data_type:t.dataType,label:t.label,description:t.description};console.log("[SourceField Click]",{fieldName:t.name,hasActiveFilter:p,isMultiSheetFilter:g,willShowWarning:p&&g}),p&&g?(console.log("[SourceField] Showing warning dialog for multi-sheet filter"),B({column:R,field:t}),D(!0)):(console.log("[SourceField] Calling assignFilter directly (single-sheet or new filter)"),m(R,"sheet",t))}else r?T(t):I(t)},z={column_name:t.name,data_type:t.dataType,label:t.label,description:t.description},$={transform:s.CSS.Transform.toString(f),transition:b},G=(()=>{if(!n||l)return{};const _={base:{hoverBorderColor:"hover:border-blue-500/40",hoverBgColor:"hover:bg-blue-50/50 dark:hover:bg-blue-950/20"},draggable:{hoverBorderColor:"hover:border-green-500/40",hoverBgColor:"hover:bg-green-50/30 dark:hover:bg-green-950/20"},indirect:{hoverBorderColor:"hover:border-yellow-500/40",hoverBgColor:"hover:bg-yellow-50/30 dark:hover:bg-yellow-950/20"},unreachable:{borderColor:"border-gray-300/40 dark:border-gray-700/40",bgColor:"bg-gray-50/30 dark:bg-gray-900/20",hoverBgColor:"hover:bg-gray-100/30 dark:hover:bg-gray-800/20",opacity:"opacity-50",cursor:"cursor-not-allowed"}}[n.state]||{};return n.isSelected&&{base:{borderColor:"border-blue-300/30 dark:border-blue-700/30",bgColor:"bg-blue-50/20 dark:bg-blue-950/10",..._},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",..._},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",..._}}[n.state]||_})();return e.jsxs("div",{ref:C,style:$,...i?{}:L,...i?{}:E,className:s.cn("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",N&&"scale-95 opacity-50",!N&&"border",G.borderColor||"border-transparent",G.bgColor||"",G.hoverBorderColor,G.hoverBgColor||"hover:bg-muted",G.opacity,G.cursor,p&&"bg-accent border-accent-foreground/20",{"cursor-pointer":r||l,"cursor-grab active:cursor-grabbing":!i&&!r&&!l}),title:n==null?void 0:n.tooltip,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:F,children:[s.getFieldIconComponent(t.dataType),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:e.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${A?"whitespace-normal break-words":"truncate"}`,children:t.label||t.name})})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:e.jsx(Fa,{field:t,fieldState:n})})]})}),r&&!l&&y(t)&&e.jsx("div",{onClick:R=>R.stopPropagation(),children:e.jsx(La,{column:z})})]}),A&&e.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:e.jsx(s.Card,{className:"",children:e.jsxs(s.CardContent,{className:"space-y-2 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ms,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:t.label||t.name})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:t.name})]}),e.jsx(s.Badge,{variant:"outline",className:"mt-2 text-xs",children:t.dataType})]})})}),e.jsx(s.AlertDialog,{open:v,onOpenChange: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 Oa({context:t="editor"}={}){var A,w,P,I;const[a,n]=S.useState(""),[r,l]=S.useState("all");s.useEditorStore(T=>T.isDevMode);const i=s.useEditorStore(T=>T.card.dataSource),c=s.useEditorStore(T=>T.card.config),o=s.useEditorStore(T=>T.card),{autoJoinMetadata:d}=s.useDashboardCardQuery(o),{columns:u=[],columnGroups:m=[],isLoading:x,error:h}=s.useColumns(),p=(i==null?void 0:i.mode)==="semanticDomain"?i.semanticDomainId:void 0,{data:j}=es(p),g=[...(c==null?void 0:c.groupByColumns)||[],...(c==null?void 0:c.metricColumns)||[]];(w=(A=c==null?void 0:c.joinPlan)==null?void 0:A.baseEntity)==null||w.name,(I=(P=d==null?void 0:d.resolvedJoinPlan)==null?void 0:P.baseEntity)==null||I.name,zs();const v=u.filter(T=>T.name.toLowerCase().includes(a.toLowerCase())||T.dataType.toLowerCase().includes(a.toLowerCase())||T.label&&T.label.toLowerCase().includes(a.toLowerCase())||T.qualifiedEntityName&&T.qualifiedEntityName.toLowerCase().includes(a.toLowerCase())),D=T=>{if(T.dataType==="number"||T.dataType==="integer"||T.dataType==="float"||T.dataType==="decimal"||T.dataType==="currency")return"metrics";const y=s.getDataType(T.dataType);return["date","string","boolean"].includes(y)?"dimensions":y==="number"?"metrics":"dimensions"},B=(r==="all"?v:v.filter(T=>D(T)===r)).reduce((T,y)=>{const M=y.qualifiedEntityName||"Other Fields";return T[M]||(T[M]={label:s.toLabel(y.entityName),fields:[]}),T[M].fields.push(y),T},{}),E=Object.keys(B),C=v.filter(T=>D(T)==="dimensions").length,f=v.filter(T=>D(T)==="metrics").length,b=v.filter(T=>D(T)==="calculated").length,N=v.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"})}):h?e.jsxs("div",{className:"flex h-full w-[290px] flex-col items-center justify-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:h.message||"Failed to load column data"})]}):!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:[u.length>0&&e.jsxs("div",{className:"relative mb-4",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:a,onChange:T=>n(T.target.value)}),a&&e.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>n(""),type:"button",children:e.jsx(s.X,{className:"size-3.5"})})]}),N&&e.jsx(s.Tabs,{defaultValue:"all",value:r,onValueChange:T=>l(T),className:"mb-4",children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-4",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:v.length})]}),e.jsxs(s.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:C})]}),e.jsxs(s.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:f})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(s.Calculator,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:b})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:E,className:"space-y-2",children:Object.entries(B).map(([T,y])=>{const M=m.find(F=>F.entityName===T)||{entityName:T,label:y.label};return e.jsxs(s.AccordionItem,{value:T,className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:e.jsxs("div",{title:M.label||M.entityName,className:"flex items-center gap-2",children:[e.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:M.label||M.entityName}),e.jsx(s.Badge,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:y.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:y.fields.map(F=>{const z=s.calculateFieldState(F,{joinabilityMap:(j==null?void 0:j.joinabilityMap)||null,selectedFields:g,cardConfig:c,autoJoinMetadata:d});return e.jsx(Pa,{field:F,context:t,fieldState:z},F.id)})})})]},T)})}),Object.keys(B).length===0&&u.length===0&&e.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[e.jsx("p",{children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:t==="filter"?"The selected data source has no available fields":"Try selecting different data sources"})]}),Object.keys(B).length===0&&u.length>0&&e.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),e.jsx(s.ScrollBar,{orientation:"horizontal"}),e.jsx(s.ScrollBar,{orientation:"vertical"})]})]})}function $s({context:t="editor"}={}){return e.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",e.jsx(Oa,{context:t})," "]})}function Ba({initialJoinPlan:t,availableDataSources:a}){const[n,r]=S.useState(t),[l,i]=S.useState(new Set),c=()=>{const C=n.joins.length>0?Math.max(...n.joins.map(b=>b.sequence))+1:1,f={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:C,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...n,joins:[...n.joins,f]}),i(new Set([...l,f.id]))},o=C=>{r({...n,joins:n.joins.filter(f=>f.id!==C)}),i(new Set([...l].filter(f=>f!==C)))},d=(C,f)=>{var P,I,T,y,M;const b=n.joins.find(F=>F.id===C);if(!b)return;const N={...b,...f};if((P=N.source)!=null&&P.name&&((I=N.target)!=null&&I.name)&&N.source.name===N.target.name){s.ue.error("Self-joins are not yet supported",{description:`Joining ${N.source.name} to itself is not currently supported. Please select a different target table.`});return}const A=n.joins.filter(F=>{var z;return F.id!==C&&F.target.name===((z=N.target)==null?void 0:z.name)});if((T=N.target)!=null&&T.name&&A.length>0){s.ue.error("Duplicate join targets are not supported",{description:`The table ${N.target.name} is already used as a target in another join. Each table can only be joined once.`});return}const w=n.joins.map(F=>F.id===C?N:F);if((y=N.source)!=null&&y.name&&((M=N.target)!=null&&M.name)&&N.joinKeyGroups[0].keys.length===0){const F=a.find(G=>{var R;return G.name===((R=N.source)==null?void 0:R.name)}),z=a.find(G=>{var R;return G.name===((R=N.target)==null?void 0:R.name)}),$={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(F==null?void 0:F.name)||"",entityName:(F==null?void 0:F.name)||"",entityType:(F==null?void 0:F.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(z==null?void 0:z.name)||"",entityName:(z==null?void 0:z.name)||"",entityType:(z==null?void 0:z.type)||"table"},operator:"="},O=[...N.joinKeyGroups];O[0]={...O[0],keys:[$]},N.joinKeyGroups=O,w[w.findIndex(G=>G.id===C)]=N}r({...n,joins:w})};return{joinPlan:n,expandedJoins:l,setJoinPlan:r,addJoin:c,removeJoin:o,updateJoin:d,moveJoinUp:C=>{const f=n.joins.findIndex(b=>b.id===C);if(f>0){const b=[...n.joins],N={...b[f]},A={...b[f-1]};b[f]=A,b[f-1]=N,b.forEach((P,I)=>{P.sequence=I+1});const w={...n,joins:b};r(w)}},moveJoinDown:C=>{const f=n.joins.findIndex(b=>b.id===C);if(f<n.joins.length-1){const b=[...n.joins],N={...b[f]},A={...b[f+1]};b[f]=A,b[f+1]=N,b.forEach((P,I)=>{P.sequence=I+1});const w={...n,joins:b};r(w)}},toggleJoinExpansion:C=>{const f=new Set(l);f.has(C)?f.delete(C):f.add(C),i(f)},getAvailableSourceEntities:C=>{if(n.joins.length===0)return a;const f=n.joins.findIndex(N=>N.id===C);if(f===0)return a.filter(N=>N.name===n.baseEntity.name);const b=new Set;return n.baseEntity.name&&b.add(n.baseEntity.name),n.joins.slice(0,f).forEach(N=>{b.add(N.source.name),b.add(N.target.name)}),a.filter(N=>b.has(N.name))},getAvailableTargetEntities:C=>a.filter(f=>f.name!==C),addJoinKeyGroup:C=>{const f=n.joins.find(N=>N.id===C);if(!f)return;const b=[...f.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];d(C,{joinKeyGroups:b})},updateGroupOperator:(C,f,b)=>{const N=n.joins.find(w=>w.id===C);if(!N)return;const A=[...N.joinKeyGroups];A[f]={...A[f],operator:b},d(C,{joinKeyGroups:A})},removeJoinKeyGroup:(C,f)=>{const b=n.joins.find(A=>A.id===C);if(!b)return;const N=[...b.joinKeyGroups];N.splice(f,1),d(C,{joinKeyGroups:N})},addJoinKey:(C,f)=>{const b=n.joins.find(I=>I.id===C);if(!b)return;const N=a.find(I=>I.name===b.source.name),A=a.find(I=>I.name===b.target.name),w=[...b.joinKeyGroups],P={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(N==null?void 0:N.name)||"",entityName:(N==null?void 0:N.name)||"",entityType:(N==null?void 0:N.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(A==null?void 0:A.name)||"",entityName:(A==null?void 0:A.name)||"",entityType:(A==null?void 0:A.type)||"table"},operator:"="};w[f]={...w[f],keys:[...w[f].keys,P]},d(C,{joinKeyGroups:w})},updateJoinKey:(C,f,b,N,A)=>{const w=n.joins.find(M=>M.id===C);if(!w)return;const P=a.find(M=>M.name===w.source.name),I=a.find(M=>M.name===w.target.name),T=[...w.joinKeyGroups],y=T[f].keys[b];N==="sourceColumnName"&&P?T[f].keys[b]={...y,source:{...y.source,name:A}}:N==="targetColumnName"&&I?T[f].keys[b]={...y,target:{...y.target,name:A}}:N==="operator"&&(T[f].keys[b]={...y,operator:A}),d(C,{joinKeyGroups:T})},removeJoinKey:(C,f,b)=>{const N=n.joins.find(w=>w.id===C);if(!N)return;const A=[...N.joinKeyGroups];A[f].keys.splice(b,1),d(C,{joinKeyGroups:A})},generateSQLPreview:()=>{const C=[...n.joins].sort((N,A)=>N.sequence-A.sequence),f=n.baseEntity;if(!f.name)return"SELECT * FROM table -- Please select a base entity";let b=`SELECT *
|
|
217
|
+
FROM ${f.name}`;return C.forEach(N=>{const A=a.find(I=>I.name===N.target.name);if(!A)return;const w=N.joinKeyGroups.filter(I=>I.keys&&I.keys.length>0).map(I=>{const T=I.keys.filter(y=>{var M,F,z,$;return((M=y.source)==null?void 0:M.name)&&((F=y.target)==null?void 0:F.name)&&((z=y.source)==null?void 0:z.entityName)&&(($=y.target)==null?void 0:$.entityName)}).map(y=>`${y.source.entityName}.${y.source.name} ${y.operator} ${y.target.entityName}.${y.target.name}`);return T.length>1?`(${T.join(` ${I.operator} `)})`:T[0]}).filter(Boolean),P=w.length>1?w.join(" OR "):w[0]||"condition_here";b+=`
|
|
218
|
+
${N.joinType} JOIN ${A.name}
|
|
219
|
+
ON ${P}`}),b},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(N=>!N.source.name||!N.target.name)||n.joins.some(N=>N.joinKeyGroups.some(A=>A.keys.length===0))||n.joins.some(N=>N.joinKeyGroups.some(A=>A.keys.some(w=>!w.source.name||!w.target.name||!w.operator))))}}function Ra({joinPlan:t,availableDataSources:a,onSave:n,onRemove:r,onCancel:l}){const{setCardConfig:i}=s.useEditorActions();s.useEditorStore(w=>w.card.config);const{columnGroups:c}=s.useColumns(),{joinPlan:o,expandedJoins:d,setJoinPlan:u,addJoin:m,removeJoin:x,updateJoin:h,moveJoinUp:p,moveJoinDown:j,toggleJoinExpansion:g,getAvailableSourceEntities:v,getAvailableTargetEntities:D,addJoinKeyGroup:k,updateGroupOperator:B,removeJoinKeyGroup:L,addJoinKey:E,updateJoinKey:C,removeJoinKey:f,generateSQLPreview:b,isValidConfiguration:N}=Ba({initialJoinPlan:t,availableDataSources:a}),A=w=>{const P=c.find(I=>I.entityName===w);return(P==null?void 0:P.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:o.baseEntity.name,onValueChange:w=>{const P=a.find(I=>I.name===w);u({...o,baseEntity:{connectionId:(P==null?void 0:P.connectionId)||"",connectionType:(P==null?void 0:P.connectionType)||"none",type:(P==null?void 0:P.type)||"table",name:w,database:P==null?void 0:P.database,schema:P==null?void 0:P.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:a.map(w=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:w.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:w.type}),w.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},w.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:b()})]}),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(w=>{const P=a.find(y=>y.name===w.source.name),I=a.find(y=>y.name===w.target.name),T=d.has(w.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:w.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",w.sequence,P&&I&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",P.name," → ",I.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>p(w.id),disabled:w.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>j(w.id),disabled:w.sequence===o.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g(w.id),children:T?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:()=>x(w.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),T&&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:w.source.name,onValueChange:y=>{const M=a.find(F=>F.name===y);h(w.id,{source:{connectionId:(M==null?void 0:M.connectionId)||"",connectionType:(M==null?void 0:M.connectionType)||"none",type:(M==null?void 0:M.type)||"table",name:y,database:M==null?void 0:M.database,schema:M==null?void 0:M.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:v(w.id).map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:y.type}),y.name]})},y.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:w.joinType,onValueChange:y=>h(w.id,{joinType:y}),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Target"}),e.jsxs(s.Select,{value:w.target.name,onValueChange:y=>{const M=a.find(F=>F.name===y);h(w.id,{target:{connectionId:(M==null?void 0:M.connectionId)||"",connectionType:(M==null?void 0:M.connectionType)||"none",type:(M==null?void 0:M.type)||"table",name:y,database:M==null?void 0:M.database,schema:M==null?void 0:M.schema}})},disabled:!w.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:w.source.name?D(w.source.name).map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:y.type}),y.name,y.name===w.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},y.name)):[]})]})]})]}),w.source.name&&w.target.name&&P&&I&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>k(w.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),w.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:w.joinKeyGroups.map((y,M)=>e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{children:["Group ",M+1]}),M>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(s.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Select,{value:y.operator,onValueChange:F=>B(w.id,M,F),children:[e.jsx(s.SelectTrigger,{className:"w-[100px]",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>L(w.id,M),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[y.keys.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-sm text-gray-500",children:"No conditions in this group. Add conditions to specify join criteria."}):e.jsx("div",{className:"space-y-2",children:y.keys.map((F,z)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[z>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:y.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:F.source.name,onValueChange:$=>C(w.id,M,z,"sourceColumnName",$),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:A(w.source.name).map($=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:$.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:$.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:$.dataType})]})},$.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:F.operator,onValueChange:$=>C(w.id,M,z,"operator",$),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:F.target.name,onValueChange:$=>C(w.id,M,z,"targetColumnName",$),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:A(w.target.name).map($=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:$.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:$.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:$.dataType})]})},$.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>f(w.id,M,z),children:e.jsx(s.X,{className:"size-3.5"})})]},F.id||z))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>E(w.id,M),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},y.id))})]})]})]},w.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:!N(),children:"Save"})]})]})}function We({children:t,open:a,onOpenChange:n,joinPlan:r,availableDataSources:l,onRemove:i,onSave:c,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(Ra,{joinPlan:r,availableDataSources:l,onSave:c,onCancel:o,onRemove:i})]}),t]})}function Va({joins:t,baseEntityId:a,availableDataSources:n,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[t.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const l=[...t].sort((c,o)=>c.sequence-o.sequence),i=n.find(c=>c.name===a);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),l.map(c=>{const o=n.find(d=>d.name===c.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:o==null?void 0:o.type}),e.jsx("span",{className:"text-xs font-medium",children:o==null?void 0:o.name})]})]},c.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",t.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...t].sort((l,i)=>l.sequence-i.sequence).map((l,i)=>{const c=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:i+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:l.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[c==null?void 0:c.name," → ",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 za(){var x,h;const t=s.useEditorStore(p=>p.card),{autoJoinMetadata:a}=s.useDashboardCardQuery(t),n=s.useEditorStore(p=>p.actions.updateCardConfig),r=((x=t==null?void 0:t.config)==null?void 0:x.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[l,i]=S.useState(!1),c=((h=t==null?void 0:t.dataSource)==null?void 0:h.selectedEntities)||[],o=p=>{n(t.id,{...t==null?void 0:t.config,joinPlan:p}),i(!1)},d=()=>{n(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},u=()=>{i(!1)},m=()=>{const p=[...r.joins].sort((v,D)=>v.sequence-D.sequence),j=r.baseEntity;if(!j.name)return"SELECT * FROM table -- Please select a base entity";let g=`SELECT *
|
|
220
|
+
FROM ${j.name}`;return p.forEach(v=>{const D=c.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 E=L.keys.filter(C=>{var f,b,N,A;return((f=C.source)==null?void 0:f.name)&&((b=C.target)==null?void 0:b.name)&&((N=C.source)==null?void 0:N.entityName)&&((A=C.target)==null?void 0:A.entityName)}).map(C=>`${C.source.entityName}.${C.source.name} ${C.operator} ${C.target.entityName}.${C.target.name}`);return E.length>1?`(${E.join(` ${L.operator} `)})`:E[0]}).filter(Boolean),B=k.length>1?k.join(" OR "):k[0]||"condition_here";g+=`
|
|
221
|
+
${v.joinType} JOIN ${D.name}
|
|
222
|
+
ON ${B}`}),g};return c.length<2?null:e.jsx(e.Fragment,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[r.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-6 text-xs font-semibold",onClick:()=>i(!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(Va,{joins:r.joins,baseEntityId:r.baseEntity.name,availableDataSources:c,generateSQLPreview:m})})]})}),(a==null?void 0:a.autoResolved)&&e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"h-6 gap-1 bg-blue-50 text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:[e.jsx(s.Sparkles,{className:"h-3 w-3"}),"Auto"]})}),e.jsx(s.TooltipContent,{side:"right",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium",children:"Auto-resolved using relationships:"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:a.relationshipsUsed.map((p,j)=>e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:p},j))})]})})]})}),e.jsx(We,{open:l,onOpenChange:i,joinPlan:r,availableDataSources:c,onSave:o,onCancel:u,onRemove:d,children:e.jsx("div",{})})]}),r.joins.length===0&&e.jsx(We,{open:l,onOpenChange:i,joinPlan:r,availableDataSources:c,onSave:o,onCancel:u,onRemove:d,children:e.jsxs(s.Button,{onClick:()=>i(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function Ga({open:t,onOpenChange:a}){const[n,r]=S.useState([]),{updateDataSource:l}=s.useEditorActions(),i=s.useDashboardStore(g=>g.dashboard.aiContext),c=(i==null?void 0:i.selectedEntities)||[];S.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([...c])},u=()=>{r([])},m=()=>{if(n.length===0)return;const g=n[0],v=g.connectionId||"",D=g.connectionType||"",B=n.some(E=>E.type==="dataset")?"semanticDomain":"database";l({connectionId:v,connectionType:D,mode:B,selectedEntities:n}),a(!1)},x=g=>{switch(g.type){case"table":return e.jsx(s.Table,{className:"h-4 w-4"});case"view":return e.jsx(Yt,{className:"h-4 w-4"});case"model":return e.jsx(wt,{className:"h-4 w-4"});case"dataset":return e.jsx(s.Database,{className:"h-4 w-4"});case"file":case"url":case"upload":return e.jsx(s.FileText,{className:"h-4 w-4"});default:return e.jsx(s.Database,{className:"h-4 w-4"})}},h=g=>"label"in g&&g.label?g.label:g.name,p=g=>{if("description"in g&&g.description)return g.description;const v=[];return g.database&&v.push(g.database),g.schema&&v.push(g.schema),g.name&&v.push(g.name),v.join(".")},j=g=>n.some(v=>v.name===g.name&&v.type===g.type);return c.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"max-w-md",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"No Data Available"}),e.jsx(s.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{onClick:()=>a(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(s.DialogDescription,{children:"Choose entities from the dashboard's context"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"outline",size:"sm",onClick:d,disabled:n.length===c.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:u,disabled:n.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[n.length," of ",c.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:c.map((g,v)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",j(g)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:j(g),onCheckedChange:()=>o(g)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:x(g)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:h(g)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:p(g)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:g.type})]},`${g.type}-${g.name}-${v}`))})})]}),e.jsx(s.DialogFooter,{children:e.jsx("div",{className:"flex w-full justify-between",children:e.jsxs("div",{className:"flex grow justify-end gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:m,disabled:n.length===0,children:["Select"," ",n.length>0?`(${n.length})`:""]})]})})})]})})}function $a({entity:t,title:a,maxDetails:n=10}){const l=s.getEntityDetails(t).slice(0,n),i=l.find(o=>o.label==="Description"),c=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)}),i&&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:i.value})]}),c.length>0&&e.jsx("div",{className:"space-y-0.5",children:c.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 qa({entities:t}){return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:[t.length," more entities"]}),e.jsx("div",{className:"space-y-1",children:t.map((a,n)=>{const r=s.getEntityDetails(a),l=r.find(c=>c.label==="Description"),i=r.filter(c=>c.label==="Description"?!1:!["Connection","Database","Schema"].includes(c.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(a)}),l&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:l.value})]}),i.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:i.map((c,o)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[c.label,":"]}),e.jsx("span",{className:"font-mono",children:c.value})]},o))})]},`remaining-${a.type}-${a.name}-${n}`)})})]})})}function qs(){const t=s.useEditorStore(c=>c.card.dataSource),{setSelectedConnectionId:a,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:l,setSelectedDatamodelId:i}=s.useEditorActions();S.useEffect(()=>{var p;if(!t)return;const{tableName:c,schemaName:o,databaseName:d,connectionId:u}=ts(t),m=(p=t.selectedEntities)==null?void 0:p[0],h=(m==null?void 0:m.type)==="model"&&"id"in m?m.id:"";a(u||""),n(d||""),r(o||""),l(c||""),i(h)},[t,a,n,r,l,i])}function Us({isVisible:t}){const a=s.useEditorStore(h=>h.isDevMode);qs();const[n,r]=S.useState(!1),[l,i]=S.useState(!1),[c,o]=S.useState(!0),d=s.useEditorStore(h=>h.card.dataSource);s.useCurrentUserInfo();const{updateDataSource:u}=s.useEditorActions(),m={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},x={...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(!c),className:"size-6 bg-background p-1 py-1 hover:bg-accent",children:c?e.jsx(s.ChevronUp,{className:"h-3.5 w-3.5"}):e.jsx(s.ChevronDown,{className:"h-3.5 w-3.5"})})})]}),e.jsxs("div",{className:`overflow-hidden px-6 ${c?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[x.selectedEntities.length>0&&e.jsx(s.TooltipProvider,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[x.selectedEntities.slice(0,3).map((h,p)=>e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[s.getDisplayName(h),e.jsx("button",{onClick:j=>{j.stopPropagation();const g=x.selectedEntities.filter(v=>!(v.name===h.name&&v.type===h.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($a,{entity:h})]},`${h.type}-${h.name}-${p}`)),x.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:["+",x.selectedEntities.length-3," more"]})}),e.jsx(qa,{entities:x.selectedEntities.slice(3)})]})]})}),!a&&e.jsx(za,{})]})]}),e.jsx($s,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(d==null?void 0:d.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:r,dataSource:x}),e.jsx(Ga,{open:l,onOpenChange:i})]})}function as({error:t,errorSql:a,onSendFeedback:n,onOpenInEditor:r,className:l,showFeedbackButton:i=!0,errorTitle:c="Query Error"}){const[o,d]=S.useState(!1);return e.jsx("div",{className:s.cn("rounded-lg border border-destructive/30 bg-destructive/5 p-4",l),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(s.CircleAlert,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-destructive"}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-destructive",children:c}),e.jsxs("div",{className:"relative rounded-md bg-background/60 p-3",children:[e.jsx(s.CopyButton,{text:t,className:"absolute right-2 top-2 h-6 w-6 z-10"}),e.jsx("div",{className:"max-h-40 overflow-auto pr-10",children:e.jsx("p",{className:"font-mono text-xs text-foreground/80 break-all",children:t})})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(s.Collapsible,{open:o,onOpenChange:d,children:e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",children:o?e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronUp,{className:"mr-1.5 h-3.5 w-3.5"}),"Hide Details"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronDown,{className:"mr-1.5 h-3.5 w-3.5"}),"Show Details"]})})})}),r&&a&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:r,children:[e.jsx(Is,{className:"mr-1.5 h-3.5 w-3.5"}),"Open in Editor"]}),i&&n&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:n,children:[e.jsx(s.MessageSquareWarning,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]})]}),e.jsx(s.Collapsible,{open:o,onOpenChange:d,children:e.jsx(s.CollapsibleContent,{className:"space-y-2",children:e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:a?"Error SQL Query":"SQL Query"}),a&&e.jsx(s.CopyButton,{text:a,className:"h-6 w-6"})]}),a?e.jsx("div",{className:"rounded-md bg-background/60 p-2 max-h-80 overflow-auto",children:e.jsx(s.CodeHighlighter,{code:a,language:"sql"})}):e.jsx("div",{className:"rounded-md bg-background/60 p-3",children:e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"SQL query not available for this error"})})]})})})]})]})})}function Ks({sql:t,error:a,errorSql:n,onDebugWithAssistant:r}){const l=s.useEditorStore(g=>g.isDevMode),{setIsDevMode:i,setCardSql:c,setRunSql:o}=s.useEditorActions(),[d,u]=S.useState(!1),m=s.useEditorStore(g=>g.card),x=s.useEditorStore(g=>g.frame),h=s.useDashboardStore(g=>g.selectedSheetId),p=s.useDashboardStore(g=>{var v;return(v=g.dashboard)==null?void 0:v.id});function j(g){i(!0),c(g||t),setTimeout(()=>{o(!0)},100)}return e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col pt-4",children:[!l&&t&&!a&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsxs(s.Button,{onClick:()=>j(),variant:"secondary",size:"sm",children:[e.jsx(Is,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),e.jsxs(s.Button,{onClick:()=>u(!d),variant:"outline",size:"sm",children:[e.jsx(s.Info,{className:"mr-2 h-4 w-4"}),"Card Details"]})]}),d&&e.jsx("div",{className:"mb-3 rounded-lg border border-border bg-muted/30 p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Card Information"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>u(!1),children:e.jsx(Es,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Card ID"}),e.jsx("code",{className:"text-xs font-mono",children:m.id||"N/A"})]}),e.jsx(s.CopyButton,{text:m.id||"",className:"h-6 w-6"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Frame ID"}),e.jsx("code",{className:"text-xs font-mono",children:x.id||"N/A"})]}),e.jsx(s.CopyButton,{text:x.id||"",className:"h-6 w-6"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Sheet ID"}),e.jsx("code",{className:"text-xs font-mono",children:h||"N/A"})]}),e.jsx(s.CopyButton,{text:h||"",className:"h-6 w-6"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Dashboard ID"}),e.jsx("code",{className:"text-xs font-mono",children:p||"N/A"})]}),e.jsx(s.CopyButton,{text:p||"",className:"h-6 w-6"})]})]})]})}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-auto text-xs leading-relaxed text-foreground/80",children:[a&&e.jsx(as,{error:a,errorSql:n,showFeedbackButton:!1,onOpenInEditor:()=>j(n)}),!a&&t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute right-2 top-2 z-10",children:e.jsx(s.CopyButton,{text:t,className:"h-6 w-6"})}),e.jsx(s.CodeHighlighter,{code:t,language:"sql"})]})})]}),a&&r&&e.jsx("div",{className:"mt-3",children:e.jsxs(s.Button,{onClick:r,size:"sm",variant:"outline",children:[e.jsx(Lt,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})})]})}function Ua({sql:t,error:a,errorSql:n,onDebugWithAssistant:r}){return e.jsxs(s.HoverCard,{openDelay:a?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:a?e.jsx(Es,{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(Ks,{errorSql:n,sql:t,error:a,onDebugWithAssistant:r})})]})}function Ka(t){return s.GenIcon({attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M439.8 200.5c-7.7-30.9-22.3-54.2-53.4-54.2h-40.1v47.4c0 36.8-31.2 67.8-66.8 67.8H172.7c-29.2 0-53.4 25-53.4 54.3v101.8c0 29 25.2 46 53.4 54.3 33.8 9.9 66.3 11.7 106.8 0 26.9-7.8 53.4-23.5 53.4-54.3v-40.7H226.2v-13.6h160.2c31.1 0 42.6-21.7 53.4-54.2 11.2-33.5 10.7-65.7 0-108.6zM286.2 404c11.1 0 20.1 9.1 20.1 20.3 0 11.3-9 20.4-20.1 20.4-11 0-20.1-9.2-20.1-20.4.1-11.3 9.1-20.3 20.1-20.3zM167.8 248.1h106.8c29.7 0 53.4-24.5 53.4-54.3V91.9c0-29-24.4-50.7-53.4-55.6-35.8-5.9-74.7-5.6-106.8.1-45.2 8-53.4 24.7-53.4 55.6v40.7h106.9v13.6h-147c-31.1 0-58.3 18.7-66.8 54.2-9.8 40.7-10.2 66.1 0 108.6 7.6 31.6 25.7 54.2 56.8 54.2H101v-48.8c0-35.3 30.5-66.4 66.8-66.4zm-6.7-142.6c-11.1 0-20.1-9.1-20.1-20.3.1-11.3 9-20.4 20.1-20.4 11 0 20.1 9.2 20.1 20.4s-9 20.3-20.1 20.3z"},child:[]}]})(t)}function _s(t){const{theme:a}=s.useTheme(),n=s.useDashboardStore(g=>g.theme),r=s.useEditorStore(g=>g.frame),l=s.useEditorStore(g=>g.card),i=s.useEditorStore(g=>g.activeTabCardId),c=s.Le(),{refetch:o}=s.useDashboardCardQuery(l),{updateCardTab:d,setRunSql:u}=s.useEditorActions(),m=S.useRef(),x=S.useRef({}),h=r.cards.find(g=>g.id===i),p=S.useCallback(()=>{let g="";return t==="python"&&(g=(h==null?void 0:h.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(g=(h==null?void 0:h.sql)||""),g},[t,h]);S.useEffect(()=>{if(i&&l.id&&l.id!==i){if(m.current&&c){const g=m.current.getModel();g&&(x.current[l.id]=g);let v=x.current[i];if(!v){const D=p();v=c.editor.createModel(D,t),x.current[i]=v}m.current.setModel(v)}d(i,l),u(!0)}},[i,l,d,c,u,t,p]),S.useEffect(()=>{if(!c)return;const g=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",v=n==="system"?g:n;c.editor.defineTheme("default",{base:v==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":v==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[a,n,c]),S.useEffect(()=>{const g=m.current;g&&c&&l&&g.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return o(),!1})},[c,o,l]);function j(g,v){if(m.current=g,!x.current[l.id]){const D=g.getModel(),k=p();x.current[l.id]=D||(v==null?void 0:v.editor.createModel(k,t))||g.getModel()}g.setModel(x.current[l.id])}return{handleEditorDidMount:j}}function _a(){const t=s.useEditorStore(c=>c.card.sql),a=s.useEditorStore(c=>c.sqlGen),{setCardSql:n,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=_s("sql");function i(c){n(c),s.isObjectEmpty(a)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:i,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function Ha(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:a}=s.useEditorActions(),{handleEditorDidMount:n}=_s("python");function r(l){a(l)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:n})}function Ja({jsonString:t}){return e.jsx(s.Ft,{theme:"default",defaultLanguage:"json",className:"mt-1 min-h-[220px]",value:t,options:{readOnly:!0,minimap:{enabled:!1},lineNumbers:"off",glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})}function Qa(){const t=s.useQueryClient(),{isConsoleMode:a}=s.useDashboardPreferences(),[n,r]=S.useState(!1),[l,i]=S.useState(!1);s.useEditorStore(R=>R.frame);const c=s.useEditorStore(R=>R.card);s.useEditorStore(R=>R.isShowingVisual),s.useEditorStore(R=>R.selectedConnectionId),s.useEditorStore(R=>R.tempQueryData),s.useEditorStore(R=>R.selectedDatabaseName),s.useEditorStore(R=>R.selectedDatamodelId),s.useEditorStore(R=>R.selectedSchemaName);const o=s.useEditorStore(R=>R.showAIDialog);s.useEditorStore(R=>R.selectedTableName);const d=s.useEditorStore(R=>{var _;return(_=R==null?void 0:R.card)==null?void 0:_.sql}),u=s.useEditorStore(R=>{var _;return(_=R==null?void 0:R.card)==null?void 0:_.python}),{cardFilterValues:m}=s.useCardFilterValues((c==null?void 0:c.id)??""),{setCardCustomCfg:x,setQueryResultColumns:h,setCardSql:p,setTempQueryData:j,setPythonStdOut:g,setCardPreferences:v,setCardType:D,setCardPython:k,runAssistant:B,setShowAIDialog:L}=s.useEditorActions();s.useEditorStore(R=>R.onSave),s.useEditorStore(R=>R.onClose),s.useEditorStore(R=>R.actions.setSqlGen);const E=s.useEditorStore(R=>R.runSql),C=s.useEditorStore(R=>R.actions.setRunSql),f=s.useEditorStore(R=>R.actions.setIsSqlRunning),{data:b,isLoading:N,isFetching:A,isSuccess:w,isError:P,error:I,errorSql:T,queryKey:y,refetch:M,errorMessage:F}=s.useDashboardCardQuery(c);S.useEffect(()=>{if(b&&(b.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),g((b==null?void 0:b.output)||""),b.records.length>0)){const{dimensionKeys:R}=s.getKeys(b.records);h(R)}},[b,h,g]),S.useEffect(()=>{(N||A)&&f(!0),(P||w)&&f(!1),P&&(h([]),g(""))},[N,A,b,g,P,w,f,h,I]),S.useEffect(()=>{E&&(t.getQueryData(y)||M(),C(!1))},[E,M,C,y,t]);async function z(){const R=`Can you help me debug this query?
|
|
223
|
+
|
|
224
|
+
Error:
|
|
225
|
+
|
|
226
|
+
${F}
|
|
227
|
+
|
|
228
|
+
Error SQL:
|
|
229
|
+
|
|
230
|
+
${T}
|
|
231
|
+
|
|
232
|
+
Query:
|
|
233
|
+
|
|
234
|
+
${d}
|
|
235
|
+
|
|
236
|
+
${u?`Python:
|
|
237
|
+
${u}`:""}
|
|
238
|
+
`;B(R)}function $(){return e.jsxs(e.Fragment,{children:[l&&e.jsx("div",{className:"relative flex w-1/3 min-w-0 grow overflow-hidden text-xs",role:"editor-filter-container",children:e.jsx("div",{className:"mt-2 w-[99%]",children:e.jsx(Ja,{jsonString:JSON.stringify(m,null,2)})})}),m&&m.length>0&&e.jsx(s.Button,{variant:"ghost",onClick:()=>i(!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 O(){return e.jsxs(s.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(s.ResizablePanel,{id:"1",order:1,defaultSize:n?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(_a,{})}),n&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),n&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(s.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:[e.jsx("div",{id:"python-container",className:"relative flex w-[99%] pt-0",children:e.jsx(Ha,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function 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:N||A,onClick:()=>{M()},className:"h-8 shrink-0",size:"sm",children:[N||A?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(s.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),e.jsx(Ua,{errorSql:T,sql:b==null?void 0:b.sql,error:F,onDebugWithAssistant:z}),e.jsx(Ze,{}),e.jsxs(s.Toggle,{pressed:n,onPressedChange:R=>r(R),className:"h-8",size:"sm",variant:"outline",children:[e.jsx(Ka,{className:"mr-2 size-4 text-foreground/70"}),"Python"]}),!o&&e.jsxs("button",{disabled:o,onClick:()=>{L(!0)},className:"flex h-9 w-full cursor-text items-center justify-start px-3 text-left text-sm text-muted-foreground",children:[e.jsx(s.Sparkles,{className:"mr-3 size-4 text-foreground/70"}),"Type your question..."]})]})})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsxs("div",{className:"relative flex grow justify-between overflow-y-scroll",children:[O(),$()]}),G()]})}const Wa=[{value:"table",label:"Table",icon:s.Table2},{value:"aggregateTable",label:"Aggregate",icon:s.Layers},{value:"pivotTable",label:"Pivot",icon:s.Grid3x3}];function Ya({className:t}){const a=s.useEditorStore(d=>d.card),{setCardType:n,setCard:r,updateCardInFrame:l}=s.useEditorActions(),i=["table","aggregateTable","pivotTable"].includes(a.type),c=s.hasValidCardConfig(a.config);if(!i||!c)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 x={...a,type:u,config:{...a.config,pivotByColumns:[]}};r(x),l(x)}else{n(u);const x={...a,type:u};l(x)}};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:Wa.map(d=>{const u=d.icon,m=a.type===d.value;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(s.RadioGroupItem,{value:d.value,id:`table-type-${d.value}`,className:"peer sr-only"}),e.jsxs(s.Label,{htmlFor:`table-type-${d.value}`,className:s.cn("flex cursor-pointer items-center gap-1.5 rounded-md px-3 py-1 text-sm font-medium transition-all",m?"bg-muted text-foreground shadow-sm":"text-muted-foreground hover:bg-muted/50"),children:[e.jsx(u,{className:"h-3.5 w-3.5"}),d.label]})]},d.value)})})})}function Xa({card:t}){var B,L,E,C,f,b,N,A,w,P,I;const[a,n]=S.useState(!1),[r,l]=S.useState([]),{authToken:i}=s.useSemaphorContext(),{theme:c}=s.useTheme(),o=s.getTokenParams(i==null?void 0:i.accessToken),d=s.useDashboardStore(T=>T.themeStyle),u={mode:c||"system",colors:((L=(B=d==null?void 0:d.chart)==null?void 0:B.dataset)==null?void 0:L.backgroundColor)||[]};(E=t.customCardPreferences)!=null&&E.inputData;const{getCard:m}=s.useCustomVisual(((C=t.customCardPreferences)==null?void 0:C.url)||""),x=((f=t.customCardPreferences)==null?void 0:f.visualType)||"single",h=s.useEditorStore(T=>T.frame),{setCustomCardPreferences:p}=s.useEditorActions(),{data:j}=s.useDashboardCardQuery(t),g=S.useCallback((T,y)=>{l(M=>({...M,[T]:y}))},[]);if(!((b=t.customCardPreferences)!=null&&b.componentName))return null;const v=m((N=t.customCardPreferences)==null?void 0:N.componentName);function D(T){n(T)}const k=Object.keys(((A=t.customCardPreferences)==null?void 0:A.dataInputCardIds)||{}).map(T=>{var F,z,$;const y=(z=(F=t.customCardPreferences)==null?void 0:F.dataInputCardIds)==null?void 0:z[T].cardId,M=($=h==null?void 0:h.cards)==null?void 0:$.find(O=>O.id===y);return M||null});return e.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:e.jsxs(S.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[v&&x==="single"&&e.jsx(v,{editing:!0,params:o,theme:u,settings:(w=t.customCardPreferences)==null?void 0:w.settings,onDataChange:g,data:(j==null?void 0:j.records)||[]}),v&&x==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((P=t.customCardPreferences)==null?void 0:P.dataInputCardIds)||{}).map(T=>{var F,z,$;const y=(z=(F=t.customCardPreferences)==null?void 0:F.dataInputCardIds)==null?void 0:z[T].cardId,M=($=h==null?void 0:h.cards)==null?void 0:$.find(O=>O.id===y);if(M)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:D,onDataChange:g,dataInputIndex:T,card:M},M.id+T)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(v,{theme:u,onDataChange:g,settings:k.map(T=>{var y;return(y=T==null?void 0:T.customCardPreferences)==null?void 0:y.settings}),data:k.map(T=>T!=null&&T.id?r==null?void 0:r[T.id]:[])})})]})]},(I=t.customCardPreferences)==null?void 0:I.componentName)})}function Za({type:t,isLinked:a,className:n}){const r=s.useDashboardStore(h=>h.selectedFrameId),l=s.useManagementStore(h=>h.selectedVisual),i=s.useEditorStore(h=>h.frame);let c;if(t)c=t;else if(a!==void 0)c=a?"linked":"library";else if(!!!(i!=null&&i.visualId||l!=null&&l.id)&&r)c="local";else if(l&&!r)c="library";else if(i!=null&&i.visualId&&r)c="linked";else if(l!=null&&l.id&&r)c="library";else return null;if(c==="local")return null;const o={linked:"border-purple-200/70 bg-gradient-to-r from-purple-50/50 to-purple-100/30 text-purple-900 shadow-sm hover:from-purple-100/60 hover:to-purple-100/50 hover:shadow-md dark:border-purple-800/50 dark:from-purple-950/40 dark:to-purple-900/30 dark:text-purple-100 dark:hover:from-purple-950/60 dark:hover:to-purple-900/50",library:"border-blue-200/70 bg-gradient-to-r from-blue-50/50 to-blue-100/30 text-blue-900 shadow-sm hover:from-blue-100/60 hover:to-blue-100/50 hover:shadow-md dark:border-blue-800/50 dark:from-blue-950/40 dark:to-blue-900/30 dark:text-blue-100 dark:hover:from-blue-950/60 dark:hover:to-blue-900/50"},d={linked:"Linked to library: Changes made here update the library visual and all linked instances.",library:"Library visual: Share and reuse this visual across multiple dashboards."},u={linked:"border-purple-200 bg-purple-50 text-purple-900 dark:border-purple-800 dark:bg-purple-950 dark:text-purple-100",library:"border-blue-200 bg-blue-50 text-blue-900 dark:border-blue-800 dark:bg-blue-950 dark:text-blue-100"},m={linked:"fill-purple-50 dark:fill-purple-950",library:"fill-blue-50 dark:fill-blue-950"},x={linked:e.jsx(Ot,{className:"h-3.5 w-3.5"}),library:e.jsx(Pt,{className:"h-3.5 w-3.5"})};return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:s.cn("cursor-help select-none transition-all",o[c],n),children:x[c]})}),e.jsxs(s.TooltipContent,{side:"bottom",className:s.cn("max-w-xs",u[c]),children:[e.jsx(s.TooltipArrow,{className:m[c]}),e.jsx("p",{children:d[c]})]})]})})}function Hs({className:t,...a}){var $;const n=s.useEditorStore(O=>O.card),r=(($=n.customCardPreferences)==null?void 0:$.showCardHeader)??!0,l=s.useEditorStore(O=>O.frame),i=s.useDashboardStore(O=>O.dashboard.filters),[c,o]=S.useState(!1),{currentUser:d}=s.useCurrentUserInfo(),{tokenProps:u}=S.useContext(s.SemaphorContext),m=s.useEditorStore(O=>O.actions.setRunSql),{updateFilter:x}=s.useDashboardActions(),h=i==null?void 0:i.find(O=>O.id===l.filterId),{data:p,isLoading:j,isFetching:g,errorMessage:v,errorSql:D,pagination:k}=s.useDashboardCardQuery(n),B=S.useMemo(()=>(p==null?void 0:p.records)||[],[p==null?void 0:p.records]),{setCard:L,updateCardInFrame:E,setIsDevMode:C,setCardSql:f}=s.useEditorActions(),{data:b}=s.useTopoJson(n),N=S.useMemo(()=>{var O;return n.type!=="pivotTable"||!((O=p==null?void 0:p.records)!=null&&O.length)?null:{records:p.records,columnSubtotalMeta:p.columnSubtotalMeta,subtotalColumns:p.subtotalColumns||[],pivotSchema:p.pivotSchema||[],groupByColumns:p.groupByColumns}},[n.type,p==null?void 0:p.records,p==null?void 0:p.columnSubtotalMeta,p==null?void 0:p.subtotalColumns,p==null?void 0:p.pivotSchema,p==null?void 0:p.groupByColumns]),A=s.usePivotTableConfig(n,N),w=O=>{C(!0),f(O||D||n.sql||n.python||""),setTimeout(()=>{m(!0)},100)},P=()=>{o(!0)},I=S.useMemo(()=>{const O=typeof window<"u"?window.location.href:"",G=typeof navigator<"u"?navigator.userAgent:"",R=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:s.FeedbackCategory.QUERY_GENERATION,user:d,tokenContext:u,systemState:{cardConfig:n.config,dataSource:n.dataSource,dashboardFilters:i,errorMessage:v||void 0,errorSql:D||n.sql||n.python,generatedSql:D||n.sql},metadata:{url:O,userAgent:G,timestamp:new Date().toISOString(),viewport:R}}},[d,u,n,i,v,D]),T=(O,G)=>{var _,J;const R={...n,paginationConfig:{page:O+1,pageSize:G}};L(R),E(R),n.sql&&((J=(_=n.preferences)==null?void 0:_.tablePrefs)!=null&&J.enableDevModePagination)&&m(!0)},y=O=>{var _,J,se,Z;const G=s.sortStateToSortByColumns(O,(_=n.config)==null?void 0:_.metricColumns,(J=n.config)==null?void 0:J.groupByColumns),R={...n,config:{...n.config||{},sortByColumns:G}};L(R),E(R),n.sql&&((Z=(se=n.preferences)==null?void 0:se.tablePrefs)!=null&&Z.enableDevModePagination)&&m(!0)},M=S.useMemo(()=>!n.id||!(p!=null&&p.records)?null:s.createChartConfig({card:n,data:p==null?void 0:p.records,cardType:n.type,queryConfig:n.queryConfig,customCfg:n.customCfg,preferences:n.preferences,topoJson:b}),[n.id,p==null?void 0:p.records,n.type,n.customCfg,n.preferences,b]);function F(O){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Xa,{card:O})})}function z(){if(p!=null&&p.records&&(p==null?void 0:p.records.length)===0&&!j&&!g)return v?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(as,{error:v,errorSql:D||n.sql||n.python,onOpenInEditor:w,onSendFeedback:P,showFeedbackButton:!0,errorTitle:"Unable to Create Visual"})}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((j||g)&&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 F(n);if(!["table","pivotTable","aggregateTable","custom"].includes(n.type)&&M)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:j||g?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:M})});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:B,paginationMetadata:k,onPaginationChange:T,onSortChange:y,isLoading:j||g})});if(n.type==="pivotTable"&&A)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:A.data,options:A.options,onAggregationChange:O=>{const G=s.handleAggregationChange(O,n.config),R={...n,config:G};L(R),E(R)},onAggregationLabelChange:O=>{const G=s.handleAggregationLabelChange(O,n.config),R={...n,config:G};L(R),E(R)}})});if(n.type==="aggregateTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.AggregateTable,{card:n,data:(p==null?void 0:p.records)||[],groupByColumns:p==null?void 0:p.groupByColumns,pivotSchema:p==null?void 0:p.pivotSchema,paginationMetadata:k,onPaginationChange:T,onAggregationChange:O=>{const G=s.handleAggregationChange(O,n.config),R={...n,config:G};L(R),E(R)},isLoading:j||g})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...a,children:[r&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.CardTitle,{className:"text-base",children:e.jsx(s.EditableText,{value:n.title,onSave:O=>L({...n,title:O}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(Za,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(Ya,{})})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:n.description||"",onSave:O=>L({...n,description:O}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),h&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:h.title||h.column,onSave:O=>x({...h,title:O}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:h})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:z()}),e.jsx(s.FeedbackDialog,{open:c,onOpenChange:o,feedbackData:I,showDebugInfo:!0})]})}const Ke=({language:t,value:a,onChange:n,readonly:r})=>e.jsx(s.Ft,{className:"h-full w-full overflow-hidden text-xs",theme:"default",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,lineHeight:16,renderLineHighlight:"none",readOnly:r},defaultLanguage:t,value:a,onChange:n}),en=()=>e.jsxs(s.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(s.DialogTitle,{children:"Customize Card"})}),e.jsxs(s.DialogDescription,{children:["See the configuration options and documentation",e.jsx("a",{target:"_blank",className:"ml-1 text-blue-500 underline",href:"https://www.chartjs.org/docs/latest/samples/bar/vertical.html",children:"here."})]})]}),sn=({customCode:t,cardCustomCfgString:a,mergedConfig:n,onConfigChange:r,onCodeChange:l})=>e.jsxs(s.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(s.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(s.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(s.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(s.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(s.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Ke,{language:"json",value:n,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Ke,{readonly:!0,language:"json",value:a,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Ke,{language:"javascript",value:t,onChange:l})})]}),tn=({error:t,hasCardCustomConfig:a,onReset:n,onApply:r,onClose:l})=>e.jsxs(s.DialogFooter,{className:"flex items-center",children:[e.jsx(s.Label,{className:"mr-2 text-red-500",children:t}),e.jsx(s.Button,{disabled:!a,onClick:n,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:l,variant:"outline",children:"Close"})]});function an(){const[t,a]=S.useState(!1),[n,r]=S.useState(""),[l,i]=S.useState(""),[c,o]=S.useState(""),[d,u]=S.useState(""),m=s.useEditorStore(E=>E.card),x=s.useEditorStore(E=>E.card.customCfg),h=x?JSON.stringify(x,null,2):"",{data:p}=s.useDashboardCardQuery(m),{data:j}=s.useTopoJson(m),{setCardCustomCfg:g,setCustomVisualCode:v}=s.useEditorActions(),D=E=>{var C,f;return JSON.stringify({...E,data:{...E.data,datasets:(f=(C=E.data)==null?void 0:C.datasets)==null?void 0:f.map(b=>({...b,data:[]}))}},null,2)},k=()=>{var C,f;if(!((C=p==null?void 0:p.records)!=null&&C.length))return;const E=s.createChartConfig({card:m,data:p.records,cardType:m.type,queryConfig:m.queryConfig,preferences:m.preferences,topoJson:j});if(E){r(D(E)),o(((f=m.preferences)==null?void 0:f.customVisualCode)||"");const b=s.merge(E,x);i(D(b))}},B=()=>{try{if(c&&v(c),l){const E=JSON.parse(l),C=s.getObjectDiff(JSON.parse(n),E);g(C),u("")}}catch{u("Invalid JSON configuration")}},L=Object.keys(x||{}).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(en,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Hs,{className:"w-1/2 rounded shadow-none"})}),e.jsx(sn,{customCode:c,cardCustomCfgString:h,mergedConfig:l,onConfigChange:E=>i(E??""),onCodeChange:E=>o(E??"")})]}),e.jsx(tn,{error:d,hasCardCustomConfig:!!x,onReset:()=>{i(n),g(null)},onApply:B,onClose:()=>a(!1)})]})]})}function Ge(t){const[a,n]=S.useState(null);return a}function Js(){const{authToken:t,tokenProps:a}=s.useSemaphorContext(),{data:n,isLoading:r,isFetching:l,isError:i}=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:i}}function Qs(){const{data:t,isLoading:a,isError:n}=Js(),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 i=a,c=n;return r.forEach((o,d)=>{var u;if(o.isLoading&&(i=!0),o.isError&&(c=!0),o.data&&((u=t==null?void 0:t.plugins)!=null&&u[d])){const m=t.plugins[d],x=o.data.visuals.map(h=>({name:h.name,pluginName:m.label,componentType:h.componentType,pluginType:m.type,icon:h.icon,chartType:h.chartType,url:m.value}));l.push(...x)}}),{data:l,isLoading:i,isError:c}}function nn({onChartTypeChange:t}){const{setCardCustomCfg:a,setCardPreferences:n,setCardType:r,setCustomCardPreferences:l}=s.useEditorActions(),{data:i,isLoading:c,isError:o}=Qs(),d=S.useCallback((u,m)=>{a(null),n({}),r(u),m&&l({type:"component",visualType:"single",url:m.url,componentName:m.name,icon:m.icon}),t==null||t()},[a,n,r,l,t]);return c?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-3"}),e.jsx("div",{className:"py-4 text-center text-sm text-muted-foreground",children:"Loading custom visuals..."})]}):o?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-3"}),e.jsx("div",{className:"py-4 text-center text-sm text-destructive",children:"Failed to load custom visuals"})]}):!i||i.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-3"}),e.jsx("div",{className:"mb-2",children:e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Custom Charts"})}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:i.map((u,m)=>e.jsx(rn,{text:u.name,onClick:()=>d("custom",u),icon:u.icon},`${u.url}-${u.name}-${m}`))})]})}const rn=({text:t,icon:a,onClick:n})=>{const r=Ge();return e.jsxs("button",{onClick:n,className:"flex flex-col items-center gap-2 rounded-lg border border-border bg-background p-3 transition-all hover:border-primary/50 hover:bg-muted/50 hover:shadow-sm",children:[r?e.jsx(r,{className:"h-6 w-6"}):e.jsx(Ae,{className:"h-6 w-6 text-muted-foreground"}),e.jsx("span",{title:t,className:"line-clamp-2 text-center text-xs font-medium text-foreground",children:t})]})};function ln({onChartTypeChange:t,iconClassName:a,searchQuery:n=""}){const{setCardType:r,setCardPreferences:l,setIsDevMode:i}=s.useEditorStore(h=>h.actions),{setCardCustomCfg:c,setCustomCardPreferences:o,setQueryConfig:d}=s.useEditorActions();function u(h,p){c(null),l({}),r(h),["custom","text","map"].includes(h)&&(i(!0),d(void 0)),t==null||t()}const x=[{type:"table",name:"Table",icon:s.Table2},{type:"bar",name:"Bar Chart",icon:s.ChartColumnIncreasing},{type:"line",name:"Line Chart",icon:s.ChartLine},{type:"stackedBar",name:"Stacked Bar",icon:s.ChartColumnStacked},{type:"stackedLine",name:"Stacked Line",icon:s.MdStackedLineChart},{type:"scatter",name:"Scatter",icon:s.ChartScatter},{type:"bubble",name:"Bubble",icon:s.TbChartBubble},{type:"pie",name:"Pie Chart",icon:s.ChartPie},{type:"doughnut",name:"Doughnut",icon:s.Donut},{type:"funnel",name:"Funnel",icon:s.TbChartFunnel},{type:"radar",name:"Radar",icon:s.Radar},{type:"polarArea",name:"Polar Area",icon:s.PiChartPolar},{type:"tornado",name:"Tornado",icon:s.Tornado},{type:"range",name:"Range",icon:s.ChartNoAxesGantt},{type:"bullet",name:"Bullet Chart",icon:s.BulletChartIcon},{type:"treemap",name:"Treemap",icon:s.TbChartTreemap},{type:"kpi",name:"KPI",icon:s.TiSortNumerically},{type:"text",name:"Text",icon:s.BookType},{type:"map",name:"Map",icon:s.Map},{type:"custom",name:"Custom",icon:Ae}].filter(h=>h.name.toLowerCase().includes(n.toLowerCase()));return e.jsx("div",{className:"grid grid-cols-3 gap-2",children:x.map(h=>{const p=h.icon;return e.jsxs("button",{onClick:()=>u(h.type),className:"flex flex-col items-center gap-2 rounded-lg border border-border bg-background p-3 transition-all hover:border-primary/50 hover:bg-muted/50 hover:shadow-sm",children:[e.jsx(p,{className:s.cn("h-6 w-6",a),strokeWidth:h.icon===s.MdStackedLineChart?0:void 0}),e.jsx("span",{className:"text-xs font-medium text-foreground",children:h.name})]},h.type)})})}function on({chartType:t,className:a,customIcon:n,componentName:r}){const l=Ge();switch(t){case"bar":return e.jsx(s.ChartColumnIncreasing,{className:a});case"line":return e.jsx(s.ChartLine,{className:a});case"pie":return e.jsx(s.ChartPie,{className:a});case"radar":return e.jsx(s.Radar,{className:a});case"scatter":return e.jsx(s.ChartScatter,{className:a});case"bubble":return e.jsx(s.TbChartBubble,{className:a});case"doughnut":return e.jsx(s.Donut,{className:a});case"stackedBar":return e.jsx(s.ChartColumnStacked,{className:a});case"stackedLine":return e.jsx(s.MdStackedLineChart,{className:a});case"polarArea":return e.jsx(s.PiChartPolar,{className:a});case"treemap":return e.jsx(s.TbChartTreemap,{className:a});case"bullet":return e.jsx(s.BulletChartIcon,{className:a});case"funnel":return e.jsx(s.TbChartFunnel,{className:a});case"tornado":case"pyramid":return e.jsx(s.Tornado,{className:a});case"range":return e.jsx(s.ChartNoAxesGantt,{className:a});case"kpi":return e.jsx(s.TiSortNumerically,{className:a});case"text":return e.jsx(s.Type,{className:a});case"map":return e.jsx(s.Map,{className:a});case"custom":return n&&l?e.jsx(l,{className:a}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(Ae,{className:a});default:return e.jsx(s.Table2,{className:a})}}function Ws({variant:t="ghost"}){var o,d;const[a,n]=S.useState(!1),[r,l]=S.useState(""),i=s.useEditorStore(u=>u.card),c=i.type;return e.jsxs(s.Popover,{open:a,onOpenChange:u=>{n(u),u||l("")},children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(on,{className:"size-4",chartType:c,customIcon:(o=i.customCardPreferences)==null?void 0:o.icon,componentName:(d=i.customCardPreferences)==null?void 0:d.componentName})})}),e.jsxs(s.PopoverContent,{onOpenAutoFocus:u=>u.preventDefault(),className:"z-[70] w-[360px] p-3",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2 rounded-sm border border-border bg-background px-3 py-2",children:[e.jsx(s.Search,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search charts...",value:r,onChange:u=>l(u.target.value),className:"h-auto border-0 p-0 text-sm focus-visible:ring-0 focus-visible:ring-offset-0"})]}),e.jsxs("div",{className:"max-h-[400px] overflow-y-auto",children:[e.jsx(ln,{onChartTypeChange:()=>n(!1),searchQuery:r}),e.jsx(nn,{onChartTypeChange:()=>n(!1)})]})]})]})}function cn({error:t,className:a="",textClassName:n="",copyButtonClassName:r=""}){const[l,i]=S.useState(!1),c=S.useRef(null),o=S.useRef(!1);function d(){t&&!o.current&&navigator.clipboard.writeText(t)}function u(h){(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),d())}function m(){const h=window.getSelection();if(h&&h.toString().trim()!==""){const p=h.toString();navigator.clipboard.writeText(p),i(!0),o.current=!0,setTimeout(()=>{i(!1),o.current=!1},1e3)}else o.current=!1}function x(){i(!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:c,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${n}`,onClick:d,onKeyDown:u,onMouseUp:m,onMouseDown:x,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),l&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function dn(){const t=s.useEditorStore(d=>{var u,m;return(m=(u=d.card.preferences)==null?void 0:u.chartOptions)==null?void 0:m.indexAxis}),a=s.useEditorStore(d=>d.card.type),{setChartOrientation:n,setCardPreferences:r}=s.useEditorStore(d=>d.actions),l=d=>{if(n(d),a!=="bullet")return;const u=d==="y"?"horizontal":"vertical",m=s.useEditorStore.getState().card.preferences,x={...m||{},bulletConfig:{...(m==null?void 0:m.bulletConfig)||{},orientation:u}};r(x)};function i(){const d=t??"x",u=()=>{l(d==="x"?"y":"x")};return e.jsx(s.IconButton,{onClick:u,tooltip:"Chart Orientation",children:d==="x"?e.jsx(Ue,{className:"size-4"}):e.jsx(qe,{className:"size-4"})})}function c(){const d=()=>{l(t==="y"||t===void 0?"x":"y")};return e.jsx(s.IconButton,{onClick:d,tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(Ue,{className:"size-4"}):e.jsx(qe,{className:"size-4"})})}function o(){const d=t??"y",u=()=>{l(d==="y"?"x":"y")};return e.jsx(s.IconButton,{onClick:u,tooltip:"Chart Orientation",children:d==="y"?e.jsx(qe,{className:"size-4"}):e.jsx(Ue,{className:"size-4"})})}return e.jsx(e.Fragment,{children:a==="funnel"?c():a==="bullet"?o():i()})}function un({className:t}){var h,p,j,g,v,D,k,B;const a=s.useEditorStore(L=>L.card),{setCardPreferences:n,updateCardInFrame:r,setCard:l}=s.useEditorActions(),[i,c]=S.useState(!1),o=((p=(h=a.preferences)==null?void 0:h.displayOptions)==null?void 0:p.showFilterInfo)??!0,d=((g=(j=a.preferences)==null?void 0:j.displayOptions)==null?void 0:g.showCardToolbar)??!0,u=((D=(v=a.preferences)==null?void 0:v.displayOptions)==null?void 0:D.showChrome)??!0,m=((B=(k=a.preferences)==null?void 0:k.displayOptions)==null?void 0:B.allowScroll)??!0,x=(L,E)=>{var b;const C={...a.preferences,displayOptions:{...(b=a.preferences)==null?void 0:b.displayOptions,[L]:E}};n(C);const f={...a,preferences:C};l(f),r(f)};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsxs(s.DropdownMenu,{modal:!1,open:i,onOpenChange:c,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{className:"h-8 w-8 p-0",tooltip:"Display Options",children:e.jsx(As,{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=>{x("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=>{x("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=>{x("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=>{x("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 Ys(){const t=s.useEditorStore(i=>i.card),a=s.useEditorStore(i=>{var c,o;return(o=(c=i.card)==null?void 0:c.preferences)==null?void 0:o.chartOptions}),n=s.getChartGridStyle(a),{setChartGrid:r}=s.useEditorActions();function l(){const i=["xy","none","x","y"],o=(i.indexOf(n)+1)%i.length;r(i[o])}return e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel","bullet"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(dn,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsx(e.Fragment,{}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(t.type)&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:l,children:[(n==="xy"||!n)&&e.jsx(s.Grid3x3,{className:"size-4"}),n==="x"&&e.jsx(Ct,{className:"size-4"}),n==="y"&&e.jsx(Ut,{className:"size-4"}),n==="none"&&e.jsx(Ht,{className:"size-4"})]}),e.jsx(un,{})]})}function mn(){const t=s.useEditorStore(j=>j.frame),a=s.useEditorStore(j=>j.card),{setFrame:n,setActiveTabCardId:r,setCard:l,updateCardInFrame:i}=s.useEditorActions(),c=(j,g)=>{j.dataTransfer.setData("tabIndex",g.toString())},o=j=>{j.preventDefault()},d=(j,g)=>{const v=j.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(j){const g=t.cards.filter(k=>k.id!==j),v=g[0],D={...t,cards:g,activeCardId:v.id};n(D),r(v.id),l(v)}function m(j,g){const v={...t,cards:[...t.cards,g],activeCardId:j.id};n(v),r(g.id)}function x(){const j={...a,id:s.v4(),title:`${a.title} Copy`,tabTitle:`${a.tabTitle||a.title} Copy`};m(a,j)}function h(j){const g={dataSource:j.dataSource,connectionId:j.connectionId,lastSelectedDatabase:j.lastSelectedDatabase,lastSelectedSchema:j.lastSelectedSchema,lastSelectedTable:j.lastSelectedTable,lastSelectedDatamodelId:j.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};m(j,g)}function p(j,g){return j.cards.length===1&&(g.displayTab===!0||g.displayTab===void 0)||j.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}),i({...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(Tt,{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((j,g)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:v=>c(v,g),onDragOver:o,onDrop:v=>d(v,g),className:"",value:j.id,children:[p(t,j),e.jsx(s.Editable,{enabled:t.activeCardId===j.id,text:j.tabTitle||j.title,onSave:v=>{l({...a,tabTitle:v}),i({...a,tabTitle:v})},children:j.tabTitle||j.title},j.id),t.activeCardId===j.id&&e.jsx(s.CopyPlus,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:v=>{v.stopPropagation(),x()}}),t.activeCardId===j.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>u(j.id)})]},j.id)),e.jsx(s.IconButton,{tooltip:"Add Card",className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",onClick:()=>h(a),children:e.jsx(s.Plus,{className:"h-4 w-4"})})]})})}function Ye(){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:i,setCard:c,setIsDevMode:o,setRunSql:d}=s.useEditorActions(),{data:u,isLoading:m,isFetching:x,isError:h}=s.useDashboardCardQuery(a);function p(v){const D=t.cards.find(k=>k.id===v);if(D!=null&&D.sql){r||o(!0),i(v);return}if(D!=null&&D.queryConfig){r&&o(!1),j(v),i(v);return}r||j(v),i(v)}function j(v){const D={...t,cards:t.cards.map(B=>B.id===a.id?a:B),activeCardId:v};l(D);const k=D.cards.find(B=>B.id===v);k.sql&&d(!0),c(k)}function g(){return a.type==="kpi"?m||x?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||x,isError:h})})}):a.type==="text"?m||x?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(Hs,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:p,value:t.activeCardId,className:"flex grow flex-col",children:[t.cards.map(v=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:v.id,children:g()},v.id)),e.jsx(mn,{})]})}function fs({children:t}){var f,b;s.useEditorStore(N=>N.frame);const a=s.useEditorStore(N=>N.card),n=s.useEditorStore(N=>N.isDevMode),r=s.useEditorStore(N=>N.isShowingVisual),l=s.useDashboardStore(N=>N.isVisualEditing),i=s.useEditorStore(N=>N.pythonStdOut);s.useEditorStore(N=>N.actions.setRunSql);const{setFrame:c,setCard:o,setActiveTabCardId:d,runAssistant:u,setIsDevMode:m,setCardPreferences:x}=s.useEditorActions(),{data:h,isLoading:p,isFetching:j,errorMessage:g,refetch:v}=s.useDashboardCardQuery(a),D=S.useMemo(()=>(h==null?void 0:h.records)||[],[h==null?void 0:h.records]),[k,B]=S.useState(!1);S.useEffect(()=>{j||B(!1)},[j]);function L(){const N=JSON.stringify(h==null?void 0:h.records,null,2),A=new Blob([N],{type:"application/json"}),w=URL.createObjectURL(A),P=document.createElement("a");P.href=w,P.download=`${a.title}.json`,P.click()}function E(){const A=[Object.keys(h==null?void 0:h.records.reduce((T,y)=>({...T,...y}),{})).join(","),...((h==null?void 0:h.records)||[]).map(T=>Object.values(T).join(","))].join(`
|
|
239
|
+
`),w=new Blob([A],{type:"text/csv"}),P=URL.createObjectURL(w),I=document.createElement("a");I.href=P,I.download=`${a.title}.csv`,I.click()}function C(){const N=`Can you get the documentation for ${a.type} chart?`;u(N)}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(Ws,{}),l&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:C,children:e.jsx(vt,{className:"size-4"})}),!["table","custom"].includes(a.type)&&l&&e.jsx(an,{})]}),!r&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:E,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:L,children:e.jsx(kt,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(h==null?void 0:h.records,null,2),className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t,e.jsx(s.IconButton,{tooltip:"Refresh",disabled:p||j,onClick:()=>{B(!0),v()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":k})})}),e.jsx(Ys,{})]}),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:((b=(f=a.preferences)==null?void 0:f.tablePrefs)==null?void 0:b.enableDevModePagination)??!1,onCheckedChange:N=>{var A;x({...a.preferences,tablePrefs:{...(A=a.preferences)==null?void 0:A.tablePrefs,enableDevModePagination:N}}),v()}}),e.jsx(s.Label,{htmlFor:"pagination",children:"Paginate Results"})]}),n&&e.jsx(xn,{})]}),r?e.jsx(Ye,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[i&&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:i&&e.jsx(hn,{})}),e.jsx(s.ResizableHandle,{})]}),e.jsxs(s.ResizablePanel,{id:"2",order:2,minSize:10,className:s.cn("relative flex h-full min-h-0 w-full flex-1 basis-0",{"px-6":i}),children:[(h==null?void 0:h.records)&&(h==null?void 0:h.records.length)>0&&e.jsx(s.TableVisual,{card:a,data:D}),g&&e.jsx(cn,{error:g})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function hn(){const t=s.useEditorStore(n=>n.pythonStdOut);if(!t)return null;const a=t.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(s.ScrollArea,{className:"overflow-y-auto pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:a}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function xn(){const t=s.useEditorStore(n=>n.isShowingVisual),a=s.useEditorStore(n=>n.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(s.SmallSwitch,{checked:t,onCheckedChange:()=>a(!t),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function ye({defaultValue:t,label:a,options:n,value:r,onValueChange:l,className:i,icon:c,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",i),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),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 pn(){var g,v;const t=s.useEditorStore(D=>D.card.customCardPreferences),{data:a}=Js(),n=(a==null?void 0:a.plugins)||[],r=s.useEditorStore(D=>D.card),l=s.useEditorStore(D=>D.frame),i=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:c}=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}};c({...t,dataInputCardIds:L})}function x(D){var B,L;const k=(B=l==null?void 0:l.cards)==null?void 0:B.filter(E=>{var C;return((C=E==null?void 0:E.customCardPreferences)==null?void 0:C.visualType)!=="multiple"}).map(E=>({value:E.id,label:E.tabTitle||E.title}));return e.jsx("div",{className:"space-y-2",children:(L=D==null?void 0:D.dataInputs)==null?void 0:L.map((E,C)=>{var f,b;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:E}),e.jsx(ye,{className:"col-span-6 h-8 w-full justify-between",label:"",options:k||[],value:((b=(f=t==null?void 0:t.dataInputCardIds)==null?void 0:f[C])==null?void 0:b.cardId)||"",onValueChange:N=>m(C,N)})]},C+Math.random())})})}function h(D,k,B=[],L=""){var E,C;return t?D==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((E=t==null?void 0:t.settings)==null?void 0:E[k])||L,onChange:f=>{c({...t,settings:{...t==null?void 0:t.settings,[k]:f.target.value}})}},k):D==="select"?e.jsx(ye,{className:"h-8 w-full",label:"",options:B,value:((C=t==null?void 0:t.settings)==null?void 0:C[k])||L,onValueChange:f=>{c({...t,settings:{...t==null?void 0:t.settings,[k]:f}})}}):null:null}function p(D){const k=Object.entries((D==null?void 0:D.settings)||{});return e.jsx("div",{className:"space-y-3",children:k.map(([B,L])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:L.title}),h(L.ui,B,L.options,L.defaultValue)]},B))})}function j(D){t&&c({...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(bt,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(t==null?void 0:t.url)||"",onValueChange:D=>c({...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:i,onValueChange:j,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(St,{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===i).map(D=>({value:D.name,label:D.name})))||[],value:t.componentName,onValueChange:D=>{console.log("changing value",D),c({...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:x(u)})]}),u&&u.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:p(u)})})]})]})]})}function ke(){const[t,a]=S.useState([]),n=s.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:l}=s.useEditorStore(u=>u.actions),i=s.useEditorStore(u=>u.queryResultColumns);s.useEditorStore(u=>{var m;return(m=u.card.preferences)==null?void 0:m.filterOnClickColumnIndex}),S.useEffect(()=>{i&&a(new Array(i.length).fill(!1))},[i]);function c(u,m){var x,h;m?n!=null&&n.onClickFilter&&((x=n==null?void 0:n.onClickFilter)==null?void 0:x.length)>0?l({...n,onClickFilter:[...n.onClickFilter,{columnIndex:u,expression:""}]}):l({...n,onClickFilter:[{columnIndex:u,expression:""}]}):(l({...n,onClickFilter:(h=n==null?void 0:n.onClickFilter)==null?void 0:h.filter(p=>p.columnIndex!==u)}),a(p=>{const j=[...p];return j[u]=!1,j}))}function o(u,m){var h;const x=(h=n==null?void 0:n.onClickFilter)==null?void 0:h.map(p=>p.columnIndex===u?{...p,expression:m.target.value}:p);l({...n,onClickFilter:x})}function d(u){var m,x,h,p;if(t!=null&&t[u]||(x=(m=n==null?void 0:n.onClickFilter)==null?void 0:m.find(j=>j.columnIndex===u))!=null&&x.expression)return e.jsx(s.Input,{value:(p=(h=n==null?void 0:n.onClickFilter)==null?void 0:h.find(j=>j.columnIndex===u))==null?void 0:p.expression,onChange:j=>o(u,j),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:i==null?void 0:i.map((u,m)=>{var x,h;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((x=n==null?void 0:n.onClickFilter)!=null&&x.find(p=>p.columnIndex===m)),onCheckedChange:p=>c(m,p)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:u}),e.jsx("div",{className:"flex items-center gap-2",children:((h=n==null?void 0:n.onClickFilter)==null?void 0:h.find(p=>p.columnIndex===m))&&e.jsx(s.Pencil,{onClick:()=>{a(p=>{const j=[...p];return j[m]=!p[m],j})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(m)]})},u)})})}function fn({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,i=n==null?void 0:n.find(d=>d.idx===t);function c(d,u){(d==="end"||d==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const m={display:d!=="none",align:d,anchor:d,clamp:!0};if(!i)r({...a,datasetOptions:[...n||[],{idx:u,datalabels:m}]});else{const x={...i};x.datalabels=m;const h=n==null?void 0:n.map(p=>p.idx===u?x:p);r({...a,datasetOptions:h})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(Ms,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(s.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>c("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>c("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Bt,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>c("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Vt,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>c("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Rt,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function gn(){const t=s.useEditorStore(i=>i.card),{data:a}=s.useDashboardCardQuery(t),{keys:n}=s.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(i=>!s.METADATA_KEYS.includes(i));let l=r;if(["stackedBar","stackedLine"].includes(t.type)){const i=s.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:c}=s.getKeys(i);l=c.slice(1)}return{transformedMetricKeys:l,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}function ns({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 Xs(){const t=s.useEditorStore(d=>d.card),a=s.useEditorStore(d=>{var u,m,x;return(x=(m=(u=d==null?void 0:d.card)==null?void 0:u.preferences)==null?void 0:m.chartOptions)==null?void 0:x.indexAxis}),{data:n}=s.useDashboardCardQuery(t),r=a==="y"?"Metric":"Dimension",l=a==="y"?"Dimension":"Metric",{dimensionKeys:i,transformedMetricKeys:c,keys:o}=gn();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:i.map(d=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:d,children:Zs(d)},d))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:l}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:c.map((d,u)=>e.jsx(et,{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 Zs(t,a=30){return t.length>a?t.slice(0,a)+"...":t}function et({col:t,idx:a,className:n,iconClassName:r,children:l}){const i=s.useEditorStore(m=>{var x;return(x=m.card)==null?void 0:x.preferences}),c=s.useEditorStore(m=>{var x,h;return(h=(x=m.card)==null?void 0:x.preferences)==null?void 0:h.datasetOptions}),o=c==null?void 0:c.find(m=>m.idx===a),{setCardPreferences:d}=s.useEditorStore(m=>m.actions);function u(m){if(!o)d({...i,datasetOptions:[...c||[],{idx:a,type:m==="area"?"line":m,fill:m==="area"?"origin":""}]});else{const x={...o};x.type=m==="area"?"line":m,x.fill=m==="area"?"origin":"";const h=c==null?void 0:c.map(p=>p.idx===a?x:p);d({...i,datasetOptions:h})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[l||e.jsx(ns,{className:"max-w-[100px]",title:t,children:Zs(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.ChartColumnIncreasing,{onClick:()=>u("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartLine,{onClick:()=>u("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartArea,{onClick:()=>u("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(fn,{idx:a})]})]})}function Me(){const t=s.useDashboardStore(o=>o.dashboard.filters),a=s.useEditorStore(o=>o.frame),{setFrame:n}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=Gs();function i(o){const d=l(o,"frame");n({...a,filterId:d})}const c=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(jn,{onSelect:i,columns:r}),c&&e.jsx(s.FilterHeader,{filter:c})]})}function jn({columns:t,onSelect:a}){var c;const[n,r]=He.useState(!1),[l,i]=He.useState("");return e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[l?(c=t.find(o=>o.column_name===l))==null?void 0:c.column_name:"Select Column...",e.jsx(s.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No framework found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(o=>e.jsxs(s.CommandItem,{value:o.column_name,onSelect:d=>{const u=d===l?"":d;i(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 bn({cardType:t}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, y-axis-1, y-axis-2,... FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"y-axis1 - number"}),e.jsx("li",{children:"y-axis2 - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:a=>a.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(Xs,{})})]}),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(ke,{}),e.jsx(Me,{})]})]})]})})}function vn({cardType:t}){function a(n){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:n==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),n==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:i=>i.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(ke,{}),e.jsx(Me,{})]})]})]})})}function st(){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 i(){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 c(){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?i():c()})}const yn={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},Nn={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function Cn(){const t=s.useEditorStore(a=>a.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:Sn(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(st,{}),e.jsx(ke,{}),e.jsx(Me,{})]})]})}function Sn(t){if(["line","bar"].includes(t))return e.jsxs(e.Fragment,{children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsx("p",{children:"Chart Query"})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT x-axis, y-axis-1, y-axis-2, y-axis-3,... FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"X-axis - Category (ex. city)"}),e.jsx("li",{children:"Y-axis - Number (ex. population)"})]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Mixed Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and change the `type` property in the dataset."]}),e.jsx("pre",{children:JSON.stringify(yn,null,2)})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Area Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and add `fill` property to the dataset. See",e.jsx("a",{className:"mx-1 text-blue-500 hover:underline",href:"https://www.chartjs.org/docs/latest/samples/area/line-boundaries.html",target:"_blank",children:"docs"}),"for more options."]}),e.jsx("pre",{children:JSON.stringify(Nn,null,2)})]})]})]});if(t==="bubble")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis, radius FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Bubble Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"}),e.jsx("li",{children:"Radius - Number (ex. population)"})]})]})]})});if(t==="scatter")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"})]})]})]})});if(["pie","doughnut","polarArea","funnel"].includes(t))return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:[e.jsx("span",{children:t==="polarArea"?"Polar":t.charAt(0).toUpperCase()+t.slice(1)})," ","chart query"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Measure - Number (ex. population)"})]})]})]})})}function wn({colorRanges:t,setColorRanges:a}){const n={start:-1/0,end:100,color:""};function r(c,o,d){const u=[...t];u[c]={...u[c],[o]:d},a(u)}function l(c){const o=[...t];o.splice(c,1),a(o)}function i(){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:i,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((c,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:c.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input,{value:c.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:c.color,className:s.cn(`h-7 min-w-14 p-0 ${s.removeRing}`),type:"color",list:"presetColors"}),e.jsxs("datalist",{id:"presetColors",children:[e.jsx("option",{children:s.colors.green[600]}),e.jsx("option",{children:s.colors.red[500]}),e.jsx("option",{children:s.colors.yellow[400]}),e.jsx("option",{children:s.colors.orange[500]})]}),e.jsx(s.Button,{onClick:()=>l(o),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},o))]})}function Dn(){var m,x,h,p,j;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 i=s.useEditorStore(g=>{var v,D;return(D=(v=g.card.preferences)==null?void 0:v.formatNumber)==null?void 0:D.locale}),c=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"})]}),(((x=t==null?void 0:t.formatNumber)==null?void 0:x.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:i||"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:c||"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:((p=(h=t==null?void 0:t.formatNumber)==null?void 0:h.decimalPlaces)==null?void 0:p.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:((j=t==null?void 0:t.formatNumber)==null?void 0:j.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(wn,{colorRanges:o,setColorRanges:d})]})]})}function Tn(){return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{type:"single",collapsible:!0,children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"",children:"KPI Query"}),e.jsxs(s.AccordionContent,{className:"font-mono",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs",children:"SELECT current, previous FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"current - number"}),e.jsx("li",{children:"previous - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/kpi",children:"example"})," in the docs."]})]})]})}),e.jsx("section",{className:"",children:e.jsx(Dn,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function _e({children:t,summary:a,open:n,className:r}){return e.jsxs("details",{open:n,className:s.cn("space-y-4 [&_summary>svg]:open:-rotate-180",r),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(s.Label,{children:a}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const kn=[{label:"Mercator",value:"mercator"},{label:"Azimuthal Equidistant",value:"azimuthalEquidistant"},{label:"Gnomonic",value:"gnomonic"},{label:"Orthographic",value:"orthographic"},{label:"Stereographic",value:"stereographic"},{label:"Equal Earth",value:"equalEarth"},{label:"Albers",value:"albers"},{label:"Albers USA",value:"albersUsa"},{label:"Conic Conformal",value:"conicConformal"},{label:"Conic Equal Area",value:"conicEqualArea"},{label:"Conic Equidistant",value:"conicEquidistant"},{label:"Equirectangular",value:"equirectangular"},{label:"Transverse Mercator",value:"transverseMercator"},{label:"Natural Earth 1",value:"naturalEarth1"}],En=["blues","brBG","buGn","buPu","cividis","cool","cubehelixDefault","gnBu","greens","greys","inferno","magma","orRd","oranges","pRGn","piYG","plasma","puBu","puBuGn","puOr","puRd","purples","rainbow","rdBu","rdGy","rdPu","rdYlBu","rdYlGn","reds","sinebow","spectral","turbo","viridis","warm","ylGn","ylGnBu","ylOrBr","ylOrRd"],In=En.map(t=>({label:t,value:t}));function An(){var d,u,m,x,h,p,j,g,v,D,k,B,L,E,C,f,b,N;const t=s.useEditorStore(A=>A.card),a=(u=(d=t==null?void 0:t.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:u.topoJsonUrl,[n,r]=S.useState(((x=(m=t==null?void 0:t.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:x.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:i}=s.useTopoJson(t),c=Object.keys((i==null?void 0:i.objects)||{}).map(A=>({label:A,value:A}))||[],o=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"p-6",children:[e.jsx(_e,{summary:"Map Chart",children:e.jsx("p",{className:"rounded-md bg-muted p-2 font-mono text-xs",children:"SELECT country, value FROM table"})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(_e,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(ye,{className:"h-9",options:o,onValueChange:A=>{console.log("value",A),l({...t.preferences,mapVisualOptions:{topoJsonUrl:A}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(s.Input,{onChange:A=>{r(A.target.value)},onBlur:()=>{var A;console.log("onBlur",n),l({...t.preferences,mapVisualOptions:{...(A=t.preferences)==null?void 0:A.mapVisualOptions,customTopoJsonUrl:n}})},value:n,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),i&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(ye,{className:"h-9",options:c,value:((p=(h=t.preferences)==null?void 0:h.mapVisualOptions)==null?void 0:p.objectKey)||"",label:"Map Object",onValueChange:A=>{var w;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,objectKey:A}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(ye,{className:"h-9",options:kn,value:((g=(j=t.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:g.projection)||"",label:"Projection",onValueChange:A=>{var w;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,projection:A}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(ye,{className:"h-9",options:In,value:((D=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:D.colorScale)||"",label:"Select Color Scale",onValueChange:A=>{var w;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,colorScale:A}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(_e,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:.1,value:((B=(k=t.preferences)==null?void 0:k.mapVisualOptions)==null?void 0:B.projectionScale)||1,onChange:A=>{var w;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,projectionScale:Number(A.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((C=(E=(L=t.preferences)==null?void 0:L.mapVisualOptions)==null?void 0:E.projectionOffset)==null?void 0:C[0])||0,onChange:A=>{var w,P,I,T;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,projectionOffset:[Number(A.target.value),((T=(I=(P=t.preferences)==null?void 0:P.mapVisualOptions)==null?void 0:I.projectionOffset)==null?void 0:T[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((N=(b=(f=t.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:b.projectionOffset)==null?void 0:N[1])||0,onChange:A=>{var w,P,I,T;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,projectionOffset:[((T=(I=(P=t.preferences)==null?void 0:P.mapVisualOptions)==null?void 0:I.projectionOffset)==null?void 0:T[0])||0,Number(A.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(ke,{})]})}function Mn(){var r;const t=s.useEditorStore(l=>l.card.preferences),{setCardPreferences:a}=s.useEditorStore(l=>l.actions);function n(l){a({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:l==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:n,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function 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(Mn,{})})]}),!["range","text"].includes(t)&&e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(ke,{}),e.jsx(Me,{})]})]})]})})}function Ln(){const t=s.useEditorStore(r=>{var l,i;return(i=(l=r==null?void 0:r.card)==null?void 0:l.preferences)==null?void 0:i.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(Xs,{})]})]}),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(ke,{}),e.jsx(Me,{})]})]})]})})}function Fn({cardType:t="table"}){console.log("cardType",t);const a=s.useEditorStore(l=>{var i;return(i=l.card)==null?void 0:i.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(ke,{}),e.jsx(Me,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{onCheckedChange:r,id:"allow-download"}),e.jsx("label",{htmlFor:"allow-download",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Allow Download"})]})]})}function tt({color:t,onColorChange:a,onClose:n}){const[r,l]=S.useState(0),[i,c]=S.useState(100),[o,d]=S.useState(50),[u,m]=S.useState(t);S.useEffect(()=>{const v=gs(t);if(v){const D=js(v.r,v.g,v.b);l(D.h),c(D.s),d(D.l),m(t)}},[t]);const x=v=>{l(v),p(v,i,o)},h=v=>{const D=v.currentTarget.getBoundingClientRect(),k=Math.max(0,Math.min(1,(v.clientX-D.left)/D.width)),B=Math.max(0,Math.min(1,(v.clientY-D.top)/D.height)),L=k*100,E=(1-B)*100;c(L),d(E),p(r,L,E)},p=(v,D,k)=>{const B=On(v,D,k),L=Pn(B.r,B.g,B.b);m(L)},j=v=>{if(m(v),/^#[0-9A-Fa-f]{6}$/.test(v)){const D=gs(v);if(D){const k=js(D.r,D.g,D.b);l(k.h),c(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:h,onMouseMove:v=>{v.buttons===1&&h(v)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${i}%`,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=>x(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=>j(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 gs(t){const a=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return a?{r:parseInt(a[1],16),g:parseInt(a[2],16),b:parseInt(a[3],16)}:null}function Pn(t,a,n){return"#"+((1<<24)+(t<<16)+(a<<8)+n).toString(16).slice(1)}function js(t,a,n){t/=255,a/=255,n/=255;const r=Math.max(t,a,n),l=Math.min(t,a,n);let i=0,c=0;const o=(r+l)/2;if(r!==l){const d=r-l;switch(c=o>.5?d/(2-r-l):d/(r+l),r){case t:i=((a-n)/d+(a<n?6:0))/6;break;case a:i=((n-t)/d+2)/6;break;case n:i=((t-a)/d+4)/6;break}}return{h:Math.round(i*360),s:Math.round(c*100),l:Math.round(o*100)}}function On(t,a,n){t/=360,a/=100,n/=100;let r,l,i;if(a===0)r=l=i=n;else{const c=(u,m,x)=>(x<0&&(x+=1),x>1&&(x-=1),x<.16666666666666666?u+(m-u)*6*x:x<.5?m:x<.6666666666666666?u+(m-u)*(.6666666666666666-x)*6:u),o=n<.5?n*(1+a):n+a-n*a,d=2*n-o;r=c(d,o,t+1/3),l=c(d,o,t),i=c(d,o,t-1/3)}return{r:Math.round(r*255),g:Math.round(l*255),b:Math.round(i*255)}}const Bn=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function at(){var B,L,E,C,f,b,N,A,w,P;const t=s.useEditorStore(I=>I.card),a=s.useEditorStore(I=>{var T;return(T=I.card)==null?void 0:T.preferences}),{setCardPreferences:n,updateCardInFrame:r}=s.useEditorActions(),{data:l}=s.useDashboardCardQuery(t),[i,c]=S.useState({}),[o,d]=S.useState(null),[u,m]=S.useState(null),x=S.useMemo(()=>{var M,F,z,$,O,G,R;if(!(l!=null&&l.records)||l.records.length===0)return[];const I=(t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine",T=(t==null?void 0:t.type)==="bar"||(t==null?void 0:t.type)==="line"||(t==null?void 0:t.type)==="horizontalBar"||(t==null?void 0:t.type)==="bullet",y=((M=t==null?void 0:t.config)==null?void 0:M.pivotByColumns)&&t.config.pivotByColumns.length>0;if((I||T)&&y){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const _=new Set;return l.pivotSchema.forEach(J=>{J.alias&&_.add(J.alias)}),Array.from(_)}if(l.records.length>0){const _=l.records[0],J=Object.keys(_),se=new Set;(F=t==null?void 0:t.config)!=null&&F.groupByColumns&&t.config.groupByColumns.forEach(Y=>{se.add(Y.label||Y.name),se.add(Y.alias||Y.name)});const Z=new Set;return(z=t==null?void 0:t.config)!=null&&z.metricColumns&&t.config.metricColumns.forEach(Y=>{const U=Y.alias||Y.name;Z.add(U),Z.add(`${U}_count`),Z.add(`${U}_sum`),Z.add(`${U}_avg`),Z.add(`${U}_min`),Z.add(`${U}_max`);const te=Y.entityName||Y.qualifiedEntityName;te&&(Z.add(`${te}_${U}`),Z.add(`${te}_${U}_count`))}),J.filter(Y=>!se.has(Y)&&!Z.has(Y))}}if((T||I)&&!y&&((O=($=t==null?void 0:t.config)==null?void 0:$.metricColumns)!=null&&O.length))return t.config.metricColumns.map(_=>_.alias||_.label||_.name);if((R=(G=t==null?void 0:t.config)==null?void 0:G.groupByColumns)!=null&&R.length){const _=t.config.groupByColumns[0],J=_.label||_.name,se=new Set;return l.records.forEach(Z=>{const ae=Z[J];ae!=null&&se.add(String(ae))}),Array.from(se)}return[]},[l,(B=t==null?void 0:t.config)==null?void 0:B.groupByColumns,(L=t==null?void 0:t.config)==null?void 0:L.pivotByColumns,(E=t==null?void 0:t.config)==null?void 0:E.metricColumns,t==null?void 0:t.type]),h=S.useMemo(()=>s.getDefaultChartColors(),[]);S.useEffect(()=>{const I={};x.forEach((T,y)=>{I[T]=s.getColorForValue(T,y,a==null?void 0:a.colorConfig)}),c(I)},[x,a==null?void 0:a.colorConfig,h]);const p=(I,T)=>{const y={...i,[I]:T};c(y);const M={...a||{},colorConfig:{segments:y}};n(M);const F={...t,preferences:M};r(F)},j=(I,T)=>{var O;const y=h[T%h.length],{[I]:M,...F}=((O=a==null?void 0:a.colorConfig)==null?void 0:O.segments)||{},z={...a||{},colorConfig:{segments:F}};n(z);const $={...t,preferences:z};r($),c(G=>({...G,[I]:y}))};if(!x.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((f=(C=t==null?void 0:t.config)==null?void 0:C.groupByColumns)==null?void 0:f.length)||((N=(b=t==null?void 0:t.config)==null?void 0:b.pivotByColumns)==null?void 0:N.length):(w=(A=t==null?void 0:t.config)==null?void 0:A.groupByColumns)==null?void 0:w.length)||["table","kpi","text","custom","heatmap"].includes(t.type))return null;const D=()=>{const I={...a||{},colorConfig:{segments:{}}};n(I);const T={...t,preferences:I};r(T);const y={};x.forEach((M,F)=>{y[M]=s.getColorForValue(M,F,void 0)}),c(y)},k=Object.keys(((P=a==null?void 0:a.colorConfig)==null?void 0:P.segments)||{}).length>0;return e.jsxs(s.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($t,{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(hs,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:x.map((I,T)=>{const y=s.isDefaultColor(i[I],T),M=!y;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:o===I,onOpenChange:F=>d(F?I:null),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"h-5 w-5 shrink-0 rounded border border-input shadow-sm transition-colors hover:border-gray-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",style:{backgroundColor:i[I]}})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-3",children:e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Theme Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:h.slice(0,10).map((F,z)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",i[I]===F?"border-gray-900":"border-transparent"),style:{backgroundColor:F},onClick:()=>{p(I,F),d(null)},children:[z===T%h.length&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-white/90 px-0.5 text-[8px] font-bold text-gray-900 shadow-sm",children:"D"})}),e.jsx("span",{className:"sr-only",children:F})]},`default-${z}`))})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Popular Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:Bn.map((F,z)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",i[I]===F?"border-2 border-gray-900":F==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:F},onClick:()=>{p(I,F),d(null)},children:e.jsx("span",{className:"sr-only",children:F})},`preset-${z}`))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsx("button",{className:"text-sm font-medium text-blue-600 hover:text-blue-700",onClick:()=>{m({value:I,color:i[I]}),d(null)},children:"Custom color"}),!y&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{j(I,T),d(null)},children:[e.jsx(hs,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:I}),M&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},I)})}),u&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>m(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(tt,{color:u.color,onColorChange:I=>{p(u.value,I),m(null)},onClose:()=>m(null)})})]})]})})]})}function Ne({value:t,onSave:a,placeholder:n="",type:r="text",className:l=""}){const[i,c]=S.useState(t??""),[o,d]=S.useState(!1);S.useEffect(()=>{c(t??"")},[t]);const u=()=>{a(i),d(!1)},m=()=>{c(t??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${l}`,children:[e.jsx(s.Input$1,{placeholder:n,type:r,value:o?i:t??"",onChange:x=>{c(x.target.value),d(!0)},onFocus:()=>d(!0),onClick:x=>x.stopPropagation(),className:"h-8 text-xs",onPointerDown:x=>x.stopPropagation(),onKeyDown:x=>{x.stopPropagation(),x.key==="Enter"&&o&&i!==t?u():x.key==="Escape"&&m()},"aria-label":n||"Edit field"}),o&&i!==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 Rn=["auto","number","currency","percent","scientific","date"],Vn=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"GBP",label:"GBP - British Pound"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"CHF",label:"CHF - Swiss Franc"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"},{value:"HKD",label:"HKD - Hong Kong Dollar"},{value:"SGD",label:"SGD - Singapore Dollar"},{value:"NZD",label:"NZD - New Zealand Dollar"},{value:"SEK",label:"SEK - Swedish Krona"},{value:"NOK",label:"NOK - Norwegian Krone"},{value:"DKK",label:"DKK - Danish Krone"},{value:"KRW",label:"KRW - South Korean Won"},{value:"INR",label:"INR - Indian Rupee"},{value:"RUB",label:"RUB - Russian Ruble"},{value:"BRL",label:"BRL - Brazilian Real"},{value:"MXN",label:"MXN - Mexican Peso"},{value:"TRY",label:"TRY - Turkish Lira"},{value:"ZAR",label:"ZAR - South African Rand"},{value:"SAR",label:"SAR - Saudi Riyal"},{value:"AED",label:"AED - UAE Dirham"},{value:"ARS",label:"ARS - Argentine Peso"},{value:"CLP",label:"CLP - Chilean Peso"},{value:"COP",label:"COP - Colombian Peso"},{value:"THB",label:"THB - Thai Baht"},{value:"IDR",label:"IDR - Indonesian Rupiah"},{value:"MYR",label:"MYR - Malaysian Ringgit"},{value:"PHP",label:"PHP - Philippine Peso"},{value:"PLN",label:"PLN - Polish Zloty"},{value:"NGN",label:"NGN - Nigerian Naira"},{value:"KES",label:"KES - Kenyan Shilling"},{value:"GHS",label:"GHS - Ghanaian Cedi"},{value:"ZMW",label:"ZMW - Zambian Kwacha"},{value:"ZWL",label:"ZWL - Zimbabwean Dollar"},{value:"EGP",label:"EGP - Egyptian Pound"},{value:"MAD",label:"MAD - Moroccan Dirham"},{value:"UAH",label:"UAH - Ukrainian Hryvnia"},{value:"HUF",label:"HUF - Hungarian Forint"},{value:"CZK",label:"CZK - Czech Koruna"},{value:"RON",label:"RON - Romanian Leu"},{value:"PKR",label:"PKR - Pakistani Rupee"},{value:"BDT",label:"BDT - Bangladeshi Taka"},{value:"VND",label:"VND - Vietnamese Dong"},{value:"TWD",label:"TWD - New Taiwan Dollar"},{value:"ILS",label:"ILS - Israeli New Shekel"}],zn=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"en-IN",label:"English (India)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"},{value:"ja-JP",label:"Japanese"},{value:"ko-KR",label:"Korean"},{value:"ru-RU",label:"Russian"},{value:"ar-SA",label:"Arabic"},{value:"hi-IN",label:"Hindi"},{value:"nl-NL",label:"Dutch"},{value:"sv-SE",label:"Swedish"}],Gn=t=>t.charAt(0).toUpperCase()+t.slice(1);function rs({formatOptions:t={},onFormatOptionsChange:a,showTitle:n=!0,title:r="NUMBER FORMAT"}){const l=t.type||"auto",i=(o,d)=>{a({...t,[o]:d})},c=()=>l==="currency"?2:l==="percent"?1:0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[n&&e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(s.Select,{value:l,onValueChange:o=>i("type",o),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Rn.map(o=>e.jsx(s.SelectItem,{value:o,className:"text-xs",children:o==="auto"?"Auto (Default)":Gn(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??c(),onChange:o=>i("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=>i("currency",o),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Vn.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=>i("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=>i("locale",o),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:zn.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=>i("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=>i("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=>i("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=>i("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=>i("dateFormat",o.target.value),className:"h-8 text-xs"})})]})]})]})}function bs({axis:t,label:a,type:n,config:r,onChange:l}){var x,h,p,j,g,v,D,k,B,L,E,C;const i=(f,b)=>{l({...r,[f]:b})},c=(f,b)=>{var N,A;l({...r,name:{enabled:f==="enabled"?b:((N=r==null?void 0:r.name)==null?void 0:N.enabled)??!1,text:f==="text"?b:(A=r==null?void 0:r.name)==null?void 0:A.text}})},o=(f,b)=>{var N,A;l({...r,labels:{enabled:f==="enabled"?b:((N=r==null?void 0:r.labels)==null?void 0:N.enabled)??!0,rotation:f==="rotation"?b:(A=r==null?void 0:r.labels)==null?void 0:A.rotation}})},d=(f,b)=>{l({...r,scale:{...r==null?void 0:r.scale,[f]:b===""?"auto":Number(b)}})},u=t==="x"?["auto","top","bottom"]:["auto","left","right"],m=["auto","0","45","90","-45","-90"];return e.jsxs(s.AccordionItem,{value:`${t}-axis`,className:"border-b-0",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx(s.AccordionTrigger,{className:"flex grow items-center justify-between gap-3 py-2 text-sm font-medium hover:no-underline",children:e.jsx("div",{className:"flex grow items-center justify-between gap-2",children:e.jsx("span",{children:a})})}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:f=>i("enabled",f),onClick:f=>f.stopPropagation()})]}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TITLE"}),e.jsx(s.SmallSwitch,{checked:((x=r==null?void 0:r.name)==null?void 0:x.enabled)??!1,onCheckedChange:f=>c("enabled",f)})]}),((h=r==null?void 0:r.name)==null?void 0:h.enabled)&&e.jsx(Ne,{placeholder:`${a} title`,value:((p=r==null?void 0:r.name)==null?void 0:p.text)||"",onSave:f=>c("text",f),className:""})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(s.Select,{value:(r==null?void 0:r.position)||"auto",onValueChange:f=>i("position",f),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(f=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:f==="auto"?"Auto (Default)":s.titleCase(f)},f))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(s.SmallSwitch,{checked:((j=r==null?void 0:r.labels)==null?void 0:j.enabled)!==!1,onCheckedChange:f=>o("enabled",f)})]}),((g=r==null?void 0:r.labels)==null?void 0:g.enabled)!==!1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Rotation"}),e.jsxs(s.Select,{value:String(((v=r==null?void 0:r.labels)==null?void 0:v.rotation)||"auto"),onValueChange:f=>o("rotation",f==="auto"?"auto":Number(f)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:m.map(f=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:f==="auto"?"Auto (Default)":`${f}°`},f))})]})]})]}),n==="value"&&e.jsx(rs,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:f=>l({...r,formatOptions:f}),showTitle:!0,title:"FORMAT"}),n==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"SCALE"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ne,{type:"number",placeholder:"auto",value:((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:f=>d("min",f),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Max"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ne,{type:"number",placeholder:"auto",value:((B=r==null?void 0:r.scale)==null?void 0:B.max)==="auto"||((L=r==null?void 0:r.scale)==null?void 0:L.max)===void 0?"":String(r.scale.max),onSave:f=>d("max",f),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Step"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ne,{type:"number",placeholder:"auto",value:((E=r==null?void 0:r.scale)==null?void 0:E.stepSize)==="auto"||((C=r==null?void 0:r.scale)==null?void 0:C.stepSize)===void 0?"":String(r.scale.stepSize),onSave:f=>d("stepSize",f),className:""})})]})]})]})]})]})}function nt(){const t=s.useEditorStore(c=>c.card),a=s.useEditorStore(c=>{var o;return(o=c.card)==null?void 0:o.preferences}),{setCardPreferences:n,updateCardInFrame:r}=s.useEditorActions();if(!t||["tornado","pyramid","kpi","treemap"].includes(t.type))return null;const l=s.AxisConfigurator.getAxisInfo(t.type,a);if(!l.hasXAxis&&!l.hasYAxis)return null;const i=(c,o)=>{const u={...a||{},[c==="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(As,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Axes"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[l.hasXAxis&&e.jsx(bs,{axis:"x",label:"X-Axis",type:l.xAxisType,config:s.mergeAxisConfig(s.getDefaultAxisConfig(t.type,"x"),a==null?void 0:a.xAxisConfig),onChange:c=>i("x",c)}),l.hasYAxis&&e.jsx(bs,{axis:"y",label:"Y-Axis",type:l.yAxisType,config:s.mergeAxisConfig(s.getDefaultAxisConfig(t.type,"y"),a==null?void 0:a.yAxisConfig),onChange:c=>i("y",c)})]})})]})}function rt(){const t=s.useEditorStore(m=>m.card),a=s.useEditorStore(m=>{var x,h,p,j;return(j=(p=(h=(x=m.card)==null?void 0:x.preferences)==null?void 0:h.chartOptions)==null?void 0:p.plugins)==null?void 0:j.legend}),{setLegendOptions:n}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r=s.getDefaultLegendConfig(t.type),l=(r==null?void 0:r.display)??!0,i=(r==null?void 0:r.position)??"top",c=(r==null?void 0:r.align)??"center",o=(m,x)=>{const h={...a,[m]:x};n(h)},d=["top","bottom","left","right"],u=["start","center","end"];return e.jsxs(s.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ft,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:(a==null?void 0:a.display)??l,onCheckedChange:m=>o("display",m)})]}),((a==null?void 0:a.display)??l)&&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)||i,onValueChange:m=>o("position",m),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:d.map(m=>e.jsx(s.SelectItem,{value:m,className:"text-xs",children:s.titleCase(m)},m))})]})]}),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)||c,onValueChange:m=>o("align",m),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(m=>e.jsx(s.SelectItem,{value:m,className:"text-xs",children:s.titleCase(m)},m))})]})]})]})]})})]})}function lt(){var w,P,I,T,y,M,F,z,$;const t=s.useEditorStore(O=>O.card),a=s.useEditorStore(O=>{var G,R;return(R=(G=O.card)==null?void 0:G.preferences)==null?void 0:R.dataLabelsConfig}),n=s.useEditorStore(O=>{var G;return(G=O.card)==null?void 0:G.preferences}),{setCardPreferences:r,updateCardInFrame:l}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(t.type))return null;const i=((w=n==null?void 0:n.chartOptions)==null?void 0:w.indexAxis)==="y",c=t.type==="stackedBar"||t.type==="stackedLine",o=t.type==="pie"||t.type==="doughnut"||t.type==="polarArea"||t.type==="funnel",d=!o,u=(I=(P=n==null?void 0:n.chartOptions)==null?void 0:P.plugins)==null?void 0:I.datalabels,m=(u==null?void 0:u.display)!==!1&&((u==null?void 0:u.anchor)||(u==null?void 0:u.align)),x=t.type==="treemap"?!0:m,h=(a==null?void 0:a.enabled)!==void 0?a.enabled:x,p=(O,G)=>{const R={...a,[O]:G},_={...t.preferences||{},dataLabelsConfig:R};r(_);const J={...t,preferences:_};l(J)},j=(O,G)=>{const R={...a,font:{...a==null?void 0:a.font,[O]:G}},_={...t.preferences||{},dataLabelsConfig:R};r(_);const J={...t,preferences:_};l(J)},g=(O,G)=>{const R={...a,formatOptions:{...a==null?void 0:a.formatOptions,[O]:G}},_={...t.preferences||{},dataLabelsConfig:R};r(_);const J={...t,preferences:_};l(J)},v=()=>{const O=t.type;return O==="stackedBar"||O==="stackedLine"||O==="pie"||O==="doughnut"?"center":i?"right":"top"},D=t.type!=="treemap"&&t.type!=="heatmap",k=t.type!=="treemap",B=v();let L=[];D&&(c||o?L=["center"]:L=["auto",...(i?["center","left","right"]:["center","top","bottom"]).filter(G=>G!==B),"custom"]);const E=()=>s.titleCase(B),C=["center","start","end"],f=["center","start","end","top","bottom"],b=d?["auto","number","currency","percent","none"]:["number","currency","percent","none"],N=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"GBP",label:"GBP - British Pound"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"INR",label:"INR - Indian Rupee"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"}],A=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"}];return e.jsxs(s.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:h,onCheckedChange:O=>p("enabled",O)})]}),h&&e.jsxs(e.Fragment,{children:[D&&!c&&!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:O=>p("position",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:L.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:O==="auto"?E():O==="custom"?"Custom (Advanced)":s.titleCase(O)},O))})]})]}),c&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Show Total"}),e.jsx(s.SmallSwitch,{checked:(a==null?void 0:a.showTotal)??!1,onCheckedChange:O=>p("showTotal",O)})]}),(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:O=>p("anchor",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:C.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:s.titleCase(O)},O))})]})]}),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:O=>p("align",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:f.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:s.titleCase(O)},O))})]})]})]}),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:O=>p("format",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:b.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:O==="auto"&&d?"Auto (Use Axis)":O==="none"?"None (Raw Value)":s.titleCase(O)},O))})]})]}),(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(((T=a==null?void 0:a.formatOptions)==null?void 0:T.decimalPlaces)??(a.format==="currency"?2:a.format==="percent"?1:0)),onSave:O=>g("decimalPlaces",Number(O)),className:""})})]}),a.format==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Currency"}),e.jsxs(s.Select,{value:((y=a==null?void 0:a.formatOptions)==null?void 0:y.currency)||"USD",onValueChange:O=>g("currency",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:N.map(O=>e.jsx(s.SelectItem,{value:O.value,className:"text-xs",children:O.label},O.value))})]})]}),["number","currency"].includes(a.format)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((M=a==null?void 0:a.formatOptions)==null?void 0:M.useSuffix)??!1,onCheckedChange:O=>g("useSuffix",O)})]}),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:O=>g("locale",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:A.map(O=>e.jsx(s.SelectItem,{value:O.value,className:"text-xs",children:O.label},O.value))})]})]})]}),k&&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(((z=a==null?void 0:a.font)==null?void 0:z.size)||12),onSave:O=>j("size",Number(O)),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:(($=a==null?void 0:a.font)==null?void 0:$.weight)||"normal",onValueChange:O=>j("weight",O),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:O=>{O==="auto"&&p("color","auto")},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Smart Contrast)"}),e.jsx(s.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom (Coming Soon)"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Rotation"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ne,{type:"number",placeholder:"0",value:String((a==null?void 0:a.rotation)||0),onSave:O=>p("rotation",Number(O)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}function Re({value:t,onCommit:a,type:n="text",placeholder:r,className:l}){const[i,c]=S.useState(t),o=S.useRef(!1);S.useEffect(()=>{c(t)},[t]);const d=()=>{if(o.current){o.current=!1;return}i!==t&&a(i)},u=m=>{if(m.key==="Enter"){m.currentTarget.blur();return}m.key==="Escape"&&(o.current=!0,c(t),m.currentTarget.blur())};return e.jsx(s.Input,{type:n,placeholder:r,value:i,onChange:m=>c(m.target.value),onBlur:d,onKeyDown:u,className:l})}const vs=["poor","satisfactory","good"];function ys(t){if(!t)return;const a={...t};return a.targetMetricKey||delete a.targetMetricKey,a.comparativeMetricKey||delete a.comparativeMetricKey,!a.targetValue&&a.targetValue!==0&&delete a.targetValue,(!a.rangeKeys||Object.keys(a.rangeKeys).length===0)&&delete a.rangeKeys,(!a.ranges||Object.keys(a.ranges).length===0)&&delete a.ranges,(!a.rangeLabels||Object.keys(a.rangeLabels).length===0)&&delete a.rangeLabels,a}function ot(){var I,T;const t=s.useEditorStore(y=>y.card.preferences),a=s.useEditorStore(y=>y.card),n=s.useEditorStore(y=>y.isDevMode),{setCardPreferences:r,setChartOrientation:l}=s.useEditorActions(),i=S.useMemo(()=>(t==null?void 0:t.bulletConfig)||{},[t==null?void 0:t.bulletConfig]),o=s.hasValidCardConfig(a==null?void 0:a.config)&&!n,[d,u]=S.useState(i.showRanges??!1),[m,x]=S.useState(i.rangesArePercentages??!1),h=i.disableAutoComparative?!1:i.comparativeMetricKey!==void 0||!o,[p,j]=S.useState(h);S.useEffect(()=>{u(i.showRanges??!1)},[i.showRanges]),S.useEffect(()=>{x(i.rangesArePercentages??!1)},[i.rangesArePercentages]);const g=i.targetValue===void 0?"":String(i.targetValue);S.useEffect(()=>{const y=i.disableAutoComparative?!1:i.comparativeMetricKey!==void 0||!o;j(y)},[i.disableAutoComparative,i.comparativeMetricKey,o]);const v=S.useMemo(()=>{var y,M;return((M=(y=a==null?void 0:a.config)==null?void 0:y.metricColumns)==null?void 0:M.map(F=>{const z=F.label||F.name||F.alias||"";return{value:z,label:z}}))||[]},[(I=a==null?void 0:a.config)==null?void 0:I.metricColumns]);S.useEffect(()=>{var R,_;if(!t||v.length===0)return;const y={};let M=!1;const F=(R=v[1])==null?void 0:R.value;!i.targetMetricKey&&F&&(y.targetMetricKey=F,M=!0);const z=(_=v[2])==null?void 0:_.value;!i.comparativeMetricKey&&!i.disableAutoComparative&&z&&(y.comparativeMetricKey=z,M=!0);const $=v.slice(3),O={...i.rangeKeys||{}};let G=!1;if(vs.forEach((J,se)=>{!O[J]&&$[se]&&(O[J]=$[se].value,G=!0)}),G&&(y.rangeKeys=O,M=!0,i.showRanges===void 0&&(y.showRanges=!0)),M){const J=ys({...i,...y});r({...t,bulletConfig:J})}},[v,i,t,r]);const D=y=>{const M=ys({...i,...y});r({...t,bulletConfig:M})},k=(y,M)=>{const F={...i.rangeKeys||{},[y]:M.trim()};M.trim()||delete F[y],D({rangeKeys:Object.keys(F).length>0?F:void 0})},B=(y,M)=>{const F=M===""?void 0:Number(M),z={...i.ranges||{}};F===void 0||Number.isNaN(F)?delete z[y]:z[y]=F,D({ranges:Object.keys(z).length?z:void 0})},L=y=>{if(y===""){D({targetValue:void 0});return}const M=Number(y);D({targetValue:Number.isNaN(M)?void 0:M})},E=(y,M)=>{const F=M.trim(),z={...i.rangeLabels||{}};F?z[y]=F:delete z[y],D({rangeLabels:Object.keys(z).length>0?z:void 0})},C=y=>{u(y),D({showRanges:y})},f=y=>{x(y),D({rangesArePercentages:y})},b=i.orientation||(((T=t==null?void 0:t.chartOptions)==null?void 0:T.indexAxis)==="y"?"horizontal":"vertical"),N=y=>{D({orientation:y}),l(y==="horizontal"?"y":"x")},A=[{value:"__none",label:"None"},...v.map(y=>({value:y.value,label:y.label}))],w=A,P=y=>{if(j(y),!y){D({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!o){D({disableAutoComparative:!1});return}if(i.comparativeMetricKey)D({disableAutoComparative:!1});else{const M=v.find(F=>F.value!==i.targetMetricKey);D({comparativeMetricKey:M==null?void 0:M.value,disableAutoComparative:!1})}};return e.jsxs(s.AccordionItem,{value:"bullet-config",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.BulletChartIcon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bullet Chart"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-6 border-t border-border/50 py-4",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"ORIENTATION"}),e.jsxs(s.Select,{value:b,onValueChange:y=>N(y),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"horizontal",className:"text-xs",children:"Horizontal"}),e.jsx(s.SelectItem,{value:"vertical",className:"text-xs",children:"Vertical"})]})]})]}),o&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TARGET METRIC"}),e.jsxs(s.Select,{value:i.targetMetricKey||"__none",onValueChange:y=>D({targetMetricKey:y==="__none"?void 0:y}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select metric"})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"__none",className:"text-xs",children:"None"}),v.map(y=>e.jsx(s.SelectItem,{value:y.value,className:"text-xs",children:y.label},y.value))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"COMPARATIVE METRIC"}),o?e.jsxs(s.Select,{value:i.comparativeMetricKey||"__none",onValueChange:y=>D({comparativeMetricKey:y==="__none"?void 0:y,disableAutoComparative:y==="__none"}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select metric"})}),e.jsx(s.SelectContent,{children:A.map(y=>e.jsx(s.SelectItem,{value:y.value,className:"text-xs",children:y.label},y.value))})]}):e.jsxs("div",{className:"space-y-2 rounded-md border border-border/50 p-3 text-xs",children:[e.jsxs("div",{className:"flex items-center justify-between font-medium",children:[e.jsx("span",{children:"Show comparative"}),e.jsx(s.SmallSwitch,{checked:p,onCheckedChange:y=>P(y)})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Comparative values are auto-detected from the third metric in your results."})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TARGET VALUE (FALLBACK)"}),e.jsx(Re,{type:"number",className:"h-8 text-xs",value:g,onCommit:L,placeholder:"Optional numeric fallback"})]})]}),e.jsxs("section",{className:"space-y-4 rounded-md border border-border/60 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"QUALITATIVE RANGES"}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:200,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"text-muted-foreground transition-colors hover:text-foreground",children:e.jsx(s.Info,{className:"h-3.5 w-3.5"})})}),e.jsx(s.TooltipContent,{side:"top",children:"Use columns or static values for Poor / Average / Good."})]})})]}),e.jsx("div",{className:"flex items-center gap-2 text-xs font-medium",children:e.jsx(s.SmallSwitch,{checked:d,onCheckedChange:C})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:m,disabled:!d,onChange:y=>f(y.target.checked),className:"h-3.5 w-3.5 accent-primary disabled:opacity-50"}),e.jsx("span",{children:"Use % of value"})]})]}),d&&e.jsx("div",{className:"space-y-3",children:vs.map(y=>{var M,F,z,$,O;return e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-muted/40 p-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[y," LABEL"]}),e.jsx(Re,{placeholder:`Display label (${y})`,value:((M=i.rangeLabels)==null?void 0:M[y])||"",onCommit:G=>E(y,G),className:"h-8 text-xs"})]}),o?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[y," COLUMN"]}),e.jsxs(s.Select,{value:((F=i.rangeKeys)==null?void 0:F[y])||"__none",onValueChange:G=>{G==="__none"?k(y,""):k(y,G)},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select column"})}),e.jsx(s.SelectContent,{children:w.map(G=>e.jsx(s.SelectItem,{value:G.value,className:"text-xs",children:G.label},G.value))})]})]}):e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[y," COLUMN KEY"]}),e.jsx(Re,{placeholder:"Column key",value:((z=i.rangeKeys)==null?void 0:z[y])||"",onCommit:G=>k(y,G),className:"h-8 text-xs"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[y," VALUE"]}),e.jsx(Re,{type:"number",placeholder:m?"0.80":"Static value",value:(($=i.ranges)==null?void 0:$[y])===void 0?"":String((O=i.ranges)==null?void 0:O[y]),onCommit:G=>B(y,G),className:"h-8 text-xs"})]})]},y)})})]})]})]})}const Ns=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],$n=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function Pe({value:t,onChange:a,label:n}){const[r,l]=S.useState(!1),[i,c]=S.useState(!1),o=()=>{const d=Ns.find(u=>u.value===t);return d?d.color:t.startsWith("#")?t:Ns[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:r,onOpenChange:l,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"size-5 rounded border-2 border-input shadow-sm transition-all hover:scale-110 hover:border-gray-400",style:{backgroundColor:o()},"aria-label":`Change color for ${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:$n.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:()=>{c(!0),l(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:n})]}),i&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>c(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(tt,{color:o(),onColorChange:d=>{a(d),c(!1)},onClose:()=>c(!1)})})]})]})}const qn=Object.keys(s.HEATMAP_PRESET_PALETTES);function it(){const t=s.useEditorStore(h=>h.card),a=s.useEditorStore(h=>{var p;return(p=h.card)==null?void 0:p.preferences}),{setCardPreferences:n}=s.useEditorActions(),r=(t==null?void 0:t.type)==="heatmap",l=(a==null?void 0:a.heatmapConfig)||{},i=l.colorPalette??"green",c=l.legendPosition??"bottom",o=S.useMemo(()=>l.colorRange&&l.colorRange[0]&&l.colorRange[1]?[l.colorRange[0],l.colorRange[1]]:[...s.DEFAULT_HEATMAP_CUSTOM_RANGE],[l.colorRange]),d=h=>{const p={...l,...h};p.colorPalette!=="custom"?delete p.colorRange:(!p.colorRange||!p.colorRange[0]||!p.colorRange[1])&&(p.colorRange=[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]),n({...a||{},heatmapConfig:p})},u=h=>{d({colorPalette:h,colorRange:h==="custom"?l.colorRange??[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},m=(h,p)=>{const j=[...o];j[h]=p,d({colorPalette:"custom",colorRange:j})},x=h=>{d({legendPosition:h})};return r?e.jsxs(s.AccordionItem,{value:"heatmap-color-config",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Grid3x3,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Heatmap Settings"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs(s.RadioGroup,{value:i,onValueChange:h=>u(h??"blue"),className:"space-y-3",children:[qn.map(h=>{const p=s.HEATMAP_PRESET_PALETTES[h];return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:`heatmap-${h}`,value:h}),e.jsxs(s.Label,{htmlFor:`heatmap-${h}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:p.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${p.start}, ${p.end})`}})]})]},h)}),e.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.RadioGroupItem,{id:"heatmap-custom",value:"custom"}),e.jsx(s.Label,{htmlFor:"heatmap-custom",className:"text-sm font-medium",children:"Custom colors"})]}),i==="custom"&&e.jsxs("div",{className:"flex flex-col gap-3 pl-6",children:[e.jsx(Pe,{value:o[0],onChange:h=>m(0,h),label:"Start color"}),e.jsx(Pe,{value:o[1],onChange:h=>m(1,h),label:"End color"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Color scale position"}),e.jsxs(s.Select,{value:c,onValueChange:h=>x(h??"bottom"),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["top","bottom","left","right"].map(h=>e.jsx(s.SelectItem,{value:h,className:"text-xs",children:h[0].toUpperCase()+h.slice(1)},h))})]})]})]})]}):null}function Un(){const t=s.useEditorStore(a=>a.card);return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Chart Configuration"}),e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:[(t==null?void 0:t.type)==="heatmap"&&e.jsx(it,{}),(t==null?void 0:t.type)==="bullet"&&e.jsx(ot,{}),e.jsx(at,{}),e.jsx(nt,{}),e.jsx(rt,{}),e.jsx(lt,{})]})]})}const Kn=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT 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."]})]}),_n=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT 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."]})]}),Hn=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 Jn(){const t=s.useEditorStore(n=>n.card.type);function a(n){const r=["kpi","table","text","map","custom"],l=i=>r.includes(n)?i:e.jsxs(e.Fragment,{children:[i,e.jsx(Un,{})]});switch(n){case"stackedBar":case"stackedLine":return l(e.jsx(Ln,{}));case"tornado":case"pyramid":return l(e.jsx(Be,{docContent:Kn,cardType:n}));case"kpi":return e.jsx(Tn,{});case"line":case"bar":return l(e.jsx(bn,{cardType:n}));case"range":return l(e.jsx(Be,{docContent:_n,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(vn,{cardType:n}));case"table":return e.jsx(Fn,{cardType:n});case"text":return e.jsx(Be,{docContent:Hn,cardType:n,suffix:"Visual"});case"map":return e.jsx(An,{});case"custom":return e.jsx(pn,{});default:return l(e.jsx(Cn,{}))}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[a(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Qn(){const t=S.useRef(null),a=S.useRef(null),n=s.useEditorStore(l=>l.isShowingVisual),r=s.useEditorStore(l=>l.showAIDialog);return S.useEffect(()=>{var l,i,c,o;r?((l=t.current)==null||l.resize(0),(i=a.current)==null||i.resize(0)):((c=t.current)==null||c.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(Jn,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(fs,{})})]}):e.jsx(fs,{})})]})}function Wn(t){var me;s.useAIInteractionStore(q=>q.currentAIContext);const[a,n]=S.useState(""),[r,l]=S.useState(null),{authToken:i,tokenProps:c}=s.useSemaphorContext(),o=s.useEditorStore(q=>{var W;return(W=q==null?void 0:q.card)==null?void 0:W.sql}),d=s.useEditorStore(q=>q.isDevMode),u=s.useEditorStore(q=>{var W;return(W=q==null?void 0:q.card)==null?void 0:W.python}),{setCardPython:m,setCardSql:x,setRunSql:h,switchCardType:p,setQueryConfig:j}=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),B=s.useEditorStore(q=>q.selectedDatabaseName),L=s.useEditorStore(q=>q.selectedTableName),E=s.useEditorStore(q=>q.selectedConnectionId),C=s.useEditorStore(q=>q.selectedSchemaName),f=s.useDashboardStore(q=>q.dashboard.aiScopeTables),{errorMessage:b,refetch:N,data:A}=s.useDashboardCardQuery(k),{setTriggerAIRun:w,setCurrentAssitantScope:P,setCardConfig:I}=s.useEditorActions(),{selectedDatamodelName:T,connectionType:y,selectedDatamodelId:M}=s.useEditorAside(),F=(me=s.useDashboardQuery().data)==null?void 0:me.assistantProfileId,{messages:z,setMessages:$,regenerate:O,error:G,sendMessage:R,status:_,addToolResult:J,stop:se,clearError:Z}=s.useChat({transport:new s.DefaultChatTransport({api:`${c.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${i==null?void 0:i.accessToken}`}),body:()=>{const q=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:F,isDevMode:d,aiContext:q.currentAIContext,reasoningEffort:q.reasoningEffort,showReasoning:q.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:q,body:W})=>({body:{...W,messages:s.cleanupIncompleteMessages(q)}})}),onError:q=>{var W;if(q.name==="AbortError"||(W=q.message)!=null&&W.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)");return}console.error("[Editor Assistant] Stream error:",q)},onToolCall:ae,onFinish({isAbort:q,isDisconnect:W,isError:de}){n(""),console.log(q?"[Editor Assistant] Stream aborted by user":W?"[Editor Assistant] Stream disconnected (network error)":de?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully")}});S.useEffect(()=>{D&&v&&(R({role:"user",parts:[{type:"text",text:v}]}),w(!1))},[D,v,R,w]);async function ae({toolCall:q}){var W,de,pe,fe,ce,V,ee,X,je,ge,be,ve,he,Ee,Se,we;if(["createChartFromSql","createForecast"].includes(q.toolName)){const Q=((W=q.input)==null?void 0:W.sql)??((de=q.args)==null?void 0:de.sql),ne=((pe=q.input)==null?void 0:pe.python)??((fe=q.args)==null?void 0:fe.python),le=((ce=q.input)==null?void 0:ce.chartType)??((V=q.args)==null?void 0:V.chartType);p(le),x(Q),m(ne),h(!0),J({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){J({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"error",message:"No SQL found"}});return}J({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",sql:o,python:u||""}})}else if(q.toolName==="generateQueryConfig"){n("Generating query config...");const Q=((ee=q.input)==null?void 0:ee.chartType)??((X=q.args)==null?void 0:X.chartType),ne=((je=q.input)==null?void 0:je.queryConfig)??((ge=q.args)==null?void 0:ge.queryConfig);((be=q.input)==null?void 0:be.cardConfig)??((ve=q.args)==null||ve.cardConfig),p(Q),I(ne),x(void 0),m(void 0);const le=await N();if((he=le==null?void 0:le.data)!=null&&he.error){J({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"error",queryConfig:ne,message:(Ee=le==null?void 0:le.data)==null?void 0:Ee.error.message}});return}if((Se=le==null?void 0:le.data)!=null&&Se.records){J({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",queryConfig:ne,message:"The data has been visualized"}});return}J({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",queryConfig:ne,message:"The data has been visualized",records:(we=le==null?void 0:le.data)==null?void 0:we.records}})}else n("Analyzing...")}function Y(q){const W=s.removeFromScopeArray(g,q);U(W)}function U(q){const W=s.sanitizeAIScope(q);P(W),$(de=>[...de,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(W)}`}]}])}function te(){const q={databaseName:B||"",schemaName:C||"",tableName:L||"",datamodelId:M||"",datamodelName:s.resolveDatamodelName(T),connectionId:E||"",connectionType:y||""},W=s.dedup([...g,q]);U(W)}function H(){const q={databaseName:B||"",schemaName:C||"",tableName:L||"",datamodelName:s.resolveDatamodelName(T),connectionId:E||"",connectionType:y||"",datamodelId:M||""};if(!s.isInAiScopeArray([...f||[],...g],q)||g.length===0){const de=s.dedup([...f||[],...g,q]).filter(pe=>pe.connectionId===q.connectionId);U(de)}}const re=!["ready","error"].includes(_),ue=s.getErrorMessage(G);return{messages:z,setMessages:$,sendMessage:R,regenerate:O,isLoading:re,handleSetAIScope:H,handleAddCurrentTableToScope:te,removeFromCurrentSelections:Y,currentAssitantScope:g,setCurrentAssitantScope:P,stop:se,status:_,toolStatus:a,llmUsage:r,onFinish:t,errorMessage:ue,clearError:Z}}const Yn=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Cs({isFullscreen:t,onFullscreenChange:a,fullscreenContainer:n}){const r=S.useRef(null),[l,i]=S.useState(!1),[c,o]=S.useState(s.isDevEnv),[d,u]=S.useState(!1),[m,x]=S.useState(!1),[h,p]=S.useState(!1),j=t??h,g=s.useCurrentAIContext(),{setCurrentAIContext:v}=s.useAIActions(),{clearQueue:D}=s.useQueueActions(),{clearFileAttachments:k}=s.useFileActions(),B=s.useFileAttachments("editor"),L=s.useDashboardStore(Q=>Q.dashboard.aiContext),E=s.useEditorStore(Q=>Q.card.dataSource),C=s.useEditorStore(Q=>Q.actions.setCardSql),f=s.useEditorStore(Q=>Q.actions.setRunSql),b=s.useEditorStore(Q=>Q.showAIDialog),N=s.useDashboardStore(Q=>Q.handleOpenAssistantProfile),{setShowAIDialog:A,setCardPython:w}=s.useEditorActions(),{setDataSource:P}=s.useEditorActions(),{assistantProfile:I}=s.useAssistantProfile(),{messages:T,setMessages:y,sendMessage:M,isLoading:F,stop:z,status:$,llmUsage:O,errorMessage:G,clearError:R}=Wn(),[_,J]=S.useState(""),se=Q=>{J(Q.target.value)},Z=Q=>{Q.preventDefault();const ne=_.trim();if(!ne&&B.length===0)return;const le=[];ne&&le.push({type:"text",text:ne}),B.forEach(De=>{De.data&&le.push({type:"file",mediaType:De.type,filename:De.name,url:`data:${De.type};base64,${De.data}`})}),M({role:"user",parts:le}),J(""),k("editor"),W({force:!0})},{visibleMessages:ae,hasMoreMessages:Y,totalMessageCount:U,loadMoreMessages:te,resetMessageWindow:H}=s.useMessageWindow(T,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:re,isAtBottom:ue,hasNewMessages:me,newMessageCount:q,scrollToBottom:W,handleScroll:de,resetNewMessageCount:pe}=s.useAutoScroll(ae,{threshold:50,behavior:"smooth",isStreaming:F});S.useEffect(()=>{var Q;b&&((Q=r.current)==null||Q.focus(),v({selectedEntities:(E==null?void 0:E.selectedEntities)||[]}))},[b,E,v]),s.useAutoSubmitQueue({assistantType:"editor",status:$,isLoading:F,sendMessage:M});const{hasActiveTools:fe}=s.useActiveToolStatus(T),ce=S.useCallback(Q=>{a==null||a(Q),t===void 0&&p(Q)},[t,a]);S.useEffect(()=>{if(!j)return;function Q(ne){ne.key==="Escape"&&ce(!1)}return window.addEventListener("keydown",Q),()=>{window.removeEventListener("keydown",Q)}},[j,ce]);const V=S.useCallback(Q=>{M({role:"user",parts:[{type:"text",text:Q}]}),W({force:!0})},[M,W]),ee=S.useCallback(async()=>{const Q=JSON.stringify(T??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(Q),s.ue.success("Conversation copied")}catch(ne){console.error("Failed to copy conversation",ne),s.ue.error("Unable to copy conversation")}},[T]),X=S.useCallback(()=>{ce(!j)},[j,ce]);function je(Q,ne){ne==="sql"?(C(Q),f(!0)):ne==="python"&&(w(Q),f(!0))}function ge(){g.selectedEntities.length===0&&v({selectedEntities:(L==null?void 0:L.selectedEntities)||[]})}function be(Q){ge();const ne={role:"user",parts:[{type:"text",text:Q.title+" "+Q.subtitle}]};M(ne)}function ve(Q){ge(),M({role:"user",parts:[{type:"text",text:Q}]})}function he(){return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuLabel,{children:"Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx(s.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:i,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:o,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:d,onCheckedChange:u,children:"System Message"})]})]})}function Ee(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const Se=(_==null?void 0:_.length)===0&&(T==null?void 0:T.filter(Q=>Q.role==="user").length)===0,we=e.jsxs("div",{"data-role":"editor-assistant",className:s.cn("flex h-full w-full flex-col justify-between px-6 py-4",j&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Ee(),N&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:N,children:(I==null?void 0:I.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[he(),c&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:ee,children:"Copy Conversation"}),e.jsx(s.IconButton,{tooltip:j?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:X,children:j?e.jsx(s.Minimize2,{className:"size-4"}):e.jsx(s.Maximize2,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{y([]),D("editor"),R(),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:()=>{A(!1)},children:e.jsx(s.X,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:re,className:"mt-2 flex w-full grow basis-0",onScroll:de,children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[Y&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:te,className:"text-xs",children:["Load ",Math.min(5,U-ae.length)," ","more messages (",U-ae.length," ","hidden)"]})}),e.jsx(s.PrintMessages,{messages:ae,showTools:c,handleRun:je,showSystemMessage:d,onQuickReply:V,disableQuickReplies:F}),!fe&&e.jsx(s.AssistantStatus,{status:$,errorMessage:G})]})}),b&&!ue&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{W({force:!0}),pe()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),me&&q>0&&e.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:q>9?"9+":q})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[Se&&!I&&e.jsx(s.Placeholders,{onClick:be,placeholders:Yn}),e.jsx("div",{children:Se&&I&&e.jsx(s.SeedQuestions,{seedQuestions:I.seedQuestions||[],handleSeedQuestionClick:ve})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:r,setInput:J,stop:z,input:_,handleInputChange:se,handleSubmit:Q=>{ge(),Z(Q),W({force:!0})},isLoading:F,status:$,assistantType:"editor",onFocus:()=>{}})]}),O&&l&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",O.inputTokens," prompt tokens, ",O.outputTokens," ","completion tokens, ",O.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(E==null?void 0:E.selectedEntities)||[],open:m,onOpenChange:x,dataSource:E||s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]});return j&&n?gt.createPortal(e.jsx("div",{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:e.jsx("div",{className:"flex h-full w-full",children:we})}),n):we}function $e(t,a){const[n,r]=S.useState(()=>{const l=localStorage.getItem(t);return l?JSON.parse(l):a});return S.useEffect(()=>{localStorage.setItem(t,JSON.stringify(n))},[n,t]),[n,r]}const Xn="chart-selector-standard-first";function Zn(){const[t,a]=$e(Xn,!0);return{standardFirst:t,updatePreference:a}}const Ss=({pluginVisual:t,index:a,onSelect:n})=>{const r=Ge(t.icon||""),l=t.name.charAt(0).toUpperCase(),i=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"}):i||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:l}),e.jsx("span",{children:t.name})]}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:"opacity-0 outline-none transition-opacity group-hover:opacity-100",children:e.jsx(s.Info,{className:"ml-1 h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"right",children:t.pluginName})]})]})},`${t.url}-${t.name}-${a}`)},ws=["default","standardPlugin","customPlugin"];function er({selectedChart:t,onChartChange:a}){var E;const[n,r]=S.useState(!1),{data:l}=Qs();Zn();const c=((E=s.useEditorStore(C=>C.card).customCardPreferences)==null?void 0:E.url)||"";Xe(c);const{setCardType:o,setCardPreferences:d,setIsDevMode:u}=s.useEditorStore(C=>C.actions),{setCardCustomCfg:m,setCustomCardPreferences:x,setQueryConfig:h}=s.useEditorActions(),[p,j]=$e("chart-section-active",null),g=S.useMemo(()=>p?[p,...ws.filter(C=>C!==p)]:ws,[p]);function v(C){m(null),d({}),o(C),["custom","map"].includes(C)&&(u(!0),h(void 0)),a(C),r(!1)}function D(C){m(null),d({}),o("custom"),x({type:"component",visualType:"single",url:C.url,componentName:C.name,icon:C.icon,pluginChartType:C.chartType}),h(void 0),a("custom"),r(!1)}const k=S.useMemo(()=>s.chartTypes.some(f=>f.id==="bullet")?s.chartTypes:[...s.chartTypes,{id:"bullet",icon:s.BulletChartIcon,label:"Bullet Chart"}],[]),B=()=>{var f;if(t==="custom"){const b=s.useEditorStore.getState().card;return((f=b==null?void 0:b.customCardPreferences)==null?void 0:f.componentName)||"Custom Visual"}const C=k.find(b=>b.id===t);return(C==null?void 0:C.label)||"Select chart type"},L=()=>{var f,b;if(t==="custom"){const N=s.useEditorStore.getState().card,A=(f=N==null?void 0:N.customCardPreferences)==null?void 0:f.icon,w=(b=N==null?void 0:N.customCardPreferences)==null?void 0:b.componentName;if(A&&w)return e.jsx(sr,{icon:A,componentName:w});if(w){const P=s.getAutoDetectedChartIcon(w);if(P)return P}return e.jsx(Ae,{className:"h-4 w-4"})}const C=k.find(N=>N.id===t);if(C){const N=C.icon;return e.jsx(N,{className:"h-4 w-4"})}return e.jsx(Ae,{className:"h-4 w-4"})};return e.jsx("div",{className:"",children:e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[L(),e.jsx("span",{children:B()})]}),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(C=>{if(C==="default")return e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center gap-2",children:"Default Visuals"})}),e.jsx(s.TooltipContent,{side:"right",children:"These are the standard visuals available in Semaphor"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:p==="default",onCheckedChange:f=>j(f?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:k.map(f=>{const b=f.icon;return e.jsx(s.CommandItem,{value:`${f.label} ${f.id} chart graph visualization`,onSelect:()=>v(f.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(b,{className:"h-4 w-4"}),e.jsx("span",{children:f.label})]})},f.id)})},"default");if(C==="standardPlugin"){const f=l.filter(b=>b.pluginType==="standard");return f.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsx("p",{children:"Standard Visuals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:p==="standardPlugin",onCheckedChange:b=>j(b?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:f.filter(b=>b.componentType==="chart").map((b,N)=>e.jsx(Ss,{pluginVisual:b,index:N,onSelect:()=>D(b)},`${b.url}-${b.name}-${N}`))},"standardPlugin"):null}if(C==="customPlugin"){const f=l.filter(b=>b.pluginType==="custom");return f.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-2",children:["Custom Visuals",e.jsx(s.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),e.jsx(s.TooltipContent,{side:"right",children:"External visuals that are specific to your project"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:p==="customPlugin",onCheckedChange:b=>j(b?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:f.map((b,N)=>e.jsx(Ss,{pluginVisual:b,index:N,onSelect:()=>D(b)},`${b.url}-${b.name}-${N}`))},"customPlugin"):null}return null})]})]})})]})})}const sr=({icon:t,componentName:a})=>{const n=Ge(),r=s.getAutoDetectedChartIcon(a);return n?e.jsx(n,{className:"h-4 w-4"}):r||e.jsx(Ae,{className:"h-4 w-4"})},tr=[{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:!1},{id:"pie",icon:s.ChartPie,label:"Pie Chart"},{id:"doughnut",icon:s.Donut,label:"Donut Chart"},{id:"kpi",icon:s.TiSortNumerically,label:"KPI"},{id:"treemap",icon:s.TbChartTreemap,label:"Treemap"},{id:"bullet",icon:s.BulletChartIcon,label:"Bullet Chart"},{id:"funnel",icon:s.TbChartFunnel,label:"Funnel Chart"},{id:"tornado",icon:s.Tornado,label:"Tornado Chart"},{id:"heatmap",icon:s.Grid3x3,label:"Heatmap"},{id:"range",icon:s.ChartNoAxesGantt,label:"Range Chart"}];function ar({selectedChart:t,onChartChange:a,isDropdownExpanded:n,onToggleDropdown:r}){var o;const l=s.useEditorStore(d=>d.card),i=((o=l==null?void 0:l.config)==null?void 0:o.pivotByColumns)&&l.config.pivotByColumns.length>0,c=tr.filter(d=>!(d.requiresPivot&&!i));return e.jsxs("div",{className:"grid grid-cols-7 gap-2",children:[c.map(d=>{const u=d.icon,m=t===d.id;return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",onClick:()=>a(d.id),className:s.cn("h-8 w-8 p-0",m&&"bg-accent text-accent-foreground"),children:[e.jsx(u,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:d.label})]})}),e.jsxs(s.TooltipContent,{side:"bottom",className:"border-foreground/20 bg-foreground text-background",children:[e.jsx("p",{children:d.label}),e.jsx(s.TooltipArrow,{className:"fill-foreground"})]})]},d.id)}),r&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:r,className:"h-8 w-8 p-0","aria-label":n?"Hide all charts":"Show all charts",children:n?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})})}),e.jsxs(s.TooltipContent,{side:"bottom",className:"border-foreground/20 bg-foreground text-background",children:[e.jsx("p",{children:n?"Hide dropdown":"Show all charts"}),e.jsx(s.TooltipArrow,{className:"fill-foreground"})]})]})]})}const ls=({dataType:t})=>s.getFieldIconComponent(t);function nr({aliasTemplate:t,onAliasTemplateChange:a}){var d;const[n,r]=S.useState(t),[l,i]=S.useState(!1),c=(d=s.useEditorStore(u=>{var m;return(m=u.card.config)==null?void 0:m.pivotByColumns}))==null?void 0:d[0],o=c?`e.g. Min Sales in {{${c.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Input$1,{placeholder:o,value:l?n:t,onChange:u=>{r(u.target.value),i(!0)},onFocus:()=>i(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&l&&n!==t?(a(n),i(!1)):u.key==="Escape"&&(r(t),i(!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),i(!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),i(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function rr({valueAliases:t,onValueAliasesChange:a}){const[n,r]=S.useState(null),[l,i]=S.useState(""),[c,o]=S.useState(""),d=()=>{a({...t,"":""})},u=x=>{const h={...t};delete h[x],a(h)},m=x=>{const h={...t};delete h[x],h[l]=c,a(h),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(t).map(([x,h],p)=>e.jsx("div",{className:"flex items-center gap-2",children:n===x?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:l,onChange:j=>i(j.target.value),className:"h-8 w-24 text-xs",onPointerDown:j=>j.stopPropagation(),onKeyDown:j=>{j.key==="Enter"?m(x):j.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:j=>o(j.target.value),className:"h-8 w-24 text-xs",onPointerDown:j=>j.stopPropagation(),onKeyDown:j=>{j.key==="Enter"?m(x):j.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(x),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:x,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(x),i(x),o(h)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(x),i(x),o(h)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(x),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},x+p)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:d,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function lr({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),i=l?r.indexOf(l):-1;function c(){return e.jsx("div",{className:"pr-1",children:l&&e.jsx(et,{idx:i,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(st,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&c(),["pie","doughnut"].includes(a)&&o()]})}function or({field:t,searchQuery:a="",limit:n=500}){const{authToken:r,tokenProps:l}=s.useSemaphorContext(),i=s.useEditorStore(u=>u.card),c=i==null?void 0:i.dataSource,o=["attribute-values",t.entityName,t.name,a,n],d=s.useQuery({queryKey:o,queryFn:async()=>{if(!(c!=null&&c.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const u={groupByColumns:[{...t,role:"groupby"}],metricColumns:[],filters:a?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:a}],groups:[]}:void 0,rowLimit:n},m={connection_id:c.connectionId,cardConfig:u,cardDataSource:c,cache_config:s.getCacheConfig({card:i})};console.log("requestBody",m);const x=await s.postRequestRegular(`${l.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",m);if(x!=null&&x.error)return console.error("Error fetching attribute values:",x.error),[];const h=t.name;return((x==null?void 0:x.records)||[]).map(j=>{const g=j[h]||j[t.alias||h]||j[t.label];return{id:g||"",value:g||"",label:String(g||"(empty)")}})}catch(u){return console.error("Error fetching attribute values:",u),[]}},enabled:!!t&&!!(c!=null&&c.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:d.data||[],isLoading:d.isLoading,isFetching:d.isFetching,isError:d.isError,error:d.error,refetch:d.refetch}}function ir({open:t,onOpenChange:a,availableFields:n,existingFilters:r,editingCondition:l,onSave:i}){var B,L;const c=!!l,[o,d]=S.useState(c?"values":"fields"),[u,m]=S.useState(""),[x,h]=S.useState({id:(l==null?void 0:l.id)||s.v4(),field:(l==null?void 0:l.field)||null,selectedValues:l?Array.isArray(l.value)?l.value:[l.value]:[]}),p=n.filter(E=>{var f;return c?!1:!((f=r==null?void 0:r.conditions)==null?void 0:f.some(b=>b.field.id===E.id))&&E.label.toLowerCase().includes(u.toLowerCase())}),j=E=>{h({...x,field:E}),d("values")},g=()=>{if(x.field&&x.selectedValues.length>0){const E={id:x.id,field:x.field,operator:"in",value:x.selectedValues};let C;if(c){const f=((r==null?void 0:r.conditions)||[]).map(b=>b.id===l.id?E:b);C={...r,conditions:f}}else{const f=(r==null?void 0:r.conditions)||[];C={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...f,E],groups:[]}}i(C),a(!1)}},v=()=>{if(!c||!l)return;const E=((r==null?void 0:r.conditions)||[]).filter(C=>C.id!==l.id);if(E.length>0){const C={...r,conditions:E};i(C)}else i(void 0);a(!1)},D=E=>{h({...x,selectedValues:E})},k=()=>{c&&l?(h({id:l.id,field:l.field,selectedValues:Array.isArray(l.value)?l.value:[l.value]}),d("values")):(h({id:s.v4(),field:null,selectedValues:[]}),d("fields")),m("")};return S.useEffect(()=>{t&&k()},[t,c,l]),e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsx(s.DialogHeader,{children:e.jsx(s.DialogTitle,{children:c?`Edit Filter: ${(B=x.field)==null?void 0:B.label}`:o==="fields"?"Select Field to Filter":`Select Values for ${(L=x.field)==null?void 0:L.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!c&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&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(E=>e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-muted rounded-md text-xs",children:[e.jsxs("span",{className:"font-medium",children:[E.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(E.value)?`${E.value.length} values`:String(E.value)})]},E.id))})]}),o==="fields"&&!c?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search fields...",value:u,onChange:E=>m(E.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:p.map(E=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>j(E),children:[e.jsx(ls,{dataType:s.getDataType(E.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:E.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[E.entityName,".",E.name]})]})]},E.id))}),p.length===0&&u&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',u,'"']}),p.length===0&&!u&&n.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(cr,{field:x.field,selectedValues:x.selectedValues,onValuesChange:D,onBack:c?void 0:()=>d("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:c?e.jsx(s.Button,{variant:"destructive",onClick:v,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick: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:!x.field||x.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function cr({field:t,selectedValues:a,onValuesChange:n,onBack:r}){const[l,i]=S.useState(""),{values:c,isLoading:o,isFetching:d}=or({field:t,searchQuery:l,limit:500}),u=l?c.filter(h=>String(h.value).toLowerCase().includes(l.toLowerCase())):c,m=h=>{const p=a.includes(h);n(p?a.filter(j=>j!==h):[...a,h])},x=()=>{a.length===u.length&&u.length>0?n([]):n(u.map(h=>h.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:r,children:"← Back"}),e.jsxs(s.Label,{className:"text-sm font-medium",children:["Select values for ",t.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search values...",value:l,onChange:h=>i(h.target.value),className:"pl-10"})]}),o||d?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx(s.Checkbox,{checked:a.length===u.length&&u.length>0,onCheckedChange:x}),e.jsxs(s.Label,{className:"text-sm",children:["Select All (",u.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:u.map(h=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>m(h.value),children:[e.jsx(s.Checkbox,{checked:a.includes(h.value),onCheckedChange:()=>m(h.value)}),e.jsx(ns,{className:"text-sm",children:h.label})]},h.id))})]})]})}function dr({field:t,zone:a,index:n,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:i=!1,cardType:c}){var is,cs,ds,us;const{attributes:o,listeners:d,setNodeRef:u,transform:m,transition:x,isDragging:h}=s.useSortable({id:t.id}),p=s.useEditorStore(K=>K.card),{updateLabel:j,handleAggregationChange:g,handleDateFormatChange:v,handleGranularityChange:D,handleAliasTemplateChange:k,handleValueAliasesChange:B,removeField:L,handleKpiComparisonTypeChange:E,handleKpiShowTrendlineChange:C,handleKpiTrendlineWindowChange:f,handleKpiTrendlineGranularityChange:b,handleKpiTargetValueChange:N}=ss(p),[A,w]=S.useState(!1),[P,I]=S.useState(!1),[T,y]=S.useState(null),[M,F]=S.useState(t.dateFormat||"YYYY-MM-DD"),[z,$]=S.useState(t.customFormat||""),[O,G]=S.useState(!!t.customFormat),[R,_]=S.useState(t.granularity||"day"),[J,se]=S.useState(t.aliasTemplate||""),[Z,ae]=S.useState(t.valueAliases||{}),[Y,U]=S.useState((is=t.parameters)==null?void 0:is.filters),te=K=>{K==="custom"?G(!0):(G(!1),F(K),a==="groupBy"&&v(n,K,""))},H=K=>{$(K),a==="groupBy"&&v(n,"custom",K)},re=K=>{var xe;_(K);const ie=(xe=s.getDateFormatOptionsForGranularity(K)[0])==null?void 0:xe.value;ie&&!O&&(F(ie),a==="groupBy"&&v(n,ie,"")),a==="groupBy"&&D(n,K)},ue=K=>{se(K),a==="metrics"&&k(n,K)},me=K=>{ae(K),a==="metrics"&&B(n,K)},q=K=>{j(a,n,K)},W=K=>{var oe;if(U(K),a==="metrics"){const ie={...t,parameters:{...t.parameters,filters:K}},xe=[...((oe=p.config)==null?void 0:oe.metricColumns)||[]];xe[n]=ie,s.useEditorStore.getState().actions.updateCardConfig(p.id,{metricColumns:xe})}I(!1)},de=()=>{L(a,n)},pe={transform:s.CSS.Transform.toString(m),transition:x},fe=s.getDataType(t.dataType),ce=fe==="date",V=c==="kpi",ee=s.getDateFormatOptionsForGranularity(R),X=a!=="pivotBy",je=ce&&a==="groupBy"&&(!V||((cs=p.config)==null?void 0:cs.comparisonType)==="start_vs_end"),ge=!V&&ce&&a==="groupBy",be=c&&s.COMPARISON_SUPPORTED_CHART_TYPES.includes(c)&&ce&&a==="groupBy",ve=c==="kpi"&&ce&&a==="groupBy",he=c&&c!=="pivotTable"&&a==="metrics"&&((ds=p.config)==null?void 0:ds.comparisonType)==="target",Ee=a==="metrics",Se=()=>e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:K=>{K.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),we=()=>X?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(Ne,{value:t.label??"",onSave:q,placeholder:"Display label...",type:"text"})]}):null,Q=()=>je?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(s.Select,{value:R,onValueChange:re,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsx(s.SelectContent,{children:["day","week","month","quarter","year"].map(K=>e.jsx(s.SelectItem,{className:"text-xs",value:K,children:s.toTitleCase(K)},K))})]})]}):null,ne=()=>ge?e.jsxs(e.Fragment,{children:[Q(),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:O?"custom":M,onValueChange:te,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select date format..."})}),e.jsx(s.SelectContent,{children:ee.map(K=>e.jsx(s.SelectItem,{className:"text-xs",value:K.value,children:K.label},K.value))})]}),O&&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:z,onChange:K=>{K.stopPropagation(),H(K.target.value)},onClick:K=>K.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}):null,le=()=>{var ie,xe,Ce,Le,ms;const K=be,oe=ve;return!K&&!oe?null:e.jsxs(e.Fragment,{children:[K&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(s.Select,{value:((ie=p.config)==null?void 0:ie.comparisonType)||"none",onValueChange:E,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"none",children:"No Comparison"}),e.jsx(s.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(s.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(s.SelectItem,{value:"start_vs_end",children:"Start vs End"})]})]})]}),oe&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(s.SmallSwitch,{checked:((xe=p.config)==null?void 0:xe.showTrendline)||!1,onCheckedChange:C})]})}),((Ce=p.config)==null?void 0:Ce.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(s.Input$1,{type:"number",min:"1",max:"365",value:((Le=p.config)==null?void 0:Le.trendlineWindow)||30,onChange:pt=>{const ft=parseInt(pt.target.value)||30;f(ft)},className:"h-8 text-xs",placeholder:"30"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Granularity"}),e.jsxs(s.Select,{value:((ms=p.config)==null?void 0:ms.trendlineGranularity)||"day",onValueChange:b,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"day",children:"Day"}),e.jsx(s.SelectItem,{value:"week",children:"Week"}),e.jsx(s.SelectItem,{value:"month",children:"Month"})]})]})]})]})]})]})},De=()=>{var K,oe;return he?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(Ne,{value:((K=p.config)==null?void 0:K.targetValue)!==void 0&&((oe=p.config)==null?void 0:oe.targetValue)!==null?String(p.config.targetValue):"",onSave:ie=>{!isNaN(Number(ie))&&ie!==null?N(Number(ie)):N(0)},placeholder:"Enter target value...",type:"text"})]}):null},mt=()=>Ee?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(s.Select,{value:t.aggregate,onValueChange:K=>{g(n,K)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(Y==null?void 0:Y.conditions)&&Y.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:Y.conditions.map(K=>e.jsxs("div",{className:"flex cursor-pointer items-center gap-2 rounded bg-muted/50 p-2 text-xs transition-colors hover:bg-muted/70",onClick:()=>{y(K),I(!0)},children:[e.jsxs("span",{className:"font-medium",children:[K.field.label,":"]}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"cursor-help text-muted-foreground",children:Array.isArray(K.value)?K.value.length===1?String(K.value[0]):K.value.length<=2?K.value.join(", "):`${K.value.slice(0,2).join(", ")} +${K.value.length-2}`:String(K.value)})}),Array.isArray(K.value)&&K.value.length>1&&e.jsx(s.TooltipContent,{side:"top",className:"max-w-[300px]",children:e.jsxs("div",{className:"text-xs",children:[e.jsxs("div",{className:"mb-1 font-medium",children:["Selected values (",K.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:K.value.map((oe,ie)=>e.jsx("div",{children:String(oe)},ie))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:oe=>{var xe;oe.stopPropagation();const ie=Y.conditions.filter(Ce=>Ce.id!==K.id);if(ie.length>0){const Ce={...Y,conditions:ie};W(Ce)}else if(U(void 0),a==="metrics"){const Ce={...t,parameters:{...t.parameters,filters:void 0}},Le=[...((xe=p.config)==null?void 0:xe.metricColumns)||[]];Le[n]=Ce,s.useEditorStore.getState().actions.updateCardConfig(p.id,{metricColumns:Le})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},K.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{y(null),I(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(lr,{column:t}),i&&e.jsxs(e.Fragment,{children:[e.jsx(nr,{aliasTemplate:J,onAliasTemplateChange:ue}),e.jsx(rr,{valueAliases:Z,onValueAliasesChange:me})]})]}):null,{columns:ht=[]}=s.useColumns(),xt=(Y==null?void 0:Y.conditions)&&Y.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:u,style:pe,...o,...d,className:`group mx-auto flex w-full flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${h?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(ls,{dataType:fe}),e.jsx(ns,{className:s.cn("w-[140px] flex-1 text-sm",xt&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),a==="metrics"&&((us=Y==null?void 0:Y.conditions)==null?void 0:us.length)&&!A&&e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 text-xs",children:[e.jsx(s.Filter,{className:"h-3 w-3"}),e.jsx("span",{children:Y.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:Y.conditions.map(K=>e.jsxs("div",{children:[K.field.label,":"," ",Array.isArray(K.value)?`${K.value.length} values`:String(K.value)]},K.id))})})]})}),a!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:K=>{K.stopPropagation(),w(!A)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${A?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:K=>{K.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const oe=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",oe),l(oe)},children:r==="asc"?e.jsx(s.ArrowUp,{className:"h-3 w-3"}):e.jsx(s.ArrowDown,{className:"h-3 w-3"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:K=>{K.stopPropagation(),de()},children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]}),A&&e.jsxs("div",{className:"space-y-3",children:[Se(),we(),c==="kpi"&&Q(),ne(),le(),De(),mt()]})]}),P&&e.jsx(ir,{open:P,onOpenChange:K=>{I(K),K||y(null)},availableFields:ht,existingFilters:Y,editingCondition:T,onSave:K=>{var oe;if(K)W(K);else if(U(void 0),a==="metrics"){const ie={...t,parameters:{...t.parameters,filters:void 0}},xe=[...((oe=p.config)==null?void 0:oe.metricColumns)||[]];xe[n]=ie,s.useEditorStore.getState().actions.updateCardConfig(p.id,{metricColumns:xe})}y(null)}})]})}function ur({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:"Pivot 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:"Metric Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});default:return null}};return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(s.TooltipContent,{side:"right",align:"start",className:"p-3",children:a()})]})})}function Ve({zone:t,fields:a,label:n,placeholder:r,shouldShow:l,hasPivotColumns:i=!1,activeField:c=null}){const{isOver:o,setNodeRef:d}=s.useDroppable({id:t}),{updateSortByColumn:u}=s.useEditorActions(),m=s.useEditorStore(v=>v.card),x=s.useEditorStore(v=>v.card.type),h=a.length>0,p=S.useMemo(()=>!c||!o?!0:Fe(c,t,x).isValid,[c,o,t,x]),j=(v,D)=>{var B;!((B=m.config)!=null&&B.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"&&x!=="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(ur,{concept:t})]}),e.jsx("div",{ref:d,className:s.cn("rounded-lg border-2 border-dotted p-0.5 transition-all",{"border-green-500 bg-green-50 dark:bg-green-950":o&&p,"border-red-500 bg-red-50 dark:bg-red-950":o&&!p,"border-muted-foreground/30 bg-muted/40":!o&&h,"min-h-[60px] border-muted-foreground/20 bg-background":!o&&!h}),children:a.length===0?e.jsx("div",{className:"flex min-h-[60px] items-center justify-center text-sm text-muted-foreground/60",children:r}):e.jsx(s.SortableContext,{items:a.map(v=>v.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:a.map((v,D)=>{const B=v.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(dr,{field:v,zone:t,index:D,sortDirection:B,onSortDirectionChange:L=>j(v.id,L),hasPivotColumns:i,cardType:x})})},v.id)})})})})]})}const Ds={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%
|
|
240
|
+
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 mr(){var h,p,j,g,v,D,k,B,L,E,C;const t=s.useEditorStore(f=>f.card),{setCardPreferences:a}=s.useEditorActions(),n=((h=t.config)==null?void 0:h.metricColumns)||[],r=((p=t.config)==null?void 0:p.groupByColumns)||[],l=n.length===2&&r.length===0,i=n.length>=1&&r.length>0;if(!(t.type==="kpi"&&(l||i)))return null;const o=((g=(j=t.preferences)==null?void 0:j.kpiVisualOptions)==null?void 0:g.metricComparison)||{},d=f=>{var N;const b={...t.preferences,kpiVisualOptions:{...(N=t.preferences)==null?void 0:N.kpiVisualOptions,metricComparison:{...o,...f}}};a(b)},u=i||o.enabled,m=((v=t.config)==null?void 0:v.comparisonType)||"none",x=m==="previous_period"||m==="same_period_last_year"||m==="start_vs_end";return e.jsxs(s.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(At,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[l&&n.length===2&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(s.SmallSwitch,{id:"enable-comparison",checked:o.enabled||!1,onCheckedChange:f=>d({enabled:f,...f&&!o.calculationType?{calculationType:"difference"}:{}})})]}),u&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Info,{className:"h-3 w-3 cursor-help text-muted-foreground"})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-xs",children:(()=>{const f=o.calculationType||"difference",b=Ds[f];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:b==null?void 0:b.label}),e.jsx("p",{children:b==null?void 0:b.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:b==null?void 0:b.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",b==null?void 0:b.example]})]})})()})]})]}),e.jsxs(s.Select,{value:o.calculationType||"difference",onValueChange:f=>d({calculationType:f}),children:[e.jsx(s.SelectTrigger,{id:"calculation-type",className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Object.entries(Ds).map(([f,b])=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:b.label},f))})]})]}),e.jsx(rs,{formatOptions:o.formatOptions||{},onFormatOptionsChange:f=>d({formatOptions:f}),showTitle:!0,title:"COMPARISON FORMAT"}),(x||l)&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator"}),l&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:o.position||"right",onValueChange:f=>d({position:f}),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"right",className:"text-xs",children:"Right"}),e.jsx(s.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(s.SelectItem,{value:"top",className:"text-xs",children:"Top"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-arrow",checked:o.showArrow!==!1,onCheckedChange:f=>d({showArrow:f})}),e.jsx(s.Label,{htmlFor:"show-arrow",className:"cursor-pointer text-xs text-muted-foreground",children:"Arrow"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-color",checked:o.showColor!==!1,onCheckedChange:f=>d({showColor:f})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),o.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(Pe,{value:((D=o.colorConfig)==null?void 0:D.increase)||"green",onChange:f=>d({colorConfig:{...o.colorConfig,increase:f}}),label:"Primary > Secondary"}),e.jsx(Pe,{value:((k=o.colorConfig)==null?void 0:k.decrease)||"red",onChange:f=>d({colorConfig:{...o.colorConfig,decrease:f}}),label:"Primary < Secondary"}),e.jsx(Pe,{value:((B=o.colorConfig)==null?void 0:B.noChange)||"neutral",onChange:f=>d({colorConfig:{...o.colorConfig,noChange:f}}),label:"Primary = Secondary"})]})]}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"conditional-label",checked:o.conditionalLabel||!1,onCheckedChange:f=>d({conditionalLabel:f})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),o.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(s.Input,{id:"label-increase",type:"text",value:((L=o.conditionalLabels)==null?void 0:L.increase)??"Increase",onChange:f=>d({conditionalLabels:{...o.conditionalLabels,increase:f.target.value}}),placeholder:"Increase",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-decrease",className:"text-xs text-muted-foreground",children:["Primary ","<"," Secondary"]}),e.jsx(s.Input,{id:"label-decrease",type:"text",value:((E=o.conditionalLabels)==null?void 0:E.decrease)??"Decrease",onChange:f=>d({conditionalLabels:{...o.conditionalLabels,decrease:f.target.value}}),placeholder:"Decrease",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-no-change",className:"text-xs text-muted-foreground",children:"Primary = Secondary"}),e.jsx(s.Input,{id:"label-no-change",type:"text",value:((C=o.conditionalLabels)==null?void 0:C.noChange)??"No change",onChange:f=>d({conditionalLabels:{...o.conditionalLabels,noChange:f.target.value}}),placeholder:"No change",className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-name",className:"text-xs text-muted-foreground",children:"Previous Label"}),e.jsx(s.Input,{id:"label-name",type:"text",value:o.labelName??"",onChange:f=>d({labelName:f.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function hr(){var l,i;const t=s.useEditorStore(c=>c.card),{setCardPreferences:a}=s.useEditorActions();if(t.type!=="kpi")return null;const n=((i=(l=t.preferences)==null?void 0:l.kpiVisualOptions)==null?void 0:i.formatOptions)||{},r=c=>{var d;const o={...t.preferences,kpiVisualOptions:{...(d=t.preferences)==null?void 0:d.kpiVisualOptions,formatOptions:c}};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(rs,{formatOptions:n,onFormatOptionsChange:r,showTitle:!1})})]})}function xr(){var i;const t=s.useEditorStore(c=>{var o;return(o=c.card)==null?void 0:o.type}),a=s.useEditorStore(c=>{var o;return(o=c.card)==null?void 0:o.preferences}),{setCardPreferences:n}=s.useEditorActions();if(t!=="treemap")return null;const r=((i=a==null?void 0:a.chartOptions)==null?void 0:i.treemapColorMode)??"branch",l=c=>{const o={...a||{},chartOptions:{...a==null?void 0:a.chartOptions,treemapColorMode:c}};n(o)};return e.jsxs(s.AccordionItem,{value:"treemap-color-mode",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TbChartTreemap,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Treemap Colors"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:e.jsxs(s.RadioGroup,{value:r,onValueChange:c=>l(c??"branch"),className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:"treemap-color-branch",value:"branch"}),e.jsxs(s.Label,{htmlFor:"treemap-color-branch",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Shade by value (default)"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Keeps parent hue and adjusts lightness based on the node's share within the branch."})]})]}),e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:"treemap-color-category",value:"category"}),e.jsxs(s.Label,{htmlFor:"treemap-color-category",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Single color per category"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Applies the top-level color to all descendants without lightening/darkening."})]})]})]})})]})}function pr({groupByFields:t,pivotByFields:a,metricsFields:n,sortByFields:r,activeField:l}){const i=s.useEditorStore(v=>{var D;return((D=v.card.customCardPreferences)==null?void 0:D.url)&&v.card.type==="custom"}),c=s.useEditorStore(v=>v.card),o=c==null?void 0:c.type,d=t.length>0||n.length>0,u=o!=="kpi"||n.length<=2,m=o!=="kpi",x=o!=="kpi"&&d,h=["pie","doughnut","polar","funnel","aggregateTable"].includes(o),p=m&&!h,j=()=>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:"Columns",placeholder:"Drop fields to measure"};return e.jsxs(s.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full",children:[e.jsxs(s.AccordionItem,{value:"fields",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.List,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[u&&e.jsx(Ve,{zone:"groupBy",fields:t,label:j().label,placeholder:j().placeholder,activeField:l}),p&&e.jsx(Ve,{zone:"pivotBy",fields:a,label:"Pivot Columns",placeholder:"Drop fields to pivot data",activeField:l}),e.jsx(Ve,{zone:"metrics",fields:n,label:g().label,placeholder:g().placeholder,hasPivotColumns:a.length>0,activeField:l}),x&&e.jsx(Ve,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics",activeField:l})]})]}),!i&&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(hr,{}),e.jsx(mr,{}),e.jsx(at,{}),e.jsx(xr,{}),e.jsx(it,{}),o==="bullet"&&e.jsx(ot,{}),e.jsx(nt,{}),e.jsx(rt,{}),e.jsx(lt,{})]})})]})]})}function fr({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 i=o=>!o||o.length===0?"No conditions":o.map(d=>{var h,p,j,g;const u=`${(h=d.source)==null?void 0:h.entityName}.${(p=d.source)==null?void 0:p.name}`,m=`${(j=d.target)==null?void 0:j.entityName}.${(g=d.target)==null?void 0:g.name}`,x=d.operator||"=";return`${u} ${x} ${m}`}).join(" AND "),c=o=>!o.joinKeyGroups||o.joinKeyGroups.length===0?"No conditions defined":o.joinKeyGroups.length===1?i(o.joinKeyGroups[0].keys):o.joinKeyGroups.map((d,u)=>({id:u,operator:d.operator,condition:i(d.keys)}));return e.jsx(s.Card,{className:"border-blue-500/30 bg-blue-50/30 dark:bg-blue-950/20",children:e.jsxs("div",{className:"flex items-center justify-between p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xt,{className:"size-4 text-blue-600 dark:text-blue-400"}),e.jsx("h3",{className:"text-sm font-medium text-blue-900 dark:text-blue-100",children:"Auto-Resolved Joins"}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"secondary",className:"cursor-help bg-blue-100 text-xs text-blue-700 dark:bg-blue-900 dark:text-blue-300",children:l.length})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"max-w-md p-3",children:e.jsx("div",{className:"space-y-2",children:l.map((o,d)=>{const u=c(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(x=>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:x.condition}),x.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",x.operator,")"]})]},x.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 Ts={getItem(t){if(typeof window>"u")return null;try{return localStorage.getItem(t)}catch(a){return console.warn(`Failed to read from localStorage (${t}):`,a),null}},setItem(t,a){if(!(typeof window>"u"))try{localStorage.setItem(t,a)}catch(n){console.warn(`Failed to write to localStorage (${t}):`,n)}}};function gr({selectedChart:t,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:i,activeField:c}){var f,b;const[o,d]=S.useState(()=>Ts.getItem("chart-selector-expanded")==="true"),[u,m]=S.useState(!1),x=s.useEditorStore(N=>N.card),h=s.useEditorStore(N=>N.actions.updateCardConfig),p=n.length>0||r.length>0||l.length>0,{data:j,autoJoinMetadata:g}=s.useDashboardCardQuery(x),v=((f=x==null?void 0:x.config)==null?void 0:f.joinPlan)||(g!=null&&g.autoResolved?g.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),D=((b=x==null?void 0:x.dataSource)==null?void 0:b.selectedEntities)||[],k=N=>{h(x.id,{...x==null?void 0:x.config,joinPlan:N}),m(!1)},B=()=>{h(x.id,{...x==null?void 0:x.config,joinPlan:void 0}),m(!1)},L=()=>{m(!1)},E=()=>{m(!0)};S.useEffect(()=>{Ts.setItem("chart-selector-expanded",String(o))},[o]);const C=()=>{d(N=>!N)};return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col border-x border-border",children:[e.jsxs("div",{className:s.cn("px-6 pt-4",{"space-y-4":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(er,{selectedChart:t,onChartChange:a})}),e.jsx("div",{"data-content":"Chart Quick Selector",className:"flex items-center justify-center",children:e.jsx(ar,{selectedChart:t,onChartChange:a,isDropdownExpanded:o,onToggleDropdown:C})})]}),e.jsx("div",{className:s.cn("flex justify-end gap-2 px-6 py-6"),children:e.jsx("div",{className:s.cn("invisible flex gap-2",{visible:p||j}),children:e.jsx(Ze,{})})}),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(fr,{onEditJoins:E}),e.jsx(pr,{groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:i,activeField:c})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]}),e.jsx(We,{open:u,onOpenChange:m,joinPlan:v,availableDataSources:D,onSave:k,onCancel:L,onRemove:B,children:e.jsx("div",{})})]})}function jr({initialFilters:t,availableFields:a}={}){const[n,r]=S.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(E=>E.card.dataSource);const{columns:l,isLoading:i}=s.useColumns(),o=a||l||[],d={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=E=>{const C=f=>{if(f.id===E){const b=o[0]||d,N=s.getDataType(b.dataType)==="date";return{...f,conditions:[...f.conditions,{id:`condition-${Date.now()}`,field:b,operator:N?"between":"=",value:N?[]:""}]}}return{...f,groups:f.groups.map(C)}};r(C(n))},m=E=>{const C=f=>{if(f.id===E){const b=o[0]||d,N=s.getDataType(b.dataType)==="date";return{...f,groups:[...f.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:b,operator:N?"between":"=",value:N?[]:""}],groups:[]}]}}return{...f,groups:f.groups.map(C)}};r(C(n))},x=(E,C)=>{const f=b=>b.id===E?{...b,conditions:b.conditions.filter(N=>N.id!==C)}:{...b,groups:b.groups.map(f)};r(f(n))},h=(E,C)=>{const f=b=>b.id===E?{...b,groups:b.groups.filter(N=>N.id!==C)}:{...b,groups:b.groups.map(f)};r(f(n))},p=(E,C,f,b)=>{if(f==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const N=A=>A.id===E?{...A,conditions:A.conditions.map(w=>w.id===C?{...w,[f]:b}:w)}:{...A,groups:A.groups.map(N)};r(N(n))},j=(E,C,f)=>{const b=N=>N.id===E?{...N,conditions:N.conditions.map(A=>A.id===C?{...A,...f}:A)}:{...N,groups:N.groups.map(b)};r(b(n))},g=(E,C)=>{const f=b=>b.id===E?{...b,logicalOperator:C}:{...b,groups:b.groups.map(f)};r(f(n))},v=(E,C)=>{const f=b=>b.id===E?{...b,negate:C}:{...b,groups:b.groups.map(f)};r(f(n))},D=(E,C,f)=>{const b=N=>N.id===E?{...N,conditions:s.arrayMove(N.conditions,C,f)}:{...N,groups:N.groups.map(b)};r(b(n))},k=(E,C,f)=>{const b=N=>N.id===E?{...N,groups:s.arrayMove(N.groups,C,f)}:{...N,groups:N.groups.map(b)};r(b(n))},B=E=>{if(!E||E.conditions.length===0&&E.groups.length===0)return"-- No filters defined";const C=b=>{let N="";typeof b.field=="object"?N=b.field.entityName?`${b.field.entityName}.${b.field.name}`:b.field.name:N=String(b.field);const A=b.operator;let w=b.value;if(b.field.dataType==="string"&&!["in","not in"].includes(b.operator))typeof w=="string"?w=`'${w}'`:Array.isArray(w)&&(w=`'${w.join(", ")}'`);else if(b.field.dataType==="date"||b.field.dataType==="datetime"||b.field.dataType==="timestamp")if(b.operator==="between"&&Array.isArray(w)&&w.length===2){const P=w[0]?`'${w[0]}'`:"NULL",I=w[1]?`'${w[1]}'`:"NULL";return`${N} BETWEEN ${P} AND ${I}`}else if((b.operator==="in"||b.operator==="not in")&&Array.isArray(w)){const P=w.map(I=>I?`'${I}'`:"NULL").join(", ");return`${N} ${A} (${P})`}else typeof w=="string"||w instanceof Date?w=`'${w}'`:Array.isArray(w)&&w.length>0&&(w=`'${w[0]}'`);else if(["in","not in"].includes(b.operator)){let P=[];Array.isArray(w)?P=w.map(I=>typeof I=="string"?`'${I}'`:String(I)):typeof w=="string"?P=w.split(",").map(I=>{const T=I.trim();return b.field.dataType==="string"?`'${T}'`:T}):typeof w=="number"&&(P=[String(w)]),w=`(${P.join(", ")})`}switch(A){case"contains":return typeof w=="string"?`${N} LIKE '%${w.replace(/'/g,"")}'`:`${N} LIKE '%${String(w)}'`;case"startsWith":return typeof w=="string"?`${N} LIKE '${w.replace(/'/g,"")}%'`:`${N} LIKE '${String(w)}%'`;case"endsWith":return typeof w=="string"?`${N} LIKE '%${w.replace(/'/g,"")}'`:`${N} LIKE '%${String(w)}'`;case"isNull":return`${N} IS NULL`;case"isNotNull":return`${N} IS NOT NULL`;default:return`${N} ${A} ${w}`}},f=b=>{const N=b.conditions.map(C),A=b.groups.map(T=>f(T)),w=[...N,...A].filter(Boolean);if(w.length===0)return"";const P=w.join(` ${b.logicalOperator} `),I=w.length>1?`(${P})`:P;return b.negate?`NOT ${I}`:I};return f(E)},L=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:o,isLoading:i,addCondition:u,addGroup:m,removeCondition:x,removeGroup:h,updateCondition:p,updateConditionFields:j,updateGroupOperator:g,updateGroupNegate:v,reorderConditions:D,reorderGroups:k,generateSQLPreview:B,hasAnyFilters:L}}function br({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 vr=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"})}},yr=t=>{if(t.qualifiedEntityName){const a=t.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function Nr({value:t,onValueChange:a,availableFields:n,placeholder:r="Select field",className:l="w-64"}){const[i,c]=S.useState(!1),o=S.useMemo(()=>{const d={};return n.forEach(u=>{const m=yr(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:i,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:s.cn("justify-between",!t&&"text-muted-foreground",l),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(br,{children:[t.entityName,".",t.name]})}):r,e.jsx(yt,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(s.CommandEmpty,{children:"No fields found."}),e.jsx(s.CommandList,{className:"max-h-80",children:Object.entries(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,x])=>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:[vr(x[0].entityType),e.jsx("span",{children:x[0].entityName})]}),x.map((h,p)=>e.jsxs(s.CommandItem,{value:h.id,onSelect:()=>{a(h),c(!1)},className:"overflow-x-auto",children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",(t==null?void 0:t.id)===h.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:h.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:h.description&&e.jsx("span",{children:h.description})})]})]},h.id+p))]},`${d}-${m}`))},d))})]})})]})}function os(t){var g;const a=s.useEditorStore(v=>v.card),{authToken:n,tokenProps:r}=s.useSemaphorContext(),l=s.useEditorStore(v=>v.card.config),i=l==null?void 0:l.joinPlan,c={...t,alias:t.name,label:"value",role:"groupby"},o={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},d={...c,role:"sortby",direction:"asc"},u={joinPlan:i,groupByColumns:[c],metricColumns:[o],sortByColumns:[d]},m=((g=a.dataSource)==null?void 0:g.connectionId)||a.connectionId,{data:x,isPending:h,error:p}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular(`${r.apiServiceUrl}/v1/query`,(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:((x==null?void 0:x.records)||[]).map(v=>({label:v.value||"BLANK",value:v.value||"BLANK",count:(v==null?void 0:v.count)||0})),isPending:h,error:p}}function Cr({field:t,selected:a,onChange:n,placeholder:r="Select items...",className:l}){const[i,c]=He.useState(!1),{filterValues:o}=os(t),d=m=>{n(a.filter(x=>x!==m))},u=m=>{a.includes(m)?n(a.filter(x=>x!==m)):n([...a,m])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open:i,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":i,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 x=o.find(h=>h.value===m);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[x==null?void 0:x.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:h=>{h.key==="Enter"&&d(m)},onMouseDown:h=>{h.preventDefault(),h.stopPropagation()},onClick:h=>{h.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,x)=>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+x))})]})]})})]})})}function Sr({field:t,value:a,onChange:n,placeholder:r="Select value...",className:l}){const{filterValues:i,isPending:c,error:o}=os(t);return c?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):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:i.map((d,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+u))})]})}function wr({value:t,operator:a,onChange:n,className:r}){var d;const{tokenProps:l}=s.useSemaphorContext(),i=(d=l==null?void 0:l.params)==null?void 0:d.timeZone,c=S.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:c,onChange:o,timezone:i,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const Dr=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Tr=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],kr=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],Er=["=","!=","isNull","isNotNull"],Ir=["between","isNull","isNotNull"],Ar={"=":"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 ks(t){return Ar[t]||s.titleCase(t)}function Mr(t){switch(t){case"string":return Tr;case"number":return kr;case"boolean":return Er;case"date":return Ir;default:return Dr}}function ct({condition:t,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:i,onUpdateGroupOperator:c,availableFields:o,updateConditionFields:d}){const{attributes:u,listeners:m,setNodeRef:x,transform:h,transition:p,isDragging:j}=s.useSortable({id:t.id}),{isPending:g,error:v}=os(t.field),D={transform:s.CSS.Transform.toString(h),transition:p};return e.jsxs("div",{ref:x,style:D,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${j?"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=>c(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(Nr,{value:t.field,onValueChange:k=>{const B=k,L=s.getDataType(B.dataType)==="date";d(n,t.id,{field:B,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?ks(t.operator):""})}),e.jsx(s.SelectContent,{children:Mr(s.getDataType(t.field.dataType)).map(k=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:k,children:ks(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(Cr,{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(Sr,{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(wr,{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:()=>i(n,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function Lr({group:t,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:i,onUpdateCondition:c,onUpdateField:o,onRemoveCondition:d,onReorderConditions:u,onReorderGroups:m,onAddCondition:x,onAddGroup:h,availableFields:p,renderFilterGroup:j,updateConditionFields:g}){const{attributes:v,listeners:D,setNodeRef:k,transform:B,transition:L,isDragging:E}=s.useSortable({id:t.id}),C={transform:s.CSS.Transform.toString(B),transition:L},f=N=>{const{active:A,over:w}=N;if(w&&A.id!==w.id){const P=t.conditions.findIndex(T=>T.id===A.id),I=t.conditions.findIndex(T=>T.id===w.id);P!==-1&&I!==-1&&u(t.id,P,I)}},b=N=>{const{active:A,over:w}=N;if(w&&A.id!==w.id&&n){const P=t.groups.findIndex(T=>T.id===A.id),I=t.groups.findIndex(T=>T.id===w.id);P!==-1&&I!==-1&&m(n,P,I)}};return e.jsxs("div",{ref:k,style:C,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${E?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...v,...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:N=>r(t.id,N),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>n&&i(n,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:f,children:e.jsx(s.SortableContext,{items:t.conditions.map(N=>N.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((N,A)=>e.jsx(ct,{condition:N,index:A,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:o,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:p,updateConditionFields:g},N.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:b,children:e.jsx(s.SortableContext,{items:t.groups.map(N=>N.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(N=>j(N,a+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>x(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Fr({filters:t,availableFields:a,onSave:n,onClearAll:r,onCancel:l}){const{currentFilters:i,availableFields:c,isLoading:o,addCondition:d,addGroup:u,removeCondition:m,removeGroup:x,updateCondition:h,updateConditionFields:p,updateGroupOperator:j,updateGroupNegate:g,reorderConditions:v,reorderGroups:D,generateSQLPreview:k,hasAnyFilters:B,setCurrentFilters:L}=jr({initialFilters:t,availableFields:a}),E=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[C,f]=S.useState(!1),b=(w,P,I)=>{const T=y=>y.id===w?{...y,conditions:y.conditions.map(M=>M.id===P?{...M,field:I,dataType:I.dataType}:M)}:{...y,groups:y.groups.map(T)};L(T(i))},N=(w,P=0,I)=>P===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragEnd:T=>{const{active:y,over:M}=T;if(M&&y.id!==M.id){const F=w.conditions.findIndex($=>$.id===y.id),z=w.conditions.findIndex($=>$.id===M.id);F!==-1&&z!==-1&&v(w.id,F,z)}},children:e.jsx(s.SortableContext,{items:w.conditions.map(T=>T.id),strategy:s.verticalListSortingStrategy,children:w.conditions.map((T,y)=>e.jsx(ct,{condition:T,index:y,groupId:w.id,groupLogicalOperator:w.logicalOperator,onUpdateCondition:h,onUpdateField:b,onRemoveCondition:m,onUpdateGroupOperator:j,availableFields:c,updateConditionFields:p},T.id))})}),e.jsx(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragEnd:T=>{const{active:y,over:M}=T;if(M&&y.id!==M.id){const F=w.groups.findIndex($=>$.id===y.id),z=w.groups.findIndex($=>$.id===M.id);F!==-1&&z!==-1&&D(w.id,F,z)}},children:e.jsx(s.SortableContext,{items:w.groups.map(T=>T.id),strategy:s.verticalListSortingStrategy,children:w.groups.map(T=>N(T,P+1,w.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(w.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),C&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(w.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},w.id):e.jsx(Lr,{group:w,depth:P,parentGroupId:I,onUpdateGroupOperator:j,onUpdateGroupNegate:g,onRemoveGroup:x,onUpdateCondition:h,onUpdateField:b,onRemoveCondition:m,onReorderConditions:v,onReorderGroups:D,onAddCondition:d,onAddGroup:u,availableFields:c,renderFilterGroup:N,updateConditionFields:p},w.id),A=s.getFilterCount(t);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Card,{children:e.jsx(s.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[o?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):N(i),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{id:"advanced-mode",checked:C,onCheckedChange:w=>f(w)}),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)"})]})}),B&&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(i)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:l,children:"Cancel"}),A>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>n(B?i:null),children:"Apply Filters"})]})]})}function Pr({cardId:t,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:l,isOpen:i,onOpenChange:c}){const o=u=>{n(t,u),c(!1)},d=()=>{r(t),c(!1)};return e.jsxs(s.Dialog,{modal:!1,open:i,onOpenChange:c,children:[i&&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(Fr,{filters:a,availableFields:l,onSave:o,onCancel:()=>c(!1),onClearAll:d})]})]})}function Or({activeCardId:t,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var v,D;const[l,i]=S.useState(null),c=s.useEditorStore(k=>k.card),o=s.useEditorStore(k=>k.actions.updateCardConfig),d=(v=c==null?void 0:c.config)==null?void 0:v.joinPlan,u=(D=c==null?void 0:c.dataSource)==null?void 0:D.semanticDomainId,{data:m}=es(u),x=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],h=S.useCallback(k=>k.startsWith("card-")?null:k.startsWith("source-")||a.find(B=>B.id===k)?"source":n("groupBy").find(B=>B.id===k)?"groupBy":n("metrics").find(B=>B.id===k)?"metrics":n("pivotBy").find(B=>B.id===k)?"pivotBy":n("sortBy").find(B=>B.id===k)?"sortBy":null,[a,n]),p=S.useCallback(k=>{i(k.active.id)},[]),j=S.useCallback(k=>{var N;const{active:B,over:L}=k;if(!L||!t){i(null);return}const E=B.id,C=L.id,f=h(E),b=h(C)||C;if(b==="sortBy"){if(f==="source"){const A=a.find(P=>P.id===E);if(!A){i(null);return}if(!(n("groupBy").some(P=>P.name===A.name&&P.qualifiedEntityName===A.qualifiedEntityName)||n("metrics").some(P=>P.name===A.name&&P.qualifiedEntityName===A.qualifiedEntityName))){i(null);return}}else if(f==="pivotBy"){i(null);return}else if(f!=="groupBy"&&f!=="metrics"&&f!=="sortBy"){i(null);return}}if(f==="source"&&b==="sortBy"){const A=[...a].find(T=>T.id===E);if(!A){i(null);return}const w=n("sortBy");if(s.fieldAlreadyExists(A,w)){i(null);return}const P=Fe(A,"sortBy",c.type);if(!P.isValid){s.ue.error("Invalid Field Type",{description:P.reason,position:"top-center",duration:3e3}),i(null);return}const I=s.getNewField(A,"sortBy",w);i(null),r("sortBy",[...w,I]);return}if(f==="source"&&b!=="source"&&b!=="sortBy"){const A=[...a].find(M=>M.id===E);if(!A){i(null);return}const w=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(w.length>0){const M=w[0].qualifiedEntityName;if(!M){i(null);return}if(M!==A.qualifiedEntityName&&A.qualifiedEntityName)if(u&&(m!=null&&m.joinabilityMap)){if(s.calculateFieldState(A,{joinabilityMap:m.joinabilityMap,selectedFields:w,baseEntityName:(N=d==null?void 0:d.baseEntity)==null?void 0:N.name}).state==="unreachable"){s.showJoinRequiredNotification(),i(null);return}}else{if(!d){s.showJoinRequiredNotification(),i(null);return}if(!s.areEntitiesJoined(M,A.qualifiedEntityName,d)){s.showJoinRequiredNotification(),i(null);return}}}const P=n(b);if(s.fieldAlreadyExists(A,P)){i(null);return}const I=Fe(A,b,c.type);if(!I.isValid){s.ue.error("Invalid Field Type",{description:I.reason,position:"top-center",duration:3e3}),i(null);return}const T=s.getNewField(A,b,P),y=[...P,T];i(null),r(b,y),b==="metrics"&&t&&Qe(c.type,c.config,o,t,y);return}if(f&&b&&f!=="source"&&b!=="source"&&f!==b){const A=n(f),w=n(b),P=A.find(F=>F.id===E);if(!P){i(null);return}const I=Fe(P,b,c.type);if(!I.isValid){s.ue.error("Invalid Field Type",{description:I.reason,position:"top-center",duration:3e3}),i(null);return}const T=s.getNewField(P,b,w);if(i(null),b==="sortBy"){s.fieldAlreadyExists(P,w)||r(b,[...w,T]);return}const y=A.filter(F=>F.id!==E),M=[...w,T];r(f,y),r(b,M),b==="metrics"&&t&&Qe(c.type,c.config,o,t,M);return}if(f&&b&&f===b&&f!=="source"){const A=n(f),w=A.findIndex(I=>I.id===E),P=A.findIndex(I=>I.id===C);if(w!==P){const I=s.arrayMove(A,w,P);r(f,I)}}i(null)},[t,a,n,r,h,d,u,m,c.type,o,c.config]),g=l?x.find(k=>k.id===l):null;return{activeId:l,activeField:g,handleDragStart:p,handleDragEnd:j}}function Br({activeView:t,onViewChange:a,splitViewEnabled:n}){const r=s.useEditorStore(d=>d.card),{config:l}=S.useContext(s.SemaphorContext).tokenProps,i=(l==null?void 0:l.showInfoTab)!==!1,{errorMessage:c}=s.useDashboardCardQuery(r),o=()=>n?!1:!["table","pivotTable","aggregateTable"].includes(r.type);return e.jsx(s.Tabs,{value:t,onValueChange:d=>a(d),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-1 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),o()&&e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),r.type!=="kpi"&&i&&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 Rr=[{value:"10",label:"Top 10"},{value:"20",label:"Top 20"},{value:"50",label:"Top 50"},{value:"100",label:"Top 100"},{value:"200",label:"Top 200"},{value:"500",label:"Top 500"},{value:"1000",label:"Top 1000"}];function Vr(){var d,u;const t=s.useEditorStore(m=>m.card),{updateRowLimit:a}=s.useEditorActions(),[n,r]=S.useState(!1),[l,i]=S.useState(""),c=m=>{if(m==="custom"){r(!0);return}r(!1),a(t.id,parseInt(m))},o=m=>{const x=m.target.value;i(x),x&&!isNaN(parseInt(x))&&a(t.id,parseInt(x))};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:c,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(s.SelectValue,{placeholder:"Select limit"})}),e.jsx(s.SelectContent,{children:Rr.map(m=>e.jsx(s.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function zr({card:t,queryData:a,isLoading:n,isFetching:r,pagination:l,onPaginationChange:i,onSortChange:c,sortState:o,splitViewEnabled:d}){const u=S.useMemo(()=>(a==null?void 0:a.records)||[],[a==null?void 0:a.records]);return!d||["table","pivotTable","aggregateTable"].includes(t.type)?e.jsx(Ye,{}):e.jsxs(s.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(s.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:e.jsx(Ye,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{defaultSize:40,minSize:20,role:"results-section",className:"flex flex-col",children:e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:(a==null?void 0:a.records)&&e.jsx(s.TableVisual,{card:t,data:u,paginationMetadata:l,onPaginationChange:i,isLoading:n||r,onSortChange:c,sortState:o})})})]})}const Gr="semaphor-split-view-enabled";function $r(){return $e(Gr,!0)}function qr({isOpen:t,onClose:a}){const n=Ls(a,{enabled:t}),r=s.useEditorStore(m=>{var x;return((x=m.card.customCardPreferences)==null?void 0:x.url)||""}),l=s.useEditorStore(m=>m.card),i=s.useEditorStore(m=>{var x;return((x=m.card.customCardPreferences)==null?void 0:x.pluginChartType)||""}),c=s.useEditorStore(m=>{var x;return((x=m.card.customCardPreferences)==null?void 0:x.settings)||{}}),{data:o}=s.useDashboardCardQuery(l),{getCard:d}=s.useCustomVisual(r),u=S.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(S.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(o==null?void 0:o.records)||[],chartType:i,settings:c})})})]})})}function Ur({activeView:t,onViewChange:a,showDebug:n,onDebugToggle:r,onFiltersClick:l,activeCard:i,columns:c,columnsLoading:o,columnsError:d}){var Y,U,te;const u=s.useEditorStore(H=>H.card),m=s.useDashboardStore(H=>H.filterValues),{updateCardConfig:x,setCard:h,updateCardInFrame:p,setShowAIDialog:j}=s.useEditorActions(),g=s.useEditorStore(H=>H.showAIDialog),v=s.useDashboardStore(H=>H.isVisualEditing),[D,k]=S.useState(!1),[B,L]=S.useState(!1),[E,C]=S.useState(null),{config:f}=S.useContext(s.SemaphorContext).tokenProps,b=(f==null?void 0:f.showInfoTab)!==!1,[N,A]=$r(),w=s.useEditorStore(H=>{var re;return((re=H.card.customCardPreferences)==null?void 0:re.url)&&H.card.type==="custom"}),{data:P,errorMessage:I,isLoading:T,isFetching:y,errorSql:M,pagination:F,refetch:z,comparisonMetadata:$}=s.useDashboardCardQuery(i),O=S.useMemo(()=>(P==null?void 0:P.records)||[],[P==null?void 0:P.records]),[G,R]=S.useState(!1);S.useEffect(()=>{y||R(!1)},[y]);const _=()=>{const H=!N;H&&t==="table"&&a("chart"),A(H)},J=(H,re)=>{const ue={...i,paginationConfig:{page:H+1,pageSize:re}};h(ue),p(ue)};function se(){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(i.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",c.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:o?"Loading...":d?"Error loading columns":JSON.stringify(c.slice(0,5),null,2)})]})]})]})}const Z=H=>{if(!u.config)return;const re=s.sortStateToSortByColumns(H,u.config.metricColumns,u.config.groupByColumns);x(u.id,{...u.config,sortByColumns:re})},ae=S.useMemo(()=>{var H;return s.sortByColumnsToSortState((H=u.config)==null?void 0:H.sortByColumns)},[(Y=u.config)==null?void 0:Y.sortByColumns]);return e.jsxs("div",{className:s.cn("relative flex w-0 grow flex-col",{"border-l":g&&v}),children:[n&&se(),e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t==="chart"&&g&&e.jsx(Ws,{variant:"outline"}),e.jsx(Br,{activeView:t,onViewChange:a,splitViewEnabled:N}),e.jsx(s.FilterInfo,{cardId:i.id,cardFilters:(U=i.config)==null?void 0:U.filters,cardFilterCount:s.getFilterCount(((te=i.config)==null?void 0:te.filters)||null),onFiltersClick:l}),$&&e.jsx(s.ComparisonMetadataBadge,{metadata:$,variant:"compact"}),e.jsx("div",{className:"ml-2",children:e.jsx(Vr,{})}),g&&e.jsx(Ze,{})]}),e.jsxs("div",{className:s.cn("flex grow items-center justify-end gap-2"),children:[e.jsx(s.IconButton,{tooltip:"Refresh",disabled:T||y,onClick:()=>{R(!0),z()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":G})})}),t==="chart"&&e.jsx(s.IconButton,{tooltip:N?"Hide Results Table":"Show Results Table",onClick:_,children:N?e.jsx(It,{className:"size-4"}):e.jsx(_t,{className:"size-4"})}),t==="chart"&&e.jsx(Ys,{}),!g&&e.jsx(s.IconButton,{onClick:()=>j(!g),tooltip:"AI",className:"h-8","aria-label":"AI",children:e.jsx(s.Sparkles,{className:"size-4"})}),r&&s.isDevEnv]})]}),!D&&w&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>k(!0),className:"absolute right-5 top-1/2 z-40 size-10 -translate-y-1/2 rounded-full border border-border bg-background shadow-lg hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:e.jsx(s.Settings2,{className:"size-4"})}),e.jsxs("div",{className:"mt-3 flex min-h-0 grow flex-col",children:[t==="chart"&&e.jsx("div",{className:s.cn("flex grow flex-col pb-6",{"pb-0":N&&!["table","pivotTable","aggregateTable"].includes(i.type)}),children:e.jsx(zr,{card:i,queryData:P,isLoading:T,isFetching:y,pagination:F,onPaginationChange:J,onSortChange:Z,sortState:ae,splitViewEnabled:N})}),t==="table"&&(P==null?void 0:P.records)&&e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:e.jsx(s.TableVisual,{card:i,data:O,paginationMetadata:F,onPaginationChange:J,isLoading:T||y,onSortChange:Z,sortState:ae})}),t==="info"&&b&&e.jsx("div",{className:"flex min-h-0 flex-1 flex-col pb-6",children:e.jsx("div",{className:"flex min-h-0 flex-1 flex-col rounded-md bg-background px-6",children:I?e.jsx(as,{error:I,errorSql:M,onSendFeedback:()=>{const H=s.prepareFeedbackData(s.FeedbackCategory.QUERY_GENERATION,{cardConfig:u.config,dataSource:i.dataSource,dashboardFilters:m,errorMessage:I,errorSql:M,generatedSql:P==null?void 0:P.sql});C(H),L(!0)},onOpenInEditor:()=>{j(!0),setTimeout(()=>{const H=s.useEditorStore.getState().actions;H.setIsDevMode(!0),H.setCardSql(M||""),setTimeout(()=>{H.setRunSql(!0)},100)},100)}}):e.jsx(Ks,{sql:P==null?void 0:P.sql,error:I,errorSql:M})})})]}),e.jsx(qr,{isOpen:D,onClose:()=>k(!1)}),E&&e.jsx(s.FeedbackDialog,{open:B,onOpenChange:L,feedbackData:E})]})]})}function Kr({activeField:t}){const[a,n]=S.useState(!0);return S.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(ls,{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 _r=()=>{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 Hr(){var $,O;const[t,a]=S.useState("chart"),[n,r]=S.useState(!1),[l,i]=S.useState(!1),[c,o]=S.useState(!0),d=s.useEditorStore(G=>G.showAIDialog),u=s.useDashboardStore(G=>G.isVisualEditing),{setCardType:m}=s.useEditorActions(),x=s.useEditorStore(G=>G.card.type);S.useEffect(()=>_r(),[]);const h=G=>{m(G)},p=s.useEditorStore(G=>G.frame),j=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:B}=s.useEditorActions(),{columns:L=[],isLoading:E,error:C}=s.useColumns(),f=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),b=j,{getFieldsForContainer:N,setFieldsForContainer:A}=ss(b),{activeField:w,handleDragStart:P,handleDragEnd:I}=Or({activeCardId:p.activeCardId,sourceFields:L,getFieldsForContainer:N,setFieldsForContainer:A}),T=(G,R)=>{R&&B(G,R)},y=G=>{var R;D(G,{config:{...(R=p.cards.find(_=>_.id===G))==null?void 0:R.config,filters:void 0}})},M=L,F=G=>{if(!G)return 0;let R=G.conditions.length;return G.groups.forEach(_=>{R+=F(_)}),R},z=F((($=b==null?void 0:b.config)==null?void 0:$.filters)||null);return e.jsxs(s.DndContext,{sensors:f,collisionDetection:s.closestCenter,onDragStart:P,onDragEnd:I,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Us,{isVisible:c,onToggleVisibility:()=>o(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(gr,{selectedChart:x,onChartChange:h,groupByFields:N("groupBy"),pivotByFields:N("pivotBy"),metricsFields:N("metrics"),sortByFields:N("sortBy"),activeField:w}),e.jsx(Ur,{selectedChart:x,activeView:t,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onFiltersClick:()=>i(!0),filterCount:z,activeCard:b,dataSourceState:j.dataSource||s.EMPTY_DATA_SOURCE,columns:L,columnsLoading:E,columnsError:C,getFieldsForContainer:N,cards:p.cards,activeCardId:p.activeCardId,addCard:g,setActiveCard:k})]}),!c&&u&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>o(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),b&&e.jsx(Pr,{cardId:b.id,filters:((O=b.config)==null?void 0:O.filters)||null,onFiltersChange:T,onClearFilters:y,availableFields:M,isOpen:l,onOpenChange:i}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Kr,{activeField:w||null})})]})}function Jr({authToken:t,onSave:a,onClose:n}){const r=S.useRef(null),l=s.useEditorStore(C=>C.showAIDialog),i=s.useEditorStore(C=>C.isDevMode),c=s.useAssistantLayoutStore(C=>C.setFullscreen),o=s.useAssistantLayoutStore(C=>C.setPanelOpen),d=s.useAssistantLayoutStore(C=>C.setContainer),u=s.useAssistantPanel("editor"),m=s.useFullscreenAssistant(),x=s.useAssistantContainer("editor"),h=m==="editor",p=S.useCallback(C=>{d("editor",C)},[d]),{setAuthToken:j}=s.useDashboardActions(),{setShowAIDialog:g,setOnSave:v,setOnClose:D}=s.useEditorActions(),{setActiveAssistantType:k}=s.useAIActions();S.useEffect(()=>{a&&v(a),n&&D(n)},[a,v,n,D]),S.useEffect(()=>{t&&t.accessToken&&j(t)},[t,j]),S.useEffect(()=>{var C,f;l?((C=r.current)==null||C.resize(40),o("editor",!0),k("editor")):((f=r.current)==null||f.resize(0),o("editor",!1),m==="editor"&&c(null),k(null))},[l,o,k,c,m]);function B(C){C<1?(g(!1),o("editor",!1),m==="editor"&&c(null),k(null)):(l||(g(!0),k("editor")),u.isOpen||o("editor",!0))}function L(){return e.jsxs(e.Fragment,{children:[e.jsx(Us,{isVisible:!0,onToggleVisibility:()=>{}}),e.jsxs("div",{className:"relative flex grow border-l",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:s.cn("grow transition-opacity",h&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Qn,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:B,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Cs,{isFullscreen:h,onFullscreenChange:C=>c(C?"editor":null),fullscreenContainer:x})})})]}),e.jsx("div",{ref:p,className:s.cn("absolute inset-0",!h&&"pointer-events-none")})]})]})}function E(){return e.jsxs("div",{className:"relative flex h-full grow",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:s.cn("flex grow transition-opacity",h&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Hr,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:B,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Cs,{isFullscreen:h,onFullscreenChange:C=>c(C?"editor":null),fullscreenContainer:x})})})]}),e.jsx("div",{ref:p,className:s.cn("absolute inset-0",!h&&"pointer-events-none")})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:i?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:L()}):E()})}function Qr(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:a}=s.useDashboardStore(c=>c.actions),n=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function l(c){t&&(r(t,c),a(!1))}function i(){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(Jr,{onSave:l,onClose:i})})}function Wr(){qs();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:i}=s.useEditorActions(),c=s.useEditorStore(d=>d.card.dataSource);return S.useEffect(()=>{var u,m;let d=r();if(!d){const x=(u=n==null?void 0:n.sheets)==null?void 0:u.find(p=>p.id===t),h=(m=x==null?void 0:x.frames)==null?void 0:m[0];h&&(l(h.id),d=h)}if(d){const x=d.cards.find(h=>h.id===d.activeCardId);x&&i(x)}},[r,t,a,n,l,i]),{hasEntities:!!(c!=null&&c.selectedEntities&&c.selectedEntities.length>0)}}function Yr(){const t=s.useDashboardStore(n=>n.actions.setShowFilters),{hasEntities:a}=Wr();return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[e.jsx(s.Label,{className:"px-2 text-base",children:"Dashboard Filters"}),e.jsx(s.Button,{onClick:()=>t(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(s.Cross2Icon,{})})]}),!a&&e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-muted-foreground/50"}),e.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"No fields configured"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Please configure a data source for this card to enable filtering"})]}),a&&e.jsx("div",{className:"flex grow",children:e.jsx(s.DndContext,{collisionDetection:s.closestCenter,children:e.jsx(s.SortableContext,{items:[],strategy:s.verticalListSortingStrategy,children:e.jsx($s,{context:"filter"})})})})]})}function Xr(){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 Zr(){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(Xr,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Yr,{})})]})}function el(){const t=s.useDashboardStore(l=>l.dashboard),a=s.useDashboardStore(l=>l.actions.setDashboard),n=s.useDashboardStore(l=>l.showDashboardJSON),r=s.useDashboardStore(l=>l.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!n}),children:[e.jsxs(s.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(s.de,{onChange:l=>{if(l)try{JSON.parse(l),a(JSON.parse(l))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(t,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function dt(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4 py-2",children:[e.jsx("div",{className:"h-9 w-full rounded bg-muted animate-pulse"}),e.jsx("div",{className:"h-9 w-full rounded bg-muted animate-pulse"}),e.jsx("div",{className:"space-y-3 pt-2",children:[...Array(3)].map((t,a)=>e.jsxs("div",{className:"flex gap-3 animate-pulse",children:[e.jsx("div",{className:"h-8 w-8 rounded bg-muted flex-shrink-0"}),e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx("div",{className:"h-4 w-2/3 rounded bg-muted"}),e.jsx("div",{className:"h-3 w-4/5 rounded bg-muted"})]})]},a))})]})})}const sl=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 tl({visual:t,isDeleting:a,isDuplicating:n,onAddVisual:r,onOpenVisual:l,onEditDetails:i,onDeleteClick:c,onDuplicateVisual:o,onShareVisual:d,formatDate:u}){var E,C,f,b;const{selectVisual:m}=s.useManagementActions(),x=s.useIsVisualSelected(t.id),h=sl(t.id),{isConsoleMode:p}=s.useDashboardPreferences(),j=S.useRef(null),[g,v]=S.useState(!1),[D,k]=S.useState(!1);S.useEffect(()=>{n?(v(!0),k(!0)):D&&(v(!1),k(!1))},[n,D]),S.useEffect(()=>{h&&j.current&&j.current.scrollIntoView({behavior:"smooth",block:"center"})},[h]);const B=()=>e.jsx(s.Grid3x3,{className:"h-4 w-4"}),L=()=>{m(t),l==null||l(t)};return e.jsx(s.Card,{ref:j,className:s.cn("group cursor-pointer border border-border/50 p-3 transition-colors hover:bg-accent/50",h?"border-purple-500":x&&"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:B()}),e.jsxs("div",{className:"min-w-0 flex-1 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium text-foreground truncate",title:t.title||"Untitled Visual",children:t.title||"Untitled Visual"}),t.ownership.status==="shared"&&e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:[e.jsx(s.Users,{className:"mr-1 h-2.5 w-2.5"}),"Shared"]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 flex-1",title:t.description||"No description",children:(E=t.description)!=null&&E.trim()?t.description:"No description"}),e.jsxs("div",{className:s.cn("invisible flex flex-shrink-0 items-center gap-1 transition-opacity duration-150 group-hover:visible",x&&"visible"),onClick:N=>N.stopPropagation(),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:N=>{N.stopPropagation(),r(t)},title:"Add to dashboard",children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),t.ownership.isOwner&&e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:N=>{N.stopPropagation(),i==null||i(t)},title:"Edit details",children:e.jsx(s.PenLine,{className:"h-3 w-3"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:g,onOpenChange:v,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),r(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),l==null||l(t)},children:[e.jsx(Et,{className:"mr-2 h-3 w-3"}),"Open"]}),e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.preventDefault(),N.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:N=>{N.stopPropagation(),i==null||i(t)},children:[e.jsx(s.PenLine,{className:"mr-2 h-3 w-3"}),"Edit details"]}),e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),d(t)},children:[e.jsx(s.Users,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),c(t)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((C=t.ownership.createdBy)==null?void 0:C.type)==="tenant"||((f=t.ownership.createdBy)==null?void 0:f.type)==="organization"&&p)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.User,{className:"h-3 w-3"}),e.jsx("span",{children:((b=t.ownership.createdBy)==null?void 0:b.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 al({open:t,onOpenChange:a,onSubmit:n,isCreating:r}){const[l,i]=S.useState(""),[c,o]=S.useState("");S.useEffect(()=>{t||(i(""),o(""))},[t]);const d=()=>{l.trim()&&n({title:l,description:c})},u=m=>{a(m)};return e.jsx(s.Dialog,{open:t,onOpenChange:u,children:e.jsxs(s.DialogContent,{children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create New Visual"}),e.jsx(s.DialogDescription,{children:"Add a new visual to your library. You can configure it after creation."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",children:"Visual Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:l,onChange:m=>i(m.target.value),disabled:r,onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),d())}})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter visual description...",value:c,onChange:m=>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 nl(){const[t,a]=S.useState(""),[n,r]=S.useState(!1),[l,i]=S.useState(!1),[c,o]=S.useState(null),[d,u]=S.useState(!1),[m,x]=S.useState(null),[h,p]=S.useState(null),[j,g]=S.useState(null),{selectVisual:v}=s.useManagementActions(),{handleEditLibraryVisual:D,handleAddLibraryVisual:k}=Te(),{resources:B,isLoading:L,isError:E,createResource:C,updateResource:f,deleteResource:b,duplicateResource:N,isCreating:A,isDeleting:w}=s.useVisualManagement(()=>{u(!1),x(null)},U=>{r(!1),U&&(v(U),D(U))});s.useCurrentUserInfo();const P=B.filter(U=>{var te,H;return((te=U==null?void 0:U.title)==null?void 0:te.toLowerCase().includes(t.toLowerCase()))||((H=U==null?void 0:U.description)==null?void 0:H.toLowerCase().includes(t.toLowerCase()))}),I=U=>new Date(U).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),T=U=>{C({title:U.title,description:U.description,isPrivate:!1})},y=U=>{x(U),u(!0)},M=()=>{m&&b(m.id)},{startUpdating:F,stopUpdating:z,isUpdating:$}=s.useResourceUpdateState(),O=(U,te,H)=>{var q;const re=Object.fromEntries(Object.entries(te).filter(([,W])=>W!==void 0));if(Object.keys(re).length===0){(q=H==null?void 0:H.onSuccess)==null||q.call(H);return}const ue=Object.keys(re),me=ue.length===1?ue[0]:void 0;F(U,me),f({resourceId:U,data:re},{onSuccess:()=>{var W;z(U,me),(W=H==null?void 0:H.onSuccess)==null||W.call(H)},onError:()=>{var W;z(U,me),(W=H==null?void 0:H.onError)==null||W.call(H)}})},G=U=>{p(U),N(U,{onSettled:()=>p(null)})},R=U=>{D(U)},_=U=>{k(U)},J=U=>{const te=B.find(H=>H.id===U);te&&f({resourceId:U,data:{isPrivate:!te.isPrivate}})},se=U=>{o(U),i(!0)},Z=U=>{g(U)},ae=()=>{g(null)},Y=({title:U,description:te})=>{if(!j)return;const H={};U!==j.title&&(H.title=U),(j.description||"")!==te&&(H.description=te),O(j.id,H,{onSuccess:()=>{g(null)}})};return L?e.jsx(dt,{}):E?e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load visuals"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]})}):e.jsxs("div",{className:"relative flex h-full flex-1 flex-col gap-4",children:[B&&B.length>5&&e.jsx("div",{className:"space-y-2",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:t,onChange:U=>a(U.target.value),className:"h-9"})}),e.jsx("div",{className:"flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-3 overflow-y-auto",children:P.length===0?e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"mb-3",children:e.jsx(s.Grid3x3,{className:"mx-auto h-12 w-12 text-muted-foreground/50"})}),e.jsx("h3",{className:"mb-1 font-medium text-foreground",children:t?"No visuals found":"No visuals yet"}),e.jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:t?"Try adjusting your search":"Create your first visual component to get started"}),!t&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>r(!0),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Create Visual"]})]}):P.map(U=>e.jsx(tl,{visual:U,onAddVisual:_,onOpenVisual:R,onEditDetails:Z,onDeleteClick:y,onDuplicateVisual:G,onTogglePrivacy:J,onShareVisual:se,isDeleting:w,isDuplicating:h===U.id,formatDate:I},U.id))})}),l&&c&&e.jsx(s.ShareDialog,{resource:c,resourceType:s.ResourceType.VISUAL,onClose:()=>{i(!1),o(null)}}),j&&e.jsx(s.ResourceEditDialog,{open:!!j,resourceLabel:"Visual",initialTitle:j.title||"",initialDescription:j.description||"",onClose:ae,onSave:Y,isSaving:$(j.id)}),e.jsx(s.AlertDialog,{open:d,onOpenChange:U=>{!U&&w||(u(U),U||x(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:w,children:"Cancel"}),e.jsxs(s.AlertDialogAction,{onClick:U=>{U.preventDefault(),U.stopPropagation(),M()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:w,children:[w?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"}),w?"Deleting...":"Delete"]})]})]})}),e.jsx(al,{open:n,onOpenChange:r,onSubmit:T,isCreating:A}),e.jsx(s.Button,{size:"icon",className:"absolute bottom-2 left-2 h-11 w-11 rounded-full shadow-lg shadow-black/15",onClick:()=>r(!0),"aria-label":"Create visual",children:e.jsx(s.Plus,{className:"h-5 w-5"})})]})}function rl({dashboard:t,isDeleting:a,isDuplicating:n,onLoadDashboard:r,onEditDetails:l,onDeleteClick:i,onDuplicateDashboard:c,onShareDashboard:o,formatDate:d,onDashboardItemClick:u}){var k,B;const{selectDashboard:m}=s.useManagementActions(),x=s.useIsDashboardSelected(t.id),{userContext:h,isLoading:p}=s.useCurrentUserInfo(),j=((k=h==null?void 0:h.permissions)==null?void 0:k.canEdit)??!1,g=p||!j,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",x&&"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:"min-w-0 flex-1 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium text-foreground truncate",title:t.title||"Untitled Dashboard",children:t.title||"Untitled Dashboard"}),t.ownership.status==="shared"&&e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:[e.jsx(s.Users,{className:"mr-1 h-2.5 w-2.5"}),"Shared"]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 flex-1",title:t.description||"No description",children:(B=t.description)!=null&&B.trim()?t.description:"No description"}),e.jsx(s.DashboardActionsMenu,{dashboard:t,isDeleting:a,isDuplicating:n,shouldHideActions:g,onEditDetails:l,onDeleteClick:i,onDuplicateDashboard:c,onShareDashboard:o,formatDate:d})]})]})]})},t.id)}function ll({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 ol(t){var ce;const{onLoadDashboard:a,onEditDashboard:n,onDashboardItemClick:r}=t,[l,i]=S.useState(""),[c,o]=S.useState(!1),[d,u]=S.useState(!1),[m,x]=S.useState(null),[h,p]=S.useState(!1),[j,g]=S.useState(null),[v,D]=S.useState(null),[k,B]=S.useState(null),L=s.useManagementStore(V=>V.lastSelectedDashboard),E=s.useManagementStore(V=>V.selectedDashboard),C=s.useManagementStore(V=>V.actions.selectDashboard),f=s.useManagementStore(V=>V.actions.clearSelectedDashboard),{tokenProps:b,id:N}=s.useSemaphorContext();s.useRoleAwareDisplayPreferences();const{onCreateSuccess:A}=s.useDashboardCreation({onDashboardSelect:r}),{resources:w,isLoading:P,isError:I,createResource:T,updateResource:y,deleteResource:M,duplicateResource:F,isCreating:z,isDeleting:$,refetch:O}=s.useDashboardManagement(()=>{p(!1);const V=j==null?void 0:j.id;g(null),(E==null?void 0:E.id)===V&&(!(b!=null&&b.dashboard_id)&&!N?f():L&&L.id!==V&&C(L))},V=>{o(!1),A(V,O)}),{currentUser:G,userContext:R}=s.useCurrentUserInfo(),_=((ce=R==null?void 0:R.permissions)==null?void 0:ce.canCreateDashboard)??!1,J=w.filter(V=>{var ee,X;return((ee=V==null?void 0:V.title)==null?void 0:ee.toLowerCase().includes(l.toLowerCase()))||((X=V==null?void 0:V.description)==null?void 0:X.toLowerCase().includes(l.toLowerCase()))}),se=V=>new Date(V).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),Z=V=>{T({title:V.title,description:V.description,isPrivate:!1})},ae=V=>{a==null||a(V)},Y=V=>{g(V),p(!0)},U=()=>{j&&M(j.id)},te=V=>{D(V),F(V,{onSettled:()=>D(null)})},{startUpdating:H,stopUpdating:re,isUpdating:ue}=s.useResourceUpdateState(),me=(V,ee,X)=>{var ve;const je=Object.fromEntries(Object.entries(ee).filter(([,he])=>he!==void 0));if(Object.keys(je).length===0){(ve=X==null?void 0:X.onSuccess)==null||ve.call(X);return}const ge=Object.keys(je),be=ge.length===1?ge[0]:void 0;H(V,be),y({resourceId:V,data:je},{onSuccess:()=>{var he;re(V,be),(he=X==null?void 0:X.onSuccess)==null||he.call(X)},onError:()=>{var he;re(V,be),(he=X==null?void 0:X.onError)==null||he.call(X)}})},q=V=>{const ee=w.find(X=>X.id===V);ee&&y({resourceId:V,data:{isPrivate:!ee.isPrivate}})},W=V=>{x(V),G==null||G.type,u(!0)},de=V=>{n==null||n(V.id),B(V)},pe=()=>{B(null)},fe=({title:V,description:ee})=>{if(!k)return;const X={};V!==k.title&&(X.title=V),(k.description||"")!==ee&&(X.description=ee),me(k.id,X,{onSuccess:()=>{B(null)}})};return P?e.jsx(dt,{}):I?e.jsx(ll,{onRetry:()=>window.location.reload()}):e.jsxs("div",{className:"relative flex h-full flex-1 flex-col gap-4",children:[w&&w.length>5&&e.jsx("div",{className:"space-y-2",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:l,onChange:V=>i(V.target.value),className:"h-9"})}),e.jsx("div",{className:"flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-3 overflow-y-auto",children:J.length===0?e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"mb-3",children:e.jsx(s.ChartColumn,{className:"mx-auto h-12 w-12 text-muted-foreground/50"})}),e.jsx("h3",{className:"mb-1 font-medium text-foreground",children:l?"No dashboards found":"No dashboards yet"}),e.jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:l?"Try adjusting your search":_?"Create your first dashboard to get started":"No dashboards have been shared with you yet"}),_&&!l&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>o(!0),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Create Dashboard"]})]}):J.map(V=>e.jsx(rl,{dashboard:V,isDeleting:$,isDuplicating:v===V.id,onLoadDashboard:ae,onEditDetails:de,onDeleteClick:Y,onDuplicateDashboard:te,onTogglePrivacy:q,onShareDashboard:W,formatDate:se,onDashboardItemClick:r},V.id))})}),d&&m&&e.jsx(s.ShareDialog,{resource:m,resourceType:s.ResourceType.DASHBOARD,onClose:()=>{u(!1),x(null)}}),e.jsx(s.AlertDialog,{open:h,onOpenChange:V=>{!V&&$||(p(V),V||g(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Dashboard"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',j==null?void 0:j.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:$,children:"Cancel"}),e.jsxs(s.AlertDialogAction,{onClick:V=>{V.preventDefault(),V.stopPropagation(),U()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:$,children:[$?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"}),$?"Deleting...":"Delete"]})]})]})}),k&&e.jsx(s.ResourceEditDialog,{open:!!k,resourceLabel:"Dashboard",initialTitle:k.title||"",initialDescription:k.description||"",onClose:pe,onSave:fe,isSaving:ue(k.id)}),e.jsx(s.CreateDashboardDialog,{open:c,onOpenChange:o,onSubmit:Z,isCreating:z}),_&&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 ut({isOpen:t,onClose:a,className:n,onDashboardItemClick:r,variant:l="inline"}){s.useDashboardStore(C=>C.dashboard);const i=s.useDashboardStore(C=>C.isDashboardEditing),{setDashboard:c,addSheet:o}=s.useDashboardStore(C=>C.actions),{currentUser:d}=s.useCurrentUserInfo(),u=d,{permissions:m}=s.useRoleAwareDisplayPreferences(),h=s.useSelectedDashboard()&&m.canAccessVisuals&&i,p="dashboards",[j,g]=$e("resource-management-active-tab",p),v=h?j:"dashboards",D=l==="overlay",k=Ls(a,{enabled:t&&D}),B=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=C=>{},E=C=>{console.log("Editing dashboard:",C)};return e.jsx(s.TooltipProvider,{children:(!D||t)&&e.jsxs("div",{ref:k,className:B,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(qt,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:v,onValueChange:h?g:void 0,className:"flex h-9 grow flex-col",children:[h&&e.jsx("div",{className:"px-4 pt-4",children:e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"dashboards",className:"text-sm",children:"Dashboards"}),e.jsx(s.TabsTrigger,{value:"visuals",className:"text-sm",children:"Visuals"})]})}),e.jsx(s.TabsContent,{value:"dashboards",className:"flex-1 px-4 py-4",children:e.jsx(ol,{onLoadDashboard:L,onEditDashboard:E,onDashboardItemClick:r})}),h&&e.jsx(s.TabsContent,{value:"visuals",className:"flex-1 px-4 py-4",children:e.jsx(nl,{})})]})})]})})}function il({showControls:t=!1,showFooter:a=!0,...n}){const r=s.useDashboardStore(h=>h.isDashboardPanelOpen);s.useDashboardStore(h=>h.isVisualEditing);const l=s.useDashboardStore(h=>h.actions.setIsDashboardPanelOpen),i=20,c=20,o=30,d=r,u=S.useRef(null),m=S.useRef(null);S.useEffect(()=>{u.current&&m.current&&(r?(u.current.resize(i),m.current.resize(100-i)):(u.current.resize(0),m.current.resize(100)))},[r]);const{preferences:x}=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:x,children:[e.jsx(el,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx(Aa,{}),e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",className:"flex grow overflow-hidden",children:[e.jsx(s.ResizablePanel,{ref:u,className:s.cn("flex h-full max-w-[26rem] overflow-hidden",{"min-w-[20rem]":d}),defaultSize:d?i:0,minSize:d?c:0,maxSize:d?o:0,children:e.jsx(ut,{isOpen:r,onClose:()=>l(!1),variant:"inline"})}),e.jsx(s.ResizableHandle,{className:s.cn("",{"w-0":!d})}),e.jsx(s.ResizablePanel,{ref:m,className:"flex min-w-0 flex-1",defaultSize:d?100-i:100,minSize:d?40:100,children:e.jsxs(s.Container,{...n,type:"dashboard",children:[e.jsx(Qr,{}),e.jsx(Zr,{})]})})]})]})]})})]})})}exports.AdvancedModeToggle=Rs;exports.DashboardPlus=il;exports.ResourceManagementPanel=ut;exports.ScheduleDashboard=Ps;exports.VisualEditingControls=Bs;exports.cleanCard=Fs;exports.getDashbaordStateWithoutData=ze;
|