react-semaphor 0.0.649 → 0.0.650
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-CU1YgreA.js → dashboard-plus-CT4SjADf.js} +2621 -2587
- package/dist/chunks/{dashboard-plus-BntME0Se.js → dashboard-plus-Shu1bSZp.js} +55 -55
- package/dist/chunks/{index-nzz4Yesh.js → index-CXH9-8g3.js} +19 -18
- package/dist/chunks/{index-B4kBqCrB.js → index-zINpyDRz.js} +95 -95
- 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/main.d.ts +1 -1
- package/dist/types/surfboard.d.ts +1 -1
- package/package.json +1 -1
|
@@ -1,49 +1,49 @@
|
|
|
1
|
-
"use strict";const e=require("react/jsx-runtime"),s=require("./index-
|
|
1
|
+
"use strict";const e=require("react/jsx-runtime"),s=require("./index-zINpyDRz.js"),A=require("react");require("react-dom");function ea(t){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const a in t)if(a!=="default"){const r=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:()=>t[a]})}}return n.default=t,Object.freeze(n)}const Ee=ea(A);/**
|
|
2
2
|
* @license lucide-react v0.453.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
5
5
|
* See the LICENSE file in the root directory of this source tree.
|
|
6
|
-
*/const
|
|
6
|
+
*/const sa=s.createLucideIcon("ArrowDown10",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M17 10V4h-2",key:"zcsr5x"}],["path",{d:"M15 10h4",key:"id2lce"}],["rect",{x:"15",y:"14",width:"4",height:"6",ry:"2",key:"33xykx"}]]);/**
|
|
7
7
|
* @license lucide-react v0.453.0 - ISC
|
|
8
8
|
*
|
|
9
9
|
* This source code is licensed under the ISC license.
|
|
10
10
|
* See the LICENSE file in the root directory of this source tree.
|
|
11
|
-
*/const
|
|
11
|
+
*/const ta=s.createLucideIcon("ArrowDownZA",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M15 4h5l-5 6h5",key:"8asdl1"}],["path",{d:"M15 20v-3.5a2.5 2.5 0 0 1 5 0V20",key:"r6l5cz"}],["path",{d:"M20 18h-5",key:"18j1r2"}]]);/**
|
|
12
12
|
* @license lucide-react v0.453.0 - ISC
|
|
13
13
|
*
|
|
14
14
|
* This source code is licensed under the ISC license.
|
|
15
15
|
* See the LICENSE file in the root directory of this source tree.
|
|
16
|
-
*/const
|
|
16
|
+
*/const aa=s.createLucideIcon("ArrowLeftRight",[["path",{d:"M8 3 4 7l4 4",key:"9rb6wj"}],["path",{d:"M4 7h16",key:"6tx8e3"}],["path",{d:"m16 21 4-4-4-4",key:"siv7j2"}],["path",{d:"M20 17H4",key:"h6l3hr"}]]);/**
|
|
17
17
|
* @license lucide-react v0.453.0 - ISC
|
|
18
18
|
*
|
|
19
19
|
* This source code is licensed under the ISC license.
|
|
20
20
|
* See the LICENSE file in the root directory of this source tree.
|
|
21
|
-
*/const
|
|
21
|
+
*/const na=s.createLucideIcon("ArrowUp01",[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["rect",{x:"15",y:"4",width:"4",height:"6",ry:"2",key:"1bwicg"}],["path",{d:"M17 20v-6h-2",key:"1qp1so"}],["path",{d:"M15 20h4",key:"1j968p"}]]);/**
|
|
22
22
|
* @license lucide-react v0.453.0 - ISC
|
|
23
23
|
*
|
|
24
24
|
* This source code is licensed under the ISC license.
|
|
25
25
|
* See the LICENSE file in the root directory of this source tree.
|
|
26
|
-
*/const
|
|
26
|
+
*/const ra=s.createLucideIcon("ArrowUpAZ",[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M20 8h-5",key:"1vsyxs"}],["path",{d:"M15 10V6.5a2.5 2.5 0 0 1 5 0V10",key:"ag13bf"}],["path",{d:"M15 14h5l-5 6h5",key:"ur5jdg"}]]);/**
|
|
27
27
|
* @license lucide-react v0.453.0 - ISC
|
|
28
28
|
*
|
|
29
29
|
* This source code is licensed under the ISC license.
|
|
30
30
|
* See the LICENSE file in the root directory of this source tree.
|
|
31
|
-
*/const
|
|
31
|
+
*/const la=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"}]]);/**
|
|
32
32
|
* @license lucide-react v0.453.0 - ISC
|
|
33
33
|
*
|
|
34
34
|
* This source code is licensed under the ISC license.
|
|
35
35
|
* See the LICENSE file in the root directory of this source tree.
|
|
36
|
-
*/const
|
|
36
|
+
*/const oa=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"}]]);/**
|
|
37
37
|
* @license lucide-react v0.453.0 - ISC
|
|
38
38
|
*
|
|
39
39
|
* This source code is licensed under the ISC license.
|
|
40
40
|
* See the LICENSE file in the root directory of this source tree.
|
|
41
|
-
*/const
|
|
41
|
+
*/const ia=s.createLucideIcon("Box",[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]]);/**
|
|
42
42
|
* @license lucide-react v0.453.0 - ISC
|
|
43
43
|
*
|
|
44
44
|
* This source code is licensed under the ISC license.
|
|
45
45
|
* See the LICENSE file in the root directory of this source tree.
|
|
46
|
-
*/const
|
|
46
|
+
*/const ca=s.createLucideIcon("Braces",[["path",{d:"M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1",key:"ezmyqa"}],["path",{d:"M16 21h1a2 2 0 0 0 2-2v-5c0-1.1.9-2 2-2a2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1",key:"e1hn23"}]]);/**
|
|
47
47
|
* @license lucide-react v0.453.0 - ISC
|
|
48
48
|
*
|
|
49
49
|
* This source code is licensed under the ISC license.
|
|
@@ -58,12 +58,12 @@
|
|
|
58
58
|
*
|
|
59
59
|
* This source code is licensed under the ISC license.
|
|
60
60
|
* See the LICENSE file in the root directory of this source tree.
|
|
61
|
-
*/const
|
|
61
|
+
*/const da=s.createLucideIcon("CircleCheckBig",[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]);/**
|
|
62
62
|
* @license lucide-react v0.453.0 - ISC
|
|
63
63
|
*
|
|
64
64
|
* This source code is licensed under the ISC license.
|
|
65
65
|
* See the LICENSE file in the root directory of this source tree.
|
|
66
|
-
*/const
|
|
66
|
+
*/const ua=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"}]]);/**
|
|
67
67
|
* @license lucide-react v0.453.0 - ISC
|
|
68
68
|
*
|
|
69
69
|
* This source code is licensed under the ISC license.
|
|
@@ -73,17 +73,17 @@
|
|
|
73
73
|
*
|
|
74
74
|
* This source code is licensed under the ISC license.
|
|
75
75
|
* See the LICENSE file in the root directory of this source tree.
|
|
76
|
-
*/const
|
|
76
|
+
*/const ma=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"}]]);/**
|
|
77
77
|
* @license lucide-react v0.453.0 - ISC
|
|
78
78
|
*
|
|
79
79
|
* This source code is licensed under the ISC license.
|
|
80
80
|
* See the LICENSE file in the root directory of this source tree.
|
|
81
|
-
*/const
|
|
81
|
+
*/const ha=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"}]]);/**
|
|
82
82
|
* @license lucide-react v0.453.0 - ISC
|
|
83
83
|
*
|
|
84
84
|
* This source code is licensed under the ISC license.
|
|
85
85
|
* See the LICENSE file in the root directory of this source tree.
|
|
86
|
-
*/const
|
|
86
|
+
*/const xa=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"}]]);/**
|
|
87
87
|
* @license lucide-react v0.453.0 - ISC
|
|
88
88
|
*
|
|
89
89
|
* This source code is licensed under the ISC license.
|
|
@@ -93,32 +93,32 @@
|
|
|
93
93
|
*
|
|
94
94
|
* This source code is licensed under the ISC license.
|
|
95
95
|
* See the LICENSE file in the root directory of this source tree.
|
|
96
|
-
*/const
|
|
96
|
+
*/const pa=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"}]]);/**
|
|
97
97
|
* @license lucide-react v0.453.0 - ISC
|
|
98
98
|
*
|
|
99
99
|
* This source code is licensed under the ISC license.
|
|
100
100
|
* See the LICENSE file in the root directory of this source tree.
|
|
101
|
-
*/const
|
|
101
|
+
*/const fa=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"}]]);/**
|
|
102
102
|
* @license lucide-react v0.453.0 - ISC
|
|
103
103
|
*
|
|
104
104
|
* This source code is licensed under the ISC license.
|
|
105
105
|
* See the LICENSE file in the root directory of this source tree.
|
|
106
|
-
*/const
|
|
106
|
+
*/const ga=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"}]]);/**
|
|
107
107
|
* @license lucide-react v0.453.0 - ISC
|
|
108
108
|
*
|
|
109
109
|
* This source code is licensed under the ISC license.
|
|
110
110
|
* See the LICENSE file in the root directory of this source tree.
|
|
111
|
-
*/const
|
|
111
|
+
*/const ja=s.createLucideIcon("Fingerprint",[["path",{d:"M12 10a2 2 0 0 0-2 2c0 1.02-.1 2.51-.26 4",key:"1nerag"}],["path",{d:"M14 13.12c0 2.38 0 6.38-1 8.88",key:"o46ks0"}],["path",{d:"M17.29 21.02c.12-.6.43-2.3.5-3.02",key:"ptglia"}],["path",{d:"M2 12a10 10 0 0 1 18-6",key:"ydlgp0"}],["path",{d:"M2 16h.01",key:"1gqxmh"}],["path",{d:"M21.8 16c.2-2 .131-5.354 0-6",key:"drycrb"}],["path",{d:"M5 19.5C5.5 18 6 15 6 12a6 6 0 0 1 .34-2",key:"1tidbn"}],["path",{d:"M8.65 22c.21-.66.45-1.32.57-2",key:"13wd9y"}],["path",{d:"M9 6.8a6 6 0 0 1 9 5.2v2",key:"1fr1j5"}]]);/**
|
|
112
112
|
* @license lucide-react v0.453.0 - ISC
|
|
113
113
|
*
|
|
114
114
|
* This source code is licensed under the ISC license.
|
|
115
115
|
* See the LICENSE file in the root directory of this source tree.
|
|
116
|
-
*/const
|
|
116
|
+
*/const ba=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"}]]);/**
|
|
117
117
|
* @license lucide-react v0.453.0 - ISC
|
|
118
118
|
*
|
|
119
119
|
* This source code is licensed under the ISC license.
|
|
120
120
|
* See the LICENSE file in the root directory of this source tree.
|
|
121
|
-
*/const
|
|
121
|
+
*/const va=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"}]]);/**
|
|
122
122
|
* @license lucide-react v0.453.0 - ISC
|
|
123
123
|
*
|
|
124
124
|
* This source code is licensed under the ISC license.
|
|
@@ -128,7 +128,7 @@
|
|
|
128
128
|
*
|
|
129
129
|
* This source code is licensed under the ISC license.
|
|
130
130
|
* See the LICENSE file in the root directory of this source tree.
|
|
131
|
-
*/const
|
|
131
|
+
*/const ya=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"}]]);/**
|
|
132
132
|
* @license lucide-react v0.453.0 - ISC
|
|
133
133
|
*
|
|
134
134
|
* This source code is licensed under the ISC license.
|
|
@@ -138,27 +138,27 @@
|
|
|
138
138
|
*
|
|
139
139
|
* This source code is licensed under the ISC license.
|
|
140
140
|
* See the LICENSE file in the root directory of this source tree.
|
|
141
|
-
*/const
|
|
141
|
+
*/const Na=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"}]]);/**
|
|
142
142
|
* @license lucide-react v0.453.0 - ISC
|
|
143
143
|
*
|
|
144
144
|
* This source code is licensed under the ISC license.
|
|
145
145
|
* See the LICENSE file in the root directory of this source tree.
|
|
146
|
-
*/const
|
|
146
|
+
*/const Ca=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"}]]);/**
|
|
147
147
|
* @license lucide-react v0.453.0 - ISC
|
|
148
148
|
*
|
|
149
149
|
* This source code is licensed under the ISC license.
|
|
150
150
|
* See the LICENSE file in the root directory of this source tree.
|
|
151
|
-
*/const
|
|
151
|
+
*/const Sa=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"}]]);/**
|
|
152
152
|
* @license lucide-react v0.453.0 - ISC
|
|
153
153
|
*
|
|
154
154
|
* This source code is licensed under the ISC license.
|
|
155
155
|
* See the LICENSE file in the root directory of this source tree.
|
|
156
|
-
*/const
|
|
156
|
+
*/const wa=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"}]]);/**
|
|
157
157
|
* @license lucide-react v0.453.0 - ISC
|
|
158
158
|
*
|
|
159
159
|
* This source code is licensed under the ISC license.
|
|
160
160
|
* See the LICENSE file in the root directory of this source tree.
|
|
161
|
-
*/const
|
|
161
|
+
*/const Da=s.createLucideIcon("Logs",[["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 18h8",key:"oe0vm4"}],["path",{d:"M13 6h8",key:"15sg57"}],["path",{d:"M3 12h1",key:"lp3yf2"}],["path",{d:"M3 18h1",key:"1eiwyy"}],["path",{d:"M3 6h1",key:"rgxa97"}],["path",{d:"M8 12h1",key:"1con00"}],["path",{d:"M8 18h1",key:"13wk12"}],["path",{d:"M8 6h1",key:"tn6mkg"}]]);/**
|
|
162
162
|
* @license lucide-react v0.453.0 - ISC
|
|
163
163
|
*
|
|
164
164
|
* This source code is licensed under the ISC license.
|
|
@@ -168,27 +168,27 @@
|
|
|
168
168
|
*
|
|
169
169
|
* This source code is licensed under the ISC license.
|
|
170
170
|
* See the LICENSE file in the root directory of this source tree.
|
|
171
|
-
*/const
|
|
171
|
+
*/const Ta=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"}]]);/**
|
|
172
172
|
* @license lucide-react v0.453.0 - ISC
|
|
173
173
|
*
|
|
174
174
|
* This source code is licensed under the ISC license.
|
|
175
175
|
* See the LICENSE file in the root directory of this source tree.
|
|
176
|
-
*/const
|
|
176
|
+
*/const ka=s.createLucideIcon("MessageCircleMore",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["path",{d:"M8 12h.01",key:"czm47f"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M16 12h.01",key:"1l6xoz"}]]);/**
|
|
177
177
|
* @license lucide-react v0.453.0 - ISC
|
|
178
178
|
*
|
|
179
179
|
* This source code is licensed under the ISC license.
|
|
180
180
|
* See the LICENSE file in the root directory of this source tree.
|
|
181
|
-
*/const
|
|
181
|
+
*/const Ea=s.createLucideIcon("MessageCircle",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]]);/**
|
|
182
182
|
* @license lucide-react v0.453.0 - ISC
|
|
183
183
|
*
|
|
184
184
|
* This source code is licensed under the ISC license.
|
|
185
185
|
* See the LICENSE file in the root directory of this source tree.
|
|
186
|
-
*/const
|
|
186
|
+
*/const Ia=s.createLucideIcon("MessageSquareWarning",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}],["path",{d:"M12 7v2",key:"stiyo7"}],["path",{d:"M12 13h.01",key:"y0uutt"}]]);/**
|
|
187
187
|
* @license lucide-react v0.453.0 - ISC
|
|
188
188
|
*
|
|
189
189
|
* This source code is licensed under the ISC license.
|
|
190
190
|
* See the LICENSE file in the root directory of this source tree.
|
|
191
|
-
*/const
|
|
191
|
+
*/const Aa=s.createLucideIcon("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]);/**
|
|
192
192
|
* @license lucide-react v0.453.0 - ISC
|
|
193
193
|
*
|
|
194
194
|
* This source code is licensed under the ISC license.
|
|
@@ -203,27 +203,27 @@
|
|
|
203
203
|
*
|
|
204
204
|
* This source code is licensed under the ISC license.
|
|
205
205
|
* See the LICENSE file in the root directory of this source tree.
|
|
206
|
-
*/const
|
|
206
|
+
*/const Ma=s.createLucideIcon("Network",[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]]);/**
|
|
207
207
|
* @license lucide-react v0.453.0 - ISC
|
|
208
208
|
*
|
|
209
209
|
* This source code is licensed under the ISC license.
|
|
210
210
|
* See the LICENSE file in the root directory of this source tree.
|
|
211
|
-
*/const
|
|
211
|
+
*/const La=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"}]]);/**
|
|
212
212
|
* @license lucide-react v0.453.0 - ISC
|
|
213
213
|
*
|
|
214
214
|
* This source code is licensed under the ISC license.
|
|
215
215
|
* See the LICENSE file in the root directory of this source tree.
|
|
216
|
-
*/const
|
|
216
|
+
*/const Ra=s.createLucideIcon("PanelLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]);/**
|
|
217
217
|
* @license lucide-react v0.453.0 - ISC
|
|
218
218
|
*
|
|
219
219
|
* This source code is licensed under the ISC license.
|
|
220
220
|
* See the LICENSE file in the root directory of this source tree.
|
|
221
|
-
*/const
|
|
221
|
+
*/const Oa=s.createLucideIcon("PenLine",[["path",{d:"M12 20h9",key:"t2du7b"}],["path",{d:"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z",key:"1ykcvy"}]]);/**
|
|
222
222
|
* @license lucide-react v0.453.0 - ISC
|
|
223
223
|
*
|
|
224
224
|
* This source code is licensed under the ISC license.
|
|
225
225
|
* See the LICENSE file in the root directory of this source tree.
|
|
226
|
-
*/const
|
|
226
|
+
*/const Fa=s.createLucideIcon("Plug",[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M9 8V2",key:"14iosj"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z",key:"osxo6l"}]]);/**
|
|
227
227
|
* @license lucide-react v0.453.0 - ISC
|
|
228
228
|
*
|
|
229
229
|
* This source code is licensed under the ISC license.
|
|
@@ -233,7 +233,7 @@
|
|
|
233
233
|
*
|
|
234
234
|
* This source code is licensed under the ISC license.
|
|
235
235
|
* See the LICENSE file in the root directory of this source tree.
|
|
236
|
-
*/const
|
|
236
|
+
*/const Pa=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"}]]);/**
|
|
237
237
|
* @license lucide-react v0.453.0 - ISC
|
|
238
238
|
*
|
|
239
239
|
* This source code is licensed under the ISC license.
|
|
@@ -253,17 +253,17 @@
|
|
|
253
253
|
*
|
|
254
254
|
* This source code is licensed under the ISC license.
|
|
255
255
|
* See the LICENSE file in the root directory of this source tree.
|
|
256
|
-
*/const
|
|
256
|
+
*/const Ba=s.createLucideIcon("Share",[["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8",key:"1b2hhj"}],["polyline",{points:"16 6 12 2 8 6",key:"m901s6"}],["line",{x1:"12",x2:"12",y1:"2",y2:"15",key:"1p0rca"}]]);/**
|
|
257
257
|
* @license lucide-react v0.453.0 - ISC
|
|
258
258
|
*
|
|
259
259
|
* This source code is licensed under the ISC license.
|
|
260
260
|
* See the LICENSE file in the root directory of this source tree.
|
|
261
|
-
*/const
|
|
261
|
+
*/const za=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"}]]);/**
|
|
262
262
|
* @license lucide-react v0.453.0 - ISC
|
|
263
263
|
*
|
|
264
264
|
* This source code is licensed under the ISC license.
|
|
265
265
|
* See the LICENSE file in the root directory of this source tree.
|
|
266
|
-
*/const
|
|
266
|
+
*/const _a=s.createLucideIcon("Shrink",[["path",{d:"m15 15 6 6m-6-6v4.8m0-4.8h4.8",key:"17vawe"}],["path",{d:"M9 19.8V15m0 0H4.2M9 15l-6 6",key:"chjx8e"}],["path",{d:"M15 4.2V9m0 0h4.8M15 9l6-6",key:"lav6yq"}],["path",{d:"M9 4.2V9m0 0H4.2M9 9 3 3",key:"1pxi2q"}]]);/**
|
|
267
267
|
* @license lucide-react v0.453.0 - ISC
|
|
268
268
|
*
|
|
269
269
|
* This source code is licensed under the ISC license.
|
|
@@ -278,12 +278,12 @@
|
|
|
278
278
|
*
|
|
279
279
|
* This source code is licensed under the ISC license.
|
|
280
280
|
* See the LICENSE file in the root directory of this source tree.
|
|
281
|
-
*/const
|
|
281
|
+
*/const Va=s.createLucideIcon("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/**
|
|
282
282
|
* @license lucide-react v0.453.0 - ISC
|
|
283
283
|
*
|
|
284
284
|
* This source code is licensed under the ISC license.
|
|
285
285
|
* See the LICENSE file in the root directory of this source tree.
|
|
286
|
-
*/const
|
|
286
|
+
*/const Ua=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"}]]);/**
|
|
287
287
|
* @license lucide-react v0.453.0 - ISC
|
|
288
288
|
*
|
|
289
289
|
* This source code is licensed under the ISC license.
|
|
@@ -293,12 +293,12 @@
|
|
|
293
293
|
*
|
|
294
294
|
* This source code is licensed under the ISC license.
|
|
295
295
|
* See the LICENSE file in the root directory of this source tree.
|
|
296
|
-
*/const
|
|
296
|
+
*/const Ga=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"}]]);/**
|
|
297
297
|
* @license lucide-react v0.453.0 - ISC
|
|
298
298
|
*
|
|
299
299
|
* This source code is licensed under the ISC license.
|
|
300
300
|
* See the LICENSE file in the root directory of this source tree.
|
|
301
|
-
*/const
|
|
301
|
+
*/const Ya=s.createLucideIcon("Terminal",[["polyline",{points:"4 17 10 11 4 5",key:"akl6gq"}],["line",{x1:"12",x2:"20",y1:"19",y2:"19",key:"q2wloq"}]]);/**
|
|
302
302
|
* @license lucide-react v0.453.0 - ISC
|
|
303
303
|
*
|
|
304
304
|
* This source code is licensed under the ISC license.
|
|
@@ -313,7 +313,7 @@
|
|
|
313
313
|
*
|
|
314
314
|
* This source code is licensed under the ISC license.
|
|
315
315
|
* See the LICENSE file in the root directory of this source tree.
|
|
316
|
-
*/const Ya=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"}]]);function $a(){const{setTheme:t}=s.useTheme(),n=s.useDashboardStore(a=>a.actions.setDashboardTheme);return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsxs(s.Button,{className:"h-7 p-2",variant:"ghost",size:"sm",children:[e.jsx(Va,{strokeWidth:1.5,className:"h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(Ia,{strokeWidth:1.5,className:"absolute h-4 w-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),e.jsx("span",{className:"sr-only",children:"Toggle theme"})]})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuItem,{onClick:()=>{t("light"),n("light")},children:"Light"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("dark"),n("dark")},children:"Dark"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("system"),n("system")},children:"System"})]})]})}function ss(t){var n;return{...t,sheets:(n=t==null?void 0:t.sheets)==null?void 0:n.map(a=>{var r;return{...a,frames:(r=a.frames)==null?void 0:r.map(l=>{var o;return{...l,cards:(o=l.cards)==null?void 0:o.map(c=>rt(c))}})}})}}function rt(t){return{...t,customCfg:qa(t.customCfg),data:[]}}function qa(t){var n,a;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(a=(n=t==null?void 0:t.data)==null?void 0:n.datasets)==null?void 0:a.map(r=>({...r,data:[]}))}}:null}async function Ha(t,n,a,r,l){if(!l)return null;const o=JSON.stringify(a),c=`${t}/v1/lens`;return await s.postRequest(c,l,{name:n,template:o,filterValues:r,operation:"create"})}async function vs(t,n,a){if(!a)return null;const{id:r,template:l,filterValues:o,isDefault:c,shared:i}=n,d=`${t}/v1/lens`;return await s.postRequest(d,a,{lensId:r,template:l,filterValues:o,isDefault:c,shared:i,operation:"update"})}async function Wa(t,n,a){if(!a)return null;const r=`${t}/v1/lens`;return await s.postRequest(r,a,{operation:"delete",lensId:n})}function Ka(){const[t,n]=M.useState(""),[a,r]=M.useState(!1),l=s.useDashboardStore(j=>j.lenses),{setLenses:o,setSelectedLensId:c}=s.useDashboardActions(),[i,d]=M.useState(!1),[u,m]=M.useState(!1),h=s.useDashboardStore(j=>j.dashboard),p=s.useDashboardStore(j=>j.filterValues),{authToken:g,tokenProps:b}=s.useSemaphorContext();async function x(){d(!0);const j=ss(h),f=await Ha(b.apiServiceUrl,t,j,p,g==null?void 0:g.accessToken);f&&(o([...l||[],f]),c(f.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:j=>{n(j.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),a&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{size:"sm",variant:"outline",type:"submit",onClick:x,disabled:i,children:i?"Creating...":"Add"})})]})]})}function Qa(){const[t,n]=M.useState(!1),a=s.useDashboardStore(h=>h.lenses),r=s.useDashboardStore(h=>h.selectedLensId),{setLenses:l,setSelectedLensId:o}=s.useDashboardActions(),{authToken:c,tokenProps:i}=s.useSemaphorContext();async function d(h){o(h)}async function u(h){if(await Wa(i.apiServiceUrl,h,c==null?void 0:c.accessToken)){const g=a==null?void 0:a.filter(b=>b.id!==h);l(g||[]),o("original")}}async function m(h){const p=a==null?void 0:a.map(x=>x.id===h.id?{...x,isDefault:!h.isDefault}:{...x,isDefault:!1});l(p||[]);const g={...h,isDefault:!h.isDefault};await vs(i.apiServiceUrl,g,c==null?void 0:c.accessToken);const b=a==null?void 0:a.find(x=>x.isDefault);if(b&&b.id!==h.id){const x={...b,isDefault:!1};await vs(i.apiServiceUrl,x,c==null?void 0:c.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:n,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(ba,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(s.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuRadioGroup,{value:r,onValueChange:d,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),a==null?void 0:a.map(h=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:h.id,children:[e.jsx("p",{children:h.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:p=>{p.preventDefault(),m(h)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!h.isDefault,"text-green-500":h.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:p=>{p.preventDefault(),u(h.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},h.id))]})]})]})}function Ja({iconClassName:t}){const[n,a]=M.useState(!1),[r,l]=M.useState(""),[o,c]=M.useState(!1),i=s.useDashboardStore(h=>h.isDownloadingPdf),{tokenProps:d}=s.useSemaphorContext();async function u(){const h=s.ue.loading("Generating PDF... may take up to 60 seconds");try{await s.downloadPdf(d.apiServiceUrl),s.ue.dismiss(h),s.ue.success("PDF downloaded successfully!",{duration:2e3})}catch(p){s.ue.dismiss(h),s.ue.error("Failed to download PDF",{description:"Please try again or contact support.",richColors:!0}),console.error("PDF download error:",p)}}async function m(){if(!r)return;a(!1),l(""),c(!1);const h=s.ue.loading("Generating protected PDF... may take up to 60 seconds");try{await s.downloadPdf(d.apiServiceUrl,r),s.ue.dismiss(h),s.ue.success("Protected PDF downloaded successfully!",{duration:2e3,position:"top-right"})}catch(p){s.ue.dismiss(h),s.ue.error("Failed to download protected PDF. Please try again."),console.error("Protected PDF download error:",p)}}return e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled:i,children:e.jsx(s.Download,{className:s.cn("size-4",t)})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsxs(s.DropdownMenuItem,{onClick:u,children:[e.jsx(s.File,{className:"mr-2 h-4 w-4"}),"Download PDF"]}),e.jsxs(s.DropdownMenuItem,{onClick:()=>a(!0),children:[e.jsx(s.Lock,{className:"mr-2 h-4 w-4"}),"Download Protected PDF"]})]})]}),e.jsx(s.Dialog,{open:n,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Download Protected PDF"}),e.jsx(s.DialogDescription,{children:"Enter a password to protect your PDF. The PDF will be encrypted and require this password to open."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Input,{id:"password",type:o?"text":"password",value:r,onChange:h=>l(h.target.value),placeholder:"Enter password",className:"pr-10",onKeyDown:h=>{h.key==="Enter"&&r&&m()}}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent",onClick:()=>c(!o),children:o?e.jsx(s.EyeOff,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(s.Eye,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:m,disabled:!r,children:"Download"})]})]})})]})}function lt({triggerButtonClassName:t}){const[n,a]=M.useState(!1),r=s.useDashboardStore(i=>{var d;return(d=i.dashboard)==null?void 0:d.id}),l=s.useDashboardStore(i=>{var d;return(d=i.dashboard)==null?void 0:d.title}),o=s.useDashboardStore(i=>{var d;return(d=i.dashboard)==null?void 0:d.sheets}),c=s.useDashboardStore(i=>i.selectedSheetId);return o==null||o.find(i=>i.id===c),r?e.jsxs(e.Fragment,{children:[e.jsx(s.IconButton,{tooltip:"Schedule Dashboard",className:s.cn("h-7 p-2",t),onClick:()=>a(!0),children:e.jsx(s.Clock,{className:"size-4"})}),e.jsx(s.EmailScheduleDialog,{open:n,onOpenChange:a,dashboardId:r,dashboardName:l})]}):null}function ts({value:t,onChange:n,placeholder:a="Search users by name, email, or department..."}){return 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:a,value:t,onChange:r=>n(r.target.value),className:"pl-9"})]})}function Re({currentRole:t,onRoleChange:n,roleOptions:a,disabled:r=!1,className:l="",allowDropdown:o=!0}){var d;const c=((d=a.find(u=>u.value===t))==null?void 0:d.label)||t,i=a.filter(u=>u.value!==t);return o?e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:`cursor-pointer hover:bg-muted ${r?"cursor-not-allowed opacity-50":""} ${l}`,children:c})}),e.jsx(s.DropdownMenuContent,{className:"z-[51]",children:i.map(u=>e.jsx(s.DropdownMenuItem,{onClick:()=>n(u.value),disabled:r,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.description})]})},u.value))})]}):e.jsx(s.Badge,{variant:"outline",className:`text-xs ${l}`,children:c})}function ot({selectedUsers:t,selectedUserObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:l}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["Selected Users (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(o=>a(o.id)),className:"h-auto p-1 text-xs",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:n.map(o=>{const c=t.find(d=>d.id===o.id),i=l(o.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[o.name,e.jsx(Re,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:d=>r(o.id,d),roleOptions:i}),e.jsx("button",{onClick:()=>a(o.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},o.id)})}),e.jsx(s.Separator,{})]})}function it({usersToRemove:t,allUsers:n,onRemove:a}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium text-destructive",children:["Users to Remove Access (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(r=>a(r)),className:"h-auto p-1 text-xs text-destructive hover:text-destructive",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:n.filter(r=>t.includes(r.id)).map(r=>e.jsxs(s.Badge,{variant:"destructive",className:"gap-1",children:[r.name,e.jsx("button",{onClick:()=>a(r.id),className:"ml-1 rounded-full p-0.5 hover:bg-destructive-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},r.id))}),e.jsx(s.Separator,{})]})}function ct({usersToUpdate:t,allUsers:n,onRemove:a,getRoleOptions:r}){if(t.length===0)return null;const l=r("tenant"),o=i=>{const d=n.find(u=>u.id===i);return(d==null?void 0:d.name)||"Unknown User"},c=i=>{const d=l.find(u=>u.value===i);return(d==null?void 0:d.label)||i};return e.jsxs("div",{className:"rounded-lg border border-orange-200 bg-orange-50 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-4 w-4 text-orange-600"}),e.jsxs("span",{className:"text-sm font-medium text-orange-800",children:["Updating Access (",t.length,")"]})]}),e.jsx("div",{className:"space-y-2",children:t.map(i=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:o(i.id)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c(i.currentRole)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsx(s.Badge,{variant:"default",className:"text-xs",children:c(i.newRole)})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",onClick:()=>a(i.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},i.id))})]})}function dt(t,n={}){const{enabled:a=!0,eventType:r="mousedown"}=n,l=M.useRef(null);return M.useEffect(()=>{const o=c=>{const i=c.target;l.current&&l.current.contains(i)||i instanceof Element&&(i.closest("[data-radix-popper-content-wrapper]")||i.closest("[data-radix-select-content]")||i.closest("[data-radix-popover-content]")||i.closest("[data-radix-dropdown-menu-content]")||i.closest("[data-radix-tooltip-content]")||i.closest('[role="listbox"]')||i.closest('[role="option"]')||i.closest('[role="combobox"]'))||i instanceof Element&&i.hasAttribute("data-radix-")||t()};return a&&document.addEventListener(r,o),()=>{document.removeEventListener(r,o)}},[t,a,r]),l}function ye(t,n){var a;return((a=n.find(r=>r.value===t))==null?void 0:a.label)||t}function Xa(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function ut(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function Za(t,n,a){const r=ut(t),l=(a==null?void 0:a.type)||"organization";if(!(!n||!n.shares))if(l==="organization")if(r==="organization"){if("specificOrgUsers"in n.shares)return(n.shares.specificOrgUsers||[]).find(i=>i.orgUserId===t.id)}else return(n.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id);else return(n.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id)}function en({user:t}){return ut(t)==="tenant"?e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:t.role==="POWER_USER"?"Power User":"Viewer"}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:t.role==="ADMIN"?"Admin":t.role==="POWER_USER"?"Power User":"Viewer"})}function sn({user:t,userShare:n,usersToUpdate:a,currentUser:r,getRoleOptions:l,handleUpdateAccess:o}){if(!(n!=null&&n.role))return null;const c=Xa((r==null?void 0:r.type)||""),i=a.some(h=>h.id===t.id),d=a.find(h=>h.id===t.id),u=d?d.newRole:n==null?void 0:n.role,m=l(t.type);return n?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(Re,{currentRole:u,onRoleChange:h=>{o(t.id,n.role,h)},roleOptions:m,disabled:!c,allowDropdown:c,className:i?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:ye(u,m)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function tn({hasAccess:t,isUserRemoving:n,isSelected:a,hasAccessFromAPI:r}){return e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[t&&!n&&e.jsxs(s.Badge,{variant:"outline",className:"border-green-200 bg-green-50 text-xs text-green-700",children:[e.jsx(s.Eye,{className:"mr-1 h-3 w-3"}),"Has Access"]}),n&&e.jsxs(s.Badge,{variant:"outline",className:"border-red-200 bg-red-50 text-xs text-red-700",children:[e.jsx(s.X,{className:"mr-1 h-3 w-3"}),"Remove Access"]}),a&&!r&&e.jsxs(s.Badge,{variant:"outline",className:"border-blue-200 bg-blue-50 text-xs text-blue-700",children:[e.jsx(Pe,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function an({isUserRemoving:t,isSelected:n,hasAccess:a,isRemoving:r,isSharing:l}){return e.jsxs(e.Fragment,{children:[t&&e.jsx("span",{className:"text-xs font-medium text-red-600",children:r?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Removing..."]}):"⚠ Will remove access"}),n&&!a&&e.jsx("span",{className:"text-xs font-medium text-blue-600",children:l?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Sharing..."]}):"Will share"})]})}function nn({existingShares:t,allUsers:n,getRoleOptions:a,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in t.shares){const c=t.shares,i=c.specificOrgUsers||[],d=c.specificTenantUsers||[],u=c.orgWide||[],m=c.orgUsersOnly||[],h=c.allTenantsOnly||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Org Users (",i.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[i.slice(0,3).map((p,g)=>{var f,N;const b=((f=n.find(T=>T.id===p.orgUserId))==null?void 0:f.name)||"Unknown User",x=((N=n.find(T=>T.id===p.orgUserId))==null?void 0:N.type)||"",j=ye(p.role,a(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:b}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},g)}),i.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",i.length-3," more users"]})]})]}),d.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-green-600",children:["Specific Tenant Users (",d.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[d.slice(0,3).map((p,g)=>{var f,N;const b=((f=n.find(T=>T.id===p.tenantUserId))==null?void 0:f.name)||"Unknown User",x=((N=n.find(T=>T.id===p.tenantUserId))==null?void 0:N.type)||"",j=ye(p.role,a(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:b}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},g)}),d.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",d.length-3," more users"]})]})]}),u.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-purple-600",children:"All Org Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:u.map((p,g)=>{const b=ye(p.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Organization Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},g)})})]}),m.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-orange-600",children:"Org Users Only"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:m.map((p,g)=>{const b=ye(p.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Org Users Only"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},g)})})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-indigo-600",children:"All Tenants"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:h.map((p,g)=>{const b=ye(p.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenants"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},g)})})]}),!i.length&&!d.length&&!u.length&&!m.length&&!h.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const c=t.shares.specificTenantUsers||[],i=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",c.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[c.slice(0,3).map((d,u)=>{var g,b;const m=((g=n.find(x=>x.id===d.tenantUserId))==null?void 0:g.name)||"Unknown User",h=((b=n.find(x=>x.id===d.tenantUserId))==null?void 0:b.type)||"",p=ye(d.role,a(h));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:m}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:p})]},u)}),c.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",c.length-3," more users"]})]})]}),i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:i.map((d,u)=>{const m=ye(d.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:m})]},u)})})]}),!c.length&&!i.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const o=t.shares.specificTenantUsers||[],c=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[o.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",o.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[o.slice(0,3).map((i,d)=>{var p,g;const u=((p=n.find(b=>b.id===i.tenantUserId))==null?void 0:p.name)||"Unknown User",m=((g=n.find(b=>b.id===i.tenantUserId))==null?void 0:g.type)||"",h=ye(i.role,a(m));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:u}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},d)}),o.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",o.length-3," more users"]})]})]}),c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:c.map((i,d)=>{const u=ye(i.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:u})]},d)})})]}),!o.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function rn({isInitialLoading:t,searchQuery:n,availableUsers:a}){return t?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(s.LoaderCircle,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading users..."})]})}):a.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:n?"No users found matching your search.":"No users available to share with."}):null}function ln({user:t,userShare:n,isUserRemoving:a,hasAccess:r,hasAccessFromAPI:l,isSelected:o,selectedUser:c,roleOptions:i,currentUser:d,usersToUpdate:u,handleUserToggle:m,handleRemoveAccess:h,handleUpdateAccess:p,handleUserRoleChange:g}){return e.jsxs("div",{className:s.cn("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!a?"border border-green-200 bg-green-50":a?"border border-red-200 bg-red-50":o?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:l?!a:o,disabled:t.id===(d==null?void 0:d.id),onCheckedChange:()=>{l?a?m(t.id):h(t.id):m(t.id)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:t.name}),e.jsx(en,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!a?e.jsx(Re,{currentRole:n==null?void 0:n.role,onRoleChange:b=>p(t.id,n.role,b),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(sn,{user:t,userShare:n,usersToUpdate:u,currentUser:d,getRoleOptions:()=>i,handleUpdateAccess:p}),o&&!l&&e.jsx("div",{onClick:b=>b.stopPropagation(),children:e.jsx(Re,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:b=>g(t.id,b),roleOptions:i,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(tn,{hasAccess:r,isUserRemoving:a,isSelected:o,hasAccessFromAPI:l}),e.jsx(an,{isUserRemoving:a,isSelected:o,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function mt({existingShares:t,isInitialLoading:n,isSearching:a,getRoleOptions:r,allUsers:l=[],currentUser:o,handleUserToggle:c,handleUserRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),g=s.useShareSearchQuery(),b=s.useShareManagementActions(),x=c||(C=>{const w=m.some(E=>E.id===C),v=h.includes(C);w?b.removeSelectedUser(C):v?b.removeUserFromRemove(C):b.addSelectedUser({id:C,role:"VIEWER"})}),j=i||b.updateSelectedUserRole,f=d||b.addUserToRemove,N=u||((C,w,v)=>{b.addUserToUpdate({id:C,currentRole:w,newRole:v})}),T=l,k=h;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["All Users (",(T??[]).length,")"]}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",children:e.jsx(s.Info,{className:"h-4 w-4"})})}),e.jsx(s.TooltipContent,{className:"w-48 max-w-sm",children:e.jsx(nn,{existingShares:t,allUsers:l,getRoleOptions:r,currentUser:o})})]})})]}),(T==null?void 0:T.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{m.length===T.length?b.setSelectedUsers([]):b.setSelectedUsers(T.map(C=>({id:C.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:m.length===T.length?"Deselect all":"Select all"})]}),e.jsxs("div",{className:"max-h-60 space-y-1 overflow-y-auto rounded-md border p-2",children:[e.jsx(rn,{isInitialLoading:n,isSearching:a,searchQuery:g,availableUsers:T||[]}),!n&&!a&&(T==null?void 0:T.length)>0&&T.map(C=>{const w=t?Za(C,t,o):void 0,v=k.includes(C.id),E=!!w,y=E&&!v,F=m.some(D=>D.id===C.id),I=m.find(D=>D.id===C.id),P=r(C.type);return e.jsx(ln,{user:C,userShare:w,isUserRemoving:v,hasAccess:y,hasAccessFromAPI:E,isSelected:F,selectedUser:I,roleOptions:P,currentUser:o,usersToUpdate:p,handleUserToggle:x,handleRemoveAccess:f,handleUpdateAccess:N,handleUserRoleChange:j},C.id)})]})]})}function Ss({shareType:t,onShareTypeChange:n,currentUser:a,options:r}){const l=(a==null?void 0:a.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(a.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:n,className:`grid grid-cols-${r.length} gap-4`,children:r.map(o=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:o.value,id:o.value,className:"peer sr-only",disabled:o.disabled}),e.jsxs(s.Label,{htmlFor:o.value,className:`flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5 [&:has([data-state=checked])]:border-primary [&:has([data-state=checked])]:bg-primary/5 ${o.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[o.icon||e.jsx(s.User,{className:"mb-3 h-6 w-6"}),e.jsxs("div",{className:"space-y-1 text-center",children:[e.jsx("p",{className:"text-sm font-medium leading-none",children:o.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o.description})]})]})]},o.value))}),!l&&r.some(o=>o.value==="all_users")&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only admins, authors, power users, and super admins can share with all users."})]})}const be=()=>[{value:"VIEWER",label:"Viewer",description:"Can view only"},{value:"EDITOR",label:"Editor",description:"Can view and edit"},{value:"CONTRIBUTOR",label:"Contributor",description:"Can view, edit, and share"},{value:"OWNER",label:"Owner",description:"Full access (view, edit, share, delete)"}];function on({currentUser:t,currentShare:n,isSharing:a,onUpdateAccess:r,allUsersToUpdate:l=null,allUsersToRemove:o=!1,isUpdating:c=!1,isRemoving:i=!1}){const d=s.useShareCurrentMode(),u=be().filter(N=>N.value==="VIEWER"||N.value==="EDITOR"||N.value==="CONTRIBUTOR"),m=n.role!=="NONE"?n.role:"NONE",h=l?l.newRole:m,p=n.role!=="NONE"&&!o&&(!l||l.newRole===m),g=l!==null&&l.newRole!==m,b=o,x=m==="NONE"||!m,j=N=>{switch(N){case"VIEWER":return e.jsx(s.Eye,{className:"h-4 w-4"});case"EDITOR":return e.jsx(s.SquarePen,{className:"h-4 w-4"});case"CONTRIBUTOR":return e.jsx(Pa,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},f=N=>{r(m,N)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",g&&!b&&!x?"border-orange-300 bg-orange-50":p?"border-green-300 bg-green-50":b||x?"border-destructive bg-destructive/10":""),children:[e.jsxs(s.CardHeader,{children:[e.jsxs(s.CardTitle,{className:"flex items-center gap-2 text-base",children:[e.jsx(s.Users,{className:"h-5 w-5"}),"Share with All"," ",d==="allOrgUsers"?"Organization":d==="allTenantUsers"?"Tenant":d==="specificOrgUsers"?"Org":"Tenant"," ","Users",p&&e.jsx(s.Badge,{variant:"default",className:"ml-2 border-green-400 bg-green-100 text-green-800",children:"Active"}),g&&e.jsx(s.Badge,{variant:"secondary",className:"ml-2 border-orange-400 bg-orange-100 text-orange-800",children:"Pending Update"}),(b||x)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:b||x?"No access for all users.":"This will share the dashboard with all users in your "+((t==null?void 0:t.type)==="organization"?"organization":"tenant")+". Select an access level below."})]}),e.jsx(s.CardContent,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Select Access Level:"}),e.jsxs(s.HoverCard,{children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-4 w-4 p-0 text-muted-foreground hover:text-foreground",children:e.jsx(s.Info,{className:"h-3 w-3"})})}),e.jsx(s.HoverCardContent,{className:"w-80",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Share with All Users"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["This action will share the dashboard with all users in your"," ",(t==null?void 0:t.type)==="organization"?"organization":"tenant",". Users will receive the selected access level."]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Viewer:"})," Can view the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Editor:"})," Can view and edit the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Contributor:"})," Can view, edit, and share the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"None:"})," No access for all users"]})]})]})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:u.map(N=>e.jsxs(s.Button,{variant:h===N.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>f(N.value),disabled:a||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[j(N.value),e.jsx("span",{className:"font-medium",children:N.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:N.description})]},N.value))})]})})]})})}function ht({currentUser:t,currentShare:n,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:o,onRemoveAccess:c,allUsersToUpdate:i,allUsersToRemove:d}){const u=x=>x==="OWNER"?"CONTRIBUTOR":x,h=n?{role:u(n.role)}:{role:"NONE"},p=i?{currentRole:u(i.currentRole),newRole:u(i.newRole)}:null,g=(x,j)=>{o(x,j)},b=()=>{c()};return e.jsx(on,{currentUser:t,currentShare:h,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:g,onRemoveAccess:b,allUsersToUpdate:p,allUsersToRemove:d})}function ze(t){const{debouncedSearchQuery:n,resourceId:a,resourceType:r=s.ResourceType.DASHBOARD,userType:l,tenantId:o}=t,c=M.useMemo(()=>({search:n,active:!0,...l?{type:l}:{},...l==="tenant"&&o?{tenantId:o}:{}}),[n,l,o]),{users:i,isLoading:d,isError:u}=s.useUnifiedUsers(c),m=s.useResourceShares(r,a);return{allUsers:i,isLoadingUsers:d,isErrorLoadingUsers:u,existingShares:m.data,isLoadingShares:m.isLoading,isErrorLoadingShares:m.isError,isFetchingShares:m.isFetching}}function cn({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var Q,X;const i=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:u,setSearchQuery:m,debouncedSearchQuery:h}=s.useShareSearchWithDebounce(),p=s.useShareSelectedUsers(),g=s.useShareUsersToRemove(),b=s.useShareUsersToUpdate(),x=s.useShareCurrentMode(),j=s.useShareOrgWideRole(),f=s.useShareManagementActions(),[N,T]=M.useState("specific_users"),k=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},C=()=>{if(i==="tenant"&&d)return d},{allUsers:w,existingShares:v,isLoadingUsers:E}=ze({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:k(),tenantId:C()});M.useEffect(()=>{f.setCurrentContext("org-tab"),f.setCurrentMode(N==="all_users"?"allOrgUsers":"specificOrgUsers")},[f,N]);const y=q=>{var G,se;const W=q;if(T(W),r==null||r(W),f.setCurrentContext("org-tab"),W==="specific_users")f.setCurrentMode("specificOrgUsers");else if(W==="all_users"){f.setCurrentMode("allOrgUsers");const V=(se=(G=v==null?void 0:v.shares)==null?void 0:G.orgUsersOnly)==null?void 0:se[0];V&&V.role!==void 0&&f.setOrgWideRole(V.role)}},F=w.filter(q=>q.name.toLowerCase().includes(u.toLowerCase())||q.email.toLowerCase().includes(u.toLowerCase())),I=w.filter(q=>p.some(W=>W.id===q.id)),P=q=>{var V,U;const W=p.some(ee=>ee.id===q),G=g.includes(q),se=(U=(V=v==null?void 0:v.shares)==null?void 0:V.specificOrgUsers)==null?void 0:U.some(ee=>ee.orgUserId===q);W?f.removeSelectedUser(q):G?f.removeUserFromRemove(q):se||f.addSelectedUser({id:q,role:"VIEWER"})},D=(q,W)=>{f.updateSelectedUserRole(q,W)},S=q=>{f.addUserToRemove(q),f.removeSelectedUser(q)},L=q=>{f.removeUserFromRemove(q)},O=q=>{f.removeUserFromUpdate(q)},R=(q,W)=>{f.setOrgWideRole(W)},A=()=>{f.setOrgWideRole((B==null?void 0:B.role)||"NONE")},B=(X=(Q=v==null?void 0:v.shares)==null?void 0:Q.orgUsersOnly)==null?void 0:X[0];M.useEffect(()=>{N==="all_users"&&B&&B.role!==void 0&&f.setOrgWideRole(B.role)},[N,B,f]);const Y=E,_=!1;return a?e.jsxs(e.Fragment,{children:[e.jsx(Ss,{shareType:N,onShareTypeChange:y,currentUser:a,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(s.User,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(a==null?void 0:a.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(a.role??"")}]}),N==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(ts,{value:u,onChange:m}),e.jsx(ot,{selectedUsers:p,selectedUserObjects:I,onRemove:P,onRoleChange:D,getRoleOptions:be}),e.jsx(it,{usersToRemove:g,allUsers:F,onRemove:L}),e.jsx(ct,{usersToUpdate:b,allUsers:F,onRemove:O,getRoleOptions:be}),e.jsx(mt,{existingShares:v,isInitialLoading:Y,isSearching:_,resource:t,onShare:()=>{},getRoleOptions:be,allUsers:F,currentUser:a,handleUserToggle:P,handleUserRoleChange:D,handleRemoveAccess:S,handleUpdateAccess:(q,W,G)=>{f.addUserToUpdate({id:q,currentRole:W,newRole:G})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(ht,{currentUser:a,currentShare:B,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:R,onRemoveAccess:A,allUsersToUpdate:x==="allOrgUsers"&&j!==((B==null?void 0:B.role)||"NONE")?{currentRole:(B==null?void 0:B.role)||"NONE",newRole:j}:null,allUsersToRemove:x==="allOrgUsers"&&(B==null?void 0:B.role)===void 0})})]}):null}function dn(t){switch(t){case"ORG_GROUP":return"Organization Group";case"TENANT_GROUP":return"Tenant Group";default:return"Group"}}function un(t){switch(t){case"ORG_GROUP":return"text-blue-600";case"TENANT_GROUP":return"text-green-600";default:return"text-gray-600"}}function xt({groups:t,existingGroupShares:n,isLoading:a,resource:r,getRoleOptions:l,currentUser:o,handleGroupToggle:c,handleGroupRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:u}){const m=s.useShareSelectedGroups(),h=s.useShareGroupsToRemove(),p=s.useShareGroupsToUpdate(),g=s.useShareManagementActions(),b=l(o==null?void 0:o.type);return a?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):t.length===0?e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"No groups available to share with"}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Available Groups"}),e.jsx("div",{className:"max-h-[300px] space-y-2 overflow-y-auto rounded-md border p-3",children:t.map(x=>{const j=n==null?void 0:n.find(v=>v.groupId===x.id),f=m.some(v=>v.id===x.id),N=h.includes(x.id),T=p.find(v=>v.id===x.id),k=!!j&&!N;let w=(j==null?void 0:j.role)||"VIEWER";if(f){const v=m.find(E=>E.id===x.id);w=(v==null?void 0:v.role)||"VIEWER"}else T&&(w=T.newRole);return e.jsxs("div",{className:s.cn("flex items-center justify-between rounded-lg p-2 transition-colors",k&&!N?"border border-green-200 bg-green-50":N?"border border-red-200 bg-red-50":f?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx(s.Checkbox,{id:`group-${x.id}`,checked:k?!N:f,disabled:!1,onCheckedChange:()=>{k?N?g.removeGroupFromRemove(x.id):d==null||d(x.id):c==null||c(x.id)}}),e.jsxs("label",{htmlFor:`group-${x.id}`,className:"flex cursor-pointer flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:x.name}),x.type==="ORG_GROUP"?e.jsx(s.Building2,{className:"h-3 w-3 text-blue-600"}):e.jsx(s.Users,{className:"h-3 w-3 text-green-600"}),e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[x.memberCount," members"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:s.cn("text-xs",un(x.type)),children:dn(x.type)}),x.type==="TENANT_GROUP"&&x.tenantName&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",x.tenantName]})]}),x.description&&e.jsx("span",{className:"text-xs text-muted-foreground",children:x.description})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[k&&!N?e.jsx(Re,{currentRole:w,onRoleChange:v=>{j&&v!==j.role&&(u==null||u(x.id,j.role,v))},roleOptions:b,disabled:!1,allowDropdown:!0,className:T?"border-orange-300 bg-orange-100":""}):f&&!k&&e.jsx(Re,{currentRole:w,onRoleChange:v=>i==null?void 0:i(x.id,v),roleOptions:b,disabled:!1}),k&&!N&&!T&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>d==null?void 0:d(x.id),children:e.jsx(s.X,{className:"h-4 w-4"})}),N&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g.removeGroupFromRemove(x.id),children:"Undo"}),T&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g.removeGroupFromUpdate(x.id),children:"Cancel"})]})]},x.id)})})]})}function pt({selectedGroups:t,groupObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:l}){if(t.length===0)return null;const o=l();return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:["Selected Groups (",t.length,")"]}),e.jsx("div",{className:"space-y-1",children:t.map(c=>{const i=n.find(d=>d.id===c.id);return i?e.jsxs("div",{className:"flex items-center justify-between rounded-md border bg-muted/50 p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[i.type==="ORG_GROUP"?e.jsx(s.Building2,{className:"h-4 w-4 text-blue-600"}):e.jsx(s.Users,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{className:"text-sm font-medium",children:i.name}),e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[i.memberCount," members"]}),i.type==="TENANT_GROUP"&&i.tenantName&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",i.tenantName]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Re,{currentRole:c.role,onRoleChange:d=>r(c.id,d),roleOptions:o}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>a(c.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})]},c.id):null})})]})}function Us({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var fe;const{searchQuery:i,debouncedSearchQuery:d,setSearchQuery:u}=s.useShareSearchWithDebounce(),m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),g=s.useShareSelectedGroups(),b=s.useShareGroupsToRemove(),x=s.useShareGroupsToUpdate(),j=s.useShareCurrentMode(),f=s.useShareTenantWideRole(),N=s.useShareAllTenantsRole(),T=s.useShareSelectedTenant(),k=s.useShareManagementActions(),{data:C,isLoading:w}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"}),{groups:v,isLoading:E}=s.useShareableGroups("tenant",(a==null?void 0:a.tenantId)||T),[y,F]=M.useState((a==null?void 0:a.type)==="organization"?"all_tenants":"specific_tenant_users");M.useEffect(()=>{(a==null?void 0:a.type)==="tenant"?(k.setCurrentContext("tenant-dialog"),k.setCurrentMode("specificTenantUsers")):(k.setCurrentContext("tenant-tab"),k.setCurrentMode("allTenants"))},[k,a==null?void 0:a.type]);const I=$=>{var Z,le,ne,je;F($);let K;if($==="specific_tenant_users"?K="specific_users":$==="all_tenant_users"||$==="all_tenants"?K="all_users":$==="groups"?K="groups":K="specific_users",r==null||r(K),$==="groups"?(k.setCurrentContext("group-share"),k.setCurrentMode("specificGroups")):(a==null?void 0:a.type)==="tenant"?(k.setCurrentContext("tenant-dialog"),$==="specific_tenant_users"?k.setCurrentMode("specificTenantUsers"):$==="all_tenant_users"&&(k.setCurrentMode("allTenantUsers"),a!=null&&a.tenantId&&k.setSelectedTenant(a.tenantId))):(k.setCurrentContext("tenant-tab"),$==="specific_tenant_users"?k.setCurrentMode("specificTenantUsers"):$==="all_tenant_users"?k.setCurrentMode("allTenantUsers"):$==="all_tenants"&&k.setCurrentMode("allTenants")),$==="all_tenant_users"){const xe=(le=(Z=S==null?void 0:S.shares)==null?void 0:Z.tenantWide)==null?void 0:le[0];xe&&xe.role!==void 0&&k.setTenantWideRole(xe.role)}else if($==="all_tenants"){const xe=(je=(ne=S==null?void 0:S.shares)==null?void 0:ne.allTenantsOnly)==null?void 0:je[0];xe&&xe.role!==void 0&&k.setAllTenantsRole(xe.role)}},P=$=>{k.setSelectedTenant($)},{allUsers:D,existingShares:S,isLoadingUsers:L,isErrorLoadingUsers:O,isLoadingShares:R,isErrorLoadingShares:A}=ze({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant",tenantId:(a==null?void 0:a.type)==="tenant"?a.tenantId:T}),B=$=>{var ne,je;const K=m.some(xe=>xe.id===$),Z=h.includes($),le=(je=(ne=S==null?void 0:S.shares)==null?void 0:ne.specificTenantUsers)==null?void 0:je.some(xe=>xe.tenantUserId===$);K?k.removeSelectedUser($):Z?k.removeUserFromRemove($):le||k.addSelectedUser({id:$,role:"VIEWER"})},Y=($,K)=>{k.updateSelectedUserRole($,K)},_=$=>{k.addUserToRemove($),k.removeSelectedUser($)},Q=$=>{k.removeUserFromRemove($)},X=$=>{k.removeUserFromUpdate($)},q=($,K,Z)=>{k.addUserToUpdate({id:$,currentRole:K,newRole:Z})},W=($,K)=>{y==="all_tenant_users"?k.setTenantWideRole(K):y==="all_tenants"&&k.setAllTenantsRole(K)},G=()=>{y==="all_tenant_users"?k.setTenantWideRole("VIEWER"):y==="all_tenants"&&k.setAllTenantsRole("VIEWER")},V=(()=>{var $,K,Z,le;return j==="allTenants"?(K=($=S==null?void 0:S.shares)==null?void 0:$.allTenantsOnly)==null?void 0:K[0]:j==="allTenantUsers"?(le=(Z=S==null?void 0:S.shares)==null?void 0:Z.tenantWide)==null?void 0:le[0]:null})();M.useEffect(()=>{var $,K,Z,le;if(y==="all_tenant_users"){const ne=(K=($=S==null?void 0:S.shares)==null?void 0:$.tenantWide)==null?void 0:K[0];ne&&ne.role!==void 0&&k.setTenantWideRole(ne.role)}else if(y==="all_tenants"){const ne=(le=(Z=S==null?void 0:S.shares)==null?void 0:Z.allTenantsOnly)==null?void 0:le[0];ne&&ne.role!==void 0&&k.setAllTenantsRole(ne.role)}},[y,S,k]);const U=D.filter($=>m.some(K=>K.id===$.id)),ee=$=>{const K=g.some(ne=>ne.id===$),Z=b.includes($),le=re==null?void 0:re.some(ne=>ne.groupId===$);K?k.removeSelectedGroup($):Z?k.removeGroupFromRemove($):le||k.addSelectedGroup({id:$,role:"VIEWER"})},ae=($,K)=>{k.updateSelectedGroupRole($,K)},ie=$=>{k.addGroupToRemove($),k.removeSelectedGroup($)},z=($,K,Z)=>{k.addGroupToUpdate({id:$,currentRole:K,newRole:Z})},te=v.filter($=>g.some(K=>K.id===$.id)),oe=M.useMemo(()=>y!=="groups"?[]:v.filter($=>$.type!=="TENANT_GROUP"?!1:$.name.toLowerCase().includes(i.toLowerCase())||$.description&&$.description.toLowerCase().includes(i.toLowerCase())),[v,y,i]),re=M.useMemo(()=>{var K,Z;const $=((K=S==null?void 0:S.shares)==null?void 0:K.specificGroups)||((Z=S==null?void 0:S.shares)==null?void 0:Z.groups)||[];return!$||$.length===0?[]:$.filter(le=>{const ne=v.find(je=>je.id===le.groupId);return(ne==null?void 0:ne.type)==="TENANT_GROUP"})},[S,v]),J=L||R||y==="groups"&&E,ce=O||A,de=()=>(a==null?void 0:a.type)==="tenant"||y==="all_tenants"||y==="groups"?!0:T&&(y==="specific_tenant_users"||y==="all_tenant_users");return e.jsxs(e.Fragment,{children:[ce&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(s.CircleAlert,{className:"mx-auto mb-2 h-8 w-8 text-destructive"}),e.jsx("p",{className:"mb-4 text-sm text-destructive",children:"Failed to load users or shares"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:()=>window.location.reload(),children:"Retry"})]})}),!ce&&a&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(Ss,{shareType:y,onShareTypeChange:I,currentUser:a,options:(a==null?void 0:a.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"specific_tenant_users",label:"Specific Users",description:"Share with specific tenant users",icon:e.jsx(s.User,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"groups",label:"Groups",description:"Share with tenant groups",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-green-500"})}]:[{value:"all_tenants",label:"All Tenants",description:"Share with all tenants and their users",icon:e.jsx(zs,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"all_tenant_users",label:"Specific Tenant",description:"Share with all users of a specific tenant",icon:e.jsx(s.House,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"specific_tenant_users",label:"Specific Tenant User",description:"Share with users of a specific tenant",icon:e.jsx(s.User,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(a==null?void 0:a.type)==="organization"&&(y==="specific_tenant_users"||y==="all_tenant_users")&&e.jsxs("div",{className:"mt-4",children:[e.jsx(s.Label,{className:"mb-1 block text-sm font-medium",children:"Select Tenant"}),e.jsxs(s.Select,{value:T||"",onValueChange:P,disabled:w,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:w?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(fe=C==null?void 0:C.tenants)==null?void 0:fe.map($=>e.jsx(s.SelectItem,{value:$.id,children:$.name},$.id))})]})]}),de()?e.jsx(e.Fragment,{children:y==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(ts,{value:i,onChange:u}),e.jsx(ot,{selectedUsers:m,selectedUserObjects:U,onRemove:$=>B($),onRoleChange:Y,getRoleOptions:be}),e.jsx(it,{usersToRemove:h,allUsers:D,onRemove:Q}),e.jsx(ct,{usersToUpdate:p,allUsers:D,onRemove:X,getRoleOptions:be}),e.jsx(mt,{existingShares:S,isInitialLoading:!!J,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:be,allUsers:D,currentUser:a,handleUserToggle:B,handleUserRoleChange:Y,handleRemoveAccess:_,handleUpdateAccess:q})]}):y==="groups"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(ts,{value:i,onChange:u,placeholder:"Search groups..."}),e.jsx(pt,{selectedGroups:g,groupObjects:te,onRemove:ee,onRoleChange:ae,getRoleOptions:be}),b.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-destructive",children:["Groups to Remove (",b.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"These groups will lose access when you save"})]}),x.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-orange-600",children:["Groups to Update (",x.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),e.jsx(xt,{groups:oe,existingGroupShares:re,isLoading:E,resource:t,getRoleOptions:be,currentUser:a,handleGroupToggle:ee,handleGroupRoleChange:ae,handleRemoveAccess:ie,handleUpdateAccess:z})]}):y==="all_tenant_users"||y==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(ht,{currentUser:a,currentShare:V,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:W,onRemoveAccess:G,allUsersToUpdate:j==="allTenantUsers"&&((V==null?void 0:V.role)===void 0||f!==V.role)||j==="allTenants"&&((V==null?void 0:V.role)===void 0||N!==V.role)?{currentRole:(V==null?void 0:V.role)||"VIEWER",newRole:j==="allTenantUsers"?f:N}:null,allUsersToRemove:j==="allTenantUsers"&&(V==null?void 0:V.role)===void 0||j==="allTenants"&&(V==null?void 0:V.role)===void 0})}):null}):(a==null?void 0:a.type)==="organization"&&(y==="specific_tenant_users"||y==="all_tenant_users")&&e.jsx("div",{className:"mt-6 flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(zs,{className:"mx-auto mb-2 h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Please select a tenant to continue"})]})})]})]})}function mn({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var O,R;const{searchQuery:i,setSearchQuery:d}=s.useShareSearchWithDebounce(),u=s.useShareSelectedGroups(),m=s.useShareGroupsToRemove(),h=s.useShareGroupsToUpdate(),p=s.useShareManagementActions(),[g,b]=M.useState("org_groups"),[x,j]=M.useState(""),{data:f,isLoading:N}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"&&g==="tenant_groups"}),T=Array.isArray(f)?f:(f==null?void 0:f.tenants)||[],k=()=>{if((a==null?void 0:a.type)==="organization")return"organization";if((a==null?void 0:a.type)==="tenant")return"tenant"},{groups:C,isLoading:w}=s.useShareableGroups(k(),g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"?x:a==null?void 0:a.tenantId),{existingShares:v}=ze({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n}),E=C.filter(A=>g==="org_groups"&&A.type!=="ORG_GROUP"||g==="tenant_groups"&&A.type!=="TENANT_GROUP"||g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&(!x||A.tenantId&&A.tenantId!==x)?!1:A.name.toLowerCase().includes(i.toLowerCase())||A.description&&A.description.toLowerCase().includes(i.toLowerCase())),y=((O=v==null?void 0:v.shares)==null?void 0:O.specificGroups)||((R=v==null?void 0:v.shares)==null?void 0:R.groups)||[];M.useEffect(()=>{p.setCurrentContext("group-share"),p.setCurrentMode("specificGroups")},[p]);const F=A=>{const B=A;b(B),B==="org_groups"&&j(""),r==null||r(B==="org_groups"?"specific_groups":"all_groups"),p.setCurrentContext("group-share"),p.setCurrentMode("specificGroups")},I=C.filter(A=>u.some(B=>B.id===A.id)),P=A=>{const B=u.some(Q=>Q.id===A),Y=m.includes(A),_=y==null?void 0:y.some(Q=>Q.groupId===A);B?p.removeSelectedGroup(A):Y?p.removeGroupFromRemove(A):_||p.addSelectedGroup({id:A,role:"VIEWER"})},D=(A,B)=>{p.updateSelectedGroupRole(A,B)},S=A=>{p.addGroupToRemove(A),p.removeSelectedGroup(A)},L=(A,B,Y)=>{p.addGroupToUpdate({id:A,currentRole:B,newRole:Y})};return a?e.jsxs(e.Fragment,{children:[e.jsx(Ss,{shareType:g,onShareTypeChange:F,currentUser:a,options:[{value:"org_groups",label:"Organization Groups",description:"Share with organization-level groups",icon:e.jsx(s.Building2,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"tenant_groups",label:"Tenant Groups",description:"Share with tenant-level groups",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-green-500"})}]}),g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(s.Label,{children:"Select Tenant"}),e.jsxs(s.Select,{value:x,onValueChange:j,disabled:N,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:N?"Loading tenants...":"Select a tenant to view its groups"})}),e.jsx(s.SelectContent,{className:"z-[51]",children:T.map(A=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:A.id,children:A.name},A.id))})]})]}),e.jsx("div",{className:"mt-3 space-y-2",children:g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&!x?e.jsx("div",{className:"rounded-md border border-dashed p-6 text-center",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Please select a tenant above to view and share with its groups"})}):e.jsxs(e.Fragment,{children:[e.jsx(ts,{value:i,onChange:d,placeholder:"Search groups..."}),e.jsx(pt,{selectedGroups:u,groupObjects:I,onRemove:P,onRoleChange:D,getRoleOptions:be}),m.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-destructive",children:["Groups to Remove (",m.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"These groups will lose access when you save"})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-orange-600",children:["Groups to Update (",h.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),e.jsx(xt,{groups:E,existingGroupShares:y,isLoading:w,resource:t,getRoleOptions:be,currentUser:a,handleGroupToggle:P,handleGroupRoleChange:D,handleRemoveAccess:S,handleUpdateAccess:L})]})})]}):null}const ft=()=>{const t=s.useShareCurrentContext(),n=s.useShareCurrentMode(),a=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),l=s.useShareUsersToUpdate(),o=s.useShareSelectedGroups(),c=s.useShareGroupsToRemove(),i=s.useShareGroupsToUpdate(),d=s.useShareSelectedTenant(),u=s.useShareOrgWideRole(),m=s.useShareAllTenantsRole(),h=s.useShareTenantWideRole(),p=s.useShareGroupWideRole(),g=M.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedGroups:o,groupsToRemove:c,groupsToUpdate:i,selectedTenant:d,orgWideRole:u,allTenantsRole:m,tenantWideRole:h}),[t,n,a,r,l,o,c,i,d,u,m,h,p]),b=M.useMemo(()=>j=>s.validateShareData(j),[]),x=M.useMemo(()=>{if(!t||!n)return!1;switch(t){case"org-tab":return n==="specificOrgUsers"?a.length>0||r.length>0||l.length>0:!0;case"tenant-tab":if(n==="allTenantUsers"){if(!d)return!1}else if(n==="specificTenantUsers")return d?a.length>0||r.length>0||l.length>0:!1;return!0;case"tenant-dialog":return n==="specificTenantUsers"?a.length>0||r.length>0||l.length>0:!0;case"group-share":return n==="specificGroups"?o.length>0||c.length>0||i.length>0:!0}return!1},[t,n,a,r,l,o,c,i,d]);return{buildShareData:g,validateShareData:b,isCurrentStateValid:x,currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedTenant:d,orgWideRole:u,allTenantsRole:m,tenantWideRole:h}};function Gs({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllUsersShare:d,onRemoveAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),g=s.useShareSelectedTenant(),b=s.useShareOrgWideRole(),x=s.useShareAllTenantsRole(),j=s.useShareTenantWideRole(),{buildShareData:f,validateShareData:N,isCurrentStateValid:T}=ft(),k=a||r||l,C=()=>{var F,I,P,D;if(k)return"Updating...";if(i==="specific_users"){if(m.length===0&&h.length===0&&p.length===0)return"Select users to share with";const S=m.length+h.length+p.length;return S===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${S} user${S!==1?"s":""}`:h.length>0&&m.length===0&&p.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&p.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:p.length>0&&m.length===0&&h.length===0?`Update access for ${p.length} user${p.length!==1?"s":""}`:`Update access for ${S} user${S!==1?"s":""}`}else if(i==="all_users"){if(!d||d.role===void 0)return"Share with All Users";const S=d.role;return b===S?"Remove Access":"Update Access"}else if(i==="all_tenants"){const S=(I=(F=n==null?void 0:n.shares)==null?void 0:F.allTenantsOnly)==null?void 0:I[0];if(!S||S.role===void 0)return"Share with All Tenants";const L=S.role;return x===L?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const S=(D=(P=n==null?void 0:n.shares)==null?void 0:P.tenantWide)==null?void 0:D[0];if(!S||S.role===void 0)return"Share with All Tenant Users";const L=S.role;return j===L?"Remove Access":"Update Access"}else if(i==="specific_tenant_users"){if(m.length===0&&h.length===0&&p.length===0)return"Select users to share with";const S=m.length+h.length+p.length;return S===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${S} user${S!==1?"s":""}`:h.length>0&&m.length===0&&p.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&p.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:p.length>0&&m.length===0&&h.length===0?`Update access for ${p.length} user${p.length!==1?"s":""}`:`Update access for ${S} user${S!==1?"s":""}`}return"Share"},w=()=>k||!t||i==="all_tenant_users"&&!g||i==="specific_tenant_users"&&!g?!0:!T,v=()=>{const F=f();F&&N(F)&&o(F)},E=()=>{var F,I,P,D;if(i==="all_users")if(!d||d.role===void 0){const S=f();S&&N(S)&&o(S)}else{const S=d.role;if(b===S)u==null||u();else{const O=f();if(O&&N(O)){const R={...O,updateAccess:!0};o(R)}}}else if(i==="all_tenants"){const S=(I=(F=n==null?void 0:n.shares)==null?void 0:F.allTenantsOnly)==null?void 0:I[0];if(!S||S.role===void 0){const L=f();L&&N(L)&&o(L)}else{const L=S.role;if(x===L)u==null||u();else{const R=f();if(R&&N(R)){const A={...R,updateAccess:!0};o(A)}}}}else if(i==="all_tenant_users"){const S=(D=(P=n==null?void 0:n.shares)==null?void 0:P.tenantWide)==null?void 0:D[0];if(!S||S.role===void 0){const L=f();L&&N(L)&&o(L)}else{const L=S.role;if(j===L)u==null||u();else{const R=f();if(R&&N(R)){const A={...R,updateAccess:!0};o(A)}}}}},y=()=>{var F,I,P,D;if(i==="all_users"){if(!d||d.role===void 0)return"default";const S=d.role;return b===S?"destructive":"default"}else if(i==="all_tenants"){const S=(I=(F=n==null?void 0:n.shares)==null?void 0:F.allTenantsOnly)==null?void 0:I[0];if(!S||S.role===void 0)return"default";const L=S.role;return x===L?"destructive":"default"}else if(i==="all_tenant_users"){const S=(D=(P=n==null?void 0:n.shares)==null?void 0:P.tenantWide)==null?void 0:D[0];if(!S||S.role===void 0)return"default";const L=S.role;return j===L?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:k,children:"Close"}),(i==="specific_users"||i==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(m.length>0||h.length>0||p.length>0)&&e.jsxs(s.Button,{onClick:v,disabled:!t||k,variant:"default",children:[k?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Pe,{className:"mr-2 h-4 w-4"}),!k&&C()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:E,disabled:w(),variant:y(),children:[k?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(s.Users,{className:"mr-2 h-4 w-4"}),!k&&C()]})]})}function hn({resource:t,isSharing:n,isRemoving:a,isUpdating:r,onShare:l,onClose:o,shareTabType:c,currentAllUsersShare:i}){const d=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),m=s.useShareUsersToUpdate(),h=s.useShareSelectedGroups(),p=s.useShareGroupsToRemove(),g=s.useShareGroupsToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const b=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:x,validateShareData:j,isCurrentStateValid:f}=ft(),N=n||a||r,T=()=>{if(N)return"Updating...";if(c==="specific_users"){if(d.length===0&&u.length===0&&m.length===0)return"Select users to share with";const y=d.length+u.length+m.length;return y===0?"Select users to share with":d.length>0&&u.length>0?`Update access for ${y} user${y!==1?"s":""}`:u.length>0&&d.length===0&&m.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:d.length>0&&u.length===0&&m.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:m.length>0&&d.length===0&&u.length===0?`Update access for ${m.length} user${m.length!==1?"s":""}`:`Update access for ${y} user${y!==1?"s":""}`}else if(c==="groups"){if(h.length===0&&p.length===0&&g.length===0)return"Select groups to share with";const y=h.length+p.length+g.length;return y===0?"Select groups to share with":h.length>0&&p.length>0?`Update access for ${y} group${y!==1?"s":""}`:p.length>0&&h.length===0&&g.length===0?`Remove access for ${p.length} group${p.length!==1?"s":""}`:h.length>0&&p.length===0&&g.length===0?`Share with ${h.length} group${h.length!==1?"s":""}`:g.length>0&&h.length===0&&p.length===0?`Update access for ${g.length} group${g.length!==1?"s":""}`:`Update access for ${y} group${y!==1?"s":""}`}else if(c==="all_users"){if(!i||i.role==="NONE")return"Share with All Users";const y=i.role;return b===y?"Remove Access":"Update Access"}return"Share"},k=()=>N||!t?!0:!f,C=()=>{const y=x();y&&j(y)&&l(y)},w=()=>{const y=x();y&&j(y)&&l(y)},v=()=>{if(!i||i.role==="NONE"){const y=x();y&&j(y)&&l(y)}else{const y=i.role;if(b===y){const I=x();if(I&&j(I)){const P={...I,removeAccess:!0};l(P)}}else{const I=x();if(I&&j(I)){const P={...I,updateAccess:!0};l(P)}}}},E=()=>!i||i.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:o,disabled:N,children:"Close"}),c==="specific_users"&&e.jsx(e.Fragment,{children:(d.length>0||u.length>0||m.length>0)&&e.jsxs(s.Button,{onClick:C,disabled:!t||N,variant:"default",children:[N?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Pe,{className:"mr-2 h-4 w-4"}),!N&&T()]})}),c==="groups"&&e.jsx(e.Fragment,{children:(h.length>0||p.length>0||g.length>0)&&e.jsxs(s.Button,{onClick:w,disabled:!t||N,variant:"default",children:[N?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Pe,{className:"mr-2 h-4 w-4"}),!N&&T()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:v,disabled:k(),variant:E(),children:[N?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Pe,{className:"mr-2 h-4 w-4"}),!N&&T()]})]})}function xn({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllGroupsShare:d,onRemoveAccess:u}){const m=s.useShareSelectedGroups(),h=s.useShareGroupsToRemove(),p=s.useShareGroupsToUpdate();s.useShareGroupWideRole(),s.useShareCurrentMode();const g=()=>{o({context:"group-share",mode:"specificGroups",selectedGroups:m,groupsToRemove:h,groupsToUpdate:p})},b=()=>m.length>0||h.length>0||p.length>0,x=()=>h.length>0&&m.length===0&&p.length===0?"Remove Access":p.length>0&&m.length===0&&h.length===0?"Update Access":"Share with Groups",j=a||r||l;return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[m.length>0&&e.jsxs("span",{children:[m.length," groups selected"]}),h.length>0&&e.jsxs("span",{className:"ml-2 text-destructive",children:["• ",h.length," to remove"]}),p.length>0&&e.jsxs("span",{className:"ml-2 text-orange-600",children:["• ",p.length," to update"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:j,children:"Cancel"}),e.jsxs(s.Button,{onClick:g,disabled:!b()||j,children:[j&&e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),x()]})]})]})}function ge(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function Se(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function pn(t,n,a){const{resourceType:r,resourceId:l,shareMutation:o,removeMutation:c,existingShares:i,resetUserSelections:d}=n;if(l)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const u=ge(r,l,[{scope:"org_users_only",role:t.orgWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h}=t;if(u&&u.length>0){const p=ge(r,l,u.map(g=>({scope:"specific_org_user",orgUserId:g.id,role:g.role})));o(p,{onSuccess:()=>{d()}})}if(m&&m.length>0){const p=Se(r,l,m.map(g=>{var x,j;const b=(j=(x=i==null?void 0:i.shares)==null?void 0:x.specificOrgUsers)==null?void 0:j.find(f=>f.orgUserId===g);return{scope:"specific_org_user",orgUserId:g,role:(b==null?void 0:b.role)||"VIEWER"}}));c(p,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(p=>{const g=ge(r,l,[{scope:"specific_org_user",orgUserId:p.id,role:p.newRole}]);o(g,{onSuccess:()=>{d()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const u=ge(r,l,[{scope:"all_tenants_only",role:t.allTenantsRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="allTenantUsers"){const u=ge(r,l,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h,tenantId:p}=t;if(m&&m.length>0){const g=Se(r,l,m.map(b=>{var j,f;const x=(f=(j=i==null?void 0:i.shares)==null?void 0:j.specificTenantUsers)==null?void 0:f.find(N=>N.tenantUserId===b);return{scope:"specific_tenant_user",tenantUserId:b,tenantId:p,role:(x==null?void 0:x.role)||"VIEWER"}}));c(g,{onSuccess:()=>{d()}})}if(h&&h.length>0&&h.forEach(g=>{const b=ge(r,l,[{scope:"specific_tenant_user",tenantUserId:g.id,tenantId:p,role:g.newRole}]);o(b,{onSuccess:()=>{d()}})}),u&&u.length>0){const g=ge(r,l,u.map(b=>({scope:"specific_tenant_user",tenantUserId:b.id,tenantId:p,role:b.role})));o(g,{onSuccess:()=>{d()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const u=Se(r,l,[{scope:"all_tenant_users",role:"VIEWER"}]);c(u,{onSuccess:()=>{d()}})}else if(t.updateAccess){const u=ge(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else{const u=ge(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h}=t;if(u&&u.length>0){const p=ge(r,l,u.map(g=>({scope:"specific_tenant_user",tenantUserId:g.id,role:g.role})));o(p,{onSuccess:()=>{d()}})}if(m&&m.length>0){const p=Se(r,l,m.map(g=>{var x,j;const b=(j=(x=i==null?void 0:i.shares)==null?void 0:x.specificTenantUsers)==null?void 0:j.find(f=>f.tenantUserId===g);return{scope:"specific_tenant_user",tenantUserId:g,role:(b==null?void 0:b.role)||"VIEWER"}}));c(p,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(p=>{const g=ge(r,l,[{scope:"specific_tenant_user",tenantUserId:p.id,role:p.newRole}]);o(g,{onSuccess:()=>{d()}})})}break;case"group-share":if(t.mode==="specificGroups"){const{selectedGroups:u,groupsToRemove:m,groupsToUpdate:h}=t;if(u&&u.length>0){const p=ge(r,l,u.map(g=>({scope:"group",groupId:g.id,role:g.role})));o(p,{onSuccess:()=>{var g;d(),(g=n.resetGroupSelections)==null||g.call(n),s.ue.success(`Shared with ${u.length} group${u.length!==1?"s":""}`)}})}if(m&&m.length>0){const p=Se(r,l,m.map(g=>({scope:"group",groupId:g,role:"VIEWER"})));c(p,{onSuccess:()=>{var g;d(),(g=n.resetGroupSelections)==null||g.call(n),s.ue.success(`Removed access from ${m.length} group${m.length!==1?"s":""}`)}})}h&&h.length>0&&h.forEach(p=>{const g=ge(r,l,[{scope:"group",groupId:p.id,role:p.newRole}]);o(g,{onSuccess:()=>{var b;d(),(b=n.resetGroupSelections)==null||b.call(n),s.ue.success("Updated access for group")}})})}break}}function fn(t,n,a,r){var u,m,h,p,g,b;const{resourceType:l,resourceId:o,removeMutation:c,existingShares:i,resetUserSelections:d}=r;if(o)if(t.length>0){const x=Se(l,o,t.map(j=>{var N,T;const f=(T=(N=i==null?void 0:i.shares)==null?void 0:N.specificTenantUsers)==null?void 0:T.find(k=>k.tenantUserId===j);return{scope:"specific_tenant_user",tenantUserId:j,role:(f==null?void 0:f.role)||"VIEWER"}}));c(x,{onSuccess:()=>{d()},onError:j=>{console.error("Remove access failed:",j)}})}else{const x=n==="tenant"&&a==="allTenants",j=n==="tenant"&&a==="allTenantUsers";if(x){const f=(m=(u=i==null?void 0:i.shares)==null?void 0:u.allTenantsOnly)==null?void 0:m[0];if(f){const N=Se(l,o,[{scope:"all_tenants_only",role:f.role}]);c(N,{onSuccess:()=>{d()},onError:T=>{console.error("Remove all-tenants access failed:",T)}})}}else if(j){const f=(p=(h=i==null?void 0:i.shares)==null?void 0:h.tenantWide)==null?void 0:p[0];if(f){const N=Se(l,o,[{scope:"all_tenant_users",role:f.role}]);c(N,{onSuccess:()=>{d()},onError:T=>{console.error("Remove all-tenant-users access failed:",T)}})}}else{const f=(b=(g=i==null?void 0:i.shares)==null?void 0:g.orgUsersOnly)==null?void 0:b[0];if(f){const N=Se(l,o,[{scope:"org_users_only",role:f.role}]);c(N,{onSuccess:()=>{d()},onError:T=>{console.error("Remove org-wide access failed:",T)}})}}}}function gn(t,n,a){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),o=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{currentUser:i}=s.useCurrentUserInfo(),{existingShares:d}=ze({debouncedSearchQuery:"",resourceId:t||"",resourceType:s.ResourceType.DASHBOARD,userType:"tenant"}),u=M.useCallback(()=>{r.resetUserSelections()},[r]),m=M.useCallback(()=>{r.resetGroupSelections()},[r]),h=M.useCallback(g=>{if(!t)return;const b={resourceType:s.ResourceType.DASHBOARD,resourceId:t,shareMutation:n,removeMutation:a,existingShares:d,resetUserSelections:u,resetGroupSelections:m};pn(g,b,i)},[t,n,a,d,u,m,i]),p=M.useCallback(()=>{if(!t)return;const g={resourceType:s.ResourceType.DASHBOARD,resourceId:t,removeMutation:a,existingShares:d,resetUserSelections:u};fn(l,o||"",c||"",g)},[t,n,a,d,u,m,l,o,c]);return{handleShareSubmit:h,handleRemoveAccess:p}}function ls({resource:t,resourceType:n,onClose:a,onShareSuccess:r,onRemoveSuccess:l}){var D,S,L,O,R,A,B,Y;const{currentUser:o}=s.useCurrentUserInfo(),[c,i]=M.useState("specific_users"),[d,u]=M.useState("specific_users"),[m,h]=M.useState("specific_groups"),p=s.useShareManagementActions(),g=s.useShareSelectedTab(),b=s.useShareCurrentMode(),x=s.useShareResource(),j=s.useRemoveResourceShares(),{handleShareSubmit:f,handleRemoveAccess:N}=gn(t.id,(_,Q)=>{x.mutate(_,{...Q,onSuccess:()=>{var X;(X=Q==null?void 0:Q.onSuccess)==null||X.call(Q),r==null||r()}})},(_,Q)=>{j.mutate(_,{...Q,onSuccess:()=>{var X;(X=Q==null?void 0:Q.onSuccess)==null||X.call(Q),l==null||l()}})}),T=x.isPending,k=j.isPending,C=x.isPending,{existingShares:w}=ze({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant"}),{existingShares:v}=ze({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"organization"}),E=(S=(D=w==null?void 0:w.shares)==null?void 0:D.tenantWide)==null?void 0:S[0],y=(O=(L=v==null?void 0:v.shares)==null?void 0:L.orgUsersOnly)==null?void 0:O[0],F=()=>{if(g==="org")return d;switch(b){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},I=M.useCallback(()=>{p.resetShareState(),a()},[p,a]),P=(o==null?void 0:o.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:I,children:e.jsxs(s.DialogContent,{className:"z-[51] flex max-h-[80vh] max-w-3xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Pe,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:P?"Share this resource with org users or tenant users. As a super admin, you can share with all users.":"Share this resource with other users in your tenant."})]}),P?e.jsxs(s.Tabs,{value:g,onValueChange:_=>{const Q=_;p.setSelectedTab(Q),p.resetUserSelections(),p.resetGroupSelections()},className:"mb-4 min-h-0 flex-1",children:[e.jsxs(s.TabsList,{className:"mb-2 grid w-full grid-cols-3",children:[e.jsx(s.TabsTrigger,{value:"org",children:"Org Users"}),e.jsx(s.TabsTrigger,{value:"tenant",children:"Tenant Users"}),e.jsx(s.TabsTrigger,{value:"groups",children:"Groups"})]}),e.jsx(s.TabsContent,{value:"org",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(cn,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:u,isSharing:T,isUpdating:C,isRemoving:k})})}),e.jsx(s.TabsContent,{value:"tenant",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(Us,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:_=>i(_),isSharing:T,isUpdating:C,isRemoving:k})})}),e.jsx(s.TabsContent,{value:"groups",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(mn,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:h,isSharing:T,isUpdating:C,isRemoving:k})})})]}):e.jsx("div",{className:"mb-4 min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(Us,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:_=>i(_),isSharing:T,isUpdating:C,isRemoving:k})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:P?g==="org"?e.jsx(Gs,{resource:t,existingShares:v,isSharing:T,isRemoving:k,isUpdating:C,onShare:f,onClose:a,shareTabType:d,currentAllUsersShare:y,onRemoveAccess:N}):g==="tenant"?e.jsx(Gs,{resource:t,existingShares:w,isSharing:T,isRemoving:k,isUpdating:C,onShare:f,onClose:a,shareTabType:F(),currentAllUsersShare:E,onRemoveAccess:N}):e.jsx(xn,{resource:t,existingShares:v,isSharing:T,isRemoving:k,isUpdating:C,onShare:f,onClose:a,shareTabType:m,currentAllGroupsShare:(o==null?void 0:o.type)==="organization"?(A=(R=v==null?void 0:v.shares)==null?void 0:R.allOrgGroups)==null?void 0:A[0]:(Y=(B=w==null?void 0:w.shares)==null?void 0:B.allTenantGroups)==null?void 0:Y[0],onRemoveAccess:N}):e.jsx(hn,{resource:t,isSharing:T,isRemoving:k,isUpdating:C,onShare:f,onClose:a,shareTabType:c,currentAllUsersShare:E,onRemoveAccess:N})})]})})}const jn=async(t,n,a)=>{const r=`${t}/management/v1/groups`;return await s.postRequestRegular(r,n,a)},bn=async(t,n,a)=>{const r=`${t}/management/v1/groups/${a}`,l=await fetch(r,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});if(!l.ok){const o=await l.text();throw new Error(o||"Failed to delete group")}},vn=async(t,n,a,r)=>{const l=`${t}/management/v1/groups/${a}/members`;return await s.postRequestRegular(l,n,r)},yn=async(t,n,a,r)=>{const l=`${t}/management/v1/groups/${a}/members`,o=await fetch(l,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(r)});if(!o.ok){const c=await o.text();throw new Error(c||"Failed to remove group members")}};function Nn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>jn(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r),onSuccess:()=>{a.invalidateQueries({queryKey:["groups"]}),s.ue.success("Group created successfully")},onError:r=>{console.error("Failed to create group:",r),s.ue.error("Failed to create group",{description:r.message})}})}function Cn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>bn(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r),onSuccess:(r,l)=>{a.invalidateQueries({queryKey:["groups"]}),a.removeQueries({queryKey:["group",l]}),s.ue.success("Group deleted successfully")},onError:r=>{console.error("Failed to delete group:",r),s.ue.error("Failed to delete group",{description:r.message})}})}function Sn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>vn(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r,l),onSuccess:(r,l)=>{a.invalidateQueries({queryKey:["group",l.groupId]}),a.invalidateQueries({queryKey:["group-members",l.groupId]}),a.invalidateQueries({queryKey:["groups"]}),s.ue.success("Members added successfully")},onError:r=>{console.error("Failed to add group members:",r),s.ue.error("Failed to add members",{description:r.message})}})}function wn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>yn(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r,l),onSuccess:(r,l)=>{a.invalidateQueries({queryKey:["group",l.groupId]}),a.invalidateQueries({queryKey:["group-members",l.groupId]}),a.invalidateQueries({queryKey:["groups"]}),s.ue.success("Members removed successfully")},onError:r=>{console.error("Failed to remove group members:",r),s.ue.error("Failed to remove members",{description:r.message})}})}function Dn({onSuccess:t,tenantId:n,isTenantUser:a}){const[r,l]=M.useState(""),[o,c]=M.useState(""),[i,d]=M.useState({}),u=Nn(),m=()=>{const p={};return r.trim()?r.length<3?p.name="Group name must be at least 3 characters":r.length>50&&(p.name="Group name must be less than 50 characters"):p.name="Group name is required",o&&o.length>200&&(p.description="Description must be less than 200 characters"),d(p),Object.keys(p).length===0},h=async p=>{if(p.preventDefault(),!m())return;const g={name:r.trim(),description:o.trim()||void 0,type:a?"TENANT_GROUP":"ORG_GROUP",...a&&n?{tenantId:n}:{}};try{await u.mutateAsync(g),l(""),c(""),d({}),t()}catch(b){console.error("Failed to create group:",b)}};return e.jsxs("form",{onSubmit:h,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"group-name",children:["Group Name ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(s.Input,{id:"group-name",placeholder:"e.g., Marketing Team, Engineering Squad",value:r,onChange:p=>{l(p.target.value),i.name&&d(g=>({...g,name:""}))},className:i.name?"border-destructive":"",disabled:u.isPending}),i.name&&e.jsx("p",{className:"text-sm text-destructive",children:i.name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"group-description",children:["Description",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:"(optional)"})]}),e.jsx(s.Textarea,{id:"group-description",placeholder:"Describe the purpose of this group...",value:o,onChange:p=>{c(p.target.value),i.description&&d(g=>({...g,description:""}))},className:i.description?"border-destructive":"",disabled:u.isPending,rows:3}),i.description&&e.jsx("p",{className:"text-sm text-destructive",children:i.description}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[o.length,"/200 characters"]})]}),e.jsx("div",{className:"rounded-lg border bg-muted/50 p-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(s.CircleAlert,{className:"h-4 w-4 mt-0.5 text-muted-foreground"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"This group will be accessible to users in your workspace. You can add members after creating the group."})]})})]}),e.jsxs("div",{className:"flex justify-end gap-3",children:[e.jsx(s.Button,{type:"button",variant:"outline",onClick:()=>{l(""),c(""),d({})},disabled:u.isPending,children:"Clear"}),e.jsx(s.Button,{type:"submit",disabled:u.isPending||!r.trim(),children:u.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Users,{className:"mr-2 h-4 w-4"}),"Create Group"]})})]})]})}function Tn({open:t,onOpenChange:n,group:a,onUpdate:r}){const[l,o]=M.useState("members"),[c,i]=M.useState(""),[d,u]=M.useState([]),[m,h]=M.useState([]),{data:p,isLoading:g,refetch:b}=s.useGroupMembers(a.id),x=a.type==="TENANT_GROUP"?"tenant":"organization",{users:j,isLoading:f}=s.useUnifiedUsers({type:x,tenantId:a.tenantId||void 0,active:!0,limit:100}),N=Sn(),T=wn(),k=(p==null?void 0:p.members)||[],C=M.useMemo(()=>new Set(k.map(D=>D.userId)),[k]),w=M.useMemo(()=>j.filter(D=>!C.has(D.id)),[j,C]),v=M.useMemo(()=>{if(!c)return w;const D=c.toLowerCase();return w.filter(S=>{var L,O;return((L=S.name)==null?void 0:L.toLowerCase().includes(D))||((O=S.email)==null?void 0:O.toLowerCase().includes(D))})},[w,c]),E=M.useMemo(()=>{if(!c)return k;const D=c.toLowerCase();return k.filter(S=>{var L,O,R,A;return((O=(L=S.user)==null?void 0:L.name)==null?void 0:O.toLowerCase().includes(D))||((A=(R=S.user)==null?void 0:R.email)==null?void 0:A.toLowerCase().includes(D))})},[k,c]),y=async()=>{if(d.length!==0)try{await N.mutateAsync({groupId:a.id,data:{userIds:d,userType:x==="tenant"?"tenant":"org"}}),u([]),o("members"),b(),r==null||r()}catch(D){console.error("Failed to add members:",D)}},F=async()=>{if(m.length!==0)try{await T.mutateAsync({groupId:a.id,data:{userIds:m}}),h([]),b(),r==null||r()}catch(D){console.error("Failed to remove members:",D)}},I=D=>{u(S=>S.includes(D)?S.filter(L=>L!==D):[...S,D])},P=D=>{h(S=>S.includes(D)?S.filter(L=>L!==D):[...S,D])};return e.jsx(e.Fragment,{children:e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-3xl max-h-[80vh]","aria-describedby":"group-members-description",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:a.name}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[k.length," ",k.length===1?"member":"members"]})}),e.jsxs("p",{id:"group-members-description",className:"sr-only",children:["Add or remove members from the ",a.name," group"]})]}),e.jsxs(s.Tabs,{value:l,onValueChange:D=>{o(D),i(""),h([])},className:"mt-4",children:[e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"members",children:"Current Members"}),e.jsx(s.TabsTrigger,{value:"add",children:"Add Members"})]}),e.jsxs(s.TabsContent,{value:"members",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search members...",value:c,onChange:D=>i(D.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:m.length>0?"h-[300px]":"h-[350px]",children:g?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(D=>e.jsx(s.Skeleton,{className:"h-16 w-full"},D))}):E.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:E.map(D=>e.jsx(kn,{member:D,selected:m.includes(D.userId),onToggle:()=>P(D.userId)},D.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:F,disabled:T.isPending,children:T.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:D=>i(D.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[300px]",children:f?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(D=>e.jsx(s.Skeleton,{className:"h-16 w-full"},D))}):v.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:v.map(D=>e.jsx(En,{user:D,selected:d.includes(D.id),onToggle:()=>I(D.id)},D.id))})}),d.length>0&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[d.length," user",d.length!==1?"s":""," selected"]}),e.jsx(s.Button,{onClick:y,disabled:N.isPending,children:N.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 kn({member:t,selected:n,onToggle:a}){var l,o,c,i;const r=((o=(l=t.user)==null?void 0:l.name)==null?void 0:o.split(" ").map(d=>d[0]).join("").toUpperCase())||"?";return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-card hover:bg-muted/50 cursor-pointer",onClick:a,children:[e.jsx(s.Checkbox,{checked:n}),e.jsx(s.Avatar,{className:"h-8 w-8",children:e.jsx(s.AvatarFallback,{className:"text-xs",children:r})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:((c=t.user)==null?void 0:c.name)||"Unknown User"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(i=t.user)==null?void 0:i.email})]})]})}function En({user:t,selected:n,onToggle:a}){var l;const r=((l=t.name)==null?void 0:l.split(" ").map(o=>o[0]).join("").toUpperCase())||"?";return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-card hover:bg-muted/50 cursor-pointer",onClick:a,children:[e.jsx(s.Checkbox,{checked:n}),e.jsx(s.Avatar,{className:"h-8 w-8",children:e.jsx(s.AvatarFallback,{className:"text-xs",children:r})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:t.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t.email})]})]})}function In({open:t,onOpenChange:n}){const[a,r]=M.useState("groups"),[l,o]=M.useState(""),[c,i]=M.useState(null),[d,u]=M.useState(!1),[m,h]=M.useState(null),{tokenProps:p}=s.useSemaphorContext(),{currentUser:g}=s.useCurrentUserInfo(),b=Cn(),x=(g==null?void 0:g.type)==="tenant",j=p==null?void 0:p.tenantId,{groups:f,isLoading:N,refetch:T}=s.useGroups({type:x?"TENANT_GROUP":"all",tenantId:x?j:void 0,includeMembers:!1}),k=f.filter(E=>{var y;return E.name.toLowerCase().includes(l.toLowerCase())||((y=E.description)==null?void 0:y.toLowerCase().includes(l.toLowerCase()))}),C=async()=>{if(m)try{await b.mutateAsync(m.id),h(null),T()}catch(E){console.error("Failed to delete group:",E)}},w=E=>{i(E),u(!0)},v=()=>{r("groups"),T()};return e.jsxs(e.Fragment,{children:[e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-4xl max-h-[80vh]",children:[e.jsxs(s.DialogHeader,{children:[e.jsxs(s.DialogTitle,{className:"flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-5 w-5"}),"Group Management"]}),e.jsx(s.DialogDescription,{children:"Manage your groups, create new groups, and control group membership"})]}),e.jsxs(s.Tabs,{value:a,onValueChange:r,className:"mt-4",children:[e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsxs(s.TabsTrigger,{value:"groups",className:"flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-4 w-4"}),"Groups"]}),e.jsxs(s.TabsTrigger,{value:"create",className:"flex items-center gap-2",children:[e.jsx(s.Plus,{className:"h-4 w-4"}),"Create Group"]})]}),e.jsx(s.TabsContent,{value:"groups",className:"mt-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search groups...",value:l,onChange:E=>o(E.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[400px]",children:N?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(E=>e.jsx(s.Skeleton,{className:"h-24 w-full"},E))}):k.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:k.map(E=>e.jsx(An,{group:E,onManageMembers:()=>w(E),onDelete:()=>h(E),currentUserId:g==null?void 0:g.id},E.id))})})]})}),e.jsx(s.TabsContent,{value:"create",className:"mt-4",children:e.jsx(Dn,{onSuccess:v,tenantId:j,isTenantUser:x})})]})]})}),c&&e.jsx(Tn,{open:d,onOpenChange:u,group:c,onUpdate:()=>T()}),e.jsx(s.AlertDialog,{open:!!m,onOpenChange:()=>h(null),children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Group"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',m==null?void 0:m.name,'"? This action cannot be undone and will remove all members from the group.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:C,disabled:b.isPending,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:b.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Deleting..."]}):"Delete Group"})]})]})})]})}function An({group:t,onManageMembers:n,onDelete:a,currentUserId:r}){const l=t.createdBy===r;return e.jsx("div",{className:"rounded-lg border bg-card p-4 transition-colors hover:bg-muted/50",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium",children:t.name}),t.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:t.description})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(s.Users,{className:"h-3 w-3"}),t.memberCount," ",t.memberCount===1?"member":"members"]}),e.jsxs("span",{children:["Created ",s.format(new Date(t.createdAt),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:n,title:"Manage members",children:e.jsx(s.UserPlus,{className:"h-4 w-4"})}),l&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:a,title:"Delete group",className:"text-destructive hover:text-destructive",children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]})})}function Mn(){var te,oe,re;const{authToken:t,tokenProps:n,id:a}=s.useSemaphorContext(),{isLocalDev:r}=s.useDashboardPreferences(),{permissions:l}=s.useRoleAwareDisplayPreferences(),o=s.useHasDashboardId();s.useDashboardStore(J=>J.theme);const c=s.useDashboardStore(J=>J.lenses),i=s.useDashboardStore(J=>J.selectedLensId),d=c==null?void 0:c.find(J=>J.id===i),u=s.useDashboardStore(J=>J.dashboard);s.useDashboardStore(J=>J.selectedSheetId);const m=s.useDashboardStore(J=>J.isDashboardEditing),[h,p]=M.useState(!1),[g,b]=M.useState(!1),[x,j]=M.useState(!1),f=s.useDashboardStore(J=>J.isDashboardPanelOpen),N=s.useDashboardStore(J=>J.actions.setIsDashboardPanelOpen),T=s.useDashboardStore(J=>J.filterValues),k=s.useDashboardStore(J=>J.isVisualEditing),C=s.useManagementStore(J=>J.selectedDashboard),w=s.useManagementStore(J=>J.initialDashboard),v=C?(oe=C==null?void 0:C.permissions)==null?void 0:oe.canEdit:(te=w==null?void 0:w.permissions)==null?void 0:te.canEdit,E=s.useDashboardStore(J=>J.showFilters),y=s.useDashboardStore(J=>J.showDashboardJSON),F=s.useDashboardStore(J=>J.onSaveFunction),I=s.useDashboardStore(J=>J.actions.setShowFilters),{setIsDashboardEditing:P,setShowDashboardJSON:D}=s.useDashboardStore(J=>J.actions),{setInitialDashboard:S,clearSelectedDashboard:L}=s.useManagementStore(J=>J.actions),{resources:O}=s.useResourceManagement(s.ResourceType.DASHBOARD),{currentUser:R}=s.useCurrentUserInfo(),A=s.canUserManageGroups(R),B=C||w,Y=B?{id:B.id,title:(u==null?void 0:u.title)||B.title||"Dashboard"}:null;M.useEffect(()=>{if(O&&O.length>0){const J=u==null?void 0:u.id;if(J){const ce=O.find(de=>de.id===J);ce&&S(ce)}}},[O,u==null?void 0:u.id,S]);const _=n.orgUserId||n.tenantId,Q=m&&!k&&_&&v,{handleAddNewFrame:X}=s.useAddNewFrame(),q=()=>{P(!0)},[W,G]=M.useState(!1),se=s.useUpdateResource(s.ResourceType.DASHBOARD);async function V(){const J=ss(u);G(!0);const ce={template:J};se.mutate({resourceId:J.id,data:ce},{onSuccess:()=>{G(!1),s.ue.success("Dashboard saved!")},onError:()=>{G(!1),s.ue.error("Failed to save dashboard")}})}async function U(){if(p(!0),!i||!d)return;const J=ss(u),ce=JSON.stringify(J),de={...d,template:ce,filterValues:T};await vs(n.apiServiceUrl,de,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),F==null||F(J),p(!1)}if(k)return null;const ee=(d==null?void 0:d.name)||u.title,ie=O&&O.length>0&&(n.orgUserId||n.tenantId&&n.endUserId&&n.endUserEmail),z=C&&!(n!=null&&n.dashboard_id)&&!a;return e.jsxs("div",{className:"flex h-10 items-center justify-between gap-2 border-b py-2 pl-3 pr-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[ie&&e.jsxs(e.Fragment,{children:[z&&e.jsx(s.IconButton,{"aria-label":"Dashboard Hub",tooltip:"Back to Dashboard Hub",onClick:()=>L(),className:"h-7 p-2",children:e.jsx(s.House,{className:"h-4 w-4"})}),e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:o?"Manage Dashboards":"Select a dashboard to continue",onClick:()=>{o&&N(!f)},className:"h-7 p-2",buttonProps:{disabled:!o},children:e.jsx(Da,{className:"h-4 w-4"})})]}),!k&&o&&e.jsx(s.Label,{children:ee})]}),e.jsxs("div",{className:"flex gap-2",children:[r&&e.jsx(s.IconButton,{tooltip:"Invalidate Token",onClick:()=>s.invalidateToken(n.apiServiceUrl),className:"h-7 p-2",children:e.jsx(Ba,{className:"h-4 w-4"})}),!k&&o&&e.jsx(Ja,{}),!k&&o&&e.jsx(lt,{}),!k&&o&&A&&e.jsx(s.IconButton,{tooltip:"Manage Groups",onClick:()=>j(!0),className:"h-7 p-2",children:e.jsx(s.Users,{className:"h-4 w-4"})}),!k&&o&&((re=B==null?void 0:B.permissions)==null?void 0:re.canShare)&&e.jsx(s.IconButton,{tooltip:"Share Dashboard",onClick:()=>b(!0),className:"h-7 p-2",children:e.jsx(s.UserPlus,{className:"h-4 w-4"})}),m&&!k&&_&&r&&o&&e.jsx(Ka,{}),!k&&_&&r&&o&&e.jsx(Qa,{}),m&&!k&&_&&d&&r&&o&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:h,onClick:U,size:"sm",children:[e.jsx(bs,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),m&&!k&&o&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",size:"sm",disabled:!m,onClick:()=>X(),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Visual"]}),!k&&!m&&l.canEdit&&o&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:q,size:"sm",children:[e.jsx(s.Pencil,{className:"mr-2 h-4 w-4"}),"Edit"]}),m&&!k&&o&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:()=>{P(!1),D(!1)},children:[e.jsx(s.Cross2Icon,{className:"mr-2 h-4 w-4"}),"Close"]}),Q&&o&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"outline",disabled:W,onClick:V,size:"sm",children:[W?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(bs,{className:"mr-2 h-4 w-4"}),W?"Saving...":"Save"]}),!E&&!k&&m&&l.canUseFilters&&o&&e.jsx(s.Button,{className:"h-7 p-2",variant:"outline",onClick:()=>I(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!k&&m&&r&&o&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(s.Button,{className:"h-7 p-2",onClick:()=>D(!y),size:"sm",variant:"ghost",children:e.jsx(Be,{className:"h-4 w-4"})})}),!k&&r&&e.jsx($a,{}),g&&Y&&e.jsx(ls,{resource:Y,resourceType:s.ResourceType.DASHBOARD,onClose:()=>b(!1)}),e.jsx(In,{open:x,onOpenChange:j})]})]})}function Ln({name:t,items:n,value:a,onChange:r,isLoading:l,isError:o,refetch:c,className:i,icon:d,showNone:u=!1}){const m=Ee.useRef(null),[h,p]=Ee.useState(!1),[g,b]=Ee.useState("100%"),x=u?[...n||[],{id:"none",name:"None"}]:n;Ee.useLayoutEffect(()=>{m.current&&b(m.current.offsetWidth)},[]);function j(){var N;return l?"Loading...":o?"Error":a?(N=n==null?void 0:n.find(T=>T.id===a))==null?void 0:N.name:`Select ${t}`}function f(N,T){r(T),p(!1)}return e.jsxs(s.Popover,{open:h,onOpenChange:p,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{ref:m,variant:"outline",role:"combobox","aria-expanded":h,className:s.cn("flex h-9 w-full justify-between",i),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[d&&e.jsx("div",{className:"mr-2",children:d}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children:j()})]}),e.jsx(s.ChevronDown,{className:"size-4 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-full p-0",style:{minWidth:g},children:e.jsxs(s.Command,{children:[e.jsxs("div",{className:"flex h-9 items-center justify-between border-b pr-1",children:[e.jsx(s.CommandInput,{className:"h-9",placeholder:"Search..."}),e.jsx(s.IconButton,{className:"h-7",onClick:c,children:e.jsx(st,{className:s.cn("size-3.5 opacity-50",l&&"animate-spin")})})]}),e.jsxs(s.CommandList,{children:[e.jsxs(s.CommandEmpty,{children:["No ",t==null?void 0:t.toLowerCase()," found."]}),e.jsx(s.CommandGroup,{children:x==null?void 0:x.map(N=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:N.name,onSelect:T=>f(T,N.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",a===N.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:N.name,children:N.name})]})},N.id))})]})]})})]})}function Fe({title:t,items:n,value:a,isLoading:r,isError:l,refetch:o,onChange:c,showNone:i=!1,className:d,disabled:u=!1,type:m="combobox"}){const h=r?"Loading...":l?"Error":a;function p(){if(t==="Connection")return e.jsx(Oa,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(Aa,{className:"size-4"});if(t==="Table")return e.jsx(s.Table2,{className:"size-4"});if(t==="Model")return e.jsx(oa,{className:"size-4"})}function g(){return e.jsxs(s.Select,{disabled:u,value:h,onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:s.cn("h-9 w-full border-muted focus:ring-1 focus:ring-offset-0",d),children:e.jsx(s.SelectValue,{placeholder:r?"Loading...":l?"Error":`Select ${t}`})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[r?e.jsx(s.SelectLabel,{children:"Loading..."}):e.jsxs(s.SelectLabel,{className:"flex items-center justify-between gap-2",children:[t,e.jsx(st,{className:s.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:o})]}),e.jsxs(e.Fragment,{children:[i&&e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),n&&n.map((x,j)=>e.jsx(s.SelectItem,{value:x.id,children:x.name},j))]}),(r||l)&&e.jsx(s.SelectItem,{value:h,children:h})]})})]})}function b(){return e.jsx(Ln,{icon:p(),items:n,value:h,onChange:c||(()=>{}),isLoading:r,isError:l,refetch:o,name:t,showNone:i})}return e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:m==="select"?g():b()})})}function Rn({column:t}){const[n,a]=M.useState(!1),r=s.useEditorStore(x=>x.selectedTableName),l=s.useEditorStore(x=>x.selectedSchemaName),o=s.useEditorStore(x=>x.selectedDatabaseName),c=s.useEditorStore(x=>x.selectedDatamodelId),i=s.useEditorStore(x=>x.sqlGen),{modelItems:d,connectionType:u}=s.useEditorAside(),m=s.useEditorStore(x=>x.actions.setSqlGen),h=s.useEditorStore(x=>x.actions.setCardSql),p=s.useEditorStore(x=>x.actions.setRunSql);function g(x,j){var k;const f=s.createSqlGenConfig(x,i,j),N=(k=d==null?void 0:d.find(C=>C.id===c))==null?void 0:k.name;m(f);const T=s.getSql(f,s.fmt(l||""),s.fmt(r),N||"",u,o||"");T&&(h(T),p(!0)),a(!1)}function b(){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 e.jsxs(s.HoverCard,{openDelay:0,open:n,onOpenChange:a,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:b()})]})}function On({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ve,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Le,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Be,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Ye,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(He,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ve,{className:"h-3 w-3"})})}function ds({column:t,className:n}){return e.jsxs("div",{className:s.cn("flex min-h-8 grow items-center gap-2 px-3 py-[6px] text-sm",n),children:[e.jsx(On,{dataType:t.data_type}),e.jsx("span",{children:t.column_name})]})}function Fn({id:t,children:n,type:a="column"}){const{attributes:r,listeners:l,setNodeRef:o,transform:c}=s.useDraggable({id:t,data:{type:a}}),i=c?{translate:s.CSS.Translate.toString(c),transform:s.CSS.Transform.toString(c)}:void 0;return e.jsx("div",{ref:o,style:i,...l,...r,children:n})}function Pn({onClick:t,column:n}){const a=s.useDndStore(m=>m.activeId),r=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.groupByColumns}),l=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.metricColumns}),o=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.filterColumns});function c(m){return i(m)||d(m)||u(m)}function i(m){return r==null?void 0:r.some(h=>h.name===m.column_name)}function d(m){return l==null?void 0:l.some(h=>h.name===m.column_name)}function u(m){return o==null?void 0:o.some(h=>h.name===m.column_name)}return e.jsxs("div",{onClick:()=>t(n),className:s.cn("group relative grow cursor-pointer overflow-x-hidden overflow-y-hidden border border-dashed border-background transition-colors hover:bg-muted/50",{"bg-muted":c(n)}),children:[a===n.column_name&&e.jsx(s.DragOverlay,{children:e.jsx(ds,{column:n,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),a===n.column_name&&e.jsx("div",{className:"absolute inset-0",children:a===n.column_name&&e.jsx(ds,{column:n})}),e.jsx(Fn,{id:n.column_name,type:"column",children:e.jsx(ds,{column:n})})]})}const us={id:"__placeholder__",role:"groupby",type:"string"},ms={id:"__placeholder__",role:"groupby",type:"string"},hs={id:"__placeholder__",role:"metric",type:"number"},xs={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},gt={id:"__placeholder__"},Ie="droppable-group-by",Ae="droppable-metrics",Me="droppable-pivot-by",as="sortable-group-by",ys="sortable-metrics",ns="sortable-pivot-by",Ns="droppable-filters",Cs="sortable-filters",ws="sortable-order-by";function Bn(){const t=s.useDndStore(S=>S.insertIndex),n=s.useEditorStore(S=>{var L;return((L=S.card.queryConfig)==null?void 0:L.groupByColumns)||[]}),a=s.useEditorStore(S=>{var L;return((L=S.card.queryConfig)==null?void 0:L.metricColumns)||[]}),r=s.useEditorStore(S=>{var L;return((L=S.card.queryConfig)==null?void 0:L.filterColumns)||[]}),l=s.useEditorStore(S=>{var L;return((L=S.card.queryConfig)==null?void 0:L.orderBy)||[]}),o=s.useEditorStore(S=>{var L;return((L=S.card.queryConfig)==null?void 0:L.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:i,setPreviewGroupByColumns:d,setPreviewMetricColumns:u,setPreviewFilterColumns:m,setPreviewPivotColumns:h}=s.useDndActions(),{setGroupByColumns:p,setMetricColumns:g,setFilterColumns:b,setOrderByColumns:x,setPivotByColumns:j}=s.useEditorActions(),{columns:f}=s.useDataColumns(),{formattedTableName:N}=s.useEditorAside(),T=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),k=S=>{var R;const{active:L,over:O}=S;if(((R=L.data.current)==null?void 0:R.type)==="column"&&O){const A=O.id,B=f.find(X=>X.column_name===L.id);if(!B)return;const Y=s.isNumberDataType(B.data_type),_=s.isTextDataType(B.data_type),Q=s.isDateDataType(B.data_type);if(_||Q){if(n.some(q=>q.id===A)){const q=n.findIndex(G=>G.id===A);c(q);const W=n.filter(G=>G.id!==us.id);W.splice(q,0,us),d(W)}else if(O.id===Ie){c(n.length);const q=[...n,us];d(q),u(a),m(r)}}if(_||Q){if(o.some(q=>q.id===A)){const q=o.findIndex(G=>G.id===A);c(q);const W=o.filter(G=>G.id!==ms.id);W.splice(q,0,ms),h(W)}else if(O.id===Me){c(o.length);const q=[...o,ms];h(q),d(n),u(a),m(r)}}if(Y||_){if(a.some(q=>q.id===A)){console.log("isOverMetricSortable",A);const q=a.findIndex(G=>G.id===A);c(q);const W=a.filter(G=>G.id!==hs.id);W.splice(q,0,hs),u(W)}else if(O.id===Ae){c(a.length);const q=[...a,hs];u(q),m(r),d(n),h(o)}}if(w(B)){if(r.some(q=>q.id===A)){const q=r.findIndex(G=>G.id===A);c(q);const W=r.filter(G=>G.id!==xs.id);W.splice(q,0,xs),m(W)}else if(O.id===Ns){c(r.length);const q=[...r,xs];m(q),u(a),d(n),h(o)}}}else d(n),u(a),m(r),h(o)};function C(S){i(S.active.id),c(null),d(n),u(a),m(r),h(o)}function w(S){return!r.some(L=>L.name===S.column_name)}function v(S,L="SUM"){const{column_name:O,data_type:R}=S,A=[...a],B=t!==null?t:a.length,Y={...S,id:Ne(O),name:O,label:qe(O,L),type:R,role:"metric",aggregate:L};A.splice(B,0,Y),g(A)}function E(S){const L=s.isTextDataType(S.data_type);s.isDateDataType(S.data_type);const O=[...o],R=t!==null?t:o.length;let A;L?A={...S,id:Ne(S.column_name),name:S.column_name,type:S.data_type,role:"groupby"}:A={...S,id:Ne(S.column_name),name:S.column_name,type:S.data_type,role:"groupby",label:_e(S.column_name,"month"),granularity:"month"},O.splice(R,0,A),j(O)}function y(S){const L=s.isTextDataType(S.data_type);s.isDateDataType(S.data_type);const O=[...n],R=t!==null?t:n.length;let A;L?A={...S,id:Ne(S.column_name),name:S.column_name,type:S.data_type,role:"groupby"}:A={...S,id:Ne(S.column_name),name:S.column_name,type:S.data_type,role:"groupby",label:_e(S.column_name,"month"),granularity:"month"},O.splice(R,0,A),p(O)}function F(S){const L=[...r],O=t!==null?t:r.length,R={...S,id:Ne(S.column_name),name:S.column_name,type:S.data_type,sql:s.getDefaultFilterSql(S.data_type,N,s.fmt(S.column_name)),role:"filter"};L.splice(O,0,R),b(L)}function I(S){var A,B,Y,_,Q,X,q,W;const{active:L,over:O}=S,R=L.data.current;if((R==null?void 0:R.type)==="column"&&O){const G=f.find(ee=>ee.column_name===L.id);if(!G)return;const se=s.isNumberDataType(G.data_type),V=s.isTextDataType(G.data_type),U=s.isDateDataType(G.data_type);(V||U)&&(O.id===Ie||((A=O.data.current)==null?void 0:A.type)===as)&&y(G),(V||U)&&(O.id===Me||((B=O.data.current)==null?void 0:B.type)===ns)?E(G):(se||V)&&(O.id===Ae||((Y=O.data.current)==null?void 0:Y.type)===ys)?(se&&v(G),V&&v(G,"COUNT")):w(G)&&(O.id===Ns||((_=O.data.current)==null?void 0:_.type)===Cs)&&F(G)}if(O&&((Q=O.data.current)==null?void 0:Q.type)===as&&n.some(G=>G.id===L.id)){const G=n.findIndex(V=>V.id===L.id),se=n.findIndex(V=>V.id===O.id);if(G!==-1&&se!==-1&&G!==se){const V=[...n],[U]=V.splice(G,1);V.splice(se,0,U),p(V)}}if(O&&((X=O.data.current)==null?void 0:X.type)===ns&&o.some(G=>G.id===L.id)){const G=o.findIndex(V=>V.id===L.id),se=o.findIndex(V=>V.id===O.id);if(G!==-1&&se!==-1&&G!==se){const V=[...o],[U]=V.splice(G,1);V.splice(se,0,U),j(V)}}if(O&&((q=O.data.current)==null?void 0:q.type)===ys&&a.some(G=>G.id===L.id)){const G=a.findIndex(V=>V.id===L.id),se=a.findIndex(V=>V.id===O.id);if(G!==-1&&se!==-1&&G!==se){const V=[...a],[U]=V.splice(G,1);V.splice(se,0,U),g(V)}}if(O&&((W=O.data.current)==null?void 0:W.type)===Cs&&r.some(G=>G.id===L.id)){const G=r.findIndex(V=>V.id===L.id),se=r.findIndex(V=>V.id===O.id);if(G!==-1&&se!==-1&&G!==se){const V=[...r],[U]=V.splice(G,1);V.splice(se,0,U),b(V)}}P(S),i(null),c(null),d(n),u(a),m(r),h(o)}function P(S){const{active:L,over:O}=S,R=L.data.current;if((R==null?void 0:R.type)===ws&&O){const A=l.findIndex(Y=>Ge(Y.columnId)===L.id),B=l.findIndex(Y=>Ge(Y.columnId)===O.id);if(A!==-1&&B!==-1&&A!==B){const Y=[...l],[_]=Y.splice(A,1);Y.splice(B,0,_),x(Y)}}}function D(){i(null),c(null),d(n),u(a),m(r)}return{handleDragOver:k,handleDragEnd:I,handleDragStart:C,handleDragCancel:D,sensors:T}}function Ne(t){return`${t}-${s.v4()}`}function qe(t,n){const a=s.toTitleCase(t.replace(/_/g," "));switch(n){case"SUM":return`Sum of ${a}`;case"COUNT":return`Count of ${a}`;case"DISTINCT":return`Unique ${a}`;case"AVG":return`Average of ${a}`;case"MIN":return`Min of ${a}`;case"MAX":return`Max of ${a}`;default:return a}}function Ge(t){return`${ws}-${t}`}function _e(t,n){const a=s.toTitleCase(t.replace(/_/g," "));switch(n){case"day":return`Date of ${a}`;case"week":return`Week of ${a}`;case"month":return`Month of ${a}`;case"year":return`Year of ${a}`;default:return a}}function zn({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ve,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Le,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Be,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Ye,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(He,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ve,{className:"h-3 w-3"})})}function _n({schemaName:t,tableName:n,columns:a,status:r}){const[l,o]=M.useState(""),[c,i]=M.useState("all"),d=s.useEditorStore(A=>A.sqlGen),u=s.useEditorStore(A=>A.isDevMode);s.useEditorStore(A=>A.selectedConnectionId);const m=s.useEditorStore(A=>{var B,Y;return(Y=(B=A.card)==null?void 0:B.queryConfig)==null?void 0:Y.metricColumns});s.useEditorStore(A=>{var B,Y;return(Y=(B=A.card)==null?void 0:B.queryConfig)==null?void 0:Y.groupByColumns});const h=s.useEditorStore(A=>A.selectedDatabaseName);s.useEditorStore(A=>A.selectedSchemaName),s.useEditorStore(A=>A.selectedTableName);const p=s.useEditorStore(A=>A.selectedDatamodelId);s.useDashboardStore(A=>A.dashboard.aiScopeTables);const{addToAIScope:g,removeFromAIScope:b}=s.useDashboardActions(),{addColumnToMetricColumns:x,addColumnToGroupBy:j,setCardSql:f,setRunSql:N,setSqlGen:T,setIsShowingVisual:k}=s.useEditorActions(),{connectionType:C,modelItems:w,selectedDatamodelName:v}=s.useEditorAside();function E(A){var B;if(u){const Y=s.createSqlGenConfig(A,d);T(Y);const _=(B=w==null?void 0:w.find(X=>X.id===p))==null?void 0:B.name,Q=s.getSql(Y,s.fmt(t),s.fmt(n),_||"",C,h||"");Q&&(f(Q),N(!0))}if(!u){if(s.isTextDataType(A.data_type))if(m&&m.length>0){const Y={...A,role:"groupby",id:Ne(A.column_name),name:A.column_name,type:A.data_type};j(Y)}else{const Y={...A,role:"metric",id:Ne(A.column_name),name:A.column_name,label:qe(A.column_name,"COUNT"),type:A.data_type,aggregate:"COUNT"};x(Y)}if(s.isDateDataType(A.data_type)){const Y={...A,role:"groupby",id:Ne(A.column_name),name:A.column_name,type:A.data_type,label:_e(A.column_name,"month"),granularity:"month"};j(Y)}if(s.isNumberDataType(A.data_type)){const Y={...A,role:"metric",id:Ne(A.column_name),name:A.column_name,label:qe(A.column_name,"SUM"),type:A.data_type,aggregate:"SUM"};x(Y)}}}function y(){const A=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:v,connectionType:C,databaseName:h||""});k(!1);const B=C==="MSSQL"?`SELECT top 10 * FROM ${A}`:`SELECT * FROM ${A} LIMIT 10`;f(B),N(!0)}function F(){const A=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:v,connectionType:C,databaseName:h||""});f(`SELECT COUNT(*) as count FROM ${A}`),N(!0)}const I=(a==null?void 0:a.filter(A=>A.column_name.toLowerCase().includes(l.toLowerCase())))||[],P=A=>s.isNumberDataType(A.data_type)?"number":"text",D=c==="all"?I:I.filter(A=>P(A)===c),S=I.filter(A=>P(A)==="text").length,L=I.filter(A=>P(A)==="number").length;function O(A){return u?e.jsxs("div",{className:"group flex cursor-pointer items-center justify-between border border-dashed border-background px-2 py-[6px] text-sm transition-colors hover:bg-muted/50",onClick:()=>E(A),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zn,{dataType:A.data_type}),e.jsx("span",{children:A.column_name})]}),e.jsx("div",{onClick:B=>B.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(A.data_type)&&e.jsx(Rn,{column:A})})]}):e.jsx(Pn,{onClick:E,column:A})}function R(){return e.jsxs("div",{className:"flex grow gap-2",children:[e.jsxs(s.Button,{disabled:r!=="Success",onClick:y,size:"sm",variant:"secondary",className:"grow",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(wa,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:F,size:"sm",variant:"secondary",className:"grow",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(tt,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-4",children:Array.from({length:3}).map((A,B)=>e.jsx(s.Skeleton,{className:"h-8 w-full"},B))}):e.jsxs("div",{className:"flex grow flex-col",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-3 px-4",children:[u&&e.jsx("div",{className:"flex items-center justify-center gap-2",children:R()}),a&&a.length>0&&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 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:l,onChange:A=>o(A.target.value)})]}),I.length>0&&e.jsx(s.Tabs,{defaultValue:"all",value:c,onValueChange:A=>i(A),children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-3",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:I.length})]}),e.jsxs(s.TabsTrigger,{value:"text",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:S})]}),e.jsxs(s.TabsTrigger,{value:"number",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:L})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-4 pt-3",children:[D.length===0&&l&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',l,'"']}),D.length===0&&!l&&c!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",c," fields found"]}),e.jsx("div",{className:"flex flex-col gap-1",children:D==null?void 0:D.map(A=>e.jsx("div",{children:O(A)},A.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function jt({ColumnsComponent:t,type:n}){var K;const[a,r]=M.useState(!1),l=s.useEditorStore(Z=>Z.card),o=s.useEditorStore(Z=>Z.selectedConnectionId),c=s.useDashboardStore(Z=>Z.showFilters),i=s.useEditorStore(Z=>Z.selectedDatamodelId),d=s.useEditorStore(Z=>Z.selectedDatabaseName),u=s.useEditorStore(Z=>Z.selectedSchemaName),m=s.useEditorStore(Z=>Z.selectedTableName),h=s.useEditorStore(Z=>Z.isDevMode),{setSelectedTableName:p,setIsDevMode:g,setCardSql:b}=s.useEditorActions(),{connectionItems:x,modelItems:j,schemaItems:f,databaseItems:N,tableItems:T,columns:k,isConnectionsLoading:C,isModelsLoading:w,isConnectionsError:v,isModelsError:E,isDatabasesLoadingOrFetching:y,isDatabaseError:F,isSchemaLoadingOrFetching:I,isSchemaError:P,isColumnsError:D,isColumnsLoadingOrFetching:S,isTableLoadingOrFetching:L,isTableError:O,connectionType:R,isNonDbConnection:A,refetchDatabases:B,refetchModels:Y,refetchSchemas:_,refetchTables:Q,refetchColumns:X,refetchConnections:q,handleConnectionChange:W,handleDatabaseChange:G,handleSchemaChange:se,handleDatamodelChange:V,handleTableChange:U,tableName:ee,schemaName:ae}=s.useEditorAside(),{data:ie,refetch:z}=s.useDashboardCardQuery(l);function te(){return t?t(ae,ee,k):e.jsx(_n,{schemaName:ae,tableName:ee,columns:k,status:S?"Loading...":D?"Error":"Success"})}function oe(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function re(Z){Z===!0?ie&&(b(ie.userSql),setTimeout(()=>{z()},100)):b(""),g(Z)}function J(){if(!o||R==="S3"||R==="API")return null;if(!i||i==="none")return e.jsx(Fe,{refetch:B,showNone:!0,onChange:G,isError:F,isLoading:y,items:N,value:d||"",title:"Database",type:"combobox"})}function ce(){if(o&&!A&&(!d||d==="none")&&(!i||i==="none"))return e.jsxs("div",{className:"grid grid-cols-3",children:[e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Label,{children:"OR"})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})})]})}function de(){if(!o||R==="S3"||R==="API")return null;if(!d||d==="none")return e.jsx(Fe,{refetch:Y,showNone:!0,onChange:V,isError:E,isLoading:w,items:j,value:i||"",title:"Model",type:"combobox"})}function fe(){return!o||R==="S3"||R==="API"||!d||d==="none"?null:e.jsx(Fe,{refetch:_,onChange:se,isError:P,isLoading:I,items:f,value:u||"",title:"Schema",type:"combobox"})}function $(){function Z(){let le=!1;return R==="API"?(le=!1,le):((R==="S3"||o&&d&&d!=="none"&&u)&&(le=!0),le)}return Z()?e.jsx(Fe,{refetch:Q,onChange:U,isError:O,items:T,isLoading:L,value:m||"",title:"Table",type:"combobox"}):null}return e.jsxs("aside",{className:s.cn("flex h-full min-w-[310px] max-w-[310px] flex-col justify-between rounded-none",{"border-r-[1px]":!c}),children:[e.jsxs("section",{className:s.cn("px-4",{"px-4 pb-0 pt-4":a,"px-4 py-4":!a}),children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Direct Source"}),e.jsx(s.Button,{onClick:()=>r(!a),size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:a?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronUp,{className:"h-4 w-4"})})]}),!a&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(Fe,{refetch:q,items:x,title:"Connection",value:o||"",onChange:W,isLoading:C,isError:v,type:"combobox",connectionTooltip:((K=x==null?void 0:x.find(Z=>Z.id===o))==null?void 0:K.type)||""}),J(),ce(),de(),fe(),$()]})]}),te(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:n==="main"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Switch,{className:"data-[state=checked]:bg-muted-foreground/80",checked:h,onCheckedChange:re,id:"dev-mode"}),e.jsx(s.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(s.Button,{onClick:oe,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(Ta,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function bt({error:t,errorSql:n,onSendFeedback:a,className:r,showFeedbackButton:l=!0}){const[o,c]=M.useState(!1);return e.jsx("div",{className:s.cn("rounded-lg border border-destructive/30 bg-destructive/5 p-4",r),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(s.CircleAlert,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-destructive"}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-destructive",children:"Query Error"}),e.jsxs("div",{className:"relative rounded-md bg-background/60 p-3",children:[e.jsx(s.CopyButton,{text:t,className:"absolute right-2 top-2 h-6 w-6 z-10"}),e.jsx("div",{className:"max-h-40 overflow-auto pr-10",children:e.jsx("p",{className:"font-mono text-xs text-foreground/80 break-all",children:t})})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n&&e.jsx(s.Collapsible,{open:o,onOpenChange:c,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"]})})})}),l&&a&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:a,children:[e.jsx(Ea,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]})]}),n&&e.jsx(s.Collapsible,{open:o,onOpenChange:c,children:e.jsx(s.CollapsibleContent,{className:"space-y-2",children:e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Error SQL Query"}),e.jsx(s.CopyButton,{text:n,className:"h-6 w-6"})]}),e.jsx("div",{className:"rounded-md bg-background/60 p-2 max-h-80 overflow-auto",children:e.jsx(s.CodeHighlighter,{code:n,language:"sql"})})]})})})]})]})})}function vt({sql:t,error:n,errorSql:a,onDebugWithAssistant:r}){const l=s.useEditorStore(u=>u.isDevMode),{setIsDevMode:o,setCardSql:c,setRunSql:i}=s.useEditorActions();function d(){o(!l),c(t),setTimeout(()=>{i(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-3",children:[e.jsxs(s.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[n&&e.jsx(bt,{error:n,errorSql:a,showFeedbackButton:!1}),!n&&t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"",children:e.jsx(s.CodeHighlighter,{code:t,language:"sql"})})})]}),!l&&t&&!n&&e.jsxs(s.Button,{onClick:d,variant:"secondary",size:"sm",children:[e.jsx(pa,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),n&&r&&e.jsxs(s.Button,{onClick:r,size:"sm",variant:"outline",children:[e.jsx(va,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function yt({sql:t,error:n,errorSql:a,onDebugWithAssistant:r}){return e.jsxs(s.HoverCard,{openDelay:n?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:n?e.jsx(da,{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(vt,{errorSql:a,sql:t,error:n,onDebugWithAssistant:r})})]})}function Vn(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 Nt(t){const{theme:n}=s.useTheme(),a=s.useDashboardStore(x=>x.theme),r=s.useEditorStore(x=>x.frame),l=s.useEditorStore(x=>x.card),o=s.useEditorStore(x=>x.activeTabCardId),c=s.Le(),{refetch:i}=s.useDashboardCardQuery(l),{updateCardTab:d,setRunSql:u}=s.useEditorActions(),m=M.useRef(),h=M.useRef({}),p=r.cards.find(x=>x.id===o),g=M.useCallback(()=>{let x="";return t==="python"&&(x=(p==null?void 0:p.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(x=(p==null?void 0:p.sql)||""),x},[t,p]);M.useEffect(()=>{if(o&&l.id&&l.id!==o){if(m.current&&c){const x=m.current.getModel();x&&(h.current[l.id]=x);let j=h.current[o];if(!j){const f=g();j=c.editor.createModel(f,t),h.current[o]=j}m.current.setModel(j)}d(o,l),u(!0)}},[o,l,d,c,u,t,g]),M.useEffect(()=>{if(!c)return;const x=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",j=a==="system"?x:a;c.editor.defineTheme("default",{base:j==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":j==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[n,a,c]),M.useEffect(()=>{const x=m.current;x&&c&&l&&x.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return i(),!1})},[c,i,l]);function b(x,j){if(m.current=x,!h.current[l.id]){const f=x.getModel(),N=g();h.current[l.id]=f||(j==null?void 0:j.editor.createModel(N,t))||x.getModel()}x.setModel(h.current[l.id])}return{handleEditorDidMount:b}}function Un(){const t=s.useEditorStore(c=>c.card.sql),n=s.useEditorStore(c=>c.sqlGen),{setCardSql:a,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=Nt("sql");function o(c){a(c),s.isObjectEmpty(n)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:o,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function Gn(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:n}=s.useEditorActions(),{handleEditorDidMount:a}=Nt("python");function r(l){n(l)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:a})}function Yn({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 Ds(t){const[n,a]=M.useState(null),[r,l]=M.useState(null);return M.useEffect(()=>{if(!t||t.trim()===""){a(null),l(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const i=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(i,{method:"HEAD"})).ok)throw new Error(`Module not found at ${i}`)}catch{}const d=await import(i);if(typeof d.useChartStore!="function")throw new Error("useChartStore is not a function");a(()=>d.useChartStore),l(null)}catch(c){const i=c instanceof Error?c.message:"Unknown error";console.error("Failed to load remote chart store:",i),l(i),a(null)}})()},[t]),n}function $n(t){const n=t.toUpperCase().indexOf("WHERE"),a=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),l=t.toUpperCase().indexOf("ORDER BY");let o=t.length;if(l!==-1&&(o=l),r!==-1&&r<o&&(o=r),n!==-1){const c=t.substring(0,n),i=t.substring(n);return`${c} {{ filters | where }} AND ${i.substring(6)}`}else if(a!==-1){const c=t.substring(0,a),i=t.substring(a);return`${c} {{ filters | where }} ${i}`}else{const c=t.substring(0,o),i=t.substring(o);return console.log("beforeClause",c),console.log("afterClause",i),i?`${c} {{ filters | where }} ${i}`:`${c.replace(/;$/,"")} {{ filters | where }}`}}function qn(t,n){if(t.length===0)return"";if(n){const a=t.find(r=>r.id===n);if(a){const r=a.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const o=r.split("__")[0],c=t.find(i=>i.tabTitle===o);return c?c.id:t[0].id}return n}}return t[0].id}async function Ys(t,n,a,r){if(!n||!a)throw new Error("Missing auth token or visual ID");const l=["resource-by-id","visual",a],o=r.getQueryData(l);if(o)return console.log("Using cached visual data for:",a),{data:o,fromCache:!0};console.log("Fetching visual data from network for:",a);const c=s.ue.loading("Loading visual...",{position:"top-center"});try{const i=await fetch(`${t}/management/v1/visuals/${a}`,{headers:{Authorization:`Bearer ${n}`}});if(!i.ok)throw new Error("Failed to load visual");const d=await i.json();return r.setQueryData(l,d),s.ue.dismiss(c),{data:d,fromCache:!1}}catch(i){throw s.ue.dismiss(c),i}}function Hn(t,n,a,r,l){const o=t.frameObject;n(o);const c=o.cards.find(i=>i.id===o.activeCardId);c&&a(c),r(!0),l(!0)}function Wn(){var p;const{setCardSql:t}=s.useEditorActions(),n=s.useEditorStore(g=>g.frame),a=s.useEditorStore(g=>g.card),r=Ds(((p=a.customCardPreferences)==null?void 0:p.url)||""),l=s.useEditorStore(g=>g.selectedSchemaName),o=s.useEditorStore(g=>g.selectedDatamodelId),c=s.useEditorStore(g=>g.selectedDatabaseName),i=s.useEditorStore(g=>g.selectedTableName),d=s.useEditorStore(g=>g.selectedConnectionId),u=s.useEditorStore(g=>g.isShowingVisual),m=a.sql;return{getUpdatedFrame:M.useCallback(()=>{var f;let g=m;m&&!m.includes("{{")&&(g=$n(m),t(g));const b=(f=r==null?void 0:r.getState())==null?void 0:f.settings,x={...a,dataSource:a.dataSource||{mode:"directSource"},lastSelectedSchema:l,lastSelectedDatamodelId:o,lastSelectedDatabase:c,lastSelectedTable:i,connectionId:d,sql:g,customCfg:u?a.customCfg:null,preferences:a.preferences,...b&&{customCardPreferences:{...a.customCardPreferences,settings:b}}},j=n.cards.map(N=>N.id===a.id?x:N);return{...n,cards:j,activeCardId:qn(j,n.activeCardId)}},[a,n,u,l,o,c,i,d,t,r,m])}}function Ts(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient(),r=s.useSelectedVisual(),{selectVisual:l}=s.useManagementActions(),{setFrame:o,setCard:c}=s.useEditorActions(),{setIsDashboardEditing:i,setIsVisualEditing:d,setSelectedFrameId:u,addFrame:m,setIsDashboardPanelOpen:h}=s.useDashboardActions(),p=s.useDashboardStore(j=>j.selectedSheetId),g=s.useVisualById((r==null?void 0:r.id)||"",{enabled:!!(r!=null&&r.id)&&!!(t!=null&&t.accessToken)}),b=M.useCallback(async j=>{try{l(j);const{data:f,fromCache:N}=await Ys(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",j.id,a);return Hn(f,o,c,i,d),{success:!0,fromCache:N}}catch(f){return console.error("Error editing visual:",f),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,n.apiServiceUrl,a,l,o,c,i,d]),x=M.useCallback(async j=>{try{if(l(j),!p)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:f,fromCache:N}=await Ys(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",j.id,a),T=f.frameObject;if(!T)return{success:!1,error:"Visual has no frame data"};const k={...T,id:s.v4()};return m(p,k,"end"),i(!0),u(k.id),h(!1),{success:!0,fromCache:N}}catch(f){return console.error("Error adding visual:",f),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,n.apiServiceUrl,a,l,p,m,i,u,h]);return{visual:g.data,isLoading:g.isLoading,isError:g.isError,error:g.error,handleEditLibraryVisual:b,handleAddLibraryVisual:x,getUpdatedFrame:Wn().getUpdatedFrame,refetch:g.refetch}}function ks({variant:t="outline"}){var c;const{setCardSql:n}=s.useEditorActions();s.useEditorStore(i=>i.frame);const a=s.useEditorStore(i=>i.card);Ds(((c=a.customCardPreferences)==null?void 0:c.url)||""),s.useEditorStore(i=>i.selectedSchemaName),s.useEditorStore(i=>i.selectedDatamodelId),s.useEditorStore(i=>i.selectedDatabaseName),s.useEditorStore(i=>i.selectedTableName),s.useEditorStore(i=>i.selectedConnectionId),s.useEditorStore(i=>i.isShowingVisual),a.sql;const r=s.useEditorStore(i=>i.onSave),{getUpdatedFrame:l}=Ts();function o(){const i=l();r==null||r(i)}return e.jsxs(s.Button,{onClick:o,className:"h-8",size:"sm",variant:t,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function Kn(){const t=s.useQueryClient(),[n,a]=M.useState(!1),r=s.useDashboardStore(u=>u.actions.setIsDashboardPanelOpen),{setIsVisualEditing:l}=s.useDashboardActions(),{getUpdatedFrame:o}=Ts(),c=s.useSelectedVisual(),i=s.useUpdateVisualMutation(),d=()=>{const u=o();if(!(c!=null&&c.id)){s.ue.error("No visual selected");return}a(!0),i.mutate({visualId:c.id,data:{frameObject:u}},{onSuccess:()=>{a(!1),l(!1),r(!0),s.ue.success("Visual updated successfully"),t.invalidateQueries({queryKey:["resource-by-id","visual",c.id],exact:!0})},onError:()=>{a(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:d,className:"h-8",size:"sm",children:[n&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!n&&e.jsxs(e.Fragment,{children:[e.jsx(bs,{className:"mr-2 size-4 font-bold"}),"Save"]})]})}function Es(){const{setTempQueryData:t,setSqlGen:n}=s.useEditorActions(),a=s.useQueryClient(),r=s.useEditorStore(d=>d.tempQueryData),l=s.useEditorStore(d=>d.onClose),o=s.useEditorStore(d=>d.card),{queryKey:c}=s.useDashboardCardQuery(o);function i(){if(r){const{queryKey:d,queryData:u}=r;d&&u&&a.setQueryData(d,u)}n({}),l==null||l()}return e.jsxs(s.Button,{onClick:i,className:"h-8",size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function os(){const{setTempQueryData:t}=s.useEditorActions(),n=s.useQueryClient(),a=s.useEditorStore(j=>j.isDevMode),r=s.useEditorStore(j=>j.tempQueryData),l=s.useEditorStore(j=>j.card),{queryKey:o}=s.useDashboardCardQuery(l),{setCardSql:c,setSqlGen:i,setCardPython:d,setCardCustomCfg:u,setCardPreferences:m,updateDataSource:h,clearQueryConfig:p,setCardConfig:g,setCardType:b}=s.useEditorActions();function x(){const j=n.getQueryData(o);r!=null&&r.queryData||t({queryKey:o,queryData:j}),n.setQueryData(o,null),n.removeQueries({queryKey:o,exact:!0}),a&&h(s.EMPTY_DATA_SOURCE),c(""),i({}),p(),g(void 0),d(""),u(""),m({}),b("bar")}return e.jsxs(s.Button,{onClick:x,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(s.SquarePen,{className:"mr-2 size-4"}),"Clear"]})}function Qn(){const t=s.useQueryClient(),[n,a]=M.useState(!1),[r,l]=M.useState(!1);s.useEditorStore(_=>_.frame);const o=s.useEditorStore(_=>_.card);s.useEditorStore(_=>_.isShowingVisual),s.useEditorStore(_=>_.selectedConnectionId),s.useEditorStore(_=>_.tempQueryData),s.useEditorStore(_=>_.selectedDatabaseName),s.useEditorStore(_=>_.selectedDatamodelId),s.useEditorStore(_=>_.selectedSchemaName);const c=s.useEditorStore(_=>_.showAIDialog);s.useEditorStore(_=>_.selectedTableName);const i=s.useEditorStore(_=>{var Q;return(Q=_==null?void 0:_.card)==null?void 0:Q.sql}),d=s.useEditorStore(_=>{var Q;return(Q=_==null?void 0:_.card)==null?void 0:Q.python}),{sheetFilterValues:u}=s.useSheetFilterValues(),{setCardCustomCfg:m,setQueryResultColumns:h,setCardSql:p,setTempQueryData:g,setPythonStdOut:b,setCardPreferences:x,setCardType:j,setCardPython:f,runAssistant:N,setShowAIDialog:T}=s.useEditorActions();s.useEditorStore(_=>_.onSave),s.useEditorStore(_=>_.onClose),s.useEditorStore(_=>_.actions.setSqlGen);const k=s.useEditorStore(_=>_.runSql),C=s.useEditorStore(_=>_.actions.setRunSql),w=s.useEditorStore(_=>_.actions.setIsSqlRunning),{data:v,isLoading:E,isFetching:y,isSuccess:F,isError:I,error:P,errorSql:D,queryKey:S,refetch:L,errorMessage:O}=s.useDashboardCardQuery(o);M.useEffect(()=>{if(v&&(v.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),b((v==null?void 0:v.output)||""),v.records.length>0)){const{dimensionKeys:_}=s.getKeys(v.records);h(_)}},[v,h,b]),M.useEffect(()=>{(E||y)&&w(!0),(I||F)&&w(!1),I&&(h([]),b(""))},[E,y,v,b,I,F,w,h,P]),M.useEffect(()=>{k&&(t.getQueryData(S)||L(),C(!1))},[k,L,C,S,t]);async function R(){const _=`Can you help me debug this query?
|
|
316
|
+
*/const $a=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"}]]);function qa(){const{setTheme:t}=s.useTheme(),n=s.useDashboardStore(a=>a.actions.setDashboardTheme);return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsxs(s.Button,{className:"h-7 p-2",variant:"ghost",size:"sm",children:[e.jsx(Ua,{strokeWidth:1.5,className:"h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(Aa,{strokeWidth:1.5,className:"absolute h-4 w-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),e.jsx("span",{className:"sr-only",children:"Toggle theme"})]})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuItem,{onClick:()=>{t("light"),n("light")},children:"Light"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("dark"),n("dark")},children:"Dark"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("system"),n("system")},children:"System"})]})]})}function ss(t){var n;return{...t,sheets:(n=t==null?void 0:t.sheets)==null?void 0:n.map(a=>{var r;return{...a,frames:(r=a.frames)==null?void 0:r.map(l=>{var o;return{...l,cards:(o=l.cards)==null?void 0:o.map(c=>rt(c))}})}})}}function rt(t){return{...t,customCfg:Ha(t.customCfg),data:[]}}function Ha(t){var n,a;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(a=(n=t==null?void 0:t.data)==null?void 0:n.datasets)==null?void 0:a.map(r=>({...r,data:[]}))}}:null}async function Wa(t,n,a,r,l){if(!l)return null;const o=JSON.stringify(a),c=`${t}/v1/lens`;return await s.postRequest(c,l,{name:n,template:o,filterValues:r,operation:"create"})}async function vs(t,n,a){if(!a)return null;const{id:r,template:l,filterValues:o,isDefault:c,shared:i}=n,d=`${t}/v1/lens`;return await s.postRequest(d,a,{lensId:r,template:l,filterValues:o,isDefault:c,shared:i,operation:"update"})}async function Ka(t,n,a){if(!a)return null;const r=`${t}/v1/lens`;return await s.postRequest(r,a,{operation:"delete",lensId:n})}function Qa(){const[t,n]=A.useState(""),[a,r]=A.useState(!1),l=s.useDashboardStore(j=>j.lenses),{setLenses:o,setSelectedLensId:c}=s.useDashboardActions(),[i,d]=A.useState(!1),[u,m]=A.useState(!1),h=s.useDashboardStore(j=>j.dashboard),p=s.useDashboardStore(j=>j.filterValues),{authToken:g,tokenProps:b}=s.useSemaphorContext();async function x(){d(!0);const j=ss(h),f=await Wa(b.apiServiceUrl,t,j,p,g==null?void 0:g.accessToken);f&&(o([...l||[],f]),c(f.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:j=>{n(j.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),a&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{size:"sm",variant:"outline",type:"submit",onClick:x,disabled:i,children:i?"Creating...":"Add"})})]})]})}function Ja(){const[t,n]=A.useState(!1),a=s.useDashboardStore(h=>h.lenses),r=s.useDashboardStore(h=>h.selectedLensId),{setLenses:l,setSelectedLensId:o}=s.useDashboardActions(),{authToken:c,tokenProps:i}=s.useSemaphorContext();async function d(h){o(h)}async function u(h){if(await Ka(i.apiServiceUrl,h,c==null?void 0:c.accessToken)){const g=a==null?void 0:a.filter(b=>b.id!==h);l(g||[]),o("original")}}async function m(h){const p=a==null?void 0:a.map(x=>x.id===h.id?{...x,isDefault:!h.isDefault}:{...x,isDefault:!1});l(p||[]);const g={...h,isDefault:!h.isDefault};await vs(i.apiServiceUrl,g,c==null?void 0:c.accessToken);const b=a==null?void 0:a.find(x=>x.isDefault);if(b&&b.id!==h.id){const x={...b,isDefault:!1};await vs(i.apiServiceUrl,x,c==null?void 0:c.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:n,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(va,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(s.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuRadioGroup,{value:r,onValueChange:d,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),a==null?void 0:a.map(h=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:h.id,children:[e.jsx("p",{children:h.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:p=>{p.preventDefault(),m(h)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!h.isDefault,"text-green-500":h.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:p=>{p.preventDefault(),u(h.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},h.id))]})]})]})}function Xa({iconClassName:t}){const[n,a]=A.useState(!1),[r,l]=A.useState(""),[o,c]=A.useState(!1),i=s.useDashboardStore(h=>h.isDownloadingPdf),{tokenProps:d}=s.useSemaphorContext();async function u(){const h=s.ue.loading("Generating PDF... may take up to 60 seconds");try{await s.downloadPdf(d.apiServiceUrl),s.ue.dismiss(h),s.ue.success("PDF downloaded successfully!",{duration:2e3})}catch(p){s.ue.dismiss(h),s.ue.error("Failed to download PDF",{description:"Please try again or contact support.",richColors:!0}),console.error("PDF download error:",p)}}async function m(){if(!r)return;a(!1),l(""),c(!1);const h=s.ue.loading("Generating protected PDF... may take up to 60 seconds");try{await s.downloadPdf(d.apiServiceUrl,r),s.ue.dismiss(h),s.ue.success("Protected PDF downloaded successfully!",{duration:2e3,position:"top-right"})}catch(p){s.ue.dismiss(h),s.ue.error("Failed to download protected PDF. Please try again."),console.error("Protected PDF download error:",p)}}return e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled:i,children:e.jsx(s.Download,{className:s.cn("size-4",t)})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsxs(s.DropdownMenuItem,{onClick:u,children:[e.jsx(s.File,{className:"mr-2 h-4 w-4"}),"Download PDF"]}),e.jsxs(s.DropdownMenuItem,{onClick:()=>a(!0),children:[e.jsx(s.Lock,{className:"mr-2 h-4 w-4"}),"Download Protected PDF"]})]})]}),e.jsx(s.Dialog,{open:n,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Download Protected PDF"}),e.jsx(s.DialogDescription,{children:"Enter a password to protect your PDF. The PDF will be encrypted and require this password to open."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Input,{id:"password",type:o?"text":"password",value:r,onChange:h=>l(h.target.value),placeholder:"Enter password",className:"pr-10",onKeyDown:h=>{h.key==="Enter"&&r&&m()}}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent",onClick:()=>c(!o),children:o?e.jsx(s.EyeOff,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(s.Eye,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:m,disabled:!r,children:"Download"})]})]})})]})}function lt({triggerButtonClassName:t}){const[n,a]=A.useState(!1),r=s.useDashboardStore(i=>{var d;return(d=i.dashboard)==null?void 0:d.id}),l=s.useDashboardStore(i=>{var d;return(d=i.dashboard)==null?void 0:d.title}),o=s.useDashboardStore(i=>{var d;return(d=i.dashboard)==null?void 0:d.sheets}),c=s.useDashboardStore(i=>i.selectedSheetId);return o==null||o.find(i=>i.id===c),r?e.jsxs(e.Fragment,{children:[e.jsx(s.IconButton,{tooltip:"Schedule Dashboard",className:s.cn("h-7 p-2",t),onClick:()=>a(!0),children:e.jsx(s.Clock,{className:"size-4"})}),e.jsx(s.EmailScheduleDialog,{open:n,onOpenChange:a,dashboardId:r,dashboardName:l})]}):null}function ts({value:t,onChange:n,placeholder:a="Search users by name, email, or department..."}){return 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:a,value:t,onChange:r=>n(r.target.value),className:"pl-9"})]})}function Re({currentRole:t,onRoleChange:n,roleOptions:a,disabled:r=!1,className:l="",allowDropdown:o=!0}){var d;const c=((d=a.find(u=>u.value===t))==null?void 0:d.label)||t,i=a.filter(u=>u.value!==t);return o?e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:`cursor-pointer hover:bg-muted ${r?"cursor-not-allowed opacity-50":""} ${l}`,children:c})}),e.jsx(s.DropdownMenuContent,{className:"z-[51]",children:i.map(u=>e.jsx(s.DropdownMenuItem,{onClick:()=>n(u.value),disabled:r,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.description})]})},u.value))})]}):e.jsx(s.Badge,{variant:"outline",className:`text-xs ${l}`,children:c})}function ot({selectedUsers:t,selectedUserObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:l}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["Selected Users (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(o=>a(o.id)),className:"h-auto p-1 text-xs",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:n.map(o=>{const c=t.find(d=>d.id===o.id),i=l(o.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[o.name,e.jsx(Re,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:d=>r(o.id,d),roleOptions:i}),e.jsx("button",{onClick:()=>a(o.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},o.id)})}),e.jsx(s.Separator,{})]})}function it({usersToRemove:t,allUsers:n,onRemove:a}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium text-destructive",children:["Users to Remove Access (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(r=>a(r)),className:"h-auto p-1 text-xs text-destructive hover:text-destructive",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:n.filter(r=>t.includes(r.id)).map(r=>e.jsxs(s.Badge,{variant:"destructive",className:"gap-1",children:[r.name,e.jsx("button",{onClick:()=>a(r.id),className:"ml-1 rounded-full p-0.5 hover:bg-destructive-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},r.id))}),e.jsx(s.Separator,{})]})}function ct({usersToUpdate:t,allUsers:n,onRemove:a,getRoleOptions:r}){if(t.length===0)return null;const l=r("tenant"),o=i=>{const d=n.find(u=>u.id===i);return(d==null?void 0:d.name)||"Unknown User"},c=i=>{const d=l.find(u=>u.value===i);return(d==null?void 0:d.label)||i};return e.jsxs("div",{className:"rounded-lg border border-orange-200 bg-orange-50 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-4 w-4 text-orange-600"}),e.jsxs("span",{className:"text-sm font-medium text-orange-800",children:["Updating Access (",t.length,")"]})]}),e.jsx("div",{className:"space-y-2",children:t.map(i=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:o(i.id)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c(i.currentRole)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsx(s.Badge,{variant:"default",className:"text-xs",children:c(i.newRole)})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",onClick:()=>a(i.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},i.id))})]})}function dt(t,n={}){const{enabled:a=!0,eventType:r="mousedown"}=n,l=A.useRef(null);return A.useEffect(()=>{const o=c=>{const i=c.target;l.current&&l.current.contains(i)||i instanceof Element&&(i.closest("[data-radix-popper-content-wrapper]")||i.closest("[data-radix-select-content]")||i.closest("[data-radix-popover-content]")||i.closest("[data-radix-dropdown-menu-content]")||i.closest("[data-radix-tooltip-content]")||i.closest('[role="listbox"]')||i.closest('[role="option"]')||i.closest('[role="combobox"]'))||i instanceof Element&&i.hasAttribute("data-radix-")||t()};return a&&document.addEventListener(r,o),()=>{document.removeEventListener(r,o)}},[t,a,r]),l}function ye(t,n){var a;return((a=n.find(r=>r.value===t))==null?void 0:a.label)||t}function Za(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function ut(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function en(t,n,a){const r=ut(t),l=(a==null?void 0:a.type)||"organization";if(!(!n||!n.shares))if(l==="organization")if(r==="organization"){if("specificOrgUsers"in n.shares)return(n.shares.specificOrgUsers||[]).find(i=>i.orgUserId===t.id)}else return(n.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id);else return(n.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id)}function sn({user:t}){return ut(t)==="tenant"?e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:t.role==="POWER_USER"?"Power User":"Viewer"}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:t.role==="ADMIN"?"Admin":t.role==="POWER_USER"?"Power User":"Viewer"})}function tn({user:t,userShare:n,usersToUpdate:a,currentUser:r,getRoleOptions:l,handleUpdateAccess:o}){if(!(n!=null&&n.role))return null;const c=Za((r==null?void 0:r.type)||""),i=a.some(h=>h.id===t.id),d=a.find(h=>h.id===t.id),u=d?d.newRole:n==null?void 0:n.role,m=l(t.type);return n?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(Re,{currentRole:u,onRoleChange:h=>{o(t.id,n.role,h)},roleOptions:m,disabled:!c,allowDropdown:c,className:i?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:ye(u,m)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function an({hasAccess:t,isUserRemoving:n,isSelected:a,hasAccessFromAPI:r}){return e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[t&&!n&&e.jsxs(s.Badge,{variant:"outline",className:"border-green-200 bg-green-50 text-xs text-green-700",children:[e.jsx(s.Eye,{className:"mr-1 h-3 w-3"}),"Has Access"]}),n&&e.jsxs(s.Badge,{variant:"outline",className:"border-red-200 bg-red-50 text-xs text-red-700",children:[e.jsx(s.X,{className:"mr-1 h-3 w-3"}),"Remove Access"]}),a&&!r&&e.jsxs(s.Badge,{variant:"outline",className:"border-blue-200 bg-blue-50 text-xs text-blue-700",children:[e.jsx(Pe,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function nn({isUserRemoving:t,isSelected:n,hasAccess:a,isRemoving:r,isSharing:l}){return e.jsxs(e.Fragment,{children:[t&&e.jsx("span",{className:"text-xs font-medium text-red-600",children:r?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Removing..."]}):"⚠ Will remove access"}),n&&!a&&e.jsx("span",{className:"text-xs font-medium text-blue-600",children:l?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Sharing..."]}):"Will share"})]})}function rn({existingShares:t,allUsers:n,getRoleOptions:a,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in t.shares){const c=t.shares,i=c.specificOrgUsers||[],d=c.specificTenantUsers||[],u=c.orgWide||[],m=c.orgUsersOnly||[],h=c.allTenantsOnly||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Org Users (",i.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[i.slice(0,3).map((p,g)=>{var f,y;const b=((f=n.find(E=>E.id===p.orgUserId))==null?void 0:f.name)||"Unknown User",x=((y=n.find(E=>E.id===p.orgUserId))==null?void 0:y.type)||"",j=ye(p.role,a(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:b}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},g)}),i.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",i.length-3," more users"]})]})]}),d.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-green-600",children:["Specific Tenant Users (",d.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[d.slice(0,3).map((p,g)=>{var f,y;const b=((f=n.find(E=>E.id===p.tenantUserId))==null?void 0:f.name)||"Unknown User",x=((y=n.find(E=>E.id===p.tenantUserId))==null?void 0:y.type)||"",j=ye(p.role,a(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:b}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},g)}),d.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",d.length-3," more users"]})]})]}),u.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-purple-600",children:"All Org Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:u.map((p,g)=>{const b=ye(p.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Organization Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},g)})})]}),m.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-orange-600",children:"Org Users Only"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:m.map((p,g)=>{const b=ye(p.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Org Users Only"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},g)})})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-indigo-600",children:"All Tenants"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:h.map((p,g)=>{const b=ye(p.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenants"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},g)})})]}),!i.length&&!d.length&&!u.length&&!m.length&&!h.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const c=t.shares.specificTenantUsers||[],i=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",c.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[c.slice(0,3).map((d,u)=>{var g,b;const m=((g=n.find(x=>x.id===d.tenantUserId))==null?void 0:g.name)||"Unknown User",h=((b=n.find(x=>x.id===d.tenantUserId))==null?void 0:b.type)||"",p=ye(d.role,a(h));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:m}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:p})]},u)}),c.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",c.length-3," more users"]})]})]}),i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:i.map((d,u)=>{const m=ye(d.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:m})]},u)})})]}),!c.length&&!i.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const o=t.shares.specificTenantUsers||[],c=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[o.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",o.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[o.slice(0,3).map((i,d)=>{var p,g;const u=((p=n.find(b=>b.id===i.tenantUserId))==null?void 0:p.name)||"Unknown User",m=((g=n.find(b=>b.id===i.tenantUserId))==null?void 0:g.type)||"",h=ye(i.role,a(m));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:u}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},d)}),o.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",o.length-3," more users"]})]})]}),c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:c.map((i,d)=>{const u=ye(i.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:u})]},d)})})]}),!o.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function ln({isInitialLoading:t,searchQuery:n,availableUsers:a}){return t?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(s.LoaderCircle,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading users..."})]})}):a.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:n?"No users found matching your search.":"No users available to share with."}):null}function on({user:t,userShare:n,isUserRemoving:a,hasAccess:r,hasAccessFromAPI:l,isSelected:o,selectedUser:c,roleOptions:i,currentUser:d,usersToUpdate:u,handleUserToggle:m,handleRemoveAccess:h,handleUpdateAccess:p,handleUserRoleChange:g}){return e.jsxs("div",{className:s.cn("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!a?"border border-green-200 bg-green-50":a?"border border-red-200 bg-red-50":o?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:l?!a:o,disabled:t.id===(d==null?void 0:d.id),onCheckedChange:()=>{l?a?m(t.id):h(t.id):m(t.id)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:t.name}),e.jsx(sn,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!a?e.jsx(Re,{currentRole:n==null?void 0:n.role,onRoleChange:b=>p(t.id,n.role,b),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(tn,{user:t,userShare:n,usersToUpdate:u,currentUser:d,getRoleOptions:()=>i,handleUpdateAccess:p}),o&&!l&&e.jsx("div",{onClick:b=>b.stopPropagation(),children:e.jsx(Re,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:b=>g(t.id,b),roleOptions:i,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(an,{hasAccess:r,isUserRemoving:a,isSelected:o,hasAccessFromAPI:l}),e.jsx(nn,{isUserRemoving:a,isSelected:o,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function mt({existingShares:t,isInitialLoading:n,isSearching:a,getRoleOptions:r,allUsers:l=[],currentUser:o,handleUserToggle:c,handleUserRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),g=s.useShareSearchQuery(),b=s.useShareManagementActions(),x=c||(C=>{const D=m.some(N=>N.id===C),v=h.includes(C);D?b.removeSelectedUser(C):v?b.removeUserFromRemove(C):b.addSelectedUser({id:C,role:"VIEWER"})}),j=i||b.updateSelectedUserRole,f=d||b.addUserToRemove,y=u||((C,D,v)=>{b.addUserToUpdate({id:C,currentRole:D,newRole:v})}),E=l,k=h;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["All Users (",(E??[]).length,")"]}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",children:e.jsx(s.Info,{className:"h-4 w-4"})})}),e.jsx(s.TooltipContent,{className:"w-48 max-w-sm",children:e.jsx(rn,{existingShares:t,allUsers:l,getRoleOptions:r,currentUser:o})})]})})]}),(E==null?void 0:E.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{m.length===E.length?b.setSelectedUsers([]):b.setSelectedUsers(E.map(C=>({id:C.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:m.length===E.length?"Deselect all":"Select all"})]}),e.jsxs("div",{className:"max-h-60 space-y-1 overflow-y-auto rounded-md border p-2",children:[e.jsx(ln,{isInitialLoading:n,isSearching:a,searchQuery:g,availableUsers:E||[]}),!n&&!a&&(E==null?void 0:E.length)>0&&E.map(C=>{const D=t?en(C,t,o):void 0,v=k.includes(C.id),N=!!D,S=N&&!v,F=m.some(T=>T.id===C.id),I=m.find(T=>T.id===C.id),P=r(C.type);return e.jsx(on,{user:C,userShare:D,isUserRemoving:v,hasAccess:S,hasAccessFromAPI:N,isSelected:F,selectedUser:I,roleOptions:P,currentUser:o,usersToUpdate:p,handleUserToggle:x,handleRemoveAccess:f,handleUpdateAccess:y,handleUserRoleChange:j},C.id)})]})]})}function Ss({shareType:t,onShareTypeChange:n,currentUser:a,options:r}){const l=(a==null?void 0:a.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(a.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:n,className:`grid grid-cols-${r.length} gap-4`,children:r.map(o=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:o.value,id:o.value,className:"peer sr-only",disabled:o.disabled}),e.jsxs(s.Label,{htmlFor:o.value,className:`flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5 [&:has([data-state=checked])]:border-primary [&:has([data-state=checked])]:bg-primary/5 ${o.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[o.icon||e.jsx(s.User,{className:"mb-3 h-6 w-6"}),e.jsxs("div",{className:"space-y-1 text-center",children:[e.jsx("p",{className:"text-sm font-medium leading-none",children:o.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o.description})]})]})]},o.value))}),!l&&r.some(o=>o.value==="all_users")&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only admins, authors, power users, and super admins can share with all users."})]})}const be=()=>[{value:"VIEWER",label:"Viewer",description:"Can view only"},{value:"EDITOR",label:"Editor",description:"Can view and edit"},{value:"CONTRIBUTOR",label:"Contributor",description:"Can view, edit, and share"},{value:"OWNER",label:"Owner",description:"Full access (view, edit, share, delete)"}];function cn({currentUser:t,currentShare:n,isSharing:a,onUpdateAccess:r,allUsersToUpdate:l=null,allUsersToRemove:o=!1,isUpdating:c=!1,isRemoving:i=!1}){const d=s.useShareCurrentMode(),u=be().filter(y=>y.value==="VIEWER"||y.value==="EDITOR"||y.value==="CONTRIBUTOR"),m=n.role!=="NONE"?n.role:"NONE",h=l?l.newRole:m,p=n.role!=="NONE"&&!o&&(!l||l.newRole===m),g=l!==null&&l.newRole!==m,b=o,x=m==="NONE"||!m,j=y=>{switch(y){case"VIEWER":return e.jsx(s.Eye,{className:"h-4 w-4"});case"EDITOR":return e.jsx(s.SquarePen,{className:"h-4 w-4"});case"CONTRIBUTOR":return e.jsx(Ba,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},f=y=>{r(m,y)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",g&&!b&&!x?"border-orange-300 bg-orange-50":p?"border-green-300 bg-green-50":b||x?"border-destructive bg-destructive/10":""),children:[e.jsxs(s.CardHeader,{children:[e.jsxs(s.CardTitle,{className:"flex items-center gap-2 text-base",children:[e.jsx(s.Users,{className:"h-5 w-5"}),"Share with All"," ",d==="allOrgUsers"?"Organization":d==="allTenantUsers"?"Tenant":d==="specificOrgUsers"?"Org":"Tenant"," ","Users",p&&e.jsx(s.Badge,{variant:"default",className:"ml-2 border-green-400 bg-green-100 text-green-800",children:"Active"}),g&&e.jsx(s.Badge,{variant:"secondary",className:"ml-2 border-orange-400 bg-orange-100 text-orange-800",children:"Pending Update"}),(b||x)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:b||x?"No access for all users.":"This will share the dashboard with all users in your "+((t==null?void 0:t.type)==="organization"?"organization":"tenant")+". Select an access level below."})]}),e.jsx(s.CardContent,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Select Access Level:"}),e.jsxs(s.HoverCard,{children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-4 w-4 p-0 text-muted-foreground hover:text-foreground",children:e.jsx(s.Info,{className:"h-3 w-3"})})}),e.jsx(s.HoverCardContent,{className:"w-80",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Share with All Users"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["This action will share the dashboard with all users in your"," ",(t==null?void 0:t.type)==="organization"?"organization":"tenant",". Users will receive the selected access level."]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Viewer:"})," Can view the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Editor:"})," Can view and edit the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Contributor:"})," Can view, edit, and share the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"None:"})," No access for all users"]})]})]})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:u.map(y=>e.jsxs(s.Button,{variant:h===y.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>f(y.value),disabled:a||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[j(y.value),e.jsx("span",{className:"font-medium",children:y.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:y.description})]},y.value))})]})})]})})}function ht({currentUser:t,currentShare:n,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:o,onRemoveAccess:c,allUsersToUpdate:i,allUsersToRemove:d}){const u=x=>x==="OWNER"?"CONTRIBUTOR":x,h=n?{role:u(n.role)}:{role:"NONE"},p=i?{currentRole:u(i.currentRole),newRole:u(i.newRole)}:null,g=(x,j)=>{o(x,j)},b=()=>{c()};return e.jsx(cn,{currentUser:t,currentShare:h,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:g,onRemoveAccess:b,allUsersToUpdate:p,allUsersToRemove:d})}function ze(t){const{debouncedSearchQuery:n,resourceId:a,resourceType:r=s.ResourceType.DASHBOARD,userType:l,tenantId:o}=t,c=A.useMemo(()=>({search:n,active:!0,...l?{type:l}:{},...l==="tenant"&&o?{tenantId:o}:{}}),[n,l,o]),{users:i,isLoading:d,isError:u}=s.useUnifiedUsers(c),m=s.useResourceShares(r,a);return{allUsers:i,isLoadingUsers:d,isErrorLoadingUsers:u,existingShares:m.data,isLoadingShares:m.isLoading,isErrorLoadingShares:m.isError,isFetchingShares:m.isFetching}}function dn({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var Q,X;const i=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:u,setSearchQuery:m,debouncedSearchQuery:h}=s.useShareSearchWithDebounce(),p=s.useShareSelectedUsers(),g=s.useShareUsersToRemove(),b=s.useShareUsersToUpdate(),x=s.useShareCurrentMode(),j=s.useShareOrgWideRole(),f=s.useShareManagementActions(),[y,E]=A.useState("specific_users"),k=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},C=()=>{if(i==="tenant"&&d)return d},{allUsers:D,existingShares:v,isLoadingUsers:N}=ze({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:k(),tenantId:C()});A.useEffect(()=>{f.setCurrentContext("org-tab"),f.setCurrentMode(y==="all_users"?"allOrgUsers":"specificOrgUsers")},[f,y]);const S=q=>{var G,se;const W=q;if(E(W),r==null||r(W),f.setCurrentContext("org-tab"),W==="specific_users")f.setCurrentMode("specificOrgUsers");else if(W==="all_users"){f.setCurrentMode("allOrgUsers");const V=(se=(G=v==null?void 0:v.shares)==null?void 0:G.orgUsersOnly)==null?void 0:se[0];V&&V.role!==void 0&&f.setOrgWideRole(V.role)}},F=D.filter(q=>q.name.toLowerCase().includes(u.toLowerCase())||q.email.toLowerCase().includes(u.toLowerCase())),I=D.filter(q=>p.some(W=>W.id===q.id)),P=q=>{var V,U;const W=p.some(ee=>ee.id===q),G=g.includes(q),se=(U=(V=v==null?void 0:v.shares)==null?void 0:V.specificOrgUsers)==null?void 0:U.some(ee=>ee.orgUserId===q);W?f.removeSelectedUser(q):G?f.removeUserFromRemove(q):se||f.addSelectedUser({id:q,role:"VIEWER"})},T=(q,W)=>{f.updateSelectedUserRole(q,W)},w=q=>{f.addUserToRemove(q),f.removeSelectedUser(q)},L=q=>{f.removeUserFromRemove(q)},O=q=>{f.removeUserFromUpdate(q)},R=(q,W)=>{f.setOrgWideRole(W)},M=()=>{f.setOrgWideRole((B==null?void 0:B.role)||"NONE")},B=(X=(Q=v==null?void 0:v.shares)==null?void 0:Q.orgUsersOnly)==null?void 0:X[0];A.useEffect(()=>{y==="all_users"&&B&&B.role!==void 0&&f.setOrgWideRole(B.role)},[y,B,f]);const Y=N,_=!1;return a?e.jsxs(e.Fragment,{children:[e.jsx(Ss,{shareType:y,onShareTypeChange:S,currentUser:a,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(s.User,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(a==null?void 0:a.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(a.role??"")}]}),y==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(ts,{value:u,onChange:m}),e.jsx(ot,{selectedUsers:p,selectedUserObjects:I,onRemove:P,onRoleChange:T,getRoleOptions:be}),e.jsx(it,{usersToRemove:g,allUsers:F,onRemove:L}),e.jsx(ct,{usersToUpdate:b,allUsers:F,onRemove:O,getRoleOptions:be}),e.jsx(mt,{existingShares:v,isInitialLoading:Y,isSearching:_,resource:t,onShare:()=>{},getRoleOptions:be,allUsers:F,currentUser:a,handleUserToggle:P,handleUserRoleChange:T,handleRemoveAccess:w,handleUpdateAccess:(q,W,G)=>{f.addUserToUpdate({id:q,currentRole:W,newRole:G})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(ht,{currentUser:a,currentShare:B,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:R,onRemoveAccess:M,allUsersToUpdate:x==="allOrgUsers"&&j!==((B==null?void 0:B.role)||"NONE")?{currentRole:(B==null?void 0:B.role)||"NONE",newRole:j}:null,allUsersToRemove:x==="allOrgUsers"&&(B==null?void 0:B.role)===void 0})})]}):null}function un(t){switch(t){case"ORG_GROUP":return"Organization Group";case"TENANT_GROUP":return"Tenant Group";default:return"Group"}}function mn(t){switch(t){case"ORG_GROUP":return"text-blue-600";case"TENANT_GROUP":return"text-green-600";default:return"text-gray-600"}}function xt({groups:t,existingGroupShares:n,isLoading:a,resource:r,getRoleOptions:l,currentUser:o,handleGroupToggle:c,handleGroupRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:u}){const m=s.useShareSelectedGroups(),h=s.useShareGroupsToRemove(),p=s.useShareGroupsToUpdate(),g=s.useShareManagementActions(),b=l(o==null?void 0:o.type);return a?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):t.length===0?e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"No groups available to share with"}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Available Groups"}),e.jsx("div",{className:"max-h-[300px] space-y-2 overflow-y-auto rounded-md border p-3",children:t.map(x=>{const j=n==null?void 0:n.find(v=>v.groupId===x.id),f=m.some(v=>v.id===x.id),y=h.includes(x.id),E=p.find(v=>v.id===x.id),k=!!j&&!y;let D=(j==null?void 0:j.role)||"VIEWER";if(f){const v=m.find(N=>N.id===x.id);D=(v==null?void 0:v.role)||"VIEWER"}else E&&(D=E.newRole);return e.jsxs("div",{className:s.cn("flex items-center justify-between rounded-lg p-2 transition-colors",k&&!y?"border border-green-200 bg-green-50":y?"border border-red-200 bg-red-50":f?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx(s.Checkbox,{id:`group-${x.id}`,checked:k?!y:f,disabled:!1,onCheckedChange:()=>{k?y?g.removeGroupFromRemove(x.id):d==null||d(x.id):c==null||c(x.id)}}),e.jsxs("label",{htmlFor:`group-${x.id}`,className:"flex cursor-pointer flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:x.name}),x.type==="ORG_GROUP"?e.jsx(s.Building2,{className:"h-3 w-3 text-blue-600"}):e.jsx(s.Users,{className:"h-3 w-3 text-green-600"}),e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[x.memberCount," members"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:s.cn("text-xs",mn(x.type)),children:un(x.type)}),x.type==="TENANT_GROUP"&&x.tenantName&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",x.tenantName]})]}),x.description&&e.jsx("span",{className:"text-xs text-muted-foreground",children:x.description})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[k&&!y?e.jsx(Re,{currentRole:D,onRoleChange:v=>{j&&v!==j.role&&(u==null||u(x.id,j.role,v))},roleOptions:b,disabled:!1,allowDropdown:!0,className:E?"border-orange-300 bg-orange-100":""}):f&&!k&&e.jsx(Re,{currentRole:D,onRoleChange:v=>i==null?void 0:i(x.id,v),roleOptions:b,disabled:!1}),k&&!y&&!E&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>d==null?void 0:d(x.id),children:e.jsx(s.X,{className:"h-4 w-4"})}),y&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g.removeGroupFromRemove(x.id),children:"Undo"}),E&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g.removeGroupFromUpdate(x.id),children:"Cancel"})]})]},x.id)})})]})}function pt({selectedGroups:t,groupObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:l}){if(t.length===0)return null;const o=l();return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:["Selected Groups (",t.length,")"]}),e.jsx("div",{className:"space-y-1",children:t.map(c=>{const i=n.find(d=>d.id===c.id);return i?e.jsxs("div",{className:"flex items-center justify-between rounded-md border bg-muted/50 p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[i.type==="ORG_GROUP"?e.jsx(s.Building2,{className:"h-4 w-4 text-blue-600"}):e.jsx(s.Users,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{className:"text-sm font-medium",children:i.name}),e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[i.memberCount," members"]}),i.type==="TENANT_GROUP"&&i.tenantName&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",i.tenantName]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Re,{currentRole:c.role,onRoleChange:d=>r(c.id,d),roleOptions:o}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>a(c.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})]},c.id):null})})]})}function Us({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var fe;const{searchQuery:i,debouncedSearchQuery:d,setSearchQuery:u}=s.useShareSearchWithDebounce(),m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),g=s.useShareSelectedGroups(),b=s.useShareGroupsToRemove(),x=s.useShareGroupsToUpdate(),j=s.useShareCurrentMode(),f=s.useShareTenantWideRole(),y=s.useShareAllTenantsRole(),E=s.useShareSelectedTenant(),k=s.useShareManagementActions(),{data:C,isLoading:D}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"}),{groups:v,isLoading:N}=s.useShareableGroups("tenant",(a==null?void 0:a.tenantId)||E),[S,F]=A.useState((a==null?void 0:a.type)==="organization"?"all_tenants":"specific_tenant_users");A.useEffect(()=>{(a==null?void 0:a.type)==="tenant"?(k.setCurrentContext("tenant-dialog"),k.setCurrentMode("specificTenantUsers")):(k.setCurrentContext("tenant-tab"),k.setCurrentMode("allTenants"))},[k,a==null?void 0:a.type]);const I=$=>{var Z,le,ne,je;F($);let K;if($==="specific_tenant_users"?K="specific_users":$==="all_tenant_users"||$==="all_tenants"?K="all_users":$==="groups"?K="groups":K="specific_users",r==null||r(K),$==="groups"?(k.setCurrentContext("group-share"),k.setCurrentMode("specificGroups")):(a==null?void 0:a.type)==="tenant"?(k.setCurrentContext("tenant-dialog"),$==="specific_tenant_users"?k.setCurrentMode("specificTenantUsers"):$==="all_tenant_users"&&(k.setCurrentMode("allTenantUsers"),a!=null&&a.tenantId&&k.setSelectedTenant(a.tenantId))):(k.setCurrentContext("tenant-tab"),$==="specific_tenant_users"?k.setCurrentMode("specificTenantUsers"):$==="all_tenant_users"?k.setCurrentMode("allTenantUsers"):$==="all_tenants"&&k.setCurrentMode("allTenants")),$==="all_tenant_users"){const xe=(le=(Z=w==null?void 0:w.shares)==null?void 0:Z.tenantWide)==null?void 0:le[0];xe&&xe.role!==void 0&&k.setTenantWideRole(xe.role)}else if($==="all_tenants"){const xe=(je=(ne=w==null?void 0:w.shares)==null?void 0:ne.allTenantsOnly)==null?void 0:je[0];xe&&xe.role!==void 0&&k.setAllTenantsRole(xe.role)}},P=$=>{k.setSelectedTenant($)},{allUsers:T,existingShares:w,isLoadingUsers:L,isErrorLoadingUsers:O,isLoadingShares:R,isErrorLoadingShares:M}=ze({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant",tenantId:(a==null?void 0:a.type)==="tenant"?a.tenantId:E}),B=$=>{var ne,je;const K=m.some(xe=>xe.id===$),Z=h.includes($),le=(je=(ne=w==null?void 0:w.shares)==null?void 0:ne.specificTenantUsers)==null?void 0:je.some(xe=>xe.tenantUserId===$);K?k.removeSelectedUser($):Z?k.removeUserFromRemove($):le||k.addSelectedUser({id:$,role:"VIEWER"})},Y=($,K)=>{k.updateSelectedUserRole($,K)},_=$=>{k.addUserToRemove($),k.removeSelectedUser($)},Q=$=>{k.removeUserFromRemove($)},X=$=>{k.removeUserFromUpdate($)},q=($,K,Z)=>{k.addUserToUpdate({id:$,currentRole:K,newRole:Z})},W=($,K)=>{S==="all_tenant_users"?k.setTenantWideRole(K):S==="all_tenants"&&k.setAllTenantsRole(K)},G=()=>{S==="all_tenant_users"?k.setTenantWideRole("VIEWER"):S==="all_tenants"&&k.setAllTenantsRole("VIEWER")},V=(()=>{var $,K,Z,le;return j==="allTenants"?(K=($=w==null?void 0:w.shares)==null?void 0:$.allTenantsOnly)==null?void 0:K[0]:j==="allTenantUsers"?(le=(Z=w==null?void 0:w.shares)==null?void 0:Z.tenantWide)==null?void 0:le[0]:null})();A.useEffect(()=>{var $,K,Z,le;if(S==="all_tenant_users"){const ne=(K=($=w==null?void 0:w.shares)==null?void 0:$.tenantWide)==null?void 0:K[0];ne&&ne.role!==void 0&&k.setTenantWideRole(ne.role)}else if(S==="all_tenants"){const ne=(le=(Z=w==null?void 0:w.shares)==null?void 0:Z.allTenantsOnly)==null?void 0:le[0];ne&&ne.role!==void 0&&k.setAllTenantsRole(ne.role)}},[S,w,k]);const U=T.filter($=>m.some(K=>K.id===$.id)),ee=$=>{const K=g.some(ne=>ne.id===$),Z=b.includes($),le=re==null?void 0:re.some(ne=>ne.groupId===$);K?k.removeSelectedGroup($):Z?k.removeGroupFromRemove($):le||k.addSelectedGroup({id:$,role:"VIEWER"})},ae=($,K)=>{k.updateSelectedGroupRole($,K)},ie=$=>{k.addGroupToRemove($),k.removeSelectedGroup($)},z=($,K,Z)=>{k.addGroupToUpdate({id:$,currentRole:K,newRole:Z})},te=v.filter($=>g.some(K=>K.id===$.id)),oe=A.useMemo(()=>S!=="groups"?[]:v.filter($=>$.type!=="TENANT_GROUP"?!1:$.name.toLowerCase().includes(i.toLowerCase())||$.description&&$.description.toLowerCase().includes(i.toLowerCase())),[v,S,i]),re=A.useMemo(()=>{var K,Z;const $=((K=w==null?void 0:w.shares)==null?void 0:K.specificGroups)||((Z=w==null?void 0:w.shares)==null?void 0:Z.groups)||[];return!$||$.length===0?[]:$.filter(le=>{const ne=v.find(je=>je.id===le.groupId);return(ne==null?void 0:ne.type)==="TENANT_GROUP"})},[w,v]),J=L||R||S==="groups"&&N,ce=O||M,de=()=>(a==null?void 0:a.type)==="tenant"||S==="all_tenants"||S==="groups"?!0:E&&(S==="specific_tenant_users"||S==="all_tenant_users");return e.jsxs(e.Fragment,{children:[ce&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(s.CircleAlert,{className:"mx-auto mb-2 h-8 w-8 text-destructive"}),e.jsx("p",{className:"mb-4 text-sm text-destructive",children:"Failed to load users or shares"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:()=>window.location.reload(),children:"Retry"})]})}),!ce&&a&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(Ss,{shareType:S,onShareTypeChange:I,currentUser:a,options:(a==null?void 0:a.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"specific_tenant_users",label:"Specific Users",description:"Share with specific tenant users",icon:e.jsx(s.User,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"groups",label:"Groups",description:"Share with tenant groups",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-green-500"})}]:[{value:"all_tenants",label:"All Tenants",description:"Share with all tenants and their users",icon:e.jsx(zs,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"all_tenant_users",label:"Specific Tenant",description:"Share with all users of a specific tenant",icon:e.jsx(s.House,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"specific_tenant_users",label:"Specific Tenant User",description:"Share with users of a specific tenant",icon:e.jsx(s.User,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(a==null?void 0:a.type)==="organization"&&(S==="specific_tenant_users"||S==="all_tenant_users")&&e.jsxs("div",{className:"mt-4",children:[e.jsx(s.Label,{className:"mb-1 block text-sm font-medium",children:"Select Tenant"}),e.jsxs(s.Select,{value:E||"",onValueChange:P,disabled:D,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:D?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(fe=C==null?void 0:C.tenants)==null?void 0:fe.map($=>e.jsx(s.SelectItem,{value:$.id,children:$.name},$.id))})]})]}),de()?e.jsx(e.Fragment,{children:S==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(ts,{value:i,onChange:u}),e.jsx(ot,{selectedUsers:m,selectedUserObjects:U,onRemove:$=>B($),onRoleChange:Y,getRoleOptions:be}),e.jsx(it,{usersToRemove:h,allUsers:T,onRemove:Q}),e.jsx(ct,{usersToUpdate:p,allUsers:T,onRemove:X,getRoleOptions:be}),e.jsx(mt,{existingShares:w,isInitialLoading:!!J,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:be,allUsers:T,currentUser:a,handleUserToggle:B,handleUserRoleChange:Y,handleRemoveAccess:_,handleUpdateAccess:q})]}):S==="groups"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(ts,{value:i,onChange:u,placeholder:"Search groups..."}),e.jsx(pt,{selectedGroups:g,groupObjects:te,onRemove:ee,onRoleChange:ae,getRoleOptions:be}),b.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-destructive",children:["Groups to Remove (",b.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"These groups will lose access when you save"})]}),x.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-orange-600",children:["Groups to Update (",x.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),e.jsx(xt,{groups:oe,existingGroupShares:re,isLoading:N,resource:t,getRoleOptions:be,currentUser:a,handleGroupToggle:ee,handleGroupRoleChange:ae,handleRemoveAccess:ie,handleUpdateAccess:z})]}):S==="all_tenant_users"||S==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(ht,{currentUser:a,currentShare:V,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:W,onRemoveAccess:G,allUsersToUpdate:j==="allTenantUsers"&&((V==null?void 0:V.role)===void 0||f!==V.role)||j==="allTenants"&&((V==null?void 0:V.role)===void 0||y!==V.role)?{currentRole:(V==null?void 0:V.role)||"VIEWER",newRole:j==="allTenantUsers"?f:y}:null,allUsersToRemove:j==="allTenantUsers"&&(V==null?void 0:V.role)===void 0||j==="allTenants"&&(V==null?void 0:V.role)===void 0})}):null}):(a==null?void 0:a.type)==="organization"&&(S==="specific_tenant_users"||S==="all_tenant_users")&&e.jsx("div",{className:"mt-6 flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(zs,{className:"mx-auto mb-2 h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Please select a tenant to continue"})]})})]})]})}function hn({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var O,R;const{searchQuery:i,setSearchQuery:d}=s.useShareSearchWithDebounce(),u=s.useShareSelectedGroups(),m=s.useShareGroupsToRemove(),h=s.useShareGroupsToUpdate(),p=s.useShareManagementActions(),[g,b]=A.useState("org_groups"),[x,j]=A.useState(""),{data:f,isLoading:y}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"&&g==="tenant_groups"}),E=Array.isArray(f)?f:(f==null?void 0:f.tenants)||[],k=()=>{if((a==null?void 0:a.type)==="organization")return"organization";if((a==null?void 0:a.type)==="tenant")return"tenant"},{groups:C,isLoading:D}=s.useShareableGroups(k(),g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"?x:a==null?void 0:a.tenantId),{existingShares:v}=ze({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n}),N=C.filter(M=>g==="org_groups"&&M.type!=="ORG_GROUP"||g==="tenant_groups"&&M.type!=="TENANT_GROUP"||g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&(!x||M.tenantId&&M.tenantId!==x)?!1:M.name.toLowerCase().includes(i.toLowerCase())||M.description&&M.description.toLowerCase().includes(i.toLowerCase())),S=((O=v==null?void 0:v.shares)==null?void 0:O.specificGroups)||((R=v==null?void 0:v.shares)==null?void 0:R.groups)||[];A.useEffect(()=>{p.setCurrentContext("group-share"),p.setCurrentMode("specificGroups")},[p]);const F=M=>{const B=M;b(B),B==="org_groups"&&j(""),r==null||r(B==="org_groups"?"specific_groups":"all_groups"),p.setCurrentContext("group-share"),p.setCurrentMode("specificGroups")},I=C.filter(M=>u.some(B=>B.id===M.id)),P=M=>{const B=u.some(Q=>Q.id===M),Y=m.includes(M),_=S==null?void 0:S.some(Q=>Q.groupId===M);B?p.removeSelectedGroup(M):Y?p.removeGroupFromRemove(M):_||p.addSelectedGroup({id:M,role:"VIEWER"})},T=(M,B)=>{p.updateSelectedGroupRole(M,B)},w=M=>{p.addGroupToRemove(M),p.removeSelectedGroup(M)},L=(M,B,Y)=>{p.addGroupToUpdate({id:M,currentRole:B,newRole:Y})};return a?e.jsxs(e.Fragment,{children:[e.jsx(Ss,{shareType:g,onShareTypeChange:F,currentUser:a,options:[{value:"org_groups",label:"Organization Groups",description:"Share with organization-level groups",icon:e.jsx(s.Building2,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"tenant_groups",label:"Tenant Groups",description:"Share with tenant-level groups",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-green-500"})}]}),g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(s.Label,{children:"Select Tenant"}),e.jsxs(s.Select,{value:x,onValueChange:j,disabled:y,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:y?"Loading tenants...":"Select a tenant to view its groups"})}),e.jsx(s.SelectContent,{className:"z-[51]",children:E.map(M=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:M.id,children:M.name},M.id))})]})]}),e.jsx("div",{className:"mt-3 space-y-2",children:g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&!x?e.jsx("div",{className:"rounded-md border border-dashed p-6 text-center",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Please select a tenant above to view and share with its groups"})}):e.jsxs(e.Fragment,{children:[e.jsx(ts,{value:i,onChange:d,placeholder:"Search groups..."}),e.jsx(pt,{selectedGroups:u,groupObjects:I,onRemove:P,onRoleChange:T,getRoleOptions:be}),m.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-destructive",children:["Groups to Remove (",m.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"These groups will lose access when you save"})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-orange-600",children:["Groups to Update (",h.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),e.jsx(xt,{groups:N,existingGroupShares:S,isLoading:D,resource:t,getRoleOptions:be,currentUser:a,handleGroupToggle:P,handleGroupRoleChange:T,handleRemoveAccess:w,handleUpdateAccess:L})]})})]}):null}const ft=()=>{const t=s.useShareCurrentContext(),n=s.useShareCurrentMode(),a=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),l=s.useShareUsersToUpdate(),o=s.useShareSelectedGroups(),c=s.useShareGroupsToRemove(),i=s.useShareGroupsToUpdate(),d=s.useShareSelectedTenant(),u=s.useShareOrgWideRole(),m=s.useShareAllTenantsRole(),h=s.useShareTenantWideRole(),p=s.useShareGroupWideRole(),g=A.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedGroups:o,groupsToRemove:c,groupsToUpdate:i,selectedTenant:d,orgWideRole:u,allTenantsRole:m,tenantWideRole:h}),[t,n,a,r,l,o,c,i,d,u,m,h,p]),b=A.useMemo(()=>j=>s.validateShareData(j),[]),x=A.useMemo(()=>{if(!t||!n)return!1;switch(t){case"org-tab":return n==="specificOrgUsers"?a.length>0||r.length>0||l.length>0:!0;case"tenant-tab":if(n==="allTenantUsers"){if(!d)return!1}else if(n==="specificTenantUsers")return d?a.length>0||r.length>0||l.length>0:!1;return!0;case"tenant-dialog":return n==="specificTenantUsers"?a.length>0||r.length>0||l.length>0:!0;case"group-share":return n==="specificGroups"?o.length>0||c.length>0||i.length>0:!0}return!1},[t,n,a,r,l,o,c,i,d]);return{buildShareData:g,validateShareData:b,isCurrentStateValid:x,currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedTenant:d,orgWideRole:u,allTenantsRole:m,tenantWideRole:h}};function Gs({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllUsersShare:d,onRemoveAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),g=s.useShareSelectedTenant(),b=s.useShareOrgWideRole(),x=s.useShareAllTenantsRole(),j=s.useShareTenantWideRole(),{buildShareData:f,validateShareData:y,isCurrentStateValid:E}=ft(),k=a||r||l,C=()=>{var F,I,P,T;if(k)return"Updating...";if(i==="specific_users"){if(m.length===0&&h.length===0&&p.length===0)return"Select users to share with";const w=m.length+h.length+p.length;return w===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${w} user${w!==1?"s":""}`:h.length>0&&m.length===0&&p.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&p.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:p.length>0&&m.length===0&&h.length===0?`Update access for ${p.length} user${p.length!==1?"s":""}`:`Update access for ${w} user${w!==1?"s":""}`}else if(i==="all_users"){if(!d||d.role===void 0)return"Share with All Users";const w=d.role;return b===w?"Remove Access":"Update Access"}else if(i==="all_tenants"){const w=(I=(F=n==null?void 0:n.shares)==null?void 0:F.allTenantsOnly)==null?void 0:I[0];if(!w||w.role===void 0)return"Share with All Tenants";const L=w.role;return x===L?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const w=(T=(P=n==null?void 0:n.shares)==null?void 0:P.tenantWide)==null?void 0:T[0];if(!w||w.role===void 0)return"Share with All Tenant Users";const L=w.role;return j===L?"Remove Access":"Update Access"}else if(i==="specific_tenant_users"){if(m.length===0&&h.length===0&&p.length===0)return"Select users to share with";const w=m.length+h.length+p.length;return w===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${w} user${w!==1?"s":""}`:h.length>0&&m.length===0&&p.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&p.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:p.length>0&&m.length===0&&h.length===0?`Update access for ${p.length} user${p.length!==1?"s":""}`:`Update access for ${w} user${w!==1?"s":""}`}return"Share"},D=()=>k||!t||i==="all_tenant_users"&&!g||i==="specific_tenant_users"&&!g?!0:!E,v=()=>{const F=f();F&&y(F)&&o(F)},N=()=>{var F,I,P,T;if(i==="all_users")if(!d||d.role===void 0){const w=f();w&&y(w)&&o(w)}else{const w=d.role;if(b===w)u==null||u();else{const O=f();if(O&&y(O)){const R={...O,updateAccess:!0};o(R)}}}else if(i==="all_tenants"){const w=(I=(F=n==null?void 0:n.shares)==null?void 0:F.allTenantsOnly)==null?void 0:I[0];if(!w||w.role===void 0){const L=f();L&&y(L)&&o(L)}else{const L=w.role;if(x===L)u==null||u();else{const R=f();if(R&&y(R)){const M={...R,updateAccess:!0};o(M)}}}}else if(i==="all_tenant_users"){const w=(T=(P=n==null?void 0:n.shares)==null?void 0:P.tenantWide)==null?void 0:T[0];if(!w||w.role===void 0){const L=f();L&&y(L)&&o(L)}else{const L=w.role;if(j===L)u==null||u();else{const R=f();if(R&&y(R)){const M={...R,updateAccess:!0};o(M)}}}}},S=()=>{var F,I,P,T;if(i==="all_users"){if(!d||d.role===void 0)return"default";const w=d.role;return b===w?"destructive":"default"}else if(i==="all_tenants"){const w=(I=(F=n==null?void 0:n.shares)==null?void 0:F.allTenantsOnly)==null?void 0:I[0];if(!w||w.role===void 0)return"default";const L=w.role;return x===L?"destructive":"default"}else if(i==="all_tenant_users"){const w=(T=(P=n==null?void 0:n.shares)==null?void 0:P.tenantWide)==null?void 0:T[0];if(!w||w.role===void 0)return"default";const L=w.role;return j===L?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:k,children:"Close"}),(i==="specific_users"||i==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(m.length>0||h.length>0||p.length>0)&&e.jsxs(s.Button,{onClick:v,disabled:!t||k,variant:"default",children:[k?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Pe,{className:"mr-2 h-4 w-4"}),!k&&C()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:N,disabled:D(),variant:S(),children:[k?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(s.Users,{className:"mr-2 h-4 w-4"}),!k&&C()]})]})}function xn({resource:t,isSharing:n,isRemoving:a,isUpdating:r,onShare:l,onClose:o,shareTabType:c,currentAllUsersShare:i}){const d=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),m=s.useShareUsersToUpdate(),h=s.useShareSelectedGroups(),p=s.useShareGroupsToRemove(),g=s.useShareGroupsToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const b=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:x,validateShareData:j,isCurrentStateValid:f}=ft(),y=n||a||r,E=()=>{if(y)return"Updating...";if(c==="specific_users"){if(d.length===0&&u.length===0&&m.length===0)return"Select users to share with";const S=d.length+u.length+m.length;return S===0?"Select users to share with":d.length>0&&u.length>0?`Update access for ${S} user${S!==1?"s":""}`:u.length>0&&d.length===0&&m.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:d.length>0&&u.length===0&&m.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:m.length>0&&d.length===0&&u.length===0?`Update access for ${m.length} user${m.length!==1?"s":""}`:`Update access for ${S} user${S!==1?"s":""}`}else if(c==="groups"){if(h.length===0&&p.length===0&&g.length===0)return"Select groups to share with";const S=h.length+p.length+g.length;return S===0?"Select groups to share with":h.length>0&&p.length>0?`Update access for ${S} group${S!==1?"s":""}`:p.length>0&&h.length===0&&g.length===0?`Remove access for ${p.length} group${p.length!==1?"s":""}`:h.length>0&&p.length===0&&g.length===0?`Share with ${h.length} group${h.length!==1?"s":""}`:g.length>0&&h.length===0&&p.length===0?`Update access for ${g.length} group${g.length!==1?"s":""}`:`Update access for ${S} group${S!==1?"s":""}`}else if(c==="all_users"){if(!i||i.role==="NONE")return"Share with All Users";const S=i.role;return b===S?"Remove Access":"Update Access"}return"Share"},k=()=>y||!t?!0:!f,C=()=>{const S=x();S&&j(S)&&l(S)},D=()=>{const S=x();S&&j(S)&&l(S)},v=()=>{if(!i||i.role==="NONE"){const S=x();S&&j(S)&&l(S)}else{const S=i.role;if(b===S){const I=x();if(I&&j(I)){const P={...I,removeAccess:!0};l(P)}}else{const I=x();if(I&&j(I)){const P={...I,updateAccess:!0};l(P)}}}},N=()=>!i||i.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:o,disabled:y,children:"Close"}),c==="specific_users"&&e.jsx(e.Fragment,{children:(d.length>0||u.length>0||m.length>0)&&e.jsxs(s.Button,{onClick:C,disabled:!t||y,variant:"default",children:[y?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Pe,{className:"mr-2 h-4 w-4"}),!y&&E()]})}),c==="groups"&&e.jsx(e.Fragment,{children:(h.length>0||p.length>0||g.length>0)&&e.jsxs(s.Button,{onClick:D,disabled:!t||y,variant:"default",children:[y?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Pe,{className:"mr-2 h-4 w-4"}),!y&&E()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:v,disabled:k(),variant:N(),children:[y?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Pe,{className:"mr-2 h-4 w-4"}),!y&&E()]})]})}function pn({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllGroupsShare:d,onRemoveAccess:u}){const m=s.useShareSelectedGroups(),h=s.useShareGroupsToRemove(),p=s.useShareGroupsToUpdate();s.useShareGroupWideRole(),s.useShareCurrentMode();const g=()=>{o({context:"group-share",mode:"specificGroups",selectedGroups:m,groupsToRemove:h,groupsToUpdate:p})},b=()=>m.length>0||h.length>0||p.length>0,x=()=>h.length>0&&m.length===0&&p.length===0?"Remove Access":p.length>0&&m.length===0&&h.length===0?"Update Access":"Share with Groups",j=a||r||l;return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[m.length>0&&e.jsxs("span",{children:[m.length," groups selected"]}),h.length>0&&e.jsxs("span",{className:"ml-2 text-destructive",children:["• ",h.length," to remove"]}),p.length>0&&e.jsxs("span",{className:"ml-2 text-orange-600",children:["• ",p.length," to update"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:j,children:"Cancel"}),e.jsxs(s.Button,{onClick:g,disabled:!b()||j,children:[j&&e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),x()]})]})]})}function ge(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function Se(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function fn(t,n,a){const{resourceType:r,resourceId:l,shareMutation:o,removeMutation:c,existingShares:i,resetUserSelections:d}=n;if(l)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const u=ge(r,l,[{scope:"org_users_only",role:t.orgWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h}=t;if(u&&u.length>0){const p=ge(r,l,u.map(g=>({scope:"specific_org_user",orgUserId:g.id,role:g.role})));o(p,{onSuccess:()=>{d()}})}if(m&&m.length>0){const p=Se(r,l,m.map(g=>{var x,j;const b=(j=(x=i==null?void 0:i.shares)==null?void 0:x.specificOrgUsers)==null?void 0:j.find(f=>f.orgUserId===g);return{scope:"specific_org_user",orgUserId:g,role:(b==null?void 0:b.role)||"VIEWER"}}));c(p,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(p=>{const g=ge(r,l,[{scope:"specific_org_user",orgUserId:p.id,role:p.newRole}]);o(g,{onSuccess:()=>{d()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const u=ge(r,l,[{scope:"all_tenants_only",role:t.allTenantsRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="allTenantUsers"){const u=ge(r,l,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h,tenantId:p}=t;if(m&&m.length>0){const g=Se(r,l,m.map(b=>{var j,f;const x=(f=(j=i==null?void 0:i.shares)==null?void 0:j.specificTenantUsers)==null?void 0:f.find(y=>y.tenantUserId===b);return{scope:"specific_tenant_user",tenantUserId:b,tenantId:p,role:(x==null?void 0:x.role)||"VIEWER"}}));c(g,{onSuccess:()=>{d()}})}if(h&&h.length>0&&h.forEach(g=>{const b=ge(r,l,[{scope:"specific_tenant_user",tenantUserId:g.id,tenantId:p,role:g.newRole}]);o(b,{onSuccess:()=>{d()}})}),u&&u.length>0){const g=ge(r,l,u.map(b=>({scope:"specific_tenant_user",tenantUserId:b.id,tenantId:p,role:b.role})));o(g,{onSuccess:()=>{d()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const u=Se(r,l,[{scope:"all_tenant_users",role:"VIEWER"}]);c(u,{onSuccess:()=>{d()}})}else if(t.updateAccess){const u=ge(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else{const u=ge(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h}=t;if(u&&u.length>0){const p=ge(r,l,u.map(g=>({scope:"specific_tenant_user",tenantUserId:g.id,role:g.role})));o(p,{onSuccess:()=>{d()}})}if(m&&m.length>0){const p=Se(r,l,m.map(g=>{var x,j;const b=(j=(x=i==null?void 0:i.shares)==null?void 0:x.specificTenantUsers)==null?void 0:j.find(f=>f.tenantUserId===g);return{scope:"specific_tenant_user",tenantUserId:g,role:(b==null?void 0:b.role)||"VIEWER"}}));c(p,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(p=>{const g=ge(r,l,[{scope:"specific_tenant_user",tenantUserId:p.id,role:p.newRole}]);o(g,{onSuccess:()=>{d()}})})}break;case"group-share":if(t.mode==="specificGroups"){const{selectedGroups:u,groupsToRemove:m,groupsToUpdate:h}=t;if(u&&u.length>0){const p=ge(r,l,u.map(g=>({scope:"group",groupId:g.id,role:g.role})));o(p,{onSuccess:()=>{var g;d(),(g=n.resetGroupSelections)==null||g.call(n),s.ue.success(`Shared with ${u.length} group${u.length!==1?"s":""}`)}})}if(m&&m.length>0){const p=Se(r,l,m.map(g=>({scope:"group",groupId:g,role:"VIEWER"})));c(p,{onSuccess:()=>{var g;d(),(g=n.resetGroupSelections)==null||g.call(n),s.ue.success(`Removed access from ${m.length} group${m.length!==1?"s":""}`)}})}h&&h.length>0&&h.forEach(p=>{const g=ge(r,l,[{scope:"group",groupId:p.id,role:p.newRole}]);o(g,{onSuccess:()=>{var b;d(),(b=n.resetGroupSelections)==null||b.call(n),s.ue.success("Updated access for group")}})})}break}}function gn(t,n,a,r){var u,m,h,p,g,b;const{resourceType:l,resourceId:o,removeMutation:c,existingShares:i,resetUserSelections:d}=r;if(o)if(t.length>0){const x=Se(l,o,t.map(j=>{var y,E;const f=(E=(y=i==null?void 0:i.shares)==null?void 0:y.specificTenantUsers)==null?void 0:E.find(k=>k.tenantUserId===j);return{scope:"specific_tenant_user",tenantUserId:j,role:(f==null?void 0:f.role)||"VIEWER"}}));c(x,{onSuccess:()=>{d()},onError:j=>{console.error("Remove access failed:",j)}})}else{const x=n==="tenant"&&a==="allTenants",j=n==="tenant"&&a==="allTenantUsers";if(x){const f=(m=(u=i==null?void 0:i.shares)==null?void 0:u.allTenantsOnly)==null?void 0:m[0];if(f){const y=Se(l,o,[{scope:"all_tenants_only",role:f.role}]);c(y,{onSuccess:()=>{d()},onError:E=>{console.error("Remove all-tenants access failed:",E)}})}}else if(j){const f=(p=(h=i==null?void 0:i.shares)==null?void 0:h.tenantWide)==null?void 0:p[0];if(f){const y=Se(l,o,[{scope:"all_tenant_users",role:f.role}]);c(y,{onSuccess:()=>{d()},onError:E=>{console.error("Remove all-tenant-users access failed:",E)}})}}else{const f=(b=(g=i==null?void 0:i.shares)==null?void 0:g.orgUsersOnly)==null?void 0:b[0];if(f){const y=Se(l,o,[{scope:"org_users_only",role:f.role}]);c(y,{onSuccess:()=>{d()},onError:E=>{console.error("Remove org-wide access failed:",E)}})}}}}function jn(t,n,a){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),o=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{currentUser:i}=s.useCurrentUserInfo(),{existingShares:d}=ze({debouncedSearchQuery:"",resourceId:t||"",resourceType:s.ResourceType.DASHBOARD,userType:"tenant"}),u=A.useCallback(()=>{r.resetUserSelections()},[r]),m=A.useCallback(()=>{r.resetGroupSelections()},[r]),h=A.useCallback(g=>{if(!t)return;const b={resourceType:s.ResourceType.DASHBOARD,resourceId:t,shareMutation:n,removeMutation:a,existingShares:d,resetUserSelections:u,resetGroupSelections:m};fn(g,b,i)},[t,n,a,d,u,m,i]),p=A.useCallback(()=>{if(!t)return;const g={resourceType:s.ResourceType.DASHBOARD,resourceId:t,removeMutation:a,existingShares:d,resetUserSelections:u};gn(l,o||"",c||"",g)},[t,n,a,d,u,m,l,o,c]);return{handleShareSubmit:h,handleRemoveAccess:p}}function ls({resource:t,resourceType:n,onClose:a,onShareSuccess:r,onRemoveSuccess:l}){var T,w,L,O,R,M,B,Y;const{currentUser:o}=s.useCurrentUserInfo(),[c,i]=A.useState("specific_users"),[d,u]=A.useState("specific_users"),[m,h]=A.useState("specific_groups"),p=s.useShareManagementActions(),g=s.useShareSelectedTab(),b=s.useShareCurrentMode(),x=s.useShareResource(),j=s.useRemoveResourceShares(),{handleShareSubmit:f,handleRemoveAccess:y}=jn(t.id,(_,Q)=>{x.mutate(_,{...Q,onSuccess:()=>{var X;(X=Q==null?void 0:Q.onSuccess)==null||X.call(Q),r==null||r()}})},(_,Q)=>{j.mutate(_,{...Q,onSuccess:()=>{var X;(X=Q==null?void 0:Q.onSuccess)==null||X.call(Q),l==null||l()}})}),E=x.isPending,k=j.isPending,C=x.isPending,{existingShares:D}=ze({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant"}),{existingShares:v}=ze({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"organization"}),N=(w=(T=D==null?void 0:D.shares)==null?void 0:T.tenantWide)==null?void 0:w[0],S=(O=(L=v==null?void 0:v.shares)==null?void 0:L.orgUsersOnly)==null?void 0:O[0],F=()=>{if(g==="org")return d;switch(b){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},I=A.useCallback(()=>{p.resetShareState(),a()},[p,a]),P=(o==null?void 0:o.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:I,children:e.jsxs(s.DialogContent,{className:"z-[51] flex max-h-[80vh] max-w-3xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Pe,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:P?"Share this resource with org users or tenant users. As a super admin, you can share with all users.":"Share this resource with other users in your tenant."})]}),P?e.jsxs(s.Tabs,{value:g,onValueChange:_=>{const Q=_;p.setSelectedTab(Q),p.resetUserSelections(),p.resetGroupSelections()},className:"mb-4 min-h-0 flex-1",children:[e.jsxs(s.TabsList,{className:"mb-2 grid w-full grid-cols-3",children:[e.jsx(s.TabsTrigger,{value:"org",children:"Org Users"}),e.jsx(s.TabsTrigger,{value:"tenant",children:"Tenant Users"}),e.jsx(s.TabsTrigger,{value:"groups",children:"Groups"})]}),e.jsx(s.TabsContent,{value:"org",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(dn,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:u,isSharing:E,isUpdating:C,isRemoving:k})})}),e.jsx(s.TabsContent,{value:"tenant",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(Us,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:_=>i(_),isSharing:E,isUpdating:C,isRemoving:k})})}),e.jsx(s.TabsContent,{value:"groups",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(hn,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:h,isSharing:E,isUpdating:C,isRemoving:k})})})]}):e.jsx("div",{className:"mb-4 min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(Us,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:_=>i(_),isSharing:E,isUpdating:C,isRemoving:k})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:P?g==="org"?e.jsx(Gs,{resource:t,existingShares:v,isSharing:E,isRemoving:k,isUpdating:C,onShare:f,onClose:a,shareTabType:d,currentAllUsersShare:S,onRemoveAccess:y}):g==="tenant"?e.jsx(Gs,{resource:t,existingShares:D,isSharing:E,isRemoving:k,isUpdating:C,onShare:f,onClose:a,shareTabType:F(),currentAllUsersShare:N,onRemoveAccess:y}):e.jsx(pn,{resource:t,existingShares:v,isSharing:E,isRemoving:k,isUpdating:C,onShare:f,onClose:a,shareTabType:m,currentAllGroupsShare:(o==null?void 0:o.type)==="organization"?(M=(R=v==null?void 0:v.shares)==null?void 0:R.allOrgGroups)==null?void 0:M[0]:(Y=(B=D==null?void 0:D.shares)==null?void 0:B.allTenantGroups)==null?void 0:Y[0],onRemoveAccess:y}):e.jsx(xn,{resource:t,isSharing:E,isRemoving:k,isUpdating:C,onShare:f,onClose:a,shareTabType:c,currentAllUsersShare:N,onRemoveAccess:y})})]})})}const bn=async(t,n,a)=>{const r=`${t}/management/v1/groups`;return await s.postRequestRegular(r,n,a)},vn=async(t,n,a)=>{const r=`${t}/management/v1/groups/${a}`,l=await fetch(r,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});if(!l.ok){const o=await l.text();throw new Error(o||"Failed to delete group")}},yn=async(t,n,a,r)=>{const l=`${t}/management/v1/groups/${a}/members`;return await s.postRequestRegular(l,n,r)},Nn=async(t,n,a,r)=>{const l=`${t}/management/v1/groups/${a}/members`,o=await fetch(l,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(r)});if(!o.ok){const c=await o.text();throw new Error(c||"Failed to remove group members")}};function Cn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>bn(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r),onSuccess:()=>{a.invalidateQueries({queryKey:["groups"]}),s.ue.success("Group created successfully")},onError:r=>{console.error("Failed to create group:",r),s.ue.error("Failed to create group",{description:r.message})}})}function Sn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>vn(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r),onSuccess:(r,l)=>{a.invalidateQueries({queryKey:["groups"]}),a.removeQueries({queryKey:["group",l]}),s.ue.success("Group deleted successfully")},onError:r=>{console.error("Failed to delete group:",r),s.ue.error("Failed to delete group",{description:r.message})}})}function wn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>yn(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r,l),onSuccess:(r,l)=>{a.invalidateQueries({queryKey:["group",l.groupId]}),a.invalidateQueries({queryKey:["group-members",l.groupId]}),a.invalidateQueries({queryKey:["groups"]}),s.ue.success("Members added successfully")},onError:r=>{console.error("Failed to add group members:",r),s.ue.error("Failed to add members",{description:r.message})}})}function Dn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>Nn(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r,l),onSuccess:(r,l)=>{a.invalidateQueries({queryKey:["group",l.groupId]}),a.invalidateQueries({queryKey:["group-members",l.groupId]}),a.invalidateQueries({queryKey:["groups"]}),s.ue.success("Members removed successfully")},onError:r=>{console.error("Failed to remove group members:",r),s.ue.error("Failed to remove members",{description:r.message})}})}function Tn({onSuccess:t,tenantId:n,isTenantUser:a}){const[r,l]=A.useState(""),[o,c]=A.useState(""),[i,d]=A.useState({}),u=Cn(),m=()=>{const p={};return r.trim()?r.length<3?p.name="Group name must be at least 3 characters":r.length>50&&(p.name="Group name must be less than 50 characters"):p.name="Group name is required",o&&o.length>200&&(p.description="Description must be less than 200 characters"),d(p),Object.keys(p).length===0},h=async p=>{if(p.preventDefault(),!m())return;const g={name:r.trim(),description:o.trim()||void 0,type:a?"TENANT_GROUP":"ORG_GROUP",...a&&n?{tenantId:n}:{}};try{await u.mutateAsync(g),l(""),c(""),d({}),t()}catch(b){console.error("Failed to create group:",b)}};return e.jsxs("form",{onSubmit:h,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"group-name",children:["Group Name ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(s.Input,{id:"group-name",placeholder:"e.g., Marketing Team, Engineering Squad",value:r,onChange:p=>{l(p.target.value),i.name&&d(g=>({...g,name:""}))},className:i.name?"border-destructive":"",disabled:u.isPending}),i.name&&e.jsx("p",{className:"text-sm text-destructive",children:i.name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"group-description",children:["Description",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:"(optional)"})]}),e.jsx(s.Textarea,{id:"group-description",placeholder:"Describe the purpose of this group...",value:o,onChange:p=>{c(p.target.value),i.description&&d(g=>({...g,description:""}))},className:i.description?"border-destructive":"",disabled:u.isPending,rows:3}),i.description&&e.jsx("p",{className:"text-sm text-destructive",children:i.description}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[o.length,"/200 characters"]})]}),e.jsx("div",{className:"rounded-lg border bg-muted/50 p-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(s.CircleAlert,{className:"h-4 w-4 mt-0.5 text-muted-foreground"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"This group will be accessible to users in your workspace. You can add members after creating the group."})]})})]}),e.jsxs("div",{className:"flex justify-end gap-3",children:[e.jsx(s.Button,{type:"button",variant:"outline",onClick:()=>{l(""),c(""),d({})},disabled:u.isPending,children:"Clear"}),e.jsx(s.Button,{type:"submit",disabled:u.isPending||!r.trim(),children:u.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Users,{className:"mr-2 h-4 w-4"}),"Create Group"]})})]})]})}function kn({open:t,onOpenChange:n,group:a,onUpdate:r}){const[l,o]=A.useState("members"),[c,i]=A.useState(""),[d,u]=A.useState([]),[m,h]=A.useState([]),{data:p,isLoading:g,refetch:b}=s.useGroupMembers(a.id),x=a.type==="TENANT_GROUP"?"tenant":"organization",{users:j,isLoading:f}=s.useUnifiedUsers({type:x,tenantId:a.tenantId||void 0,active:!0,limit:100}),y=wn(),E=Dn(),k=(p==null?void 0:p.members)||[],C=A.useMemo(()=>new Set(k.map(T=>T.userId)),[k]),D=A.useMemo(()=>j.filter(T=>!C.has(T.id)),[j,C]),v=A.useMemo(()=>{if(!c)return D;const T=c.toLowerCase();return D.filter(w=>{var L,O;return((L=w.name)==null?void 0:L.toLowerCase().includes(T))||((O=w.email)==null?void 0:O.toLowerCase().includes(T))})},[D,c]),N=A.useMemo(()=>{if(!c)return k;const T=c.toLowerCase();return k.filter(w=>{var L,O,R,M;return((O=(L=w.user)==null?void 0:L.name)==null?void 0:O.toLowerCase().includes(T))||((M=(R=w.user)==null?void 0:R.email)==null?void 0:M.toLowerCase().includes(T))})},[k,c]),S=async()=>{if(d.length!==0)try{await y.mutateAsync({groupId:a.id,data:{userIds:d,userType:x==="tenant"?"tenant":"org"}}),u([]),o("members"),b(),r==null||r()}catch(T){console.error("Failed to add members:",T)}},F=async()=>{if(m.length!==0)try{await E.mutateAsync({groupId:a.id,data:{userIds:m}}),h([]),b(),r==null||r()}catch(T){console.error("Failed to remove members:",T)}},I=T=>{u(w=>w.includes(T)?w.filter(L=>L!==T):[...w,T])},P=T=>{h(w=>w.includes(T)?w.filter(L=>L!==T):[...w,T])};return e.jsx(e.Fragment,{children:e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-3xl max-h-[80vh]","aria-describedby":"group-members-description",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:a.name}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[k.length," ",k.length===1?"member":"members"]})}),e.jsxs("p",{id:"group-members-description",className:"sr-only",children:["Add or remove members from the ",a.name," group"]})]}),e.jsxs(s.Tabs,{value:l,onValueChange:T=>{o(T),i(""),h([])},className:"mt-4",children:[e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"members",children:"Current Members"}),e.jsx(s.TabsTrigger,{value:"add",children:"Add Members"})]}),e.jsxs(s.TabsContent,{value:"members",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search members...",value:c,onChange:T=>i(T.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:m.length>0?"h-[300px]":"h-[350px]",children:g?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(T=>e.jsx(s.Skeleton,{className:"h-16 w-full"},T))}):N.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:N.map(T=>e.jsx(En,{member:T,selected:m.includes(T.userId),onToggle:()=>P(T.userId)},T.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:F,disabled:E.isPending,children:E.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:T=>i(T.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[300px]",children:f?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(T=>e.jsx(s.Skeleton,{className:"h-16 w-full"},T))}):v.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:v.map(T=>e.jsx(In,{user:T,selected:d.includes(T.id),onToggle:()=>I(T.id)},T.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:S,disabled:y.isPending,children:y.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 En({member:t,selected:n,onToggle:a}){var l,o,c,i;const r=((o=(l=t.user)==null?void 0:l.name)==null?void 0:o.split(" ").map(d=>d[0]).join("").toUpperCase())||"?";return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-card hover:bg-muted/50 cursor-pointer",onClick:a,children:[e.jsx(s.Checkbox,{checked:n}),e.jsx(s.Avatar,{className:"h-8 w-8",children:e.jsx(s.AvatarFallback,{className:"text-xs",children:r})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:((c=t.user)==null?void 0:c.name)||"Unknown User"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(i=t.user)==null?void 0:i.email})]})]})}function In({user:t,selected:n,onToggle:a}){var l;const r=((l=t.name)==null?void 0:l.split(" ").map(o=>o[0]).join("").toUpperCase())||"?";return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-card hover:bg-muted/50 cursor-pointer",onClick:a,children:[e.jsx(s.Checkbox,{checked:n}),e.jsx(s.Avatar,{className:"h-8 w-8",children:e.jsx(s.AvatarFallback,{className:"text-xs",children:r})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:t.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t.email})]})]})}function An({open:t,onOpenChange:n}){const[a,r]=A.useState("groups"),[l,o]=A.useState(""),[c,i]=A.useState(null),[d,u]=A.useState(!1),[m,h]=A.useState(null),{tokenProps:p}=s.useSemaphorContext(),{currentUser:g}=s.useCurrentUserInfo(),b=Sn(),x=(g==null?void 0:g.type)==="tenant",j=p==null?void 0:p.tenantId,{groups:f,isLoading:y,refetch:E}=s.useGroups({type:x?"TENANT_GROUP":"all",tenantId:x?j:void 0,includeMembers:!1}),k=f.filter(N=>{var S;return N.name.toLowerCase().includes(l.toLowerCase())||((S=N.description)==null?void 0:S.toLowerCase().includes(l.toLowerCase()))}),C=async()=>{if(m)try{await b.mutateAsync(m.id),h(null),E()}catch(N){console.error("Failed to delete group:",N)}},D=N=>{i(N),u(!0)},v=()=>{r("groups"),E()};return e.jsxs(e.Fragment,{children:[e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-4xl max-h-[80vh]",children:[e.jsxs(s.DialogHeader,{children:[e.jsxs(s.DialogTitle,{className:"flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-5 w-5"}),"Group Management"]}),e.jsx(s.DialogDescription,{children:"Manage your groups, create new groups, and control group membership"})]}),e.jsxs(s.Tabs,{value:a,onValueChange:r,className:"mt-4",children:[e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsxs(s.TabsTrigger,{value:"groups",className:"flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-4 w-4"}),"Groups"]}),e.jsxs(s.TabsTrigger,{value:"create",className:"flex items-center gap-2",children:[e.jsx(s.Plus,{className:"h-4 w-4"}),"Create Group"]})]}),e.jsx(s.TabsContent,{value:"groups",className:"mt-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search groups...",value:l,onChange:N=>o(N.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[400px]",children:y?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(N=>e.jsx(s.Skeleton,{className:"h-24 w-full"},N))}):k.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:k.map(N=>e.jsx(Mn,{group:N,onManageMembers:()=>D(N),onDelete:()=>h(N),currentUserId:g==null?void 0:g.id},N.id))})})]})}),e.jsx(s.TabsContent,{value:"create",className:"mt-4",children:e.jsx(Tn,{onSuccess:v,tenantId:j,isTenantUser:x})})]})]})}),c&&e.jsx(kn,{open:d,onOpenChange:u,group:c,onUpdate:()=>E()}),e.jsx(s.AlertDialog,{open:!!m,onOpenChange:()=>h(null),children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Group"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',m==null?void 0:m.name,'"? This action cannot be undone and will remove all members from the group.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:C,disabled:b.isPending,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:b.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Deleting..."]}):"Delete Group"})]})]})})]})}function Mn({group:t,onManageMembers:n,onDelete:a,currentUserId:r}){const l=t.createdBy===r;return e.jsx("div",{className:"rounded-lg border bg-card p-4 transition-colors hover:bg-muted/50",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium",children:t.name}),t.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:t.description})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(s.Users,{className:"h-3 w-3"}),t.memberCount," ",t.memberCount===1?"member":"members"]}),e.jsxs("span",{children:["Created ",s.format(new Date(t.createdAt),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:n,title:"Manage members",children:e.jsx(s.UserPlus,{className:"h-4 w-4"})}),l&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:a,title:"Delete group",className:"text-destructive hover:text-destructive",children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]})})}function Ln(){var te,oe,re;const{authToken:t,tokenProps:n,id:a}=s.useSemaphorContext(),{isLocalDev:r}=s.useDashboardPreferences(),{permissions:l}=s.useRoleAwareDisplayPreferences(),o=s.useHasDashboardId();s.useDashboardStore(J=>J.theme);const c=s.useDashboardStore(J=>J.lenses),i=s.useDashboardStore(J=>J.selectedLensId),d=c==null?void 0:c.find(J=>J.id===i),u=s.useDashboardStore(J=>J.dashboard);s.useDashboardStore(J=>J.selectedSheetId);const m=s.useDashboardStore(J=>J.isDashboardEditing),[h,p]=A.useState(!1),[g,b]=A.useState(!1),[x,j]=A.useState(!1),f=s.useDashboardStore(J=>J.isDashboardPanelOpen),y=s.useDashboardStore(J=>J.actions.setIsDashboardPanelOpen),E=s.useDashboardStore(J=>J.filterValues),k=s.useDashboardStore(J=>J.isVisualEditing),C=s.useManagementStore(J=>J.selectedDashboard),D=s.useManagementStore(J=>J.initialDashboard),v=C?(oe=C==null?void 0:C.permissions)==null?void 0:oe.canEdit:(te=D==null?void 0:D.permissions)==null?void 0:te.canEdit,N=s.useDashboardStore(J=>J.showFilters),S=s.useDashboardStore(J=>J.showDashboardJSON),F=s.useDashboardStore(J=>J.onSaveFunction),I=s.useDashboardStore(J=>J.actions.setShowFilters),{setIsDashboardEditing:P,setShowDashboardJSON:T}=s.useDashboardStore(J=>J.actions),{setInitialDashboard:w,clearSelectedDashboard:L}=s.useManagementStore(J=>J.actions),{resources:O}=s.useResourceManagement(s.ResourceType.DASHBOARD),{currentUser:R}=s.useCurrentUserInfo(),M=s.canUserManageGroups(R),B=C||D,Y=B?{id:B.id,title:(u==null?void 0:u.title)||B.title||"Dashboard"}:null;A.useEffect(()=>{if(O&&O.length>0){const J=u==null?void 0:u.id;if(J){const ce=O.find(de=>de.id===J);ce&&w(ce)}}},[O,u==null?void 0:u.id,w]);const _=n.orgUserId||n.tenantId,Q=m&&!k&&_&&v,{handleAddNewFrame:X}=s.useAddNewFrame(),q=()=>{P(!0)},[W,G]=A.useState(!1),se=s.useUpdateResource(s.ResourceType.DASHBOARD);async function V(){const J=ss(u);G(!0);const ce={template:J};se.mutate({resourceId:J.id,data:ce},{onSuccess:()=>{G(!1),s.ue.success("Dashboard saved!")},onError:()=>{G(!1),s.ue.error("Failed to save dashboard")}})}async function U(){if(p(!0),!i||!d)return;const J=ss(u),ce=JSON.stringify(J),de={...d,template:ce,filterValues:E};await vs(n.apiServiceUrl,de,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),F==null||F(J),p(!1)}if(k)return null;const ee=(d==null?void 0:d.name)||u.title,ie=O&&O.length>0&&(n.orgUserId||n.tenantId&&n.endUserId&&n.endUserEmail),z=C&&!(n!=null&&n.dashboard_id)&&!a;return e.jsxs("div",{className:"flex h-10 items-center justify-between gap-2 border-b py-2 pl-3 pr-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[ie&&e.jsxs(e.Fragment,{children:[z&&e.jsx(s.IconButton,{"aria-label":"Dashboard Hub",tooltip:"Back to Dashboard Hub",onClick:()=>L(),className:"h-7 p-2",children:e.jsx(s.House,{className:"h-4 w-4"})}),e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:o?"Manage Dashboards":"Select a dashboard to continue",onClick:()=>{o&&y(!f)},className:"h-7 p-2",buttonProps:{disabled:!o},children:e.jsx(Ta,{className:"h-4 w-4"})})]}),!k&&o&&e.jsx(s.Label,{children:ee})]}),e.jsxs("div",{className:"flex gap-2",children:[r&&e.jsx(s.IconButton,{tooltip:"Invalidate Token",onClick:()=>s.invalidateToken(n.apiServiceUrl),className:"h-7 p-2",children:e.jsx(za,{className:"h-4 w-4"})}),!k&&o&&e.jsx(Xa,{}),!k&&o&&e.jsx(lt,{}),!k&&o&&M&&e.jsx(s.IconButton,{tooltip:"Manage Groups",onClick:()=>j(!0),className:"h-7 p-2",children:e.jsx(s.Users,{className:"h-4 w-4"})}),!k&&o&&((re=B==null?void 0:B.permissions)==null?void 0:re.canShare)&&e.jsx(s.IconButton,{tooltip:"Share Dashboard",onClick:()=>b(!0),className:"h-7 p-2",children:e.jsx(s.UserPlus,{className:"h-4 w-4"})}),m&&!k&&_&&r&&o&&e.jsx(Qa,{}),!k&&_&&r&&o&&e.jsx(Ja,{}),m&&!k&&_&&d&&r&&o&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:h,onClick:U,size:"sm",children:[e.jsx(bs,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),m&&!k&&o&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",size:"sm",disabled:!m,onClick:()=>X(),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Visual"]}),!k&&!m&&l.canEdit&&o&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:q,size:"sm",children:[e.jsx(s.Pencil,{className:"mr-2 h-4 w-4"}),"Edit"]}),m&&!k&&o&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:()=>{P(!1),T(!1)},children:[e.jsx(s.Cross2Icon,{className:"mr-2 h-4 w-4"}),"Close"]}),Q&&o&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"outline",disabled:W,onClick:V,size:"sm",children:[W?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(bs,{className:"mr-2 h-4 w-4"}),W?"Saving...":"Save"]}),!N&&!k&&m&&l.canUseFilters&&o&&e.jsx(s.Button,{className:"h-7 p-2",variant:"outline",onClick:()=>I(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!k&&m&&r&&o&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(s.Button,{className:"h-7 p-2",onClick:()=>T(!S),size:"sm",variant:"ghost",children:e.jsx(Be,{className:"h-4 w-4"})})}),!k&&r&&e.jsx(qa,{}),g&&Y&&e.jsx(ls,{resource:Y,resourceType:s.ResourceType.DASHBOARD,onClose:()=>b(!1)}),e.jsx(An,{open:x,onOpenChange:j})]})]})}function Rn({name:t,items:n,value:a,onChange:r,isLoading:l,isError:o,refetch:c,className:i,icon:d,showNone:u=!1}){const m=Ee.useRef(null),[h,p]=Ee.useState(!1),[g,b]=Ee.useState("100%"),x=u?[...n||[],{id:"none",name:"None"}]:n;Ee.useLayoutEffect(()=>{m.current&&b(m.current.offsetWidth)},[]);function j(){var y;return l?"Loading...":o?"Error":a?(y=n==null?void 0:n.find(E=>E.id===a))==null?void 0:y.name:`Select ${t}`}function f(y,E){r(E),p(!1)}return e.jsxs(s.Popover,{open:h,onOpenChange:p,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{ref:m,variant:"outline",role:"combobox","aria-expanded":h,className:s.cn("flex h-9 w-full justify-between",i),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[d&&e.jsx("div",{className:"mr-2",children:d}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children:j()})]}),e.jsx(s.ChevronDown,{className:"size-4 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-full p-0",style:{minWidth:g},children:e.jsxs(s.Command,{children:[e.jsxs("div",{className:"flex h-9 items-center justify-between border-b pr-1",children:[e.jsx(s.CommandInput,{className:"h-9",placeholder:"Search..."}),e.jsx(s.IconButton,{className:"h-7",onClick:c,children:e.jsx(st,{className:s.cn("size-3.5 opacity-50",l&&"animate-spin")})})]}),e.jsxs(s.CommandList,{children:[e.jsxs(s.CommandEmpty,{children:["No ",t==null?void 0:t.toLowerCase()," found."]}),e.jsx(s.CommandGroup,{children:x==null?void 0:x.map(y=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:y.name,onSelect:E=>f(E,y.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",a===y.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:y.name,children:y.name})]})},y.id))})]})]})})]})}function Fe({title:t,items:n,value:a,isLoading:r,isError:l,refetch:o,onChange:c,showNone:i=!1,className:d,disabled:u=!1,type:m="combobox"}){const h=r?"Loading...":l?"Error":a;function p(){if(t==="Connection")return e.jsx(Fa,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(Ma,{className:"size-4"});if(t==="Table")return e.jsx(s.Table2,{className:"size-4"});if(t==="Model")return e.jsx(ia,{className:"size-4"})}function g(){return e.jsxs(s.Select,{disabled:u,value:h,onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:s.cn("h-9 w-full border-muted focus:ring-1 focus:ring-offset-0",d),children:e.jsx(s.SelectValue,{placeholder:r?"Loading...":l?"Error":`Select ${t}`})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[r?e.jsx(s.SelectLabel,{children:"Loading..."}):e.jsxs(s.SelectLabel,{className:"flex items-center justify-between gap-2",children:[t,e.jsx(st,{className:s.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:o})]}),e.jsxs(e.Fragment,{children:[i&&e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),n&&n.map((x,j)=>e.jsx(s.SelectItem,{value:x.id,children:x.name},j))]}),(r||l)&&e.jsx(s.SelectItem,{value:h,children:h})]})})]})}function b(){return e.jsx(Rn,{icon:p(),items:n,value:h,onChange:c||(()=>{}),isLoading:r,isError:l,refetch:o,name:t,showNone:i})}return e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:m==="select"?g():b()})})}function On({column:t}){const[n,a]=A.useState(!1),r=s.useEditorStore(x=>x.selectedTableName),l=s.useEditorStore(x=>x.selectedSchemaName),o=s.useEditorStore(x=>x.selectedDatabaseName),c=s.useEditorStore(x=>x.selectedDatamodelId),i=s.useEditorStore(x=>x.sqlGen),{modelItems:d,connectionType:u}=s.useEditorAside(),m=s.useEditorStore(x=>x.actions.setSqlGen),h=s.useEditorStore(x=>x.actions.setCardSql),p=s.useEditorStore(x=>x.actions.setRunSql);function g(x,j){var k;const f=s.createSqlGenConfig(x,i,j),y=(k=d==null?void 0:d.find(C=>C.id===c))==null?void 0:k.name;m(f);const E=s.getSql(f,s.fmt(l||""),s.fmt(r),y||"",u,o||"");E&&(h(E),p(!0)),a(!1)}function b(){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 e.jsxs(s.HoverCard,{openDelay:0,open:n,onOpenChange:a,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:b()})]})}function Fn({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ve,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Le,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Be,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Ye,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(He,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ve,{className:"h-3 w-3"})})}function ds({column:t,className:n}){return e.jsxs("div",{className:s.cn("flex min-h-8 grow items-center gap-2 px-3 py-[6px] text-sm",n),children:[e.jsx(Fn,{dataType:t.data_type}),e.jsx("span",{children:t.column_name})]})}function Pn({id:t,children:n,type:a="column"}){const{attributes:r,listeners:l,setNodeRef:o,transform:c}=s.useDraggable({id:t,data:{type:a}}),i=c?{translate:s.CSS.Translate.toString(c),transform:s.CSS.Transform.toString(c)}:void 0;return e.jsx("div",{ref:o,style:i,...l,...r,children:n})}function Bn({onClick:t,column:n}){const a=s.useDndStore(m=>m.activeId),r=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.groupByColumns}),l=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.metricColumns}),o=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.filterColumns});function c(m){return i(m)||d(m)||u(m)}function i(m){return r==null?void 0:r.some(h=>h.name===m.column_name)}function d(m){return l==null?void 0:l.some(h=>h.name===m.column_name)}function u(m){return o==null?void 0:o.some(h=>h.name===m.column_name)}return e.jsxs("div",{onClick:()=>t(n),className:s.cn("group relative grow cursor-pointer overflow-x-hidden overflow-y-hidden border border-dashed border-background transition-colors hover:bg-muted/50",{"bg-muted":c(n)}),children:[a===n.column_name&&e.jsx(s.DragOverlay,{children:e.jsx(ds,{column:n,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),a===n.column_name&&e.jsx("div",{className:"absolute inset-0",children:a===n.column_name&&e.jsx(ds,{column:n})}),e.jsx(Pn,{id:n.column_name,type:"column",children:e.jsx(ds,{column:n})})]})}const us={id:"__placeholder__",role:"groupby",type:"string"},ms={id:"__placeholder__",role:"groupby",type:"string"},hs={id:"__placeholder__",role:"metric",type:"number"},xs={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},gt={id:"__placeholder__"},Ie="droppable-group-by",Ae="droppable-metrics",Me="droppable-pivot-by",as="sortable-group-by",ys="sortable-metrics",ns="sortable-pivot-by",Ns="droppable-filters",Cs="sortable-filters",ws="sortable-order-by";function zn(){const t=s.useDndStore(w=>w.insertIndex),n=s.useEditorStore(w=>{var L;return((L=w.card.queryConfig)==null?void 0:L.groupByColumns)||[]}),a=s.useEditorStore(w=>{var L;return((L=w.card.queryConfig)==null?void 0:L.metricColumns)||[]}),r=s.useEditorStore(w=>{var L;return((L=w.card.queryConfig)==null?void 0:L.filterColumns)||[]}),l=s.useEditorStore(w=>{var L;return((L=w.card.queryConfig)==null?void 0:L.orderBy)||[]}),o=s.useEditorStore(w=>{var L;return((L=w.card.queryConfig)==null?void 0:L.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:i,setPreviewGroupByColumns:d,setPreviewMetricColumns:u,setPreviewFilterColumns:m,setPreviewPivotColumns:h}=s.useDndActions(),{setGroupByColumns:p,setMetricColumns:g,setFilterColumns:b,setOrderByColumns:x,setPivotByColumns:j}=s.useEditorActions(),{columns:f}=s.useDataColumns(),{formattedTableName:y}=s.useEditorAside(),E=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),k=w=>{var R;const{active:L,over:O}=w;if(((R=L.data.current)==null?void 0:R.type)==="column"&&O){const M=O.id,B=f.find(X=>X.column_name===L.id);if(!B)return;const Y=s.isNumberDataType(B.data_type),_=s.isTextDataType(B.data_type),Q=s.isDateDataType(B.data_type);if(_||Q){if(n.some(q=>q.id===M)){const q=n.findIndex(G=>G.id===M);c(q);const W=n.filter(G=>G.id!==us.id);W.splice(q,0,us),d(W)}else if(O.id===Ie){c(n.length);const q=[...n,us];d(q),u(a),m(r)}}if(_||Q){if(o.some(q=>q.id===M)){const q=o.findIndex(G=>G.id===M);c(q);const W=o.filter(G=>G.id!==ms.id);W.splice(q,0,ms),h(W)}else if(O.id===Me){c(o.length);const q=[...o,ms];h(q),d(n),u(a),m(r)}}if(Y||_){if(a.some(q=>q.id===M)){console.log("isOverMetricSortable",M);const q=a.findIndex(G=>G.id===M);c(q);const W=a.filter(G=>G.id!==hs.id);W.splice(q,0,hs),u(W)}else if(O.id===Ae){c(a.length);const q=[...a,hs];u(q),m(r),d(n),h(o)}}if(D(B)){if(r.some(q=>q.id===M)){const q=r.findIndex(G=>G.id===M);c(q);const W=r.filter(G=>G.id!==xs.id);W.splice(q,0,xs),m(W)}else if(O.id===Ns){c(r.length);const q=[...r,xs];m(q),u(a),d(n),h(o)}}}else d(n),u(a),m(r),h(o)};function C(w){i(w.active.id),c(null),d(n),u(a),m(r),h(o)}function D(w){return!r.some(L=>L.name===w.column_name)}function v(w,L="SUM"){const{column_name:O,data_type:R}=w,M=[...a],B=t!==null?t:a.length,Y={...w,id:Ne(O),name:O,label:qe(O,L),type:R,role:"metric",aggregate:L};M.splice(B,0,Y),g(M)}function N(w){const L=s.isTextDataType(w.data_type);s.isDateDataType(w.data_type);const O=[...o],R=t!==null?t:o.length;let M;L?M={...w,id:Ne(w.column_name),name:w.column_name,type:w.data_type,role:"groupby"}:M={...w,id:Ne(w.column_name),name:w.column_name,type:w.data_type,role:"groupby",label:_e(w.column_name,"month"),granularity:"month"},O.splice(R,0,M),j(O)}function S(w){const L=s.isTextDataType(w.data_type);s.isDateDataType(w.data_type);const O=[...n],R=t!==null?t:n.length;let M;L?M={...w,id:Ne(w.column_name),name:w.column_name,type:w.data_type,role:"groupby"}:M={...w,id:Ne(w.column_name),name:w.column_name,type:w.data_type,role:"groupby",label:_e(w.column_name,"month"),granularity:"month"},O.splice(R,0,M),p(O)}function F(w){const L=[...r],O=t!==null?t:r.length,R={...w,id:Ne(w.column_name),name:w.column_name,type:w.data_type,sql:s.getDefaultFilterSql(w.data_type,y,s.fmt(w.column_name)),role:"filter"};L.splice(O,0,R),b(L)}function I(w){var M,B,Y,_,Q,X,q,W;const{active:L,over:O}=w,R=L.data.current;if((R==null?void 0:R.type)==="column"&&O){const G=f.find(ee=>ee.column_name===L.id);if(!G)return;const se=s.isNumberDataType(G.data_type),V=s.isTextDataType(G.data_type),U=s.isDateDataType(G.data_type);(V||U)&&(O.id===Ie||((M=O.data.current)==null?void 0:M.type)===as)&&S(G),(V||U)&&(O.id===Me||((B=O.data.current)==null?void 0:B.type)===ns)?N(G):(se||V)&&(O.id===Ae||((Y=O.data.current)==null?void 0:Y.type)===ys)?(se&&v(G),V&&v(G,"COUNT")):D(G)&&(O.id===Ns||((_=O.data.current)==null?void 0:_.type)===Cs)&&F(G)}if(O&&((Q=O.data.current)==null?void 0:Q.type)===as&&n.some(G=>G.id===L.id)){const G=n.findIndex(V=>V.id===L.id),se=n.findIndex(V=>V.id===O.id);if(G!==-1&&se!==-1&&G!==se){const V=[...n],[U]=V.splice(G,1);V.splice(se,0,U),p(V)}}if(O&&((X=O.data.current)==null?void 0:X.type)===ns&&o.some(G=>G.id===L.id)){const G=o.findIndex(V=>V.id===L.id),se=o.findIndex(V=>V.id===O.id);if(G!==-1&&se!==-1&&G!==se){const V=[...o],[U]=V.splice(G,1);V.splice(se,0,U),j(V)}}if(O&&((q=O.data.current)==null?void 0:q.type)===ys&&a.some(G=>G.id===L.id)){const G=a.findIndex(V=>V.id===L.id),se=a.findIndex(V=>V.id===O.id);if(G!==-1&&se!==-1&&G!==se){const V=[...a],[U]=V.splice(G,1);V.splice(se,0,U),g(V)}}if(O&&((W=O.data.current)==null?void 0:W.type)===Cs&&r.some(G=>G.id===L.id)){const G=r.findIndex(V=>V.id===L.id),se=r.findIndex(V=>V.id===O.id);if(G!==-1&&se!==-1&&G!==se){const V=[...r],[U]=V.splice(G,1);V.splice(se,0,U),b(V)}}P(w),i(null),c(null),d(n),u(a),m(r),h(o)}function P(w){const{active:L,over:O}=w,R=L.data.current;if((R==null?void 0:R.type)===ws&&O){const M=l.findIndex(Y=>Ge(Y.columnId)===L.id),B=l.findIndex(Y=>Ge(Y.columnId)===O.id);if(M!==-1&&B!==-1&&M!==B){const Y=[...l],[_]=Y.splice(M,1);Y.splice(B,0,_),x(Y)}}}function T(){i(null),c(null),d(n),u(a),m(r)}return{handleDragOver:k,handleDragEnd:I,handleDragStart:C,handleDragCancel:T,sensors:E}}function Ne(t){return`${t}-${s.v4()}`}function qe(t,n){const a=s.toTitleCase(t.replace(/_/g," "));switch(n){case"SUM":return`Sum of ${a}`;case"COUNT":return`Count of ${a}`;case"DISTINCT":return`Unique ${a}`;case"AVG":return`Average of ${a}`;case"MIN":return`Min of ${a}`;case"MAX":return`Max of ${a}`;default:return a}}function Ge(t){return`${ws}-${t}`}function _e(t,n){const a=s.toTitleCase(t.replace(/_/g," "));switch(n){case"day":return`Date of ${a}`;case"week":return`Week of ${a}`;case"month":return`Month of ${a}`;case"year":return`Year of ${a}`;default:return a}}function _n({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ve,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Le,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Be,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Ye,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(He,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ve,{className:"h-3 w-3"})})}function Vn({schemaName:t,tableName:n,columns:a,status:r}){const[l,o]=A.useState(""),[c,i]=A.useState("all"),d=s.useEditorStore(M=>M.sqlGen),u=s.useEditorStore(M=>M.isDevMode);s.useEditorStore(M=>M.selectedConnectionId);const m=s.useEditorStore(M=>{var B,Y;return(Y=(B=M.card)==null?void 0:B.queryConfig)==null?void 0:Y.metricColumns});s.useEditorStore(M=>{var B,Y;return(Y=(B=M.card)==null?void 0:B.queryConfig)==null?void 0:Y.groupByColumns});const h=s.useEditorStore(M=>M.selectedDatabaseName);s.useEditorStore(M=>M.selectedSchemaName),s.useEditorStore(M=>M.selectedTableName);const p=s.useEditorStore(M=>M.selectedDatamodelId);s.useDashboardStore(M=>M.dashboard.aiScopeTables);const{addToAIScope:g,removeFromAIScope:b}=s.useDashboardActions(),{addColumnToMetricColumns:x,addColumnToGroupBy:j,setCardSql:f,setRunSql:y,setSqlGen:E,setIsShowingVisual:k}=s.useEditorActions(),{connectionType:C,modelItems:D,selectedDatamodelName:v}=s.useEditorAside();function N(M){var B;if(u){const Y=s.createSqlGenConfig(M,d);E(Y);const _=(B=D==null?void 0:D.find(X=>X.id===p))==null?void 0:B.name,Q=s.getSql(Y,s.fmt(t),s.fmt(n),_||"",C,h||"");Q&&(f(Q),y(!0))}if(!u){if(s.isTextDataType(M.data_type))if(m&&m.length>0){const Y={...M,role:"groupby",id:Ne(M.column_name),name:M.column_name,type:M.data_type};j(Y)}else{const Y={...M,role:"metric",id:Ne(M.column_name),name:M.column_name,label:qe(M.column_name,"COUNT"),type:M.data_type,aggregate:"COUNT"};x(Y)}if(s.isDateDataType(M.data_type)){const Y={...M,role:"groupby",id:Ne(M.column_name),name:M.column_name,type:M.data_type,label:_e(M.column_name,"month"),granularity:"month"};j(Y)}if(s.isNumberDataType(M.data_type)){const Y={...M,role:"metric",id:Ne(M.column_name),name:M.column_name,label:qe(M.column_name,"SUM"),type:M.data_type,aggregate:"SUM"};x(Y)}}}function S(){const M=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:v,connectionType:C,databaseName:h||""});k(!1);const B=C==="MSSQL"?`SELECT top 10 * FROM ${M}`:`SELECT * FROM ${M} LIMIT 10`;f(B),y(!0)}function F(){const M=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:v,connectionType:C,databaseName:h||""});f(`SELECT COUNT(*) as count FROM ${M}`),y(!0)}const I=(a==null?void 0:a.filter(M=>M.column_name.toLowerCase().includes(l.toLowerCase())))||[],P=M=>s.isNumberDataType(M.data_type)?"number":"text",T=c==="all"?I:I.filter(M=>P(M)===c),w=I.filter(M=>P(M)==="text").length,L=I.filter(M=>P(M)==="number").length;function O(M){return u?e.jsxs("div",{className:"group flex cursor-pointer items-center justify-between border border-dashed border-background px-2 py-[6px] text-sm transition-colors hover:bg-muted/50",onClick:()=>N(M),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_n,{dataType:M.data_type}),e.jsx("span",{children:M.column_name})]}),e.jsx("div",{onClick:B=>B.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(M.data_type)&&e.jsx(On,{column:M})})]}):e.jsx(Bn,{onClick:N,column:M})}function R(){return e.jsxs("div",{className:"flex grow gap-2",children:[e.jsxs(s.Button,{disabled:r!=="Success",onClick:S,size:"sm",variant:"secondary",className:"grow",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(Da,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:F,size:"sm",variant:"secondary",className:"grow",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(tt,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-4",children:Array.from({length:3}).map((M,B)=>e.jsx(s.Skeleton,{className:"h-8 w-full"},B))}):e.jsxs("div",{className:"flex grow flex-col",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-3 px-4",children:[u&&e.jsx("div",{className:"flex items-center justify-center gap-2",children:R()}),a&&a.length>0&&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 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:l,onChange:M=>o(M.target.value)})]}),I.length>0&&e.jsx(s.Tabs,{defaultValue:"all",value:c,onValueChange:M=>i(M),children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-3",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:I.length})]}),e.jsxs(s.TabsTrigger,{value:"text",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:w})]}),e.jsxs(s.TabsTrigger,{value:"number",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:L})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-4 pt-3",children:[T.length===0&&l&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',l,'"']}),T.length===0&&!l&&c!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",c," fields found"]}),e.jsx("div",{className:"flex flex-col gap-1",children:T==null?void 0:T.map(M=>e.jsx("div",{children:O(M)},M.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function jt({ColumnsComponent:t,type:n}){var K;const[a,r]=A.useState(!1),l=s.useEditorStore(Z=>Z.card),o=s.useEditorStore(Z=>Z.selectedConnectionId),c=s.useDashboardStore(Z=>Z.showFilters),i=s.useEditorStore(Z=>Z.selectedDatamodelId),d=s.useEditorStore(Z=>Z.selectedDatabaseName),u=s.useEditorStore(Z=>Z.selectedSchemaName),m=s.useEditorStore(Z=>Z.selectedTableName),h=s.useEditorStore(Z=>Z.isDevMode),{setSelectedTableName:p,setIsDevMode:g,setCardSql:b}=s.useEditorActions(),{connectionItems:x,modelItems:j,schemaItems:f,databaseItems:y,tableItems:E,columns:k,isConnectionsLoading:C,isModelsLoading:D,isConnectionsError:v,isModelsError:N,isDatabasesLoadingOrFetching:S,isDatabaseError:F,isSchemaLoadingOrFetching:I,isSchemaError:P,isColumnsError:T,isColumnsLoadingOrFetching:w,isTableLoadingOrFetching:L,isTableError:O,connectionType:R,isNonDbConnection:M,refetchDatabases:B,refetchModels:Y,refetchSchemas:_,refetchTables:Q,refetchColumns:X,refetchConnections:q,handleConnectionChange:W,handleDatabaseChange:G,handleSchemaChange:se,handleDatamodelChange:V,handleTableChange:U,tableName:ee,schemaName:ae}=s.useEditorAside(),{data:ie,refetch:z}=s.useDashboardCardQuery(l);function te(){return t?t(ae,ee,k):e.jsx(Vn,{schemaName:ae,tableName:ee,columns:k,status:w?"Loading...":T?"Error":"Success"})}function oe(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function re(Z){Z===!0?ie&&(b(ie.userSql),setTimeout(()=>{z()},100)):b(""),g(Z)}function J(){if(!o||R==="S3"||R==="API")return null;if(!i||i==="none")return e.jsx(Fe,{refetch:B,showNone:!0,onChange:G,isError:F,isLoading:S,items:y,value:d||"",title:"Database",type:"combobox"})}function ce(){if(o&&!M&&(!d||d==="none")&&(!i||i==="none"))return e.jsxs("div",{className:"grid grid-cols-3",children:[e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Label,{children:"OR"})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})})]})}function de(){if(!o||R==="S3"||R==="API")return null;if(!d||d==="none")return e.jsx(Fe,{refetch:Y,showNone:!0,onChange:V,isError:N,isLoading:D,items:j,value:i||"",title:"Model",type:"combobox"})}function fe(){return!o||R==="S3"||R==="API"||!d||d==="none"?null:e.jsx(Fe,{refetch:_,onChange:se,isError:P,isLoading:I,items:f,value:u||"",title:"Schema",type:"combobox"})}function $(){function Z(){let le=!1;return R==="API"?(le=!1,le):((R==="S3"||o&&d&&d!=="none"&&u)&&(le=!0),le)}return Z()?e.jsx(Fe,{refetch:Q,onChange:U,isError:O,items:E,isLoading:L,value:m||"",title:"Table",type:"combobox"}):null}return e.jsxs("aside",{className:s.cn("flex h-full min-w-[310px] max-w-[310px] flex-col justify-between rounded-none",{"border-r-[1px]":!c}),children:[e.jsxs("section",{className:s.cn("px-4",{"px-4 pb-0 pt-4":a,"px-4 py-4":!a}),children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Direct Source"}),e.jsx(s.Button,{onClick:()=>r(!a),size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:a?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronUp,{className:"h-4 w-4"})})]}),!a&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(Fe,{refetch:q,items:x,title:"Connection",value:o||"",onChange:W,isLoading:C,isError:v,type:"combobox",connectionTooltip:((K=x==null?void 0:x.find(Z=>Z.id===o))==null?void 0:K.type)||""}),J(),ce(),de(),fe(),$()]})]}),te(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:n==="main"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Switch,{className:"data-[state=checked]:bg-muted-foreground/80",checked:h,onCheckedChange:re,id:"dev-mode"}),e.jsx(s.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(s.Button,{onClick:oe,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(ka,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function bt({error:t,errorSql:n,onSendFeedback:a,className:r,showFeedbackButton:l=!0}){const[o,c]=A.useState(!1);return e.jsx("div",{className:s.cn("rounded-lg border border-destructive/30 bg-destructive/5 p-4",r),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(s.CircleAlert,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-destructive"}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-destructive",children:"Query Error"}),e.jsxs("div",{className:"relative rounded-md bg-background/60 p-3",children:[e.jsx(s.CopyButton,{text:t,className:"absolute right-2 top-2 h-6 w-6 z-10"}),e.jsx("div",{className:"max-h-40 overflow-auto pr-10",children:e.jsx("p",{className:"font-mono text-xs text-foreground/80 break-all",children:t})})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n&&e.jsx(s.Collapsible,{open:o,onOpenChange:c,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"]})})})}),l&&a&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:a,children:[e.jsx(Ia,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]})]}),n&&e.jsx(s.Collapsible,{open:o,onOpenChange:c,children:e.jsx(s.CollapsibleContent,{className:"space-y-2",children:e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Error SQL Query"}),e.jsx(s.CopyButton,{text:n,className:"h-6 w-6"})]}),e.jsx("div",{className:"rounded-md bg-background/60 p-2 max-h-80 overflow-auto",children:e.jsx(s.CodeHighlighter,{code:n,language:"sql"})})]})})})]})]})})}function vt({sql:t,error:n,errorSql:a,onDebugWithAssistant:r}){const l=s.useEditorStore(u=>u.isDevMode),{setIsDevMode:o,setCardSql:c,setRunSql:i}=s.useEditorActions();function d(){o(!l),c(t),setTimeout(()=>{i(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-3",children:[e.jsxs(s.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[n&&e.jsx(bt,{error:n,errorSql:a,showFeedbackButton:!1}),!n&&t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"",children:e.jsx(s.CodeHighlighter,{code:t,language:"sql"})})})]}),!l&&t&&!n&&e.jsxs(s.Button,{onClick:d,variant:"secondary",size:"sm",children:[e.jsx(fa,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),n&&r&&e.jsxs(s.Button,{onClick:r,size:"sm",variant:"outline",children:[e.jsx(ya,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function yt({sql:t,error:n,errorSql:a,onDebugWithAssistant:r}){return e.jsxs(s.HoverCard,{openDelay:n?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:n?e.jsx(ua,{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(vt,{errorSql:a,sql:t,error:n,onDebugWithAssistant:r})})]})}function Un(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 Nt(t){const{theme:n}=s.useTheme(),a=s.useDashboardStore(x=>x.theme),r=s.useEditorStore(x=>x.frame),l=s.useEditorStore(x=>x.card),o=s.useEditorStore(x=>x.activeTabCardId),c=s.Le(),{refetch:i}=s.useDashboardCardQuery(l),{updateCardTab:d,setRunSql:u}=s.useEditorActions(),m=A.useRef(),h=A.useRef({}),p=r.cards.find(x=>x.id===o),g=A.useCallback(()=>{let x="";return t==="python"&&(x=(p==null?void 0:p.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(x=(p==null?void 0:p.sql)||""),x},[t,p]);A.useEffect(()=>{if(o&&l.id&&l.id!==o){if(m.current&&c){const x=m.current.getModel();x&&(h.current[l.id]=x);let j=h.current[o];if(!j){const f=g();j=c.editor.createModel(f,t),h.current[o]=j}m.current.setModel(j)}d(o,l),u(!0)}},[o,l,d,c,u,t,g]),A.useEffect(()=>{if(!c)return;const x=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",j=a==="system"?x:a;c.editor.defineTheme("default",{base:j==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":j==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[n,a,c]),A.useEffect(()=>{const x=m.current;x&&c&&l&&x.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return i(),!1})},[c,i,l]);function b(x,j){if(m.current=x,!h.current[l.id]){const f=x.getModel(),y=g();h.current[l.id]=f||(j==null?void 0:j.editor.createModel(y,t))||x.getModel()}x.setModel(h.current[l.id])}return{handleEditorDidMount:b}}function Gn(){const t=s.useEditorStore(c=>c.card.sql),n=s.useEditorStore(c=>c.sqlGen),{setCardSql:a,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=Nt("sql");function o(c){a(c),s.isObjectEmpty(n)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:o,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function Yn(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:n}=s.useEditorActions(),{handleEditorDidMount:a}=Nt("python");function r(l){n(l)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:a})}function $n({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 Ds(t){const[n,a]=A.useState(null),[r,l]=A.useState(null);return A.useEffect(()=>{if(!t||t.trim()===""){a(null),l(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const i=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(i,{method:"HEAD"})).ok)throw new Error(`Module not found at ${i}`)}catch{}const d=await import(i);if(typeof d.useChartStore!="function")throw new Error("useChartStore is not a function");a(()=>d.useChartStore),l(null)}catch(c){const i=c instanceof Error?c.message:"Unknown error";console.error("Failed to load remote chart store:",i),l(i),a(null)}})()},[t]),n}function qn(t){const n=t.toUpperCase().indexOf("WHERE"),a=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),l=t.toUpperCase().indexOf("ORDER BY");let o=t.length;if(l!==-1&&(o=l),r!==-1&&r<o&&(o=r),n!==-1){const c=t.substring(0,n),i=t.substring(n);return`${c} {{ filters | where }} AND ${i.substring(6)}`}else if(a!==-1){const c=t.substring(0,a),i=t.substring(a);return`${c} {{ filters | where }} ${i}`}else{const c=t.substring(0,o),i=t.substring(o);return console.log("beforeClause",c),console.log("afterClause",i),i?`${c} {{ filters | where }} ${i}`:`${c.replace(/;$/,"")} {{ filters | where }}`}}function Hn(t,n){if(t.length===0)return"";if(n){const a=t.find(r=>r.id===n);if(a){const r=a.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const o=r.split("__")[0],c=t.find(i=>i.tabTitle===o);return c?c.id:t[0].id}return n}}return t[0].id}async function Ys(t,n,a,r){if(!n||!a)throw new Error("Missing auth token or visual ID");const l=["resource-by-id","visual",a],o=r.getQueryData(l);if(o)return console.log("Using cached visual data for:",a),{data:o,fromCache:!0};console.log("Fetching visual data from network for:",a);const c=s.ue.loading("Loading visual...",{position:"top-center"});try{const i=await fetch(`${t}/management/v1/visuals/${a}`,{headers:{Authorization:`Bearer ${n}`}});if(!i.ok)throw new Error("Failed to load visual");const d=await i.json();return r.setQueryData(l,d),s.ue.dismiss(c),{data:d,fromCache:!1}}catch(i){throw s.ue.dismiss(c),i}}function Ct(t){if(typeof t=="string")return JSON.parse(t);if(typeof t=="object")return t;throw new Error("Invalid frame object format")}function Wn(t,n,a,r,l){var d,u;const o=(t==null?void 0:t.frameObject)??((d=t==null?void 0:t.visual)==null?void 0:d.frameObject);if(!o)return;const c=Ct(o);if(!(c!=null&&c.cards)||c.cards.length===0)return;n(c);const i=(u=c.cards)==null?void 0:u.find(m=>m.id===c.activeCardId);i&&a(i),r(!0),l(!0)}function Kn(){var p;const{setCardSql:t}=s.useEditorActions(),n=s.useEditorStore(g=>g.frame),a=s.useEditorStore(g=>g.card),r=Ds(((p=a.customCardPreferences)==null?void 0:p.url)||""),l=s.useEditorStore(g=>g.selectedSchemaName),o=s.useEditorStore(g=>g.selectedDatamodelId),c=s.useEditorStore(g=>g.selectedDatabaseName),i=s.useEditorStore(g=>g.selectedTableName),d=s.useEditorStore(g=>g.selectedConnectionId),u=s.useEditorStore(g=>g.isShowingVisual),m=a.sql;return{getUpdatedFrame:A.useCallback(()=>{var f;let g=m;m&&!m.includes("{{")&&(g=qn(m),t(g));const b=(f=r==null?void 0:r.getState())==null?void 0:f.settings,x={...a,dataSource:a.dataSource||{mode:"directSource"},lastSelectedSchema:l,lastSelectedDatamodelId:o,lastSelectedDatabase:c,lastSelectedTable:i,connectionId:d,sql:g,customCfg:u?a.customCfg:null,preferences:a.preferences,...b&&{customCardPreferences:{...a.customCardPreferences,settings:b}}},j=n.cards.map(y=>y.id===a.id?x:y);return{...n,cards:j,activeCardId:Hn(j,n.activeCardId)}},[a,n,u,l,o,c,i,d,t,r,m])}}function Ts(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient(),r=s.useSelectedVisual(),{selectVisual:l}=s.useManagementActions(),{setFrame:o,setCard:c}=s.useEditorActions(),{setIsDashboardEditing:i,setIsVisualEditing:d,setSelectedFrameId:u,addFrame:m,setIsDashboardPanelOpen:h}=s.useDashboardActions(),p=s.useDashboardStore(j=>j.selectedSheetId),g=s.useVisualById((r==null?void 0:r.id)||"",{enabled:!!(r!=null&&r.id)&&!!(t!=null&&t.accessToken)}),b=A.useCallback(async j=>{try{l(j);const{data:f,fromCache:y}=await Ys(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",j.id,a);return Wn(f,o,c,i,d),{success:!0,fromCache:y}}catch(f){return console.error("Error editing visual:",f),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,n.apiServiceUrl,a,l,o,c,i,d]),x=A.useCallback(async j=>{var f;try{if(l(j),!p)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:y,fromCache:E}=await Ys(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",j.id,a),k=(y==null?void 0:y.frameObject)??((f=y==null?void 0:y.visual)==null?void 0:f.frameObject);if(!k)return{success:!1,error:"Visual has no frame data"};const C=Ct(k);if(!(C!=null&&C.cards)||C.cards.length===0)return{success:!1,error:"Visual frame is malformed"};const D={...C,id:s.v4()};return m(p,D,"end"),i(!0),u(D.id),h(!1),{success:!0,fromCache:E}}catch(y){return console.error("Error adding visual:",y),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,n.apiServiceUrl,a,l,p,m,i,u,h]);return{visual:g.data,isLoading:g.isLoading,isError:g.isError,error:g.error,handleEditLibraryVisual:b,handleAddLibraryVisual:x,getUpdatedFrame:Kn().getUpdatedFrame,refetch:g.refetch}}function ks({variant:t="outline"}){var c;const{setCardSql:n}=s.useEditorActions();s.useEditorStore(i=>i.frame);const a=s.useEditorStore(i=>i.card);Ds(((c=a.customCardPreferences)==null?void 0:c.url)||""),s.useEditorStore(i=>i.selectedSchemaName),s.useEditorStore(i=>i.selectedDatamodelId),s.useEditorStore(i=>i.selectedDatabaseName),s.useEditorStore(i=>i.selectedTableName),s.useEditorStore(i=>i.selectedConnectionId),s.useEditorStore(i=>i.isShowingVisual),a.sql;const r=s.useEditorStore(i=>i.onSave),{getUpdatedFrame:l}=Ts();function o(){const i=l();r==null||r(i)}return e.jsxs(s.Button,{onClick:o,className:"h-8",size:"sm",variant:t,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function Qn(){const t=s.useQueryClient(),[n,a]=A.useState(!1),r=s.useDashboardStore(u=>u.actions.setIsDashboardPanelOpen),{setIsVisualEditing:l}=s.useDashboardActions(),{getUpdatedFrame:o}=Ts(),c=s.useSelectedVisual(),i=s.useUpdateVisualMutation(),d=()=>{const u=o();if(!(c!=null&&c.id)){s.ue.error("No visual selected");return}a(!0),i.mutate({visualId:c.id,data:{frameObject:u}},{onSuccess:()=>{a(!1),l(!1),r(!0),s.ue.success("Visual updated successfully"),t.invalidateQueries({queryKey:["resource-by-id","visual",c.id],exact:!0})},onError:()=>{a(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:d,className:"h-8",size:"sm",children:[n&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!n&&e.jsxs(e.Fragment,{children:[e.jsx(bs,{className:"mr-2 size-4 font-bold"}),"Save"]})]})}function Es(){const{setTempQueryData:t,setSqlGen:n}=s.useEditorActions(),a=s.useQueryClient(),r=s.useEditorStore(d=>d.tempQueryData),l=s.useEditorStore(d=>d.onClose),o=s.useEditorStore(d=>d.card),{queryKey:c}=s.useDashboardCardQuery(o);function i(){if(r){const{queryKey:d,queryData:u}=r;d&&u&&a.setQueryData(d,u)}n({}),l==null||l()}return e.jsxs(s.Button,{onClick:i,className:"h-8",size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function os(){const{setTempQueryData:t}=s.useEditorActions(),n=s.useQueryClient(),a=s.useEditorStore(j=>j.isDevMode),r=s.useEditorStore(j=>j.tempQueryData),l=s.useEditorStore(j=>j.card),{queryKey:o}=s.useDashboardCardQuery(l),{setCardSql:c,setSqlGen:i,setCardPython:d,setCardCustomCfg:u,setCardPreferences:m,updateDataSource:h,clearQueryConfig:p,setCardConfig:g,setCardType:b}=s.useEditorActions();function x(){const j=n.getQueryData(o);r!=null&&r.queryData||t({queryKey:o,queryData:j}),n.setQueryData(o,null),n.removeQueries({queryKey:o,exact:!0}),a&&h(s.EMPTY_DATA_SOURCE),c(""),i({}),p(),g(void 0),d(""),u(""),m({}),b("bar")}return e.jsxs(s.Button,{onClick:x,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(s.SquarePen,{className:"mr-2 size-4"}),"Clear"]})}function Jn(){const t=s.useQueryClient(),[n,a]=A.useState(!1),[r,l]=A.useState(!1);s.useEditorStore(_=>_.frame);const o=s.useEditorStore(_=>_.card);s.useEditorStore(_=>_.isShowingVisual),s.useEditorStore(_=>_.selectedConnectionId),s.useEditorStore(_=>_.tempQueryData),s.useEditorStore(_=>_.selectedDatabaseName),s.useEditorStore(_=>_.selectedDatamodelId),s.useEditorStore(_=>_.selectedSchemaName);const c=s.useEditorStore(_=>_.showAIDialog);s.useEditorStore(_=>_.selectedTableName);const i=s.useEditorStore(_=>{var Q;return(Q=_==null?void 0:_.card)==null?void 0:Q.sql}),d=s.useEditorStore(_=>{var Q;return(Q=_==null?void 0:_.card)==null?void 0:Q.python}),{sheetFilterValues:u}=s.useSheetFilterValues(),{setCardCustomCfg:m,setQueryResultColumns:h,setCardSql:p,setTempQueryData:g,setPythonStdOut:b,setCardPreferences:x,setCardType:j,setCardPython:f,runAssistant:y,setShowAIDialog:E}=s.useEditorActions();s.useEditorStore(_=>_.onSave),s.useEditorStore(_=>_.onClose),s.useEditorStore(_=>_.actions.setSqlGen);const k=s.useEditorStore(_=>_.runSql),C=s.useEditorStore(_=>_.actions.setRunSql),D=s.useEditorStore(_=>_.actions.setIsSqlRunning),{data:v,isLoading:N,isFetching:S,isSuccess:F,isError:I,error:P,errorSql:T,queryKey:w,refetch:L,errorMessage:O}=s.useDashboardCardQuery(o);A.useEffect(()=>{if(v&&(v.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),b((v==null?void 0:v.output)||""),v.records.length>0)){const{dimensionKeys:_}=s.getKeys(v.records);h(_)}},[v,h,b]),A.useEffect(()=>{(N||S)&&D(!0),(I||F)&&D(!1),I&&(h([]),b(""))},[N,S,v,b,I,F,D,h,P]),A.useEffect(()=>{k&&(t.getQueryData(w)||L(),C(!1))},[k,L,C,w,t]);async function R(){const _=`Can you help me debug this query?
|
|
317
317
|
|
|
318
318
|
Error:
|
|
319
319
|
|
|
@@ -321,7 +321,7 @@
|
|
|
321
321
|
|
|
322
322
|
Error SQL:
|
|
323
323
|
|
|
324
|
-
${
|
|
324
|
+
${T}
|
|
325
325
|
|
|
326
326
|
Query:
|
|
327
327
|
|
|
@@ -329,12 +329,12 @@
|
|
|
329
329
|
|
|
330
330
|
${d?`Python:
|
|
331
331
|
${d}`:""}
|
|
332
|
-
`;N(_)}function A(){return e.jsxs(e.Fragment,{children:[r&&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(Yn,{jsonString:JSON.stringify(u,null,2)})})}),u&&u.length>0&&e.jsx(s.Button,{variant:"ghost",onClick:()=>l(!r),className:"absolute bottom-0 right-6 size-7 p-1",children:r?e.jsx(s.X,{className:"size-3.5 text-muted-foreground"}):e.jsx(s.Filter,{className:"size-3.5 text-muted-foreground"})})]})}function B(){return e.jsxs(s.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(s.ResizablePanel,{id:"1",order:1,defaultSize:n?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(Un,{})}),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(Gn,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function Y(){return e.jsxs("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:E||y,onClick:()=>{L()},className:"h-8 shrink-0",size:"sm",children:[E||y?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(yt,{errorSql:D,sql:v==null?void 0:v.sql,error:O,onDebugWithAssistant:R}),e.jsx(os,{}),e.jsx(s.Toggle,{pressed:n,onPressedChange:_=>a(_),className:"h-8",size:"sm",variant:"outline",children:e.jsx(Vn,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:c,onClick:()=>{T(!0)},className:"h-9 w-full cursor-text px-3 text-left text-sm text-muted-foreground",children:c?"":"Type your question..."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Es,{}),e.jsx(ks,{})]})]})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsxs("div",{className:"relative flex grow justify-between overflow-y-scroll",children:[B(),A()]}),Y()]})}const Jn=[{value:"table",label:"Table",icon:s.Table2},{value:"aggregateTable",label:"Aggregate",icon:s.Layers},{value:"pivotTable",label:"Pivot",icon:rs}];function Xn({className:t}){const n=s.useEditorStore(d=>d.card),{setCardType:a,setCard:r,updateCardInFrame:l}=s.useEditorActions(),o=["table","aggregateTable","pivotTable"].includes(n.type),c=s.hasValidCardConfig(n.config);if(!o||!c)return null;const i=d=>{var m;const u=d;if(u==="aggregateTable"&&((m=n.config)!=null&&m.pivotByColumns)&&n.config.pivotByColumns.length>0){const h={...n,type:u,config:{...n.config,pivotByColumns:[]}};r(h),l(h)}else{a(u);const h={...n,type:u};l(h)}};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsx(s.RadioGroup,{value:n.type,onValueChange:i,className:"flex flex-row items-center justify-between gap-1 rounded-lg border p-1",children:Jn.map(d=>{const u=d.icon,m=n.type===d.value;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(s.RadioGroupItem,{value:d.value,id:`table-type-${d.value}`,className:"peer sr-only"}),e.jsxs(s.Label,{htmlFor:`table-type-${d.value}`,className:s.cn("flex cursor-pointer items-center gap-1.5 rounded-md px-3 py-1 text-sm font-medium transition-all",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 Zn({card:t}){var T,k,C,w,v,E,y,F,I,P,D;const[n,a]=M.useState(!1),[r,l]=M.useState([]),{authToken:o}=s.useSemaphorContext(),{theme:c}=s.useTheme(),i=s.getTokenParams(o==null?void 0:o.accessToken),d=s.useDashboardStore(S=>S.themeStyle),u={mode:c||"system",colors:((k=(T=d==null?void 0:d.chart)==null?void 0:T.dataset)==null?void 0:k.backgroundColor)||[]};(C=t.customCardPreferences)!=null&&C.inputData;const{getCard:m}=s.useCustomVisual(((w=t.customCardPreferences)==null?void 0:w.url)||""),h=((v=t.customCardPreferences)==null?void 0:v.visualType)||"single",p=s.useEditorStore(S=>S.frame),{setCustomCardPreferences:g}=s.useEditorActions(),{data:b}=s.useDashboardCardQuery(t),x=M.useCallback((S,L)=>{l(O=>({...O,[S]:L}))},[]);if(!((E=t.customCardPreferences)!=null&&E.componentName))return null;const j=m((y=t.customCardPreferences)==null?void 0:y.componentName);function f(S){a(S)}const N=Object.keys(((F=t.customCardPreferences)==null?void 0:F.dataInputCardIds)||{}).map(S=>{var R,A,B;const L=(A=(R=t.customCardPreferences)==null?void 0:R.dataInputCardIds)==null?void 0:A[S].cardId,O=(B=p==null?void 0:p.cards)==null?void 0:B.find(Y=>Y.id===L);return O||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(M.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[j&&h==="single"&&e.jsx(j,{editing:!0,params:i,theme:u,settings:(I=t.customCardPreferences)==null?void 0:I.settings,onDataChange:x,data:(b==null?void 0:b.records)||[]}),j&&h==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((P=t.customCardPreferences)==null?void 0:P.dataInputCardIds)||{}).map(S=>{var R,A,B;const L=(A=(R=t.customCardPreferences)==null?void 0:R.dataInputCardIds)==null?void 0:A[S].cardId,O=(B=p==null?void 0:p.cards)==null?void 0:B.find(Y=>Y.id===L);if(O)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:f,onDataChange:x,dataInputIndex:S,card:O},O.id+S)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(j,{theme:u,onDataChange:x,settings:N.map(S=>{var L;return(L=S==null?void 0:S.customCardPreferences)==null?void 0:L.settings}),data:N.map(S=>S!=null&&S.id?r==null?void 0:r[S.id]:[])})})]})]},(D=t.customCardPreferences)==null?void 0:D.componentName)})}function Ct({className:t,...n}){var E;const a=s.useEditorStore(y=>y.card),r=s.isExplorerCard(a),l=((E=a.customCardPreferences)==null?void 0:E.showCardHeader)??!0,o=s.useEditorStore(y=>y.frame),c=s.useDashboardStore(y=>y.dashboard.filters),i=s.useEditorStore(y=>y.actions.setRunSql),{updateFilter:d}=s.useDashboardActions(),u=c==null?void 0:c.find(y=>y.id===o.filterId),{data:m,isLoading:h,isFetching:p,errorMessage:g,pagination:b}=s.useDashboardCardQuery(a),{setCard:x,updateCardInFrame:j}=s.useEditorActions(),{data:f}=s.useTopoJson(a),N=M.useMemo(()=>{var y;return a.type!=="pivotTable"||!((y=m==null?void 0:m.records)!=null&&y.length)?null:{records:m.records,columnSubtotalMeta:m.columnSubtotalMeta,subtotalColumns:m.subtotalColumns||[],pivotSchema:m.pivotSchema||[],groupByColumns:m.groupByColumns}},[a.type,m==null?void 0:m.records,m==null?void 0:m.columnSubtotalMeta,m==null?void 0:m.subtotalColumns,m==null?void 0:m.pivotSchema,m==null?void 0:m.groupByColumns]),T=s.usePivotTableConfig(a,N),k=(y,F)=>{var P,D;const I={...a,paginationConfig:{page:y+1,pageSize:F}};x(I),j(I),a.sql&&((D=(P=a.preferences)==null?void 0:P.tablePrefs)!=null&&D.enableDevModePagination)&&i(!0)},C=M.useMemo(()=>!a.id||!(m!=null&&m.records)?null:s.createChartConfig({card:a,data:m==null?void 0:m.records,cardType:a.type,queryConfig:a.queryConfig,customCfg:a.customCfg,preferences:a.preferences,topoJson:f}),[a.id,m==null?void 0:m.records,a.type,a.queryConfig,a.customCfg,a.preferences,f]);function w(y){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Zn,{card:y})})}function v(){if(m!=null&&m.records&&(m==null?void 0:m.records.length)===0&&!h&&!p)return g?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.SearchX,{className:"size-8 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r?"Error fetching data. Please check your chart configuration":"Error fetching data. Please check your SQL or Python code."})]}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((h||p)&&a.type!=="table")return e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!a.id)return null;if(a.type==="custom")return w(a);if(!["table","pivotTable","aggregateTable","custom"].includes(a.type)&&C)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:h||p?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:C})});if(a.type==="table")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:a,data:(m==null?void 0:m.records)||[],paginationMetadata:b,onPaginationChange:k,isLoading:h||p})});if(a.type==="pivotTable"&&T)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.PivotTableTanstack,{card:a,data:T.data,options:T.options,onAggregationChange:y=>{const F=s.handleAggregationChange(y,a.config),I={...a,config:F};x(I),j(I)},onAggregationLabelChange:y=>{const F=s.handleAggregationLabelChange(y,a.config),I={...a,config:F};x(I),j(I)}})});if(a.type==="aggregateTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.AggregateTable,{card:a,data:(m==null?void 0:m.records)||[],groupByColumns:m==null?void 0:m.groupByColumns,pivotSchema:m==null?void 0:m.pivotSchema,paginationMetadata:b,onPaginationChange:k,onAggregationChange:y=>{const F=s.handleAggregationChange(y,a.config),I={...a,config:F};x(I),j(I)},isLoading:h||p})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...n,children:[l&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-5",children:[e.jsx(s.CardTitle,{className:"text-base",children:e.jsx(s.EditableText,{value:a.title,onSave:y=>x({...a,title:y}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(Xn,{})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:a.description||"",onSave:y=>x({...a,description:y}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),u&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:u.title||u.column,onSave:y=>d({...u,title:y}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:u})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:v()})]})}const ps=({language:t,value:n,onChange:a,readonly:r})=>e.jsx(s.Ft,{className:"h-full w-full overflow-hidden text-xs",theme:"default",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,lineHeight:16,renderLineHighlight:"none",readOnly:r},defaultLanguage:t,value:n,onChange:a}),er=()=>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."})]})]}),sr=({customCode:t,cardCustomCfgString:n,mergedConfig:a,onConfigChange:r,onCodeChange:l})=>e.jsxs(s.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(s.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(s.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(s.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(s.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(s.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ps,{language:"json",value:a,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ps,{readonly:!0,language:"json",value:n,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ps,{language:"javascript",value:t,onChange:l})})]}),tr=({error:t,hasCardCustomConfig:n,onReset:a,onApply:r,onClose:l})=>e.jsxs(s.DialogFooter,{className:"flex items-center",children:[e.jsx(s.Label,{className:"mr-2 text-red-500",children:t}),e.jsx(s.Button,{disabled:!n,onClick:a,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:l,variant:"outline",children:"Close"})]});function ar(){const[t,n]=M.useState(!1),[a,r]=M.useState(""),[l,o]=M.useState(""),[c,i]=M.useState(""),[d,u]=M.useState(""),m=s.useEditorStore(C=>C.card),h=s.useEditorStore(C=>C.card.customCfg),p=h?JSON.stringify(h,null,2):"",{data:g}=s.useDashboardCardQuery(m),{data:b}=s.useTopoJson(m),{setCardCustomCfg:x,setCustomVisualCode:j}=s.useEditorActions(),f=C=>{var w,v;return JSON.stringify({...C,data:{...C.data,datasets:(v=(w=C.data)==null?void 0:w.datasets)==null?void 0:v.map(E=>({...E,data:[]}))}},null,2)},N=()=>{var w,v;if(!((w=g==null?void 0:g.records)!=null&&w.length))return;const C=s.createChartConfig({card:m,data:g.records,cardType:m.type,queryConfig:m.queryConfig,preferences:m.preferences,topoJson:b});if(C){r(f(C)),i(((v=m.preferences)==null?void 0:v.customVisualCode)||"");const E=s.merge(C,h);o(f(E))}},T=()=>{try{if(c&&j(c),l){const C=JSON.parse(l),w=s.getObjectDiff(JSON.parse(a),C);x(w),u("")}}catch{u("Invalid JSON configuration")}},k=Object.keys(h||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:n,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:N,className:k?"":"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(er,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Ct,{className:"w-1/2 rounded shadow-none"})}),e.jsx(sr,{customCode:c,cardCustomCfgString:p,mergedConfig:l,onConfigChange:C=>o(C??""),onCodeChange:C=>i(C??"")})]}),e.jsx(tr,{error:d,hasCardCustomConfig:!!h,onReset:()=>{o(a),x(null)},onApply:T,onClose:()=>n(!1)})]})]})}function is(t){const[n,a]=M.useState(null);return n}function St(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),{data:a,isLoading:r,isFetching:l,isError:o}=s.useQuery({queryKey:["plugins",t==null?void 0:t.accessToken],queryFn:()=>s.getPlugins(n.apiServiceUrl,t==null?void 0:t.accessToken)});return{data:a,isLoading:r,isFetching:l,isError:o}}function wt(){const{data:t,isLoading:n,isError:a}=St(),r=s.useQueries({queries:((t==null?void 0:t.plugins)||[]).map(i=>({queryKey:["manifest",i.value],queryFn:()=>s.loadManifest(i.value),enabled:!!i.value,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:d=>Math.min(1e3*2**d,3e4)}))}),l=[];let o=n,c=a;return r.forEach((i,d)=>{var u;if(i.isLoading&&(o=!0),i.isError&&(c=!0),i.data&&((u=t==null?void 0:t.plugins)!=null&&u[d])){const m=t.plugins[d],h=i.data.visuals.map(p=>({name:p.name,pluginName:m.label,componentType:p.componentType,pluginType:m.type,icon:p.icon,chartType:p.chartType,url:m.value}));l.push(...h)}}),{data:l,isLoading:o,isError:c}}function nr({onChartTypeChange:t}){const{setCardCustomCfg:n,setCardPreferences:a,setCardType:r,setCustomCardPreferences:l}=s.useEditorActions(),{data:o,isLoading:c,isError:i}=wt(),d=M.useCallback((u,m)=>{n(null),a({}),r(u),m&&l({type:"component",visualType:"single",url:m.url,componentName:m.name,icon:m.icon}),t==null||t()},[n,a,r,l,t]);return c?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading custom visuals..."})})]}):i?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-destructive",children:"Failed to load custom visuals"})})]}):!o||o.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:o.map((u,m)=>e.jsx(rr,{text:u.name,onClick:()=>d("custom",u),icon:u.icon},`${u.url}-${u.name}-${m}`))})]})}const rr=({text:t,icon:n,onClick:a})=>{const r=is(),l=t.charAt(0).toUpperCase();return e.jsx(s.IconButton,{onClick:a,tooltip:t,children:r?e.jsx(r,{className:"h-4 w-4"}):l})};function Dt({onChartTypeChange:t,iconClassName:n}){const{setCardType:a,setCardPreferences:r,setIsDevMode:l}=s.useEditorStore(m=>m.actions),{setCardCustomCfg:o,setCustomCardPreferences:c,setQueryConfig:i}=s.useEditorActions();function d(m,h){o(null),r({}),a(m),["custom","text","map"].includes(m)&&(l(!0),i(void 0)),t==null||t()}const u=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(s.IconButton,{openDelay:u,tooltip:"Table",onClick:()=>d("table"),className:"h-10 p-4",children:e.jsx(s.Table2,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bar Chart",onClick:()=>d("bar"),className:"h-10 p-4",children:e.jsx(s.ChartColumnIncreasing,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Line Chart",onClick:()=>d("line"),className:"h-10 p-4",children:e.jsx(s.ChartLine,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Bar Chart",onClick:()=>d("stackedBar"),className:"h-10 p-4",children:e.jsx(s.ChartColumnStacked,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Line Chart",onClick:()=>d("stackedLine"),className:"h-10 p-4",children:e.jsx(s.MdStackedLineChart,{className:s.cn("size-5",n),strokeWidth:0})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Scatter Chart",onClick:()=>d("scatter"),className:"h-10 p-4",children:e.jsx(s.ChartScatter,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bubble Chart",onClick:()=>d("bubble"),className:"h-10 p-4",children:e.jsx(s.TbChartBubble,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Pie Chart",onClick:()=>d("pie"),className:"h-10 p-4",children:e.jsx(s.ChartPie,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Doughnut Chart",onClick:()=>d("doughnut"),className:"h-10 p-4",children:e.jsx(s.Donut,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Funnel Chart",onClick:()=>d("funnel"),className:"h-10 p-4",children:e.jsx(s.TbChartFunnel,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Radar Chart",onClick:()=>d("radar"),className:"h-10 p-4",children:e.jsx(s.Radar,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Polar Area Chart",onClick:()=>d("polarArea"),className:"h-10 p-4",children:e.jsx(s.PiChartPolar,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Tornado Chart",onClick:()=>d("tornado"),className:"h-10 p-4",children:e.jsx(s.Tornado,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{tooltip:"Range Chart",onClick:()=>d("range"),className:"h-10 p-4",children:e.jsx(s.ChartNoAxesGantt,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"KPI",onClick:()=>d("kpi"),className:"h-10 p-4",children:e.jsx(s.TiSortNumerically,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Text",onClick:()=>d("text"),className:"h-10 p-4",children:e.jsx(s.BookType,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{tooltip:"Map",onClick:()=>d("map"),className:"h-10 p-4",children:e.jsx(s.Map,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Custom",onClick:()=>d("custom"),className:"h-10 p-4",children:e.jsx($e,{className:s.cn("size-5",n)})})]})}function lr({chartType:t,className:n,customIcon:a,componentName:r}){const l=is();switch(t){case"bar":return e.jsx(s.ChartColumnIncreasing,{className:n});case"line":return e.jsx(s.ChartLine,{className:n});case"pie":return e.jsx(s.ChartPie,{className:n});case"radar":return e.jsx(s.Radar,{className:n});case"scatter":return e.jsx(s.ChartScatter,{className:n});case"bubble":return e.jsx(s.TbChartBubble,{className:n});case"doughnut":return e.jsx(s.Donut,{className:n});case"stackedBar":return e.jsx(s.ChartColumnStacked,{className:n});case"stackedLine":return e.jsx(s.MdStackedLineChart,{className:n});case"polarArea":return e.jsx(s.PiChartPolar,{className:n});case"funnel":return e.jsx(s.TbChartFunnel,{className:n});case"tornado":case"pyramid":return e.jsx(s.Tornado,{className:n});case"range":return e.jsx(s.ChartNoAxesGantt,{className:n});case"kpi":return e.jsx(s.TiSortNumerically,{className:n});case"text":return e.jsx(ve,{className:n});case"map":return e.jsx(s.Map,{className:n});case"custom":return a&&l?e.jsx(l,{className:n}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx($e,{className:n});default:return e.jsx(s.Table2,{className:n})}}function Tt({variant:t="ghost"}){var o,c;const[n,a]=M.useState(!1),r=s.useEditorStore(i=>i.card),l=r.type;return s.useDashboardStore(i=>i.isVisualEditing),e.jsxs(s.Popover,{open:n,onOpenChange:a,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(lr,{className:"size-4",chartType:l,customIcon:(o=r.customCardPreferences)==null?void 0:o.icon,componentName:(c=r.customCardPreferences)==null?void 0:c.componentName})})}),e.jsxs(s.PopoverContentCustom,{onOpenAutoFocus:i=>i.preventDefault(),className:"z-[51] w-72 p-1",children:[e.jsx(Dt,{onChartTypeChange:()=>a(!1)}),e.jsx(nr,{onChartTypeChange:()=>a(!1)})]})]})}function or({error:t,className:n="",textClassName:a="",copyButtonClassName:r=""}){const[l,o]=M.useState(!1),c=M.useRef(null),i=M.useRef(!1);function d(){t&&!i.current&&navigator.clipboard.writeText(t)}function u(p){(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),d())}function m(){const p=window.getSelection();if(p&&p.toString().trim()!==""){const g=p.toString();navigator.clipboard.writeText(g),o(!0),i.current=!0,setTimeout(()=>{o(!1),i.current=!1},1e3)}else i.current=!1}function h(){o(!1),i.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${n}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:c,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${a}`,onClick:d,onKeyDown:u,onMouseUp:m,onMouseDown:h,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),l&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function ir(){const t=s.useEditorStore(o=>{var c,i;return(i=(c=o.card.preferences)==null?void 0:c.chartOptions)==null?void 0:i.indexAxis}),n=s.useEditorStore(o=>o.card.type),{setChartOrientation:a}=s.useEditorStore(o=>o.actions);function r(){return e.jsx(s.IconButton,{onClick:()=>{a(t==="x"||t===void 0?"y":"x")},tooltip:"Chart Orientation",children:t==="x"||t===void 0?e.jsx(Vs,{className:"size-4"}):e.jsx(_s,{className:"size-4"})})}function l(){return e.jsx(s.IconButton,{onClick:()=>{a(t==="y"||t===void 0?"x":"y")},tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(Vs,{className:"size-4"}):e.jsx(_s,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?l():r()})}function cr({className:t}){var p,g,b,x,j,f,N,T;const n=s.useEditorStore(k=>k.card),{setCardPreferences:a,updateCardInFrame:r,setCard:l}=s.useEditorActions(),[o,c]=M.useState(!1),i=((g=(p=n.preferences)==null?void 0:p.displayOptions)==null?void 0:g.showFilterInfo)??!0,d=((x=(b=n.preferences)==null?void 0:b.displayOptions)==null?void 0:x.showCardToolbar)??!0,u=((f=(j=n.preferences)==null?void 0:j.displayOptions)==null?void 0:f.showChrome)??!0,m=((T=(N=n.preferences)==null?void 0:N.displayOptions)==null?void 0:T.allowScroll)??!0,h=(k,C)=>{var E;const w={...n.preferences,displayOptions:{...(E=n.preferences)==null?void 0:E.displayOptions,[k]:C}};a(w);const v={...n,preferences:w};l(v),r(v)};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsxs(s.DropdownMenu,{modal:!1,open:o,onOpenChange:c,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{className:"h-8 w-8 p-0",tooltip:"Display Options",children:e.jsx(at,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(s.DropdownMenuLabel,{children:"Display Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx("div",{className:"px-2 py-1.5",children:e.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"Changes apply to dashboard view only"})}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:i,onCheckedChange:k=>{h("showFilterInfo",k)},onSelect:k=>k.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:k=>{h("showCardToolbar",k)},onSelect:k=>k.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:k=>{h("showChrome",k)},onSelect:k=>k.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:k=>{h("allowScroll",k)},onSelect:k=>k.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 kt(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>c.isShowingVisual),a=s.useEditorStore(c=>{var i,d;return(d=(i=c.card)==null?void 0:i.preferences)==null?void 0:d.chartOptions}),r=s.getChartGridStyle(a),{setChartGrid:l}=s.useEditorActions();function o(){const c=["xy","none","x","y"],d=(c.indexOf(r)+1)%c.length;l(c[d])}return n?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(ir,{})}),!["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:o,children:[(r==="xy"||!r)&&e.jsx(rs,{className:"size-4"}),r==="x"&&e.jsx(ua,{className:"size-4"}),r==="y"&&e.jsx(Fa,{className:"size-4"}),r==="none"&&e.jsx(_a,{className:"size-4"})]}),e.jsx(cr,{})]}):null}function dr(){const t=s.useEditorStore(b=>b.frame),n=s.useEditorStore(b=>b.card),{setFrame:a,setActiveTabCardId:r,setCard:l,updateCardInFrame:o}=s.useEditorActions(),c=(b,x)=>{b.dataTransfer.setData("tabIndex",x.toString())},i=b=>{b.preventDefault()},d=(b,x)=>{const j=b.dataTransfer.getData("tabIndex");if(j===x.toString())return;const f=Array.from(t.cards),[N]=f.splice(parseInt(j),1);f.splice(x,0,N),a({...t,cards:f})};function u(b){const x=t.cards.filter(N=>N.id!==b),j=x[0],f={...t,cards:x,activeCardId:j.id};a(f),r(j.id),l(j)}function m(b,x){const j={...t,cards:[...t.cards,x],activeCardId:b.id};a(j),r(x.id)}function h(){const b={...n,id:s.v4(),title:`${n.title} Copy`,tabTitle:`${n.tabTitle||n.title} Copy`};m(n,b)}function p(b){const x={dataSource:b.dataSource,connectionId:b.connectionId,lastSelectedDatabase:b.lastSelectedDatabase,lastSelectedSchema:b.lastSelectedSchema,lastSelectedTable:b.lastSelectedTable,lastSelectedDatamodelId:b.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};m(b,x)}function g(b,x){return b.cards.length===1&&(x.displayTab===!0||x.displayTab===void 0)||b.activeCardId!==x.id&&(x.displayTab===!0||x.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const j=x.displayTab===void 0?!1:!x.displayTab;l({...x,displayTab:j}),o({...x,displayTab:j})},children:x.displayTab===!0||x.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(xa,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(s.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[t.cards.map((b,x)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:j=>c(j,x),onDragOver:i,onDrop:j=>d(j,x),className:"",value:b.id,children:[g(t,b),e.jsx(s.Editable,{enabled:t.activeCardId===b.id,text:b.tabTitle||b.title,onSave:j=>{l({...n,tabTitle:j}),o({...n,tabTitle:j})},children:b.tabTitle||b.title},b.id),t.activeCardId===b.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>u(b.id)})]},b.id)),e.jsx(s.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>p(n),children:e.jsx(s.Plus,{className:"h-4 w-4"})}),e.jsx(s.Button,{className:"invisible ml-1 h-8 px-2 hover:bg-muted-foreground/50 group-hover:visible",variant:"outline",onClick:h,children:e.jsx(s.CopyPlus,{className:"h-4 w-4"})})]})})}function Et(){const t=s.useEditorStore(x=>x.frame),n=s.useEditorStore(x=>x.card),a=s.useEditorStore(x=>x.isSqlRunning),r=s.useEditorStore(x=>x.isDevMode),{setFrame:l,setActiveTabCardId:o,setCard:c,setIsDevMode:i,setRunSql:d}=s.useEditorActions(),{data:u,isLoading:m,isFetching:h}=s.useDashboardCardQuery(n);function p(x){const j=t.cards.find(f=>f.id===x);if(j!=null&&j.sql){r||i(!0),o(x);return}if(j!=null&&j.queryConfig){r&&i(!1),g(x),o(x);return}r||g(x),o(x)}function g(x){const j={...t,cards:t.cards.map(N=>N.id===n.id?n:N),activeCardId:x};l(j);const f=j.cards.find(N=>N.id===x);f.sql&&d(!0),c(f)}function b(){return n.type==="kpi"?m||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border border-border",children:e.jsx(s.KPICard,{card:n,data:u==null?void 0:u.records,isPending:m||h})})}):n.type==="text"?m||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:a,card:n,data:u==null?void 0:u.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Ct,{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(x=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:x.id,children:b()},x.id)),e.jsx(dr,{})]})}function Je({children:t}){var k,C;s.useEditorStore(w=>w.frame);const n=s.useEditorStore(w=>w.card),a=s.useEditorStore(w=>w.isDevMode),r=s.useEditorStore(w=>w.isShowingVisual),l=s.useDashboardStore(w=>w.isVisualEditing),o=s.useEditorStore(w=>w.pythonStdOut);s.useEditorStore(w=>w.actions.setRunSql);const{setFrame:c,setCard:i,setActiveTabCardId:d,runAssistant:u,setIsDevMode:m,setCardPreferences:h}=s.useEditorActions(),{data:p,isLoading:g,isFetching:b,errorMessage:x,refetch:j}=s.useDashboardCardQuery(n);function f(){const w=JSON.stringify(p==null?void 0:p.records,null,2),v=new Blob([w],{type:"application/json"}),E=URL.createObjectURL(v),y=document.createElement("a");y.href=E,y.download=`${n.title}.json`,y.click()}function N(){const v=[Object.keys(p==null?void 0:p.records.reduce((I,P)=>({...I,...P}),{})).join(","),...((p==null?void 0:p.records)||[]).map(I=>Object.values(I).join(","))].join(`
|
|
333
|
-
`),E=new Blob([v],{type:"text/csv"}),y=URL.createObjectURL(E),F=document.createElement("a");F.href=y,F.download=`${n.title}.csv`,F.click()}function T(){const w=`Can you get the documentation for ${n.type} chart?`;u(w)}return n?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[r&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(Tt,{}),l&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:T,children:e.jsx(la,{className:"size-4"})}),!["table","custom"].includes(n.type)&&l&&e.jsx(ar,{})]}),!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:N,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:f,children:e.jsx(fa,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(p==null?void 0:p.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(kt,{})]}),n.type==="table"&&n.sql&&!s.hasValidCardConfig(n.config)&&e.jsxs("div",{className:"mr-2 flex items-center gap-3",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((C=(k=n.preferences)==null?void 0:k.tablePrefs)==null?void 0:C.enableDevModePagination)??!1,onCheckedChange:w=>{var v;h({...n.preferences,tablePrefs:{...(v=n.preferences)==null?void 0:v.tablePrefs,enableDevModePagination:w}}),j()}}),e.jsx(s.Label,{htmlFor:"pagination",children:"Paginate Results"})]}),a&&e.jsx(mr,{})]}),r?e.jsx(Et,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[o&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:o&&e.jsx(ur,{})}),e.jsx(s.ResizableHandle,{})]}),e.jsxs(s.ResizablePanel,{id:"2",order:2,minSize:10,className:s.cn("relative flex h-full min-h-0 w-full flex-1 basis-0",{"px-6":o}),children:[(p==null?void 0:p.records)&&(p==null?void 0:p.records.length)>0&&e.jsx(s.TableVisual,{card:n,data:(p==null?void 0:p.records)||[]}),x&&e.jsx(or,{error:x})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function ur(){const t=s.useEditorStore(a=>a.pythonStdOut);if(!t)return null;const n=t.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(s.ScrollArea,{className:"overflow-y-auto pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:n}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function mr(){const t=s.useEditorStore(a=>a.isShowingVisual),n=s.useEditorStore(a=>a.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(s.SmallSwitch,{checked:t,onCheckedChange:()=>n(!t),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function Ce({defaultValue:t,label:n,options:a,value:r,onValueChange:l,className:o,icon:c,showPlaceholderLabel:i=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:l,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",o),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),i&&e.jsx(s.SelectValue,{placeholder:n})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:n}),a.map(d=>e.jsx(s.SelectItem,{value:d.value,children:d.label},d.value))]})})]})}function hr(){var x,j;const t=s.useEditorStore(f=>f.card.customCardPreferences),{data:n}=St(),a=(n==null?void 0:n.plugins)||[],r=s.useEditorStore(f=>f.card),l=s.useEditorStore(f=>f.frame),o=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:c}=s.useEditorActions(),{components:i,manifest:d}=s.useCustomVisual((t==null?void 0:t.url)||""),u=(x=d==null?void 0:d.visuals)==null?void 0:x.find(f=>f.name===(t==null?void 0:t.componentName));function m(f,N){if(!t)return;const k={...(t==null?void 0:t.dataInputCardIds)||{},[f]:{cardId:N,hookRef:null}};c({...t,dataInputCardIds:k})}function h(f){var T,k;const N=(T=l==null?void 0:l.cards)==null?void 0:T.filter(C=>{var w;return((w=C==null?void 0:C.customCardPreferences)==null?void 0:w.visualType)!=="multiple"}).map(C=>({value:C.id,label:C.tabTitle||C.title}));return e.jsx("div",{className:"space-y-2",children:(k=f==null?void 0:f.dataInputs)==null?void 0:k.map((C,w)=>{var v,E;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:C}),e.jsx(Ce,{className:"col-span-6 h-8 w-full justify-between",label:"",options:N||[],value:((E=(v=t==null?void 0:t.dataInputCardIds)==null?void 0:v[w])==null?void 0:E.cardId)||"",onValueChange:y=>m(w,y)})]},w+Math.random())})})}function p(f,N,T=[],k=""){var C,w;return t?f==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((C=t==null?void 0:t.settings)==null?void 0:C[N])||k,onChange:v=>{c({...t,settings:{...t==null?void 0:t.settings,[N]:v.target.value}})}},N):f==="select"?e.jsx(Ce,{className:"h-8 w-full",label:"",options:T,value:((w=t==null?void 0:t.settings)==null?void 0:w[N])||k,onValueChange:v=>{c({...t,settings:{...t==null?void 0:t.settings,[N]:v}})}}):null:null}function g(f){const N=Object.entries((f==null?void 0:f.settings)||{});return e.jsx("div",{className:"space-y-3",children:N.map(([T,k])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:k.title}),p(k.ui,T,k.options,k.defaultValue)]},T))})}function b(f){t&&c({...t,visualType:f,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(Ce,{icon:e.jsx(ra,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:a,value:(t==null?void 0:t.url)||"",onValueChange:f=>c({...t||{url:"",componentName:""},url:f})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:o,onValueChange:b,children:e.jsxs(s.TabsList,{className:"h-9 w-full",children:[e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&e.jsx(e.Fragment,{children:i&&e.jsx(Ce,{icon:e.jsx(ma,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(i==null?void 0:i.filter(f=>f.type===o).map(f=>({value:f.name,label:f.name})))||[],value:t.componentName,onValueChange:f=>{console.log("changing value",f),c({...t,componentName:f})}})})]})})]}),((j=r==null?void 0:r.customCardPreferences)==null?void 0:j.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{children:[u&&u.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:h(u)})]}),u&&u.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:g(u)})})]})]})]})}function Oe(){const[t,n]=M.useState([]),a=s.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:l}=s.useEditorStore(u=>u.actions),o=s.useEditorStore(u=>u.queryResultColumns);s.useEditorStore(u=>{var m;return(m=u.card.preferences)==null?void 0:m.filterOnClickColumnIndex}),M.useEffect(()=>{o&&n(new Array(o.length).fill(!1))},[o]);function c(u,m){var h,p;m?a!=null&&a.onClickFilter&&((h=a==null?void 0:a.onClickFilter)==null?void 0:h.length)>0?l({...a,onClickFilter:[...a.onClickFilter,{columnIndex:u,expression:""}]}):l({...a,onClickFilter:[{columnIndex:u,expression:""}]}):(l({...a,onClickFilter:(p=a==null?void 0:a.onClickFilter)==null?void 0:p.filter(g=>g.columnIndex!==u)}),n(g=>{const b=[...g];return b[u]=!1,b}))}function i(u,m){var p;const h=(p=a==null?void 0:a.onClickFilter)==null?void 0:p.map(g=>g.columnIndex===u?{...g,expression:m.target.value}:g);l({...a,onClickFilter:h})}function d(u){var m,h,p,g;if(t!=null&&t[u]||(h=(m=a==null?void 0:a.onClickFilter)==null?void 0:m.find(b=>b.columnIndex===u))!=null&&h.expression)return e.jsx(s.Input,{value:(g=(p=a==null?void 0:a.onClickFilter)==null?void 0:p.find(b=>b.columnIndex===u))==null?void 0:g.expression,onChange:b=>i(u,b),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsx("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:o==null?void 0:o.map((u,m)=>{var h,p;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((h=a==null?void 0:a.onClickFilter)!=null&&h.find(g=>g.columnIndex===m)),onCheckedChange:g=>c(m,g)}),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:((p=a==null?void 0:a.onClickFilter)==null?void 0:p.find(g=>g.columnIndex===m))&&e.jsx(s.Pencil,{onClick:()=>{n(g=>{const b=[...g];return b[m]=!g[m],b})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(m)]})},u)})})}function xr({idx:t}){var i;const n=s.useEditorStore(d=>{var u;return(u=d.card)==null?void 0:u.preferences}),a=s.useEditorStore(d=>{var u;return(u=d.card.preferences)==null?void 0:u.datasetOptions}),r=s.useEditorStore(d=>d.actions.setCardPreferences),l=(i=n==null?void 0:n.chartOptions)==null?void 0:i.indexAxis,o=a==null?void 0:a.find(d=>d.idx===t);function c(d,u){(d==="end"||d==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const m={display:d!=="none",align:d,anchor:d,clamp:!0};if(!o)r({...n,datasetOptions:[...a||[],{idx:u,datalabels:m}]});else{const h={...o};h.datalabels=m;const p=a==null?void 0:a.map(g=>g.idx===u?h:g);r({...n,datasetOptions:p})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(nt,{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(Na,{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(Sa,{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(Ca,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function pr(){const t=s.useEditorStore(o=>o.card),{data:n}=s.useDashboardCardQuery(t),{keys:a}=s.getKeys((n==null?void 0:n.records)||[]),r=a.slice(1).filter(o=>!s.METADATA_KEYS.includes(o));let l=r;if(["stackedBar","stackedLine"].includes(t.type)){const o=s.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:c}=s.getKeys(o);l=c.slice(1)}return{transformedMetricKeys:l,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}function cs({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",n),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function It(){const t=s.useEditorStore(d=>d.card),n=s.useEditorStore(d=>{var u,m,h;return(h=(m=(u=d==null?void 0:d.card)==null?void 0:u.preferences)==null?void 0:m.chartOptions)==null?void 0:h.indexAxis}),{data:a}=s.useDashboardCardQuery(t),r=n==="y"?"Metric":"Dimension",l=n==="y"?"Dimension":"Metric",{dimensionKeys:o,transformedMetricKeys:c,keys:i}=pr();return i.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:o.map(d=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:d,children:At(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(Mt,{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 At(t,n=30){return t.length>n?t.slice(0,n)+"...":t}function Mt({col:t,idx:n,className:a,iconClassName:r,children:l}){const o=s.useEditorStore(m=>{var h;return(h=m.card)==null?void 0:h.preferences}),c=s.useEditorStore(m=>{var h,p;return(p=(h=m.card)==null?void 0:h.preferences)==null?void 0:p.datasetOptions}),i=c==null?void 0:c.find(m=>m.idx===n),{setCardPreferences:d}=s.useEditorStore(m=>m.actions);function u(m){if(!i)d({...o,datasetOptions:[...c||[],{idx:n,type:m==="area"?"line":m,fill:m==="area"?"origin":""}]});else{const h={...i};h.type=m==="area"?"line":m,h.fill=m==="area"?"origin":"";const p=c==null?void 0:c.map(g=>g.idx===n?h:g);d({...o,datasetOptions:p})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[l||e.jsx(cs,{className:"max-w-[100px]",title:t,children:At(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(xr,{idx:n})]})]})}function Is(){const t=s.useEditorStore(g=>g.selectedConnectionId),n=s.useEditorStore(g=>g.selectedDatamodelId),a=s.useEditorStore(g=>g.selectedDatabaseName),r=s.useEditorStore(g=>g.selectedSchemaName),l=s.useEditorStore(g=>g.selectedTableName),o=s.useDashboardStore(g=>g.dashboard.filters)||[],c=s.useDashboardStore(g=>g.actions.addFilter),i=s.useDashboardStore(g=>g.actions.removeFilter),{removeFilterValues:d}=s.useDashboardActions(),{modelItems:u,tableName:m,connectionType:h}=s.useEditorAside();function p(g,b="dashboard",x){var E;const j=s.fmt(g.column_name),f=s.fmt(a||""),N=s.fmt(r||""),T=s.fmt(m);let k=s.getQualifiedTableName({schemaName:N,tableName:T,connectionType:h,databaseName:f}),C=`${k}.${j}`;const w=(E=u==null?void 0:u.find(y=>y.id===n))==null?void 0:E.name;n&&n!=="none"&&(C=`${s.DATAMODEL_NAMESPCACE}.${w}.${j}`,k=`${s.DATAMODEL_NAMESPCACE}.${w}`),x!=null&&x.qualifiedFieldName&&(C=x.qualifiedFieldName),x!=null&&x.entityName&&(k=x.entityName);const v=o==null?void 0:o.find(y=>y.column===C&&y.table===T&&(y.database===f||y.database===a));if(v)d(v.id),i(v.id);else{const y=s.v4();return m==="api"&&t?(c({location:b,id:y,column:C,title:g.column_name,dataType:g.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(g.data_type,k,j)}),y):(c({id:y,location:b,column:C,title:g.column_name,dataType:g.data_type,table:l||"",database:a||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(g.data_type,k,j)}),y)}}return{assignFilter:p}}function Ve(){const t=s.useDashboardStore(i=>i.dashboard.filters),n=s.useEditorStore(i=>i.frame),{setFrame:a}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=Is();function o(i){const d=l(i,"frame");a({...n,filterId:d})}const c=t==null?void 0:t.find(i=>i.id===n.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(fr,{onSelect:o,columns:r}),c&&e.jsx(s.FilterHeader,{filter:c})]})}function fr({columns:t,onSelect:n}){var c;const[a,r]=Ee.useState(!1),[l,o]=Ee.useState("");return e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between font-normal",children:[l?(c=t.find(i=>i.column_name===l))==null?void 0:c.column_name:"Select Column...",e.jsx(s.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No framework found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(i=>e.jsxs(s.CommandItem,{value:i.column_name,onSelect:d=>{const u=d===l?"":d;o(u),r(!1),u&&n(i)},children:[i.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",l===i.column_name?"opacity-100":"opacity-0")})]},i.column_name))})]})]})})]})}function gr({cardType:t}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, y-axis-1, y-axis-2,... FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"y-axis1 - number"}),e.jsx("li",{children:"y-axis2 - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:n=>n.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(It,{})})]}),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(Oe,{}),e.jsx(Ve,{})]})]})]})})}function jr({cardType:t}){function n(a){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:a==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),a==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:o=>o.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsx(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:n(t)})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Oe,{}),e.jsx(Ve,{})]})]})]})})}function Lt(){const t=s.useEditorStore(i=>i.card.type),n=s.useEditorStore(i=>i.isDevMode),a=s.useEditorStore(i=>i.card.preferences),{setCardPreferences:r}=s.useEditorStore(i=>i.actions);function l(i){var m;const d={datalabels:{display:i!=="none",align:i,anchor:i,clamp:!0}},u={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(m=a==null?void 0:a.chartOptions)==null?void 0:m.plugins,...d}}};r(u)}function o(){var i,d,u;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((u=(d=(i=a==null?void 0:a.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Data Labels"}),e.jsx(s.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"start",children:"Start"}),e.jsx(s.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"end",children:"End"})]})})]})]})}function c(){var i,d,u;return e.jsx("div",{children:e.jsxs(s.Select,{value:((u=(d=(i=a==null?void 0:a.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(s.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:n?o():c()})}const br={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},vr={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function yr(){const t=s.useEditorStore(n=>n.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:Nr(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Lt,{}),e.jsx(Oe,{}),e.jsx(Ve,{})]})]})}function Nr(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(br,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(vr,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 Cr({colorRanges:t,setColorRanges:n}){const a={start:-1/0,end:100,color:""};function r(c,i,d){const u=[...t];u[c]={...u[c],[i]:d},n(u)}function l(c){const i=[...t];i.splice(c,1),n(i)}function o(){n([...t,a])}return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:"Color Range"}),e.jsx(s.Button,{onClick:o,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((c,i)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input,{onChange:d=>r(i,"start",d.target.value),value:c.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input,{value:c.end,onChange:d=>r(i,"end",d.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input,{onChange:d=>r(i,"color",d.target.value),value:c.color,className:s.cn(`h-7 min-w-14 p-0 ${s.removeRing}`),type:"color",list:"presetColors"}),e.jsxs("datalist",{id:"presetColors",children:[e.jsx("option",{children:s.colors.green[600]}),e.jsx("option",{children:s.colors.red[500]}),e.jsx("option",{children:s.colors.yellow[400]}),e.jsx("option",{children:s.colors.orange[500]})]}),e.jsx(s.Button,{onClick:()=>l(i),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},i))]})}function Sr(){var m,h,p,g,b;const t=s.useEditorStore(x=>x.card.preferences),n=s.useEditorStore(x=>x.actions.setCardPreferences),a=s.useEditorStore(x=>x.card),r=s.isExplorerCard(a),l=s.useEditorStore(x=>x.actions.setNumberFormat);s.useEditorStore(x=>{var j,f;return(f=(j=x.card.preferences)==null?void 0:j.formatNumber)==null?void 0:f.decimalPlaces});const o=s.useEditorStore(x=>{var j,f;return(f=(j=x.card.preferences)==null?void 0:j.formatNumber)==null?void 0:f.locale}),c=s.useEditorStore(x=>{var j,f;return(f=(j=x.card.preferences)==null?void 0:j.formatNumber)==null?void 0:f.currency});s.useEditorStore(x=>x.actions.setFilterOnClickField);const i=s.useEditorStore(x=>{var j,f;return(f=(j=x.card.preferences)==null?void 0:j.formatNumber)==null?void 0:f.colorRanges})||[],d=s.useEditorStore(x=>x.actions.setColorRanges),u=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(x=>x.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:x=>{n({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:x}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((h=t==null?void 0:t.formatNumber)==null?void 0:h.enabled)===!0||r)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Locale"}),e.jsxs(s.Select,{value:o||"none",onValueChange:x=>{var j,f,N;return l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,((f=t==null?void 0:t.formatNumber)==null?void 0:f.currency)||"",x,((N=t==null?void 0:t.formatNumber)==null?void 0:N.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(x=>e.jsx(s.SelectItem,{value:x.locale,children:x.locale},x.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:x=>{var j,f,N;console.log("currency",x),l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,x==="none"?"":x,((f=t==null?void 0:t.formatNumber)==null?void 0:f.locale)||"",((N=t==null?void 0:t.formatNumber)==null?void 0:N.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(x=>e.jsx(s.SelectItem,{value:x,children:x},x))]})})]})]})]}),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:((g=(p=t==null?void 0:t.formatNumber)==null?void 0:p.decimalPlaces)==null?void 0:g.toString())||"0",onValueChange:x=>{var j,f,N;return l(Number(x),((j=t==null?void 0:t.formatNumber)==null?void 0:j.currency)||"",((f=t==null?void 0:t.formatNumber)==null?void 0:f.locale)||"",((N=t==null?void 0:t.formatNumber)==null?void 0:N.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(x=>e.jsx(s.SelectItem,{value:x,children:x},x))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Suffix"}),e.jsx(s.Input,{value:((b=t==null?void 0:t.formatNumber)==null?void 0:b.suffix)||"",className:"h-8 font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"K, M, B, %",onChange:x=>{var j,f,N;return l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,((f=t==null?void 0:t.formatNumber)==null?void 0:f.currency)||"",((N=t==null?void 0:t.formatNumber)==null?void 0:N.locale)||"",x.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(Cr,{colorRanges:i,setColorRanges:d})]})]})}function wr(){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(Sr,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function fs({children:t,summary:n,open:a,className:r}){return e.jsxs("details",{open:a,className:s.cn("space-y-4 [&_summary>svg]:open:-rotate-180",r),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(s.Label,{children:n}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const Dr=[{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"}],Tr=["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"],kr=Tr.map(t=>({label:t,value:t}));function Er(){var d,u,m,h,p,g,b,x,j,f,N,T,k,C,w,v,E,y;const t=s.useEditorStore(F=>F.card),n=(u=(d=t==null?void 0:t.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:u.topoJsonUrl,[a,r]=M.useState(((h=(m=t==null?void 0:t.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:o}=s.useTopoJson(t),c=Object.keys((o==null?void 0:o.objects)||{}).map(F=>({label:F,value:F}))||[],i=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"p-6",children:[e.jsx(fs,{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(fs,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(Ce,{className:"h-9",options:i,onValueChange:F=>{console.log("value",F),l({...t.preferences,mapVisualOptions:{topoJsonUrl:F}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(s.Input,{onChange:F=>{r(F.target.value)},onBlur:()=>{var F;console.log("onBlur",a),l({...t.preferences,mapVisualOptions:{...(F=t.preferences)==null?void 0:F.mapVisualOptions,customTopoJsonUrl:a}})},value:a,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),o&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(Ce,{className:"h-9",options:c,value:((g=(p=t.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:g.objectKey)||"",label:"Map Object",onValueChange:F=>{var I;l({...t.preferences,mapVisualOptions:{...(I=t.preferences)==null?void 0:I.mapVisualOptions,objectKey:F}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(Ce,{className:"h-9",options:Dr,value:((x=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:x.projection)||"",label:"Projection",onValueChange:F=>{var I;l({...t.preferences,mapVisualOptions:{...(I=t.preferences)==null?void 0:I.mapVisualOptions,projection:F}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(Ce,{className:"h-9",options:kr,value:((f=(j=t.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:f.colorScale)||"",label:"Select Color Scale",onValueChange:F=>{var I;l({...t.preferences,mapVisualOptions:{...(I=t.preferences)==null?void 0:I.mapVisualOptions,colorScale:F}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(fs,{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:((T=(N=t.preferences)==null?void 0:N.mapVisualOptions)==null?void 0:T.projectionScale)||1,onChange:F=>{var I;l({...t.preferences,mapVisualOptions:{...(I=t.preferences)==null?void 0:I.mapVisualOptions,projectionScale:Number(F.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((w=(C=(k=t.preferences)==null?void 0:k.mapVisualOptions)==null?void 0:C.projectionOffset)==null?void 0:w[0])||0,onChange:F=>{var I,P,D,S;l({...t.preferences,mapVisualOptions:{...(I=t.preferences)==null?void 0:I.mapVisualOptions,projectionOffset:[Number(F.target.value),((S=(D=(P=t.preferences)==null?void 0:P.mapVisualOptions)==null?void 0:D.projectionOffset)==null?void 0:S[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((y=(E=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:E.projectionOffset)==null?void 0:y[1])||0,onChange:F=>{var I,P,D,S;l({...t.preferences,mapVisualOptions:{...(I=t.preferences)==null?void 0:I.mapVisualOptions,projectionOffset:[((S=(D=(P=t.preferences)==null?void 0:P.mapVisualOptions)==null?void 0:D.projectionOffset)==null?void 0:S[0])||0,Number(F.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Oe,{})]})}function Ir(){var r;const t=s.useEditorStore(l=>l.card.preferences),{setCardPreferences:n}=s.useEditorStore(l=>l.actions);function a(l){n({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:l==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:a,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function Xe({cardType:t,docContent:n,suffix:a="Chart"}){let r="pie-donut-polar";return t==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} ${a}`}),e.jsx(s.AccordionContent,{children:n||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:l=>l.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),t==="text"&&e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2 py-4",children:e.jsx(Ir,{})})]}),!["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(Oe,{}),e.jsx(Ve,{})]})]})]})})}function Ar(){const t=s.useEditorStore(r=>{var l,o;return(o=(l=r==null?void 0:r.card)==null?void 0:l.preferences)==null?void 0:o.sortChart}),{setSortChart:n}=s.useEditorActions();function a(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(Ce,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:t||"none",onValueChange:r=>{n(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[a(),e.jsx(It,{})]})]}),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(Oe,{}),e.jsx(Ve,{})]})]})]})})}function Mr({cardType:t="table"}){console.log("cardType",t);const n=s.useEditorStore(l=>{var o;return(o=l.card)==null?void 0:o.preferences}),a=s.useEditorStore(l=>l.actions.setCardPreferences),r=l=>{a({...n,allowDownload:l})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Oe,{}),e.jsx(Ve,{})]})]})}),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 Rt({color:t,onColorChange:n,onClose:a}){const[r,l]=M.useState(0),[o,c]=M.useState(100),[i,d]=M.useState(50),[u,m]=M.useState(t);M.useEffect(()=>{const j=$s(t);if(j){const f=qs(j.r,j.g,j.b);l(f.h),c(f.s),d(f.l),m(t)}},[t]);const h=j=>{l(j),g(j,o,i)},p=j=>{const f=j.currentTarget.getBoundingClientRect(),N=Math.max(0,Math.min(1,(j.clientX-f.left)/f.width)),T=Math.max(0,Math.min(1,(j.clientY-f.top)/f.height)),k=N*100,C=(1-T)*100;c(k),d(C),g(r,k,C)},g=(j,f,N)=>{const T=Rr(j,f,N),k=Lr(T.r,T.g,T.b);m(k)},b=j=>{if(m(j),/^#[0-9A-Fa-f]{6}$/.test(j)){const f=$s(j);if(f){const N=qs(f.r,f.g,f.b);l(N.h),c(N.s),d(N.l)}}},x=()=>{/^#[0-9A-Fa-f]{6}$/.test(u)&&(n(u),a())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:p,onMouseMove:j=>{j.buttons===1&&p(j)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${o}%`,top:`${100-i}%`,backgroundColor:u}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:j=>h(Number(j.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:j=>b(j.target.value),placeholder:"#000000",className:"font-mono"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:t}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:u}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(s.Button,{variant:"outline",onClick:a,children:"Cancel"}),e.jsx(s.Button,{onClick:x,children:"OK"})]})]})}function $s(t){const n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return n?{r:parseInt(n[1],16),g:parseInt(n[2],16),b:parseInt(n[3],16)}:null}function Lr(t,n,a){return"#"+((1<<24)+(t<<16)+(n<<8)+a).toString(16).slice(1)}function qs(t,n,a){t/=255,n/=255,a/=255;const r=Math.max(t,n,a),l=Math.min(t,n,a);let o=0,c=0;const i=(r+l)/2;if(r!==l){const d=r-l;switch(c=i>.5?d/(2-r-l):d/(r+l),r){case t:o=((n-a)/d+(n<a?6:0))/6;break;case n:o=((a-t)/d+2)/6;break;case a:o=((t-n)/d+4)/6;break}}return{h:Math.round(o*360),s:Math.round(c*100),l:Math.round(i*100)}}function Rr(t,n,a){t/=360,n/=100,a/=100;let r,l,o;if(n===0)r=l=o=a;else{const c=(u,m,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?u+(m-u)*6*h:h<.5?m:h<.6666666666666666?u+(m-u)*(.6666666666666666-h)*6:u),i=a<.5?a*(1+n):a+n-a*n,d=2*a-i;r=c(d,i,t+1/3),l=c(d,i,t),o=c(d,i,t-1/3)}return{r:Math.round(r*255),g:Math.round(l*255),b:Math.round(o*255)}}const Or=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function Ot(){var T,k,C,w,v,E,y,F,I,P;const t=s.useEditorStore(D=>D.card),n=s.useEditorStore(D=>{var S;return(S=D.card)==null?void 0:S.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions(),{data:l}=s.useDashboardCardQuery(t),[o,c]=M.useState({}),[i,d]=M.useState(null),[u,m]=M.useState(null),h=M.useMemo(()=>{var O,R,A,B,Y,_,Q;if(!(l!=null&&l.records)||l.records.length===0)return[];const D=(t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine",S=(t==null?void 0:t.type)==="bar"||(t==null?void 0:t.type)==="line",L=((O=t==null?void 0:t.config)==null?void 0:O.pivotByColumns)&&t.config.pivotByColumns.length>0;if((D||S)&&L){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const X=new Set;return l.pivotSchema.forEach(q=>{q.alias&&X.add(q.alias)}),Array.from(X)}if(l.records.length>0){const X=l.records[0],q=Object.keys(X),W=new Set;(R=t==null?void 0:t.config)!=null&&R.groupByColumns&&t.config.groupByColumns.forEach(V=>{W.add(V.label||V.name),W.add(V.alias||V.name)});const G=new Set;return(A=t==null?void 0:t.config)!=null&&A.metricColumns&&t.config.metricColumns.forEach(V=>{const U=V.alias||V.name;G.add(U),G.add(`${U}_count`),G.add(`${U}_sum`),G.add(`${U}_avg`),G.add(`${U}_min`),G.add(`${U}_max`);const ee=V.entityName||V.qualifiedEntityName;ee&&(G.add(`${ee}_${U}`),G.add(`${ee}_${U}_count`))}),q.filter(V=>!W.has(V)&&!G.has(V))}}if((S||D)&&!L&&((Y=(B=t==null?void 0:t.config)==null?void 0:B.metricColumns)!=null&&Y.length))return t.config.metricColumns.map(X=>X.alias||X.label||X.name);if((Q=(_=t==null?void 0:t.config)==null?void 0:_.groupByColumns)!=null&&Q.length){const X=t.config.groupByColumns[0],q=X.label||X.name,W=new Set;return l.records.forEach(G=>{const se=G[q];se!=null&&W.add(String(se))}),Array.from(W)}return[]},[l,(T=t==null?void 0:t.config)==null?void 0:T.groupByColumns,(k=t==null?void 0:t.config)==null?void 0:k.pivotByColumns,(C=t==null?void 0:t.config)==null?void 0:C.metricColumns,t==null?void 0:t.type]),p=M.useMemo(()=>s.getDefaultChartColors(),[]);M.useEffect(()=>{const D={};h.forEach((S,L)=>{D[S]=s.getColorForValue(S,L,n==null?void 0:n.colorConfig)}),c(D)},[h,n==null?void 0:n.colorConfig,p]);const g=(D,S)=>{const L={...o,[D]:S};c(L);const O={...n||{},colorConfig:{segments:L}};a(O);const R={...t,preferences:O};r(R)},b=(D,S)=>{var Y;const L=p[S%p.length],{[D]:O,...R}=((Y=n==null?void 0:n.colorConfig)==null?void 0:Y.segments)||{},A={...n||{},colorConfig:{segments:R}};a(A);const B={...t,preferences:A};r(B),c(_=>({..._,[D]:L}))};if(!h.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((v=(w=t==null?void 0:t.config)==null?void 0:w.groupByColumns)==null?void 0:v.length)||((y=(E=t==null?void 0:t.config)==null?void 0:E.pivotByColumns)==null?void 0:y.length):(I=(F=t==null?void 0:t.config)==null?void 0:F.groupByColumns)==null?void 0:I.length)||["table","kpi","text","custom"].includes(t.type))return null;const f=()=>{const D={...n||{},colorConfig:{segments:{}}};a(D);const S={...t,preferences:D};r(S);const L={};h.forEach((O,R)=>{L[O]=s.getColorForValue(O,R,void 0)}),c(L)},N=Object.keys(((P=n==null?void 0:n.colorConfig)==null?void 0:P.segments)||{}).length>0;return e.jsxs(s.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ma,{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:N&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:f,children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:h.map((D,S)=>{const L=s.isDefaultColor(o[D],S),O=!L;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:i===D,onOpenChange:R=>d(R?D:null),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"h-5 w-5 shrink-0 rounded border border-input shadow-sm transition-colors hover:border-gray-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",style:{backgroundColor:o[D]}})}),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:p.slice(0,10).map((R,A)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",o[D]===R?"border-gray-900":"border-transparent"),style:{backgroundColor:R},onClick:()=>{g(D,R),d(null)},children:[A===S%p.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:R})]},`default-${A}`))})]}),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:Or.map((R,A)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",o[D]===R?"border-2 border-gray-900":R==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:R},onClick:()=>{g(D,R),d(null)},children:e.jsx("span",{className:"sr-only",children:R})},`preset-${A}`))})]}),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:D,color:o[D]}),d(null)},children:"Custom color"}),!L&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{b(D,S),d(null)},children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:D}),O&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},D)})}),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(Rt,{color:u.color,onColorChange:D=>{g(u.value,D),m(null)},onClose:()=>m(null)})})]})]})})]})}function we({value:t,onSave:n,placeholder:a="",type:r="text",className:l=""}){const[o,c]=M.useState(t??""),[i,d]=M.useState(!1);M.useEffect(()=>{c(t??"")},[t]);const u=()=>{n(o),d(!1)},m=()=>{c(t??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${l}`,children:[e.jsx(s.Input$1,{placeholder:a,type:r,value:i?o:t??"",onChange:h=>{c(h.target.value),d(!0)},onFocus:()=>d(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&i&&o!==t?u():h.key==="Escape"&&m()},"aria-label":a||"Edit field"}),i&&o!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:u,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:m,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}const Fr=["auto","number","currency","percent","scientific","date"],Pr=[{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"}],Br=[{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"}],zr=t=>t.charAt(0).toUpperCase()+t.slice(1);function As({formatOptions:t={},onFormatOptionsChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const l=t.type||"auto",o=(i,d)=>{n({...t,[i]:d})},c=()=>l==="currency"?2:l==="percent"?1:0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[a&&e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(s.Select,{value:l,onValueChange:i=>o("type",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Fr.map(i=>e.jsx(s.SelectItem,{value:i,className:"text-xs",children:i==="auto"?"Auto (Default)":zr(i)},i))})]})]}),l!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent"].includes(l)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",min:"0",max:"10",placeholder:"0",value:t.decimalPlaces??c(),onChange:i=>o("decimalPlaces",parseInt(i.target.value)||0),className:"h-8 text-xs"})})]}),l==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(s.Select,{value:t.currency||"USD",onValueChange:i=>o("currency",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Pr.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:t.useSuffix??!1,onCheckedChange:i=>o("useSuffix",i)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(s.Select,{value:t.locale||"en-US",onValueChange:i=>o("locale",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Br.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., $",value:t.prefix||"",onChange:i=>o("prefix",i.target.value),className:"h-8 text-xs"})})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., units",value:t.suffix||"",onChange:i=>o("suffix",i.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Negative in ()"}),e.jsx(s.SmallSwitch,{checked:t.negativeInParentheses??!1,onCheckedChange:i=>o("negativeInParentheses",i)})]}),l==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",placeholder:"100",value:t.multiplyBy??"",onChange:i=>o("multiplyBy",i.target.value?parseFloat(i.target.value):void 0),className:"h-8 text-xs"})})]}),l==="date"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Format"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"text",placeholder:"MM/DD/YYYY",value:t.dateFormat||"",onChange:i=>o("dateFormat",i.target.value),className:"h-8 text-xs"})})]})]})]})}function Hs({axis:t,label:n,type:a,config:r,onChange:l}){var h,p,g,b,x,j,f,N,T,k,C,w;const o=(v,E)=>{l({...r,[v]:E})},c=(v,E)=>{var y,F;l({...r,name:{enabled:v==="enabled"?E:((y=r==null?void 0:r.name)==null?void 0:y.enabled)??!1,text:v==="text"?E:(F=r==null?void 0:r.name)==null?void 0:F.text}})},i=(v,E)=>{var y,F;l({...r,labels:{enabled:v==="enabled"?E:((y=r==null?void 0:r.labels)==null?void 0:y.enabled)??!0,rotation:v==="rotation"?E:(F=r==null?void 0:r.labels)==null?void 0:F.rotation}})},d=(v,E)=>{l({...r,scale:{...r==null?void 0:r.scale,[v]:E===""?"auto":Number(E)}})},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:n})})}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:v=>o("enabled",v),onClick:v=>v.stopPropagation()})]}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TITLE"}),e.jsx(s.SmallSwitch,{checked:((h=r==null?void 0:r.name)==null?void 0:h.enabled)??!1,onCheckedChange:v=>c("enabled",v)})]}),((p=r==null?void 0:r.name)==null?void 0:p.enabled)&&e.jsx(we,{placeholder:`${n} title`,value:((g=r==null?void 0:r.name)==null?void 0:g.text)||"",onSave:v=>c("text",v),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:v=>o("position",v),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(v=>e.jsx(s.SelectItem,{value:v,className:"text-xs",children:v==="auto"?"Auto (Default)":s.titleCase(v)},v))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(s.SmallSwitch,{checked:((b=r==null?void 0:r.labels)==null?void 0:b.enabled)!==!1,onCheckedChange:v=>i("enabled",v)})]}),((x=r==null?void 0:r.labels)==null?void 0:x.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(((j=r==null?void 0:r.labels)==null?void 0:j.rotation)||"auto"),onValueChange:v=>i("rotation",v==="auto"?"auto":Number(v)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:m.map(v=>e.jsx(s.SelectItem,{value:v,className:"text-xs",children:v==="auto"?"Auto (Default)":`${v}°`},v))})]})]})]}),a==="value"&&e.jsx(As,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:v=>l({...r,formatOptions:v}),showTitle:!0,title:"FORMAT"}),a==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"SCALE"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"auto",value:((f=r==null?void 0:r.scale)==null?void 0:f.min)==="auto"||((N=r==null?void 0:r.scale)==null?void 0:N.min)===void 0?"":String(r.scale.min),onSave:v=>d("min",v),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(we,{type:"number",placeholder:"auto",value:((T=r==null?void 0:r.scale)==null?void 0:T.max)==="auto"||((k=r==null?void 0:r.scale)==null?void 0:k.max)===void 0?"":String(r.scale.max),onSave:v=>d("max",v),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(we,{type:"number",placeholder:"auto",value:((C=r==null?void 0:r.scale)==null?void 0:C.stepSize)==="auto"||((w=r==null?void 0:r.scale)==null?void 0:w.stepSize)===void 0?"":String(r.scale.stepSize),onSave:v=>d("stepSize",v),className:""})})]})]})]})]})]})}function Ft(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>{var i;return(i=c.card)==null?void 0:i.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions();if(!t||["tornado","pyramid","kpi"].includes(t.type))return null;const l=s.AxisConfigurator.getAxisInfo(t.type,n);if(!l.hasXAxis&&!l.hasYAxis)return null;const o=(c,i)=>{const u={...n||{},[c==="x"?"xAxisConfig":"yAxisConfig"]:i};a(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(at,{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(Hs,{axis:"x",label:"X-Axis",type:l.xAxisType,config:n==null?void 0:n.xAxisConfig,onChange:c=>o("x",c)}),l.hasYAxis&&e.jsx(Hs,{axis:"y",label:"Y-Axis",type:l.yAxisType,config:n==null?void 0:n.yAxisConfig,onChange:c=>o("y",c)})]})})]})}function Pt(){const t=s.useEditorStore(u=>u.card),n=s.useEditorStore(u=>{var m,h,p,g;return(g=(p=(h=(m=u.card)==null?void 0:m.preferences)==null?void 0:h.chartOptions)==null?void 0:p.plugins)==null?void 0:g.legend}),{setLegendOptions:a}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r="bottom",l="center",o=!(t.type==="stackedBar"||t.type==="stackedLine"),c=(u,m)=>{const h={...n,[u]:m};a(h)},i=["top","bottom","left","right"],d=["start","center","end"];return e.jsxs(s.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ya,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:(n==null?void 0:n.display)??o,onCheckedChange:u=>c("display",u)})]}),((n==null?void 0:n.display)??o)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(n==null?void 0:n.position)||r,onValueChange:u=>c("position",u),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:i.map(u=>e.jsx(s.SelectItem,{value:u,className:"text-xs",children:s.titleCase(u)},u))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(s.Select,{value:(n==null?void 0:n.align)||l,onValueChange:u=>c("align",u),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:d.map(u=>e.jsx(s.SelectItem,{value:u,className:"text-xs",children:s.titleCase(u)},u))})]})]})]})]})})]})}function Bt(){var E,y,F,I,P,D,S,L,O;const t=s.useEditorStore(R=>R.card),n=s.useEditorStore(R=>{var A,B;return(B=(A=R.card)==null?void 0:A.preferences)==null?void 0:B.dataLabelsConfig}),a=s.useEditorStore(R=>{var A;return(A=R.card)==null?void 0:A.preferences}),{setCardPreferences:r,updateCardInFrame:l}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(t.type))return null;const o=((E=a==null?void 0:a.chartOptions)==null?void 0:E.indexAxis)==="y",c=t.type==="stackedBar"||t.type==="stackedLine",i=t.type==="pie"||t.type==="doughnut"||t.type==="polarArea"||t.type==="funnel",d=!i,u=(F=(y=a==null?void 0:a.chartOptions)==null?void 0:y.plugins)==null?void 0:F.datalabels,m=(u==null?void 0:u.display)!==!1&&((u==null?void 0:u.anchor)||(u==null?void 0:u.align)),h=(n==null?void 0:n.enabled)!==void 0?n.enabled:m,p=(R,A)=>{const B={...n,[R]:A},Y={...t.preferences||{},dataLabelsConfig:B};r(Y);const _={...t,preferences:Y};l(_)},g=(R,A)=>{const B={...n,font:{...n==null?void 0:n.font,[R]:A}},Y={...t.preferences||{},dataLabelsConfig:B};r(Y);const _={...t,preferences:Y};l(_)},b=(R,A)=>{const B={...n,formatOptions:{...n==null?void 0:n.formatOptions,[R]:A}},Y={...t.preferences||{},dataLabelsConfig:B};r(Y);const _={...t,preferences:Y};l(_)},j=(()=>{const R=t.type;return R==="stackedBar"||R==="stackedLine"||R==="pie"||R==="doughnut"?"center":o?"right":"top"})();let f=[];c||i?f=["center"]:f=["auto",...(o?["center","left","right"]:["center","top","bottom"]).filter(A=>A!==j),"custom"];const N=()=>s.titleCase(j),T=["center","start","end"],k=["center","start","end","top","bottom"],C=d?["auto","number","currency","percent","none"]:["number","currency","percent","none"],w=[{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"}],v=[{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(Ua,{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:R=>p("enabled",R)})]}),h&&e.jsxs(e.Fragment,{children:[!c&&!i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(n==null?void 0:n.position)||"auto",onValueChange:R=>p("position",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:f.map(R=>e.jsx(s.SelectItem,{value:R,className:"text-xs",children:R==="auto"?N():R==="custom"?"Custom (Advanced)":s.titleCase(R)},R))})]})]}),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:(n==null?void 0:n.showTotal)??!1,onCheckedChange:R=>p("showTotal",R)})]}),(n==null?void 0:n.position)==="custom"&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Anchor"}),e.jsxs(s.Select,{value:(n==null?void 0:n.anchor)||"center",onValueChange:R=>p("anchor",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:T.map(R=>e.jsx(s.SelectItem,{value:R,className:"text-xs",children:s.titleCase(R)},R))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Align"}),e.jsxs(s.Select,{value:String((n==null?void 0:n.align)||"center"),onValueChange:R=>p("align",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:k.map(R=>e.jsx(s.SelectItem,{value:R,className:"text-xs",children:s.titleCase(R)},R))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(n==null?void 0:n.format)||(d?"auto":"none"),onValueChange:R=>p("format",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:C.map(R=>e.jsx(s.SelectItem,{value:R,className:"text-xs",children:R==="auto"&&d?"Auto (Use Axis)":R==="none"?"None (Raw Value)":s.titleCase(R)},R))})]})]}),(n==null?void 0:n.format)&&!["auto","none"].includes(n.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(n.format)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"0",value:String(((I=n==null?void 0:n.formatOptions)==null?void 0:I.decimalPlaces)??(n.format==="currency"?2:n.format==="percent"?1:0)),onSave:R=>b("decimalPlaces",Number(R)),className:""})})]}),n.format==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Currency"}),e.jsxs(s.Select,{value:((P=n==null?void 0:n.formatOptions)==null?void 0:P.currency)||"USD",onValueChange:R=>b("currency",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:w.map(R=>e.jsx(s.SelectItem,{value:R.value,className:"text-xs",children:R.label},R.value))})]})]}),["number","currency"].includes(n.format)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((D=n==null?void 0:n.formatOptions)==null?void 0:D.useSuffix)??!1,onCheckedChange:R=>b("useSuffix",R)})]}),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:((S=n==null?void 0:n.formatOptions)==null?void 0:S.locale)||"en-US",onValueChange:R=>b("locale",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:v.map(R=>e.jsx(s.SelectItem,{value:R.value,className:"text-xs",children:R.label},R.value))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Appearance"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Size"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"12",value:String(((L=n==null?void 0:n.font)==null?void 0:L.size)||12),onSave:R=>g("size",Number(R)),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:((O=n==null?void 0:n.font)==null?void 0:O.weight)||"normal",onValueChange:R=>g("weight",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(s.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Color"}),e.jsxs(s.Select,{value:(n==null?void 0:n.color)==="auto"||!(n!=null&&n.color)?"auto":"custom",onValueChange:R=>{R==="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(we,{type:"number",placeholder:"0",value:String((n==null?void 0:n.rotation)||0),onSave:R=>p("rotation",Number(R)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}function _r(){return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Chart Configuration"}),e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:[e.jsx(Ot,{}),e.jsx(Ft,{}),e.jsx(Pt,{}),e.jsx(Bt,{})]})]})}const Vr=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."]})]}),Ur=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."]})]}),Gr=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 Yr(){const t=s.useEditorStore(a=>a.card.type);function n(a){const r=["kpi","table","text","map","custom"],l=o=>r.includes(a)?o:e.jsxs(e.Fragment,{children:[o,e.jsx(_r,{})]});switch(a){case"stackedBar":case"stackedLine":return l(e.jsx(Ar,{}));case"tornado":case"pyramid":return l(e.jsx(Xe,{docContent:Vr,cardType:a}));case"kpi":return e.jsx(wr,{});case"line":case"bar":return l(e.jsx(gr,{cardType:a}));case"range":return l(e.jsx(Xe,{docContent:Ur,cardType:a}));case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return l(e.jsx(Xe,{cardType:a}));case"bubble":case"scatter":return l(e.jsx(jr,{cardType:a}));case"table":return e.jsx(Mr,{cardType:a});case"text":return e.jsx(Xe,{docContent:Gr,cardType:a,suffix:"Visual"});case"map":return e.jsx(Er,{});case"custom":return e.jsx(hr,{});default:return l(e.jsx(yr,{}))}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[n(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function zt({label:t,column:n,functions:a,onFunctionChange:r}){let l=a[0];"aggregate"in n?l=a.find(c=>c.value===n.aggregate)||a[0]:"granularity"in n&&(l=a.find(c=>c.value===n.granularity)||a[0]);function o(c){r(c)}return e.jsx(Ce,{className:"flex h-8 w-8 justify-center overflow-clip rounded-none border-none bg-muted px-0 [&>svg]:hidden",icon:l.logo,options:a,value:l.value,onValueChange:c=>o(c),label:t,showPlaceholderLabel:!1})}const $r=[{label:"Sum",value:"SUM",logo:e.jsx(tt,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(De,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(ga,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(ta,{className:"size-3.5"})},{label:"Min",value:"MIN",logo:e.jsx(s.ArrowDown,{className:"size-3.5"})},{label:"Max",value:"MAX",logo:e.jsx(s.ArrowUp,{className:"size-3.5"})}];function qr({column:t}){const{updateMetricColumnOld:n}=s.useEditorActions();let a=$r;s.isTextDataType(t.type)&&(a=a.filter(l=>["COUNT","DISTINCT"].includes(l.value))),s.isNumberDataType(t.type)&&(a=a.filter(l=>!["DISTINCT"].includes(l.value)));function r(l){const o={...t,aggregate:l,label:qe(t.name,l)};n(t.id,o)}return e.jsx(zt,{column:t,functions:a,onFunctionChange:l=>r(l),label:"Aggregation"})}const Hr=[{label:"Day (D)",value:"day",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"D"})},{label:"Week (W)",value:"week",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"W"})},{label:"Month (M)",value:"month",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"M"})},{label:"Year (Y)",value:"year",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"Y"})}];function Wr({column:t}){const{updateGroupByColumnOld:n}=s.useEditorActions();function a(r){const l={...t,granularity:r,label:_e(t.name,r)};n(t.id,l)}return e.jsx(zt,{column:t,functions:Hr,onFunctionChange:r=>a(r),label:"Granularity"})}function Kr({col:t,onChange:n,droppableId:a}){const{columns:r}=s.useDataColumns(),l=M.useMemo(()=>{let i=[];(a===Ie||a===Ae||a===Me)&&(i=r);const d=i==null?void 0:i.filter(u=>u.column_name!==t.name);return d==null?void 0:d.map(u=>({id:u.column_name,value:u.column_name}))},[r,a,t.name]),o=[{id:t.name,value:t.name}];function c(i){const d=r==null?void 0:r.find(u=>{var m;return u.column_name===((m=i[0])==null?void 0:m.id)});d&&n(d)}return l!=null&&l.length?e.jsx(s.ComboBox2,{multiple:!1,options:l,selectedOptions:o,onChange:c,selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"border-none bg-muted pl-0 pr-8"}):e.jsx("input",{disabled:!0,type:"text",className:"overflow-hidden truncate text-ellipsis whitespace-nowrap bg-muted text-sm",value:t.name})}function _t({column:t}){const n=s.useEditorStore(d=>d.card.type),a=s.useEditorStore(d=>{var u,m;return(m=(u=d.card)==null?void 0:u.config)==null?void 0:m.metricColumns}),r=(a==null?void 0:a.map(d=>d.label))||[],l=r==null?void 0:r.find(d=>d===t.label||d===t.name),o=l?r.indexOf(l):-1;function c(){return e.jsx("div",{className:"pr-1",children:l&&e.jsx(Mt,{idx:o,col:l,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function i(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(Lt,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&c(),["pie","doughnut"].includes(n)&&i()]})}function Qr({column:t,type:n,onRemoveColumn:a,droppableId:r}){const[l,o]=M.useState(!1),{updateGroupByColumnOld:c,updateMetricColumnOld:i,updatePivotByColumnOld:d}=s.useEditorActions(),{attributes:u,listeners:m,setNodeRef:h,transform:p,transition:g,isDragging:b}=s.useSortable({id:t.id,data:{type:n}}),x=p?{opacity:b?.5:void 0,transform:s.CSS.Translate.toString(p),transition:g}:void 0,j=s.isTextDataType(t.type);function f(w){const v=s.isNumberDataType(w.data_type),E=s.isTextDataType(w.data_type),y=s.isDateDataType(w.data_type),F=v?"number":E?"string":y?"date":"string";if(r===Ie){if(E){const I={id:t.id,name:w.column_name,type:F,role:"groupby"};c(t.id,I)}if(y){const I={id:t.id,name:w.column_name,type:F,role:"groupby",label:_e(w.column_name,"month"),granularity:"month"};c(t.id,I)}}if(r===Me){if(E){const I={id:t.id,name:w.column_name,type:F,role:"groupby"};d(t.id,I)}if(y){const I={id:t.id,name:w.column_name,type:F,label:_e(w.column_name,"month"),granularity:"month",role:"groupby"};d(t.id,I)}}if(r===Ae){const I={id:t.id,name:w.column_name,type:F,role:"metric",label:qe(w.column_name,"SUM"),aggregate:v?"SUM":"COUNT"};i(t.id,I)}}function N(){if(r===Ae)return e.jsx("div",{"data-setting-container":"",className:"mt-1.5 max-h-32 overflow-y-auto rounded-md border border-border p-3 text-sm",children:e.jsx(_t,{column:t})})}function T(){const w=s.isDateDataType(t.type);if(r===Ae)return e.jsx(qr,{column:t});if((r===Ie||r===Me)&&w)return e.jsx(Wr,{column:t})}function k(){return e.jsx("div",{className:s.cn("grow",{"pl-3":(r===Ie||r===Me)&&j}),children:e.jsx(Kr,{col:t,onChange:f,droppableId:r})})}function C(){return e.jsx("div",{"data-setting-actions":"",className:"flex h-full items-center gap-2",children:e.jsx("button",{className:"h-full pl-2",onClick:()=>o(!l),children:l?e.jsx(za,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(et,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...m,...u,ref:h,style:x,children:e.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex h-8 grow items-center justify-between rounded-md bg-muted",children:[C(),T(),k()]}),l&&N()]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:l}),children:e.jsx("button",{onClick:()=>a(t.id),children:e.jsx(s.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function gs({id:t,label:n,columns:a,previewColumns:r,sortableType:l,onRemoveColumn:o}){var x,j;const{setNodeRef:c,isOver:i,over:d}=s.useDroppable({id:t}),u=s.useDndStore(f=>f.activeId),m=s.useEditorStore(f=>{var N;return(N=f.card)==null?void 0:N.type}),h=i||((j=(x=d==null?void 0:d.data)==null?void 0:x.current)==null?void 0:j.type)===l,p=u?r:a,g=l===as?"Rows":l===ns?"Pivot Columns":"Columns";function b(){if(!p||p.length===0)return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}return e.jsx(s.SortableContext,{items:a==null?void 0:a.map(f=>f.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md p-4",h&&"border border-muted-foreground/20"),ref:c,children:[e.jsxs("div",{className:"flex items-center justify-between pr-5",children:[e.jsx(s.Label,{className:"text-sm",children:n}),m!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:g})]}),b(),e.jsx("div",{className:"space-y-2",children:p==null?void 0:p.map(f=>f.id===gt.id?e.jsx(Jr,{},f.id):e.jsx(Qr,{droppableId:t,type:l,column:f,onRemoveColumn:o},f.id))})]})})}function Jr(){return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm",children:e.jsx("span",{className:"text-muted-foreground/70",children:"Drop here"})})}function Vt({children:t,id:n,type:a}){const{attributes:r,listeners:l,setNodeRef:o,transform:c,transition:i,isDragging:d}=s.useSortable({id:n,data:{type:a}}),u=c?{opacity:d?.5:void 0,transform:s.CSS.Translate.toString(c),transition:i}:void 0;return e.jsx("div",{...l,...r,ref:o,style:u,children:t})}function Xr(){const t=s.useEditorStore(f=>{var N;return(N=f.card.queryConfig)==null?void 0:N.orderBy})||[],n=s.useEditorStore(f=>{var N;return(N=f.card.queryConfig)==null?void 0:N.groupByColumns})||[],a=s.useEditorStore(f=>{var N;return(N=f.card.queryConfig)==null?void 0:N.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:l,updateOrderByColumn:o}=s.useEditorActions(),c=[...n,...a];if(c.length===0)return e.jsx(e.Fragment,{});const i=e.jsx(na,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx(sa,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=e.jsx(aa,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=e.jsx(ea,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=c==null?void 0:c.filter(f=>!t.some(N=>N.columnId===f.id)).map(f=>({id:f.id,value:f.label||f.name}));function p(f,N){const T=g(f);return T?T.role==="metric"?N==="asc"?u:m:N==="asc"?i:d:null}function g(f){return c.find(N=>N.id===f)}function b(f){const N=t.find(T=>T.columnId===f);if(N){const T={...N,direction:N.direction==="asc"?"desc":"asc"};o(T)}}const x=f=>{r({columnId:f.id,direction:"asc"})};function j(f){const N=t.find(T=>T.columnId===f);N&&l(N)}return e.jsx(s.SortableContext,{items:t.map(f=>Ge(f.columnId)),children:e.jsxs("div",{className:"space-y-2 rounded-md p-4 text-sm",children:[e.jsx(s.Label,{className:"text-sm",children:"Sort By"}),h.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(s.ComboBox2,{multiple:!1,options:h,selectedOptions:[],onChange:f=>x(f[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),t.map(f=>{var N,T;return e.jsx(Vt,{id:Ge(f.columnId),type:ws,children:e.jsx("div",{className:"group flex h-8 items-center gap-2 rounded-sm p-0",children:e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2 rounded-sm bg-muted px-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(et,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(cs,{className:"w-[175px] text-sm",children:((N=g(f.columnId))==null?void 0:N.label)||((T=g(f.columnId))==null?void 0:T.name)})]}),e.jsx("button",{title:f.direction==="asc"?"Ascending":"Descending",onClick:()=>b(f.columnId),className:"rounded-sm p-0",children:p(f.columnId,f.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>j(f.columnId),className:"rounded-sm p-0",children:e.jsx(s.X,{className:"size-3 text-muted-foreground opacity-0 transition-opacity duration-200 hover:text-foreground group-hover:opacity-100"})})})]})},f.columnId)},Ge(f.columnId))})]})})}function Zr(){const t=s.useEditorStore(j=>{var f;return((f=j.card.queryConfig)==null?void 0:f.groupByColumns)||[]}),n=s.useEditorStore(j=>j.card.type),a=s.useDndStore(j=>j.previewGroupByColumns),r=s.useEditorStore(j=>{var f;return((f=j.card.queryConfig)==null?void 0:f.metricColumns)||[]}),l=s.useDndStore(j=>j.previewMetricColumns),o=s.useEditorStore(j=>{var f;return((f=j.card.queryConfig)==null?void 0:f.pivotColumns)||[]}),c=s.useDndStore(j=>j.previewPivotColumns),{removeColumnFromGroupBy:i,removeColumnFromMetricColumns:d,removeColumnFromPivotBy:u}=s.useEditorActions();function m(j){i(j)}function h(j){d(j)}function p(j){u(j)}let g="Group By",b="Metrics",x="Stack By";return n==="table"&&(g="Rows",b="Metrics",x="Columns"),e.jsxs("div",{className:"flex h-full w-full flex-col gap-3 py-4",children:[e.jsx(Dt,{iconClassName:"size-[19px]"}),e.jsxs(s.CustomScrollArea,{className:"flex min-h-0 grow basis-0 flex-col gap-4 overflow-y-auto",children:[e.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[e.jsx(gs,{onRemoveColumn:m,sortableType:as,id:Ie,label:g,columns:t,previewColumns:a}),e.jsx(gs,{onRemoveColumn:p,sortableType:ns,id:Me,label:x,columns:o,previewColumns:c}),e.jsx(gs,{onRemoveColumn:h,sortableType:ys,id:Ae,label:b,columns:r,previewColumns:l}),e.jsx(Xr,{})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Ms({children:t,column:n,id:a,sortableType:r,className:l}){const[o,c]=M.useState(!1),{removeEditorFilter:i,clearEditorFilter:d}=s.useEditorActions(),u=s.useEditorStore(h=>{var p,g;return(g=(p=h.card.queryConfig)==null?void 0:p.filters)==null?void 0:g.some(b=>b.filterColumnName===n.name)});function m(h){i(h)}return e.jsx(Vt,{id:a,type:r,children:e.jsxs("div",{className:s.cn("group space-y-1 rounded-md bg-muted px-3 py-2",{"border-border":o}),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-sm",children:n.name}),u&&e.jsx("button",{onClick:()=>d(n),children:e.jsx(s.FilterX,{className:"size-3 cursor-pointer items-center justify-center text-muted-foreground hover:text-foreground"})})]}),e.jsx("div",{"data-setting-actions":"",className:"invisible flex h-full items-center gap-2 group-hover:visible",children:e.jsx("button",{onClick:()=>m(n),children:e.jsx(s.X,{className:"size-3.5 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground"})})})]}),e.jsxs("div",{className:s.cn("group flex items-center rounded-t-md text-sm",!o&&"rounded-b-md",o&&"border border-border"),children:[e.jsx("div",{children:e.jsx(s.GripVertical,{className:"mr-2 size-3.5 cursor-move items-center justify-center p-0 text-muted-foreground/60 hover:text-foreground"})}),e.jsx("div",{className:s.cn("grow cursor-pointer overflow-hidden truncate text-ellipsis whitespace-nowrap",l),children:t})]})]})})}function el({column:t,sortableType:n}){const a=s.useDashboardStore(T=>T.themeStyle),r=s.useEditorStore(T=>{var k,C;return(C=(k=T.card)==null?void 0:k.queryConfig)==null?void 0:C.filters}),l=s.useEditorStore(T=>{var k,C;return(C=(k=T.card.queryConfig)==null?void 0:k.filterColumns)==null?void 0:C.find(w=>w.name===t.name)}),{selectedConnectionId:o,selectedDatabaseName:c,selectedTableName:i}=s.useEditorAside(),d=M.useMemo(()=>{var T;return(T=r==null?void 0:r.find(k=>k.filterColumnName===t.name))==null?void 0:T.filterValue},[r,t.name]),u=M.useMemo(()=>Array.isArray(d)?d.map(T=>({id:T,value:T})):[],[d]),{updateEditorFilterValue:m}=s.useEditorActions(),h={column:t.name,sql:t.sql,id:t.name,connectionId:o,dataType:t.type},{data:p,isLoading:g,isFetching:b,isError:x}=s.useFilterQuery(h),j=M.useMemo(()=>{var k;return h.column?(k=p==null?void 0:p.records)==null?void 0:k.map(C=>{let w=h.column.split(".").slice(-1)[0].replace(/"/g,"");return C[w]===void 0&&(w=w.toLowerCase()),{id:C[w],value:C[w]}}):[]},[p,h.column]);function f(T){const k=T.map(C=>C.id);m(t.name,k)}function N(){return g||b?e.jsx(s.Skeleton,{style:{borderRadius:a==null?void 0:a.controlInputRadius},className:"h-8 min-w-60 bg-foreground/10"}):x?e.jsx("div",{className:"flex h-8 min-w-60 items-center bg-muted px-2 text-sm",children:"Error"}):e.jsx(s.ComboBox2,{renderFilterModeButton:()=>e.jsx(sl,{columnName:t.name}),showNegativeIndicator:(l==null?void 0:l.mode)==="exclude",options:j,onChange:f,selectedOptions:u,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(Ms,{className:"w-60",id:t.id,sortableType:n,column:t,children:N()})}function sl({columnName:t}){const{setEditorFilterMode:n}=s.useEditorActions(),a=s.useEditorStore(l=>{var o,c;return(c=(o=l.card.queryConfig)==null?void 0:o.filterColumns)==null?void 0:c.find(i=>i.name===t)});function r(){(a==null?void 0:a.mode)==="exclude"?n(t,"include"):n(t,"exclude")}return e.jsx(s.Button,{onClick:r,variant:"secondary",size:"sm",className:s.cn("h-5 text-xs hover:underline",{}),children:s.titleCase((a==null?void 0:a.mode)==="exclude"?"exclude":"include")})}function tl({open:t,setOpen:n,dateRange:a,setDateRange:r,containerClassName:l,inputClassName:o,title:c,onApply:i,onClear:d}){const u=s.useDashboardStore(m=>m.themeStyle);return e.jsx("div",{className:s.cn("grid gap-2",l),children:e.jsxs(s.Popover,{open:t,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{style:{borderRadius:u==null?void 0:u.controlInputRadius},asChild:!0,children:e.jsxs(s.Button,{size:"sm",id:"date",variant:"outline",className:s.cn("h-9 w-full justify-start rounded-sm text-left font-normal",!a&&"text-muted-foreground",o),children:[e.jsx(s.Calendar,{className:"mr-2 h-4 w-4"}),a!=null&&a.from?a.to?e.jsxs(e.Fragment,{children:[s.format(a.from,"LLL dd, y")," -"," ",s.format(a.to,"LLL dd, y")]}):s.format(a.from,"LLL dd, y"):e.jsx("span",{children:"Pick a date"})]})}),e.jsxs(s.PopoverContent,{style:{borderRadius:u==null?void 0:u.controlInputRadius},className:"w-auto p-0",align:"start",children:[e.jsx("div",{className:"px-4 pt-3",children:e.jsx(s.Label,{children:c})}),e.jsx(s.Calendar$1,{initialFocus:!0,mode:"range",defaultMonth:a==null?void 0:a.from,selected:a,onSelect:r,numberOfMonths:2}),e.jsxs("div",{className:"flex justify-end gap-2 px-4 py-3",children:[e.jsx(s.Button,{style:{borderRadius:u==null?void 0:u.controlInputRadius},size:"sm",variant:"outline",onClick:m=>{m.stopPropagation(),i(a),n(!1)},children:"Apply"}),e.jsx(s.Button,{style:{borderRadius:u==null?void 0:u.controlInputRadius},size:"sm",variant:"outline",onClick:d,children:"Clear"})]})]})]})})}function al({column:t,sortableType:n}){const[a,r]=M.useState(!1),{selectedConnectionId:l,selectedDatabaseName:o,selectedTableName:c}=s.useEditorAside(),i={column:t.name,sql:t.sql,id:t.name,connectionId:l,title:"",dataType:t.type},{isLoading:d,isFetching:u,isError:m,data:h}=s.useFilterQuery(i),p=h==null?void 0:h.records,{dateRange:g,setDateRange:b,initialDateRange:x}=s.useDateRangeFromRecords(p),{updateEditorFilterValue:j}=s.useEditorActions();function f(k){var w,v;const C={gte:(w=k==null?void 0:k.from)==null?void 0:w.toISOString(),lte:(v=k==null?void 0:k.to)==null?void 0:v.toISOString()};j(t.name,C)}function N(){j(t.name,null,!0),b(x)}function T(){return d||u?e.jsx("div",{children:e.jsx(s.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):m?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):p?e.jsx(tl,{title:i.title,open:a,inputClassName:"h-8",setOpen:r,dateRange:g,setDateRange:b,onApply:f,onClear:N}):e.jsx(s.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(Ms,{className:"w-72",id:t.id,sortableType:n,column:t,children:T()})}function nl({id:t,label:n,columns:a,previewColumns:r,sortableType:l}){var b,x;const{setNodeRef:o,isOver:c,over:i}=s.useDroppable({id:t}),d=s.useDndStore(j=>j.activeId),u={},m=c||((x=(b=i==null?void 0:i.data)==null?void 0:b.current)==null?void 0:x.type)===l;function h(){if(!g||g.length===0)return e.jsx("div",{className:"flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}function p(j){const f=s.isDateDataType(j.type);return j.id===gt.id?e.jsx(Ms,{id:j.id,sortableType:l,column:j,children:e.jsx(rl,{})},j.id):f?e.jsx(al,{droppableId:t,sortableType:l,column:j},j.id):e.jsx(el,{droppableId:t,sortableType:l,column:j},j.id)}const g=d?r:a;return e.jsx(s.SortableContext,{items:a==null?void 0:a.map(j=>j.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",m&&"border border-muted-foreground/20"),ref:o,style:u,children:[e.jsx(s.Label,{className:"text-sm",children:n}),h(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:g==null?void 0:g.map(j=>p(j))})]})})}function rl(){return e.jsx("div",{className:"flex h-8 w-60 items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm text-muted-foreground",children:"Drop here"})}function ll(){const t=s.useEditorStore(l=>{var o;return((o=l.card.queryConfig)==null?void 0:o.filterColumns)||[]}),n=s.useDndStore(l=>l.previewFilterColumns),{removeColumnFromFilterColumns:a}=s.useEditorActions();function r(l){a(l)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(nl,{onRemoveColumn:r,sortableType:Cs,id:Ns,label:"Filters",columns:t,previewColumns:n})})}function ol(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>c.showAIDialog),{setShowAIDialog:a}=s.useEditorActions(),{data:r,errorMessage:l,errorSql:o}=s.useDashboardCardQuery(t);return e.jsxs("section",{className:"flex justify-between gap-2 p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(os,{}),!n&&e.jsxs(s.Button,{onClick:()=>a(!0),variant:"secondary",size:"sm",children:[e.jsx(ka,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(yt,{sql:r==null?void 0:r.sql,error:l,errorSql:o})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-green-300 px-3 py-1 text-xs font-medium text-black",children:"Preview"}),e.jsx(Es,{}),e.jsx(ks,{variant:"default"})]})]})}function il(){const t=M.useRef(null),n=M.useRef(null),a=s.useEditorStore(i=>i.isShowingVisual),r=s.useEditorStore(i=>i.showAIDialog),l=s.useEditorStore(i=>i.isDevMode);M.useEffect(()=>{var i,d,u,m;r?((i=t.current)==null||i.resize(0),(d=n.current)==null||d.resize(0)):((u=t.current)==null||u.resize(25),(m=n.current)==null||m.resize(25))},[r]);function o(){return e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(Qn,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:a&&!r?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:t,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(Yr,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(Je,{})})]}):e.jsx(Je,{})})]})}function c(){return e.jsx(e.Fragment,{children:e.jsx("div",{className:"grow","data-biz-mode-container":"",children:a?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:n,defaultSize:25,maxSize:30,children:e.jsx(Zr,{})})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{defaultSize:75,maxSize:100,children:e.jsxs(s.ResizablePanelGroup,{direction:"vertical",children:[e.jsxs(s.ResizablePanel,{className:"flex min-h-fit flex-col",minSize:10,defaultSize:20,children:[e.jsx(ol,{}),e.jsx(ll,{})]}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(Je,{})})]})})]}):e.jsx(Je,{})})})}return e.jsx(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:l?o():c()})}function cl(t){s.useAIInteractionStore(z=>z.currentAIContext);const[n,a]=M.useState(""),[r,l]=M.useState(null),{authToken:o,tokenProps:c}=s.useSemaphorContext(),i=s.useEditorStore(z=>{var te;return(te=z==null?void 0:z.card)==null?void 0:te.sql}),d=s.useEditorStore(z=>z.isDevMode),u=s.useEditorStore(z=>{var te;return(te=z==null?void 0:z.card)==null?void 0:te.python}),{setCardPython:m,setCardSql:h,setRunSql:p,switchCardType:g,setQueryConfig:b}=s.useEditorActions(),x=s.useEditorStore(z=>z.currentAssitantScope)||[],j=s.useEditorStore(z=>z.userInputForAI),f=s.useEditorStore(z=>z.triggerAIRun),N=s.useEditorStore(z=>z.card),T=s.useEditorStore(z=>z.selectedDatabaseName),k=s.useEditorStore(z=>z.selectedTableName),C=s.useEditorStore(z=>z.selectedConnectionId),w=s.useEditorStore(z=>z.selectedSchemaName),v=s.useDashboardStore(z=>z.dashboard.aiScopeTables),{errorMessage:E,refetch:y,data:F}=s.useDashboardCardQuery(N),{setTriggerAIRun:I,setCurrentAssitantScope:P,setCardConfig:D}=s.useEditorActions(),{selectedDatamodelName:S,connectionType:L,selectedDatamodelId:O}=s.useEditorAside(),{messages:R,setMessages:A,regenerate:B,error:Y,sendMessage:_,status:Q,addToolResult:X,stop:q,clearError:W}=s.useChat({transport:new s.DefaultChatTransport({api:`${c.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${o==null?void 0:o.accessToken}`}),body:()=>{const z=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",isDevMode:d,aiContext:z.currentAIContext,reasoningEffort:z.reasoningEffort,showReasoning:z.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:z,body:te})=>({body:{...te,messages:s.cleanupIncompleteMessages(z)}})}),onError:z=>{console.log("on error",z)},onToolCall:G,onFinish(){a("")}});M.useEffect(()=>{f&&j&&(_({role:"user",parts:[{type:"text",text:j}]}),I(!1))},[f,j,_,I]);async function G({toolCall:z}){var te,oe,re,J,ce,de,fe,$,K,Z,le,ne,je,xe,We,Ke;if(["createChartFromSql","createForecast"].includes(z.toolName)){const Ue=((te=z.input)==null?void 0:te.sql)??((oe=z.args)==null?void 0:oe.sql),Te=((re=z.input)==null?void 0:re.python)??((J=z.args)==null?void 0:J.python),he=((ce=z.input)==null?void 0:ce.chartType)??((de=z.args)==null?void 0:de.chartType);g(he),h(Ue),m(Te),p(!0),X({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(z.toolName==="getUserSql"){if(!i){X({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"error",message:"No SQL found"}});return}X({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",sql:i,python:u||""}})}else if(z.toolName==="generateQueryConfig"){a("Generating query config...");const Ue=((fe=z.input)==null?void 0:fe.chartType)??(($=z.args)==null?void 0:$.chartType),Te=((K=z.input)==null?void 0:K.queryConfig)??((Z=z.args)==null?void 0:Z.queryConfig);((le=z.input)==null?void 0:le.cardConfig)??((ne=z.args)==null||ne.cardConfig),g(Ue),D(Te),h(void 0),m(void 0);const he=await y();if((je=he==null?void 0:he.data)!=null&&je.error){X({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"error",queryConfig:Te,message:(xe=he==null?void 0:he.data)==null?void 0:xe.error.message}});return}if((We=he==null?void 0:he.data)!=null&&We.records){X({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",queryConfig:Te,message:"The data has been visualized"}});return}X({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",queryConfig:Te,message:"The data has been visualized",records:(Ke=he==null?void 0:he.data)==null?void 0:Ke.records}})}else a("Analyzing...")}function se(z){const te=s.removeFromScopeArray(x,z);V(te)}function V(z){const te=s.sanitizeAIScope(z);P(te),A(oe=>[...oe,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(te)}`}]}])}function U(){const z={databaseName:T||"",schemaName:w||"",tableName:k||"",datamodelId:O||"",datamodelName:s.resolveDatamodelName(S),connectionId:C||"",connectionType:L||""},te=s.dedup([...x,z]);V(te)}function ee(){const z={databaseName:T||"",schemaName:w||"",tableName:k||"",datamodelName:s.resolveDatamodelName(S),connectionId:C||"",connectionType:L||"",datamodelId:O||""};if(!s.isInAiScopeArray([...v||[],...x],z)||x.length===0){const oe=s.dedup([...v||[],...x,z]).filter(re=>re.connectionId===z.connectionId);V(oe)}}const ae=!["ready","error"].includes(Q),ie=s.getErrorMessage(Y);return{messages:R,setMessages:A,sendMessage:_,regenerate:B,isLoading:ae,handleSetAIScope:ee,handleAddCurrentTableToScope:U,removeFromCurrentSelections:se,currentAssitantScope:x,setCurrentAssitantScope:P,stop:q,status:Q,toolStatus:n,llmUsage:r,onFinish:t,errorMessage:ie,clearError:W}}const dl=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Ws(){const t=M.useRef(null),[n,a]=M.useState(!1),[r,l]=M.useState(s.isDevEnv),[o,c]=M.useState(!1),[i,d]=M.useState(!1),u=s.useCurrentAIContext(),{setCurrentAIContext:m}=s.useAIActions(),{clearQueue:h}=s.useQueueActions(),{clearFileAttachments:p}=s.useFileActions(),g=s.useFileAttachments("editor"),b=s.useDashboardStore(K=>K.dashboard.aiContext),x=s.useEditorStore(K=>K.card.dataSource),j=s.useEditorStore(K=>K.actions.setCardSql),f=s.useEditorStore(K=>K.actions.setRunSql),N=s.useEditorStore(K=>K.showAIDialog),T=s.useDashboardStore(K=>K.handleOpenAssistantProfile),{setShowAIDialog:k,setCardPython:C}=s.useEditorActions(),{setDataSource:w}=s.useEditorActions(),{assistantProfile:v}=s.useAssistantProfile(),{messages:E,setMessages:y,sendMessage:F,isLoading:I,stop:P,status:D,llmUsage:S,errorMessage:L,clearError:O}=cl(),[R,A]=M.useState(""),B=K=>{A(K.target.value)},Y=K=>{K.preventDefault();const Z=R.trim();if(!Z&&g.length===0)return;const le=[];Z&&le.push({type:"text",text:Z}),g.forEach(ne=>{ne.data&&le.push({type:"file",mediaType:ne.type,filename:ne.name,url:`data:${ne.type};base64,${ne.data}`})}),F({role:"user",parts:le}),A(""),p("editor"),ee({force:!0})},{visibleMessages:_,hasMoreMessages:Q,totalMessageCount:X,loadMoreMessages:q,resetMessageWindow:W}=s.useMessageWindow(E,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:G,isAtBottom:se,hasNewMessages:V,newMessageCount:U,scrollToBottom:ee,handleScroll:ae,resetNewMessageCount:ie}=s.useAutoScroll(_,{threshold:50,delay:0,dependencies:[D,E.length]});M.useEffect(()=>{var K;N&&((K=t.current)==null||K.focus(),m({selectedEntities:(x==null?void 0:x.selectedEntities)||[]}))},[N,x,m]),s.useAutoSubmitQueue({assistantType:"editor",status:D,isLoading:I,sendMessage:F});const{hasActiveTools:z}=s.useActiveToolStatus(E);function te(K,Z){Z==="sql"?(j(K),f(!0)):Z==="python"&&(C(K),f(!0))}function oe(){var K;(K=b==null?void 0:b.selectedEntities)==null||K[0],d(!0)}function re(){u.selectedEntities.length===0&&m({selectedEntities:(b==null?void 0:b.selectedEntities)||[]})}function J(K){re();const Z={role:"user",parts:[{type:"text",text:K.title+" "+K.subtitle}]};F(Z)}function ce(K){re(),F({role:"user",parts:[{type:"text",text:K}]})}function de(){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/50 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:n,onCheckedChange:a,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:r,onCheckedChange:l,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:c,children:"System Message"})]})]})}function fe(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const $=(R==null?void 0:R.length)===0&&(E==null?void 0:E.filter(K=>K.role==="user").length)===0;return e.jsxs("div",{"data-role":"editor-assistant",className:"flex h-full w-full flex-col justify-between px-6 py-4",children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[fe(),T&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:T,children:(v==null?void 0:v.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[de(),s.isDevEnv,e.jsx(s.IconButton,{tooltip:"Add Context",className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",onClick:oe,children:e.jsx(s.Settings,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",tooltip:"New Chat",onClick:()=>{y([]),h("editor"),O(),W()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",size:"sm",onClick:()=>{k(!1)},children:e.jsx(s.X,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:G,className:"mt-2 flex w-full grow basis-0",onScroll:ae,children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[Q&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:q,className:"text-xs",children:["Load ",Math.min(5,X-_.length)," ","more messages (",X-_.length," ","hidden)"]})}),e.jsx(s.PrintMessages,{messages:_,showTools:r,handleRun:te,showSystemMessage:o}),!z&&e.jsx(s.AssistantStatus,{status:D,errorMessage:L})]})}),!se&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{ee({force:!0}),ie()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),V&&U>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:U>9?"9+":U})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[$&&!v&&e.jsx(s.Placeholders,{onClick:J,placeholders:dl}),e.jsx("div",{children:$&&v&&e.jsx(s.SeedQuestions,{seedQuestions:v.seedQuestions||[],handleSeedQuestionClick:ce})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:t,setInput:A,stop:P,input:R,handleInputChange:B,handleSubmit:K=>{re(),Y(K),ee({force:!0})},isLoading:I,status:D,assistantType:"editor",onFocus:()=>{}})]}),S&&n&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",S.inputTokens," prompt tokens, ",S.outputTokens," ","completion tokens, ",S.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(x==null?void 0:x.selectedEntities)||[],open:i,onOpenChange:d,dataSource:x||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}const Ls=t=>{var I;const{updateCardConfig:n,updateGroupByColumn:a,updateMetricColumn:r,updatePivotByColumn:l,updateSortByColumn:o,removeGroupByColumn:c,removeMetricColumn:i,removePivotByColumn:d,removeSortByColumn:u}=s.useEditorActions(),m=s.useEditorStore(P=>P.card.type),h=t==null?void 0:t.id,p=M.useCallback(P=>{if(!(t!=null&&t.config))return[];switch(P){case"groupBy":return(t.config.groupByColumns||[]).map(D=>({id:D.id,name:D.name,dataType:D.dataType,label:D.label!==void 0?D.label:D.name,qualifiedEntityName:D.qualifiedEntityName,entityId:D.entityId,entityName:D.entityName,entityType:D.entityType,dateFormat:D.dateFormat,customFormat:D.customFormat,granularity:D.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(D=>({id:D.id,name:D.name,dataType:D.dataType,label:D.label!==void 0?D.label:D.name,qualifiedEntityName:D.qualifiedEntityName,entityId:D.entityId,entityName:D.entityName,entityType:D.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(D=>({id:D.id,name:D.name,dataType:D.dataType,label:D.label!==void 0?D.label:D.name,qualifiedEntityName:D.qualifiedEntityName,entityId:D.entityId,entityName:D.entityName,entityType:D.entityType,direction:D.direction}));case"source":return[];default:return[]}},[t]),g=M.useCallback((P,D)=>{if(h)switch(P){case"groupBy":{n(h,{groupByColumns:D});break}case"metrics":{n(h,{metricColumns:D});break}case"pivotBy":{n(h,{pivotByColumns:D});break}case"sortBy":{n(h,{sortByColumns:D});break}}},[h,n]),b=M.useCallback((P,D,S)=>{if(!h)return;const O=p(P)[D];if(O)switch(P){case"groupBy":a(h,O.id,{label:S});break;case"metrics":r(h,O.id,{label:S});break;case"pivotBy":l(h,O.id,{label:S});break;case"sortBy":o(h,O.id,{label:S});break}},[h,p,a,r,l,o]),x=M.useCallback((P,D)=>{if(!h)return;const L=p("metrics")[P];L&&r(h,L.id,{aggregate:D,label:s.getAggregationLabel(L.name,D)})},[h,p,r]),j=M.useCallback((P,D,S)=>{if(!h)return;const O=p("groupBy")[P];if(!O)return;const R={dateFormat:D};D==="custom"&&S?R.customFormat=S:R.customFormat=void 0,a(h,O.id,R)},[h,p,a]),f=M.useCallback((P,D)=>{if(!h)return;const L=p("groupBy")[P];L&&a(h,L.id,{granularity:D})},[h,p,a]),N=M.useCallback((P,D)=>{if(!h)return;const L=p("metrics")[P];L&&r(h,L.id,{aliasTemplate:D})},[h,p,r]),T=M.useCallback((P,D)=>{if(console.log("handleValueAliasesChange",P,D),!h)return;console.log("handleValueAliasesChange",P,D);const L=p("metrics")[P];L&&(console.log("handleValueAliasesChange",D),r(h,L.id,{valueAliases:D}))},[h,p,r]),k=M.useCallback(P=>{h&&n(h,{comparisonType:P})},[h,n]),C=M.useCallback(P=>{h&&n(h,{showTrendline:P})},[h,n]),w=M.useCallback(P=>{h&&n(h,{trendlineWindow:P})},[h,n]),v=M.useCallback(P=>{h&&n(h,{trendlineGranularity:P})},[h,n]),E=M.useCallback(P=>{h&&n(h,{targetValue:P})},[h,n]),y=M.useCallback(P=>{var B;if(!h)return;const D=[...p("groupBy"),...p("pivotBy"),...p("metrics"),...p("sortBy")],S=(B=t==null?void 0:t.config)==null?void 0:B.joinPlan,L=s.validateEntityConsistency(P,D,S);if(!L.isValid){L.showError&&s.showJoinRequiredNotification();return}const O=s.getSmartContainerForField(P,D),R=p(O);if(s.fieldAlreadyExists(P,R))return;const A=s.getNewField(P,O,R);A&&g(O,[...R,A])},[h,(I=t==null?void 0:t.config)==null?void 0:I.joinPlan,p,g]),F=M.useCallback((P,D)=>{if(!h)return;const L=p(P)[D];if(L){if(P!=="sortBy"){const O=p("sortBy"),R=O.filter(A=>!(A.name===L.name&&A.qualifiedEntityName===L.qualifiedEntityName));R.length!==O.length&&n(h,{sortByColumns:R})}switch(P){case"groupBy":c(h,L.id);break;case"metrics":i(h,L.id);break;case"pivotBy":d(h,L.id);break;case"sortBy":u(h,L.id);break}}},[h,p,c,i,d,u,n]);return{getFieldsForContainer:p,setFieldsForContainer:g,updateLabel:b,handleAggregationChange:x,handleDateFormatChange:j,handleGranularityChange:f,handleAliasTemplateChange:N,handleValueAliasesChange:T,removeField:F,handleFieldClick:y,handleKpiComparisonTypeChange:k,handleKpiShowTrendlineChange:C,handleKpiTrendlineWindowChange:w,handleKpiTrendlineGranularityChange:v,handleKpiTargetValueChange:E,cardType:m}};function ul({field:t}){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}),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 ml({field:t}){const{attributes:n,listeners:a,setNodeRef:r,transform:l,transition:o,isDragging:c}=s.useSortable({id:t.id}),[i,d]=M.useState(!1),u=s.useEditorStore(b=>b.card),{handleFieldClick:m}=Ls(u),h={transform:s.CSS.Transform.toString(l),transition:o};s.getDataType(t.dataType);const p=b=>{const x=(b||"").toLowerCase();switch(s.getDataType(x)){case"number":return De;case"date":return s.Calendar;case"boolean":return Le;case"json":return Be;case"geo":return Ye;default:return ve}},g=b=>{const x=(b||"").toLowerCase(),j=s.getDataType(x);return j==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ve,{className:"h-3 w-3"})}):j==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):j==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):j==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Le,{className:"h-3 w-3"})}):j==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Be,{className:"h-3 w-3"})}):j==="geo"?e.jsx("div",{className:"bg-orange -100 flex size-6 shrink-0 items-center justify-center rounded-sm text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Ye,{className:"h-3 w-3"})}):j==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(He,{className:"h-3 w-3"})}):null};return p(t.dataType),e.jsxs("div",{ref:r,style:h,...n,...a,className:`group/container max-w-[265px] overflow-hidden rounded-lg transition-all ${c?"scale-95 opacity-50":"border border-transparent hover:bg-muted"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:()=>m(t),children:[g(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-xs text-foreground/80 hover:text-foreground dark:text-muted-foreground ${i?"whitespace-normal break-words":"truncate"}`,children:t.label||t.name})})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:e.jsx(ul,{field:t})})]})})]}),i&&e.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:e.jsx(s.Card,{className:"",children:e.jsxs(s.CardContent,{className:"space-y-2 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nt,{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(Ga,{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})]})})})]})}function hl(){const[t,n]=M.useState(""),[a,r]=M.useState("all"),l=s.useEditorStore(T=>T.card.dataSource),{columns:o=[],columnGroups:c=[],isLoading:i,error:d}=s.useColumns(),u=o.filter(T=>T.name.toLowerCase().includes(t.toLowerCase())||T.dataType.toLowerCase().includes(t.toLowerCase())||T.qualifiedEntityName&&T.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),m=T=>{if(T.dataType==="number"||T.dataType==="integer"||T.dataType==="float"||T.dataType==="decimal"||T.dataType==="currency")return"metrics";const k=s.getDataType(T.dataType);return["date","string","boolean"].includes(k)?"dimensions":k==="number"?"metrics":"dimensions"},p=(a==="all"?u:u.filter(T=>m(T)===a)).reduce((T,k)=>{const C=k.qualifiedEntityName||"Other Fields";return T[C]||(T[C]={label:s.toLabel(k.entityName),fields:[]}),T[C].fields.push(k),T},{}),b=Object.keys(p),x=u.filter(T=>m(T)==="dimensions").length,j=u.filter(T=>m(T)==="metrics").length,f=u.filter(T=>m(T)==="calculated").length,N=u.length>0;return i?e.jsx("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):d?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] 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:d.message||"Failed to load column data"})]}):!l||!l.selectedEntities||l.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:"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-[calc(100vh-200px)] 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:[o.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:t,onChange:T=>n(T.target.value)}),t&&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:a,onValueChange:T=>r(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:u.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:x})]}),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:j})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(He,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:f})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:b,className:"space-y-2",children:Object.entries(p).map(([T,k])=>{const C=c.find(w=>w.entityName===T)||{entityName:T,label:k.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:C.label||C.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:C.label||C.entityName}),e.jsx(s.Badge,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:k.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:k.fields.map(w=>e.jsx(ml,{field:w},w.id))})})]},T)})}),Object.keys(p).length===0&&o.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:"Try selecting different data sources"})]}),Object.keys(p).length===0&&o.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 xl(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(hl,{})," "]})}function pl({initialJoinPlan:t,availableDataSources:n}){const[a,r]=M.useState(t),[l,o]=M.useState(new Set),c=()=>{const w=a.joins.length>0?Math.max(...a.joins.map(E=>E.sequence))+1:1,v={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:w,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...a,joins:[...a.joins,v]}),o(new Set([...l,v.id]))},i=w=>{r({...a,joins:a.joins.filter(v=>v.id!==w)}),o(new Set([...l].filter(v=>v!==w)))},d=(w,v)=>{var I,P;const E=a.joins.find(D=>D.id===w);if(!E)return;const y={...E,...v},F=a.joins.map(D=>D.id===w?y:D);if((I=y.source)!=null&&I.name&&((P=y.target)!=null&&P.name)&&y.joinKeyGroups[0].keys.length===0){const D=n.find(R=>{var A;return R.name===((A=y.source)==null?void 0:A.name)}),S=n.find(R=>{var A;return R.name===((A=y.target)==null?void 0:A.name)}),L={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(D==null?void 0:D.name)||"",entityName:(D==null?void 0:D.name)||"",entityType:(D==null?void 0:D.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(S==null?void 0:S.name)||"",entityName:(S==null?void 0:S.name)||"",entityType:(S==null?void 0:S.type)||"table"},operator:"="},O=[...y.joinKeyGroups];O[0]={...O[0],keys:[L]},y.joinKeyGroups=O,F[F.findIndex(R=>R.id===w)]=y}r({...a,joins:F})};return{joinPlan:a,expandedJoins:l,setJoinPlan:r,addJoin:c,removeJoin:i,updateJoin:d,moveJoinUp:w=>{const v=a.joins.findIndex(E=>E.id===w);if(v>0){const E=[...a.joins],y={...E[v]},F={...E[v-1]};E[v]=F,E[v-1]=y,E.forEach((P,D)=>{P.sequence=D+1});const I={...a,joins:E};r(I)}},moveJoinDown:w=>{const v=a.joins.findIndex(E=>E.id===w);if(v<a.joins.length-1){const E=[...a.joins],y={...E[v]},F={...E[v+1]};E[v]=F,E[v+1]=y,E.forEach((P,D)=>{P.sequence=D+1});const I={...a,joins:E};r(I)}},toggleJoinExpansion:w=>{const v=new Set(l);v.has(w)?v.delete(w):v.add(w),o(v)},getAvailableSourceEntities:w=>{if(a.joins.length===0)return n;const v=a.joins.findIndex(y=>y.id===w);if(v===0)return n;const E=new Set;return a.baseEntity.name&&E.add(a.baseEntity.name),a.joins.slice(0,v).forEach(y=>{E.add(y.source.name),E.add(y.target.name)}),n.filter(y=>E.has(y.name))},getAvailableTargetEntities:w=>n.filter(v=>v.name!==w),addJoinKeyGroup:w=>{const v=a.joins.find(y=>y.id===w);if(!v)return;const E=[...v.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];d(w,{joinKeyGroups:E})},updateGroupOperator:(w,v,E)=>{const y=a.joins.find(I=>I.id===w);if(!y)return;const F=[...y.joinKeyGroups];F[v]={...F[v],operator:E},d(w,{joinKeyGroups:F})},removeJoinKeyGroup:(w,v)=>{const E=a.joins.find(F=>F.id===w);if(!E)return;const y=[...E.joinKeyGroups];y.splice(v,1),d(w,{joinKeyGroups:y})},addJoinKey:(w,v)=>{const E=a.joins.find(D=>D.id===w);if(!E)return;const y=n.find(D=>D.name===E.source.name),F=n.find(D=>D.name===E.target.name),I=[...E.joinKeyGroups],P={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(y==null?void 0:y.name)||"",entityName:(y==null?void 0:y.name)||"",entityType:(y==null?void 0:y.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(F==null?void 0:F.name)||"",entityName:(F==null?void 0:F.name)||"",entityType:(F==null?void 0:F.type)||"table"},operator:"="};I[v]={...I[v],keys:[...I[v].keys,P]},d(w,{joinKeyGroups:I})},updateJoinKey:(w,v,E,y,F)=>{const I=a.joins.find(O=>O.id===w);if(!I)return;const P=n.find(O=>O.name===I.source.name),D=n.find(O=>O.name===I.target.name),S=[...I.joinKeyGroups],L=S[v].keys[E];y==="sourceColumnName"&&P?S[v].keys[E]={...L,source:{...L.source,name:F}}:y==="targetColumnName"&&D?S[v].keys[E]={...L,target:{...L.target,name:F}}:y==="operator"&&(S[v].keys[E]={...L,operator:F}),d(w,{joinKeyGroups:S})},removeJoinKey:(w,v,E)=>{const y=a.joins.find(I=>I.id===w);if(!y)return;const F=[...y.joinKeyGroups];F[v].keys.splice(E,1),d(w,{joinKeyGroups:F})},generateSQLPreview:()=>{const w=[...a.joins].sort((y,F)=>y.sequence-F.sequence),v=a.baseEntity;if(!v.name)return"SELECT * FROM table -- Please select a base entity";let E=`SELECT *
|
|
334
|
-
FROM ${v.name}`;return
|
|
335
|
-
${
|
|
336
|
-
ON ${P}`}),E},isValidConfiguration:()=>!(!a.baseEntity.name||a.joins.some(y=>!y.source.name||!y.target.name)||a.joins.some(y=>y.joinKeyGroups.some(F=>F.keys.length===0))||a.joins.some(y=>y.joinKeyGroups.some(F=>F.keys.some(I=>!I.source.name||!I.target.name||!I.operator))))}}function fl({joinPlan:t,availableDataSources:n,onSave:a,onRemove:r,onCancel:l}){const{setCardConfig:o}=s.useEditorActions();s.useEditorStore(I=>I.card.config);const{columnGroups:c}=s.useColumns(),{joinPlan:i,expandedJoins:d,setJoinPlan:u,addJoin:m,removeJoin:h,updateJoin:p,moveJoinUp:g,moveJoinDown:b,toggleJoinExpansion:x,getAvailableSourceEntities:j,getAvailableTargetEntities:f,addJoinKeyGroup:N,updateGroupOperator:T,removeJoinKeyGroup:k,addJoinKey:C,updateJoinKey:w,removeJoinKey:v,generateSQLPreview:E,isValidConfiguration:y}=pl({initialJoinPlan:t,availableDataSources:n}),F=I=>{const P=c.find(D=>D.entityName===I);return(P==null?void 0:P.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:i.baseEntity.name,onValueChange:I=>{const P=n.find(D=>D.name===I);u({...i,baseEntity:{connectionId:(P==null?void 0:P.connectionId)||"",connectionType:(P==null?void 0:P.connectionType)||"none",type:(P==null?void 0:P.type)||"table",name:I,database:P==null?void 0:P.database,schema:P==null?void 0:P.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:n.map(I=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:I.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:I.type}),I.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},I.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:E()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{children:["Joins Configuration (",i.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:m,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),i.joins.length===0?e.jsx("div",{className:"rounded-lg border border-dashed py-8 text-center text-muted-foreground",children:e.jsx("p",{children:"No joins configured. Add a join to connect multiple data sources."})}):e.jsx("div",{className:"max-h-[300px] space-y-4 overflow-y-auto",children:i.joins.map(I=>{const P=n.find(L=>L.name===I.source.name),D=n.find(L=>L.name===I.target.name),S=d.has(I.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:I.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",I.sequence,P&&D&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",P.name," → ",D.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g(I.id),disabled:I.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>b(I.id),disabled:I.sequence===i.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>x(I.id),children:S?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>h(I.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),S&&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:I.source.name,onValueChange:L=>{const O=n.find(R=>R.name===L);p(I.id,{source:{connectionId:(O==null?void 0:O.connectionId)||"",connectionType:(O==null?void 0:O.connectionType)||"none",type:(O==null?void 0:O.type)||"table",name:L,database:O==null?void 0:O.database,schema:O==null?void 0:O.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:j(I.id).map(L=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:L.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:L.type}),L.name]})},L.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:I.joinType,onValueChange:L=>p(I.id,{joinType:L}),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:I.target.name,onValueChange:L=>{const O=n.find(R=>R.name===L);p(I.id,{target:{connectionId:(O==null?void 0:O.connectionId)||"",connectionType:(O==null?void 0:O.connectionType)||"none",type:(O==null?void 0:O.type)||"table",name:L,database:O==null?void 0:O.database,schema:O==null?void 0:O.schema}})},disabled:!I.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:I.source.name?f(I.source.name).map(L=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:L.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:L.type}),L.name,L.name===I.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},L.name)):[]})]})]})]}),I.source.name&&I.target.name&&P&&D&&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:()=>N(I.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),I.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:I.joinKeyGroups.map((L,O)=>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 ",O+1]}),O>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:L.operator,onValueChange:R=>T(I.id,O,R),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:()=>k(I.id,O),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[L.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:L.keys.map((R,A)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[A>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:L.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:R.source.name,onValueChange:B=>w(I.id,O,A,"sourceColumnName",B),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:F(I.source.name).map(B=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:B.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:B.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:B.dataType})]})},B.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:R.operator,onValueChange:B=>w(I.id,O,A,"operator",B),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:R.target.name,onValueChange:B=>w(I.id,O,A,"targetColumnName",B),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:F(I.target.name).map(B=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:B.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:B.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:B.dataType})]})},B.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>v(I.id,O,A),children:e.jsx(s.X,{className:"size-3.5"})})]},R.id||A))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>C(I.id,O),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},L.id))})]})]})]},I.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),l()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:l,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>a(i),disabled:!y(),children:"Save"})]})]})}function Ks({children:t,open:n,onOpenChange:a,joinPlan:r,availableDataSources:l,onRemove:o,onSave:c,onCancel:i}){return e.jsxs(s.Dialog,{open:n,onOpenChange:a,children:[e.jsxs(s.DialogContent,{className:"max-w-4xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Join Configuration"}),e.jsx(s.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(fl,{joinPlan:r,availableDataSources:l,onSave:c,onCancel:i,onRemove:o})]}),t]})}function gl({joins:t,baseEntityId:n,availableDataSources:a,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[t.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const l=[...t].sort((c,i)=>c.sequence-i.sequence),o=a.find(c=>c.name===n);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:o==null?void 0:o.type}),e.jsx("span",{className:"text-xs font-medium",children:o==null?void 0:o.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),l.map(c=>{const i=a.find(d=>d.name===c.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name})]})]},c.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",t.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...t].sort((l,o)=>l.sequence-o.sequence).map((l,o)=>{const c=a.find(d=>d.name===l.source.name),i=a.find(d=>d.name===l.target.name);return e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted p-2 text-left",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:o+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:l.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[c==null?void 0:c.name," → ",i==null?void 0:i.name]}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto text-xs",children:[l.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)," ","condition",l.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)>1?"s":""]})]},l.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function jl(){var m,h;const t=s.useEditorStore(p=>p.card),n=s.useEditorStore(p=>p.actions.updateCardConfig),a=((m=t==null?void 0:t.config)==null?void 0:m.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[r,l]=M.useState(!1),o=((h=t==null?void 0:t.dataSource)==null?void 0:h.selectedEntities)||[],c=p=>{n(t.id,{...t==null?void 0:t.config,joinPlan:p}),l(!1)},i=()=>{n(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},d=()=>{l(!1)},u=()=>{const p=[...a.joins].sort((x,j)=>x.sequence-j.sequence),g=a.baseEntity;if(!g.name)return"SELECT * FROM table -- Please select a base entity";let b=`SELECT *
|
|
337
|
-
FROM ${g.name}`;return p.forEach(x=>{const j=o.find(
|
|
332
|
+
`;y(_)}function M(){return e.jsxs(e.Fragment,{children:[r&&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($n,{jsonString:JSON.stringify(u,null,2)})})}),u&&u.length>0&&e.jsx(s.Button,{variant:"ghost",onClick:()=>l(!r),className:"absolute bottom-0 right-6 size-7 p-1",children:r?e.jsx(s.X,{className:"size-3.5 text-muted-foreground"}):e.jsx(s.Filter,{className:"size-3.5 text-muted-foreground"})})]})}function B(){return e.jsxs(s.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(s.ResizablePanel,{id:"1",order:1,defaultSize:n?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(Gn,{})}),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(Yn,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function Y(){return e.jsxs("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||S,onClick:()=>{L()},className:"h-8 shrink-0",size:"sm",children:[N||S?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(yt,{errorSql:T,sql:v==null?void 0:v.sql,error:O,onDebugWithAssistant:R}),e.jsx(os,{}),e.jsx(s.Toggle,{pressed:n,onPressedChange:_=>a(_),className:"h-8",size:"sm",variant:"outline",children:e.jsx(Un,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:c,onClick:()=>{E(!0)},className:"h-9 w-full cursor-text px-3 text-left text-sm text-muted-foreground",children:c?"":"Type your question..."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Es,{}),e.jsx(ks,{})]})]})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsxs("div",{className:"relative flex grow justify-between overflow-y-scroll",children:[B(),M()]}),Y()]})}const Xn=[{value:"table",label:"Table",icon:s.Table2},{value:"aggregateTable",label:"Aggregate",icon:s.Layers},{value:"pivotTable",label:"Pivot",icon:rs}];function Zn({className:t}){const n=s.useEditorStore(d=>d.card),{setCardType:a,setCard:r,updateCardInFrame:l}=s.useEditorActions(),o=["table","aggregateTable","pivotTable"].includes(n.type),c=s.hasValidCardConfig(n.config);if(!o||!c)return null;const i=d=>{var m;const u=d;if(u==="aggregateTable"&&((m=n.config)!=null&&m.pivotByColumns)&&n.config.pivotByColumns.length>0){const h={...n,type:u,config:{...n.config,pivotByColumns:[]}};r(h),l(h)}else{a(u);const h={...n,type:u};l(h)}};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsx(s.RadioGroup,{value:n.type,onValueChange:i,className:"flex flex-row items-center justify-between gap-1 rounded-lg border p-1",children:Xn.map(d=>{const u=d.icon,m=n.type===d.value;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(s.RadioGroupItem,{value:d.value,id:`table-type-${d.value}`,className:"peer sr-only"}),e.jsxs(s.Label,{htmlFor:`table-type-${d.value}`,className:s.cn("flex cursor-pointer items-center gap-1.5 rounded-md px-3 py-1 text-sm font-medium transition-all",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 er({card:t}){var E,k,C,D,v,N,S,F,I,P,T;const[n,a]=A.useState(!1),[r,l]=A.useState([]),{authToken:o}=s.useSemaphorContext(),{theme:c}=s.useTheme(),i=s.getTokenParams(o==null?void 0:o.accessToken),d=s.useDashboardStore(w=>w.themeStyle),u={mode:c||"system",colors:((k=(E=d==null?void 0:d.chart)==null?void 0:E.dataset)==null?void 0:k.backgroundColor)||[]};(C=t.customCardPreferences)!=null&&C.inputData;const{getCard:m}=s.useCustomVisual(((D=t.customCardPreferences)==null?void 0:D.url)||""),h=((v=t.customCardPreferences)==null?void 0:v.visualType)||"single",p=s.useEditorStore(w=>w.frame),{setCustomCardPreferences:g}=s.useEditorActions(),{data:b}=s.useDashboardCardQuery(t),x=A.useCallback((w,L)=>{l(O=>({...O,[w]:L}))},[]);if(!((N=t.customCardPreferences)!=null&&N.componentName))return null;const j=m((S=t.customCardPreferences)==null?void 0:S.componentName);function f(w){a(w)}const y=Object.keys(((F=t.customCardPreferences)==null?void 0:F.dataInputCardIds)||{}).map(w=>{var R,M,B;const L=(M=(R=t.customCardPreferences)==null?void 0:R.dataInputCardIds)==null?void 0:M[w].cardId,O=(B=p==null?void 0:p.cards)==null?void 0:B.find(Y=>Y.id===L);return O||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(A.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[j&&h==="single"&&e.jsx(j,{editing:!0,params:i,theme:u,settings:(I=t.customCardPreferences)==null?void 0:I.settings,onDataChange:x,data:(b==null?void 0:b.records)||[]}),j&&h==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((P=t.customCardPreferences)==null?void 0:P.dataInputCardIds)||{}).map(w=>{var R,M,B;const L=(M=(R=t.customCardPreferences)==null?void 0:R.dataInputCardIds)==null?void 0:M[w].cardId,O=(B=p==null?void 0:p.cards)==null?void 0:B.find(Y=>Y.id===L);if(O)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:f,onDataChange:x,dataInputIndex:w,card:O},O.id+w)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(j,{theme:u,onDataChange:x,settings:y.map(w=>{var L;return(L=w==null?void 0:w.customCardPreferences)==null?void 0:L.settings}),data:y.map(w=>w!=null&&w.id?r==null?void 0:r[w.id]:[])})})]})]},(T=t.customCardPreferences)==null?void 0:T.componentName)})}function St({className:t,...n}){var N;const a=s.useEditorStore(S=>S.card),r=s.isExplorerCard(a),l=((N=a.customCardPreferences)==null?void 0:N.showCardHeader)??!0,o=s.useEditorStore(S=>S.frame),c=s.useDashboardStore(S=>S.dashboard.filters),i=s.useEditorStore(S=>S.actions.setRunSql),{updateFilter:d}=s.useDashboardActions(),u=c==null?void 0:c.find(S=>S.id===o.filterId),{data:m,isLoading:h,isFetching:p,errorMessage:g,pagination:b}=s.useDashboardCardQuery(a),{setCard:x,updateCardInFrame:j}=s.useEditorActions(),{data:f}=s.useTopoJson(a),y=A.useMemo(()=>{var S;return a.type!=="pivotTable"||!((S=m==null?void 0:m.records)!=null&&S.length)?null:{records:m.records,columnSubtotalMeta:m.columnSubtotalMeta,subtotalColumns:m.subtotalColumns||[],pivotSchema:m.pivotSchema||[],groupByColumns:m.groupByColumns}},[a.type,m==null?void 0:m.records,m==null?void 0:m.columnSubtotalMeta,m==null?void 0:m.subtotalColumns,m==null?void 0:m.pivotSchema,m==null?void 0:m.groupByColumns]),E=s.usePivotTableConfig(a,y),k=(S,F)=>{var P,T;const I={...a,paginationConfig:{page:S+1,pageSize:F}};x(I),j(I),a.sql&&((T=(P=a.preferences)==null?void 0:P.tablePrefs)!=null&&T.enableDevModePagination)&&i(!0)},C=A.useMemo(()=>!a.id||!(m!=null&&m.records)?null:s.createChartConfig({card:a,data:m==null?void 0:m.records,cardType:a.type,queryConfig:a.queryConfig,customCfg:a.customCfg,preferences:a.preferences,topoJson:f}),[a.id,m==null?void 0:m.records,a.type,a.queryConfig,a.customCfg,a.preferences,f]);function D(S){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(er,{card:S})})}function v(){if(m!=null&&m.records&&(m==null?void 0:m.records.length)===0&&!h&&!p)return g?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.SearchX,{className:"size-8 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r?"Error fetching data. Please check your chart configuration":"Error fetching data. Please check your SQL or Python code."})]}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((h||p)&&a.type!=="table")return e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!a.id)return null;if(a.type==="custom")return D(a);if(!["table","pivotTable","aggregateTable","custom"].includes(a.type)&&C)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:h||p?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:C})});if(a.type==="table")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:a,data:(m==null?void 0:m.records)||[],paginationMetadata:b,onPaginationChange:k,isLoading:h||p})});if(a.type==="pivotTable"&&E)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.PivotTableTanstack,{card:a,data:E.data,options:E.options,onAggregationChange:S=>{const F=s.handleAggregationChange(S,a.config),I={...a,config:F};x(I),j(I)},onAggregationLabelChange:S=>{const F=s.handleAggregationLabelChange(S,a.config),I={...a,config:F};x(I),j(I)}})});if(a.type==="aggregateTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.AggregateTable,{card:a,data:(m==null?void 0:m.records)||[],groupByColumns:m==null?void 0:m.groupByColumns,pivotSchema:m==null?void 0:m.pivotSchema,paginationMetadata:b,onPaginationChange:k,onAggregationChange:S=>{const F=s.handleAggregationChange(S,a.config),I={...a,config:F};x(I),j(I)},isLoading:h||p})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...n,children:[l&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-5",children:[e.jsx(s.CardTitle,{className:"text-base",children:e.jsx(s.EditableText,{value:a.title,onSave:S=>x({...a,title:S}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(Zn,{})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:a.description||"",onSave:S=>x({...a,description:S}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),u&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:u.title||u.column,onSave:S=>d({...u,title:S}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:u})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:v()})]})}const ps=({language:t,value:n,onChange:a,readonly:r})=>e.jsx(s.Ft,{className:"h-full w-full overflow-hidden text-xs",theme:"default",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,lineHeight:16,renderLineHighlight:"none",readOnly:r},defaultLanguage:t,value:n,onChange:a}),sr=()=>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."})]})]}),tr=({customCode:t,cardCustomCfgString:n,mergedConfig:a,onConfigChange:r,onCodeChange:l})=>e.jsxs(s.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(s.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(s.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(s.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(s.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(s.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ps,{language:"json",value:a,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ps,{readonly:!0,language:"json",value:n,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ps,{language:"javascript",value:t,onChange:l})})]}),ar=({error:t,hasCardCustomConfig:n,onReset:a,onApply:r,onClose:l})=>e.jsxs(s.DialogFooter,{className:"flex items-center",children:[e.jsx(s.Label,{className:"mr-2 text-red-500",children:t}),e.jsx(s.Button,{disabled:!n,onClick:a,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:l,variant:"outline",children:"Close"})]});function nr(){const[t,n]=A.useState(!1),[a,r]=A.useState(""),[l,o]=A.useState(""),[c,i]=A.useState(""),[d,u]=A.useState(""),m=s.useEditorStore(C=>C.card),h=s.useEditorStore(C=>C.card.customCfg),p=h?JSON.stringify(h,null,2):"",{data:g}=s.useDashboardCardQuery(m),{data:b}=s.useTopoJson(m),{setCardCustomCfg:x,setCustomVisualCode:j}=s.useEditorActions(),f=C=>{var D,v;return JSON.stringify({...C,data:{...C.data,datasets:(v=(D=C.data)==null?void 0:D.datasets)==null?void 0:v.map(N=>({...N,data:[]}))}},null,2)},y=()=>{var D,v;if(!((D=g==null?void 0:g.records)!=null&&D.length))return;const C=s.createChartConfig({card:m,data:g.records,cardType:m.type,queryConfig:m.queryConfig,preferences:m.preferences,topoJson:b});if(C){r(f(C)),i(((v=m.preferences)==null?void 0:v.customVisualCode)||"");const N=s.merge(C,h);o(f(N))}},E=()=>{try{if(c&&j(c),l){const C=JSON.parse(l),D=s.getObjectDiff(JSON.parse(a),C);x(D),u("")}}catch{u("Invalid JSON configuration")}},k=Object.keys(h||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:n,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:y,className:k?"":"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(sr,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(St,{className:"w-1/2 rounded shadow-none"})}),e.jsx(tr,{customCode:c,cardCustomCfgString:p,mergedConfig:l,onConfigChange:C=>o(C??""),onCodeChange:C=>i(C??"")})]}),e.jsx(ar,{error:d,hasCardCustomConfig:!!h,onReset:()=>{o(a),x(null)},onApply:E,onClose:()=>n(!1)})]})]})}function is(t){const[n,a]=A.useState(null);return n}function wt(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),{data:a,isLoading:r,isFetching:l,isError:o}=s.useQuery({queryKey:["plugins",t==null?void 0:t.accessToken],queryFn:()=>s.getPlugins(n.apiServiceUrl,t==null?void 0:t.accessToken)});return{data:a,isLoading:r,isFetching:l,isError:o}}function Dt(){const{data:t,isLoading:n,isError:a}=wt(),r=s.useQueries({queries:((t==null?void 0:t.plugins)||[]).map(i=>({queryKey:["manifest",i.value],queryFn:()=>s.loadManifest(i.value),enabled:!!i.value,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:d=>Math.min(1e3*2**d,3e4)}))}),l=[];let o=n,c=a;return r.forEach((i,d)=>{var u;if(i.isLoading&&(o=!0),i.isError&&(c=!0),i.data&&((u=t==null?void 0:t.plugins)!=null&&u[d])){const m=t.plugins[d],h=i.data.visuals.map(p=>({name:p.name,pluginName:m.label,componentType:p.componentType,pluginType:m.type,icon:p.icon,chartType:p.chartType,url:m.value}));l.push(...h)}}),{data:l,isLoading:o,isError:c}}function rr({onChartTypeChange:t}){const{setCardCustomCfg:n,setCardPreferences:a,setCardType:r,setCustomCardPreferences:l}=s.useEditorActions(),{data:o,isLoading:c,isError:i}=Dt(),d=A.useCallback((u,m)=>{n(null),a({}),r(u),m&&l({type:"component",visualType:"single",url:m.url,componentName:m.name,icon:m.icon}),t==null||t()},[n,a,r,l,t]);return c?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading custom visuals..."})})]}):i?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-destructive",children:"Failed to load custom visuals"})})]}):!o||o.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:o.map((u,m)=>e.jsx(lr,{text:u.name,onClick:()=>d("custom",u),icon:u.icon},`${u.url}-${u.name}-${m}`))})]})}const lr=({text:t,icon:n,onClick:a})=>{const r=is(),l=t.charAt(0).toUpperCase();return e.jsx(s.IconButton,{onClick:a,tooltip:t,children:r?e.jsx(r,{className:"h-4 w-4"}):l})};function Tt({onChartTypeChange:t,iconClassName:n}){const{setCardType:a,setCardPreferences:r,setIsDevMode:l}=s.useEditorStore(m=>m.actions),{setCardCustomCfg:o,setCustomCardPreferences:c,setQueryConfig:i}=s.useEditorActions();function d(m,h){o(null),r({}),a(m),["custom","text","map"].includes(m)&&(l(!0),i(void 0)),t==null||t()}const u=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(s.IconButton,{openDelay:u,tooltip:"Table",onClick:()=>d("table"),className:"h-10 p-4",children:e.jsx(s.Table2,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bar Chart",onClick:()=>d("bar"),className:"h-10 p-4",children:e.jsx(s.ChartColumnIncreasing,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Line Chart",onClick:()=>d("line"),className:"h-10 p-4",children:e.jsx(s.ChartLine,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Bar Chart",onClick:()=>d("stackedBar"),className:"h-10 p-4",children:e.jsx(s.ChartColumnStacked,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Line Chart",onClick:()=>d("stackedLine"),className:"h-10 p-4",children:e.jsx(s.MdStackedLineChart,{className:s.cn("size-5",n),strokeWidth:0})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Scatter Chart",onClick:()=>d("scatter"),className:"h-10 p-4",children:e.jsx(s.ChartScatter,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bubble Chart",onClick:()=>d("bubble"),className:"h-10 p-4",children:e.jsx(s.TbChartBubble,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Pie Chart",onClick:()=>d("pie"),className:"h-10 p-4",children:e.jsx(s.ChartPie,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Doughnut Chart",onClick:()=>d("doughnut"),className:"h-10 p-4",children:e.jsx(s.Donut,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Funnel Chart",onClick:()=>d("funnel"),className:"h-10 p-4",children:e.jsx(s.TbChartFunnel,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Radar Chart",onClick:()=>d("radar"),className:"h-10 p-4",children:e.jsx(s.Radar,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Polar Area Chart",onClick:()=>d("polarArea"),className:"h-10 p-4",children:e.jsx(s.PiChartPolar,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Tornado Chart",onClick:()=>d("tornado"),className:"h-10 p-4",children:e.jsx(s.Tornado,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{tooltip:"Range Chart",onClick:()=>d("range"),className:"h-10 p-4",children:e.jsx(s.ChartNoAxesGantt,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"KPI",onClick:()=>d("kpi"),className:"h-10 p-4",children:e.jsx(s.TiSortNumerically,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Text",onClick:()=>d("text"),className:"h-10 p-4",children:e.jsx(s.BookType,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{tooltip:"Map",onClick:()=>d("map"),className:"h-10 p-4",children:e.jsx(s.Map,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Custom",onClick:()=>d("custom"),className:"h-10 p-4",children:e.jsx($e,{className:s.cn("size-5",n)})})]})}function or({chartType:t,className:n,customIcon:a,componentName:r}){const l=is();switch(t){case"bar":return e.jsx(s.ChartColumnIncreasing,{className:n});case"line":return e.jsx(s.ChartLine,{className:n});case"pie":return e.jsx(s.ChartPie,{className:n});case"radar":return e.jsx(s.Radar,{className:n});case"scatter":return e.jsx(s.ChartScatter,{className:n});case"bubble":return e.jsx(s.TbChartBubble,{className:n});case"doughnut":return e.jsx(s.Donut,{className:n});case"stackedBar":return e.jsx(s.ChartColumnStacked,{className:n});case"stackedLine":return e.jsx(s.MdStackedLineChart,{className:n});case"polarArea":return e.jsx(s.PiChartPolar,{className:n});case"funnel":return e.jsx(s.TbChartFunnel,{className:n});case"tornado":case"pyramid":return e.jsx(s.Tornado,{className:n});case"range":return e.jsx(s.ChartNoAxesGantt,{className:n});case"kpi":return e.jsx(s.TiSortNumerically,{className:n});case"text":return e.jsx(ve,{className:n});case"map":return e.jsx(s.Map,{className:n});case"custom":return a&&l?e.jsx(l,{className:n}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx($e,{className:n});default:return e.jsx(s.Table2,{className:n})}}function kt({variant:t="ghost"}){var o,c;const[n,a]=A.useState(!1),r=s.useEditorStore(i=>i.card),l=r.type;return s.useDashboardStore(i=>i.isVisualEditing),e.jsxs(s.Popover,{open:n,onOpenChange:a,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(or,{className:"size-4",chartType:l,customIcon:(o=r.customCardPreferences)==null?void 0:o.icon,componentName:(c=r.customCardPreferences)==null?void 0:c.componentName})})}),e.jsxs(s.PopoverContentCustom,{onOpenAutoFocus:i=>i.preventDefault(),className:"z-[51] w-72 p-1",children:[e.jsx(Tt,{onChartTypeChange:()=>a(!1)}),e.jsx(rr,{onChartTypeChange:()=>a(!1)})]})]})}function ir({error:t,className:n="",textClassName:a="",copyButtonClassName:r=""}){const[l,o]=A.useState(!1),c=A.useRef(null),i=A.useRef(!1);function d(){t&&!i.current&&navigator.clipboard.writeText(t)}function u(p){(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),d())}function m(){const p=window.getSelection();if(p&&p.toString().trim()!==""){const g=p.toString();navigator.clipboard.writeText(g),o(!0),i.current=!0,setTimeout(()=>{o(!1),i.current=!1},1e3)}else i.current=!1}function h(){o(!1),i.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${n}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:c,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${a}`,onClick:d,onKeyDown:u,onMouseUp:m,onMouseDown:h,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),l&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function cr(){const t=s.useEditorStore(o=>{var c,i;return(i=(c=o.card.preferences)==null?void 0:c.chartOptions)==null?void 0:i.indexAxis}),n=s.useEditorStore(o=>o.card.type),{setChartOrientation:a}=s.useEditorStore(o=>o.actions);function r(){return e.jsx(s.IconButton,{onClick:()=>{a(t==="x"||t===void 0?"y":"x")},tooltip:"Chart Orientation",children:t==="x"||t===void 0?e.jsx(Vs,{className:"size-4"}):e.jsx(_s,{className:"size-4"})})}function l(){return e.jsx(s.IconButton,{onClick:()=>{a(t==="y"||t===void 0?"x":"y")},tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(Vs,{className:"size-4"}):e.jsx(_s,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?l():r()})}function dr({className:t}){var p,g,b,x,j,f,y,E;const n=s.useEditorStore(k=>k.card),{setCardPreferences:a,updateCardInFrame:r,setCard:l}=s.useEditorActions(),[o,c]=A.useState(!1),i=((g=(p=n.preferences)==null?void 0:p.displayOptions)==null?void 0:g.showFilterInfo)??!0,d=((x=(b=n.preferences)==null?void 0:b.displayOptions)==null?void 0:x.showCardToolbar)??!0,u=((f=(j=n.preferences)==null?void 0:j.displayOptions)==null?void 0:f.showChrome)??!0,m=((E=(y=n.preferences)==null?void 0:y.displayOptions)==null?void 0:E.allowScroll)??!0,h=(k,C)=>{var N;const D={...n.preferences,displayOptions:{...(N=n.preferences)==null?void 0:N.displayOptions,[k]:C}};a(D);const v={...n,preferences:D};l(v),r(v)};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsxs(s.DropdownMenu,{modal:!1,open:o,onOpenChange:c,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{className:"h-8 w-8 p-0",tooltip:"Display Options",children:e.jsx(at,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(s.DropdownMenuLabel,{children:"Display Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx("div",{className:"px-2 py-1.5",children:e.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"Changes apply to dashboard view only"})}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:i,onCheckedChange:k=>{h("showFilterInfo",k)},onSelect:k=>k.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:k=>{h("showCardToolbar",k)},onSelect:k=>k.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:k=>{h("showChrome",k)},onSelect:k=>k.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:k=>{h("allowScroll",k)},onSelect:k=>k.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 Et(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>c.isShowingVisual),a=s.useEditorStore(c=>{var i,d;return(d=(i=c.card)==null?void 0:i.preferences)==null?void 0:d.chartOptions}),r=s.getChartGridStyle(a),{setChartGrid:l}=s.useEditorActions();function o(){const c=["xy","none","x","y"],d=(c.indexOf(r)+1)%c.length;l(c[d])}return n?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(cr,{})}),!["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:o,children:[(r==="xy"||!r)&&e.jsx(rs,{className:"size-4"}),r==="x"&&e.jsx(ma,{className:"size-4"}),r==="y"&&e.jsx(Pa,{className:"size-4"}),r==="none"&&e.jsx(Va,{className:"size-4"})]}),e.jsx(dr,{})]}):null}function ur(){const t=s.useEditorStore(b=>b.frame),n=s.useEditorStore(b=>b.card),{setFrame:a,setActiveTabCardId:r,setCard:l,updateCardInFrame:o}=s.useEditorActions(),c=(b,x)=>{b.dataTransfer.setData("tabIndex",x.toString())},i=b=>{b.preventDefault()},d=(b,x)=>{const j=b.dataTransfer.getData("tabIndex");if(j===x.toString())return;const f=Array.from(t.cards),[y]=f.splice(parseInt(j),1);f.splice(x,0,y),a({...t,cards:f})};function u(b){const x=t.cards.filter(y=>y.id!==b),j=x[0],f={...t,cards:x,activeCardId:j.id};a(f),r(j.id),l(j)}function m(b,x){const j={...t,cards:[...t.cards,x],activeCardId:b.id};a(j),r(x.id)}function h(){const b={...n,id:s.v4(),title:`${n.title} Copy`,tabTitle:`${n.tabTitle||n.title} Copy`};m(n,b)}function p(b){const x={dataSource:b.dataSource,connectionId:b.connectionId,lastSelectedDatabase:b.lastSelectedDatabase,lastSelectedSchema:b.lastSelectedSchema,lastSelectedTable:b.lastSelectedTable,lastSelectedDatamodelId:b.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};m(b,x)}function g(b,x){return b.cards.length===1&&(x.displayTab===!0||x.displayTab===void 0)||b.activeCardId!==x.id&&(x.displayTab===!0||x.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const j=x.displayTab===void 0?!1:!x.displayTab;l({...x,displayTab:j}),o({...x,displayTab:j})},children:x.displayTab===!0||x.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(pa,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(s.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[t.cards.map((b,x)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:j=>c(j,x),onDragOver:i,onDrop:j=>d(j,x),className:"",value:b.id,children:[g(t,b),e.jsx(s.Editable,{enabled:t.activeCardId===b.id,text:b.tabTitle||b.title,onSave:j=>{l({...n,tabTitle:j}),o({...n,tabTitle:j})},children:b.tabTitle||b.title},b.id),t.activeCardId===b.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>u(b.id)})]},b.id)),e.jsx(s.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>p(n),children:e.jsx(s.Plus,{className:"h-4 w-4"})}),e.jsx(s.Button,{className:"invisible ml-1 h-8 px-2 hover:bg-muted-foreground/50 group-hover:visible",variant:"outline",onClick:h,children:e.jsx(s.CopyPlus,{className:"h-4 w-4"})})]})})}function It(){const t=s.useEditorStore(x=>x.frame),n=s.useEditorStore(x=>x.card),a=s.useEditorStore(x=>x.isSqlRunning),r=s.useEditorStore(x=>x.isDevMode),{setFrame:l,setActiveTabCardId:o,setCard:c,setIsDevMode:i,setRunSql:d}=s.useEditorActions(),{data:u,isLoading:m,isFetching:h}=s.useDashboardCardQuery(n);function p(x){const j=t.cards.find(f=>f.id===x);if(j!=null&&j.sql){r||i(!0),o(x);return}if(j!=null&&j.queryConfig){r&&i(!1),g(x),o(x);return}r||g(x),o(x)}function g(x){const j={...t,cards:t.cards.map(y=>y.id===n.id?n:y),activeCardId:x};l(j);const f=j.cards.find(y=>y.id===x);f.sql&&d(!0),c(f)}function b(){return n.type==="kpi"?m||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border border-border",children:e.jsx(s.KPICard,{card:n,data:u==null?void 0:u.records,isPending:m||h})})}):n.type==="text"?m||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:a,card:n,data:u==null?void 0:u.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(St,{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(x=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:x.id,children:b()},x.id)),e.jsx(ur,{})]})}function Je({children:t}){var k,C;s.useEditorStore(D=>D.frame);const n=s.useEditorStore(D=>D.card),a=s.useEditorStore(D=>D.isDevMode),r=s.useEditorStore(D=>D.isShowingVisual),l=s.useDashboardStore(D=>D.isVisualEditing),o=s.useEditorStore(D=>D.pythonStdOut);s.useEditorStore(D=>D.actions.setRunSql);const{setFrame:c,setCard:i,setActiveTabCardId:d,runAssistant:u,setIsDevMode:m,setCardPreferences:h}=s.useEditorActions(),{data:p,isLoading:g,isFetching:b,errorMessage:x,refetch:j}=s.useDashboardCardQuery(n);function f(){const D=JSON.stringify(p==null?void 0:p.records,null,2),v=new Blob([D],{type:"application/json"}),N=URL.createObjectURL(v),S=document.createElement("a");S.href=N,S.download=`${n.title}.json`,S.click()}function y(){const v=[Object.keys(p==null?void 0:p.records.reduce((I,P)=>({...I,...P}),{})).join(","),...((p==null?void 0:p.records)||[]).map(I=>Object.values(I).join(","))].join(`
|
|
333
|
+
`),N=new Blob([v],{type:"text/csv"}),S=URL.createObjectURL(N),F=document.createElement("a");F.href=S,F.download=`${n.title}.csv`,F.click()}function E(){const D=`Can you get the documentation for ${n.type} chart?`;u(D)}return n?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[r&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(kt,{}),l&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:E,children:e.jsx(oa,{className:"size-4"})}),!["table","custom"].includes(n.type)&&l&&e.jsx(nr,{})]}),!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:y,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:f,children:e.jsx(ga,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(p==null?void 0:p.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(Et,{})]}),n.type==="table"&&n.sql&&!s.hasValidCardConfig(n.config)&&e.jsxs("div",{className:"mr-2 flex items-center gap-3",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((C=(k=n.preferences)==null?void 0:k.tablePrefs)==null?void 0:C.enableDevModePagination)??!1,onCheckedChange:D=>{var v;h({...n.preferences,tablePrefs:{...(v=n.preferences)==null?void 0:v.tablePrefs,enableDevModePagination:D}}),j()}}),e.jsx(s.Label,{htmlFor:"pagination",children:"Paginate Results"})]}),a&&e.jsx(hr,{})]}),r?e.jsx(It,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[o&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:o&&e.jsx(mr,{})}),e.jsx(s.ResizableHandle,{})]}),e.jsxs(s.ResizablePanel,{id:"2",order:2,minSize:10,className:s.cn("relative flex h-full min-h-0 w-full flex-1 basis-0",{"px-6":o}),children:[(p==null?void 0:p.records)&&(p==null?void 0:p.records.length)>0&&e.jsx(s.TableVisual,{card:n,data:(p==null?void 0:p.records)||[]}),x&&e.jsx(ir,{error:x})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function mr(){const t=s.useEditorStore(a=>a.pythonStdOut);if(!t)return null;const n=t.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(s.ScrollArea,{className:"overflow-y-auto pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:n}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function hr(){const t=s.useEditorStore(a=>a.isShowingVisual),n=s.useEditorStore(a=>a.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(s.SmallSwitch,{checked:t,onCheckedChange:()=>n(!t),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function Ce({defaultValue:t,label:n,options:a,value:r,onValueChange:l,className:o,icon:c,showPlaceholderLabel:i=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:l,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",o),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),i&&e.jsx(s.SelectValue,{placeholder:n})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:n}),a.map(d=>e.jsx(s.SelectItem,{value:d.value,children:d.label},d.value))]})})]})}function xr(){var x,j;const t=s.useEditorStore(f=>f.card.customCardPreferences),{data:n}=wt(),a=(n==null?void 0:n.plugins)||[],r=s.useEditorStore(f=>f.card),l=s.useEditorStore(f=>f.frame),o=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:c}=s.useEditorActions(),{components:i,manifest:d}=s.useCustomVisual((t==null?void 0:t.url)||""),u=(x=d==null?void 0:d.visuals)==null?void 0:x.find(f=>f.name===(t==null?void 0:t.componentName));function m(f,y){if(!t)return;const k={...(t==null?void 0:t.dataInputCardIds)||{},[f]:{cardId:y,hookRef:null}};c({...t,dataInputCardIds:k})}function h(f){var E,k;const y=(E=l==null?void 0:l.cards)==null?void 0:E.filter(C=>{var D;return((D=C==null?void 0:C.customCardPreferences)==null?void 0:D.visualType)!=="multiple"}).map(C=>({value:C.id,label:C.tabTitle||C.title}));return e.jsx("div",{className:"space-y-2",children:(k=f==null?void 0:f.dataInputs)==null?void 0:k.map((C,D)=>{var v,N;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:C}),e.jsx(Ce,{className:"col-span-6 h-8 w-full justify-between",label:"",options:y||[],value:((N=(v=t==null?void 0:t.dataInputCardIds)==null?void 0:v[D])==null?void 0:N.cardId)||"",onValueChange:S=>m(D,S)})]},D+Math.random())})})}function p(f,y,E=[],k=""){var C,D;return t?f==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((C=t==null?void 0:t.settings)==null?void 0:C[y])||k,onChange:v=>{c({...t,settings:{...t==null?void 0:t.settings,[y]:v.target.value}})}},y):f==="select"?e.jsx(Ce,{className:"h-8 w-full",label:"",options:E,value:((D=t==null?void 0:t.settings)==null?void 0:D[y])||k,onValueChange:v=>{c({...t,settings:{...t==null?void 0:t.settings,[y]:v}})}}):null:null}function g(f){const y=Object.entries((f==null?void 0:f.settings)||{});return e.jsx("div",{className:"space-y-3",children:y.map(([E,k])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:k.title}),p(k.ui,E,k.options,k.defaultValue)]},E))})}function b(f){t&&c({...t,visualType:f,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(Ce,{icon:e.jsx(la,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:a,value:(t==null?void 0:t.url)||"",onValueChange:f=>c({...t||{url:"",componentName:""},url:f})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:o,onValueChange:b,children:e.jsxs(s.TabsList,{className:"h-9 w-full",children:[e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&e.jsx(e.Fragment,{children:i&&e.jsx(Ce,{icon:e.jsx(ha,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(i==null?void 0:i.filter(f=>f.type===o).map(f=>({value:f.name,label:f.name})))||[],value:t.componentName,onValueChange:f=>{console.log("changing value",f),c({...t,componentName:f})}})})]})})]}),((j=r==null?void 0:r.customCardPreferences)==null?void 0:j.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{children:[u&&u.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:h(u)})]}),u&&u.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:g(u)})})]})]})]})}function Oe(){const[t,n]=A.useState([]),a=s.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:l}=s.useEditorStore(u=>u.actions),o=s.useEditorStore(u=>u.queryResultColumns);s.useEditorStore(u=>{var m;return(m=u.card.preferences)==null?void 0:m.filterOnClickColumnIndex}),A.useEffect(()=>{o&&n(new Array(o.length).fill(!1))},[o]);function c(u,m){var h,p;m?a!=null&&a.onClickFilter&&((h=a==null?void 0:a.onClickFilter)==null?void 0:h.length)>0?l({...a,onClickFilter:[...a.onClickFilter,{columnIndex:u,expression:""}]}):l({...a,onClickFilter:[{columnIndex:u,expression:""}]}):(l({...a,onClickFilter:(p=a==null?void 0:a.onClickFilter)==null?void 0:p.filter(g=>g.columnIndex!==u)}),n(g=>{const b=[...g];return b[u]=!1,b}))}function i(u,m){var p;const h=(p=a==null?void 0:a.onClickFilter)==null?void 0:p.map(g=>g.columnIndex===u?{...g,expression:m.target.value}:g);l({...a,onClickFilter:h})}function d(u){var m,h,p,g;if(t!=null&&t[u]||(h=(m=a==null?void 0:a.onClickFilter)==null?void 0:m.find(b=>b.columnIndex===u))!=null&&h.expression)return e.jsx(s.Input,{value:(g=(p=a==null?void 0:a.onClickFilter)==null?void 0:p.find(b=>b.columnIndex===u))==null?void 0:g.expression,onChange:b=>i(u,b),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsx("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:o==null?void 0:o.map((u,m)=>{var h,p;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((h=a==null?void 0:a.onClickFilter)!=null&&h.find(g=>g.columnIndex===m)),onCheckedChange:g=>c(m,g)}),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:((p=a==null?void 0:a.onClickFilter)==null?void 0:p.find(g=>g.columnIndex===m))&&e.jsx(s.Pencil,{onClick:()=>{n(g=>{const b=[...g];return b[m]=!g[m],b})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(m)]})},u)})})}function pr({idx:t}){var i;const n=s.useEditorStore(d=>{var u;return(u=d.card)==null?void 0:u.preferences}),a=s.useEditorStore(d=>{var u;return(u=d.card.preferences)==null?void 0:u.datasetOptions}),r=s.useEditorStore(d=>d.actions.setCardPreferences),l=(i=n==null?void 0:n.chartOptions)==null?void 0:i.indexAxis,o=a==null?void 0:a.find(d=>d.idx===t);function c(d,u){(d==="end"||d==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const m={display:d!=="none",align:d,anchor:d,clamp:!0};if(!o)r({...n,datasetOptions:[...a||[],{idx:u,datalabels:m}]});else{const h={...o};h.datalabels=m;const p=a==null?void 0:a.map(g=>g.idx===u?h:g);r({...n,datasetOptions:p})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(nt,{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(Ca,{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(wa,{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(Sa,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function fr(){const t=s.useEditorStore(o=>o.card),{data:n}=s.useDashboardCardQuery(t),{keys:a}=s.getKeys((n==null?void 0:n.records)||[]),r=a.slice(1).filter(o=>!s.METADATA_KEYS.includes(o));let l=r;if(["stackedBar","stackedLine"].includes(t.type)){const o=s.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:c}=s.getKeys(o);l=c.slice(1)}return{transformedMetricKeys:l,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}function cs({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",n),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function At(){const t=s.useEditorStore(d=>d.card),n=s.useEditorStore(d=>{var u,m,h;return(h=(m=(u=d==null?void 0:d.card)==null?void 0:u.preferences)==null?void 0:m.chartOptions)==null?void 0:h.indexAxis}),{data:a}=s.useDashboardCardQuery(t),r=n==="y"?"Metric":"Dimension",l=n==="y"?"Dimension":"Metric",{dimensionKeys:o,transformedMetricKeys:c,keys:i}=fr();return i.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:o.map(d=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:d,children:Mt(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(Lt,{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 Mt(t,n=30){return t.length>n?t.slice(0,n)+"...":t}function Lt({col:t,idx:n,className:a,iconClassName:r,children:l}){const o=s.useEditorStore(m=>{var h;return(h=m.card)==null?void 0:h.preferences}),c=s.useEditorStore(m=>{var h,p;return(p=(h=m.card)==null?void 0:h.preferences)==null?void 0:p.datasetOptions}),i=c==null?void 0:c.find(m=>m.idx===n),{setCardPreferences:d}=s.useEditorStore(m=>m.actions);function u(m){if(!i)d({...o,datasetOptions:[...c||[],{idx:n,type:m==="area"?"line":m,fill:m==="area"?"origin":""}]});else{const h={...i};h.type=m==="area"?"line":m,h.fill=m==="area"?"origin":"";const p=c==null?void 0:c.map(g=>g.idx===n?h:g);d({...o,datasetOptions:p})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[l||e.jsx(cs,{className:"max-w-[100px]",title:t,children:Mt(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(pr,{idx:n})]})]})}function Is(){const t=s.useEditorStore(g=>g.selectedConnectionId),n=s.useEditorStore(g=>g.selectedDatamodelId),a=s.useEditorStore(g=>g.selectedDatabaseName),r=s.useEditorStore(g=>g.selectedSchemaName),l=s.useEditorStore(g=>g.selectedTableName),o=s.useDashboardStore(g=>g.dashboard.filters)||[],c=s.useDashboardStore(g=>g.actions.addFilter),i=s.useDashboardStore(g=>g.actions.removeFilter),{removeFilterValues:d}=s.useDashboardActions(),{modelItems:u,tableName:m,connectionType:h}=s.useEditorAside();function p(g,b="dashboard",x){var N;const j=s.fmt(g.column_name),f=s.fmt(a||""),y=s.fmt(r||""),E=s.fmt(m);let k=s.getQualifiedTableName({schemaName:y,tableName:E,connectionType:h,databaseName:f}),C=`${k}.${j}`;const D=(N=u==null?void 0:u.find(S=>S.id===n))==null?void 0:N.name;n&&n!=="none"&&(C=`${s.DATAMODEL_NAMESPCACE}.${D}.${j}`,k=`${s.DATAMODEL_NAMESPCACE}.${D}`),x!=null&&x.qualifiedFieldName&&(C=x.qualifiedFieldName),x!=null&&x.entityName&&(k=x.entityName);const v=o==null?void 0:o.find(S=>S.column===C&&S.table===E&&(S.database===f||S.database===a));if(v)d(v.id),i(v.id);else{const S=s.v4();return m==="api"&&t?(c({location:b,id:S,column:C,title:g.column_name,dataType:g.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(g.data_type,k,j)}),S):(c({id:S,location:b,column:C,title:g.column_name,dataType:g.data_type,table:l||"",database:a||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(g.data_type,k,j)}),S)}}return{assignFilter:p}}function Ve(){const t=s.useDashboardStore(i=>i.dashboard.filters),n=s.useEditorStore(i=>i.frame),{setFrame:a}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=Is();function o(i){const d=l(i,"frame");a({...n,filterId:d})}const c=t==null?void 0:t.find(i=>i.id===n.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(gr,{onSelect:o,columns:r}),c&&e.jsx(s.FilterHeader,{filter:c})]})}function gr({columns:t,onSelect:n}){var c;const[a,r]=Ee.useState(!1),[l,o]=Ee.useState("");return e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between font-normal",children:[l?(c=t.find(i=>i.column_name===l))==null?void 0:c.column_name:"Select Column...",e.jsx(s.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No framework found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(i=>e.jsxs(s.CommandItem,{value:i.column_name,onSelect:d=>{const u=d===l?"":d;o(u),r(!1),u&&n(i)},children:[i.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",l===i.column_name?"opacity-100":"opacity-0")})]},i.column_name))})]})]})})]})}function jr({cardType:t}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, y-axis-1, y-axis-2,... FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"y-axis1 - number"}),e.jsx("li",{children:"y-axis2 - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:n=>n.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(At,{})})]}),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(Oe,{}),e.jsx(Ve,{})]})]})]})})}function br({cardType:t}){function n(a){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:a==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),a==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:o=>o.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsx(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:n(t)})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Oe,{}),e.jsx(Ve,{})]})]})]})})}function Rt(){const t=s.useEditorStore(i=>i.card.type),n=s.useEditorStore(i=>i.isDevMode),a=s.useEditorStore(i=>i.card.preferences),{setCardPreferences:r}=s.useEditorStore(i=>i.actions);function l(i){var m;const d={datalabels:{display:i!=="none",align:i,anchor:i,clamp:!0}},u={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(m=a==null?void 0:a.chartOptions)==null?void 0:m.plugins,...d}}};r(u)}function o(){var i,d,u;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((u=(d=(i=a==null?void 0:a.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Data Labels"}),e.jsx(s.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"start",children:"Start"}),e.jsx(s.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"end",children:"End"})]})})]})]})}function c(){var i,d,u;return e.jsx("div",{children:e.jsxs(s.Select,{value:((u=(d=(i=a==null?void 0:a.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(s.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:n?o():c()})}const vr={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},yr={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function Nr(){const t=s.useEditorStore(n=>n.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:Cr(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Rt,{}),e.jsx(Oe,{}),e.jsx(Ve,{})]})]})}function Cr(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(vr,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(yr,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 Sr({colorRanges:t,setColorRanges:n}){const a={start:-1/0,end:100,color:""};function r(c,i,d){const u=[...t];u[c]={...u[c],[i]:d},n(u)}function l(c){const i=[...t];i.splice(c,1),n(i)}function o(){n([...t,a])}return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:"Color Range"}),e.jsx(s.Button,{onClick:o,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((c,i)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input,{onChange:d=>r(i,"start",d.target.value),value:c.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input,{value:c.end,onChange:d=>r(i,"end",d.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input,{onChange:d=>r(i,"color",d.target.value),value:c.color,className:s.cn(`h-7 min-w-14 p-0 ${s.removeRing}`),type:"color",list:"presetColors"}),e.jsxs("datalist",{id:"presetColors",children:[e.jsx("option",{children:s.colors.green[600]}),e.jsx("option",{children:s.colors.red[500]}),e.jsx("option",{children:s.colors.yellow[400]}),e.jsx("option",{children:s.colors.orange[500]})]}),e.jsx(s.Button,{onClick:()=>l(i),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},i))]})}function wr(){var m,h,p,g,b;const t=s.useEditorStore(x=>x.card.preferences),n=s.useEditorStore(x=>x.actions.setCardPreferences),a=s.useEditorStore(x=>x.card),r=s.isExplorerCard(a),l=s.useEditorStore(x=>x.actions.setNumberFormat);s.useEditorStore(x=>{var j,f;return(f=(j=x.card.preferences)==null?void 0:j.formatNumber)==null?void 0:f.decimalPlaces});const o=s.useEditorStore(x=>{var j,f;return(f=(j=x.card.preferences)==null?void 0:j.formatNumber)==null?void 0:f.locale}),c=s.useEditorStore(x=>{var j,f;return(f=(j=x.card.preferences)==null?void 0:j.formatNumber)==null?void 0:f.currency});s.useEditorStore(x=>x.actions.setFilterOnClickField);const i=s.useEditorStore(x=>{var j,f;return(f=(j=x.card.preferences)==null?void 0:j.formatNumber)==null?void 0:f.colorRanges})||[],d=s.useEditorStore(x=>x.actions.setColorRanges),u=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(x=>x.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:x=>{n({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:x}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((h=t==null?void 0:t.formatNumber)==null?void 0:h.enabled)===!0||r)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Locale"}),e.jsxs(s.Select,{value:o||"none",onValueChange:x=>{var j,f,y;return l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,((f=t==null?void 0:t.formatNumber)==null?void 0:f.currency)||"",x,((y=t==null?void 0:t.formatNumber)==null?void 0:y.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(x=>e.jsx(s.SelectItem,{value:x.locale,children:x.locale},x.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:x=>{var j,f,y;console.log("currency",x),l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,x==="none"?"":x,((f=t==null?void 0:t.formatNumber)==null?void 0:f.locale)||"",((y=t==null?void 0:t.formatNumber)==null?void 0:y.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(x=>e.jsx(s.SelectItem,{value:x,children:x},x))]})})]})]})]}),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:((g=(p=t==null?void 0:t.formatNumber)==null?void 0:p.decimalPlaces)==null?void 0:g.toString())||"0",onValueChange:x=>{var j,f,y;return l(Number(x),((j=t==null?void 0:t.formatNumber)==null?void 0:j.currency)||"",((f=t==null?void 0:t.formatNumber)==null?void 0:f.locale)||"",((y=t==null?void 0:t.formatNumber)==null?void 0:y.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(x=>e.jsx(s.SelectItem,{value:x,children:x},x))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Suffix"}),e.jsx(s.Input,{value:((b=t==null?void 0:t.formatNumber)==null?void 0:b.suffix)||"",className:"h-8 font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"K, M, B, %",onChange:x=>{var j,f,y;return l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,((f=t==null?void 0:t.formatNumber)==null?void 0:f.currency)||"",((y=t==null?void 0:t.formatNumber)==null?void 0:y.locale)||"",x.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(Sr,{colorRanges:i,setColorRanges:d})]})]})}function Dr(){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(wr,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function fs({children:t,summary:n,open:a,className:r}){return e.jsxs("details",{open:a,className:s.cn("space-y-4 [&_summary>svg]:open:-rotate-180",r),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(s.Label,{children:n}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const Tr=[{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"}],kr=["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"],Er=kr.map(t=>({label:t,value:t}));function Ir(){var d,u,m,h,p,g,b,x,j,f,y,E,k,C,D,v,N,S;const t=s.useEditorStore(F=>F.card),n=(u=(d=t==null?void 0:t.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:u.topoJsonUrl,[a,r]=A.useState(((h=(m=t==null?void 0:t.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:o}=s.useTopoJson(t),c=Object.keys((o==null?void 0:o.objects)||{}).map(F=>({label:F,value:F}))||[],i=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"p-6",children:[e.jsx(fs,{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(fs,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(Ce,{className:"h-9",options:i,onValueChange:F=>{console.log("value",F),l({...t.preferences,mapVisualOptions:{topoJsonUrl:F}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(s.Input,{onChange:F=>{r(F.target.value)},onBlur:()=>{var F;console.log("onBlur",a),l({...t.preferences,mapVisualOptions:{...(F=t.preferences)==null?void 0:F.mapVisualOptions,customTopoJsonUrl:a}})},value:a,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),o&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(Ce,{className:"h-9",options:c,value:((g=(p=t.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:g.objectKey)||"",label:"Map Object",onValueChange:F=>{var I;l({...t.preferences,mapVisualOptions:{...(I=t.preferences)==null?void 0:I.mapVisualOptions,objectKey:F}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(Ce,{className:"h-9",options:Tr,value:((x=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:x.projection)||"",label:"Projection",onValueChange:F=>{var I;l({...t.preferences,mapVisualOptions:{...(I=t.preferences)==null?void 0:I.mapVisualOptions,projection:F}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(Ce,{className:"h-9",options:Er,value:((f=(j=t.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:f.colorScale)||"",label:"Select Color Scale",onValueChange:F=>{var I;l({...t.preferences,mapVisualOptions:{...(I=t.preferences)==null?void 0:I.mapVisualOptions,colorScale:F}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(fs,{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:((E=(y=t.preferences)==null?void 0:y.mapVisualOptions)==null?void 0:E.projectionScale)||1,onChange:F=>{var I;l({...t.preferences,mapVisualOptions:{...(I=t.preferences)==null?void 0:I.mapVisualOptions,projectionScale:Number(F.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((D=(C=(k=t.preferences)==null?void 0:k.mapVisualOptions)==null?void 0:C.projectionOffset)==null?void 0:D[0])||0,onChange:F=>{var I,P,T,w;l({...t.preferences,mapVisualOptions:{...(I=t.preferences)==null?void 0:I.mapVisualOptions,projectionOffset:[Number(F.target.value),((w=(T=(P=t.preferences)==null?void 0:P.mapVisualOptions)==null?void 0:T.projectionOffset)==null?void 0:w[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((S=(N=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:N.projectionOffset)==null?void 0:S[1])||0,onChange:F=>{var I,P,T,w;l({...t.preferences,mapVisualOptions:{...(I=t.preferences)==null?void 0:I.mapVisualOptions,projectionOffset:[((w=(T=(P=t.preferences)==null?void 0:P.mapVisualOptions)==null?void 0:T.projectionOffset)==null?void 0:w[0])||0,Number(F.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Oe,{})]})}function Ar(){var r;const t=s.useEditorStore(l=>l.card.preferences),{setCardPreferences:n}=s.useEditorStore(l=>l.actions);function a(l){n({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:l==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:a,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function Xe({cardType:t,docContent:n,suffix:a="Chart"}){let r="pie-donut-polar";return t==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} ${a}`}),e.jsx(s.AccordionContent,{children:n||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:l=>l.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),t==="text"&&e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2 py-4",children:e.jsx(Ar,{})})]}),!["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(Oe,{}),e.jsx(Ve,{})]})]})]})})}function Mr(){const t=s.useEditorStore(r=>{var l,o;return(o=(l=r==null?void 0:r.card)==null?void 0:l.preferences)==null?void 0:o.sortChart}),{setSortChart:n}=s.useEditorActions();function a(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(Ce,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:t||"none",onValueChange:r=>{n(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[a(),e.jsx(At,{})]})]}),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(Oe,{}),e.jsx(Ve,{})]})]})]})})}function Lr({cardType:t="table"}){console.log("cardType",t);const n=s.useEditorStore(l=>{var o;return(o=l.card)==null?void 0:o.preferences}),a=s.useEditorStore(l=>l.actions.setCardPreferences),r=l=>{a({...n,allowDownload:l})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Oe,{}),e.jsx(Ve,{})]})]})}),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 Ot({color:t,onColorChange:n,onClose:a}){const[r,l]=A.useState(0),[o,c]=A.useState(100),[i,d]=A.useState(50),[u,m]=A.useState(t);A.useEffect(()=>{const j=$s(t);if(j){const f=qs(j.r,j.g,j.b);l(f.h),c(f.s),d(f.l),m(t)}},[t]);const h=j=>{l(j),g(j,o,i)},p=j=>{const f=j.currentTarget.getBoundingClientRect(),y=Math.max(0,Math.min(1,(j.clientX-f.left)/f.width)),E=Math.max(0,Math.min(1,(j.clientY-f.top)/f.height)),k=y*100,C=(1-E)*100;c(k),d(C),g(r,k,C)},g=(j,f,y)=>{const E=Or(j,f,y),k=Rr(E.r,E.g,E.b);m(k)},b=j=>{if(m(j),/^#[0-9A-Fa-f]{6}$/.test(j)){const f=$s(j);if(f){const y=qs(f.r,f.g,f.b);l(y.h),c(y.s),d(y.l)}}},x=()=>{/^#[0-9A-Fa-f]{6}$/.test(u)&&(n(u),a())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:p,onMouseMove:j=>{j.buttons===1&&p(j)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${o}%`,top:`${100-i}%`,backgroundColor:u}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:j=>h(Number(j.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:j=>b(j.target.value),placeholder:"#000000",className:"font-mono"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:t}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:u}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(s.Button,{variant:"outline",onClick:a,children:"Cancel"}),e.jsx(s.Button,{onClick:x,children:"OK"})]})]})}function $s(t){const n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return n?{r:parseInt(n[1],16),g:parseInt(n[2],16),b:parseInt(n[3],16)}:null}function Rr(t,n,a){return"#"+((1<<24)+(t<<16)+(n<<8)+a).toString(16).slice(1)}function qs(t,n,a){t/=255,n/=255,a/=255;const r=Math.max(t,n,a),l=Math.min(t,n,a);let o=0,c=0;const i=(r+l)/2;if(r!==l){const d=r-l;switch(c=i>.5?d/(2-r-l):d/(r+l),r){case t:o=((n-a)/d+(n<a?6:0))/6;break;case n:o=((a-t)/d+2)/6;break;case a:o=((t-n)/d+4)/6;break}}return{h:Math.round(o*360),s:Math.round(c*100),l:Math.round(i*100)}}function Or(t,n,a){t/=360,n/=100,a/=100;let r,l,o;if(n===0)r=l=o=a;else{const c=(u,m,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?u+(m-u)*6*h:h<.5?m:h<.6666666666666666?u+(m-u)*(.6666666666666666-h)*6:u),i=a<.5?a*(1+n):a+n-a*n,d=2*a-i;r=c(d,i,t+1/3),l=c(d,i,t),o=c(d,i,t-1/3)}return{r:Math.round(r*255),g:Math.round(l*255),b:Math.round(o*255)}}const Fr=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function Ft(){var E,k,C,D,v,N,S,F,I,P;const t=s.useEditorStore(T=>T.card),n=s.useEditorStore(T=>{var w;return(w=T.card)==null?void 0:w.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions(),{data:l}=s.useDashboardCardQuery(t),[o,c]=A.useState({}),[i,d]=A.useState(null),[u,m]=A.useState(null),h=A.useMemo(()=>{var O,R,M,B,Y,_,Q;if(!(l!=null&&l.records)||l.records.length===0)return[];const T=(t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine",w=(t==null?void 0:t.type)==="bar"||(t==null?void 0:t.type)==="line",L=((O=t==null?void 0:t.config)==null?void 0:O.pivotByColumns)&&t.config.pivotByColumns.length>0;if((T||w)&&L){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const X=new Set;return l.pivotSchema.forEach(q=>{q.alias&&X.add(q.alias)}),Array.from(X)}if(l.records.length>0){const X=l.records[0],q=Object.keys(X),W=new Set;(R=t==null?void 0:t.config)!=null&&R.groupByColumns&&t.config.groupByColumns.forEach(V=>{W.add(V.label||V.name),W.add(V.alias||V.name)});const G=new Set;return(M=t==null?void 0:t.config)!=null&&M.metricColumns&&t.config.metricColumns.forEach(V=>{const U=V.alias||V.name;G.add(U),G.add(`${U}_count`),G.add(`${U}_sum`),G.add(`${U}_avg`),G.add(`${U}_min`),G.add(`${U}_max`);const ee=V.entityName||V.qualifiedEntityName;ee&&(G.add(`${ee}_${U}`),G.add(`${ee}_${U}_count`))}),q.filter(V=>!W.has(V)&&!G.has(V))}}if((w||T)&&!L&&((Y=(B=t==null?void 0:t.config)==null?void 0:B.metricColumns)!=null&&Y.length))return t.config.metricColumns.map(X=>X.alias||X.label||X.name);if((Q=(_=t==null?void 0:t.config)==null?void 0:_.groupByColumns)!=null&&Q.length){const X=t.config.groupByColumns[0],q=X.label||X.name,W=new Set;return l.records.forEach(G=>{const se=G[q];se!=null&&W.add(String(se))}),Array.from(W)}return[]},[l,(E=t==null?void 0:t.config)==null?void 0:E.groupByColumns,(k=t==null?void 0:t.config)==null?void 0:k.pivotByColumns,(C=t==null?void 0:t.config)==null?void 0:C.metricColumns,t==null?void 0:t.type]),p=A.useMemo(()=>s.getDefaultChartColors(),[]);A.useEffect(()=>{const T={};h.forEach((w,L)=>{T[w]=s.getColorForValue(w,L,n==null?void 0:n.colorConfig)}),c(T)},[h,n==null?void 0:n.colorConfig,p]);const g=(T,w)=>{const L={...o,[T]:w};c(L);const O={...n||{},colorConfig:{segments:L}};a(O);const R={...t,preferences:O};r(R)},b=(T,w)=>{var Y;const L=p[w%p.length],{[T]:O,...R}=((Y=n==null?void 0:n.colorConfig)==null?void 0:Y.segments)||{},M={...n||{},colorConfig:{segments:R}};a(M);const B={...t,preferences:M};r(B),c(_=>({..._,[T]:L}))};if(!h.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((v=(D=t==null?void 0:t.config)==null?void 0:D.groupByColumns)==null?void 0:v.length)||((S=(N=t==null?void 0:t.config)==null?void 0:N.pivotByColumns)==null?void 0:S.length):(I=(F=t==null?void 0:t.config)==null?void 0:F.groupByColumns)==null?void 0:I.length)||["table","kpi","text","custom"].includes(t.type))return null;const f=()=>{const T={...n||{},colorConfig:{segments:{}}};a(T);const w={...t,preferences:T};r(w);const L={};h.forEach((O,R)=>{L[O]=s.getColorForValue(O,R,void 0)}),c(L)},y=Object.keys(((P=n==null?void 0:n.colorConfig)==null?void 0:P.segments)||{}).length>0;return e.jsxs(s.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(La,{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:y&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:f,children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:h.map((T,w)=>{const L=s.isDefaultColor(o[T],w),O=!L;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:i===T,onOpenChange:R=>d(R?T:null),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"h-5 w-5 shrink-0 rounded border border-input shadow-sm transition-colors hover:border-gray-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",style:{backgroundColor:o[T]}})}),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:p.slice(0,10).map((R,M)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",o[T]===R?"border-gray-900":"border-transparent"),style:{backgroundColor:R},onClick:()=>{g(T,R),d(null)},children:[M===w%p.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:R})]},`default-${M}`))})]}),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:Fr.map((R,M)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",o[T]===R?"border-2 border-gray-900":R==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:R},onClick:()=>{g(T,R),d(null)},children:e.jsx("span",{className:"sr-only",children:R})},`preset-${M}`))})]}),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:T,color:o[T]}),d(null)},children:"Custom color"}),!L&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{b(T,w),d(null)},children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:T}),O&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},T)})}),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(Ot,{color:u.color,onColorChange:T=>{g(u.value,T),m(null)},onClose:()=>m(null)})})]})]})})]})}function we({value:t,onSave:n,placeholder:a="",type:r="text",className:l=""}){const[o,c]=A.useState(t??""),[i,d]=A.useState(!1);A.useEffect(()=>{c(t??"")},[t]);const u=()=>{n(o),d(!1)},m=()=>{c(t??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${l}`,children:[e.jsx(s.Input$1,{placeholder:a,type:r,value:i?o:t??"",onChange:h=>{c(h.target.value),d(!0)},onFocus:()=>d(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&i&&o!==t?u():h.key==="Escape"&&m()},"aria-label":a||"Edit field"}),i&&o!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:u,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:m,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}const Pr=["auto","number","currency","percent","scientific","date"],Br=[{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"}],zr=[{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"}],_r=t=>t.charAt(0).toUpperCase()+t.slice(1);function As({formatOptions:t={},onFormatOptionsChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const l=t.type||"auto",o=(i,d)=>{n({...t,[i]:d})},c=()=>l==="currency"?2:l==="percent"?1:0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[a&&e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(s.Select,{value:l,onValueChange:i=>o("type",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Pr.map(i=>e.jsx(s.SelectItem,{value:i,className:"text-xs",children:i==="auto"?"Auto (Default)":_r(i)},i))})]})]}),l!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent"].includes(l)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",min:"0",max:"10",placeholder:"0",value:t.decimalPlaces??c(),onChange:i=>o("decimalPlaces",parseInt(i.target.value)||0),className:"h-8 text-xs"})})]}),l==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(s.Select,{value:t.currency||"USD",onValueChange:i=>o("currency",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Br.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:t.useSuffix??!1,onCheckedChange:i=>o("useSuffix",i)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(s.Select,{value:t.locale||"en-US",onValueChange:i=>o("locale",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:zr.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., $",value:t.prefix||"",onChange:i=>o("prefix",i.target.value),className:"h-8 text-xs"})})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., units",value:t.suffix||"",onChange:i=>o("suffix",i.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Negative in ()"}),e.jsx(s.SmallSwitch,{checked:t.negativeInParentheses??!1,onCheckedChange:i=>o("negativeInParentheses",i)})]}),l==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",placeholder:"100",value:t.multiplyBy??"",onChange:i=>o("multiplyBy",i.target.value?parseFloat(i.target.value):void 0),className:"h-8 text-xs"})})]}),l==="date"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Format"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"text",placeholder:"MM/DD/YYYY",value:t.dateFormat||"",onChange:i=>o("dateFormat",i.target.value),className:"h-8 text-xs"})})]})]})]})}function Hs({axis:t,label:n,type:a,config:r,onChange:l}){var h,p,g,b,x,j,f,y,E,k,C,D;const o=(v,N)=>{l({...r,[v]:N})},c=(v,N)=>{var S,F;l({...r,name:{enabled:v==="enabled"?N:((S=r==null?void 0:r.name)==null?void 0:S.enabled)??!1,text:v==="text"?N:(F=r==null?void 0:r.name)==null?void 0:F.text}})},i=(v,N)=>{var S,F;l({...r,labels:{enabled:v==="enabled"?N:((S=r==null?void 0:r.labels)==null?void 0:S.enabled)??!0,rotation:v==="rotation"?N:(F=r==null?void 0:r.labels)==null?void 0:F.rotation}})},d=(v,N)=>{l({...r,scale:{...r==null?void 0:r.scale,[v]:N===""?"auto":Number(N)}})},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:n})})}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:v=>o("enabled",v),onClick:v=>v.stopPropagation()})]}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TITLE"}),e.jsx(s.SmallSwitch,{checked:((h=r==null?void 0:r.name)==null?void 0:h.enabled)??!1,onCheckedChange:v=>c("enabled",v)})]}),((p=r==null?void 0:r.name)==null?void 0:p.enabled)&&e.jsx(we,{placeholder:`${n} title`,value:((g=r==null?void 0:r.name)==null?void 0:g.text)||"",onSave:v=>c("text",v),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:v=>o("position",v),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(v=>e.jsx(s.SelectItem,{value:v,className:"text-xs",children:v==="auto"?"Auto (Default)":s.titleCase(v)},v))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(s.SmallSwitch,{checked:((b=r==null?void 0:r.labels)==null?void 0:b.enabled)!==!1,onCheckedChange:v=>i("enabled",v)})]}),((x=r==null?void 0:r.labels)==null?void 0:x.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(((j=r==null?void 0:r.labels)==null?void 0:j.rotation)||"auto"),onValueChange:v=>i("rotation",v==="auto"?"auto":Number(v)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:m.map(v=>e.jsx(s.SelectItem,{value:v,className:"text-xs",children:v==="auto"?"Auto (Default)":`${v}°`},v))})]})]})]}),a==="value"&&e.jsx(As,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:v=>l({...r,formatOptions:v}),showTitle:!0,title:"FORMAT"}),a==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"SCALE"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"auto",value:((f=r==null?void 0:r.scale)==null?void 0:f.min)==="auto"||((y=r==null?void 0:r.scale)==null?void 0:y.min)===void 0?"":String(r.scale.min),onSave:v=>d("min",v),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(we,{type:"number",placeholder:"auto",value:((E=r==null?void 0:r.scale)==null?void 0:E.max)==="auto"||((k=r==null?void 0:r.scale)==null?void 0:k.max)===void 0?"":String(r.scale.max),onSave:v=>d("max",v),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(we,{type:"number",placeholder:"auto",value:((C=r==null?void 0:r.scale)==null?void 0:C.stepSize)==="auto"||((D=r==null?void 0:r.scale)==null?void 0:D.stepSize)===void 0?"":String(r.scale.stepSize),onSave:v=>d("stepSize",v),className:""})})]})]})]})]})]})}function Pt(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>{var i;return(i=c.card)==null?void 0:i.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions();if(!t||["tornado","pyramid","kpi"].includes(t.type))return null;const l=s.AxisConfigurator.getAxisInfo(t.type,n);if(!l.hasXAxis&&!l.hasYAxis)return null;const o=(c,i)=>{const u={...n||{},[c==="x"?"xAxisConfig":"yAxisConfig"]:i};a(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(at,{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(Hs,{axis:"x",label:"X-Axis",type:l.xAxisType,config:n==null?void 0:n.xAxisConfig,onChange:c=>o("x",c)}),l.hasYAxis&&e.jsx(Hs,{axis:"y",label:"Y-Axis",type:l.yAxisType,config:n==null?void 0:n.yAxisConfig,onChange:c=>o("y",c)})]})})]})}function Bt(){const t=s.useEditorStore(u=>u.card),n=s.useEditorStore(u=>{var m,h,p,g;return(g=(p=(h=(m=u.card)==null?void 0:m.preferences)==null?void 0:h.chartOptions)==null?void 0:p.plugins)==null?void 0:g.legend}),{setLegendOptions:a}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r="bottom",l="center",o=!(t.type==="stackedBar"||t.type==="stackedLine"),c=(u,m)=>{const h={...n,[u]:m};a(h)},i=["top","bottom","left","right"],d=["start","center","end"];return e.jsxs(s.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Na,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:(n==null?void 0:n.display)??o,onCheckedChange:u=>c("display",u)})]}),((n==null?void 0:n.display)??o)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(n==null?void 0:n.position)||r,onValueChange:u=>c("position",u),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:i.map(u=>e.jsx(s.SelectItem,{value:u,className:"text-xs",children:s.titleCase(u)},u))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(s.Select,{value:(n==null?void 0:n.align)||l,onValueChange:u=>c("align",u),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:d.map(u=>e.jsx(s.SelectItem,{value:u,className:"text-xs",children:s.titleCase(u)},u))})]})]})]})]})})]})}function zt(){var N,S,F,I,P,T,w,L,O;const t=s.useEditorStore(R=>R.card),n=s.useEditorStore(R=>{var M,B;return(B=(M=R.card)==null?void 0:M.preferences)==null?void 0:B.dataLabelsConfig}),a=s.useEditorStore(R=>{var M;return(M=R.card)==null?void 0:M.preferences}),{setCardPreferences:r,updateCardInFrame:l}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(t.type))return null;const o=((N=a==null?void 0:a.chartOptions)==null?void 0:N.indexAxis)==="y",c=t.type==="stackedBar"||t.type==="stackedLine",i=t.type==="pie"||t.type==="doughnut"||t.type==="polarArea"||t.type==="funnel",d=!i,u=(F=(S=a==null?void 0:a.chartOptions)==null?void 0:S.plugins)==null?void 0:F.datalabels,m=(u==null?void 0:u.display)!==!1&&((u==null?void 0:u.anchor)||(u==null?void 0:u.align)),h=(n==null?void 0:n.enabled)!==void 0?n.enabled:m,p=(R,M)=>{const B={...n,[R]:M},Y={...t.preferences||{},dataLabelsConfig:B};r(Y);const _={...t,preferences:Y};l(_)},g=(R,M)=>{const B={...n,font:{...n==null?void 0:n.font,[R]:M}},Y={...t.preferences||{},dataLabelsConfig:B};r(Y);const _={...t,preferences:Y};l(_)},b=(R,M)=>{const B={...n,formatOptions:{...n==null?void 0:n.formatOptions,[R]:M}},Y={...t.preferences||{},dataLabelsConfig:B};r(Y);const _={...t,preferences:Y};l(_)},j=(()=>{const R=t.type;return R==="stackedBar"||R==="stackedLine"||R==="pie"||R==="doughnut"?"center":o?"right":"top"})();let f=[];c||i?f=["center"]:f=["auto",...(o?["center","left","right"]:["center","top","bottom"]).filter(M=>M!==j),"custom"];const y=()=>s.titleCase(j),E=["center","start","end"],k=["center","start","end","top","bottom"],C=d?["auto","number","currency","percent","none"]:["number","currency","percent","none"],D=[{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"}],v=[{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(Ga,{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:R=>p("enabled",R)})]}),h&&e.jsxs(e.Fragment,{children:[!c&&!i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(n==null?void 0:n.position)||"auto",onValueChange:R=>p("position",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:f.map(R=>e.jsx(s.SelectItem,{value:R,className:"text-xs",children:R==="auto"?y():R==="custom"?"Custom (Advanced)":s.titleCase(R)},R))})]})]}),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:(n==null?void 0:n.showTotal)??!1,onCheckedChange:R=>p("showTotal",R)})]}),(n==null?void 0:n.position)==="custom"&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Anchor"}),e.jsxs(s.Select,{value:(n==null?void 0:n.anchor)||"center",onValueChange:R=>p("anchor",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:E.map(R=>e.jsx(s.SelectItem,{value:R,className:"text-xs",children:s.titleCase(R)},R))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Align"}),e.jsxs(s.Select,{value:String((n==null?void 0:n.align)||"center"),onValueChange:R=>p("align",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:k.map(R=>e.jsx(s.SelectItem,{value:R,className:"text-xs",children:s.titleCase(R)},R))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(n==null?void 0:n.format)||(d?"auto":"none"),onValueChange:R=>p("format",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:C.map(R=>e.jsx(s.SelectItem,{value:R,className:"text-xs",children:R==="auto"&&d?"Auto (Use Axis)":R==="none"?"None (Raw Value)":s.titleCase(R)},R))})]})]}),(n==null?void 0:n.format)&&!["auto","none"].includes(n.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(n.format)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"0",value:String(((I=n==null?void 0:n.formatOptions)==null?void 0:I.decimalPlaces)??(n.format==="currency"?2:n.format==="percent"?1:0)),onSave:R=>b("decimalPlaces",Number(R)),className:""})})]}),n.format==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Currency"}),e.jsxs(s.Select,{value:((P=n==null?void 0:n.formatOptions)==null?void 0:P.currency)||"USD",onValueChange:R=>b("currency",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:D.map(R=>e.jsx(s.SelectItem,{value:R.value,className:"text-xs",children:R.label},R.value))})]})]}),["number","currency"].includes(n.format)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((T=n==null?void 0:n.formatOptions)==null?void 0:T.useSuffix)??!1,onCheckedChange:R=>b("useSuffix",R)})]}),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:((w=n==null?void 0:n.formatOptions)==null?void 0:w.locale)||"en-US",onValueChange:R=>b("locale",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:v.map(R=>e.jsx(s.SelectItem,{value:R.value,className:"text-xs",children:R.label},R.value))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Appearance"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Size"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"12",value:String(((L=n==null?void 0:n.font)==null?void 0:L.size)||12),onSave:R=>g("size",Number(R)),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:((O=n==null?void 0:n.font)==null?void 0:O.weight)||"normal",onValueChange:R=>g("weight",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(s.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Color"}),e.jsxs(s.Select,{value:(n==null?void 0:n.color)==="auto"||!(n!=null&&n.color)?"auto":"custom",onValueChange:R=>{R==="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(we,{type:"number",placeholder:"0",value:String((n==null?void 0:n.rotation)||0),onSave:R=>p("rotation",Number(R)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}function Vr(){return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Chart Configuration"}),e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:[e.jsx(Ft,{}),e.jsx(Pt,{}),e.jsx(Bt,{}),e.jsx(zt,{})]})]})}const Ur=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."]})]}),Gr=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."]})]}),Yr=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 $r(){const t=s.useEditorStore(a=>a.card.type);function n(a){const r=["kpi","table","text","map","custom"],l=o=>r.includes(a)?o:e.jsxs(e.Fragment,{children:[o,e.jsx(Vr,{})]});switch(a){case"stackedBar":case"stackedLine":return l(e.jsx(Mr,{}));case"tornado":case"pyramid":return l(e.jsx(Xe,{docContent:Ur,cardType:a}));case"kpi":return e.jsx(Dr,{});case"line":case"bar":return l(e.jsx(jr,{cardType:a}));case"range":return l(e.jsx(Xe,{docContent:Gr,cardType:a}));case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return l(e.jsx(Xe,{cardType:a}));case"bubble":case"scatter":return l(e.jsx(br,{cardType:a}));case"table":return e.jsx(Lr,{cardType:a});case"text":return e.jsx(Xe,{docContent:Yr,cardType:a,suffix:"Visual"});case"map":return e.jsx(Ir,{});case"custom":return e.jsx(xr,{});default:return l(e.jsx(Nr,{}))}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[n(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function _t({label:t,column:n,functions:a,onFunctionChange:r}){let l=a[0];"aggregate"in n?l=a.find(c=>c.value===n.aggregate)||a[0]:"granularity"in n&&(l=a.find(c=>c.value===n.granularity)||a[0]);function o(c){r(c)}return e.jsx(Ce,{className:"flex h-8 w-8 justify-center overflow-clip rounded-none border-none bg-muted px-0 [&>svg]:hidden",icon:l.logo,options:a,value:l.value,onValueChange:c=>o(c),label:t,showPlaceholderLabel:!1})}const qr=[{label:"Sum",value:"SUM",logo:e.jsx(tt,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(De,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(ja,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(aa,{className:"size-3.5"})},{label:"Min",value:"MIN",logo:e.jsx(s.ArrowDown,{className:"size-3.5"})},{label:"Max",value:"MAX",logo:e.jsx(s.ArrowUp,{className:"size-3.5"})}];function Hr({column:t}){const{updateMetricColumnOld:n}=s.useEditorActions();let a=qr;s.isTextDataType(t.type)&&(a=a.filter(l=>["COUNT","DISTINCT"].includes(l.value))),s.isNumberDataType(t.type)&&(a=a.filter(l=>!["DISTINCT"].includes(l.value)));function r(l){const o={...t,aggregate:l,label:qe(t.name,l)};n(t.id,o)}return e.jsx(_t,{column:t,functions:a,onFunctionChange:l=>r(l),label:"Aggregation"})}const Wr=[{label:"Day (D)",value:"day",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"D"})},{label:"Week (W)",value:"week",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"W"})},{label:"Month (M)",value:"month",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"M"})},{label:"Year (Y)",value:"year",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"Y"})}];function Kr({column:t}){const{updateGroupByColumnOld:n}=s.useEditorActions();function a(r){const l={...t,granularity:r,label:_e(t.name,r)};n(t.id,l)}return e.jsx(_t,{column:t,functions:Wr,onFunctionChange:r=>a(r),label:"Granularity"})}function Qr({col:t,onChange:n,droppableId:a}){const{columns:r}=s.useDataColumns(),l=A.useMemo(()=>{let i=[];(a===Ie||a===Ae||a===Me)&&(i=r);const d=i==null?void 0:i.filter(u=>u.column_name!==t.name);return d==null?void 0:d.map(u=>({id:u.column_name,value:u.column_name}))},[r,a,t.name]),o=[{id:t.name,value:t.name}];function c(i){const d=r==null?void 0:r.find(u=>{var m;return u.column_name===((m=i[0])==null?void 0:m.id)});d&&n(d)}return l!=null&&l.length?e.jsx(s.ComboBox2,{multiple:!1,options:l,selectedOptions:o,onChange:c,selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"border-none bg-muted pl-0 pr-8"}):e.jsx("input",{disabled:!0,type:"text",className:"overflow-hidden truncate text-ellipsis whitespace-nowrap bg-muted text-sm",value:t.name})}function Vt({column:t}){const n=s.useEditorStore(d=>d.card.type),a=s.useEditorStore(d=>{var u,m;return(m=(u=d.card)==null?void 0:u.config)==null?void 0:m.metricColumns}),r=(a==null?void 0:a.map(d=>d.label))||[],l=r==null?void 0:r.find(d=>d===t.label||d===t.name),o=l?r.indexOf(l):-1;function c(){return e.jsx("div",{className:"pr-1",children:l&&e.jsx(Lt,{idx:o,col:l,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function i(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(Rt,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&c(),["pie","doughnut"].includes(n)&&i()]})}function Jr({column:t,type:n,onRemoveColumn:a,droppableId:r}){const[l,o]=A.useState(!1),{updateGroupByColumnOld:c,updateMetricColumnOld:i,updatePivotByColumnOld:d}=s.useEditorActions(),{attributes:u,listeners:m,setNodeRef:h,transform:p,transition:g,isDragging:b}=s.useSortable({id:t.id,data:{type:n}}),x=p?{opacity:b?.5:void 0,transform:s.CSS.Translate.toString(p),transition:g}:void 0,j=s.isTextDataType(t.type);function f(D){const v=s.isNumberDataType(D.data_type),N=s.isTextDataType(D.data_type),S=s.isDateDataType(D.data_type),F=v?"number":N?"string":S?"date":"string";if(r===Ie){if(N){const I={id:t.id,name:D.column_name,type:F,role:"groupby"};c(t.id,I)}if(S){const I={id:t.id,name:D.column_name,type:F,role:"groupby",label:_e(D.column_name,"month"),granularity:"month"};c(t.id,I)}}if(r===Me){if(N){const I={id:t.id,name:D.column_name,type:F,role:"groupby"};d(t.id,I)}if(S){const I={id:t.id,name:D.column_name,type:F,label:_e(D.column_name,"month"),granularity:"month",role:"groupby"};d(t.id,I)}}if(r===Ae){const I={id:t.id,name:D.column_name,type:F,role:"metric",label:qe(D.column_name,"SUM"),aggregate:v?"SUM":"COUNT"};i(t.id,I)}}function y(){if(r===Ae)return e.jsx("div",{"data-setting-container":"",className:"mt-1.5 max-h-32 overflow-y-auto rounded-md border border-border p-3 text-sm",children:e.jsx(Vt,{column:t})})}function E(){const D=s.isDateDataType(t.type);if(r===Ae)return e.jsx(Hr,{column:t});if((r===Ie||r===Me)&&D)return e.jsx(Kr,{column:t})}function k(){return e.jsx("div",{className:s.cn("grow",{"pl-3":(r===Ie||r===Me)&&j}),children:e.jsx(Qr,{col:t,onChange:f,droppableId:r})})}function C(){return e.jsx("div",{"data-setting-actions":"",className:"flex h-full items-center gap-2",children:e.jsx("button",{className:"h-full pl-2",onClick:()=>o(!l),children:l?e.jsx(_a,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(et,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...m,...u,ref:h,style:x,children:e.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex h-8 grow items-center justify-between rounded-md bg-muted",children:[C(),E(),k()]}),l&&y()]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:l}),children:e.jsx("button",{onClick:()=>a(t.id),children:e.jsx(s.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function gs({id:t,label:n,columns:a,previewColumns:r,sortableType:l,onRemoveColumn:o}){var x,j;const{setNodeRef:c,isOver:i,over:d}=s.useDroppable({id:t}),u=s.useDndStore(f=>f.activeId),m=s.useEditorStore(f=>{var y;return(y=f.card)==null?void 0:y.type}),h=i||((j=(x=d==null?void 0:d.data)==null?void 0:x.current)==null?void 0:j.type)===l,p=u?r:a,g=l===as?"Rows":l===ns?"Pivot Columns":"Columns";function b(){if(!p||p.length===0)return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}return e.jsx(s.SortableContext,{items:a==null?void 0:a.map(f=>f.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md p-4",h&&"border border-muted-foreground/20"),ref:c,children:[e.jsxs("div",{className:"flex items-center justify-between pr-5",children:[e.jsx(s.Label,{className:"text-sm",children:n}),m!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:g})]}),b(),e.jsx("div",{className:"space-y-2",children:p==null?void 0:p.map(f=>f.id===gt.id?e.jsx(Xr,{},f.id):e.jsx(Jr,{droppableId:t,type:l,column:f,onRemoveColumn:o},f.id))})]})})}function Xr(){return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm",children:e.jsx("span",{className:"text-muted-foreground/70",children:"Drop here"})})}function Ut({children:t,id:n,type:a}){const{attributes:r,listeners:l,setNodeRef:o,transform:c,transition:i,isDragging:d}=s.useSortable({id:n,data:{type:a}}),u=c?{opacity:d?.5:void 0,transform:s.CSS.Translate.toString(c),transition:i}:void 0;return e.jsx("div",{...l,...r,ref:o,style:u,children:t})}function Zr(){const t=s.useEditorStore(f=>{var y;return(y=f.card.queryConfig)==null?void 0:y.orderBy})||[],n=s.useEditorStore(f=>{var y;return(y=f.card.queryConfig)==null?void 0:y.groupByColumns})||[],a=s.useEditorStore(f=>{var y;return(y=f.card.queryConfig)==null?void 0:y.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:l,updateOrderByColumn:o}=s.useEditorActions(),c=[...n,...a];if(c.length===0)return e.jsx(e.Fragment,{});const i=e.jsx(ra,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx(ta,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=e.jsx(na,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=e.jsx(sa,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=c==null?void 0:c.filter(f=>!t.some(y=>y.columnId===f.id)).map(f=>({id:f.id,value:f.label||f.name}));function p(f,y){const E=g(f);return E?E.role==="metric"?y==="asc"?u:m:y==="asc"?i:d:null}function g(f){return c.find(y=>y.id===f)}function b(f){const y=t.find(E=>E.columnId===f);if(y){const E={...y,direction:y.direction==="asc"?"desc":"asc"};o(E)}}const x=f=>{r({columnId:f.id,direction:"asc"})};function j(f){const y=t.find(E=>E.columnId===f);y&&l(y)}return e.jsx(s.SortableContext,{items:t.map(f=>Ge(f.columnId)),children:e.jsxs("div",{className:"space-y-2 rounded-md p-4 text-sm",children:[e.jsx(s.Label,{className:"text-sm",children:"Sort By"}),h.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(s.ComboBox2,{multiple:!1,options:h,selectedOptions:[],onChange:f=>x(f[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),t.map(f=>{var y,E;return e.jsx(Ut,{id:Ge(f.columnId),type:ws,children:e.jsx("div",{className:"group flex h-8 items-center gap-2 rounded-sm p-0",children:e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2 rounded-sm bg-muted px-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(et,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(cs,{className:"w-[175px] text-sm",children:((y=g(f.columnId))==null?void 0:y.label)||((E=g(f.columnId))==null?void 0:E.name)})]}),e.jsx("button",{title:f.direction==="asc"?"Ascending":"Descending",onClick:()=>b(f.columnId),className:"rounded-sm p-0",children:p(f.columnId,f.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>j(f.columnId),className:"rounded-sm p-0",children:e.jsx(s.X,{className:"size-3 text-muted-foreground opacity-0 transition-opacity duration-200 hover:text-foreground group-hover:opacity-100"})})})]})},f.columnId)},Ge(f.columnId))})]})})}function el(){const t=s.useEditorStore(j=>{var f;return((f=j.card.queryConfig)==null?void 0:f.groupByColumns)||[]}),n=s.useEditorStore(j=>j.card.type),a=s.useDndStore(j=>j.previewGroupByColumns),r=s.useEditorStore(j=>{var f;return((f=j.card.queryConfig)==null?void 0:f.metricColumns)||[]}),l=s.useDndStore(j=>j.previewMetricColumns),o=s.useEditorStore(j=>{var f;return((f=j.card.queryConfig)==null?void 0:f.pivotColumns)||[]}),c=s.useDndStore(j=>j.previewPivotColumns),{removeColumnFromGroupBy:i,removeColumnFromMetricColumns:d,removeColumnFromPivotBy:u}=s.useEditorActions();function m(j){i(j)}function h(j){d(j)}function p(j){u(j)}let g="Group By",b="Metrics",x="Stack By";return n==="table"&&(g="Rows",b="Metrics",x="Columns"),e.jsxs("div",{className:"flex h-full w-full flex-col gap-3 py-4",children:[e.jsx(Tt,{iconClassName:"size-[19px]"}),e.jsxs(s.CustomScrollArea,{className:"flex min-h-0 grow basis-0 flex-col gap-4 overflow-y-auto",children:[e.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[e.jsx(gs,{onRemoveColumn:m,sortableType:as,id:Ie,label:g,columns:t,previewColumns:a}),e.jsx(gs,{onRemoveColumn:p,sortableType:ns,id:Me,label:x,columns:o,previewColumns:c}),e.jsx(gs,{onRemoveColumn:h,sortableType:ys,id:Ae,label:b,columns:r,previewColumns:l}),e.jsx(Zr,{})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Ms({children:t,column:n,id:a,sortableType:r,className:l}){const[o,c]=A.useState(!1),{removeEditorFilter:i,clearEditorFilter:d}=s.useEditorActions(),u=s.useEditorStore(h=>{var p,g;return(g=(p=h.card.queryConfig)==null?void 0:p.filters)==null?void 0:g.some(b=>b.filterColumnName===n.name)});function m(h){i(h)}return e.jsx(Ut,{id:a,type:r,children:e.jsxs("div",{className:s.cn("group space-y-1 rounded-md bg-muted px-3 py-2",{"border-border":o}),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-sm",children:n.name}),u&&e.jsx("button",{onClick:()=>d(n),children:e.jsx(s.FilterX,{className:"size-3 cursor-pointer items-center justify-center text-muted-foreground hover:text-foreground"})})]}),e.jsx("div",{"data-setting-actions":"",className:"invisible flex h-full items-center gap-2 group-hover:visible",children:e.jsx("button",{onClick:()=>m(n),children:e.jsx(s.X,{className:"size-3.5 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground"})})})]}),e.jsxs("div",{className:s.cn("group flex items-center rounded-t-md text-sm",!o&&"rounded-b-md",o&&"border border-border"),children:[e.jsx("div",{children:e.jsx(s.GripVertical,{className:"mr-2 size-3.5 cursor-move items-center justify-center p-0 text-muted-foreground/60 hover:text-foreground"})}),e.jsx("div",{className:s.cn("grow cursor-pointer overflow-hidden truncate text-ellipsis whitespace-nowrap",l),children:t})]})]})})}function sl({column:t,sortableType:n}){const a=s.useDashboardStore(E=>E.themeStyle),r=s.useEditorStore(E=>{var k,C;return(C=(k=E.card)==null?void 0:k.queryConfig)==null?void 0:C.filters}),l=s.useEditorStore(E=>{var k,C;return(C=(k=E.card.queryConfig)==null?void 0:k.filterColumns)==null?void 0:C.find(D=>D.name===t.name)}),{selectedConnectionId:o,selectedDatabaseName:c,selectedTableName:i}=s.useEditorAside(),d=A.useMemo(()=>{var E;return(E=r==null?void 0:r.find(k=>k.filterColumnName===t.name))==null?void 0:E.filterValue},[r,t.name]),u=A.useMemo(()=>Array.isArray(d)?d.map(E=>({id:E,value:E})):[],[d]),{updateEditorFilterValue:m}=s.useEditorActions(),h={column:t.name,sql:t.sql,id:t.name,connectionId:o,dataType:t.type},{data:p,isLoading:g,isFetching:b,isError:x}=s.useFilterQuery(h),j=A.useMemo(()=>{var k;return h.column?(k=p==null?void 0:p.records)==null?void 0:k.map(C=>{let D=h.column.split(".").slice(-1)[0].replace(/"/g,"");return C[D]===void 0&&(D=D.toLowerCase()),{id:C[D],value:C[D]}}):[]},[p,h.column]);function f(E){const k=E.map(C=>C.id);m(t.name,k)}function y(){return g||b?e.jsx(s.Skeleton,{style:{borderRadius:a==null?void 0:a.controlInputRadius},className:"h-8 min-w-60 bg-foreground/10"}):x?e.jsx("div",{className:"flex h-8 min-w-60 items-center bg-muted px-2 text-sm",children:"Error"}):e.jsx(s.ComboBox2,{renderFilterModeButton:()=>e.jsx(tl,{columnName:t.name}),showNegativeIndicator:(l==null?void 0:l.mode)==="exclude",options:j,onChange:f,selectedOptions:u,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(Ms,{className:"w-60",id:t.id,sortableType:n,column:t,children:y()})}function tl({columnName:t}){const{setEditorFilterMode:n}=s.useEditorActions(),a=s.useEditorStore(l=>{var o,c;return(c=(o=l.card.queryConfig)==null?void 0:o.filterColumns)==null?void 0:c.find(i=>i.name===t)});function r(){(a==null?void 0:a.mode)==="exclude"?n(t,"include"):n(t,"exclude")}return e.jsx(s.Button,{onClick:r,variant:"secondary",size:"sm",className:s.cn("h-5 text-xs hover:underline",{}),children:s.titleCase((a==null?void 0:a.mode)==="exclude"?"exclude":"include")})}function al({open:t,setOpen:n,dateRange:a,setDateRange:r,containerClassName:l,inputClassName:o,title:c,onApply:i,onClear:d}){const u=s.useDashboardStore(m=>m.themeStyle);return e.jsx("div",{className:s.cn("grid gap-2",l),children:e.jsxs(s.Popover,{open:t,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{style:{borderRadius:u==null?void 0:u.controlInputRadius},asChild:!0,children:e.jsxs(s.Button,{size:"sm",id:"date",variant:"outline",className:s.cn("h-9 w-full justify-start rounded-sm text-left font-normal",!a&&"text-muted-foreground",o),children:[e.jsx(s.Calendar,{className:"mr-2 h-4 w-4"}),a!=null&&a.from?a.to?e.jsxs(e.Fragment,{children:[s.format(a.from,"LLL dd, y")," -"," ",s.format(a.to,"LLL dd, y")]}):s.format(a.from,"LLL dd, y"):e.jsx("span",{children:"Pick a date"})]})}),e.jsxs(s.PopoverContent,{style:{borderRadius:u==null?void 0:u.controlInputRadius},className:"w-auto p-0",align:"start",children:[e.jsx("div",{className:"px-4 pt-3",children:e.jsx(s.Label,{children:c})}),e.jsx(s.Calendar$1,{initialFocus:!0,mode:"range",defaultMonth:a==null?void 0:a.from,selected:a,onSelect:r,numberOfMonths:2}),e.jsxs("div",{className:"flex justify-end gap-2 px-4 py-3",children:[e.jsx(s.Button,{style:{borderRadius:u==null?void 0:u.controlInputRadius},size:"sm",variant:"outline",onClick:m=>{m.stopPropagation(),i(a),n(!1)},children:"Apply"}),e.jsx(s.Button,{style:{borderRadius:u==null?void 0:u.controlInputRadius},size:"sm",variant:"outline",onClick:d,children:"Clear"})]})]})]})})}function nl({column:t,sortableType:n}){const[a,r]=A.useState(!1),{selectedConnectionId:l,selectedDatabaseName:o,selectedTableName:c}=s.useEditorAside(),i={column:t.name,sql:t.sql,id:t.name,connectionId:l,title:"",dataType:t.type},{isLoading:d,isFetching:u,isError:m,data:h}=s.useFilterQuery(i),p=h==null?void 0:h.records,{dateRange:g,setDateRange:b,initialDateRange:x}=s.useDateRangeFromRecords(p),{updateEditorFilterValue:j}=s.useEditorActions();function f(k){var D,v;const C={gte:(D=k==null?void 0:k.from)==null?void 0:D.toISOString(),lte:(v=k==null?void 0:k.to)==null?void 0:v.toISOString()};j(t.name,C)}function y(){j(t.name,null,!0),b(x)}function E(){return d||u?e.jsx("div",{children:e.jsx(s.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):m?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):p?e.jsx(al,{title:i.title,open:a,inputClassName:"h-8",setOpen:r,dateRange:g,setDateRange:b,onApply:f,onClear:y}):e.jsx(s.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(Ms,{className:"w-72",id:t.id,sortableType:n,column:t,children:E()})}function rl({id:t,label:n,columns:a,previewColumns:r,sortableType:l}){var b,x;const{setNodeRef:o,isOver:c,over:i}=s.useDroppable({id:t}),d=s.useDndStore(j=>j.activeId),u={},m=c||((x=(b=i==null?void 0:i.data)==null?void 0:b.current)==null?void 0:x.type)===l;function h(){if(!g||g.length===0)return e.jsx("div",{className:"flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}function p(j){const f=s.isDateDataType(j.type);return j.id===gt.id?e.jsx(Ms,{id:j.id,sortableType:l,column:j,children:e.jsx(ll,{})},j.id):f?e.jsx(nl,{droppableId:t,sortableType:l,column:j},j.id):e.jsx(sl,{droppableId:t,sortableType:l,column:j},j.id)}const g=d?r:a;return e.jsx(s.SortableContext,{items:a==null?void 0:a.map(j=>j.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",m&&"border border-muted-foreground/20"),ref:o,style:u,children:[e.jsx(s.Label,{className:"text-sm",children:n}),h(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:g==null?void 0:g.map(j=>p(j))})]})})}function ll(){return e.jsx("div",{className:"flex h-8 w-60 items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm text-muted-foreground",children:"Drop here"})}function ol(){const t=s.useEditorStore(l=>{var o;return((o=l.card.queryConfig)==null?void 0:o.filterColumns)||[]}),n=s.useDndStore(l=>l.previewFilterColumns),{removeColumnFromFilterColumns:a}=s.useEditorActions();function r(l){a(l)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(rl,{onRemoveColumn:r,sortableType:Cs,id:Ns,label:"Filters",columns:t,previewColumns:n})})}function il(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>c.showAIDialog),{setShowAIDialog:a}=s.useEditorActions(),{data:r,errorMessage:l,errorSql:o}=s.useDashboardCardQuery(t);return e.jsxs("section",{className:"flex justify-between gap-2 p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(os,{}),!n&&e.jsxs(s.Button,{onClick:()=>a(!0),variant:"secondary",size:"sm",children:[e.jsx(Ea,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(yt,{sql:r==null?void 0:r.sql,error:l,errorSql:o})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-green-300 px-3 py-1 text-xs font-medium text-black",children:"Preview"}),e.jsx(Es,{}),e.jsx(ks,{variant:"default"})]})]})}function cl(){const t=A.useRef(null),n=A.useRef(null),a=s.useEditorStore(i=>i.isShowingVisual),r=s.useEditorStore(i=>i.showAIDialog),l=s.useEditorStore(i=>i.isDevMode);A.useEffect(()=>{var i,d,u,m;r?((i=t.current)==null||i.resize(0),(d=n.current)==null||d.resize(0)):((u=t.current)==null||u.resize(25),(m=n.current)==null||m.resize(25))},[r]);function o(){return e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(Jn,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:a&&!r?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:t,className:"flex",defaultSize:25,maxSize:30,children:e.jsx($r,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(Je,{})})]}):e.jsx(Je,{})})]})}function c(){return e.jsx(e.Fragment,{children:e.jsx("div",{className:"grow","data-biz-mode-container":"",children:a?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:n,defaultSize:25,maxSize:30,children:e.jsx(el,{})})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{defaultSize:75,maxSize:100,children:e.jsxs(s.ResizablePanelGroup,{direction:"vertical",children:[e.jsxs(s.ResizablePanel,{className:"flex min-h-fit flex-col",minSize:10,defaultSize:20,children:[e.jsx(il,{}),e.jsx(ol,{})]}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(Je,{})})]})})]}):e.jsx(Je,{})})})}return e.jsx(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:l?o():c()})}function dl(t){s.useAIInteractionStore(z=>z.currentAIContext);const[n,a]=A.useState(""),[r,l]=A.useState(null),{authToken:o,tokenProps:c}=s.useSemaphorContext(),i=s.useEditorStore(z=>{var te;return(te=z==null?void 0:z.card)==null?void 0:te.sql}),d=s.useEditorStore(z=>z.isDevMode),u=s.useEditorStore(z=>{var te;return(te=z==null?void 0:z.card)==null?void 0:te.python}),{setCardPython:m,setCardSql:h,setRunSql:p,switchCardType:g,setQueryConfig:b}=s.useEditorActions(),x=s.useEditorStore(z=>z.currentAssitantScope)||[],j=s.useEditorStore(z=>z.userInputForAI),f=s.useEditorStore(z=>z.triggerAIRun),y=s.useEditorStore(z=>z.card),E=s.useEditorStore(z=>z.selectedDatabaseName),k=s.useEditorStore(z=>z.selectedTableName),C=s.useEditorStore(z=>z.selectedConnectionId),D=s.useEditorStore(z=>z.selectedSchemaName),v=s.useDashboardStore(z=>z.dashboard.aiScopeTables),{errorMessage:N,refetch:S,data:F}=s.useDashboardCardQuery(y),{setTriggerAIRun:I,setCurrentAssitantScope:P,setCardConfig:T}=s.useEditorActions(),{selectedDatamodelName:w,connectionType:L,selectedDatamodelId:O}=s.useEditorAside(),{messages:R,setMessages:M,regenerate:B,error:Y,sendMessage:_,status:Q,addToolResult:X,stop:q,clearError:W}=s.useChat({transport:new s.DefaultChatTransport({api:`${c.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${o==null?void 0:o.accessToken}`}),body:()=>{const z=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",isDevMode:d,aiContext:z.currentAIContext,reasoningEffort:z.reasoningEffort,showReasoning:z.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:z,body:te})=>({body:{...te,messages:s.cleanupIncompleteMessages(z)}})}),onError:z=>{console.log("on error",z)},onToolCall:G,onFinish(){a("")}});A.useEffect(()=>{f&&j&&(_({role:"user",parts:[{type:"text",text:j}]}),I(!1))},[f,j,_,I]);async function G({toolCall:z}){var te,oe,re,J,ce,de,fe,$,K,Z,le,ne,je,xe,We,Ke;if(["createChartFromSql","createForecast"].includes(z.toolName)){const Ue=((te=z.input)==null?void 0:te.sql)??((oe=z.args)==null?void 0:oe.sql),Te=((re=z.input)==null?void 0:re.python)??((J=z.args)==null?void 0:J.python),he=((ce=z.input)==null?void 0:ce.chartType)??((de=z.args)==null?void 0:de.chartType);g(he),h(Ue),m(Te),p(!0),X({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(z.toolName==="getUserSql"){if(!i){X({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"error",message:"No SQL found"}});return}X({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",sql:i,python:u||""}})}else if(z.toolName==="generateQueryConfig"){a("Generating query config...");const Ue=((fe=z.input)==null?void 0:fe.chartType)??(($=z.args)==null?void 0:$.chartType),Te=((K=z.input)==null?void 0:K.queryConfig)??((Z=z.args)==null?void 0:Z.queryConfig);((le=z.input)==null?void 0:le.cardConfig)??((ne=z.args)==null||ne.cardConfig),g(Ue),T(Te),h(void 0),m(void 0);const he=await S();if((je=he==null?void 0:he.data)!=null&&je.error){X({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"error",queryConfig:Te,message:(xe=he==null?void 0:he.data)==null?void 0:xe.error.message}});return}if((We=he==null?void 0:he.data)!=null&&We.records){X({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",queryConfig:Te,message:"The data has been visualized"}});return}X({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",queryConfig:Te,message:"The data has been visualized",records:(Ke=he==null?void 0:he.data)==null?void 0:Ke.records}})}else a("Analyzing...")}function se(z){const te=s.removeFromScopeArray(x,z);V(te)}function V(z){const te=s.sanitizeAIScope(z);P(te),M(oe=>[...oe,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(te)}`}]}])}function U(){const z={databaseName:E||"",schemaName:D||"",tableName:k||"",datamodelId:O||"",datamodelName:s.resolveDatamodelName(w),connectionId:C||"",connectionType:L||""},te=s.dedup([...x,z]);V(te)}function ee(){const z={databaseName:E||"",schemaName:D||"",tableName:k||"",datamodelName:s.resolveDatamodelName(w),connectionId:C||"",connectionType:L||"",datamodelId:O||""};if(!s.isInAiScopeArray([...v||[],...x],z)||x.length===0){const oe=s.dedup([...v||[],...x,z]).filter(re=>re.connectionId===z.connectionId);V(oe)}}const ae=!["ready","error"].includes(Q),ie=s.getErrorMessage(Y);return{messages:R,setMessages:M,sendMessage:_,regenerate:B,isLoading:ae,handleSetAIScope:ee,handleAddCurrentTableToScope:U,removeFromCurrentSelections:se,currentAssitantScope:x,setCurrentAssitantScope:P,stop:q,status:Q,toolStatus:n,llmUsage:r,onFinish:t,errorMessage:ie,clearError:W}}const ul=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Ws(){const t=A.useRef(null),[n,a]=A.useState(!1),[r,l]=A.useState(s.isDevEnv),[o,c]=A.useState(!1),[i,d]=A.useState(!1),u=s.useCurrentAIContext(),{setCurrentAIContext:m}=s.useAIActions(),{clearQueue:h}=s.useQueueActions(),{clearFileAttachments:p}=s.useFileActions(),g=s.useFileAttachments("editor"),b=s.useDashboardStore(K=>K.dashboard.aiContext),x=s.useEditorStore(K=>K.card.dataSource),j=s.useEditorStore(K=>K.actions.setCardSql),f=s.useEditorStore(K=>K.actions.setRunSql),y=s.useEditorStore(K=>K.showAIDialog),E=s.useDashboardStore(K=>K.handleOpenAssistantProfile),{setShowAIDialog:k,setCardPython:C}=s.useEditorActions(),{setDataSource:D}=s.useEditorActions(),{assistantProfile:v}=s.useAssistantProfile(),{messages:N,setMessages:S,sendMessage:F,isLoading:I,stop:P,status:T,llmUsage:w,errorMessage:L,clearError:O}=dl(),[R,M]=A.useState(""),B=K=>{M(K.target.value)},Y=K=>{K.preventDefault();const Z=R.trim();if(!Z&&g.length===0)return;const le=[];Z&&le.push({type:"text",text:Z}),g.forEach(ne=>{ne.data&&le.push({type:"file",mediaType:ne.type,filename:ne.name,url:`data:${ne.type};base64,${ne.data}`})}),F({role:"user",parts:le}),M(""),p("editor"),ee({force:!0})},{visibleMessages:_,hasMoreMessages:Q,totalMessageCount:X,loadMoreMessages:q,resetMessageWindow:W}=s.useMessageWindow(N,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:G,isAtBottom:se,hasNewMessages:V,newMessageCount:U,scrollToBottom:ee,handleScroll:ae,resetNewMessageCount:ie}=s.useAutoScroll(_,{threshold:50,delay:0,dependencies:[T,N.length]});A.useEffect(()=>{var K;y&&((K=t.current)==null||K.focus(),m({selectedEntities:(x==null?void 0:x.selectedEntities)||[]}))},[y,x,m]),s.useAutoSubmitQueue({assistantType:"editor",status:T,isLoading:I,sendMessage:F});const{hasActiveTools:z}=s.useActiveToolStatus(N);function te(K,Z){Z==="sql"?(j(K),f(!0)):Z==="python"&&(C(K),f(!0))}function oe(){var K;(K=b==null?void 0:b.selectedEntities)==null||K[0],d(!0)}function re(){u.selectedEntities.length===0&&m({selectedEntities:(b==null?void 0:b.selectedEntities)||[]})}function J(K){re();const Z={role:"user",parts:[{type:"text",text:K.title+" "+K.subtitle}]};F(Z)}function ce(K){re(),F({role:"user",parts:[{type:"text",text:K}]})}function de(){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/50 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:n,onCheckedChange:a,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:r,onCheckedChange:l,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:c,children:"System Message"})]})]})}function fe(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const $=(R==null?void 0:R.length)===0&&(N==null?void 0:N.filter(K=>K.role==="user").length)===0;return e.jsxs("div",{"data-role":"editor-assistant",className:"flex h-full w-full flex-col justify-between px-6 py-4",children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[fe(),E&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:E,children:(v==null?void 0:v.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[de(),s.isDevEnv,e.jsx(s.IconButton,{tooltip:"Add Context",className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",onClick:oe,children:e.jsx(s.Settings,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",tooltip:"New Chat",onClick:()=>{S([]),h("editor"),O(),W()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",size:"sm",onClick:()=>{k(!1)},children:e.jsx(s.X,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:G,className:"mt-2 flex w-full grow basis-0",onScroll:ae,children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[Q&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:q,className:"text-xs",children:["Load ",Math.min(5,X-_.length)," ","more messages (",X-_.length," ","hidden)"]})}),e.jsx(s.PrintMessages,{messages:_,showTools:r,handleRun:te,showSystemMessage:o}),!z&&e.jsx(s.AssistantStatus,{status:T,errorMessage:L})]})}),!se&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{ee({force:!0}),ie()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),V&&U>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:U>9?"9+":U})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[$&&!v&&e.jsx(s.Placeholders,{onClick:J,placeholders:ul}),e.jsx("div",{children:$&&v&&e.jsx(s.SeedQuestions,{seedQuestions:v.seedQuestions||[],handleSeedQuestionClick:ce})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:t,setInput:M,stop:P,input:R,handleInputChange:B,handleSubmit:K=>{re(),Y(K),ee({force:!0})},isLoading:I,status:T,assistantType:"editor",onFocus:()=>{}})]}),w&&n&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",w.inputTokens," prompt tokens, ",w.outputTokens," ","completion tokens, ",w.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(x==null?void 0:x.selectedEntities)||[],open:i,onOpenChange:d,dataSource:x||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}const Ls=t=>{var I;const{updateCardConfig:n,updateGroupByColumn:a,updateMetricColumn:r,updatePivotByColumn:l,updateSortByColumn:o,removeGroupByColumn:c,removeMetricColumn:i,removePivotByColumn:d,removeSortByColumn:u}=s.useEditorActions(),m=s.useEditorStore(P=>P.card.type),h=t==null?void 0:t.id,p=A.useCallback(P=>{if(!(t!=null&&t.config))return[];switch(P){case"groupBy":return(t.config.groupByColumns||[]).map(T=>({id:T.id,name:T.name,dataType:T.dataType,label:T.label!==void 0?T.label:T.name,qualifiedEntityName:T.qualifiedEntityName,entityId:T.entityId,entityName:T.entityName,entityType:T.entityType,dateFormat:T.dateFormat,customFormat:T.customFormat,granularity:T.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(T=>({id:T.id,name:T.name,dataType:T.dataType,label:T.label!==void 0?T.label:T.name,qualifiedEntityName:T.qualifiedEntityName,entityId:T.entityId,entityName:T.entityName,entityType:T.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(T=>({id:T.id,name:T.name,dataType:T.dataType,label:T.label!==void 0?T.label:T.name,qualifiedEntityName:T.qualifiedEntityName,entityId:T.entityId,entityName:T.entityName,entityType:T.entityType,direction:T.direction}));case"source":return[];default:return[]}},[t]),g=A.useCallback((P,T)=>{if(h)switch(P){case"groupBy":{n(h,{groupByColumns:T});break}case"metrics":{n(h,{metricColumns:T});break}case"pivotBy":{n(h,{pivotByColumns:T});break}case"sortBy":{n(h,{sortByColumns:T});break}}},[h,n]),b=A.useCallback((P,T,w)=>{if(!h)return;const O=p(P)[T];if(O)switch(P){case"groupBy":a(h,O.id,{label:w});break;case"metrics":r(h,O.id,{label:w});break;case"pivotBy":l(h,O.id,{label:w});break;case"sortBy":o(h,O.id,{label:w});break}},[h,p,a,r,l,o]),x=A.useCallback((P,T)=>{if(!h)return;const L=p("metrics")[P];L&&r(h,L.id,{aggregate:T,label:s.getAggregationLabel(L.name,T)})},[h,p,r]),j=A.useCallback((P,T,w)=>{if(!h)return;const O=p("groupBy")[P];if(!O)return;const R={dateFormat:T};T==="custom"&&w?R.customFormat=w:R.customFormat=void 0,a(h,O.id,R)},[h,p,a]),f=A.useCallback((P,T)=>{if(!h)return;const L=p("groupBy")[P];L&&a(h,L.id,{granularity:T})},[h,p,a]),y=A.useCallback((P,T)=>{if(!h)return;const L=p("metrics")[P];L&&r(h,L.id,{aliasTemplate:T})},[h,p,r]),E=A.useCallback((P,T)=>{if(console.log("handleValueAliasesChange",P,T),!h)return;console.log("handleValueAliasesChange",P,T);const L=p("metrics")[P];L&&(console.log("handleValueAliasesChange",T),r(h,L.id,{valueAliases:T}))},[h,p,r]),k=A.useCallback(P=>{h&&n(h,{comparisonType:P})},[h,n]),C=A.useCallback(P=>{h&&n(h,{showTrendline:P})},[h,n]),D=A.useCallback(P=>{h&&n(h,{trendlineWindow:P})},[h,n]),v=A.useCallback(P=>{h&&n(h,{trendlineGranularity:P})},[h,n]),N=A.useCallback(P=>{h&&n(h,{targetValue:P})},[h,n]),S=A.useCallback(P=>{var B;if(!h)return;const T=[...p("groupBy"),...p("pivotBy"),...p("metrics"),...p("sortBy")],w=(B=t==null?void 0:t.config)==null?void 0:B.joinPlan,L=s.validateEntityConsistency(P,T,w);if(!L.isValid){L.showError&&s.showJoinRequiredNotification();return}const O=s.getSmartContainerForField(P,T),R=p(O);if(s.fieldAlreadyExists(P,R))return;const M=s.getNewField(P,O,R);M&&g(O,[...R,M])},[h,(I=t==null?void 0:t.config)==null?void 0:I.joinPlan,p,g]),F=A.useCallback((P,T)=>{if(!h)return;const L=p(P)[T];if(L){if(P!=="sortBy"){const O=p("sortBy"),R=O.filter(M=>!(M.name===L.name&&M.qualifiedEntityName===L.qualifiedEntityName));R.length!==O.length&&n(h,{sortByColumns:R})}switch(P){case"groupBy":c(h,L.id);break;case"metrics":i(h,L.id);break;case"pivotBy":d(h,L.id);break;case"sortBy":u(h,L.id);break}}},[h,p,c,i,d,u,n]);return{getFieldsForContainer:p,setFieldsForContainer:g,updateLabel:b,handleAggregationChange:x,handleDateFormatChange:j,handleGranularityChange:f,handleAliasTemplateChange:y,handleValueAliasesChange:E,removeField:F,handleFieldClick:S,handleKpiComparisonTypeChange:k,handleKpiShowTrendlineChange:C,handleKpiTrendlineWindowChange:D,handleKpiTrendlineGranularityChange:v,handleKpiTargetValueChange:N,cardType:m}};function ml({field:t}){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}),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 hl({field:t}){const{attributes:n,listeners:a,setNodeRef:r,transform:l,transition:o,isDragging:c}=s.useSortable({id:t.id}),[i,d]=A.useState(!1),u=s.useEditorStore(b=>b.card),{handleFieldClick:m}=Ls(u),h={transform:s.CSS.Transform.toString(l),transition:o};s.getDataType(t.dataType);const p=b=>{const x=(b||"").toLowerCase();switch(s.getDataType(x)){case"number":return De;case"date":return s.Calendar;case"boolean":return Le;case"json":return Be;case"geo":return Ye;default:return ve}},g=b=>{const x=(b||"").toLowerCase(),j=s.getDataType(x);return j==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ve,{className:"h-3 w-3"})}):j==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):j==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):j==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Le,{className:"h-3 w-3"})}):j==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Be,{className:"h-3 w-3"})}):j==="geo"?e.jsx("div",{className:"bg-orange -100 flex size-6 shrink-0 items-center justify-center rounded-sm text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Ye,{className:"h-3 w-3"})}):j==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(He,{className:"h-3 w-3"})}):null};return p(t.dataType),e.jsxs("div",{ref:r,style:h,...n,...a,className:`group/container max-w-[265px] overflow-hidden rounded-lg transition-all ${c?"scale-95 opacity-50":"border border-transparent hover:bg-muted"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:()=>m(t),children:[g(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-xs text-foreground/80 hover:text-foreground dark:text-muted-foreground ${i?"whitespace-normal break-words":"truncate"}`,children:t.label||t.name})})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:e.jsx(ml,{field:t})})]})})]}),i&&e.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:e.jsx(s.Card,{className:"",children:e.jsxs(s.CardContent,{className:"space-y-2 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nt,{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(Ya,{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})]})})})]})}function xl(){const[t,n]=A.useState(""),[a,r]=A.useState("all"),l=s.useEditorStore(E=>E.card.dataSource),{columns:o=[],columnGroups:c=[],isLoading:i,error:d}=s.useColumns(),u=o.filter(E=>E.name.toLowerCase().includes(t.toLowerCase())||E.dataType.toLowerCase().includes(t.toLowerCase())||E.qualifiedEntityName&&E.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),m=E=>{if(E.dataType==="number"||E.dataType==="integer"||E.dataType==="float"||E.dataType==="decimal"||E.dataType==="currency")return"metrics";const k=s.getDataType(E.dataType);return["date","string","boolean"].includes(k)?"dimensions":k==="number"?"metrics":"dimensions"},p=(a==="all"?u:u.filter(E=>m(E)===a)).reduce((E,k)=>{const C=k.qualifiedEntityName||"Other Fields";return E[C]||(E[C]={label:s.toLabel(k.entityName),fields:[]}),E[C].fields.push(k),E},{}),b=Object.keys(p),x=u.filter(E=>m(E)==="dimensions").length,j=u.filter(E=>m(E)==="metrics").length,f=u.filter(E=>m(E)==="calculated").length,y=u.length>0;return i?e.jsx("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):d?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] 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:d.message||"Failed to load column data"})]}):!l||!l.selectedEntities||l.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:"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-[calc(100vh-200px)] 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:[o.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:t,onChange:E=>n(E.target.value)}),t&&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"})})]}),y&&e.jsx(s.Tabs,{defaultValue:"all",value:a,onValueChange:E=>r(E),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:u.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:x})]}),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:j})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(He,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:f})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:b,className:"space-y-2",children:Object.entries(p).map(([E,k])=>{const C=c.find(D=>D.entityName===E)||{entityName:E,label:k.label};return e.jsxs(s.AccordionItem,{value:E,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:C.label||C.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:C.label||C.entityName}),e.jsx(s.Badge,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:k.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:k.fields.map(D=>e.jsx(hl,{field:D},D.id))})})]},E)})}),Object.keys(p).length===0&&o.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:"Try selecting different data sources"})]}),Object.keys(p).length===0&&o.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 pl(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(xl,{})," "]})}function fl({initialJoinPlan:t,availableDataSources:n}){const[a,r]=A.useState(t),[l,o]=A.useState(new Set),c=()=>{const D=a.joins.length>0?Math.max(...a.joins.map(N=>N.sequence))+1:1,v={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:D,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...a,joins:[...a.joins,v]}),o(new Set([...l,v.id]))},i=D=>{r({...a,joins:a.joins.filter(v=>v.id!==D)}),o(new Set([...l].filter(v=>v!==D)))},d=(D,v)=>{var I,P;const N=a.joins.find(T=>T.id===D);if(!N)return;const S={...N,...v},F=a.joins.map(T=>T.id===D?S:T);if((I=S.source)!=null&&I.name&&((P=S.target)!=null&&P.name)&&S.joinKeyGroups[0].keys.length===0){const T=n.find(R=>{var M;return R.name===((M=S.source)==null?void 0:M.name)}),w=n.find(R=>{var M;return R.name===((M=S.target)==null?void 0:M.name)}),L={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(T==null?void 0:T.name)||"",entityName:(T==null?void 0:T.name)||"",entityType:(T==null?void 0:T.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(w==null?void 0:w.name)||"",entityName:(w==null?void 0:w.name)||"",entityType:(w==null?void 0:w.type)||"table"},operator:"="},O=[...S.joinKeyGroups];O[0]={...O[0],keys:[L]},S.joinKeyGroups=O,F[F.findIndex(R=>R.id===D)]=S}r({...a,joins:F})};return{joinPlan:a,expandedJoins:l,setJoinPlan:r,addJoin:c,removeJoin:i,updateJoin:d,moveJoinUp:D=>{const v=a.joins.findIndex(N=>N.id===D);if(v>0){const N=[...a.joins],S={...N[v]},F={...N[v-1]};N[v]=F,N[v-1]=S,N.forEach((P,T)=>{P.sequence=T+1});const I={...a,joins:N};r(I)}},moveJoinDown:D=>{const v=a.joins.findIndex(N=>N.id===D);if(v<a.joins.length-1){const N=[...a.joins],S={...N[v]},F={...N[v+1]};N[v]=F,N[v+1]=S,N.forEach((P,T)=>{P.sequence=T+1});const I={...a,joins:N};r(I)}},toggleJoinExpansion:D=>{const v=new Set(l);v.has(D)?v.delete(D):v.add(D),o(v)},getAvailableSourceEntities:D=>{if(a.joins.length===0)return n;const v=a.joins.findIndex(S=>S.id===D);if(v===0)return n;const N=new Set;return a.baseEntity.name&&N.add(a.baseEntity.name),a.joins.slice(0,v).forEach(S=>{N.add(S.source.name),N.add(S.target.name)}),n.filter(S=>N.has(S.name))},getAvailableTargetEntities:D=>n.filter(v=>v.name!==D),addJoinKeyGroup:D=>{const v=a.joins.find(S=>S.id===D);if(!v)return;const N=[...v.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];d(D,{joinKeyGroups:N})},updateGroupOperator:(D,v,N)=>{const S=a.joins.find(I=>I.id===D);if(!S)return;const F=[...S.joinKeyGroups];F[v]={...F[v],operator:N},d(D,{joinKeyGroups:F})},removeJoinKeyGroup:(D,v)=>{const N=a.joins.find(F=>F.id===D);if(!N)return;const S=[...N.joinKeyGroups];S.splice(v,1),d(D,{joinKeyGroups:S})},addJoinKey:(D,v)=>{const N=a.joins.find(T=>T.id===D);if(!N)return;const S=n.find(T=>T.name===N.source.name),F=n.find(T=>T.name===N.target.name),I=[...N.joinKeyGroups],P={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(S==null?void 0:S.name)||"",entityName:(S==null?void 0:S.name)||"",entityType:(S==null?void 0:S.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(F==null?void 0:F.name)||"",entityName:(F==null?void 0:F.name)||"",entityType:(F==null?void 0:F.type)||"table"},operator:"="};I[v]={...I[v],keys:[...I[v].keys,P]},d(D,{joinKeyGroups:I})},updateJoinKey:(D,v,N,S,F)=>{const I=a.joins.find(O=>O.id===D);if(!I)return;const P=n.find(O=>O.name===I.source.name),T=n.find(O=>O.name===I.target.name),w=[...I.joinKeyGroups],L=w[v].keys[N];S==="sourceColumnName"&&P?w[v].keys[N]={...L,source:{...L.source,name:F}}:S==="targetColumnName"&&T?w[v].keys[N]={...L,target:{...L.target,name:F}}:S==="operator"&&(w[v].keys[N]={...L,operator:F}),d(D,{joinKeyGroups:w})},removeJoinKey:(D,v,N)=>{const S=a.joins.find(I=>I.id===D);if(!S)return;const F=[...S.joinKeyGroups];F[v].keys.splice(N,1),d(D,{joinKeyGroups:F})},generateSQLPreview:()=>{const D=[...a.joins].sort((S,F)=>S.sequence-F.sequence),v=a.baseEntity;if(!v.name)return"SELECT * FROM table -- Please select a base entity";let N=`SELECT *
|
|
334
|
+
FROM ${v.name}`;return D.forEach(S=>{const F=n.find(T=>T.name===S.target.name);if(!F)return;const I=S.joinKeyGroups.filter(T=>T.keys&&T.keys.length>0).map(T=>{const w=T.keys.filter(L=>{var O,R,M,B;return((O=L.source)==null?void 0:O.name)&&((R=L.target)==null?void 0:R.name)&&((M=L.source)==null?void 0:M.entityName)&&((B=L.target)==null?void 0:B.entityName)}).map(L=>`${L.source.entityName}.${L.source.name} ${L.operator} ${L.target.entityName}.${L.target.name}`);return w.length>1?`(${w.join(` ${T.operator} `)})`:w[0]}).filter(Boolean),P=I.length>1?I.join(" OR "):I[0]||"condition_here";N+=`
|
|
335
|
+
${S.joinType} JOIN ${F.name}
|
|
336
|
+
ON ${P}`}),N},isValidConfiguration:()=>!(!a.baseEntity.name||a.joins.some(S=>!S.source.name||!S.target.name)||a.joins.some(S=>S.joinKeyGroups.some(F=>F.keys.length===0))||a.joins.some(S=>S.joinKeyGroups.some(F=>F.keys.some(I=>!I.source.name||!I.target.name||!I.operator))))}}function gl({joinPlan:t,availableDataSources:n,onSave:a,onRemove:r,onCancel:l}){const{setCardConfig:o}=s.useEditorActions();s.useEditorStore(I=>I.card.config);const{columnGroups:c}=s.useColumns(),{joinPlan:i,expandedJoins:d,setJoinPlan:u,addJoin:m,removeJoin:h,updateJoin:p,moveJoinUp:g,moveJoinDown:b,toggleJoinExpansion:x,getAvailableSourceEntities:j,getAvailableTargetEntities:f,addJoinKeyGroup:y,updateGroupOperator:E,removeJoinKeyGroup:k,addJoinKey:C,updateJoinKey:D,removeJoinKey:v,generateSQLPreview:N,isValidConfiguration:S}=fl({initialJoinPlan:t,availableDataSources:n}),F=I=>{const P=c.find(T=>T.entityName===I);return(P==null?void 0:P.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:i.baseEntity.name,onValueChange:I=>{const P=n.find(T=>T.name===I);u({...i,baseEntity:{connectionId:(P==null?void 0:P.connectionId)||"",connectionType:(P==null?void 0:P.connectionType)||"none",type:(P==null?void 0:P.type)||"table",name:I,database:P==null?void 0:P.database,schema:P==null?void 0:P.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:n.map(I=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:I.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:I.type}),I.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},I.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:N()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{children:["Joins Configuration (",i.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:m,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),i.joins.length===0?e.jsx("div",{className:"rounded-lg border border-dashed py-8 text-center text-muted-foreground",children:e.jsx("p",{children:"No joins configured. Add a join to connect multiple data sources."})}):e.jsx("div",{className:"max-h-[300px] space-y-4 overflow-y-auto",children:i.joins.map(I=>{const P=n.find(L=>L.name===I.source.name),T=n.find(L=>L.name===I.target.name),w=d.has(I.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:I.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",I.sequence,P&&T&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",P.name," → ",T.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g(I.id),disabled:I.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>b(I.id),disabled:I.sequence===i.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>x(I.id),children:w?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>h(I.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),w&&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:I.source.name,onValueChange:L=>{const O=n.find(R=>R.name===L);p(I.id,{source:{connectionId:(O==null?void 0:O.connectionId)||"",connectionType:(O==null?void 0:O.connectionType)||"none",type:(O==null?void 0:O.type)||"table",name:L,database:O==null?void 0:O.database,schema:O==null?void 0:O.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:j(I.id).map(L=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:L.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:L.type}),L.name]})},L.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:I.joinType,onValueChange:L=>p(I.id,{joinType:L}),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:I.target.name,onValueChange:L=>{const O=n.find(R=>R.name===L);p(I.id,{target:{connectionId:(O==null?void 0:O.connectionId)||"",connectionType:(O==null?void 0:O.connectionType)||"none",type:(O==null?void 0:O.type)||"table",name:L,database:O==null?void 0:O.database,schema:O==null?void 0:O.schema}})},disabled:!I.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:I.source.name?f(I.source.name).map(L=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:L.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:L.type}),L.name,L.name===I.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},L.name)):[]})]})]})]}),I.source.name&&I.target.name&&P&&T&&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:()=>y(I.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),I.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:I.joinKeyGroups.map((L,O)=>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 ",O+1]}),O>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:L.operator,onValueChange:R=>E(I.id,O,R),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:()=>k(I.id,O),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[L.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:L.keys.map((R,M)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[M>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:L.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:R.source.name,onValueChange:B=>D(I.id,O,M,"sourceColumnName",B),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:F(I.source.name).map(B=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:B.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:B.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:B.dataType})]})},B.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:R.operator,onValueChange:B=>D(I.id,O,M,"operator",B),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:R.target.name,onValueChange:B=>D(I.id,O,M,"targetColumnName",B),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:F(I.target.name).map(B=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:B.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:B.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:B.dataType})]})},B.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>v(I.id,O,M),children:e.jsx(s.X,{className:"size-3.5"})})]},R.id||M))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>C(I.id,O),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},L.id))})]})]})]},I.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),l()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:l,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>a(i),disabled:!S(),children:"Save"})]})]})}function Ks({children:t,open:n,onOpenChange:a,joinPlan:r,availableDataSources:l,onRemove:o,onSave:c,onCancel:i}){return e.jsxs(s.Dialog,{open:n,onOpenChange:a,children:[e.jsxs(s.DialogContent,{className:"max-w-4xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Join Configuration"}),e.jsx(s.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(gl,{joinPlan:r,availableDataSources:l,onSave:c,onCancel:i,onRemove:o})]}),t]})}function jl({joins:t,baseEntityId:n,availableDataSources:a,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[t.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const l=[...t].sort((c,i)=>c.sequence-i.sequence),o=a.find(c=>c.name===n);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:o==null?void 0:o.type}),e.jsx("span",{className:"text-xs font-medium",children:o==null?void 0:o.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),l.map(c=>{const i=a.find(d=>d.name===c.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name})]})]},c.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",t.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...t].sort((l,o)=>l.sequence-o.sequence).map((l,o)=>{const c=a.find(d=>d.name===l.source.name),i=a.find(d=>d.name===l.target.name);return e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted p-2 text-left",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:o+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:l.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[c==null?void 0:c.name," → ",i==null?void 0:i.name]}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto text-xs",children:[l.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)," ","condition",l.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)>1?"s":""]})]},l.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function bl(){var m,h;const t=s.useEditorStore(p=>p.card),n=s.useEditorStore(p=>p.actions.updateCardConfig),a=((m=t==null?void 0:t.config)==null?void 0:m.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[r,l]=A.useState(!1),o=((h=t==null?void 0:t.dataSource)==null?void 0:h.selectedEntities)||[],c=p=>{n(t.id,{...t==null?void 0:t.config,joinPlan:p}),l(!1)},i=()=>{n(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},d=()=>{l(!1)},u=()=>{const p=[...a.joins].sort((x,j)=>x.sequence-j.sequence),g=a.baseEntity;if(!g.name)return"SELECT * FROM table -- Please select a base entity";let b=`SELECT *
|
|
337
|
+
FROM ${g.name}`;return p.forEach(x=>{const j=o.find(E=>E.name===x.target.name);if(!j)return;const f=x.joinKeyGroups.filter(E=>E.keys&&E.keys.length>0).map(E=>{const k=E.keys.filter(C=>{var D,v,N,S;return((D=C.source)==null?void 0:D.name)&&((v=C.target)==null?void 0:v.name)&&((N=C.source)==null?void 0:N.entityName)&&((S=C.target)==null?void 0:S.entityName)}).map(C=>`${C.source.entityName}.${C.source.name} ${C.operator} ${C.target.entityName}.${C.target.name}`);return k.length>1?`(${k.join(` ${E.operator} `)})`:k[0]}).filter(Boolean),y=f.length>1?f.join(" OR "):f[0]||"condition_here";b+=`
|
|
338
338
|
${x.joinType} JOIN ${j.name}
|
|
339
|
-
ON ${N}`}),b};return o.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:[a.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:()=>l(!0),children:[e.jsx(s.Link,{className:s.cn("mr-1 h-3 w-3",{"text-blue-500":a.joins.length>0,"text-gray-500":a.joins.length===0})}),"Join",a.joins.length>1?"s":""," (",a.joins.length,")"]})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(gl,{joins:a.joins,baseEntityId:a.baseEntity.name,availableDataSources:o,generateSQLPreview:u})})]})}),e.jsx(Ks,{open:r,onOpenChange:l,joinPlan:a,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsx("div",{})})]}),a.joins.length===0&&e.jsx(Ks,{open:r,onOpenChange:l,joinPlan:a,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsxs(s.Button,{onClick:()=>l(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function bl({open:t,onOpenChange:n}){const[a,r]=M.useState([]),{updateDataSource:l}=s.useEditorActions(),o=s.useDashboardStore(x=>x.dashboard.aiContext),c=(o==null?void 0:o.selectedEntities)||[];M.useEffect(()=>{t&&r([])},[t]);const i=x=>{r(j=>j.some(N=>N.name===x.name&&N.type===x.type)?j.filter(N=>!(N.name===x.name&&N.type===x.type)):[...j,x])},d=()=>{r([...c])},u=()=>{r([])},m=()=>{if(a.length===0)return;const x=a[0],j=x.connectionId||"",f=x.connectionType||"",T=a.some(C=>C.type==="dataset")?"semanticDomain":"database";l({connectionId:j,connectionType:f,mode:T,selectedEntities:a}),n(!1)},h=x=>{switch(x.type){case"table":return e.jsx(s.Table,{className:"h-4 w-4"});case"view":return e.jsx(Ya,{className:"h-4 w-4"});case"model":return e.jsx(ha,{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"})}},p=x=>"label"in x&&x.label?x.label:x.name,g=x=>{if("description"in x&&x.description)return x.description;const j=[];return x.database&&j.push(x.database),x.schema&&j.push(x.schema),x.name&&j.push(x.name),j.join(".")},b=x=>a.some(j=>j.name===x.name&&j.type===x.type);return c.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-md",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"No Data Available"}),e.jsx(s.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{onClick:()=>n(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(s.DialogDescription,{children:"Choose entities from the dashboard's context"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"outline",size:"sm",onClick:d,disabled:a.length===c.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:u,disabled:a.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[a.length," of ",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((x,j)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",b(x)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:b(x),onCheckedChange:()=>i(x)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:h(x)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:p(x)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:g(x)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:x.type})]},`${x.type}-${x.name}-${j}`))})})]}),e.jsx(s.DialogFooter,{children:e.jsx("div",{className:"flex w-full justify-between",children:e.jsxs("div",{className:"flex grow justify-end gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:m,disabled:a.length===0,children:["Select"," ",a.length>0?`(${a.length})`:""]})]})})})]})})}function vl({entity:t,title:n,maxDetails:a=10}){const l=s.getEntityDetails(t).slice(0,a),o=l.find(i=>i.label==="Description"),c=l.filter(i=>i.label==="Description"?!1:!["Connection","Database","Schema"].includes(i.label));return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:n||s.getDisplayName(t)}),o&&e.jsxs("div",{className:"border-t border-border pt-2",children:[e.jsx("div",{className:"mb-1 text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:o.value})]}),c.length>0&&e.jsx("div",{className:"space-y-0.5",children:c.map((i,d)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[i.label,":"]}),e.jsx("span",{className:"font-mono",children:i.value})]},d))})]})})}function yl({entities:t}){return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:[t.length," more entities"]}),e.jsx("div",{className:"space-y-1",children:t.map((n,a)=>{const r=s.getEntityDetails(n),l=r.find(c=>c.label==="Description"),o=r.filter(c=>c.label==="Description"?!1:!["Connection","Database","Schema"].includes(c.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(n)}),l&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:l.value})]}),o.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:o.map((c,i)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[c.label,":"]}),e.jsx("span",{className:"font-mono",children:c.value})]},i))})]},`remaining-${n.type}-${n.name}-${a}`)})})]})})}function Nl({isVisible:t}){const[n,a]=M.useState(!1),[r,l]=M.useState(!1),[o,c]=M.useState(!0),i=s.useEditorStore(h=>h.card.dataSource);s.useCurrentUserInfo();const{updateDataSource:d}=s.useEditorActions(),u={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},m={...u,...i,selectedEntities:(i==null?void 0:i.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:()=>a(!0),children:[e.jsx(s.Database,{className:"mr-2 h-3.5 w-3.5"}),"Add Data"]})}),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:()=>c(!o),className:"size-6 bg-background p-1 py-1 hover:bg-accent",children:o?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 ${o?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[m.selectedEntities.length>0&&e.jsx(s.TooltipProvider,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[m.selectedEntities.slice(0,3).map((h,p)=>e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[s.getDisplayName(h),e.jsx("button",{onClick:g=>{g.stopPropagation();const b=m.selectedEntities.filter(x=>!(x.name===h.name&&x.type===h.type));d({...u,...i,selectedEntities:b})},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(vl,{entity:h})]},`${h.type}-${h.name}-${p}`)),m.selectedEntities.length>3&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:["+",m.selectedEntities.length-3," more"]})}),e.jsx(yl,{entities:m.selectedEntities.slice(3)})]})]})}),e.jsx(jl,{})]})]}),e.jsx(xl,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(i==null?void 0:i.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:a,dataSource:m,fallbackDataSource:u}),e.jsx(bl,{open:r,onOpenChange:l})]})}const Cl="chart-selector-standard-first";function Sl(){const[t,n]=s.useLocalStorageState(Cl,!0);return{standardFirst:t,updatePreference:n}}const Qs=({pluginVisual:t,index:n,onSelect:a})=>{const r=is(t.icon||""),l=t.name.charAt(0).toUpperCase(),o=s.getAutoDetectedChartIcon(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:a,className:"group flex items-center gap-2",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(r,{className:"h-4 w-4"}):o||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:l}),e.jsx("span",{children:t.name})]}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:"opacity-0 outline-none transition-opacity group-hover:opacity-100",children:e.jsx(s.Info,{className:"ml-1 h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"right",children:t.pluginName})]})]})},`${t.url}-${t.name}-${n}`)},Js=["default","standardPlugin","customPlugin"];function wl({selectedChart:t,onChartChange:n}){var k;const[a,r]=M.useState(!1),{data:l}=wt();Sl();const c=((k=s.useEditorStore(C=>C.card).customCardPreferences)==null?void 0:k.url)||"";Ds(c);const{setCardType:i,setCardPreferences:d,setIsDevMode:u}=s.useEditorStore(C=>C.actions),{setCardCustomCfg:m,setCustomCardPreferences:h,setQueryConfig:p}=s.useEditorActions(),[g,b]=s.useLocalStorageState("chart-section-active",null),x=M.useMemo(()=>g?[g,...Js.filter(C=>C!==g)]:Js,[g]);function j(C){m(null),d({}),i(C),["custom","map"].includes(C)&&(u(!0),p(void 0)),n(C),r(!1)}function f(C){m(null),d({}),i("custom"),h({type:"component",visualType:"single",url:C.url,componentName:C.name,icon:C.icon,pluginChartType:C.chartType}),p(void 0),n("custom"),r(!1)}const N=()=>{var w;if(t==="custom"){const v=s.useEditorStore.getState().card;return((w=v==null?void 0:v.customCardPreferences)==null?void 0:w.componentName)||"Custom Visual"}const C=s.chartTypes.find(v=>v.id===t);return(C==null?void 0:C.label)||"Select chart type"},T=()=>{var w,v;if(t==="custom"){const E=s.useEditorStore.getState().card,y=(w=E==null?void 0:E.customCardPreferences)==null?void 0:w.icon,F=(v=E==null?void 0:E.customCardPreferences)==null?void 0:v.componentName;if(y&&F)return e.jsx(Dl,{icon:y,componentName:F});if(F){const I=s.getAutoDetectedChartIcon(F);if(I)return I}return e.jsx($e,{className:"h-4 w-4"})}const C=s.chartTypes.find(E=>E.id===t);if(C){const E=C.icon;return e.jsx(E,{className:"h-4 w-4"})}return e.jsx($e,{className:"h-4 w-4"})};return e.jsx("div",{className:"",children:e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[T(),e.jsx("span",{children:N()})]}),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."}),x.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:g==="default",onCheckedChange:w=>b(w?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:s.chartTypes.map(w=>{const v=w.icon;return e.jsx(s.CommandItem,{value:`${w.label} ${w.id} chart graph visualization`,onSelect:()=>j(w.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(v,{className:"h-4 w-4"}),e.jsx("span",{children:w.label})]})},w.id)})},"default");if(C==="standardPlugin"){const w=l.filter(v=>v.pluginType==="standard");return w.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:g==="standardPlugin",onCheckedChange:v=>b(v?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:w.filter(v=>v.componentType==="chart").map((v,E)=>e.jsx(Qs,{pluginVisual:v,index:E,onSelect:()=>f(v)},`${v.url}-${v.name}-${E}`))},"standardPlugin"):null}if(C==="customPlugin"){const w=l.filter(v=>v.pluginType==="custom");return w.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:g==="customPlugin",onCheckedChange:v=>b(v?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:w.map((v,E)=>e.jsx(Qs,{pluginVisual:v,index:E,onSelect:()=>f(v)},`${v.url}-${v.name}-${E}`))},"customPlugin"):null}return null})]})]})})]})})}const Dl=({icon:t,componentName:n})=>{const a=is(),r=s.getAutoDetectedChartIcon(n);return a?e.jsx(a,{className:"h-4 w-4"}):r||e.jsx($e,{className:"h-4 w-4"})},Tl=[{id:"table",icon:s.Table2,label:"Table"},{id:"bar",icon:s.ChartColumnIncreasing,label:"Bar Chart"},{id:"line",icon:s.ChartLine,label:"Line Chart"},{id:"stackedBar",icon:s.ChartColumnStacked,label:"Stacked Bar",requiresPivot:!0},{id:"pie",icon:s.ChartPie,label:"Pie Chart"},{id:"doughnut",icon:s.Donut,label:"Donut Chart"},{id:"kpi",icon:s.TiSortNumerically,label:"KPI"}];function kl({selectedChart:t,onChartChange:n}){var l;const a=s.useEditorStore(o=>o.card),r=((l=a==null?void 0:a.config)==null?void 0:l.pivotByColumns)&&a.config.pivotByColumns.length>0;return e.jsx("div",{className:"flex items-center justify-center gap-1",children:Tl.map(o=>{if(o.requiresPivot&&!r)return null;const c=o.icon,i=t===o.id;return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",onClick:()=>n(o.id),className:s.cn("h-8 w-8 p-0",i&&"bg-accent text-accent-foreground"),children:[e.jsx(c,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:o.label})]})}),e.jsx(s.TooltipContent,{side:"bottom",children:e.jsx("p",{children:o.label})})]},o.id)})})}const Rs=({dataType:t})=>{const n=s.getDataType(t);return n==="string"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ve,{className:"h-3 w-3"})}):n==="number"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):n==="date"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Le,{className:"h-3 w-3"})}):e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ve,{className:"h-3 w-3"})})};function El({aliasTemplate:t,onAliasTemplateChange:n}){var d;const[a,r]=M.useState(t),[l,o]=M.useState(!1),c=(d=s.useEditorStore(u=>{var m;return(m=u.card.config)==null?void 0:m.pivotByColumns}))==null?void 0:d[0],i=c?`e.g. Min Sales in {{${c.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Input$1,{placeholder:i,value:l?a:t,onChange:u=>{r(u.target.value),o(!0)},onFocus:()=>o(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&l&&a!==t?(n(a),o(!1)):u.key==="Escape"&&(r(t),o(!1))},"aria-label":"Edit alias template"}),l&&a!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{n(a),o(!1)},children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(t),o(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function Il({valueAliases:t,onValueAliasesChange:n}){const[a,r]=M.useState(null),[l,o]=M.useState(""),[c,i]=M.useState(""),d=()=>{n({...t,"":""})},u=h=>{const p={...t};delete p[h],n(p)},m=h=>{const p={...t};delete p[h],p[l]=c,n(p),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(t).map(([h,p],g)=>e.jsx("div",{className:"flex items-center gap-2",children:a===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:l,onChange:b=>o(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?m(h):b.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:b=>i(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?m(h):b.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>m(h),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(p)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:p,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(p)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+g)),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 Al({field:t,searchQuery:n="",limit:a=500}){const{authToken:r,tokenProps:l}=s.useSemaphorContext(),o=s.useEditorStore(u=>u.card),c=o==null?void 0:o.dataSource,i=["attribute-values",t.entityName,t.name,n,a],d=s.useQuery({queryKey:i,queryFn:async()=>{if(!(c!=null&&c.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const u={groupByColumns:[{...t,role:"groupby"}],metricColumns:[],filters:n?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:n}],groups:[]}:void 0,rowLimit:a},m={connection_id:c.connectionId,cardConfig:u,cardDataSource:c,cache_config:s.getCacheConfig({card:o})};console.log("requestBody",m);const h=await s.postRequestRegular(`${l.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",m);if(h!=null&&h.error)return console.error("Error fetching attribute values:",h.error),[];const p=t.name;return((h==null?void 0:h.records)||[]).map(b=>{const x=b[p]||b[t.alias||p]||b[t.label];return{id:x||"",value:x||"",label:String(x||"(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 Ml({open:t,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:l,onSave:o}){var T,k;const c=!!l,[i,d]=M.useState(c?"values":"fields"),[u,m]=M.useState(""),[h,p]=M.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]:[]}),g=a.filter(C=>{var v;return c?!1:!((v=r==null?void 0:r.conditions)==null?void 0:v.some(E=>E.field.id===C.id))&&C.label.toLowerCase().includes(u.toLowerCase())}),b=C=>{p({...h,field:C}),d("values")},x=()=>{if(h.field&&h.selectedValues.length>0){const C={id:h.id,field:h.field,operator:"in",value:h.selectedValues};let w;if(c){const v=((r==null?void 0:r.conditions)||[]).map(E=>E.id===l.id?C:E);w={...r,conditions:v}}else{const v=(r==null?void 0:r.conditions)||[];w={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...v,C],groups:[]}}o(w),n(!1)}},j=()=>{if(!c||!l)return;const C=((r==null?void 0:r.conditions)||[]).filter(w=>w.id!==l.id);if(C.length>0){const w={...r,conditions:C};o(w)}else o(void 0);n(!1)},f=C=>{p({...h,selectedValues:C})},N=()=>{c&&l?(p({id:l.id,field:l.field,selectedValues:Array.isArray(l.value)?l.value:[l.value]}),d("values")):(p({id:s.v4(),field:null,selectedValues:[]}),d("fields")),m("")};return M.useEffect(()=>{t&&N()},[t,c,l]),e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsx(s.DialogHeader,{children:e.jsx(s.DialogTitle,{children:c?`Edit Filter: ${(T=h.field)==null?void 0:T.label}`:i==="fields"?"Select Field to Filter":`Select Values for ${(k=h.field)==null?void 0:k.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!c&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&i==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Current Filters:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.conditions.map(C=>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:[C.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(C.value)?`${C.value.length} values`:String(C.value)})]},C.id))})]}),i==="fields"&&!c?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search fields...",value:u,onChange:C=>m(C.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:g.map(C=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>b(C),children:[e.jsx(Rs,{dataType:s.getDataType(C.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:C.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[C.entityName,".",C.name]})]})]},C.id))}),g.length===0&&u&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',u,'"']}),g.length===0&&!u&&a.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(Ll,{field:h.field,selectedValues:h.selectedValues,onValuesChange:f,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:j,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:N,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:x,disabled:!h.field||h.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function Ll({field:t,selectedValues:n,onValuesChange:a,onBack:r}){const[l,o]=M.useState(""),{values:c,isLoading:i,isFetching:d}=Al({field:t,searchQuery:l,limit:500}),u=l?c.filter(p=>String(p.value).toLowerCase().includes(l.toLowerCase())):c,m=p=>{const g=n.includes(p);a(g?n.filter(b=>b!==p):[...n,p])},h=()=>{n.length===u.length&&u.length>0?a([]):a(u.map(p=>p.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:p=>o(p.target.value),className:"pl-10"})]}),i||d?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx(s.Checkbox,{checked:n.length===u.length&&u.length>0,onCheckedChange:h}),e.jsxs(s.Label,{className:"text-sm",children:["Select All (",u.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:u.map(p=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>m(p.value),children:[e.jsx(s.Checkbox,{checked:n.includes(p.value),onCheckedChange:()=>m(p.value)}),e.jsx(cs,{className:"text-sm",children:p.label})]},p.id))})]})]})}function Rl({field:t,zone:n,index:a,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:o=!1,cardType:c}){var Fs,Ps,Bs;const{attributes:i,listeners:d,setNodeRef:u,transform:m,transition:h,isDragging:p}=s.useSortable({id:t.id}),g=s.useEditorStore(H=>H.card),{updateLabel:b,handleAggregationChange:x,handleDateFormatChange:j,handleGranularityChange:f,handleAliasTemplateChange:N,handleValueAliasesChange:T,removeField:k,handleKpiComparisonTypeChange:C,handleKpiShowTrendlineChange:w,handleKpiTrendlineWindowChange:v,handleKpiTrendlineGranularityChange:E,handleKpiTargetValueChange:y}=Ls(g),[F,I]=M.useState(!1),[P,D]=M.useState(!1),[S,L]=M.useState(null),[O,R]=M.useState(t.dateFormat||"YYYY-MM-DD"),[A,B]=M.useState(t.customFormat||""),[Y,_]=M.useState(!!t.customFormat),[Q,X]=M.useState(t.granularity||"day"),[q,W]=M.useState(t.aliasTemplate||""),[G,se]=M.useState(t.valueAliases||{}),[V,U]=M.useState((Fs=t.parameters)==null?void 0:Fs.filters),ee=H=>{H==="custom"?_(!0):(_(!1),R(H),n==="groupBy"&&j(a,H,""))},ae=H=>{B(H),n==="groupBy"&&j(a,"custom",H)},ie=H=>{var pe;X(H);const me=(pe=K(H)[0])==null?void 0:pe.value;me&&!Y&&(R(me),n==="groupBy"&&j(a,me,"")),n==="groupBy"&&f(a,H)},z=H=>{W(H),n==="metrics"&&N(a,H)},te=H=>{se(H),n==="metrics"&&T(a,H)},oe=H=>{b(n,a,H)},re=H=>{var ue;if(U(H),n==="metrics"){const me={...t,parameters:{...t.parameters,filters:H}},pe=[...((ue=g.config)==null?void 0:ue.metricColumns)||[]];pe[a]=me,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:pe})}D(!1)},J=()=>{k(n,a)},ce={transform:s.CSS.Transform.toString(m),transition:h},de=s.getDataType(t.dataType),fe=de==="date",$=c==="kpi",K=H=>{switch(H){case"day":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"custom",label:"Custom Format..."}];case"week":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"Week of MMM DD, YYYY",label:"Week of Jan 15, 2024"},{value:"Week of MMMM DD, YYYY",label:"Week of January 15, 2024"},{value:"YYYY-WW",label:"2024-W03 (YYYY-WW)"},{value:"custom",label:"Custom Format..."}];case"month":return[{value:"MMM YYYY",label:"Jan 2024 (MMM YYYY)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MM/YYYY",label:"01/2024 (MM/YYYY)"},{value:"YYYY MMM",label:"2024 Jan (YYYY MMM)"},{value:"custom",label:"Custom Format..."}];case"quarter":return[{value:"Q1 YYYY",label:"Q1 2024 (Q1 YYYY)"},{value:"YYYY Q1",label:"2024 Q1 (YYYY Q1)"},{value:"1st Quarter YYYY",label:"1st Quarter 2024"},{value:"YYYY-Q1",label:"2024-Q1 (YYYY-Q1)"},{value:"Quarter 1, YYYY",label:"Quarter 1, 2024"},{value:"custom",label:"Custom Format..."}];case"year":return[{value:"YYYY",label:"2024 (YYYY)"},{value:"YY",label:"24 (YY)"},{value:"custom",label:"Custom Format..."}];default:return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"custom",label:"Custom Format..."}]}},Z=K(Q),le=n!=="pivotBy",ne=fe&&n==="groupBy",je=!$&&fe&&n==="groupBy",xe=$&&fe&&n==="groupBy",We=$&&n==="metrics"&&((Ps=g.config)==null?void 0:Ps.comparisonType)==="target",Ke=n==="metrics",Ue=()=>e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:H=>{H.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}`}),Te=()=>le?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(we,{value:t.label??"",onSave:oe,placeholder:"Display label...",type:"text"})]}):null,he=()=>ne?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:Q,onValueChange:ie,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(H=>e.jsx(s.SelectItem,{className:"text-xs",value:H,children:s.toTitleCase(H)},H))})]})]}):null,qt=()=>je?e.jsxs(e.Fragment,{children:[he(),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:Y?"custom":O,onValueChange:ee,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select date format..."})}),e.jsx(s.SelectContent,{children:Z.map(H=>e.jsx(s.SelectItem,{className:"text-xs",value:H.value,children:H.label},H.value))})]}),Y&&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:A,onChange:H=>{H.stopPropagation(),ae(H.target.value)},onClick:H=>H.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,Ht=()=>{var H,ue,me,pe,ke;return xe?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(s.Select,{value:((H=g.config)==null?void 0:H.comparisonType)||"none",onValueChange:C,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:"target",children:"Target Value"})]})]})]}),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:((ue=g.config)==null?void 0:ue.showTrendline)||!1,onCheckedChange:w})]})}),((me=g.config)==null?void 0:me.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:((pe=g.config)==null?void 0:pe.trendlineWindow)||30,onChange:Qe=>{const Xt=parseInt(Qe.target.value)||30;v(Xt)},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:((ke=g.config)==null?void 0:ke.trendlineGranularity)||"day",onValueChange:E,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"day",children:"Day"}),e.jsx(s.SelectItem,{value:"week",children:"Week"}),e.jsx(s.SelectItem,{value:"month",children:"Month"})]})]})]})]})]}):null},Wt=()=>{var H,ue;return We?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(we,{value:((H=g.config)==null?void 0:H.targetValue)!==void 0&&((ue=g.config)==null?void 0:ue.targetValue)!==null?String(g.config.targetValue):"",onSave:me=>{!isNaN(Number(me))&&me!==null?y(Number(me)):y(0)},placeholder:"Enter target value...",type:"text"})]}):null},Kt=()=>Ke?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:H=>{x(a,H)},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"}),(V==null?void 0:V.conditions)&&V.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:V.conditions.map(H=>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:()=>{L(H),D(!0)},children:[e.jsxs("span",{className:"font-medium",children:[H.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(H.value)?H.value.length===1?String(H.value[0]):H.value.length<=2?H.value.join(", "):`${H.value.slice(0,2).join(", ")} +${H.value.length-2}`:String(H.value)})}),Array.isArray(H.value)&&H.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 (",H.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:H.value.map((ue,me)=>e.jsx("div",{children:String(ue)},me))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:ue=>{var pe;ue.stopPropagation();const me=V.conditions.filter(ke=>ke.id!==H.id);if(me.length>0){const ke={...V,conditions:me};re(ke)}else if(U(void 0),n==="metrics"){const ke={...t,parameters:{...t.parameters,filters:void 0}},Qe=[...((pe=g.config)==null?void 0:pe.metricColumns)||[]];Qe[a]=ke,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:Qe})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},H.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{L(null),D(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(_t,{column:t}),o&&e.jsxs(e.Fragment,{children:[e.jsx(El,{aliasTemplate:q,onAliasTemplateChange:z}),e.jsx(Il,{valueAliases:G,onValueAliasesChange:te})]})]}):null,{columns:Qt=[]}=s.useColumns(),Jt=(V==null?void 0:V.conditions)&&V.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:u,style:ce,...i,...d,className:`group mx-auto flex w-full flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${p?"z-50 scale-95 opacity-50":"border-slate-200"} ${n==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(Rs,{dataType:de}),e.jsx(cs,{className:s.cn("w-[140px] flex-1 text-xs",Jt&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),n==="metrics"&&((Bs=V==null?void 0:V.conditions)==null?void 0:Bs.length)&&!F&&e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 text-xs",children:[e.jsx(s.Filter,{className:"h-3 w-3"}),e.jsx("span",{children:V.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:V.conditions.map(H=>e.jsxs("div",{children:[H.field.label,":"," ",Array.isArray(H.value)?`${H.value.length} values`:String(H.value)]},H.id))})})]})}),n!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:H=>{H.stopPropagation(),I(!F)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${F?"rotate-180":""}`})}),n==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:H=>{H.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const ue=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",ue),l(ue)},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:H=>{H.stopPropagation(),J()},children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]}),F&&e.jsxs("div",{className:"space-y-3",children:[Ue(),Te(),c==="kpi"&&he(),qt(),Ht(),Wt(),Kt()]})]}),P&&e.jsx(Ml,{open:P,onOpenChange:H=>{D(H),H||L(null)},availableFields:Qt,existingFilters:V,editingCondition:S,onSave:H=>{var ue;if(H)re(H);else if(U(void 0),n==="metrics"){const me={...t,parameters:{...t.parameters,filters:void 0}},pe=[...((ue=g.config)==null?void 0:ue.metricColumns)||[]];pe[a]=me,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:pe})}L(null)}})]})}function Ol({concept:t}){const n=()=>{switch(t){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-100 text-xs font-medium dark:bg-blue-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/50 text-xs font-medium dark:bg-blue-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/30 text-xs font-medium dark:bg-blue-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/20 text-xs font-medium dark:bg-blue-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metrics = Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});default:return null}};return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(s.TooltipContent,{side:"right",align:"start",className:"p-3",children:n()})]})})}function Ze({zone:t,fields:n,label:a,placeholder:r,shouldShow:l,hasPivotColumns:o=!1}){const{isOver:c,setNodeRef:i}=s.useDroppable({id:t}),{updateSortByColumn:d}=s.useEditorActions(),u=s.useEditorStore(b=>b.card),m=s.useEditorStore(b=>b.card.type),h=n.length>0,p=(b,x)=>{var f;!((f=u.config)!=null&&f.sortByColumns)||u.config.sortByColumns.findIndex(N=>N.id===b)===-1||d(u.id,b,{direction:x})};if(t==="sortBy"&&l===!1)return null;const g=t!=="sortBy"&&m!=="kpi";return e.jsxs("div",{className:"mb-4 w-full",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:a}),g&&e.jsx(Ol,{concept:t})]}),e.jsx("div",{ref:i,className:`rounded-lg border-2 border-dashed p-1 transition-all ${c?"border-blue-500 bg-blue-50 dark:bg-blue-950":h?"border-blue-200 bg-blue-50/30 dark:border-blue-800 dark:bg-blue-950/30":"min-h-[60px] border-muted-foreground/20 bg-background"}`,children:n.length===0?e.jsx("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:r}):e.jsx(s.SortableContext,{items:n.map(b=>b.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:n.map((b,x)=>{const f=b.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(Rl,{field:b,zone:t,index:x,sortDirection:f,onSortDirectionChange:N=>p(b.id,N),hasPivotColumns:o,cardType:m})})},b.id)})})})})]})}const Xs=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],Fl=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function js({value:t,onChange:n,label:a}){const[r,l]=M.useState(!1),[o,c]=M.useState(!1),i=()=>{const d=Xs.find(u=>u.value===t);return d?d.color:t.startsWith("#")?t:Xs[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:r,onOpenChange:l,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"size-5 rounded border-2 border-input shadow-sm transition-all hover:scale-110 hover:border-gray-400",style:{backgroundColor:i()},"aria-label":`Change color for ${a}`})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"grid grid-cols-3 items-center justify-items-center gap-1",children:Fl.map(d=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",i()===d?"border-gray-900":"border-transparent"),style:{backgroundColor:d},onClick:()=>{n(d),l(!1)},children:e.jsx("span",{className:"sr-only",children:d})},d))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{c(!0),l(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a})]}),o&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>c(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Rt,{color:i(),onColorChange:d=>{n(d),c(!1)},onClose:()=>c(!1)})})]})]})}const es={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%
|
|
340
|
-
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 Pl(){var i,d,u,m,h,p,g,b,x,j;const t=s.useEditorStore(f=>f.card),{setCardPreferences:n}=s.useEditorActions(),a=((i=t.config)==null?void 0:i.metricColumns)||[],r=((d=t.config)==null?void 0:d.groupByColumns)||[];if(!(t.type==="kpi"&&(a.length>=2&&r.length===0||a.length>=1&&r.length>0)))return null;const o=((m=(u=t.preferences)==null?void 0:u.kpiVisualOptions)==null?void 0:m.metricComparison)||{},c=f=>{var T;const N={...t.preferences,kpiVisualOptions:{...(T=t.preferences)==null?void 0:T.kpiVisualOptions,metricComparison:{...o,...f}}};n(N)};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(ja,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[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=>c({enabled:f,...f&&!o.calculationType?{calculationType:"difference"}:{}})})]}),o.enabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(s.Select,{value:o.calculationType||"difference",onValueChange:f=>c({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(es).map(([f,N])=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:N.label},f))})]}),(()=>{var N,T,k;const f=o.calculationType||"difference";return e.jsxs("div",{className:"space-y-2 rounded-md bg-muted/50 p-2 text-xs",children:[e.jsx("p",{className:"text-muted-foreground",children:(N=es[f])==null?void 0:N.description}),e.jsxs("div",{className:"text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Formula:"})," ",e.jsx("code",{className:"rounded bg-background px-1 py-0.5 text-[10px]",children:(T=es[f])==null?void 0:T.formula})]}),e.jsxs("div",{className:"border-t pt-1 italic text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",(k=es[f])==null?void 0:k.example]})]})})()]}),e.jsx(As,{formatOptions:o.formatOptions||{},onFormatOptionsChange:f=>c({formatOptions:f}),showTitle:!0,title:"COMPARISON FORMAT"}),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"}),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||"left",onValueChange:f=>c({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:"top",className:"text-xs",children:"Top"}),e.jsx(s.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(s.SelectItem,{value:"right",className:"text-xs",children:"Right"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-arrow",checked:o.showArrow!==!1,onCheckedChange:f=>c({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=>c({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(js,{value:((h=o.colorConfig)==null?void 0:h.increase)||"green",onChange:f=>c({colorConfig:{...o.colorConfig,increase:f}}),label:"Primary > Secondary"}),e.jsx(js,{value:((p=o.colorConfig)==null?void 0:p.decrease)||"red",onChange:f=>c({colorConfig:{...o.colorConfig,decrease:f}}),label:"Primary < Secondary"}),e.jsx(js,{value:((g=o.colorConfig)==null?void 0:g.noChange)||"neutral",onChange:f=>c({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=>c({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:((b=o.conditionalLabels)==null?void 0:b.increase)??"Increase",onChange:f=>c({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:((x=o.conditionalLabels)==null?void 0:x.decrease)??"Decrease",onChange:f=>c({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:((j=o.conditionalLabels)==null?void 0:j.noChange)??"No change",onChange:f=>c({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:"Name"}),e.jsx(s.Input,{id:"label-name",type:"text",value:o.labelName??"",onChange:f=>c({labelName:f.target.value}),placeholder:"e.g. Versus, Compared to",className:"h-7 text-xs"})]})]})]})]})]})}function Bl(){var l,o;const t=s.useEditorStore(c=>c.card),{setCardPreferences:n}=s.useEditorActions();if(t.type!=="kpi")return null;const a=((o=(l=t.preferences)==null?void 0:l.kpiVisualOptions)==null?void 0:o.formatOptions)||{},r=c=>{var d;const i={...t.preferences,kpiVisualOptions:{...(d=t.preferences)==null?void 0:d.kpiVisualOptions,formatOptions:c}};n(i)};return e.jsxs(s.AccordionItem,{value:"kpi-format",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(De,{className:"h-4 w-4"}),e.jsx("span",{children:"Number Format"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:e.jsx(As,{formatOptions:a,onFormatOptionsChange:r,showTitle:!1})})]})}function zl({groupByFields:t,pivotByFields:n,metricsFields:a,sortByFields:r}){const l=s.useEditorStore(b=>{var x;return((x=b.card.customCardPreferences)==null?void 0:x.url)&&b.card.type==="custom"}),o=s.useEditorStore(b=>b.card),c=o==null?void 0:o.type,i=t.length>0||a.length>0,d=c!=="kpi",u=c!=="kpi"&&i,m=["pie","doughnut","polar","funnel","aggregateTable"].includes(c),h=d&&!m,p=()=>c==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},g=()=>c==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs(s.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full",children:[e.jsxs(s.AccordionItem,{value:"fields",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.List,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsx(Ze,{zone:"groupBy",fields:t,label:p().label,placeholder:p().placeholder}),h&&e.jsx(Ze,{zone:"pivotBy",fields:n,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(Ze,{zone:"metrics",fields:a,label:g().label,placeholder:g().placeholder,hasPivotColumns:n.length>0}),u&&e.jsx(Ze,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})]}),!l&&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.Settings,{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(Bl,{}),e.jsx(Pl,{}),e.jsx(Ot,{}),e.jsx(Ft,{}),e.jsx(Pt,{}),e.jsx(Bt,{})]})})]})]})}function _l({selectedChart:t,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:o}){const c=s.useEditorStore(h=>h.showAIDialog),i=a.length>0||r.length>0||l.length>0,{setShowAIDialog:d}=s.useEditorActions(),u=s.useEditorStore(h=>h.card),{data:m}=s.useDashboardCardQuery(u);return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col border-x border-border",children:[e.jsxs("div",{className:"space-y-4 px-6 pt-4",children:[e.jsx(kl,{selectedChart:t,onChartChange:n}),e.jsx(wl,{selectedChart:t,onChartChange:n})]}),e.jsxs("div",{className:s.cn("flex justify-end gap-2 px-6 py-6"),children:[e.jsx("div",{className:s.cn("invisible",{visible:i||m}),children:e.jsx(os,{})}),!c&&e.jsxs(s.Button,{onClick:()=>d(!c),variant:"outline",className:"h-8",size:"sm",children:[e.jsx(s.Sparkles,{className:"mr-2 size-4"}),"AI"]})]}),e.jsxs(s.ScrollArea,{className:"w-full flex-1 basis-0 px-6 pb-6",children:[e.jsx(zl,{groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:o}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Vl({initialFilters:t,availableFields:n}={}){const[a,r]=M.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(C=>C.card.dataSource);const{columns:l,isLoading:o}=s.useColumns(),i=n||l||[],d={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=C=>{const w=v=>{if(v.id===C){const E=i[0]||d,y=s.getDataType(E.dataType)==="date";return{...v,conditions:[...v.conditions,{id:`condition-${Date.now()}`,field:E,operator:y?"between":"=",value:y?[]:""}]}}return{...v,groups:v.groups.map(w)}};r(w(a))},m=C=>{const w=v=>{if(v.id===C){const E=i[0]||d,y=s.getDataType(E.dataType)==="date";return{...v,groups:[...v.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:E,operator:y?"between":"=",value:y?[]:""}],groups:[]}]}}return{...v,groups:v.groups.map(w)}};r(w(a))},h=(C,w)=>{const v=E=>E.id===C?{...E,conditions:E.conditions.filter(y=>y.id!==w)}:{...E,groups:E.groups.map(v)};r(v(a))},p=(C,w)=>{const v=E=>E.id===C?{...E,groups:E.groups.filter(y=>y.id!==w)}:{...E,groups:E.groups.map(v)};r(v(a))},g=(C,w,v,E)=>{if(v==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const y=F=>F.id===C?{...F,conditions:F.conditions.map(I=>I.id===w?{...I,[v]:E}:I)}:{...F,groups:F.groups.map(y)};r(y(a))},b=(C,w,v)=>{const E=y=>y.id===C?{...y,conditions:y.conditions.map(F=>F.id===w?{...F,...v}:F)}:{...y,groups:y.groups.map(E)};r(E(a))},x=(C,w)=>{const v=E=>E.id===C?{...E,logicalOperator:w}:{...E,groups:E.groups.map(v)};r(v(a))},j=(C,w)=>{const v=E=>E.id===C?{...E,negate:w}:{...E,groups:E.groups.map(v)};r(v(a))},f=(C,w,v)=>{const E=y=>y.id===C?{...y,conditions:s.arrayMove(y.conditions,w,v)}:{...y,groups:y.groups.map(E)};r(E(a))},N=(C,w,v)=>{const E=y=>y.id===C?{...y,groups:s.arrayMove(y.groups,w,v)}:{...y,groups:y.groups.map(E)};r(E(a))},T=C=>{if(!C||C.conditions.length===0&&C.groups.length===0)return"-- No filters defined";const w=E=>{let y="";typeof E.field=="object"?y=E.field.entityName?`${E.field.entityName}.${E.field.name}`:E.field.name:y=String(E.field);const F=E.operator;let I=E.value;if(E.field.dataType==="string"&&!["in","not in"].includes(E.operator))typeof I=="string"?I=`'${I}'`:Array.isArray(I)&&(I=`'${I.join(", ")}'`);else if(E.field.dataType==="date"||E.field.dataType==="datetime"||E.field.dataType==="timestamp")if(E.operator==="between"&&Array.isArray(I)&&I.length===2){const P=I[0]?`'${I[0]}'`:"NULL",D=I[1]?`'${I[1]}'`:"NULL";return`${y} BETWEEN ${P} AND ${D}`}else if((E.operator==="in"||E.operator==="not in")&&Array.isArray(I)){const P=I.map(D=>D?`'${D}'`:"NULL").join(", ");return`${y} ${F} (${P})`}else typeof I=="string"||I instanceof Date?I=`'${I}'`:Array.isArray(I)&&I.length>0&&(I=`'${I[0]}'`);else if(["in","not in"].includes(E.operator)){let P=[];Array.isArray(I)?P=I.map(D=>typeof D=="string"?`'${D}'`:String(D)):typeof I=="string"?P=I.split(",").map(D=>{const S=D.trim();return E.field.dataType==="string"?`'${S}'`:S}):typeof I=="number"&&(P=[String(I)]),I=`(${P.join(", ")})`}switch(F){case"contains":return typeof I=="string"?`${y} LIKE '%${I.replace(/'/g,"")}'`:`${y} LIKE '%${String(I)}'`;case"startsWith":return typeof I=="string"?`${y} LIKE '${I.replace(/'/g,"")}%'`:`${y} LIKE '${String(I)}%'`;case"endsWith":return typeof I=="string"?`${y} LIKE '%${I.replace(/'/g,"")}'`:`${y} LIKE '%${String(I)}'`;case"isNull":return`${y} IS NULL`;case"isNotNull":return`${y} IS NOT NULL`;default:return`${y} ${F} ${I}`}},v=E=>{const y=E.conditions.map(w),F=E.groups.map(S=>v(S)),I=[...y,...F].filter(Boolean);if(I.length===0)return"";const P=I.join(` ${E.logicalOperator} `),D=I.length>1?`(${P})`:P;return E.negate?`NOT ${D}`:D};return v(C)},k=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:i,isLoading:o,addCondition:u,addGroup:m,removeCondition:h,removeGroup:p,updateCondition:g,updateConditionFields:b,updateGroupOperator:x,updateGroupNegate:j,reorderConditions:f,reorderGroups:N,generateSQLPreview:T,hasAnyFilters:k}}function Ul({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",n),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const Gl=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"})}},Yl=t=>{if(t.qualifiedEntityName){const n=t.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function $l({value:t,onValueChange:n,availableFields:a,placeholder:r="Select field",className:l="w-64"}){const[o,c]=M.useState(!1),i=M.useMemo(()=>{const d={};return a.forEach(u=>{const m=Yl(u);d[m]||(d[m]={}),d[m][u.entityId]||(d[m][u.entityId]=[]),d[m][u.entityId].push(u)}),d},[a]);return e.jsxs(s.Popover,{modal:!0,open:o,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:s.cn("justify-between",!t&&"text-muted-foreground",l),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Ul,{children:[t.entityName,".",t.name]})}):r,e.jsx(s.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(s.CommandEmpty,{children:"No fields found."}),e.jsx(s.CommandList,{className:"max-h-80",children:Object.entries(i).map(([d,u])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),d]}),children:Object.entries(u).map(([m,h])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[Gl(h[0].entityType),e.jsx("span",{children:h[0].entityName})]}),h.map((p,g)=>e.jsxs(s.CommandItem,{value:p.id,onSelect:()=>{n(p),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)===p.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:p.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:p.description&&e.jsx("span",{children:p.description})})]})]},p.id+g))]},`${d}-${m}`))},d))})]})})]})}function Os(t){var x;const n=s.useEditorStore(j=>j.card),{authToken:a,tokenProps:r}=s.useSemaphorContext(),l=s.useEditorStore(j=>j.card.config),o=l==null?void 0:l.joinPlan,c={...t,alias:t.name,label:"value",role:"groupby"},i={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},d={...c,role:"sortby",direction:"asc"},u={joinPlan:o,groupByColumns:[c],metricColumns:[i],sortByColumns:[d]},m=((x=n.dataSource)==null?void 0:x.connectionId)||n.connectionId,{data:h,isPending:p,error:g}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular(`${r.apiServiceUrl}/v1/query`,(a==null?void 0:a.accessToken)||"",{connection_id:m,cardConfig:u,cardDataSource:n.dataSource})}catch(j){console.log(t),console.error("error",j)}},enabled:!!m,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((h==null?void 0:h.records)||[]).map(j=>({label:j.value||"BLANK",value:j.value||"BLANK",count:(j==null?void 0:j.count)||0})),isPending:p,error:g}}function ql({field:t,selected:n,onChange:a,placeholder:r="Select items...",className:l}){const[o,c]=Ee.useState(!1),{filterValues:i}=Os(t),d=m=>{a(n.filter(h=>h!==m))},u=m=>{n.includes(m)?a(n.filter(h=>h!==m)):a([...n,m])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open:o,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:n.length>0?n.map(m=>{const h=i.find(p=>p.value===m);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[h==null?void 0:h.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:p=>{p.key==="Enter"&&d(m)},onMouseDown:p=>{p.preventDefault(),p.stopPropagation()},onClick:p=>{p.stopPropagation(),d(m)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},m)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No results found."}),e.jsx(s.CommandGroup,{children:i.map((m,h)=>e.jsxs(s.CommandItem,{onSelect:()=>u(m.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",n.includes(m.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.count})]})]},m.value+h))})]})]})})]})})}function Hl({field:t,value:n,onChange:a,placeholder:r="Select value...",className:l}){const{filterValues:o,isPending:c,error:i}=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..."]}):i?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:n,onValueChange:a,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:n})}),e.jsx(s.SelectContent,{children:o.map((d,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+u))})]})}function Wl({value:t,operator:n,onChange:a,className:r}){var d;const{tokenProps:l}=s.useSemaphorContext(),o=(d=l==null?void 0:l.params)==null?void 0:d.timeZone,c=M.useMemo(()=>{if(t){if(n==="between"||n==="not between"){if(Array.isArray(t)&&t.length===2){const u=t[0]?new Date(t[0]):void 0,m=t[1]?new Date(t[1]):void 0;if(u&&m)return{from:u,to:m}}}else if(n==="="||n==="!="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:u}}}else if(n===">"||n===">="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:void 0}}}else if(n==="<"||n==="<="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:void 0,to:u}}}else if((n==="in"||n==="not in")&&Array.isArray(t)&&t.length>0){const u=new Date(t[0]),m=t.length>1?new Date(t[t.length-1]):u;if(!isNaN(u.getTime()))return{from:u,to:m}}}},[t,n]),i=u=>{if(!u){a(void 0);return}if(u.from&&u.to)a([u.from.toISOString(),u.to.toISOString()]);else if(u.from){const m=new Date(u.from);m.setHours(23,59,59,999),a([u.from.toISOString(),m.toISOString()])}else if(u.to){const m=new Date(u.to);m.setHours(0,0,0,0),a([m.toISOString(),u.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:c,onChange:i,timezone:o,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const Kl=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Ql=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Jl=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],Xl=["=","!=","isNull","isNotNull"],Zl=["between","isNull","isNotNull"],eo={"=":"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"};function Zs(t){return eo[t]||s.titleCase(t)}function so(t){switch(t){case"string":return Ql;case"number":return Jl;case"boolean":return Xl;case"date":return Zl;default:return Kl}}function Ut({condition:t,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:o,onUpdateGroupOperator:c,availableFields:i,updateConditionFields:d}){const{attributes:u,listeners:m,setNodeRef:h,transform:p,transition:g,isDragging:b}=s.useSortable({id:t.id}),{isPending:x,error:j}=Os(t.field),f={transform:s.CSS.Transform.toString(p),transition:g};return e.jsxs("div",{ref:h,style:f,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${b?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...m,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),n>0&&e.jsxs(s.Select,{value:r,onValueChange:N=>c(a,N),children:[e.jsx(s.SelectTrigger,{className:"w-24",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),n===0&&e.jsx("div",{className:"w-24"}),e.jsx($l,{value:t.field,onValueChange:N=>{const T=N,k=s.getDataType(T.dataType)==="date";d(a,t.id,{field:T,value:"",operator:k?"between":"="})},availableFields:i,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:N=>{N==="in"||N==="not in"?d(a,t.id,{operator:N,value:[]}):N==="isNull"||N==="isNotNull"?d(a,t.id,{operator:N,value:null}):d(a,t.id,{operator:N,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?Zs(t.operator):""})}),e.jsx(s.SelectContent,{children:so(s.getDataType(t.field.dataType)).map(N=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:N,children:Zs(N)},N))})]}),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"?x?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..."]}):j?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(ql,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(N=>typeof N=="string")?t.value:[],onChange:N=>d(a,t.id,{value:N}),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:N=>d(a,t.id,{value:N.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(Hl,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:N=>d(a,t.id,{value:N}),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:N=>d(a,t.id,{value:N==="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(Wl,{value:t.value,operator:t.operator,onChange:N=>d(a,t.id,{value:N}),className:"flex-1"}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:N=>l(a,t.id,"value",N.target.value),className:"flex-1",placeholder:t.operator==="in"||t.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>o(a,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function to({group:t,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:o,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onReorderConditions:u,onReorderGroups:m,onAddCondition:h,onAddGroup:p,availableFields:g,renderFilterGroup:b,updateConditionFields:x}){const{attributes:j,listeners:f,setNodeRef:N,transform:T,transition:k,isDragging:C}=s.useSortable({id:t.id}),w={transform:s.CSS.Transform.toString(T),transition:k},v=y=>{const{active:F,over:I}=y;if(I&&F.id!==I.id){const P=t.conditions.findIndex(S=>S.id===F.id),D=t.conditions.findIndex(S=>S.id===I.id);P!==-1&&D!==-1&&u(t.id,P,D)}},E=y=>{const{active:F,over:I}=y;if(I&&F.id!==I.id&&a){const P=t.groups.findIndex(S=>S.id===F.id),D=t.groups.findIndex(S=>S.id===I.id);P!==-1&&D!==-1&&m(a,P,D)}};return e.jsxs("div",{ref:N,style:w,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${C?"z-50 opacity-50":""}`,children:[n>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...j,...f,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(s.Button,{variant:t.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>l(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:y=>r(t.id,y),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>a&&o(a,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${n>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:v,children:e.jsx(s.SortableContext,{items:t.conditions.map(y=>y.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((y,F)=>e.jsx(Ut,{condition:y,index:F,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:g,updateConditionFields:x},y.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:E,children:e.jsx(s.SortableContext,{items:t.groups.map(y=>y.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(y=>b(y,n+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>p(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function ao({filters:t,availableFields:n,onSave:a,onClearAll:r,onCancel:l}){const{currentFilters:o,availableFields:c,isLoading:i,addCondition:d,addGroup:u,removeCondition:m,removeGroup:h,updateCondition:p,updateConditionFields:g,updateGroupOperator:b,updateGroupNegate:x,reorderConditions:j,reorderGroups:f,generateSQLPreview:N,hasAnyFilters:T,setCurrentFilters:k}=Vl({initialFilters:t,availableFields:n}),C=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[w,v]=M.useState(!1),E=(I,P,D)=>{const S=L=>L.id===I?{...L,conditions:L.conditions.map(O=>O.id===P?{...O,field:D,dataType:D.dataType}:O)}:{...L,groups:L.groups.map(S)};k(S(o))},y=(I,P=0,D)=>P===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:C,collisionDetection:s.closestCenter,onDragEnd:S=>{const{active:L,over:O}=S;if(O&&L.id!==O.id){const R=I.conditions.findIndex(B=>B.id===L.id),A=I.conditions.findIndex(B=>B.id===O.id);R!==-1&&A!==-1&&j(I.id,R,A)}},children:e.jsx(s.SortableContext,{items:I.conditions.map(S=>S.id),strategy:s.verticalListSortingStrategy,children:I.conditions.map((S,L)=>e.jsx(Ut,{condition:S,index:L,groupId:I.id,groupLogicalOperator:I.logicalOperator,onUpdateCondition:p,onUpdateField:E,onRemoveCondition:m,onUpdateGroupOperator:b,availableFields:c,updateConditionFields:g},S.id))})}),e.jsx(s.DndContext,{sensors:C,collisionDetection:s.closestCenter,onDragEnd:S=>{const{active:L,over:O}=S;if(O&&L.id!==O.id){const R=I.groups.findIndex(B=>B.id===L.id),A=I.groups.findIndex(B=>B.id===O.id);R!==-1&&A!==-1&&f(I.id,R,A)}},children:e.jsx(s.SortableContext,{items:I.groups.map(S=>S.id),strategy:s.verticalListSortingStrategy,children:I.groups.map(S=>y(S,P+1,I.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(I.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),w&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(I.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},I.id):e.jsx(to,{group:I,depth:P,parentGroupId:D,onUpdateGroupOperator:b,onUpdateGroupNegate:x,onRemoveGroup:h,onUpdateCondition:p,onUpdateField:E,onRemoveCondition:m,onReorderConditions:j,onReorderGroups:f,onAddCondition:d,onAddGroup:u,availableFields:c,renderFilterGroup:y,updateConditionFields:g},I.id),F=s.getFilterCount(t);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Card,{children:e.jsx(s.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[i?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):y(o),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{id:"advanced-mode",checked:w,onCheckedChange:I=>v(I)}),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)"})]})}),T&&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:N(o)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:l,children:"Cancel"}),F>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>a(T?o:null),children:"Apply Filters"})]})]})}function no({cardId:t,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:l,isOpen:o,onOpenChange:c}){const i=u=>{a(t,u),c(!1)},d=()=>{r(t),c(!1)};return e.jsxs(s.Dialog,{modal:!1,open:o,onOpenChange:c,children:[o&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:u=>{u.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Card Filters"}),e.jsx(s.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(ao,{filters:n,availableFields:l,onSave:i,onCancel:()=>c(!1),onClearAll:d})]})]})}function ro({activeCardId:t,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var g;const[l,o]=M.useState(null),c=s.useEditorStore(b=>b.card),i=(g=c==null?void 0:c.config)==null?void 0:g.joinPlan,d=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")],u=M.useCallback(b=>b.startsWith("card-")?null:b.startsWith("source-")||n.find(x=>x.id===b)?"source":a("groupBy").find(x=>x.id===b)?"groupBy":a("metrics").find(x=>x.id===b)?"metrics":a("pivotBy").find(x=>x.id===b)?"pivotBy":a("sortBy").find(x=>x.id===b)?"sortBy":null,[n,a]),m=M.useCallback(b=>{o(b.active.id)},[]),h=M.useCallback(b=>{const{active:x,over:j}=b;if(!j||!t){o(null);return}const f=x.id,N=j.id,T=u(f),k=u(N)||N;if(k==="sortBy"){if(T==="source"){const C=n.find(v=>v.id===f);if(!C){o(null);return}if(!(a("groupBy").some(v=>v.name===C.name&&v.qualifiedEntityName===C.qualifiedEntityName)||a("metrics").some(v=>v.name===C.name&&v.qualifiedEntityName===C.qualifiedEntityName))){o(null);return}}else if(T==="pivotBy"){o(null);return}else if(T!=="groupBy"&&T!=="metrics"&&T!=="sortBy"){o(null);return}}if(T==="source"&&k==="sortBy"){const C=[...n].find(E=>E.id===f);if(!C){o(null);return}const w=a("sortBy");if(s.fieldAlreadyExists(C,w)){o(null);return}const v=s.getNewField(C,"sortBy",w);o(null),r("sortBy",[...w,v]);return}if(T==="source"&&k!=="source"&&k!=="sortBy"){const C=[...n].find(y=>y.id===f);if(!C){o(null);return}const w=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")];if(w.length>0){const y=w[0].qualifiedEntityName;if(!y){o(null);return}if(y!==C.qualifiedEntityName&&C.qualifiedEntityName)if(i){if(!s.areEntitiesJoined(y,C.qualifiedEntityName,i)){s.showJoinRequiredNotification(),o(null);return}}else{s.showJoinRequiredNotification(),o(null);return}}const v=a(k);if(s.fieldAlreadyExists(C,v)){o(null);return}const E=s.getNewField(C,k,v);o(null),r(k,[...v,E]);return}if(T&&k&&T!=="source"&&k!=="source"&&T!==k){const C=a(T),w=a(k),v=C.find(F=>F.id===f);if(!v){o(null);return}const E=s.getNewField(v,k,w);if(o(null),k==="sortBy"){s.fieldAlreadyExists(v,w)||r(k,[...w,E]);return}const y=C.filter(F=>F.id!==f);r(T,y),r(k,[...w,E]);return}if(T&&k&&T===k&&T!=="source"){const C=a(T),w=C.findIndex(E=>E.id===f),v=C.findIndex(E=>E.id===N);if(w!==v){const E=s.arrayMove(C,w,v);r(T,E)}}o(null)},[t,n,a,r,u,i]),p=l?d.find(b=>b.id===l):null;return{activeId:l,activeField:p,handleDragStart:m,handleDragEnd:h}}function lo({dashboardFilterCount:t=0,cardFilterCount:n=0,clickFilterCount:a=0,onClick:r,className:l,showIcon:o=!0}){const c=t+n+a,i=c>0,d=t>0,u=n>0,m=a>0,h=e.jsxs(e.Fragment,{children:[o&&e.jsx(s.Filter,{className:"h-3.5 w-3.5"}),i&&e.jsx("span",{className:"font-medium",children:c})]}),p=e.jsx(s.Button,{variant:i?"secondary":"outline",size:"sm",onClick:r,className:s.cn("h-8 gap-1.5 transition-all",l),children:h});return i?e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:200,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:p}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"p-2 text-xs",children:e.jsxs("div",{className:"space-y-1.5",children:[d&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-purple-500"}),e.jsxs("span",{children:[t," Dashboard filter",t!==1?"s":""]})]}),u&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-blue-500"}),e.jsxs("span",{children:[n," Card filter",n!==1?"s":""]})]}),m&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-gray-500"}),e.jsxs("span",{children:[a," Click filter",a!==1?"s":""]})]})]})})]})}):p}function oo({onAdvancedToggle:t,onDebugToggle:n,onAccept:a}){const{currentUser:r}=s.useCurrentUserInfo();r==null||r.role;const[l,o]=M.useState(!1),c=s.useEditorStore(f=>f.isDevMode),i=s.useEditorStore(f=>f.card),d=s.useEditorStore(f=>f.card.dataSource);s.isExplorerCard(i);const{config:u}=M.useContext(s.SemaphorContext).tokenProps,m=(u==null?void 0:u.showAdvancedMode)!==!1,{setIsDevMode:h}=s.useEditorActions(),p=s.useEditorStore(f=>f.showAIDialog),g=s.useEditorStore(f=>f.frame),b=s.useManagementStore(f=>f.selectedVisual),x=(b==null?void 0:b.id)===(g==null?void 0:g.id),{setShowAIDialog:j}=s.useEditorActions();return e.jsxs("div",{className:s.cn("flex items-center justify-between px-6 py-3",p&&"justify-end",!m&&"justify-end"),children:[m&&t&&!p&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{className:s.cn("",{}),checked:c,onCheckedChange:()=>h(!c),id:"advanced-mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium",children:"Advanced Mode"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Es,{}),a&&!x&&e.jsx(ks,{variant:"default"}),x&&e.jsx(Kn,{}),n&&s.isDevEnv]}),l&&e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(d==null?void 0:d.selectedEntities)||[],open:l,onOpenChange:o,dataSource:d||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function io({activeView:t,onViewChange:n}){const a=s.useEditorStore(c=>c.card),{config:r}=M.useContext(s.SemaphorContext).tokenProps,l=(r==null?void 0:r.showInfoTab)!==!1,{errorMessage:o}=s.useDashboardCardQuery(a);return e.jsx(s.Tabs,{value:t,onValueChange:c=>n(c),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-1 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),a.type!=="kpi"&&l&&e.jsx(s.TabsTrigger,{value:"info",className:s.cn("rounded-md transition data-[state=active]:bg-muted",o&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:o?"Error":"Info"})]})})}const co=[{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 uo(){var d,u;const t=s.useEditorStore(m=>m.card),{updateRowLimit:n}=s.useEditorActions(),[a,r]=M.useState(!1),[l,o]=M.useState(""),c=m=>{if(m==="custom"){r(!0);return}r(!1),n(t.id,parseInt(m))},i=m=>{const h=m.target.value;o(h),h&&!isNaN(parseInt(h))&&n(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:a?e.jsx(s.Input,{type:"number",value:l,onChange:i,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(d=t.config)==null?void 0:d.rowLimit)==null?void 0:u.toString())||"100",onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(s.SelectValue,{placeholder:"Select limit"})}),e.jsx(s.SelectContent,{children:co.map(m=>e.jsx(s.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function mo({isOpen:t,onClose:n}){const a=dt(n,{enabled:t}),r=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.url)||""}),l=s.useEditorStore(m=>m.card),o=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.pluginChartType)||""}),c=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.settings)||{}}),{data:i}=s.useDashboardCardQuery(l),{getCard:d}=s.useCustomVisual(r),u=M.useMemo(()=>!r||r.trim()===""?null:d("Chart Settings"),[d,r]);return e.jsx("div",{ref:a,className:s.cn("absolute right-0 top-0 z-40 h-full w-[350px] border-l bg-background shadow-lg transition-transform duration-300",t?"translate-x-0":"translate-x-full"),style:{willChange:"transform"},tabIndex:t?0:-1,"aria-hidden":!t,children:e.jsxs("div",{className:"flex h-full flex-col p-4 px-5 pr-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Chart Settings"}),e.jsx(s.IconButton,{"aria-label":"Hide Chart Settings",tooltip:"Hide",onClick:n,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:u&&e.jsx(M.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(i==null?void 0:i.records)||[],chartType:o,settings:c})})})]})})}function ho(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),{currentUser:a}=s.useCurrentUserInfo(),r=s.useMutation({mutationFn:async l=>{if(!(t!=null&&t.accessToken))throw new Error("No authentication token available");const c=`${n.apiServiceUrl||""}/v1/feedback`,i={...l,user:a,tokenContext:n},d=await s.postRequestRegular(c,t.accessToken,i,"POST");if(!d||!d.success)throw new Error((d==null?void 0:d.error)||"Failed to send feedback");return d},onSuccess:l=>{s.ue.success(`Feedback sent successfully! Issue: ${l.issueNumber}`,{duration:5e3})},onError:l=>{console.error("Feedback submission error:",l),s.ue.error("Failed to send feedback. Please try again later.",{duration:5e3})}});return{sendFeedback:r.mutate,sendFeedbackAsync:r.mutateAsync,isLoading:r.isPending,isSuccess:r.isSuccess,isError:r.isError,error:r.error,data:r.data,reset:r.reset}}function xo(t,n,a){return{category:t,userMessage:a,systemState:n,metadata:{url:window.location.href,userAgent:navigator.userAgent,timestamp:new Date().toISOString(),viewport:`${window.innerWidth}x${window.innerHeight}`}}}function po({open:t,onOpenChange:n,feedbackData:a}){var x,j,f,N,T,k;const[r,l]=M.useState(""),[o,c]=M.useState(!1),{sendFeedback:i,isLoading:d,isSuccess:u,data:m,reset:h}=ho(),p=()=>{const C={...a,userMessage:r.trim()||void 0};i(C)},g=()=>{l(""),c(!1),h(),n(!1)},b={category:a.category,error:{message:(x=a.systemState)==null?void 0:x.errorMessage,sql:(j=a.systemState)==null?void 0:j.generatedSql,errorSql:(f=a.systemState)==null?void 0:f.errorSql},cardConfig:(N=a.systemState)==null?void 0:N.cardConfig,dataSource:(T=a.systemState)==null?void 0:T.dataSource,filters:(k=a.systemState)==null?void 0:k.dashboardFilters,metadata:a.metadata};return e.jsx(s.Dialog,{open:t,onOpenChange:g,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:u?"Feedback Sent Successfully":"Report Query Generation Issue"}),e.jsx(s.DialogDescription,{children:u?`Your feedback has been submitted with issue number: ${m==null?void 0:m.issueNumber}`:"Help us improve by reporting this query generation issue. Your feedback will be sent to our support team."})]}),!u&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"message",children:"Additional Information (Optional)"}),e.jsx(s.Textarea,{id:"message",placeholder:"Please describe what you were trying to do when this error occurred...",value:r,onChange:C=>l(C.target.value),className:"min-h-[100px] resize-none ring-inset focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-0",disabled:d})]}),e.jsxs(s.Collapsible,{open:o,onOpenChange:c,children:[e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",className:"flex w-full items-center justify-between p-2 hover:bg-muted",children:[e.jsx("span",{className:"text-sm font-medium",children:"View data to be sent"}),o?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronRight,{className:"h-4 w-4"})]})}),e.jsx(s.CollapsibleContent,{children:e.jsx(s.ScrollArea,{className:"h-[300px] w-full rounded-md border bg-muted/50 p-4",children:e.jsx("div",{className:"text-xs",children:e.jsx(s.CodeHighlighter,{code:JSON.stringify(b,null,2),language:"json"})})})})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:g,disabled:d,children:"Cancel"}),e.jsx(s.Button,{onClick:p,disabled:d,className:"min-w-[100px]",children:d?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Sending..."]}):"Send Feedback"})]})]}),u&&e.jsxs("div",{className:"flex flex-col items-center space-y-4 py-6",children:[e.jsx(ca,{className:"h-12 w-12 text-green-600"}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-lg font-medium",children:"Thank you for your feedback!"}),e.jsxs("p",{className:"mt-2 text-sm text-muted-foreground",children:["Issue Number:"," ",e.jsx("span",{className:"font-mono font-medium",children:m==null?void 0:m.issueNumber})]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Our support team will review your feedback and take appropriate action."})]}),e.jsx(s.Button,{onClick:g,className:"mt-4",children:"Close"})]})]})})}var Gt=(t=>(t.QUERY_GENERATION="query-generation",t))(Gt||{});function fo({activeView:t,onViewChange:n,showDebug:a,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:d,activeCard:u,columns:m,columnsLoading:h,columnsError:p}){var V;const g=s.useEditorStore(U=>U.card),b=s.useDashboardStore(U=>U.filterValues),x=(b==null?void 0:b.length)||0,{updateCardConfig:j,setCard:f,updateCardInFrame:N,setCardId:T}=s.useEditorActions(),{updateCardId:k}=s.useDashboardActions(),[C,w]=M.useState(null),v=s.useEditorStore(U=>U.showAIDialog),[E,y]=M.useState(!1),[F,I]=M.useState(!1),[P,D]=M.useState(null),{isConsoleMode:S}=s.useDashboardPreferences(),{config:L}=M.useContext(s.SemaphorContext).tokenProps,O=(L==null?void 0:L.showInfoTab)!==!1,R=s.useEditorStore(U=>{var ee;return((ee=U.card.customCardPreferences)==null?void 0:ee.url)&&U.card.type==="custom"}),{data:A,errorMessage:B,isLoading:Y,isFetching:_,errorSql:Q,pagination:X}=s.useDashboardCardQuery(u),q=(U,ee)=>{const ae={...u,paginationConfig:{page:U+1,pageSize:ee}};f(ae),N(ae)};function W(){return e.jsx("div",{className:"border-b border-border bg-background p-4",children:e.jsxs("div",{className:"space-y-4",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(g.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(b||{},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(u.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",m.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:h?"Loading...":p?"Error loading columns":JSON.stringify(m.slice(0,5),null,2)})]})]})})}const G=U=>{if(!g.config)return;if(!U.length){j(g.id,{...g.config,sortByColumns:[]});return}const ee=g.config,ae=U.map(({id:ie,desc:z})=>{var J,ce;const te=(J=ee.metricColumns)==null?void 0:J.find(de=>de.label===ie),oe=(ce=ee.groupByColumns)==null?void 0:ce.find(de=>de.label===ie),re=te||oe;return re?{id:s.getFieldId("sortBy",re),name:re.name,dataType:re.dataType,label:re.label,qualifiedEntityName:re.qualifiedEntityName,entityId:re.entityId,entityName:re.entityName,entityType:re.entityType,role:"sortby",direction:z?"desc":"asc"}:null}).filter(ie=>ie!==null);j(g.id,{...ee,sortByColumns:ae})},se=M.useMemo(()=>{var U,ee;return(ee=(U=g.config)==null?void 0:U.sortByColumns)==null?void 0:ee.map(ae=>({id:ae.label,desc:ae.direction==="desc"}))},[(V=g.config)==null?void 0:V.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[e.jsx(oo,{showDebug:a,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:d}),a&&W(),e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t==="chart"&&v&&e.jsx(Tt,{variant:"outline"}),e.jsx(io,{activeView:t,onViewChange:n}),i&&e.jsx(lo,{dashboardFilterCount:x,cardFilterCount:d,onClick:i,className:"h-8"}),e.jsx("div",{className:"ml-2",children:e.jsx(uo,{})}),v&&e.jsx(os,{})]}),e.jsx("div",{className:s.cn("flex grow items-center justify-end"),children:t==="chart"&&e.jsx(kt,{})})]}),!E&&R&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>y(!0),className:"absolute right-5 top-1/2 z-40 size-10 -translate-y-1/2 rounded-full border border-border bg-background shadow-lg hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:e.jsx(s.Settings2,{className:"size-4"})}),e.jsxs("div",{className:"mt-3 flex grow flex-col",children:[t==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:e.jsx(Et,{})}),t==="table"&&(A==null?void 0:A.records)&&e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:e.jsx(s.TableVisual,{card:u,data:(A==null?void 0:A.records)||[],paginationMetadata:X,onPaginationChange:q,isLoading:Y||_,onSortChange:G,sortState:se})}),t==="info"&&O&&e.jsx("div",{className:"px-6",children:e.jsxs("div",{className:"rounded-md bg-background",children:[e.jsxs("div",{className:"mb-2",children:[S&&e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Card ID:"}),e.jsx(s.EditableText,{value:g.id,onSave:U=>{const ee=s.sanitizeCardId(U);if(!ee){w("Card ID cannot be empty");return}const ae=k(g.id,ee);if(ae.success){T(ee);const ie={...g,id:ee};f(ie),N(ie),w(null),s.ue.success("Card ID updated successfully")}else w(ae.error||"Failed to update Card ID"),s.ue.error(ae.error||"Failed to update Card ID")},isEditable:!0,placeholder:"Enter card ID",displayClassName:"font-mono text-xs text-muted-foreground hover:text-foreground",inputClassName:"font-mono text-xs"}),e.jsx(s.CopyButton,{text:g.id,className:"h-5 w-5"})]}),C&&e.jsx("p",{className:"text-xs text-destructive",children:C})]}),B||Q?e.jsx(bt,{error:B,errorSql:Q,onSendFeedback:()=>{const U=xo(Gt.QUERY_GENERATION,{cardConfig:g.config,dataSource:u.dataSource,dashboardFilters:b,errorMessage:B,errorSql:Q,generatedSql:A==null?void 0:A.sql});D(U),I(!0)}}):e.jsxs(e.Fragment,{children:[(A==null?void 0:A.sql)&&e.jsx("h3",{className:"mb-1 px-2 font-mono text-xs font-medium",children:"Generated SQL Query"}),e.jsx(vt,{sql:A==null?void 0:A.sql,error:B,errorSql:Q})]})]})})]}),e.jsx(mo,{isOpen:E,onClose:()=>y(!1)}),P&&e.jsx(po,{open:F,onOpenChange:I,feedbackData:P})]})]})}function go({activeField:t}){const[n,a]=M.useState(!0);return M.useEffect(()=>{t&&a(!0)},[t]),t?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${n?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(s.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(Rs,{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 jo=()=>{const t=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||t.apply(console,r)};const n=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},a=r=>{var l;if((l=r.reason)!=null&&l.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",n,!0),window.addEventListener("unhandledrejection",a,!0),()=>{console.error=t,window.removeEventListener("error",n,!0),window.removeEventListener("unhandledrejection",a,!0)}};function bo(){var X,q;const[t,n]=M.useState("chart"),[a,r]=M.useState(!1),[l,o]=M.useState(!1),[c,i]=M.useState(!0),d=s.useEditorStore(W=>W.showAIDialog),u=s.useDashboardStore(W=>W.isVisualEditing),{setCardType:m}=s.useEditorActions(),h=s.useEditorStore(W=>W.card.type);M.useEffect(()=>jo(),[]);const p=()=>{console.log("Accept clicked - would save/apply current configuration")},g=()=>{console.log("Clear clicked - would reset all configurations")},b=()=>{console.log("Advanced mode toggled")},x=()=>{o(!0)},j=W=>{m(W)},f=s.useEditorStore(W=>W.frame),N=s.useEditorStore(W=>W.card);s.useEditorStore(W=>W.activeTabCardId),s.useEditorStore(W=>W.actions.getAvailableFields);const{addCard:T,removeCard:k,updateCard:C,setActiveCard:w,updateFilters:v}=s.useEditorActions(),{columns:E=[],isLoading:y,error:F}=s.useColumns(),I=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),P=N,{getFieldsForContainer:D,setFieldsForContainer:S}=Ls(P),{activeField:L,handleDragStart:O,handleDragEnd:R}=ro({activeCardId:f.activeCardId,sourceFields:E,getFieldsForContainer:D,setFieldsForContainer:S}),A=(W,G)=>{G&&v(W,G)},B=W=>{var G;C(W,{config:{...(G=f.cards.find(se=>se.id===W))==null?void 0:G.config,filters:void 0}})},Y=E,_=W=>{if(!W)return 0;let G=W.conditions.length;return W.groups.forEach(se=>{G+=_(se)}),G},Q=_(((X=P==null?void 0:P.config)==null?void 0:X.filters)||null);return e.jsxs(s.DndContext,{sensors:I,collisionDetection:s.closestCenter,onDragStart:O,onDragEnd:R,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Nl,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(_l,{selectedChart:h,onChartChange:j,groupByFields:D("groupBy"),pivotByFields:D("pivotBy"),metricsFields:D("metrics"),sortByFields:D("sortBy")}),e.jsx(fo,{selectedChart:h,activeView:t,onViewChange:n,showDebug:a,onDebugToggle:()=>r(!a),onAccept:p,onClear:g,onAdvancedToggle:b,onFiltersClick:x,filterCount:Q,activeCard:P,dataSourceState:N.dataSource||s.EMPTY_DATA_SOURCE,columns:E,columnsLoading:y,columnsError:F,getFieldsForContainer:D,cards:f.cards,activeCardId:f.activeCardId,addCard:T,setActiveCard:w})]}),!c&&u&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>i(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),P&&e.jsx(no,{cardId:P.id,filters:((q=P.config)==null?void 0:q.filters)||null,onFiltersChange:A,onClearFilters:B,availableFields:Y,isOpen:l,onOpenChange:o}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(go,{activeField:L||null})})]})}function vo({authToken:t,onSave:n,onClose:a}){const r=M.useRef(null),l=s.useEditorStore(N=>N.showAIDialog),o=s.useEditorStore(N=>N.isDevMode),{setAuthToken:c}=s.useDashboardActions(),{setShowAIDialog:i,setOnSave:d,setOnClose:u}=s.useEditorActions(),{handleDragOver:m,handleDragEnd:h,handleDragStart:p,handleDragCancel:g,sensors:b}=Bn();M.useEffect(()=>{n&&d(n),a&&u(a)},[n,d,a,u]),M.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),M.useEffect(()=>{var N,T;l?((N=r.current)==null||N.resize(40),i(!0)):(i(!1),(T=r.current)==null||T.resize(0))},[l,i]);function x(N){N<1?i(!1):l||i(!0)}function j(){return e.jsxs(e.Fragment,{children:[e.jsx(jt,{type:"main"}),e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:"grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(il,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(Ws,{})})]})]})}function f(){return e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:"flex grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(bo,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(Ws,{})})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:o?e.jsx(s.DndContext,{sensors:b,onDragStart:p,onDragEnd:h,onDragOver:m,onDragCancel:g,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:j()})}):f()})}function yo(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:n}=s.useDashboardStore(c=>c.actions),a=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function l(c){t&&(r(t,c),n(!1))}function o(){n(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!a}),children:e.jsx(vo,{onSave:l,onClose:o})})}function No({column:t}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{className:"shrink-0",asChild:!0,children:s.isTextDataType(t.data_type)?e.jsx(s.TextIcon,{className:"size-3 text-muted-foreground"}):s.isNumberDataType(t.data_type)?e.jsx(De,{className:"size-3 text-muted-foreground"}):s.isDateDataType(t.data_type)?e.jsx(s.Calendar,{className:"size-3 text-muted-foreground"}):s.isBooleanDataType(t.data_type)?e.jsx(Le,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(ia,{className:"size-3 text-muted-foreground"}):e.jsx(s.QuestionMarkIcon,{className:"size-3 text-muted-foreground"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{className:"text-xs",children:t.data_type})})]})})}function Co(){const t=s.useEditorStore(o=>o.selectedDatabaseName),n=s.useEditorStore(o=>o.selectedTableName),a=s.useDashboardStore(o=>o.dashboard.filters)||[],{columns:r}=s.useEditorAside(),{assignFilter:l}=Is();return e.jsx(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(o=>{const c=a==null?void 0:a.find(i=>i.column===s.fmt(o.column_name)&&i.table===n&&i.database===t);return e.jsx("div",{onClick:()=>l(o),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":c}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(No,{column:o}),e.jsx("span",{children:o.column_name})]})},o.column_name)})})}function So({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ve,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Le,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Be,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Ye,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(He,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ve,{className:"h-3 w-3"})})}function wo(){const[t,n]=M.useState(""),[a,r]=M.useState("all"),l=s.useDashboardStore(f=>f.dashboard.filters)||[],{assignFilter:o}=Is(),c=s.useEditorStore(f=>f.card.dataSource),{columns:i=[],isLoading:d,error:u}=s.useColumns(),m=i.filter(f=>f.name.toLowerCase().includes(t.toLowerCase())||f.dataType.toLowerCase().includes(t.toLowerCase())||f.label&&f.label.toLowerCase().includes(t.toLowerCase())),h=f=>{const N=s.getDataType(f.dataType);return N==="number"?"metrics":(["date","string","boolean"].includes(N),"dimensions")},p=a==="all"?m:m.filter(f=>h(f)===a),g=m.filter(f=>h(f)==="dimensions").length,b=m.filter(f=>h(f)==="metrics").length,x=f=>{const N={column_name:f.name,data_type:f.dataType,label:f.label,description:f.description};o(N,"dashboard",f)};if(d)return e.jsx("div",{className:"flex h-full grow flex-col items-center justify-center px-3",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading fields"})});if(u)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-3",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:u.message||"Failed to load column data"})]});if(!c||!c.selectedEntities||c.selectedEntities.length===0)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 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:"Select a table, view, or dataset from the data source panel to see available fields"})]});if(i.length===0)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx("p",{className:"text-sm text-gray-500",children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]});const j=m.length>0;return e.jsxs("div",{className:"flex h-full grow flex-col pb-4",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-3 px-3 pt-3",children:[i.length>0&&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 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:t,onChange:f=>n(f.target.value)})]}),j&&e.jsx(s.Tabs,{defaultValue:"all",value:a,onValueChange:f=>r(f),children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-3",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:m.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:g})]}),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:b})]})]})})]}),e.jsxs(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3 pt-3",children:[p.length===0&&t&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',t,'"']}),p.length===0&&!t&&a!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",a," fields found"]}),p.map(f=>{const N=l==null?void 0:l.some(T=>{var k;return T.title===f.name||((k=T.column)==null?void 0:k.includes(f.name))});return e.jsx("div",{onClick:()=>x(f),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":N}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(So,{dataType:f.dataType}),e.jsx("span",{children:f.label||f.name})]})},f.id)})]})]})}function Do(){var r;const t=s.useDashboardStore(l=>l.actions.setShowFilters),n=s.useCurrentActiveCard(),a=n&&((r=n.dataSource)==null?void 0:r.selectedEntities)&&n.dataSource.selectedEntities.length>0;return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l px-1",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-3",children:[e.jsx(s.Label,{className:"px-2 text-lg",children:"Filters"}),e.jsx(s.Button,{onClick:()=>t(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(s.Cross2Icon,{})})]}),e.jsx("div",{className:"flex grow",children:a?e.jsx(wo,{}):e.jsx(jt,{type:"filter",ColumnsComponent:()=>e.jsx(Co,{})})})]})}function To(){const t=s.useDashboardStore(r=>r.dashboard.filters),n=s.useDashboardStore(r=>r.theme),a=t==null?void 0:t.filter(r=>r.hide);return a!=null&&a.length?e.jsx("div",{className:s.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":n==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":n==="dark"}),children:a==null?void 0:a.map(r=>e.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[e.jsx(s.FilterHeader,{filter:r}),e.jsx(s.FilterComponent,{filter:r})]},r.id))}):null}function ko(){const t=s.useDashboardStore(r=>r.showFilters),n=s.useDashboardStore(r=>r.isVisualEditing),a=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":n,"flex grow overflow-auto":!n}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[a&&e.jsx(To,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Do,{})})]})}function Eo(){const t=s.useDashboardStore(l=>l.dashboard),n=s.useDashboardStore(l=>l.actions.setDashboard),a=s.useDashboardStore(l=>l.showDashboardJSON),r=s.useDashboardStore(l=>l.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!a}),children:[e.jsxs(s.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(s.de,{onChange:l=>{if(l)try{JSON.parse(l),n(JSON.parse(l))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(t,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function Yt(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4",children:[e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"space-y-2",children:[...Array(4)].map((t,n)=>e.jsx("div",{className:"animate-pulse",children:e.jsxs("div",{className:"group relative flex items-start gap-3 px-4 py-3",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-muted"})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("div",{className:"h-4 w-32 rounded bg-muted"})}),e.jsx("div",{className:"shrink-0",children:e.jsx("div",{className:"h-3.5 w-3.5 rounded bg-muted"})})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-3 w-48 rounded bg-muted"})})]}),e.jsx("div",{className:"absolute right-3 top-2",children:e.jsx("div",{className:"flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:e.jsx("div",{className:"h-6 w-6 rounded bg-muted"})})})]})]})},n))})]})})}function Io({visual:t,isDeleting:n,isDuplicating:a,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onAddVisual:o,onEditVisual:c,onUpdateVisual:i,onDeleteClick:d,onDuplicateVisual:u,onShareVisual:m,formatDate:h}){var w,v,E;const{selectVisual:p}=s.useManagementActions(),g=s.useIsVisualSelected(t.id),{isConsoleMode:b}=s.useDashboardPreferences(),x=s.useDashboardStore(y=>y.actions.setIsDashboardPanelOpen),[j,f]=M.useState(!1),[N,T]=M.useState(!1);M.useEffect(()=>{a?(f(!0),T(!0)):N&&(f(!1),T(!1))},[a,N]);const k=()=>e.jsx(rs,{className:"h-4 w-4"}),C=()=>{p(t),c==null||c(t)};return e.jsx(s.Card,{className:s.cn("group p-3 hover:bg-accent/50 transition-colors cursor-pointer border-border/50",g&&"ring-1 ring-primary"),onClick:C,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 p-1.5 rounded bg-muted",children:k()}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-foreground",value:t.title,onSave:y=>i==null?void 0:i(t.id,{title:y}),isEditable:t.ownership.isOwner&&g,isPending:r,placeholder:"Untitled Visual",displayClassName:"font-medium text-sm text-foreground truncate"}),t.ownership.status==="shared"&&e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:[e.jsx(s.Users,{className:"h-2.5 w-2.5 mr-1"}),"Shared"]})]}),e.jsx(s.EditableText,{inputClassName:"text-xs text-muted-foreground line-clamp-2",value:t.description||"",onSave:y=>i==null?void 0:i(t.id,{description:y}),isEditable:t.ownership.isOwner&&g,isPending:l,placeholder:"No description",displayClassName:"text-xs text-muted-foreground line-clamp-2 mb-2"}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsxs("span",{children:["Updated ",h(t.lastModified)]})]})]}),e.jsxs("div",{className:s.cn("opacity-0 transition-opacity duration-150 group-hover:opacity-100","ml-2 flex-shrink-0 flex items-center gap-1"),onClick:y=>y.stopPropagation(),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:y=>{y.stopPropagation(),o(t)},title:"Add to dashboard",children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:j,onOpenChange:f,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),o(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.preventDefault(),y.stopPropagation(),u(t.id)},disabled:a,children:[a?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),a?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),c==null||c(t)},children:[e.jsx(Ra,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),m(t)},children:[e.jsx(s.Users,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),d(t),x(!1)},className:"text-destructive",disabled:n,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),n?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((w=t.ownership.createdBy)==null?void 0:w.type)==="tenant"||((v=t.ownership.createdBy)==null?void 0:v.type)==="organization"&&b)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.User,{className:"h-3 w-3"}),e.jsx("span",{children:((E=t.ownership.createdBy)==null?void 0:E.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:h(t.lastModified)})]})]})]})]})]})]})},t.id)}function Ao(){const[t,n]=M.useState(""),[a,r]=M.useState(!1),[l,o]=M.useState(""),[c,i]=M.useState(""),[d,u]=M.useState(!1),[m,h]=M.useState(null),[p,g]=M.useState(!1),[b,x]=M.useState(null),[j,f]=M.useState(null),{setIsDashboardEditing:N,setIsVisualEditing:T}=s.useDashboardActions(),{handleEditLibraryVisual:k,handleAddLibraryVisual:C}=Ts(),{resources:w,isLoading:v,isError:E,createResource:y,updateResource:F,deleteResource:I,duplicateResource:P,isCreating:D,isDeleting:S}=s.useVisualManagement(()=>{g(!1),x(null)},()=>{r(!1),o(""),i("")});s.useCurrentUserInfo();const L=w.filter(U=>{var ee,ae;return((ee=U==null?void 0:U.title)==null?void 0:ee.toLowerCase().includes(t.toLowerCase()))||((ae=U==null?void 0:U.description)==null?void 0:ae.toLowerCase().includes(t.toLowerCase()))}),O=U=>new Date(U).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),R=()=>{l.trim()&&y({title:l,description:c,isPrivate:!1})},A=U=>{x(U),g(!0)},B=()=>{b&&I(b.id)},{startUpdating:Y,stopUpdating:_,isUpdating:Q}=s.useResourceUpdateState(),X=(U,ee)=>{const ae=ee.title!==void 0?"title":"description";Y(U,ae),F({resourceId:U,data:ee},{onSuccess:()=>{_(U,ae)},onError:()=>{_(U,ae)}})},q=U=>{f(U),P(U,{onSettled:()=>f(null)})},W=U=>{k(U)},G=U=>{C(U)},se=U=>{const ee=w.find(ae=>ae.id===U);ee&&F({resourceId:U,data:{isPrivate:!ee.isPrivate}})},V=U=>{h(U),u(!0)};return v?e.jsx(Yt,{}):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:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[e.jsx("div",{className:"px-1",children:a?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Visual"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:l,onChange:U=>o(U.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter visual description...",value:c,onChange:U=>i(U.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:R,size:"sm",className:"h-7 text-xs",disabled:!l.trim()||D,children:D?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),o(""),i("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:D,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>r(!0),className:"w-full bg-primary hover:bg-primary/90 text-primary-foreground",disabled:D,children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),D?"Creating...":"Create New Visual"]})}),w&&w.length>5&&e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:t,onChange:U=>n(U.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:L.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"mb-3",children:e.jsx(rs,{className:"h-12 w-12 mx-auto text-muted-foreground/50"})}),e.jsx("h3",{className:"font-medium text-foreground mb-1",children:t?"No visuals found":"No visuals yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",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:"h-4 w-4 mr-2"}),"Create Visual"]})]}):L.map(U=>e.jsx(Io,{visual:U,onAddVisual:G,onEditVisual:W,onUpdateVisual:X,onDeleteClick:A,onDuplicateVisual:q,onTogglePrivacy:se,onShareVisual:V,isDeleting:S,isDuplicating:j===U.id,isTitleUpdating:Q(U.id,"title"),isDescriptionUpdating:Q(U.id,"description"),formatDate:O},U.id))})}),d&&m&&e.jsx(ls,{resource:m,resourceType:s.ResourceType.VISUAL,onClose:()=>{u(!1),h(null)}}),e.jsx(s.AlertDialog,{open:p,onOpenChange:U=>{!U&&S||(g(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 "',b==null?void 0:b.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:S,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:U=>{U.preventDefault(),U.stopPropagation(),B()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:S,children:S?"Deleting...":"Delete"})]})]})})]})}function Mo({dashboard:t,isDeleting:n,isDuplicating:a,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onLoadDashboard:o,onUpdateDashboard:c,onDeleteClick:i,onDuplicateDashboard:d,onShareDashboard:u,formatDate:m,onDashboardItemClick:h}){var w,v,E;const{selectDashboard:p}=s.useManagementActions(),g=s.useIsDashboardSelected(t.id),{isConsoleMode:b}=s.useDashboardPreferences(),[x,j]=M.useState(!1),[f,N]=M.useState(!1),T=s.useDashboardStore(y=>y.actions.setIsDashboardPanelOpen);M.useEffect(()=>{a?(j(!0),N(!0)):f&&(j(!1),N(!1))},[a,f]);const k=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4"}),C=()=>{p(t),o(t.id),h==null||h(t.id)};return e.jsx(s.Card,{className:s.cn("group p-3 hover:bg-accent/50 transition-colors cursor-pointer border-border/50",g&&"ring-1 ring-primary"),onClick:C,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 p-1.5 rounded bg-muted",children:k()}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-foreground",value:t.title,onSave:y=>c==null?void 0:c(t.id,{title:y}),isEditable:t.permissions.canEdit&&g,isPending:r,placeholder:"Untitled Dashboard",displayClassName:"font-medium text-sm text-foreground truncate"}),t.ownership.status==="shared"&&e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:[e.jsx(s.Users,{className:"h-2.5 w-2.5 mr-1"}),"Shared"]})]}),e.jsx(s.EditableText,{inputClassName:"text-xs text-muted-foreground line-clamp-2",value:t.description||"",onSave:y=>c==null?void 0:c(t.id,{description:y}),isEditable:t.permissions.canEdit&&g,isPending:l,placeholder:"No description",displayClassName:"text-xs text-muted-foreground line-clamp-2 mb-2"}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsxs("span",{children:["Updated ",m(t.lastModified)]})]})]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-150 group-hover:opacity-100","ml-2 flex-shrink-0"),onClick:y=>y.stopPropagation(),children:e.jsxs(s.DropdownMenu,{modal:!1,open:x,onOpenChange:j,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.preventDefault(),y.stopPropagation(),d(t.id)},disabled:a,children:[a?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),a?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),u(t)},children:[e.jsx(s.Users,{className:"mr-2 h-3 w-3"}),"Share"]})}),t.permissions.canDelete&&e.jsxs(e.Fragment,{children:[e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),i(t),T(!1)},className:"text-destructive",disabled:n,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),n?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((w=t.ownership.createdBy)==null?void 0:w.type)==="tenant"||((v=t.ownership.createdBy)==null?void 0:v.type)==="organization"&&b)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.User,{className:"h-3 w-3"}),e.jsx("span",{children:((E=t.ownership.createdBy)==null?void 0:E.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:m(t.lastModified)})]})]})]})]})})]})},t.id)}function Lo({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 Ro(t){const[n,a]=M.useState(""),[r,l]=M.useState(!1),[o,c]=M.useState(""),[i,d]=M.useState(""),[u,m]=M.useState(!1),[h,p]=M.useState(null),[g,b]=M.useState(!1),[x,j]=M.useState(null),[f,N]=M.useState(null),T=s.useManagementStore(z=>z.lastSelectedDashboard),k=s.useManagementStore(z=>z.selectedDashboard),C=s.useManagementStore(z=>z.actions.selectDashboard),w=s.useManagementStore(z=>z.actions.clearSelectedDashboard),{tokenProps:v,id:E}=s.useSemaphorContext(),{permissions:y}=s.useRoleAwareDisplayPreferences(),{resources:F,isLoading:I,isError:P,createResource:D,updateResource:S,deleteResource:L,duplicateResource:O,isCreating:R,isDeleting:A}=s.useDashboardManagement(()=>{b(!1);const z=x==null?void 0:x.id;j(null),(k==null?void 0:k.id)===z&&(!(v!=null&&v.dashboard_id)&&!E?w():T&&T.id!==z&&C(T))},()=>{l(!1),c(""),d("")}),{currentUser:B}=s.useCurrentUserInfo(),Y=F.filter(z=>{var te,oe;return((te=z==null?void 0:z.title)==null?void 0:te.toLowerCase().includes(n.toLowerCase()))||((oe=z==null?void 0:z.description)==null?void 0:oe.toLowerCase().includes(n.toLowerCase()))}),_=z=>new Date(z).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),Q=()=>{o.trim()&&D({title:o,description:i,isPrivate:!1})},X=z=>{var te;(te=t.onLoadDashboard)==null||te.call(t,z)},q=z=>{j(z),b(!0)},W=()=>{x&&L(x.id)},G=z=>{N(z),O(z,{onSettled:()=>N(null)})},{startUpdating:se,stopUpdating:V,isUpdating:U}=s.useResourceUpdateState(),ee=(z,te)=>{const oe=te.title!==void 0?"title":"description";se(z,oe),S({resourceId:z,data:te},{onSuccess:()=>{V(z,oe)},onError:()=>{V(z,oe)}})},ae=z=>{const te=F.find(oe=>oe.id===z);te&&S({resourceId:z,data:{isPrivate:!te.isPrivate}})},ie=z=>{p(z),B==null||B.type,m(!0)};return I?e.jsx(Yt,{}):P?e.jsx(Lo,{onRetry:()=>window.location.reload()}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[y.canCreateDashboards&&e.jsx("div",{className:"px-1",children:r?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Dashboard"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter dashboard title...",value:o,onChange:z=>c(z.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter dashboard description...",value:i,onChange:z=>d(z.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:Q,size:"sm",className:"h-7 text-xs",disabled:!o.trim()||R,children:R?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{l(!1),c(""),d("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:R,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>l(!0),className:"w-full bg-primary hover:bg-primary/90 text-primary-foreground",disabled:R,children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),R?"Creating...":"Create New Dashboard"]})}),F&&F.length>5&&e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:n,onChange:z=>a(z.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:Y.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"mb-3",children:e.jsx(s.ChartColumn,{className:"h-12 w-12 mx-auto text-muted-foreground/50"})}),e.jsx("h3",{className:"font-medium text-foreground mb-1",children:n?"No dashboards found":"No dashboards yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:n?"Try adjusting your search":y.canCreateDashboards?"Create your first dashboard to get started":"No dashboards have been shared with you yet"}),y.canCreateDashboards&&!n&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>l(!0),children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),"Create Dashboard"]})]}):Y.map(z=>e.jsx(Mo,{dashboard:z,isDeleting:A,isDuplicating:f===z.id,isTitleUpdating:U(z.id,"title"),isDescriptionUpdating:U(z.id,"description"),onLoadDashboard:X,onEditDashboard:t.onEditDashboard,onUpdateDashboard:ee,onDeleteClick:q,onDuplicateDashboard:G,onTogglePrivacy:ae,onShareDashboard:ie,formatDate:_,onDashboardItemClick:t.onDashboardItemClick},z.id))})}),u&&h&&e.jsx(ls,{resource:h,resourceType:s.ResourceType.DASHBOARD,onClose:()=>{m(!1),p(null)}}),e.jsx(s.AlertDialog,{open:g,onOpenChange:z=>{!z&&A||(b(z),z||j(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Dashboard"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',x==null?void 0:x.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:A,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:z=>{z.preventDefault(),z.stopPropagation(),W()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:A,children:A?"Deleting...":"Delete"})]})]})})]})}function $t({isOpen:t,onClose:n,className:a,onDashboardItemClick:r,variant:l="inline"}){s.useDashboardStore(T=>T.dashboard);const{setDashboard:o,addSheet:c}=s.useDashboardStore(T=>T.actions),{currentUser:i}=s.useCurrentUserInfo(),d=i,{permissions:u}=s.useRoleAwareDisplayPreferences(),m=(u.canAccessVisuals,"dashboards"),[h,p]=s.useLocalStorageState("resource-management-active-tab",m),g=u.canAccessVisuals?h:"dashboards",b=l==="overlay",x=dt(n,{enabled:t&&b}),j=s.cn("flex h-full flex-col border-r bg-background",b?s.cn("absolute inset-y-0 left-0 z-[51] w-96 shadow-lg transition-transform duration-300 ease-in-out",t?"translate-x-0":"pointer-events-none -translate-x-full"):"w-full max-w-[28rem] min-w-[18rem] overflow-hidden shadow-sm",a),f=T=>{},N=T=>{console.log("Editing dashboard:",T)};return e.jsx(s.TooltipProvider,{children:(!b||t)&&e.jsxs("div",{ref:x,className:j,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:d&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-full bg-primary/10",children:e.jsx("span",{className:"text-sm font-medium text-primary",children:d.name.charAt(0).toUpperCase()})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:d.name}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:u.canCreateDashboards?"default":"secondary",className:"cursor-help text-xs",children:u.canCreateDashboards?e.jsxs(e.Fragment,{children:[e.jsx(s.Users,{className:"mr-1 h-3 w-3"}),"Power User"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Eye,{className:"mr-1 h-3 w-3"}),"Viewer"]})})}),e.jsx(s.TooltipContent,{side:"bottom",className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"font-medium",children:d.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:d.email}),d.role&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Role:"," ",s.toTitleCase(d.role.replace(/_/g," "))]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",d.id]})]})})]})})]})]})}),e.jsx(s.IconButton,{className:"h-8 w-8 cursor-w-resize p-0 text-muted-foreground hover:text-foreground",onClick:n,tooltip:"Close Sidebar",children:e.jsx(La,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:g,onValueChange:u.canAccessVisuals?p:void 0,className:"flex h-9 grow flex-col",children:[u.canAccessVisuals?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("div",{className:"px-4 pb-0 pt-4",children:e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Dashboards"})}),e.jsx(s.TabsContent,{value:"dashboards",className:"mt-4 flex-1",children:e.jsx(Ro,{onLoadDashboard:f,onEditDashboard:N,onDashboardItemClick:r})}),u.canAccessVisuals&&e.jsx(s.TabsContent,{value:"visuals",className:"mt-4 flex-1",children:e.jsx(Ao,{})})]})})]})})}function Oo({showControls:t=!1,showFooter:n=!0,...a}){const r=s.useDashboardStore(h=>h.isDashboardPanelOpen),l=s.useDashboardStore(h=>h.isVisualEditing),o=s.useDashboardStore(h=>h.actions.setIsDashboardPanelOpen),c=20,i=20,d=30,u=r&&!l;if(typeof window>"u")return null;const{preferences:m}=a;return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:a,children:[e.jsx(s.$e,{}),e.jsx(s.UXProvider,{children:e.jsxs(s.DashboardPreferencesProvider,{preferences:m,children:[e.jsx(Eo,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx(Mn,{}),e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",className:"flex grow overflow-hidden",children:[e.jsx(s.ResizablePanel,{className:s.cn("flex h-full max-w-[26rem] overflow-hidden",{"min-w-[20rem]":r}),defaultSize:r?c:0,minSize:r?i:0,maxSize:r?d:0,children:e.jsx($t,{isOpen:r,onClose:()=>o(!1),variant:"inline"})}),e.jsx(s.ResizableHandle,{withHandle:r,className:s.cn("w-1",{"w-0":!r})}),e.jsx(s.ResizablePanel,{className:"flex min-w-0 flex-1",defaultSize:u?100-c:100,minSize:u?40:100,children:e.jsxs(s.Container,{...a,type:"dashboard",children:[e.jsx(yo,{}),e.jsx(ko,{})]})})]},u?"with-management":"without-management")]})]})})]})})}exports.DashboardPlus=Oo;exports.ResourceManagementPanel=$t;exports.ScheduleDashboard=lt;exports.SelectComponent=Fe;exports.ShareDialog=ls;exports.cleanCard=rt;exports.getDashbaordStateWithoutData=ss;
|
|
339
|
+
ON ${y}`}),b};return o.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:[a.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:()=>l(!0),children:[e.jsx(s.Link,{className:s.cn("mr-1 h-3 w-3",{"text-blue-500":a.joins.length>0,"text-gray-500":a.joins.length===0})}),"Join",a.joins.length>1?"s":""," (",a.joins.length,")"]})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(jl,{joins:a.joins,baseEntityId:a.baseEntity.name,availableDataSources:o,generateSQLPreview:u})})]})}),e.jsx(Ks,{open:r,onOpenChange:l,joinPlan:a,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsx("div",{})})]}),a.joins.length===0&&e.jsx(Ks,{open:r,onOpenChange:l,joinPlan:a,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsxs(s.Button,{onClick:()=>l(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function vl({open:t,onOpenChange:n}){const[a,r]=A.useState([]),{updateDataSource:l}=s.useEditorActions(),o=s.useDashboardStore(x=>x.dashboard.aiContext),c=(o==null?void 0:o.selectedEntities)||[];A.useEffect(()=>{t&&r([])},[t]);const i=x=>{r(j=>j.some(y=>y.name===x.name&&y.type===x.type)?j.filter(y=>!(y.name===x.name&&y.type===x.type)):[...j,x])},d=()=>{r([...c])},u=()=>{r([])},m=()=>{if(a.length===0)return;const x=a[0],j=x.connectionId||"",f=x.connectionType||"",E=a.some(C=>C.type==="dataset")?"semanticDomain":"database";l({connectionId:j,connectionType:f,mode:E,selectedEntities:a}),n(!1)},h=x=>{switch(x.type){case"table":return e.jsx(s.Table,{className:"h-4 w-4"});case"view":return e.jsx($a,{className:"h-4 w-4"});case"model":return e.jsx(xa,{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"})}},p=x=>"label"in x&&x.label?x.label:x.name,g=x=>{if("description"in x&&x.description)return x.description;const j=[];return x.database&&j.push(x.database),x.schema&&j.push(x.schema),x.name&&j.push(x.name),j.join(".")},b=x=>a.some(j=>j.name===x.name&&j.type===x.type);return c.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-md",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"No Data Available"}),e.jsx(s.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{onClick:()=>n(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(s.DialogDescription,{children:"Choose entities from the dashboard's context"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"outline",size:"sm",onClick:d,disabled:a.length===c.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:u,disabled:a.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[a.length," of ",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((x,j)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",b(x)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:b(x),onCheckedChange:()=>i(x)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:h(x)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:p(x)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:g(x)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:x.type})]},`${x.type}-${x.name}-${j}`))})})]}),e.jsx(s.DialogFooter,{children:e.jsx("div",{className:"flex w-full justify-between",children:e.jsxs("div",{className:"flex grow justify-end gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:m,disabled:a.length===0,children:["Select"," ",a.length>0?`(${a.length})`:""]})]})})})]})})}function yl({entity:t,title:n,maxDetails:a=10}){const l=s.getEntityDetails(t).slice(0,a),o=l.find(i=>i.label==="Description"),c=l.filter(i=>i.label==="Description"?!1:!["Connection","Database","Schema"].includes(i.label));return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:n||s.getDisplayName(t)}),o&&e.jsxs("div",{className:"border-t border-border pt-2",children:[e.jsx("div",{className:"mb-1 text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:o.value})]}),c.length>0&&e.jsx("div",{className:"space-y-0.5",children:c.map((i,d)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[i.label,":"]}),e.jsx("span",{className:"font-mono",children:i.value})]},d))})]})})}function Nl({entities:t}){return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:[t.length," more entities"]}),e.jsx("div",{className:"space-y-1",children:t.map((n,a)=>{const r=s.getEntityDetails(n),l=r.find(c=>c.label==="Description"),o=r.filter(c=>c.label==="Description"?!1:!["Connection","Database","Schema"].includes(c.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(n)}),l&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:l.value})]}),o.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:o.map((c,i)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[c.label,":"]}),e.jsx("span",{className:"font-mono",children:c.value})]},i))})]},`remaining-${n.type}-${n.name}-${a}`)})})]})})}function Cl({isVisible:t}){const[n,a]=A.useState(!1),[r,l]=A.useState(!1),[o,c]=A.useState(!0),i=s.useEditorStore(h=>h.card.dataSource);s.useCurrentUserInfo();const{updateDataSource:d}=s.useEditorActions(),u={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},m={...u,...i,selectedEntities:(i==null?void 0:i.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:()=>a(!0),children:[e.jsx(s.Database,{className:"mr-2 h-3.5 w-3.5"}),"Add Data"]})}),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:()=>c(!o),className:"size-6 bg-background p-1 py-1 hover:bg-accent",children:o?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 ${o?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[m.selectedEntities.length>0&&e.jsx(s.TooltipProvider,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[m.selectedEntities.slice(0,3).map((h,p)=>e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[s.getDisplayName(h),e.jsx("button",{onClick:g=>{g.stopPropagation();const b=m.selectedEntities.filter(x=>!(x.name===h.name&&x.type===h.type));d({...u,...i,selectedEntities:b})},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(yl,{entity:h})]},`${h.type}-${h.name}-${p}`)),m.selectedEntities.length>3&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:["+",m.selectedEntities.length-3," more"]})}),e.jsx(Nl,{entities:m.selectedEntities.slice(3)})]})]})}),e.jsx(bl,{})]})]}),e.jsx(pl,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(i==null?void 0:i.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:a,dataSource:m,fallbackDataSource:u}),e.jsx(vl,{open:r,onOpenChange:l})]})}const Sl="chart-selector-standard-first";function wl(){const[t,n]=s.useLocalStorageState(Sl,!0);return{standardFirst:t,updatePreference:n}}const Qs=({pluginVisual:t,index:n,onSelect:a})=>{const r=is(t.icon||""),l=t.name.charAt(0).toUpperCase(),o=s.getAutoDetectedChartIcon(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:a,className:"group flex items-center gap-2",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(r,{className:"h-4 w-4"}):o||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:l}),e.jsx("span",{children:t.name})]}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:"opacity-0 outline-none transition-opacity group-hover:opacity-100",children:e.jsx(s.Info,{className:"ml-1 h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"right",children:t.pluginName})]})]})},`${t.url}-${t.name}-${n}`)},Js=["default","standardPlugin","customPlugin"];function Dl({selectedChart:t,onChartChange:n}){var k;const[a,r]=A.useState(!1),{data:l}=Dt();wl();const c=((k=s.useEditorStore(C=>C.card).customCardPreferences)==null?void 0:k.url)||"";Ds(c);const{setCardType:i,setCardPreferences:d,setIsDevMode:u}=s.useEditorStore(C=>C.actions),{setCardCustomCfg:m,setCustomCardPreferences:h,setQueryConfig:p}=s.useEditorActions(),[g,b]=s.useLocalStorageState("chart-section-active",null),x=A.useMemo(()=>g?[g,...Js.filter(C=>C!==g)]:Js,[g]);function j(C){m(null),d({}),i(C),["custom","map"].includes(C)&&(u(!0),p(void 0)),n(C),r(!1)}function f(C){m(null),d({}),i("custom"),h({type:"component",visualType:"single",url:C.url,componentName:C.name,icon:C.icon,pluginChartType:C.chartType}),p(void 0),n("custom"),r(!1)}const y=()=>{var D;if(t==="custom"){const v=s.useEditorStore.getState().card;return((D=v==null?void 0:v.customCardPreferences)==null?void 0:D.componentName)||"Custom Visual"}const C=s.chartTypes.find(v=>v.id===t);return(C==null?void 0:C.label)||"Select chart type"},E=()=>{var D,v;if(t==="custom"){const N=s.useEditorStore.getState().card,S=(D=N==null?void 0:N.customCardPreferences)==null?void 0:D.icon,F=(v=N==null?void 0:N.customCardPreferences)==null?void 0:v.componentName;if(S&&F)return e.jsx(Tl,{icon:S,componentName:F});if(F){const I=s.getAutoDetectedChartIcon(F);if(I)return I}return e.jsx($e,{className:"h-4 w-4"})}const C=s.chartTypes.find(N=>N.id===t);if(C){const N=C.icon;return e.jsx(N,{className:"h-4 w-4"})}return e.jsx($e,{className:"h-4 w-4"})};return e.jsx("div",{className:"",children:e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[E(),e.jsx("span",{children:y()})]}),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."}),x.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:g==="default",onCheckedChange:D=>b(D?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:s.chartTypes.map(D=>{const v=D.icon;return e.jsx(s.CommandItem,{value:`${D.label} ${D.id} chart graph visualization`,onSelect:()=>j(D.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(v,{className:"h-4 w-4"}),e.jsx("span",{children:D.label})]})},D.id)})},"default");if(C==="standardPlugin"){const D=l.filter(v=>v.pluginType==="standard");return D.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:g==="standardPlugin",onCheckedChange:v=>b(v?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:D.filter(v=>v.componentType==="chart").map((v,N)=>e.jsx(Qs,{pluginVisual:v,index:N,onSelect:()=>f(v)},`${v.url}-${v.name}-${N}`))},"standardPlugin"):null}if(C==="customPlugin"){const D=l.filter(v=>v.pluginType==="custom");return D.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:g==="customPlugin",onCheckedChange:v=>b(v?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:D.map((v,N)=>e.jsx(Qs,{pluginVisual:v,index:N,onSelect:()=>f(v)},`${v.url}-${v.name}-${N}`))},"customPlugin"):null}return null})]})]})})]})})}const Tl=({icon:t,componentName:n})=>{const a=is(),r=s.getAutoDetectedChartIcon(n);return a?e.jsx(a,{className:"h-4 w-4"}):r||e.jsx($e,{className:"h-4 w-4"})},kl=[{id:"table",icon:s.Table2,label:"Table"},{id:"bar",icon:s.ChartColumnIncreasing,label:"Bar Chart"},{id:"line",icon:s.ChartLine,label:"Line Chart"},{id:"stackedBar",icon:s.ChartColumnStacked,label:"Stacked Bar",requiresPivot:!0},{id:"pie",icon:s.ChartPie,label:"Pie Chart"},{id:"doughnut",icon:s.Donut,label:"Donut Chart"},{id:"kpi",icon:s.TiSortNumerically,label:"KPI"}];function El({selectedChart:t,onChartChange:n}){var l;const a=s.useEditorStore(o=>o.card),r=((l=a==null?void 0:a.config)==null?void 0:l.pivotByColumns)&&a.config.pivotByColumns.length>0;return e.jsx("div",{className:"flex items-center justify-center gap-1",children:kl.map(o=>{if(o.requiresPivot&&!r)return null;const c=o.icon,i=t===o.id;return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",onClick:()=>n(o.id),className:s.cn("h-8 w-8 p-0",i&&"bg-accent text-accent-foreground"),children:[e.jsx(c,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:o.label})]})}),e.jsx(s.TooltipContent,{side:"bottom",children:e.jsx("p",{children:o.label})})]},o.id)})})}const Rs=({dataType:t})=>{const n=s.getDataType(t);return n==="string"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ve,{className:"h-3 w-3"})}):n==="number"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):n==="date"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Le,{className:"h-3 w-3"})}):e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ve,{className:"h-3 w-3"})})};function Il({aliasTemplate:t,onAliasTemplateChange:n}){var d;const[a,r]=A.useState(t),[l,o]=A.useState(!1),c=(d=s.useEditorStore(u=>{var m;return(m=u.card.config)==null?void 0:m.pivotByColumns}))==null?void 0:d[0],i=c?`e.g. Min Sales in {{${c.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Input$1,{placeholder:i,value:l?a:t,onChange:u=>{r(u.target.value),o(!0)},onFocus:()=>o(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&l&&a!==t?(n(a),o(!1)):u.key==="Escape"&&(r(t),o(!1))},"aria-label":"Edit alias template"}),l&&a!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{n(a),o(!1)},children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(t),o(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function Al({valueAliases:t,onValueAliasesChange:n}){const[a,r]=A.useState(null),[l,o]=A.useState(""),[c,i]=A.useState(""),d=()=>{n({...t,"":""})},u=h=>{const p={...t};delete p[h],n(p)},m=h=>{const p={...t};delete p[h],p[l]=c,n(p),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(t).map(([h,p],g)=>e.jsx("div",{className:"flex items-center gap-2",children:a===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:l,onChange:b=>o(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?m(h):b.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:b=>i(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?m(h):b.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>m(h),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(p)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:p,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(p)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+g)),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 Ml({field:t,searchQuery:n="",limit:a=500}){const{authToken:r,tokenProps:l}=s.useSemaphorContext(),o=s.useEditorStore(u=>u.card),c=o==null?void 0:o.dataSource,i=["attribute-values",t.entityName,t.name,n,a],d=s.useQuery({queryKey:i,queryFn:async()=>{if(!(c!=null&&c.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const u={groupByColumns:[{...t,role:"groupby"}],metricColumns:[],filters:n?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:n}],groups:[]}:void 0,rowLimit:a},m={connection_id:c.connectionId,cardConfig:u,cardDataSource:c,cache_config:s.getCacheConfig({card:o})};console.log("requestBody",m);const h=await s.postRequestRegular(`${l.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",m);if(h!=null&&h.error)return console.error("Error fetching attribute values:",h.error),[];const p=t.name;return((h==null?void 0:h.records)||[]).map(b=>{const x=b[p]||b[t.alias||p]||b[t.label];return{id:x||"",value:x||"",label:String(x||"(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 Ll({open:t,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:l,onSave:o}){var E,k;const c=!!l,[i,d]=A.useState(c?"values":"fields"),[u,m]=A.useState(""),[h,p]=A.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]:[]}),g=a.filter(C=>{var v;return c?!1:!((v=r==null?void 0:r.conditions)==null?void 0:v.some(N=>N.field.id===C.id))&&C.label.toLowerCase().includes(u.toLowerCase())}),b=C=>{p({...h,field:C}),d("values")},x=()=>{if(h.field&&h.selectedValues.length>0){const C={id:h.id,field:h.field,operator:"in",value:h.selectedValues};let D;if(c){const v=((r==null?void 0:r.conditions)||[]).map(N=>N.id===l.id?C:N);D={...r,conditions:v}}else{const v=(r==null?void 0:r.conditions)||[];D={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...v,C],groups:[]}}o(D),n(!1)}},j=()=>{if(!c||!l)return;const C=((r==null?void 0:r.conditions)||[]).filter(D=>D.id!==l.id);if(C.length>0){const D={...r,conditions:C};o(D)}else o(void 0);n(!1)},f=C=>{p({...h,selectedValues:C})},y=()=>{c&&l?(p({id:l.id,field:l.field,selectedValues:Array.isArray(l.value)?l.value:[l.value]}),d("values")):(p({id:s.v4(),field:null,selectedValues:[]}),d("fields")),m("")};return A.useEffect(()=>{t&&y()},[t,c,l]),e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsx(s.DialogHeader,{children:e.jsx(s.DialogTitle,{children:c?`Edit Filter: ${(E=h.field)==null?void 0:E.label}`:i==="fields"?"Select Field to Filter":`Select Values for ${(k=h.field)==null?void 0:k.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!c&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&i==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Current Filters:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.conditions.map(C=>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:[C.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(C.value)?`${C.value.length} values`:String(C.value)})]},C.id))})]}),i==="fields"&&!c?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search fields...",value:u,onChange:C=>m(C.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:g.map(C=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>b(C),children:[e.jsx(Rs,{dataType:s.getDataType(C.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:C.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[C.entityName,".",C.name]})]})]},C.id))}),g.length===0&&u&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',u,'"']}),g.length===0&&!u&&a.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(Rl,{field:h.field,selectedValues:h.selectedValues,onValuesChange:f,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:j,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:y,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:x,disabled:!h.field||h.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function Rl({field:t,selectedValues:n,onValuesChange:a,onBack:r}){const[l,o]=A.useState(""),{values:c,isLoading:i,isFetching:d}=Ml({field:t,searchQuery:l,limit:500}),u=l?c.filter(p=>String(p.value).toLowerCase().includes(l.toLowerCase())):c,m=p=>{const g=n.includes(p);a(g?n.filter(b=>b!==p):[...n,p])},h=()=>{n.length===u.length&&u.length>0?a([]):a(u.map(p=>p.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:p=>o(p.target.value),className:"pl-10"})]}),i||d?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx(s.Checkbox,{checked:n.length===u.length&&u.length>0,onCheckedChange:h}),e.jsxs(s.Label,{className:"text-sm",children:["Select All (",u.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:u.map(p=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>m(p.value),children:[e.jsx(s.Checkbox,{checked:n.includes(p.value),onCheckedChange:()=>m(p.value)}),e.jsx(cs,{className:"text-sm",children:p.label})]},p.id))})]})]})}function Ol({field:t,zone:n,index:a,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:o=!1,cardType:c}){var Fs,Ps,Bs;const{attributes:i,listeners:d,setNodeRef:u,transform:m,transition:h,isDragging:p}=s.useSortable({id:t.id}),g=s.useEditorStore(H=>H.card),{updateLabel:b,handleAggregationChange:x,handleDateFormatChange:j,handleGranularityChange:f,handleAliasTemplateChange:y,handleValueAliasesChange:E,removeField:k,handleKpiComparisonTypeChange:C,handleKpiShowTrendlineChange:D,handleKpiTrendlineWindowChange:v,handleKpiTrendlineGranularityChange:N,handleKpiTargetValueChange:S}=Ls(g),[F,I]=A.useState(!1),[P,T]=A.useState(!1),[w,L]=A.useState(null),[O,R]=A.useState(t.dateFormat||"YYYY-MM-DD"),[M,B]=A.useState(t.customFormat||""),[Y,_]=A.useState(!!t.customFormat),[Q,X]=A.useState(t.granularity||"day"),[q,W]=A.useState(t.aliasTemplate||""),[G,se]=A.useState(t.valueAliases||{}),[V,U]=A.useState((Fs=t.parameters)==null?void 0:Fs.filters),ee=H=>{H==="custom"?_(!0):(_(!1),R(H),n==="groupBy"&&j(a,H,""))},ae=H=>{B(H),n==="groupBy"&&j(a,"custom",H)},ie=H=>{var pe;X(H);const me=(pe=K(H)[0])==null?void 0:pe.value;me&&!Y&&(R(me),n==="groupBy"&&j(a,me,"")),n==="groupBy"&&f(a,H)},z=H=>{W(H),n==="metrics"&&y(a,H)},te=H=>{se(H),n==="metrics"&&E(a,H)},oe=H=>{b(n,a,H)},re=H=>{var ue;if(U(H),n==="metrics"){const me={...t,parameters:{...t.parameters,filters:H}},pe=[...((ue=g.config)==null?void 0:ue.metricColumns)||[]];pe[a]=me,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:pe})}T(!1)},J=()=>{k(n,a)},ce={transform:s.CSS.Transform.toString(m),transition:h},de=s.getDataType(t.dataType),fe=de==="date",$=c==="kpi",K=H=>{switch(H){case"day":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"custom",label:"Custom Format..."}];case"week":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"Week of MMM DD, YYYY",label:"Week of Jan 15, 2024"},{value:"Week of MMMM DD, YYYY",label:"Week of January 15, 2024"},{value:"YYYY-WW",label:"2024-W03 (YYYY-WW)"},{value:"custom",label:"Custom Format..."}];case"month":return[{value:"MMM YYYY",label:"Jan 2024 (MMM YYYY)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MM/YYYY",label:"01/2024 (MM/YYYY)"},{value:"YYYY MMM",label:"2024 Jan (YYYY MMM)"},{value:"custom",label:"Custom Format..."}];case"quarter":return[{value:"Q1 YYYY",label:"Q1 2024 (Q1 YYYY)"},{value:"YYYY Q1",label:"2024 Q1 (YYYY Q1)"},{value:"1st Quarter YYYY",label:"1st Quarter 2024"},{value:"YYYY-Q1",label:"2024-Q1 (YYYY-Q1)"},{value:"Quarter 1, YYYY",label:"Quarter 1, 2024"},{value:"custom",label:"Custom Format..."}];case"year":return[{value:"YYYY",label:"2024 (YYYY)"},{value:"YY",label:"24 (YY)"},{value:"custom",label:"Custom Format..."}];default:return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"custom",label:"Custom Format..."}]}},Z=K(Q),le=n!=="pivotBy",ne=fe&&n==="groupBy",je=!$&&fe&&n==="groupBy",xe=$&&fe&&n==="groupBy",We=$&&n==="metrics"&&((Ps=g.config)==null?void 0:Ps.comparisonType)==="target",Ke=n==="metrics",Ue=()=>e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:H=>{H.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}`}),Te=()=>le?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(we,{value:t.label??"",onSave:oe,placeholder:"Display label...",type:"text"})]}):null,he=()=>ne?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:Q,onValueChange:ie,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(H=>e.jsx(s.SelectItem,{className:"text-xs",value:H,children:s.toTitleCase(H)},H))})]})]}):null,Ht=()=>je?e.jsxs(e.Fragment,{children:[he(),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:Y?"custom":O,onValueChange:ee,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select date format..."})}),e.jsx(s.SelectContent,{children:Z.map(H=>e.jsx(s.SelectItem,{className:"text-xs",value:H.value,children:H.label},H.value))})]}),Y&&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:M,onChange:H=>{H.stopPropagation(),ae(H.target.value)},onClick:H=>H.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,Wt=()=>{var H,ue,me,pe,ke;return xe?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(s.Select,{value:((H=g.config)==null?void 0:H.comparisonType)||"none",onValueChange:C,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:"target",children:"Target Value"})]})]})]}),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:((ue=g.config)==null?void 0:ue.showTrendline)||!1,onCheckedChange:D})]})}),((me=g.config)==null?void 0:me.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:((pe=g.config)==null?void 0:pe.trendlineWindow)||30,onChange:Qe=>{const Zt=parseInt(Qe.target.value)||30;v(Zt)},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:((ke=g.config)==null?void 0:ke.trendlineGranularity)||"day",onValueChange:N,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"day",children:"Day"}),e.jsx(s.SelectItem,{value:"week",children:"Week"}),e.jsx(s.SelectItem,{value:"month",children:"Month"})]})]})]})]})]}):null},Kt=()=>{var H,ue;return We?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(we,{value:((H=g.config)==null?void 0:H.targetValue)!==void 0&&((ue=g.config)==null?void 0:ue.targetValue)!==null?String(g.config.targetValue):"",onSave:me=>{!isNaN(Number(me))&&me!==null?S(Number(me)):S(0)},placeholder:"Enter target value...",type:"text"})]}):null},Qt=()=>Ke?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:H=>{x(a,H)},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"}),(V==null?void 0:V.conditions)&&V.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:V.conditions.map(H=>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:()=>{L(H),T(!0)},children:[e.jsxs("span",{className:"font-medium",children:[H.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(H.value)?H.value.length===1?String(H.value[0]):H.value.length<=2?H.value.join(", "):`${H.value.slice(0,2).join(", ")} +${H.value.length-2}`:String(H.value)})}),Array.isArray(H.value)&&H.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 (",H.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:H.value.map((ue,me)=>e.jsx("div",{children:String(ue)},me))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:ue=>{var pe;ue.stopPropagation();const me=V.conditions.filter(ke=>ke.id!==H.id);if(me.length>0){const ke={...V,conditions:me};re(ke)}else if(U(void 0),n==="metrics"){const ke={...t,parameters:{...t.parameters,filters:void 0}},Qe=[...((pe=g.config)==null?void 0:pe.metricColumns)||[]];Qe[a]=ke,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:Qe})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},H.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{L(null),T(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(Vt,{column:t}),o&&e.jsxs(e.Fragment,{children:[e.jsx(Il,{aliasTemplate:q,onAliasTemplateChange:z}),e.jsx(Al,{valueAliases:G,onValueAliasesChange:te})]})]}):null,{columns:Jt=[]}=s.useColumns(),Xt=(V==null?void 0:V.conditions)&&V.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:u,style:ce,...i,...d,className:`group mx-auto flex w-full flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${p?"z-50 scale-95 opacity-50":"border-slate-200"} ${n==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(Rs,{dataType:de}),e.jsx(cs,{className:s.cn("w-[140px] flex-1 text-xs",Xt&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),n==="metrics"&&((Bs=V==null?void 0:V.conditions)==null?void 0:Bs.length)&&!F&&e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 text-xs",children:[e.jsx(s.Filter,{className:"h-3 w-3"}),e.jsx("span",{children:V.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:V.conditions.map(H=>e.jsxs("div",{children:[H.field.label,":"," ",Array.isArray(H.value)?`${H.value.length} values`:String(H.value)]},H.id))})})]})}),n!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:H=>{H.stopPropagation(),I(!F)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${F?"rotate-180":""}`})}),n==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:H=>{H.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const ue=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",ue),l(ue)},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:H=>{H.stopPropagation(),J()},children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]}),F&&e.jsxs("div",{className:"space-y-3",children:[Ue(),Te(),c==="kpi"&&he(),Ht(),Wt(),Kt(),Qt()]})]}),P&&e.jsx(Ll,{open:P,onOpenChange:H=>{T(H),H||L(null)},availableFields:Jt,existingFilters:V,editingCondition:w,onSave:H=>{var ue;if(H)re(H);else if(U(void 0),n==="metrics"){const me={...t,parameters:{...t.parameters,filters:void 0}},pe=[...((ue=g.config)==null?void 0:ue.metricColumns)||[]];pe[a]=me,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:pe})}L(null)}})]})}function Fl({concept:t}){const n=()=>{switch(t){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-100 text-xs font-medium dark:bg-blue-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/50 text-xs font-medium dark:bg-blue-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/30 text-xs font-medium dark:bg-blue-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/20 text-xs font-medium dark:bg-blue-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metrics = Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});default:return null}};return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(s.TooltipContent,{side:"right",align:"start",className:"p-3",children:n()})]})})}function Ze({zone:t,fields:n,label:a,placeholder:r,shouldShow:l,hasPivotColumns:o=!1}){const{isOver:c,setNodeRef:i}=s.useDroppable({id:t}),{updateSortByColumn:d}=s.useEditorActions(),u=s.useEditorStore(b=>b.card),m=s.useEditorStore(b=>b.card.type),h=n.length>0,p=(b,x)=>{var f;!((f=u.config)!=null&&f.sortByColumns)||u.config.sortByColumns.findIndex(y=>y.id===b)===-1||d(u.id,b,{direction:x})};if(t==="sortBy"&&l===!1)return null;const g=t!=="sortBy"&&m!=="kpi";return e.jsxs("div",{className:"mb-4 w-full",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:a}),g&&e.jsx(Fl,{concept:t})]}),e.jsx("div",{ref:i,className:`rounded-lg border-2 border-dashed p-1 transition-all ${c?"border-blue-500 bg-blue-50 dark:bg-blue-950":h?"border-blue-200 bg-blue-50/30 dark:border-blue-800 dark:bg-blue-950/30":"min-h-[60px] border-muted-foreground/20 bg-background"}`,children:n.length===0?e.jsx("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:r}):e.jsx(s.SortableContext,{items:n.map(b=>b.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:n.map((b,x)=>{const f=b.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(Ol,{field:b,zone:t,index:x,sortDirection:f,onSortDirectionChange:y=>p(b.id,y),hasPivotColumns:o,cardType:m})})},b.id)})})})})]})}const Xs=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],Pl=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function js({value:t,onChange:n,label:a}){const[r,l]=A.useState(!1),[o,c]=A.useState(!1),i=()=>{const d=Xs.find(u=>u.value===t);return d?d.color:t.startsWith("#")?t:Xs[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:r,onOpenChange:l,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"size-5 rounded border-2 border-input shadow-sm transition-all hover:scale-110 hover:border-gray-400",style:{backgroundColor:i()},"aria-label":`Change color for ${a}`})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"grid grid-cols-3 items-center justify-items-center gap-1",children:Pl.map(d=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",i()===d?"border-gray-900":"border-transparent"),style:{backgroundColor:d},onClick:()=>{n(d),l(!1)},children:e.jsx("span",{className:"sr-only",children:d})},d))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{c(!0),l(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a})]}),o&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>c(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Ot,{color:i(),onColorChange:d=>{n(d),c(!1)},onClose:()=>c(!1)})})]})]})}const es={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%
|
|
340
|
+
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 Bl(){var i,d,u,m,h,p,g,b,x,j;const t=s.useEditorStore(f=>f.card),{setCardPreferences:n}=s.useEditorActions(),a=((i=t.config)==null?void 0:i.metricColumns)||[],r=((d=t.config)==null?void 0:d.groupByColumns)||[];if(!(t.type==="kpi"&&(a.length>=2&&r.length===0||a.length>=1&&r.length>0)))return null;const o=((m=(u=t.preferences)==null?void 0:u.kpiVisualOptions)==null?void 0:m.metricComparison)||{},c=f=>{var E;const y={...t.preferences,kpiVisualOptions:{...(E=t.preferences)==null?void 0:E.kpiVisualOptions,metricComparison:{...o,...f}}};n(y)};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(ba,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[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=>c({enabled:f,...f&&!o.calculationType?{calculationType:"difference"}:{}})})]}),o.enabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(s.Select,{value:o.calculationType||"difference",onValueChange:f=>c({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(es).map(([f,y])=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:y.label},f))})]}),(()=>{var y,E,k;const f=o.calculationType||"difference";return e.jsxs("div",{className:"space-y-2 rounded-md bg-muted/50 p-2 text-xs",children:[e.jsx("p",{className:"text-muted-foreground",children:(y=es[f])==null?void 0:y.description}),e.jsxs("div",{className:"text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Formula:"})," ",e.jsx("code",{className:"rounded bg-background px-1 py-0.5 text-[10px]",children:(E=es[f])==null?void 0:E.formula})]}),e.jsxs("div",{className:"border-t pt-1 italic text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",(k=es[f])==null?void 0:k.example]})]})})()]}),e.jsx(As,{formatOptions:o.formatOptions||{},onFormatOptionsChange:f=>c({formatOptions:f}),showTitle:!0,title:"COMPARISON FORMAT"}),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"}),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||"left",onValueChange:f=>c({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:"top",className:"text-xs",children:"Top"}),e.jsx(s.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(s.SelectItem,{value:"right",className:"text-xs",children:"Right"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-arrow",checked:o.showArrow!==!1,onCheckedChange:f=>c({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=>c({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(js,{value:((h=o.colorConfig)==null?void 0:h.increase)||"green",onChange:f=>c({colorConfig:{...o.colorConfig,increase:f}}),label:"Primary > Secondary"}),e.jsx(js,{value:((p=o.colorConfig)==null?void 0:p.decrease)||"red",onChange:f=>c({colorConfig:{...o.colorConfig,decrease:f}}),label:"Primary < Secondary"}),e.jsx(js,{value:((g=o.colorConfig)==null?void 0:g.noChange)||"neutral",onChange:f=>c({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=>c({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:((b=o.conditionalLabels)==null?void 0:b.increase)??"Increase",onChange:f=>c({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:((x=o.conditionalLabels)==null?void 0:x.decrease)??"Decrease",onChange:f=>c({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:((j=o.conditionalLabels)==null?void 0:j.noChange)??"No change",onChange:f=>c({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:"Name"}),e.jsx(s.Input,{id:"label-name",type:"text",value:o.labelName??"",onChange:f=>c({labelName:f.target.value}),placeholder:"e.g. Versus, Compared to",className:"h-7 text-xs"})]})]})]})]})]})}function zl(){var l,o;const t=s.useEditorStore(c=>c.card),{setCardPreferences:n}=s.useEditorActions();if(t.type!=="kpi")return null;const a=((o=(l=t.preferences)==null?void 0:l.kpiVisualOptions)==null?void 0:o.formatOptions)||{},r=c=>{var d;const i={...t.preferences,kpiVisualOptions:{...(d=t.preferences)==null?void 0:d.kpiVisualOptions,formatOptions:c}};n(i)};return e.jsxs(s.AccordionItem,{value:"kpi-format",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(De,{className:"h-4 w-4"}),e.jsx("span",{children:"Number Format"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:e.jsx(As,{formatOptions:a,onFormatOptionsChange:r,showTitle:!1})})]})}function _l({groupByFields:t,pivotByFields:n,metricsFields:a,sortByFields:r}){const l=s.useEditorStore(b=>{var x;return((x=b.card.customCardPreferences)==null?void 0:x.url)&&b.card.type==="custom"}),o=s.useEditorStore(b=>b.card),c=o==null?void 0:o.type,i=t.length>0||a.length>0,d=c!=="kpi",u=c!=="kpi"&&i,m=["pie","doughnut","polar","funnel","aggregateTable"].includes(c),h=d&&!m,p=()=>c==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},g=()=>c==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs(s.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full",children:[e.jsxs(s.AccordionItem,{value:"fields",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.List,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsx(Ze,{zone:"groupBy",fields:t,label:p().label,placeholder:p().placeholder}),h&&e.jsx(Ze,{zone:"pivotBy",fields:n,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(Ze,{zone:"metrics",fields:a,label:g().label,placeholder:g().placeholder,hasPivotColumns:n.length>0}),u&&e.jsx(Ze,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})]}),!l&&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.Settings,{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(zl,{}),e.jsx(Bl,{}),e.jsx(Ft,{}),e.jsx(Pt,{}),e.jsx(Bt,{}),e.jsx(zt,{})]})})]})]})}function Vl({selectedChart:t,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:o}){const[c,i]=A.useState(!1);s.useEditorStore(x=>x.showAIDialog);const d=s.useEditorStore(x=>x.card),{isLoading:u,isFetching:m,refetch:h}=s.useDashboardCardQuery(d),p=a.length>0||r.length>0||l.length>0,{setShowAIDialog:g}=s.useEditorActions(),{data:b}=s.useDashboardCardQuery(d);return A.useEffect(()=>{m||i(!1)},[m]),e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col border-x border-border",children:[e.jsxs("div",{className:"space-y-4 px-6 pt-4",children:[e.jsx(El,{selectedChart:t,onChartChange:n}),e.jsx(Dl,{selectedChart:t,onChartChange:n})]}),e.jsx("div",{className:s.cn("flex justify-end gap-2 px-6 py-6"),children:e.jsxs("div",{className:s.cn("invisible flex gap-2",{visible:p||b}),children:[e.jsx(os,{}),e.jsx(s.Button,{disabled:u||m,onClick:()=>{i(!0),h()},className:"h-8 shrink-0",size:"sm",variant:"outline",children:c?e.jsx(s.LoaderCircle,{className:"h-4 w-4 animate-spin"}):e.jsx(s.RefreshCcw,{className:"h-4 w-4"})})]})}),e.jsxs(s.ScrollArea,{className:"w-full flex-1 basis-0 px-6 pb-6",children:[e.jsx(_l,{groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:o}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Ul({initialFilters:t,availableFields:n}={}){const[a,r]=A.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(C=>C.card.dataSource);const{columns:l,isLoading:o}=s.useColumns(),i=n||l||[],d={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=C=>{const D=v=>{if(v.id===C){const N=i[0]||d,S=s.getDataType(N.dataType)==="date";return{...v,conditions:[...v.conditions,{id:`condition-${Date.now()}`,field:N,operator:S?"between":"=",value:S?[]:""}]}}return{...v,groups:v.groups.map(D)}};r(D(a))},m=C=>{const D=v=>{if(v.id===C){const N=i[0]||d,S=s.getDataType(N.dataType)==="date";return{...v,groups:[...v.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:N,operator:S?"between":"=",value:S?[]:""}],groups:[]}]}}return{...v,groups:v.groups.map(D)}};r(D(a))},h=(C,D)=>{const v=N=>N.id===C?{...N,conditions:N.conditions.filter(S=>S.id!==D)}:{...N,groups:N.groups.map(v)};r(v(a))},p=(C,D)=>{const v=N=>N.id===C?{...N,groups:N.groups.filter(S=>S.id!==D)}:{...N,groups:N.groups.map(v)};r(v(a))},g=(C,D,v,N)=>{if(v==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const S=F=>F.id===C?{...F,conditions:F.conditions.map(I=>I.id===D?{...I,[v]:N}:I)}:{...F,groups:F.groups.map(S)};r(S(a))},b=(C,D,v)=>{const N=S=>S.id===C?{...S,conditions:S.conditions.map(F=>F.id===D?{...F,...v}:F)}:{...S,groups:S.groups.map(N)};r(N(a))},x=(C,D)=>{const v=N=>N.id===C?{...N,logicalOperator:D}:{...N,groups:N.groups.map(v)};r(v(a))},j=(C,D)=>{const v=N=>N.id===C?{...N,negate:D}:{...N,groups:N.groups.map(v)};r(v(a))},f=(C,D,v)=>{const N=S=>S.id===C?{...S,conditions:s.arrayMove(S.conditions,D,v)}:{...S,groups:S.groups.map(N)};r(N(a))},y=(C,D,v)=>{const N=S=>S.id===C?{...S,groups:s.arrayMove(S.groups,D,v)}:{...S,groups:S.groups.map(N)};r(N(a))},E=C=>{if(!C||C.conditions.length===0&&C.groups.length===0)return"-- No filters defined";const D=N=>{let S="";typeof N.field=="object"?S=N.field.entityName?`${N.field.entityName}.${N.field.name}`:N.field.name:S=String(N.field);const F=N.operator;let I=N.value;if(N.field.dataType==="string"&&!["in","not in"].includes(N.operator))typeof I=="string"?I=`'${I}'`:Array.isArray(I)&&(I=`'${I.join(", ")}'`);else if(N.field.dataType==="date"||N.field.dataType==="datetime"||N.field.dataType==="timestamp")if(N.operator==="between"&&Array.isArray(I)&&I.length===2){const P=I[0]?`'${I[0]}'`:"NULL",T=I[1]?`'${I[1]}'`:"NULL";return`${S} BETWEEN ${P} AND ${T}`}else if((N.operator==="in"||N.operator==="not in")&&Array.isArray(I)){const P=I.map(T=>T?`'${T}'`:"NULL").join(", ");return`${S} ${F} (${P})`}else typeof I=="string"||I instanceof Date?I=`'${I}'`:Array.isArray(I)&&I.length>0&&(I=`'${I[0]}'`);else if(["in","not in"].includes(N.operator)){let P=[];Array.isArray(I)?P=I.map(T=>typeof T=="string"?`'${T}'`:String(T)):typeof I=="string"?P=I.split(",").map(T=>{const w=T.trim();return N.field.dataType==="string"?`'${w}'`:w}):typeof I=="number"&&(P=[String(I)]),I=`(${P.join(", ")})`}switch(F){case"contains":return typeof I=="string"?`${S} LIKE '%${I.replace(/'/g,"")}'`:`${S} LIKE '%${String(I)}'`;case"startsWith":return typeof I=="string"?`${S} LIKE '${I.replace(/'/g,"")}%'`:`${S} LIKE '${String(I)}%'`;case"endsWith":return typeof I=="string"?`${S} LIKE '%${I.replace(/'/g,"")}'`:`${S} LIKE '%${String(I)}'`;case"isNull":return`${S} IS NULL`;case"isNotNull":return`${S} IS NOT NULL`;default:return`${S} ${F} ${I}`}},v=N=>{const S=N.conditions.map(D),F=N.groups.map(w=>v(w)),I=[...S,...F].filter(Boolean);if(I.length===0)return"";const P=I.join(` ${N.logicalOperator} `),T=I.length>1?`(${P})`:P;return N.negate?`NOT ${T}`:T};return v(C)},k=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:i,isLoading:o,addCondition:u,addGroup:m,removeCondition:h,removeGroup:p,updateCondition:g,updateConditionFields:b,updateGroupOperator:x,updateGroupNegate:j,reorderConditions:f,reorderGroups:y,generateSQLPreview:E,hasAnyFilters:k}}function Gl({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",n),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const Yl=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"})}},$l=t=>{if(t.qualifiedEntityName){const n=t.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function ql({value:t,onValueChange:n,availableFields:a,placeholder:r="Select field",className:l="w-64"}){const[o,c]=A.useState(!1),i=A.useMemo(()=>{const d={};return a.forEach(u=>{const m=$l(u);d[m]||(d[m]={}),d[m][u.entityId]||(d[m][u.entityId]=[]),d[m][u.entityId].push(u)}),d},[a]);return e.jsxs(s.Popover,{modal:!0,open:o,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:s.cn("justify-between",!t&&"text-muted-foreground",l),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Gl,{children:[t.entityName,".",t.name]})}):r,e.jsx(s.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(s.CommandEmpty,{children:"No fields found."}),e.jsx(s.CommandList,{className:"max-h-80",children:Object.entries(i).map(([d,u])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),d]}),children:Object.entries(u).map(([m,h])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[Yl(h[0].entityType),e.jsx("span",{children:h[0].entityName})]}),h.map((p,g)=>e.jsxs(s.CommandItem,{value:p.id,onSelect:()=>{n(p),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)===p.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:p.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:p.description&&e.jsx("span",{children:p.description})})]})]},p.id+g))]},`${d}-${m}`))},d))})]})})]})}function Os(t){var x;const n=s.useEditorStore(j=>j.card),{authToken:a,tokenProps:r}=s.useSemaphorContext(),l=s.useEditorStore(j=>j.card.config),o=l==null?void 0:l.joinPlan,c={...t,alias:t.name,label:"value",role:"groupby"},i={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},d={...c,role:"sortby",direction:"asc"},u={joinPlan:o,groupByColumns:[c],metricColumns:[i],sortByColumns:[d]},m=((x=n.dataSource)==null?void 0:x.connectionId)||n.connectionId,{data:h,isPending:p,error:g}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular(`${r.apiServiceUrl}/v1/query`,(a==null?void 0:a.accessToken)||"",{connection_id:m,cardConfig:u,cardDataSource:n.dataSource})}catch(j){console.log(t),console.error("error",j)}},enabled:!!m,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((h==null?void 0:h.records)||[]).map(j=>({label:j.value||"BLANK",value:j.value||"BLANK",count:(j==null?void 0:j.count)||0})),isPending:p,error:g}}function Hl({field:t,selected:n,onChange:a,placeholder:r="Select items...",className:l}){const[o,c]=Ee.useState(!1),{filterValues:i}=Os(t),d=m=>{a(n.filter(h=>h!==m))},u=m=>{n.includes(m)?a(n.filter(h=>h!==m)):a([...n,m])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open:o,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:n.length>0?n.map(m=>{const h=i.find(p=>p.value===m);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[h==null?void 0:h.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:p=>{p.key==="Enter"&&d(m)},onMouseDown:p=>{p.preventDefault(),p.stopPropagation()},onClick:p=>{p.stopPropagation(),d(m)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},m)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No results found."}),e.jsx(s.CommandGroup,{children:i.map((m,h)=>e.jsxs(s.CommandItem,{onSelect:()=>u(m.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",n.includes(m.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.count})]})]},m.value+h))})]})]})})]})})}function Wl({field:t,value:n,onChange:a,placeholder:r="Select value...",className:l}){const{filterValues:o,isPending:c,error:i}=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..."]}):i?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:n,onValueChange:a,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:n})}),e.jsx(s.SelectContent,{children:o.map((d,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+u))})]})}function Kl({value:t,operator:n,onChange:a,className:r}){var d;const{tokenProps:l}=s.useSemaphorContext(),o=(d=l==null?void 0:l.params)==null?void 0:d.timeZone,c=A.useMemo(()=>{if(t){if(n==="between"||n==="not between"){if(Array.isArray(t)&&t.length===2){const u=t[0]?new Date(t[0]):void 0,m=t[1]?new Date(t[1]):void 0;if(u&&m)return{from:u,to:m}}}else if(n==="="||n==="!="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:u}}}else if(n===">"||n===">="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:void 0}}}else if(n==="<"||n==="<="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:void 0,to:u}}}else if((n==="in"||n==="not in")&&Array.isArray(t)&&t.length>0){const u=new Date(t[0]),m=t.length>1?new Date(t[t.length-1]):u;if(!isNaN(u.getTime()))return{from:u,to:m}}}},[t,n]),i=u=>{if(!u){a(void 0);return}if(u.from&&u.to)a([u.from.toISOString(),u.to.toISOString()]);else if(u.from){const m=new Date(u.from);m.setHours(23,59,59,999),a([u.from.toISOString(),m.toISOString()])}else if(u.to){const m=new Date(u.to);m.setHours(0,0,0,0),a([m.toISOString(),u.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:c,onChange:i,timezone:o,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const Ql=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Jl=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Xl=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],Zl=["=","!=","isNull","isNotNull"],eo=["between","isNull","isNotNull"],so={"=":"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"};function Zs(t){return so[t]||s.titleCase(t)}function to(t){switch(t){case"string":return Jl;case"number":return Xl;case"boolean":return Zl;case"date":return eo;default:return Ql}}function Gt({condition:t,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:o,onUpdateGroupOperator:c,availableFields:i,updateConditionFields:d}){const{attributes:u,listeners:m,setNodeRef:h,transform:p,transition:g,isDragging:b}=s.useSortable({id:t.id}),{isPending:x,error:j}=Os(t.field),f={transform:s.CSS.Transform.toString(p),transition:g};return e.jsxs("div",{ref:h,style:f,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${b?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...m,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),n>0&&e.jsxs(s.Select,{value:r,onValueChange:y=>c(a,y),children:[e.jsx(s.SelectTrigger,{className:"w-24",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),n===0&&e.jsx("div",{className:"w-24"}),e.jsx(ql,{value:t.field,onValueChange:y=>{const E=y,k=s.getDataType(E.dataType)==="date";d(a,t.id,{field:E,value:"",operator:k?"between":"="})},availableFields:i,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:y=>{y==="in"||y==="not in"?d(a,t.id,{operator:y,value:[]}):y==="isNull"||y==="isNotNull"?d(a,t.id,{operator:y,value:null}):d(a,t.id,{operator:y,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?Zs(t.operator):""})}),e.jsx(s.SelectContent,{children:to(s.getDataType(t.field.dataType)).map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y,children:Zs(y)},y))})]}),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"?x?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..."]}):j?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(Hl,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(y=>typeof y=="string")?t.value:[],onChange:y=>d(a,t.id,{value:y}),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:y=>d(a,t.id,{value:y.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(Wl,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:y=>d(a,t.id,{value:y}),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:y=>d(a,t.id,{value:y==="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(Kl,{value:t.value,operator:t.operator,onChange:y=>d(a,t.id,{value:y}),className:"flex-1"}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:y=>l(a,t.id,"value",y.target.value),className:"flex-1",placeholder:t.operator==="in"||t.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>o(a,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function ao({group:t,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:o,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onReorderConditions:u,onReorderGroups:m,onAddCondition:h,onAddGroup:p,availableFields:g,renderFilterGroup:b,updateConditionFields:x}){const{attributes:j,listeners:f,setNodeRef:y,transform:E,transition:k,isDragging:C}=s.useSortable({id:t.id}),D={transform:s.CSS.Transform.toString(E),transition:k},v=S=>{const{active:F,over:I}=S;if(I&&F.id!==I.id){const P=t.conditions.findIndex(w=>w.id===F.id),T=t.conditions.findIndex(w=>w.id===I.id);P!==-1&&T!==-1&&u(t.id,P,T)}},N=S=>{const{active:F,over:I}=S;if(I&&F.id!==I.id&&a){const P=t.groups.findIndex(w=>w.id===F.id),T=t.groups.findIndex(w=>w.id===I.id);P!==-1&&T!==-1&&m(a,P,T)}};return e.jsxs("div",{ref:y,style:D,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${C?"z-50 opacity-50":""}`,children:[n>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...j,...f,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:S=>r(t.id,S),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>a&&o(a,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${n>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:v,children:e.jsx(s.SortableContext,{items:t.conditions.map(S=>S.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((S,F)=>e.jsx(Gt,{condition:S,index:F,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:g,updateConditionFields:x},S.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:N,children:e.jsx(s.SortableContext,{items:t.groups.map(S=>S.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(S=>b(S,n+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>p(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function no({filters:t,availableFields:n,onSave:a,onClearAll:r,onCancel:l}){const{currentFilters:o,availableFields:c,isLoading:i,addCondition:d,addGroup:u,removeCondition:m,removeGroup:h,updateCondition:p,updateConditionFields:g,updateGroupOperator:b,updateGroupNegate:x,reorderConditions:j,reorderGroups:f,generateSQLPreview:y,hasAnyFilters:E,setCurrentFilters:k}=Ul({initialFilters:t,availableFields:n}),C=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[D,v]=A.useState(!1),N=(I,P,T)=>{const w=L=>L.id===I?{...L,conditions:L.conditions.map(O=>O.id===P?{...O,field:T,dataType:T.dataType}:O)}:{...L,groups:L.groups.map(w)};k(w(o))},S=(I,P=0,T)=>P===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:C,collisionDetection:s.closestCenter,onDragEnd:w=>{const{active:L,over:O}=w;if(O&&L.id!==O.id){const R=I.conditions.findIndex(B=>B.id===L.id),M=I.conditions.findIndex(B=>B.id===O.id);R!==-1&&M!==-1&&j(I.id,R,M)}},children:e.jsx(s.SortableContext,{items:I.conditions.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:I.conditions.map((w,L)=>e.jsx(Gt,{condition:w,index:L,groupId:I.id,groupLogicalOperator:I.logicalOperator,onUpdateCondition:p,onUpdateField:N,onRemoveCondition:m,onUpdateGroupOperator:b,availableFields:c,updateConditionFields:g},w.id))})}),e.jsx(s.DndContext,{sensors:C,collisionDetection:s.closestCenter,onDragEnd:w=>{const{active:L,over:O}=w;if(O&&L.id!==O.id){const R=I.groups.findIndex(B=>B.id===L.id),M=I.groups.findIndex(B=>B.id===O.id);R!==-1&&M!==-1&&f(I.id,R,M)}},children:e.jsx(s.SortableContext,{items:I.groups.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:I.groups.map(w=>S(w,P+1,I.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(I.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),D&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(I.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},I.id):e.jsx(ao,{group:I,depth:P,parentGroupId:T,onUpdateGroupOperator:b,onUpdateGroupNegate:x,onRemoveGroup:h,onUpdateCondition:p,onUpdateField:N,onRemoveCondition:m,onReorderConditions:j,onReorderGroups:f,onAddCondition:d,onAddGroup:u,availableFields:c,renderFilterGroup:S,updateConditionFields:g},I.id),F=s.getFilterCount(t);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Card,{children:e.jsx(s.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[i?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):S(o),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{id:"advanced-mode",checked:D,onCheckedChange:I=>v(I)}),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)"})]})}),E&&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:y(o)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:l,children:"Cancel"}),F>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>a(E?o:null),children:"Apply Filters"})]})]})}function ro({cardId:t,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:l,isOpen:o,onOpenChange:c}){const i=u=>{a(t,u),c(!1)},d=()=>{r(t),c(!1)};return e.jsxs(s.Dialog,{modal:!1,open:o,onOpenChange:c,children:[o&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:u=>{u.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Card Filters"}),e.jsx(s.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(no,{filters:n,availableFields:l,onSave:i,onCancel:()=>c(!1),onClearAll:d})]})]})}function lo({activeCardId:t,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var g;const[l,o]=A.useState(null),c=s.useEditorStore(b=>b.card),i=(g=c==null?void 0:c.config)==null?void 0:g.joinPlan,d=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")],u=A.useCallback(b=>b.startsWith("card-")?null:b.startsWith("source-")||n.find(x=>x.id===b)?"source":a("groupBy").find(x=>x.id===b)?"groupBy":a("metrics").find(x=>x.id===b)?"metrics":a("pivotBy").find(x=>x.id===b)?"pivotBy":a("sortBy").find(x=>x.id===b)?"sortBy":null,[n,a]),m=A.useCallback(b=>{o(b.active.id)},[]),h=A.useCallback(b=>{const{active:x,over:j}=b;if(!j||!t){o(null);return}const f=x.id,y=j.id,E=u(f),k=u(y)||y;if(k==="sortBy"){if(E==="source"){const C=n.find(v=>v.id===f);if(!C){o(null);return}if(!(a("groupBy").some(v=>v.name===C.name&&v.qualifiedEntityName===C.qualifiedEntityName)||a("metrics").some(v=>v.name===C.name&&v.qualifiedEntityName===C.qualifiedEntityName))){o(null);return}}else if(E==="pivotBy"){o(null);return}else if(E!=="groupBy"&&E!=="metrics"&&E!=="sortBy"){o(null);return}}if(E==="source"&&k==="sortBy"){const C=[...n].find(N=>N.id===f);if(!C){o(null);return}const D=a("sortBy");if(s.fieldAlreadyExists(C,D)){o(null);return}const v=s.getNewField(C,"sortBy",D);o(null),r("sortBy",[...D,v]);return}if(E==="source"&&k!=="source"&&k!=="sortBy"){const C=[...n].find(S=>S.id===f);if(!C){o(null);return}const D=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")];if(D.length>0){const S=D[0].qualifiedEntityName;if(!S){o(null);return}if(S!==C.qualifiedEntityName&&C.qualifiedEntityName)if(i){if(!s.areEntitiesJoined(S,C.qualifiedEntityName,i)){s.showJoinRequiredNotification(),o(null);return}}else{s.showJoinRequiredNotification(),o(null);return}}const v=a(k);if(s.fieldAlreadyExists(C,v)){o(null);return}const N=s.getNewField(C,k,v);o(null),r(k,[...v,N]);return}if(E&&k&&E!=="source"&&k!=="source"&&E!==k){const C=a(E),D=a(k),v=C.find(F=>F.id===f);if(!v){o(null);return}const N=s.getNewField(v,k,D);if(o(null),k==="sortBy"){s.fieldAlreadyExists(v,D)||r(k,[...D,N]);return}const S=C.filter(F=>F.id!==f);r(E,S),r(k,[...D,N]);return}if(E&&k&&E===k&&E!=="source"){const C=a(E),D=C.findIndex(N=>N.id===f),v=C.findIndex(N=>N.id===y);if(D!==v){const N=s.arrayMove(C,D,v);r(E,N)}}o(null)},[t,n,a,r,u,i]),p=l?d.find(b=>b.id===l):null;return{activeId:l,activeField:p,handleDragStart:m,handleDragEnd:h}}function oo({dashboardFilterCount:t=0,cardFilterCount:n=0,clickFilterCount:a=0,onClick:r,className:l,showIcon:o=!0}){const c=t+n+a,i=c>0,d=t>0,u=n>0,m=a>0,h=e.jsxs(e.Fragment,{children:[o&&e.jsx(s.Filter,{className:"h-3.5 w-3.5"}),i&&e.jsx("span",{className:"font-medium",children:c})]}),p=e.jsx(s.Button,{variant:i?"secondary":"outline",size:"sm",onClick:r,className:s.cn("h-8 gap-1.5 transition-all",l),children:h});return i?e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:200,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:p}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"p-2 text-xs",children:e.jsxs("div",{className:"space-y-1.5",children:[d&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-purple-500"}),e.jsxs("span",{children:[t," Dashboard filter",t!==1?"s":""]})]}),u&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-blue-500"}),e.jsxs("span",{children:[n," Card filter",n!==1?"s":""]})]}),m&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-gray-500"}),e.jsxs("span",{children:[a," Click filter",a!==1?"s":""]})]})]})})]})}):p}function io({onAdvancedToggle:t,onDebugToggle:n,onAccept:a}){const{currentUser:r}=s.useCurrentUserInfo();r==null||r.role;const[l,o]=A.useState(!1),c=s.useEditorStore(f=>f.isDevMode),i=s.useEditorStore(f=>f.card),d=s.useEditorStore(f=>f.card.dataSource);s.isExplorerCard(i);const{config:u}=A.useContext(s.SemaphorContext).tokenProps,m=(u==null?void 0:u.showAdvancedMode)!==!1,{setIsDevMode:h}=s.useEditorActions(),p=s.useEditorStore(f=>f.showAIDialog),g=s.useEditorStore(f=>f.frame),b=s.useManagementStore(f=>f.selectedVisual),x=(b==null?void 0:b.id)===(g==null?void 0:g.id),{setShowAIDialog:j}=s.useEditorActions();return e.jsxs("div",{className:s.cn("flex items-center justify-between px-6 py-3",p&&"justify-end",!m&&"justify-end"),children:[m&&t&&!p&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{className:s.cn("",{}),checked:c,onCheckedChange:()=>h(!c),id:"advanced-mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium",children:"Advanced Mode"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[!p&&e.jsxs(s.Button,{onClick:()=>j(!p),variant:"outline",className:"h-8",size:"sm",children:[e.jsx(s.Sparkles,{className:"mr-2 size-4"}),"AI"]}),e.jsx(Es,{}),a&&!x&&e.jsx(ks,{variant:"default"}),x&&e.jsx(Qn,{}),n&&s.isDevEnv]}),l&&e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(d==null?void 0:d.selectedEntities)||[],open:l,onOpenChange:o,dataSource:d||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function co({activeView:t,onViewChange:n}){const a=s.useEditorStore(c=>c.card),{config:r}=A.useContext(s.SemaphorContext).tokenProps,l=(r==null?void 0:r.showInfoTab)!==!1,{errorMessage:o}=s.useDashboardCardQuery(a);return e.jsx(s.Tabs,{value:t,onValueChange:c=>n(c),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-1 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),a.type!=="kpi"&&l&&e.jsx(s.TabsTrigger,{value:"info",className:s.cn("rounded-md transition data-[state=active]:bg-muted",o&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:o?"Error":"Info"})]})})}const uo=[{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 mo(){var d,u;const t=s.useEditorStore(m=>m.card),{updateRowLimit:n}=s.useEditorActions(),[a,r]=A.useState(!1),[l,o]=A.useState(""),c=m=>{if(m==="custom"){r(!0);return}r(!1),n(t.id,parseInt(m))},i=m=>{const h=m.target.value;o(h),h&&!isNaN(parseInt(h))&&n(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:a?e.jsx(s.Input,{type:"number",value:l,onChange:i,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(d=t.config)==null?void 0:d.rowLimit)==null?void 0:u.toString())||"100",onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(s.SelectValue,{placeholder:"Select limit"})}),e.jsx(s.SelectContent,{children:uo.map(m=>e.jsx(s.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function ho({isOpen:t,onClose:n}){const a=dt(n,{enabled:t}),r=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.url)||""}),l=s.useEditorStore(m=>m.card),o=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.pluginChartType)||""}),c=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.settings)||{}}),{data:i}=s.useDashboardCardQuery(l),{getCard:d}=s.useCustomVisual(r),u=A.useMemo(()=>!r||r.trim()===""?null:d("Chart Settings"),[d,r]);return e.jsx("div",{ref:a,className:s.cn("absolute right-0 top-0 z-40 h-full w-[350px] border-l bg-background shadow-lg transition-transform duration-300",t?"translate-x-0":"translate-x-full"),style:{willChange:"transform"},tabIndex:t?0:-1,"aria-hidden":!t,children:e.jsxs("div",{className:"flex h-full flex-col p-4 px-5 pr-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Chart Settings"}),e.jsx(s.IconButton,{"aria-label":"Hide Chart Settings",tooltip:"Hide",onClick:n,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:u&&e.jsx(A.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(i==null?void 0:i.records)||[],chartType:o,settings:c})})})]})})}function xo(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),{currentUser:a}=s.useCurrentUserInfo(),r=s.useMutation({mutationFn:async l=>{if(!(t!=null&&t.accessToken))throw new Error("No authentication token available");const c=`${n.apiServiceUrl||""}/v1/feedback`,i={...l,user:a,tokenContext:n},d=await s.postRequestRegular(c,t.accessToken,i,"POST");if(!d||!d.success)throw new Error((d==null?void 0:d.error)||"Failed to send feedback");return d},onSuccess:l=>{s.ue.success(`Feedback sent successfully! Issue: ${l.issueNumber}`,{duration:5e3})},onError:l=>{console.error("Feedback submission error:",l),s.ue.error("Failed to send feedback. Please try again later.",{duration:5e3})}});return{sendFeedback:r.mutate,sendFeedbackAsync:r.mutateAsync,isLoading:r.isPending,isSuccess:r.isSuccess,isError:r.isError,error:r.error,data:r.data,reset:r.reset}}function po(t,n,a){return{category:t,userMessage:a,systemState:n,metadata:{url:window.location.href,userAgent:navigator.userAgent,timestamp:new Date().toISOString(),viewport:`${window.innerWidth}x${window.innerHeight}`}}}function fo({open:t,onOpenChange:n,feedbackData:a}){var x,j,f,y,E,k;const[r,l]=A.useState(""),[o,c]=A.useState(!1),{sendFeedback:i,isLoading:d,isSuccess:u,data:m,reset:h}=xo(),p=()=>{const C={...a,userMessage:r.trim()||void 0};i(C)},g=()=>{l(""),c(!1),h(),n(!1)},b={category:a.category,error:{message:(x=a.systemState)==null?void 0:x.errorMessage,sql:(j=a.systemState)==null?void 0:j.generatedSql,errorSql:(f=a.systemState)==null?void 0:f.errorSql},cardConfig:(y=a.systemState)==null?void 0:y.cardConfig,dataSource:(E=a.systemState)==null?void 0:E.dataSource,filters:(k=a.systemState)==null?void 0:k.dashboardFilters,metadata:a.metadata};return e.jsx(s.Dialog,{open:t,onOpenChange:g,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:u?"Feedback Sent Successfully":"Report Query Generation Issue"}),e.jsx(s.DialogDescription,{children:u?`Your feedback has been submitted with issue number: ${m==null?void 0:m.issueNumber}`:"Help us improve by reporting this query generation issue. Your feedback will be sent to our support team."})]}),!u&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"message",children:"Additional Information (Optional)"}),e.jsx(s.Textarea,{id:"message",placeholder:"Please describe what you were trying to do when this error occurred...",value:r,onChange:C=>l(C.target.value),className:"min-h-[100px] resize-none ring-inset focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-0",disabled:d})]}),e.jsxs(s.Collapsible,{open:o,onOpenChange:c,children:[e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",className:"flex w-full items-center justify-between p-2 hover:bg-muted",children:[e.jsx("span",{className:"text-sm font-medium",children:"View data to be sent"}),o?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronRight,{className:"h-4 w-4"})]})}),e.jsx(s.CollapsibleContent,{children:e.jsx(s.ScrollArea,{className:"h-[300px] w-full rounded-md border bg-muted/50 p-4",children:e.jsx("div",{className:"text-xs",children:e.jsx(s.CodeHighlighter,{code:JSON.stringify(b,null,2),language:"json"})})})})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:g,disabled:d,children:"Cancel"}),e.jsx(s.Button,{onClick:p,disabled:d,className:"min-w-[100px]",children:d?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Sending..."]}):"Send Feedback"})]})]}),u&&e.jsxs("div",{className:"flex flex-col items-center space-y-4 py-6",children:[e.jsx(da,{className:"h-12 w-12 text-green-600"}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-lg font-medium",children:"Thank you for your feedback!"}),e.jsxs("p",{className:"mt-2 text-sm text-muted-foreground",children:["Issue Number:"," ",e.jsx("span",{className:"font-mono font-medium",children:m==null?void 0:m.issueNumber})]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Our support team will review your feedback and take appropriate action."})]}),e.jsx(s.Button,{onClick:g,className:"mt-4",children:"Close"})]})]})})}var Yt=(t=>(t.QUERY_GENERATION="query-generation",t))(Yt||{});function go({activeView:t,onViewChange:n,showDebug:a,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:d,activeCard:u,columns:m,columnsLoading:h,columnsError:p}){var V;const g=s.useEditorStore(U=>U.card),b=s.useDashboardStore(U=>U.filterValues),x=(b==null?void 0:b.length)||0,{updateCardConfig:j,setCard:f,updateCardInFrame:y,setCardId:E}=s.useEditorActions(),{updateCardId:k}=s.useDashboardActions(),[C,D]=A.useState(null),v=s.useEditorStore(U=>U.showAIDialog),[N,S]=A.useState(!1),[F,I]=A.useState(!1),[P,T]=A.useState(null),{isConsoleMode:w}=s.useDashboardPreferences(),{config:L}=A.useContext(s.SemaphorContext).tokenProps,O=(L==null?void 0:L.showInfoTab)!==!1,R=s.useEditorStore(U=>{var ee;return((ee=U.card.customCardPreferences)==null?void 0:ee.url)&&U.card.type==="custom"}),{data:M,errorMessage:B,isLoading:Y,isFetching:_,errorSql:Q,pagination:X}=s.useDashboardCardQuery(u),q=(U,ee)=>{const ae={...u,paginationConfig:{page:U+1,pageSize:ee}};f(ae),y(ae)};function W(){return e.jsx("div",{className:"border-b border-border bg-background p-4",children:e.jsxs("div",{className:"space-y-4",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(g.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(b||{},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(u.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",m.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:h?"Loading...":p?"Error loading columns":JSON.stringify(m.slice(0,5),null,2)})]})]})})}const G=U=>{if(!g.config)return;if(!U.length){j(g.id,{...g.config,sortByColumns:[]});return}const ee=g.config,ae=U.map(({id:ie,desc:z})=>{var J,ce;const te=(J=ee.metricColumns)==null?void 0:J.find(de=>de.label===ie),oe=(ce=ee.groupByColumns)==null?void 0:ce.find(de=>de.label===ie),re=te||oe;return re?{id:s.getFieldId("sortBy",re),name:re.name,dataType:re.dataType,label:re.label,qualifiedEntityName:re.qualifiedEntityName,entityId:re.entityId,entityName:re.entityName,entityType:re.entityType,role:"sortby",direction:z?"desc":"asc"}:null}).filter(ie=>ie!==null);j(g.id,{...ee,sortByColumns:ae})},se=A.useMemo(()=>{var U,ee;return(ee=(U=g.config)==null?void 0:U.sortByColumns)==null?void 0:ee.map(ae=>({id:ae.label,desc:ae.direction==="desc"}))},[(V=g.config)==null?void 0:V.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[e.jsx(io,{showDebug:a,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:d}),a&&W(),e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t==="chart"&&v&&e.jsx(kt,{variant:"outline"}),e.jsx(co,{activeView:t,onViewChange:n}),i&&e.jsx(oo,{dashboardFilterCount:x,cardFilterCount:d,onClick:i,className:"h-8"}),e.jsx("div",{className:"ml-2",children:e.jsx(mo,{})}),v&&e.jsx(os,{})]}),e.jsx("div",{className:s.cn("flex grow items-center justify-end"),children:t==="chart"&&e.jsx(Et,{})})]}),!N&&R&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>S(!0),className:"absolute right-5 top-1/2 z-40 size-10 -translate-y-1/2 rounded-full border border-border bg-background shadow-lg hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:e.jsx(s.Settings2,{className:"size-4"})}),e.jsxs("div",{className:"mt-3 flex grow flex-col",children:[t==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:e.jsx(It,{})}),t==="table"&&(M==null?void 0:M.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:u,data:(M==null?void 0:M.records)||[],paginationMetadata:X,onPaginationChange:q,isLoading:Y||_,onSortChange:G,sortState:se})}),t==="info"&&O&&e.jsx("div",{className:"px-6",children:e.jsxs("div",{className:"rounded-md bg-background",children:[e.jsxs("div",{className:"mb-2",children:[w&&e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Card ID:"}),e.jsx(s.EditableText,{value:g.id,onSave:U=>{const ee=s.sanitizeCardId(U);if(!ee){D("Card ID cannot be empty");return}const ae=k(g.id,ee);if(ae.success){E(ee);const ie={...g,id:ee};f(ie),y(ie),D(null),s.ue.success("Card ID updated successfully")}else D(ae.error||"Failed to update Card ID"),s.ue.error(ae.error||"Failed to update Card ID")},isEditable:!0,placeholder:"Enter card ID",displayClassName:"font-mono text-xs text-muted-foreground hover:text-foreground",inputClassName:"font-mono text-xs"}),e.jsx(s.CopyButton,{text:g.id,className:"h-5 w-5"})]}),C&&e.jsx("p",{className:"text-xs text-destructive",children:C})]}),B||Q?e.jsx(bt,{error:B,errorSql:Q,onSendFeedback:()=>{const U=po(Yt.QUERY_GENERATION,{cardConfig:g.config,dataSource:u.dataSource,dashboardFilters:b,errorMessage:B,errorSql:Q,generatedSql:M==null?void 0:M.sql});T(U),I(!0)}}):e.jsxs(e.Fragment,{children:[(M==null?void 0:M.sql)&&e.jsx("h3",{className:"mb-1 px-2 font-mono text-xs font-medium",children:"Generated SQL Query"}),e.jsx(vt,{sql:M==null?void 0:M.sql,error:B,errorSql:Q})]})]})})]}),e.jsx(ho,{isOpen:N,onClose:()=>S(!1)}),P&&e.jsx(fo,{open:F,onOpenChange:I,feedbackData:P})]})]})}function jo({activeField:t}){const[n,a]=A.useState(!0);return A.useEffect(()=>{t&&a(!0)},[t]),t?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${n?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(s.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(Rs,{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 bo=()=>{const t=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||t.apply(console,r)};const n=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},a=r=>{var l;if((l=r.reason)!=null&&l.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",n,!0),window.addEventListener("unhandledrejection",a,!0),()=>{console.error=t,window.removeEventListener("error",n,!0),window.removeEventListener("unhandledrejection",a,!0)}};function vo(){var X,q;const[t,n]=A.useState("chart"),[a,r]=A.useState(!1),[l,o]=A.useState(!1),[c,i]=A.useState(!0),d=s.useEditorStore(W=>W.showAIDialog),u=s.useDashboardStore(W=>W.isVisualEditing),{setCardType:m}=s.useEditorActions(),h=s.useEditorStore(W=>W.card.type);A.useEffect(()=>bo(),[]);const p=()=>{console.log("Accept clicked - would save/apply current configuration")},g=()=>{console.log("Clear clicked - would reset all configurations")},b=()=>{console.log("Advanced mode toggled")},x=()=>{o(!0)},j=W=>{m(W)},f=s.useEditorStore(W=>W.frame),y=s.useEditorStore(W=>W.card);s.useEditorStore(W=>W.activeTabCardId),s.useEditorStore(W=>W.actions.getAvailableFields);const{addCard:E,removeCard:k,updateCard:C,setActiveCard:D,updateFilters:v}=s.useEditorActions(),{columns:N=[],isLoading:S,error:F}=s.useColumns(),I=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),P=y,{getFieldsForContainer:T,setFieldsForContainer:w}=Ls(P),{activeField:L,handleDragStart:O,handleDragEnd:R}=lo({activeCardId:f.activeCardId,sourceFields:N,getFieldsForContainer:T,setFieldsForContainer:w}),M=(W,G)=>{G&&v(W,G)},B=W=>{var G;C(W,{config:{...(G=f.cards.find(se=>se.id===W))==null?void 0:G.config,filters:void 0}})},Y=N,_=W=>{if(!W)return 0;let G=W.conditions.length;return W.groups.forEach(se=>{G+=_(se)}),G},Q=_(((X=P==null?void 0:P.config)==null?void 0:X.filters)||null);return e.jsxs(s.DndContext,{sensors:I,collisionDetection:s.closestCenter,onDragStart:O,onDragEnd:R,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Cl,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(Vl,{selectedChart:h,onChartChange:j,groupByFields:T("groupBy"),pivotByFields:T("pivotBy"),metricsFields:T("metrics"),sortByFields:T("sortBy")}),e.jsx(go,{selectedChart:h,activeView:t,onViewChange:n,showDebug:a,onDebugToggle:()=>r(!a),onAccept:p,onClear:g,onAdvancedToggle:b,onFiltersClick:x,filterCount:Q,activeCard:P,dataSourceState:y.dataSource||s.EMPTY_DATA_SOURCE,columns:N,columnsLoading:S,columnsError:F,getFieldsForContainer:T,cards:f.cards,activeCardId:f.activeCardId,addCard:E,setActiveCard:D})]}),!c&&u&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>i(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),P&&e.jsx(ro,{cardId:P.id,filters:((q=P.config)==null?void 0:q.filters)||null,onFiltersChange:M,onClearFilters:B,availableFields:Y,isOpen:l,onOpenChange:o}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(jo,{activeField:L||null})})]})}function yo({authToken:t,onSave:n,onClose:a}){const r=A.useRef(null),l=s.useEditorStore(y=>y.showAIDialog),o=s.useEditorStore(y=>y.isDevMode),{setAuthToken:c}=s.useDashboardActions(),{setShowAIDialog:i,setOnSave:d,setOnClose:u}=s.useEditorActions(),{handleDragOver:m,handleDragEnd:h,handleDragStart:p,handleDragCancel:g,sensors:b}=zn();A.useEffect(()=>{n&&d(n),a&&u(a)},[n,d,a,u]),A.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),A.useEffect(()=>{var y,E;l?((y=r.current)==null||y.resize(40),i(!0)):(i(!1),(E=r.current)==null||E.resize(0))},[l,i]);function x(y){y<1?i(!1):l||i(!0)}function j(){return e.jsxs(e.Fragment,{children:[e.jsx(jt,{type:"main"}),e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:"grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(cl,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(Ws,{})})]})]})}function f(){return e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:"flex grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(vo,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(Ws,{})})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:o?e.jsx(s.DndContext,{sensors:b,onDragStart:p,onDragEnd:h,onDragOver:m,onDragCancel:g,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:j()})}):f()})}function No(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:n}=s.useDashboardStore(c=>c.actions),a=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function l(c){t&&(r(t,c),n(!1))}function o(){n(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!a}),children:e.jsx(yo,{onSave:l,onClose:o})})}function Co({column:t}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{className:"shrink-0",asChild:!0,children:s.isTextDataType(t.data_type)?e.jsx(s.TextIcon,{className:"size-3 text-muted-foreground"}):s.isNumberDataType(t.data_type)?e.jsx(De,{className:"size-3 text-muted-foreground"}):s.isDateDataType(t.data_type)?e.jsx(s.Calendar,{className:"size-3 text-muted-foreground"}):s.isBooleanDataType(t.data_type)?e.jsx(Le,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(ca,{className:"size-3 text-muted-foreground"}):e.jsx(s.QuestionMarkIcon,{className:"size-3 text-muted-foreground"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{className:"text-xs",children:t.data_type})})]})})}function So(){const t=s.useEditorStore(o=>o.selectedDatabaseName),n=s.useEditorStore(o=>o.selectedTableName),a=s.useDashboardStore(o=>o.dashboard.filters)||[],{columns:r}=s.useEditorAside(),{assignFilter:l}=Is();return e.jsx(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(o=>{const c=a==null?void 0:a.find(i=>i.column===s.fmt(o.column_name)&&i.table===n&&i.database===t);return e.jsx("div",{onClick:()=>l(o),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":c}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Co,{column:o}),e.jsx("span",{children:o.column_name})]})},o.column_name)})})}function wo({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ve,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Le,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Be,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Ye,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(He,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ve,{className:"h-3 w-3"})})}function Do(){const[t,n]=A.useState(""),[a,r]=A.useState("all"),l=s.useDashboardStore(f=>f.dashboard.filters)||[],{assignFilter:o}=Is(),c=s.useEditorStore(f=>f.card.dataSource),{columns:i=[],isLoading:d,error:u}=s.useColumns(),m=i.filter(f=>f.name.toLowerCase().includes(t.toLowerCase())||f.dataType.toLowerCase().includes(t.toLowerCase())||f.label&&f.label.toLowerCase().includes(t.toLowerCase())),h=f=>{const y=s.getDataType(f.dataType);return y==="number"?"metrics":(["date","string","boolean"].includes(y),"dimensions")},p=a==="all"?m:m.filter(f=>h(f)===a),g=m.filter(f=>h(f)==="dimensions").length,b=m.filter(f=>h(f)==="metrics").length,x=f=>{const y={column_name:f.name,data_type:f.dataType,label:f.label,description:f.description};o(y,"dashboard",f)};if(d)return e.jsx("div",{className:"flex h-full grow flex-col items-center justify-center px-3",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading fields"})});if(u)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-3",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:u.message||"Failed to load column data"})]});if(!c||!c.selectedEntities||c.selectedEntities.length===0)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 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:"Select a table, view, or dataset from the data source panel to see available fields"})]});if(i.length===0)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx("p",{className:"text-sm text-gray-500",children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]});const j=m.length>0;return e.jsxs("div",{className:"flex h-full grow flex-col pb-4",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-3 px-3 pt-3",children:[i.length>0&&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 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:t,onChange:f=>n(f.target.value)})]}),j&&e.jsx(s.Tabs,{defaultValue:"all",value:a,onValueChange:f=>r(f),children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-3",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:m.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:g})]}),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:b})]})]})})]}),e.jsxs(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3 pt-3",children:[p.length===0&&t&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',t,'"']}),p.length===0&&!t&&a!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",a," fields found"]}),p.map(f=>{const y=l==null?void 0:l.some(E=>{var k;return E.title===f.name||((k=E.column)==null?void 0:k.includes(f.name))});return e.jsx("div",{onClick:()=>x(f),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":y}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wo,{dataType:f.dataType}),e.jsx("span",{children:f.label||f.name})]})},f.id)})]})]})}function To(){var r;const t=s.useDashboardStore(l=>l.actions.setShowFilters),n=s.useCurrentActiveCard(),a=n&&((r=n.dataSource)==null?void 0:r.selectedEntities)&&n.dataSource.selectedEntities.length>0;return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l px-1",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-3",children:[e.jsx(s.Label,{className:"px-2 text-lg",children:"Filters"}),e.jsx(s.Button,{onClick:()=>t(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(s.Cross2Icon,{})})]}),e.jsx("div",{className:"flex grow",children:a?e.jsx(Do,{}):e.jsx(jt,{type:"filter",ColumnsComponent:()=>e.jsx(So,{})})})]})}function ko(){const t=s.useDashboardStore(r=>r.dashboard.filters),n=s.useDashboardStore(r=>r.theme),a=t==null?void 0:t.filter(r=>r.hide);return a!=null&&a.length?e.jsx("div",{className:s.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":n==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":n==="dark"}),children:a==null?void 0:a.map(r=>e.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[e.jsx(s.FilterHeader,{filter:r}),e.jsx(s.FilterComponent,{filter:r})]},r.id))}):null}function Eo(){const t=s.useDashboardStore(r=>r.showFilters),n=s.useDashboardStore(r=>r.isVisualEditing),a=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":n,"flex grow overflow-auto":!n}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[a&&e.jsx(ko,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(To,{})})]})}function Io(){const t=s.useDashboardStore(l=>l.dashboard),n=s.useDashboardStore(l=>l.actions.setDashboard),a=s.useDashboardStore(l=>l.showDashboardJSON),r=s.useDashboardStore(l=>l.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!a}),children:[e.jsxs(s.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(s.de,{onChange:l=>{if(l)try{JSON.parse(l),n(JSON.parse(l))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(t,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function $t(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4",children:[e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"space-y-2",children:[...Array(4)].map((t,n)=>e.jsx("div",{className:"animate-pulse",children:e.jsxs("div",{className:"group relative flex items-start gap-3 px-4 py-3",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-muted"})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("div",{className:"h-4 w-32 rounded bg-muted"})}),e.jsx("div",{className:"shrink-0",children:e.jsx("div",{className:"h-3.5 w-3.5 rounded bg-muted"})})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-3 w-48 rounded bg-muted"})})]}),e.jsx("div",{className:"absolute right-3 top-2",children:e.jsx("div",{className:"flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:e.jsx("div",{className:"h-6 w-6 rounded bg-muted"})})})]})]})},n))})]})})}function Ao({visual:t,isDeleting:n,isDuplicating:a,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onAddVisual:o,onEditVisual:c,onUpdateVisual:i,onDeleteClick:d,onDuplicateVisual:u,onShareVisual:m,formatDate:h}){var C,D,v;const{selectVisual:p}=s.useManagementActions(),g=s.useIsVisualSelected(t.id),{isConsoleMode:b}=s.useDashboardPreferences();s.useDashboardStore(N=>N.actions.setIsDashboardPanelOpen);const[x,j]=A.useState(!1),[f,y]=A.useState(!1);A.useEffect(()=>{a?(j(!0),y(!0)):f&&(j(!1),y(!1))},[a,f]);const E=()=>e.jsx(rs,{className:"h-4 w-4"}),k=()=>{p(t),c==null||c(t)};return e.jsx(s.Card,{className:s.cn("group cursor-pointer border-border/50 p-3 transition-colors hover:bg-accent/50",g&&"ring-1 ring-primary"),onClick:k,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:E()}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-2",children:[e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-foreground",value:t.title,onSave:N=>i==null?void 0:i(t.id,{title:N}),isEditable:t.ownership.isOwner&&g,isPending:r,placeholder:"Untitled Visual",displayClassName:"font-medium text-sm text-foreground truncate"}),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.jsx(s.EditableText,{inputClassName:"text-xs text-muted-foreground line-clamp-2",value:t.description||"",onSave:N=>i==null?void 0:i(t.id,{description:N}),isEditable:t.ownership.isOwner&&g,isPending:l,placeholder:"No description",displayClassName:"text-xs text-muted-foreground line-clamp-2 mb-2"}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsxs("span",{children:["Updated ",h(t.lastModified)]})]})]}),e.jsxs("div",{className:s.cn("opacity-0 transition-opacity duration-150 group-hover:opacity-100","ml-2 flex flex-shrink-0 items-center gap-1"),onClick:N=>N.stopPropagation(),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:N=>{N.stopPropagation(),o(t)},title:"Add to dashboard",children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:x,onOpenChange:j,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(),o(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.preventDefault(),N.stopPropagation(),u(t.id)},disabled:a,children:[a?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),a?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),console.log("Edit visual",t),c==null||c(t)},children:[e.jsx(Oa,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),m(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(),d(t)},className:"text-destructive",disabled:n,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),n?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((C=t.ownership.createdBy)==null?void 0:C.type)==="tenant"||((D=t.ownership.createdBy)==null?void 0:D.type)==="organization"&&b)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.User,{className:"h-3 w-3"}),e.jsx("span",{children:((v=t.ownership.createdBy)==null?void 0:v.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:h(t.lastModified)})]})]})]})]})]})]})},t.id)}function Mo(){const[t,n]=A.useState(""),[a,r]=A.useState(!1),[l,o]=A.useState(""),[c,i]=A.useState(""),[d,u]=A.useState(!1),[m,h]=A.useState(null),[p,g]=A.useState(!1),[b,x]=A.useState(null),[j,f]=A.useState(null),{setIsDashboardEditing:y,setIsVisualEditing:E}=s.useDashboardActions(),{handleEditLibraryVisual:k,handleAddLibraryVisual:C}=Ts(),{resources:D,isLoading:v,isError:N,createResource:S,updateResource:F,deleteResource:I,duplicateResource:P,isCreating:T,isDeleting:w}=s.useVisualManagement(()=>{g(!1),x(null)},()=>{r(!1),o(""),i("")});s.useCurrentUserInfo();const L=D.filter(U=>{var ee,ae;return((ee=U==null?void 0:U.title)==null?void 0:ee.toLowerCase().includes(t.toLowerCase()))||((ae=U==null?void 0:U.description)==null?void 0:ae.toLowerCase().includes(t.toLowerCase()))}),O=U=>new Date(U).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),R=()=>{l.trim()&&S({title:l,description:c,isPrivate:!1})},M=U=>{x(U),g(!0)},B=()=>{b&&I(b.id)},{startUpdating:Y,stopUpdating:_,isUpdating:Q}=s.useResourceUpdateState(),X=(U,ee)=>{const ae=ee.title!==void 0?"title":"description";Y(U,ae),F({resourceId:U,data:ee},{onSuccess:()=>{_(U,ae)},onError:()=>{_(U,ae)}})},q=U=>{f(U),P(U,{onSettled:()=>f(null)})},W=U=>{k(U)},G=U=>{C(U)},se=U=>{const ee=D.find(ae=>ae.id===U);ee&&F({resourceId:U,data:{isPrivate:!ee.isPrivate}})},V=U=>{h(U),u(!0)};return v?e.jsx($t,{}):N?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:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[e.jsx("div",{className:"px-1",children:a?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Visual"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:l,onChange:U=>o(U.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter visual description...",value:c,onChange:U=>i(U.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:R,size:"sm",className:"h-7 text-xs",disabled:!l.trim()||T,children:T?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),o(""),i("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:T,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>r(!0),className:"w-full bg-primary text-primary-foreground hover:bg-primary/90",disabled:T,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),T?"Creating...":"Create New Visual"]})}),D&&D.length>5&&e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:t,onChange:U=>n(U.target.value),className:"h-9"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:L.length===0?e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"mb-3",children:e.jsx(rs,{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"]})]}):L.map(U=>e.jsx(Ao,{visual:U,onAddVisual:G,onEditVisual:W,onUpdateVisual:X,onDeleteClick:M,onDuplicateVisual:q,onTogglePrivacy:se,onShareVisual:V,isDeleting:w,isDuplicating:j===U.id,isTitleUpdating:Q(U.id,"title"),isDescriptionUpdating:Q(U.id,"description"),formatDate:O},U.id))})}),d&&m&&e.jsx(ls,{resource:m,resourceType:s.ResourceType.VISUAL,onClose:()=>{u(!1),h(null)}}),e.jsx(s.AlertDialog,{open:p,onOpenChange:U=>{!U&&w||(g(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 "',b==null?void 0:b.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(),B()},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"]})]})]})})]})}function Lo({dashboard:t,isDeleting:n,isDuplicating:a,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onLoadDashboard:o,onUpdateDashboard:c,onDeleteClick:i,onDuplicateDashboard:d,onShareDashboard:u,formatDate:m,onDashboardItemClick:h}){var C,D,v;const{selectDashboard:p}=s.useManagementActions(),g=s.useIsDashboardSelected(t.id),{isConsoleMode:b}=s.useDashboardPreferences(),[x,j]=A.useState(!1),[f,y]=A.useState(!1);s.useDashboardStore(N=>N.actions.setIsDashboardPanelOpen),A.useEffect(()=>{a?(j(!0),y(!0)):f&&(j(!1),y(!1))},[a,f]);const E=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4"}),k=()=>{p(t),o(t.id),h==null||h(t.id)};return e.jsx(s.Card,{className:s.cn("group cursor-pointer border-border/50 p-3 transition-colors hover:bg-accent/50",g&&"ring-1 ring-primary"),onClick:k,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:E()}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-2",children:[e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-foreground",value:t.title,onSave:N=>c==null?void 0:c(t.id,{title:N}),isEditable:t.permissions.canEdit&&g,isPending:r,placeholder:"Untitled Dashboard",displayClassName:"font-medium text-sm text-foreground truncate"}),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.jsx(s.EditableText,{inputClassName:"text-xs text-muted-foreground line-clamp-2",value:t.description||"",onSave:N=>c==null?void 0:c(t.id,{description:N}),isEditable:t.permissions.canEdit&&g,isPending:l,placeholder:"No description",displayClassName:"text-xs text-muted-foreground line-clamp-2 mb-2"}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsxs("span",{children:["Updated ",m(t.lastModified)]})]})]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-150 group-hover:opacity-100","ml-2 flex-shrink-0"),onClick:N=>N.stopPropagation(),children:e.jsxs(s.DropdownMenu,{modal:!1,open:x,onOpenChange:j,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.preventDefault(),N.stopPropagation(),d(t.id)},disabled:a,children:[a?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),a?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),u(t)},children:[e.jsx(s.Users,{className:"mr-2 h-3 w-3"}),"Share"]})}),t.permissions.canDelete&&e.jsxs(e.Fragment,{children:[e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),i(t)},className:"text-destructive",disabled:n,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),n?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((C=t.ownership.createdBy)==null?void 0:C.type)==="tenant"||((D=t.ownership.createdBy)==null?void 0:D.type)==="organization"&&b)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.User,{className:"h-3 w-3"}),e.jsx("span",{children:((v=t.ownership.createdBy)==null?void 0:v.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:m(t.lastModified)})]})]})]})]})})]})},t.id)}function Ro({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 Oo(t){const[n,a]=A.useState(""),[r,l]=A.useState(!1),[o,c]=A.useState(""),[i,d]=A.useState(""),[u,m]=A.useState(!1),[h,p]=A.useState(null),[g,b]=A.useState(!1),[x,j]=A.useState(null),[f,y]=A.useState(null),E=s.useManagementStore(z=>z.lastSelectedDashboard),k=s.useManagementStore(z=>z.selectedDashboard),C=s.useManagementStore(z=>z.actions.selectDashboard),D=s.useManagementStore(z=>z.actions.clearSelectedDashboard),{tokenProps:v,id:N}=s.useSemaphorContext(),{permissions:S}=s.useRoleAwareDisplayPreferences(),{resources:F,isLoading:I,isError:P,createResource:T,updateResource:w,deleteResource:L,duplicateResource:O,isCreating:R,isDeleting:M}=s.useDashboardManagement(()=>{b(!1);const z=x==null?void 0:x.id;j(null),(k==null?void 0:k.id)===z&&(!(v!=null&&v.dashboard_id)&&!N?D():E&&E.id!==z&&C(E))},()=>{l(!1),c(""),d("")}),{currentUser:B}=s.useCurrentUserInfo(),Y=F.filter(z=>{var te,oe;return((te=z==null?void 0:z.title)==null?void 0:te.toLowerCase().includes(n.toLowerCase()))||((oe=z==null?void 0:z.description)==null?void 0:oe.toLowerCase().includes(n.toLowerCase()))}),_=z=>new Date(z).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),Q=()=>{o.trim()&&T({title:o,description:i,isPrivate:!1})},X=z=>{var te;(te=t.onLoadDashboard)==null||te.call(t,z)},q=z=>{j(z),b(!0)},W=()=>{x&&L(x.id)},G=z=>{y(z),O(z,{onSettled:()=>y(null)})},{startUpdating:se,stopUpdating:V,isUpdating:U}=s.useResourceUpdateState(),ee=(z,te)=>{const oe=te.title!==void 0?"title":"description";se(z,oe),w({resourceId:z,data:te},{onSuccess:()=>{V(z,oe)},onError:()=>{V(z,oe)}})},ae=z=>{const te=F.find(oe=>oe.id===z);te&&w({resourceId:z,data:{isPrivate:!te.isPrivate}})},ie=z=>{p(z),B==null||B.type,m(!0)};return I?e.jsx($t,{}):P?e.jsx(Ro,{onRetry:()=>window.location.reload()}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[S.canCreateDashboards&&e.jsx("div",{className:"px-1",children:r?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Dashboard"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter dashboard title...",value:o,onChange:z=>c(z.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter dashboard description...",value:i,onChange:z=>d(z.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:Q,size:"sm",className:"h-7 text-xs",disabled:!o.trim()||R,children:R?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{l(!1),c(""),d("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:R,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>l(!0),className:"w-full bg-primary text-primary-foreground hover:bg-primary/90",disabled:R,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),R?"Creating...":"Create New Dashboard"]})}),F&&F.length>5&&e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:n,onChange:z=>a(z.target.value),className:"h-9"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:Y.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:n?"No dashboards found":"No dashboards yet"}),e.jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:n?"Try adjusting your search":S.canCreateDashboards?"Create your first dashboard to get started":"No dashboards have been shared with you yet"}),S.canCreateDashboards&&!n&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>l(!0),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Create Dashboard"]})]}):Y.map(z=>e.jsx(Lo,{dashboard:z,isDeleting:M,isDuplicating:f===z.id,isTitleUpdating:U(z.id,"title"),isDescriptionUpdating:U(z.id,"description"),onLoadDashboard:X,onEditDashboard:t.onEditDashboard,onUpdateDashboard:ee,onDeleteClick:q,onDuplicateDashboard:G,onTogglePrivacy:ae,onShareDashboard:ie,formatDate:_,onDashboardItemClick:t.onDashboardItemClick},z.id))})}),u&&h&&e.jsx(ls,{resource:h,resourceType:s.ResourceType.DASHBOARD,onClose:()=>{m(!1),p(null)}}),e.jsx(s.AlertDialog,{open:g,onOpenChange:z=>{!z&&M||(b(z),z||j(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Dashboard"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',x==null?void 0:x.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:M,children:"Cancel"}),e.jsxs(s.AlertDialogAction,{onClick:z=>{z.preventDefault(),z.stopPropagation(),W()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:M,children:[M?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"}),M?"Deleting...":"Delete"]})]})]})})]})}function qt({isOpen:t,onClose:n,className:a,onDashboardItemClick:r,variant:l="inline"}){s.useDashboardStore(E=>E.dashboard);const{setDashboard:o,addSheet:c}=s.useDashboardStore(E=>E.actions),{currentUser:i}=s.useCurrentUserInfo(),d=i,{permissions:u}=s.useRoleAwareDisplayPreferences(),m=(u.canAccessVisuals,"dashboards"),[h,p]=s.useLocalStorageState("resource-management-active-tab",m),g=u.canAccessVisuals?h:"dashboards",b=l==="overlay",x=dt(n,{enabled:t&&b}),j=s.cn("flex h-full flex-col border-r bg-background",b?s.cn("absolute inset-y-0 left-0 z-[51] w-96 shadow-lg transition-transform duration-300 ease-in-out",t?"translate-x-0":"pointer-events-none -translate-x-full"):"w-full max-w-[28rem] min-w-[18rem] overflow-hidden shadow-sm",a),f=E=>{},y=E=>{console.log("Editing dashboard:",E)};return e.jsx(s.TooltipProvider,{children:(!b||t)&&e.jsxs("div",{ref:x,className:j,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:d&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-full bg-primary/10",children:e.jsx("span",{className:"text-sm font-medium text-primary",children:d.name.charAt(0).toUpperCase()})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:d.name}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:u.canCreateDashboards?"default":"secondary",className:"cursor-help text-xs",children:u.canCreateDashboards?e.jsxs(e.Fragment,{children:[e.jsx(s.Users,{className:"mr-1 h-3 w-3"}),"Power User"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Eye,{className:"mr-1 h-3 w-3"}),"Viewer"]})})}),e.jsx(s.TooltipContent,{side:"bottom",className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"font-medium",children:d.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:d.email}),d.role&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Role:"," ",s.toTitleCase(d.role.replace(/_/g," "))]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",d.id]})]})})]})})]})]})}),e.jsx(s.IconButton,{className:"h-8 w-8 p-0 text-muted-foreground hover:text-foreground",onClick:n,tooltip:"Close Sidebar",children:e.jsx(Ra,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:g,onValueChange:u.canAccessVisuals?p:void 0,className:"flex h-9 grow flex-col",children:[u.canAccessVisuals?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("div",{className:"px-4 pb-0 pt-4",children:e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Dashboards"})}),e.jsx(s.TabsContent,{value:"dashboards",className:"mt-4 flex-1",children:e.jsx(Oo,{onLoadDashboard:f,onEditDashboard:y,onDashboardItemClick:r})}),u.canAccessVisuals&&e.jsx(s.TabsContent,{value:"visuals",className:"mt-4 flex-1",children:e.jsx(Mo,{})})]})})]})})}function Fo({showControls:t=!1,showFooter:n=!0,...a}){const r=s.useDashboardStore(g=>g.isDashboardPanelOpen),l=s.useDashboardStore(g=>g.isVisualEditing),o=s.useDashboardStore(g=>g.actions.setIsDashboardPanelOpen),c=20,i=20,d=30,u=r&&!l,m=A.useRef(null),h=A.useRef(null);A.useEffect(()=>{m.current&&h.current&&(r?(m.current.resize(c),h.current.resize(100-c)):(m.current.resize(0),h.current.resize(100)))},[r]);const{preferences:p}=a;return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:a,children:[e.jsx(s.$e,{}),e.jsx(s.UXProvider,{children:e.jsxs(s.DashboardPreferencesProvider,{preferences:p,children:[e.jsx(Io,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx(Ln,{}),e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",className:"flex grow overflow-hidden",children:[e.jsx(s.ResizablePanel,{ref:m,className:s.cn("flex h-full max-w-[26rem] overflow-hidden",{"min-w-[20rem]":r}),defaultSize:r?c:0,minSize:r?i:0,maxSize:r?d:0,children:e.jsx(qt,{isOpen:r,onClose:()=>o(!1),variant:"inline"})}),e.jsx(s.ResizableHandle,{withHandle:r,className:s.cn("w-1",{"w-0":!r})}),e.jsx(s.ResizablePanel,{ref:h,className:"flex min-w-0 flex-1",defaultSize:u?100-c:100,minSize:u?40:100,children:e.jsxs(s.Container,{...a,type:"dashboard",children:[e.jsx(No,{}),e.jsx(Eo,{})]})})]})]})]})})]})})}exports.DashboardPlus=Fo;exports.ResourceManagementPanel=qt;exports.ScheduleDashboard=lt;exports.SelectComponent=Fe;exports.ShareDialog=ls;exports.cleanCard=rt;exports.getDashbaordStateWithoutData=ss;
|