react-semaphor 0.0.536 → 0.0.538

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.
@@ -1,64 +1,64 @@
1
- "use strict";const e=require("react/jsx-runtime"),s=require("./index-Cp70TiL_.js"),A=require("react");require("react-dom");function rn(t){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(a,n,r.get?r:{enumerable:!0,get:()=>t[n]})}}return a.default=t,Object.freeze(a)}const ye=rn(A);/**
1
+ "use strict";const e=require("react/jsx-runtime"),s=require("./index-BuxOBuu9.js"),M=require("react");require("react-dom");function ln(t){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(a,n,r.get?r:{enumerable:!0,get:()=>t[n]})}}return a.default=t,Object.freeze(a)}const ye=ln(M);/**
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 ln=s.createLucideIcon("AlignCenter",[["path",{d:"M17 12H7",key:"16if0g"}],["path",{d:"M19 18H5",key:"18s9l3"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);/**
6
+ */const on=s.createLucideIcon("AlignCenter",[["path",{d:"M17 12H7",key:"16if0g"}],["path",{d:"M19 18H5",key:"18s9l3"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);/**
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 on=s.createLucideIcon("AlignLeft",[["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M17 18H3",key:"1amg6g"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);/**
11
+ */const cn=s.createLucideIcon("AlignLeft",[["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M17 18H3",key:"1amg6g"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);/**
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 cn=s.createLucideIcon("AlignRight",[["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M21 18H7",key:"1ygte8"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);/**
16
+ */const dn=s.createLucideIcon("AlignRight",[["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M21 18H7",key:"1ygte8"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);/**
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 dn=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"}]]);/**
21
+ */const un=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"}]]);/**
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 un=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"}]]);/**
26
+ */const mn=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"}]]);/**
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 mn=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"}]]);/**
31
+ */const hn=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"}]]);/**
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 hn=s.createLucideIcon("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);/**
36
+ */const xn=s.createLucideIcon("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);/**
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 xn=s.createLucideIcon("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);/**
41
+ */const pn=s.createLucideIcon("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);/**
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 pn=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"}]]);/**
46
+ */const fn=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"}]]);/**
47
47
  * @license lucide-react v0.453.0 - ISC
48
48
  *
49
49
  * This source code is licensed under the ISC license.
50
50
  * See the LICENSE file in the root directory of this source tree.
51
- */const fn=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"}]]);/**
51
+ */const gn=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"}]]);/**
52
52
  * @license lucide-react v0.453.0 - ISC
53
53
  *
54
54
  * This source code is licensed under the ISC license.
55
55
  * See the LICENSE file in the root directory of this source tree.
56
- */const gn=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"}]]);/**
56
+ */const jn=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"}]]);/**
57
57
  * @license lucide-react v0.453.0 - ISC
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 jn=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"}]]);/**
61
+ */const yn=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"}]]);/**
62
62
  * @license lucide-react v0.453.0 - ISC
63
63
  *
64
64
  * This source code is licensed under the ISC license.
@@ -68,12 +68,12 @@
68
68
  *
69
69
  * This source code is licensed under the ISC license.
70
70
  * See the LICENSE file in the root directory of this source tree.
71
- */const yn=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"}]]);/**
71
+ */const vn=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"}]]);/**
72
72
  * @license lucide-react v0.453.0 - ISC
73
73
  *
74
74
  * This source code is licensed under the ISC license.
75
75
  * See the LICENSE file in the root directory of this source tree.
76
- */const vn=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"}]]);/**
76
+ */const bn=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"}]]);/**
77
77
  * @license lucide-react v0.453.0 - ISC
78
78
  *
79
79
  * This source code is licensed under the ISC license.
@@ -83,7 +83,7 @@
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 bn=s.createLucideIcon("Calculator",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["line",{x1:"8",x2:"16",y1:"6",y2:"6",key:"x4nwl0"}],["line",{x1:"16",x2:"16",y1:"14",y2:"18",key:"wjye3r"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M8 18h.01",key:"lrp35t"}]]);/**
86
+ */const Nn=s.createLucideIcon("Calculator",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["line",{x1:"8",x2:"16",y1:"6",y2:"6",key:"x4nwl0"}],["line",{x1:"16",x2:"16",y1:"14",y2:"18",key:"wjye3r"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M8 18h.01",key:"lrp35t"}]]);/**
87
87
  * @license lucide-react v0.453.0 - ISC
88
88
  *
89
89
  * This source code is licensed under the ISC license.
@@ -108,7 +108,7 @@
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 Nn=s.createLucideIcon("ChartNoAxesCombined",[["path",{d:"M12 16v5",key:"zza2cw"}],["path",{d:"M16 14v7",key:"1g90b9"}],["path",{d:"M20 10v11",key:"1iqoj0"}],["path",{d:"m22 3-8.646 8.646a.5.5 0 0 1-.708 0L9.354 8.354a.5.5 0 0 0-.707 0L2 15",key:"1fw8x9"}],["path",{d:"M4 18v3",key:"1yp0dc"}],["path",{d:"M8 14v7",key:"n3cwzv"}]]);/**
111
+ */const Cn=s.createLucideIcon("ChartNoAxesCombined",[["path",{d:"M12 16v5",key:"zza2cw"}],["path",{d:"M16 14v7",key:"1g90b9"}],["path",{d:"M20 10v11",key:"1iqoj0"}],["path",{d:"m22 3-8.646 8.646a.5.5 0 0 1-.708 0L9.354 8.354a.5.5 0 0 0-.707 0L2 15",key:"1fw8x9"}],["path",{d:"M4 18v3",key:"1yp0dc"}],["path",{d:"M8 14v7",key:"n3cwzv"}]]);/**
112
112
  * @license lucide-react v0.453.0 - ISC
113
113
  *
114
114
  * 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 Cn=s.createLucideIcon("CircleArrowRight",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"m12 16 4-4-4-4",key:"1i9zcv"}]]);/**
131
+ */const Sn=s.createLucideIcon("CircleArrowRight",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"m12 16 4-4-4-4",key:"1i9zcv"}]]);/**
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 Sn=s.createLucideIcon("Code",[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]]);/**
141
+ */const wn=s.createLucideIcon("Code",[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]]);/**
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 wn=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"}]]);/**
146
+ */const Tn=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"}]]);/**
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 Tn=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"}]]);/**
151
+ */const kn=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"}]]);/**
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 kn=s.createLucideIcon("CopyPlus",[["line",{x1:"15",x2:"15",y1:"12",y2:"18",key:"1p7wdc"}],["line",{x1:"12",x2:"18",y1:"15",y2:"15",key:"1nscbv"}],["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/**
156
+ */const Dn=s.createLucideIcon("CopyPlus",[["line",{x1:"15",x2:"15",y1:"12",y2:"18",key:"1p7wdc"}],["line",{x1:"12",x2:"18",y1:"15",y2:"15",key:"1nscbv"}],["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/**
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 Dn=s.createLucideIcon("DollarSign",[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]]);/**
161
+ */const En=s.createLucideIcon("DollarSign",[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]]);/**
162
162
  * @license lucide-react v0.453.0 - ISC
163
163
  *
164
164
  * This source code is licensed under the ISC license.
@@ -173,47 +173,47 @@
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 En=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"}]]);/**
176
+ */const In=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"}]]);/**
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 In=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"}]]);/**
181
+ */const An=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"}]]);/**
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 An=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"}]]);/**
186
+ */const Mn=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"}]]);/**
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 Mn=s.createLucideIcon("File",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}]]);/**
191
+ */const Ln=s.createLucideIcon("File",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}]]);/**
192
192
  * @license lucide-react v0.453.0 - ISC
193
193
  *
194
194
  * This source code is licensed under the ISC license.
195
195
  * See the LICENSE file in the root directory of this source tree.
196
- */const Ln=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"}]]);/**
196
+ */const On=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"}]]);/**
197
197
  * @license lucide-react v0.453.0 - ISC
198
198
  *
199
199
  * This source code is licensed under the ISC license.
200
200
  * See the LICENSE file in the root directory of this source tree.
201
- */const On=s.createLucideIcon("FolderOpen",[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]]);/**
201
+ */const Rn=s.createLucideIcon("FolderOpen",[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]]);/**
202
202
  * @license lucide-react v0.453.0 - ISC
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 Rn=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"}]]);/**
206
+ */const Bn=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"}]]);/**
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 Bn=s.createLucideIcon("Grid3x3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
211
+ */const Fn=s.createLucideIcon("Grid3x3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
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 Fn=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"}]]);/**
216
+ */const zn=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"}]]);/**
217
217
  * @license lucide-react v0.453.0 - ISC
218
218
  *
219
219
  * This source code is licensed under the ISC license.
@@ -223,27 +223,27 @@
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 zn=s.createLucideIcon("LayoutGrid",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]]);/**
226
+ */const Pn=s.createLucideIcon("LayoutGrid",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]]);/**
227
227
  * @license lucide-react v0.453.0 - ISC
228
228
  *
229
229
  * This source code is licensed under the ISC license.
230
230
  * See the LICENSE file in the root directory of this source tree.
231
- */const Pn=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"}]]);/**
231
+ */const _n=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"}]]);/**
232
232
  * @license lucide-react v0.453.0 - ISC
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 _n=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"}]]);/**
236
+ */const Vn=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"}]]);/**
237
237
  * @license lucide-react v0.453.0 - ISC
238
238
  *
239
239
  * This source code is licensed under the ISC license.
240
240
  * See the LICENSE file in the root directory of this source tree.
241
- */const Vn=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"}]]);/**
241
+ */const Un=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"}]]);/**
242
242
  * @license lucide-react v0.453.0 - ISC
243
243
  *
244
244
  * This source code is licensed under the ISC license.
245
245
  * See the LICENSE file in the root directory of this source tree.
246
- */const Un=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"}]]);/**
246
+ */const qn=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"}]]);/**
247
247
  * @license lucide-react v0.453.0 - ISC
248
248
  *
249
249
  * 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 qn=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"}]]);/**
256
+ */const $n=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"}]]);/**
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 $n=s.createLucideIcon("Mail",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}]]);/**
261
+ */const Gn=s.createLucideIcon("Mail",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}]]);/**
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 Gn=s.createLucideIcon("MapPin",[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}]]);/**
266
+ */const Hn=s.createLucideIcon("MapPin",[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}]]);/**
267
267
  * @license lucide-react v0.453.0 - ISC
268
268
  *
269
269
  * This source code is licensed under the ISC license.
@@ -273,12 +273,12 @@
273
273
  *
274
274
  * This source code is licensed under the ISC license.
275
275
  * See the LICENSE file in the root directory of this source tree.
276
- */const Hn=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"}]]);/**
276
+ */const Jn=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"}]]);/**
277
277
  * @license lucide-react v0.453.0 - ISC
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 Jn=s.createLucideIcon("MessageCircle",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]]);/**
281
+ */const Wn=s.createLucideIcon("MessageCircle",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]]);/**
282
282
  * @license lucide-react v0.453.0 - ISC
283
283
  *
284
284
  * This source code is licensed under the ISC license.
@@ -293,17 +293,17 @@
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 Wn=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"}]]);/**
296
+ */const Yn=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"}]]);/**
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 Yn=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"}]]);/**
301
+ */const Kn=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"}]]);/**
302
302
  * @license lucide-react v0.453.0 - ISC
303
303
  *
304
304
  * This source code is licensed under the ISC license.
305
305
  * See the LICENSE file in the root directory of this source tree.
306
- */const Kn=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"}]]);/**
306
+ */const Qn=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"}]]);/**
307
307
  * @license lucide-react v0.453.0 - ISC
308
308
  *
309
309
  * This source code is licensed under the ISC license.
@@ -318,12 +318,12 @@
318
318
  *
319
319
  * This source code is licensed under the ISC license.
320
320
  * See the LICENSE file in the root directory of this source tree.
321
- */const Qn=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"}]]);/**
321
+ */const Xn=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"}]]);/**
322
322
  * @license lucide-react v0.453.0 - ISC
323
323
  *
324
324
  * This source code is licensed under the ISC license.
325
325
  * See the LICENSE file in the root directory of this source tree.
326
- */const Xn=s.createLucideIcon("Settings2",[["path",{d:"M20 7h-9",key:"3s1dr2"}],["path",{d:"M14 17H5",key:"gfn3mx"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]]);/**
326
+ */const Zn=s.createLucideIcon("Settings2",[["path",{d:"M20 7h-9",key:"3s1dr2"}],["path",{d:"M14 17H5",key:"gfn3mx"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]]);/**
327
327
  * @license lucide-react v0.453.0 - ISC
328
328
  *
329
329
  * This source code is licensed under the ISC license.
@@ -338,12 +338,12 @@
338
338
  *
339
339
  * This source code is licensed under the ISC license.
340
340
  * See the LICENSE file in the root directory of this source tree.
341
- */const Zn=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"}]]);/**
341
+ */const ea=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"}]]);/**
342
342
  * @license lucide-react v0.453.0 - ISC
343
343
  *
344
344
  * This source code is licensed under the ISC license.
345
345
  * See the LICENSE file in the root directory of this source tree.
346
- */const ea=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"}]]);/**
346
+ */const sa=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"}]]);/**
347
347
  * @license lucide-react v0.453.0 - ISC
348
348
  *
349
349
  * This source code is licensed under the ISC license.
@@ -353,12 +353,12 @@
353
353
  *
354
354
  * This source code is licensed under the ISC license.
355
355
  * See the LICENSE file in the root directory of this source tree.
356
- */const sa=s.createLucideIcon("Sparkles",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}],["path",{d:"M20 3v4",key:"1olli1"}],["path",{d:"M22 5h-4",key:"1gvqau"}],["path",{d:"M4 17v2",key:"vumght"}],["path",{d:"M5 18H3",key:"zchphs"}]]);/**
356
+ */const ta=s.createLucideIcon("Sparkles",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}],["path",{d:"M20 3v4",key:"1olli1"}],["path",{d:"M22 5h-4",key:"1gvqau"}],["path",{d:"M4 17v2",key:"vumght"}],["path",{d:"M5 18H3",key:"zchphs"}]]);/**
357
357
  * @license lucide-react v0.453.0 - ISC
358
358
  *
359
359
  * This source code is licensed under the ISC license.
360
360
  * See the LICENSE file in the root directory of this source tree.
361
- */const ta=s.createLucideIcon("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/**
361
+ */const na=s.createLucideIcon("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/**
362
362
  * @license lucide-react v0.453.0 - ISC
363
363
  *
364
364
  * This source code is licensed under the ISC license.
@@ -373,7 +373,7 @@
373
373
  *
374
374
  * This source code is licensed under the ISC license.
375
375
  * See the LICENSE file in the root directory of this source tree.
376
- */const na=s.createLucideIcon("Terminal",[["polyline",{points:"4 17 10 11 4 5",key:"akl6gq"}],["line",{x1:"12",x2:"20",y1:"19",y2:"19",key:"q2wloq"}]]);/**
376
+ */const aa=s.createLucideIcon("Terminal",[["polyline",{points:"4 17 10 11 4 5",key:"akl6gq"}],["line",{x1:"12",x2:"20",y1:"19",y2:"19",key:"q2wloq"}]]);/**
377
377
  * @license lucide-react v0.453.0 - ISC
378
378
  *
379
379
  * This source code is licensed under the ISC license.
@@ -398,7 +398,7 @@
398
398
  *
399
399
  * This source code is licensed under the ISC license.
400
400
  * See the LICENSE file in the root directory of this source tree.
401
- */const me=s.createLucideIcon("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);function vs(t){var a;return{...t,sheets:(a=t==null?void 0:t.sheets)==null?void 0:a.map(n=>{var r;return{...n,frames:(r=n.frames)==null?void 0:r.map(l=>{var o;return{...l,cards:(o=l.cards)==null?void 0:o.map(c=>ct(c))}})}})}}function ct(t){return{...t,customCfg:aa(t.customCfg),data:[]}}function aa(t){var a,n;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(n=(a=t==null?void 0:t.data)==null?void 0:a.datasets)==null?void 0:n.map(r=>({...r,data:[]}))}}:null}async function ra(t,a,n,r){if(!r)return null;const l=JSON.stringify(a);return await s.postRequest("https://semaphor.cloud/api/v1/lens",r,{name:t,template:l,filterValues:n,operation:"create"})}async function rs(t,a){if(!a)return null;const{id:n,template:r,filterValues:l,isDefault:o,shared:c}=t;return await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{lensId:n,template:r,filterValues:l,isDefault:o,shared:c,operation:"update"})}async function la(t,a){return a?await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{operation:"delete",lensId:t}):null}function oa(){const[t,a]=A.useState(""),[n,r]=A.useState(!1),l=s.useDashboardStore(x=>x.lenses),{setLenses:o,setSelectedLensId:c}=s.useDashboardActions(),[i,d]=A.useState(!1),[m,h]=A.useState(!1),u=s.useDashboardStore(x=>x.dashboard),p=s.useDashboardStore(x=>x.filterValues),{authToken:f}=s.useSemaphorContext();async function j(){d(!0);const x=vs(u),T=await ra(t,x,p,f==null?void 0:f.accessToken);T&&(o([...l||[],T]),c(T.id),h(!1)),d(!1)}return e.jsxs(s.Dialog,{open:m,onOpenChange:h,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:x=>{a(x.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),n&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{size:"sm",variant:"outline",type:"submit",onClick:j,disabled:i,children:i?"Creating...":"Add"})})]})]})}function ia(){const[t,a]=A.useState(!1),n=s.useDashboardStore(h=>h.lenses),r=s.useDashboardStore(h=>h.selectedLensId),{setLenses:l,setSelectedLensId:o}=s.useDashboardActions(),{authToken:c}=s.useSemaphorContext();async function i(h){o(h)}async function d(h){if(await la(h,c==null?void 0:c.accessToken)){const p=n==null?void 0:n.filter(f=>f.id!==h);l(p||[]),o("original")}}async function m(h){const u=n==null?void 0:n.map(j=>j.id===h.id?{...j,isDefault:!h.isDefault}:{...j,isDefault:!1});l(u||[]);const p={...h,isDefault:!h.isDefault};await rs(p,c==null?void 0:c.accessToken);const f=n==null?void 0:n.find(j=>j.isDefault);if(f&&f.id!==h.id){const j={...f,isDefault:!1};await rs(j,c==null?void 0:c.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:a,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(Rn,{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:i,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),n==null?void 0:n.map(h=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:h.id,children:[e.jsx("p",{children:h.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:u=>{u.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:u=>{u.preventDefault(),d(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 dt(){var o;const t=s.useDashboardStore.getState().authToken,a=s.useDashboardStore.getState().theme,n=s.useDashboardStore.getState().filterValues,r=(o=s.useDashboardStore.getState().dashboard)==null?void 0:o.title,l=s.useDashboardStore.getState().selectedSheetId;return{authToken:t,theme:a||"light",filterValues:n,dashboardTitle:r||"",selectedSheetId:l||""}}async function ut(){const t=s.useDashboardStore.getState().isDownloadingPdf,{authToken:a,theme:n,filterValues:r,dashboardTitle:l,selectedSheetId:o}=dt();if(t)return;const c=new URLSearchParams;c.set("token",(a==null?void 0:a.accessToken)||""),c.set("theme",n),c.set("filterValues",JSON.stringify(r)),c.set("selectedSheetId",o||"");const i=`https://semaphor.cloud/api/v1/generate-pdf?params=${encodeURIComponent(c.toString())}`;s.useDashboardStore.setState({isDownloadingPdf:!0});const h=(await(await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${a==null?void 0:a.accessToken}`}})).json()).url,u=document.createElement("a");u.href=h;const p=`${l}-${new Date().toISOString()}.pdf`;u.download=p,u.click(),s.useDashboardStore.setState({isDownloadingPdf:!1})}function ca({iconClassName:t}){const{authToken:a}=s.useSemaphorContext();s.useDashboardStore(l=>{var o;return(o=l.dashboard)==null?void 0:o.title}),s.useDashboardStore(l=>l.theme),s.useDashboardStore(l=>l.filterValues);const n=s.useDashboardStore(l=>l.isDownloadingPdf);async function r(){await ut()}return e.jsx(s.IconButton,{tooltip:"Download PDF",className:"h-7 p-2",onClick:r,children:n?e.jsx(s.LoaderCircle,{className:s.cn("size-3.5 animate-spin",t)}):e.jsx(s.Download,{className:s.cn("size-4",t)})})}function ce({defaultValue:t,label:a,options:n,value:r,onValueChange:l,className:o,icon:c,showPlaceholderLabel:i=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:l,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",o),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),i&&e.jsx(s.SelectValue,{placeholder:a})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:a}),n.map(d=>e.jsx(s.SelectItem,{value:d.value,children:d.label},d.value))]})})]})}const Vs=[{value:"daily",label:"Daily"},{value:"weekly",label:"Weekly"},{value:"biweekly",label:"Bi-Weekly"},{value:"monthly",label:"Monthly"}];function mt({triggerButtonClassName:t}){const{data:a,handleScheduleSubscription:n,handleDeleteSubscription:r,status:l,error:o,isDeleting:c}=da(),[i,d]=A.useState(""),[m,h]=A.useState(Vs[0].value),[u,p]=A.useState("06:00"),[f,j]=A.useState("");return e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Schedule Dashboard",className:s.cn("h-7 p-2",t),children:e.jsx(s.Clock,{className:"size-4"})})}),e.jsx(s.PopoverContent,{align:"end",className:"w-80",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Schedule Subscription"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribe to receive dashboard via email"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"email",children:"Email"}),e.jsx(s.Input,{id:"email",value:i,onChange:x=>d(x.target.value),className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"subject",children:"Subject"}),e.jsx(s.Input,{id:"subject",placeholder:"Monthly Sales Report",value:f,onChange:x=>{j(x.target.value.replace(/[^a-zA-Z0-9\s-_]/g,""))},className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"frequency",children:"Frequency"}),e.jsx(ce,{className:"col-span-2 h-8",label:"Select Frequency",options:Vs,value:m,onValueChange:x=>h(x)})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"time",children:"Time"}),e.jsx(s.Input,{id:"time",type:"time",value:u,onChange:x=>p(x.target.value),className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsx("div",{className:"mt-2 flex justify-end",children:e.jsxs(s.Button,{onClick:async()=>{await n({email:i,frequency:m,time:u,subject:f}),p("00:00"),d(""),j("")},className:"h-8 p-2",disabled:l==="loading"||!i,children:[l==="loading"&&e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin"}),l==="success"&&e.jsx(s.Check,{className:"mr-2 size-4"}),l==="error"&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{children:e.jsx(st,{className:"mr-2 size-4 text-destructive"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{children:o})})]}),"Schedule"]})}),a&&a.length>0&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Subscriptions"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Active email subscriptions"})]}),s.isDevEnv]})}),e.jsx("div",{className:"grid gap-2",children:a==null?void 0:a.map(x=>e.jsxs("div",{className:"group grid grid-cols-5 gap-3",children:[e.jsx("div",{className:"col-span-3 text-sm",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"boder-border rounded-md border bg-muted px-2 py-1",children:[s.titleCase(x.frequency)," "]}),e.jsx(s.Label,{children:x.time})]})}),e.jsxs("div",{className:"col-span-2 flex items-center justify-end gap-4",children:[e.jsx(Us,{tooltip:`Next Run: ${new Date(x.nextRun).toLocaleString()} ${x.timezone}`,children:e.jsx(Cn,{className:"size-3.5"})}),e.jsx(Us,{tooltip:`${x.endUserEmail}`,children:e.jsx($n,{className:"size-3.5"})}),c===x.id?e.jsx(s.LoaderCircle,{className:"size-3.5 animate-spin"}):e.jsx(s.Trash2,{onClick:()=>r(x.id),className:"size-3.5 cursor-pointer"})]})]},x.id))})]})]})]})})]})})}const Us=({children:t,tooltip:a})=>e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:t}),e.jsx(s.TooltipContent,{children:a})]})});function da(){const[t,a]=A.useState("idle"),[n,r]=A.useState(""),[l,o]=A.useState(null),c=s.useDashboardStore(C=>C.authToken),i=s.useDashboardStore(C=>C.dashboard.id),d=s.useDashboardStore(C=>C.dashboard.title),{endUserId:m}=s.getTenantAndEndUserId((c==null?void 0:c.accessToken)||""),h="https://semaphor.cloud/api/v1/subscriptions/get",u={dashboardId:i,endUserId:m},{data:p,isLoading:f,isError:j,isFetching:x,refetch:T}=s.useQuery({queryKey:["subscriptions",i,m],queryFn:()=>s.getRequest(h,(c==null?void 0:c.accessToken)||"",u),enabled:!!(c!=null&&c.accessToken)&&!!i&&!!m});async function g({email:C,subject:O,frequency:S,time:E}){const{authToken:N,...D}=dt(),w=Intl.DateTimeFormat().resolvedOptions().timeZone,M={email:C,frequency:S,time:E,timezone:w,endUserId:m,endUserEmail:C,subject:O||d||"Scheduled Dashboard",dashboardId:i,dashboardParams:D};a("loading");const k="https://semaphor.cloud/api/v1/subscriptions/create";try{const R=await s.postRequestRegular(k,(N==null?void 0:N.accessToken)||"",{...M});a("success"),r(""),T(),setTimeout(()=>{a("idle")},2e3)}catch(R){console.error(R),a("error"),r(R.message)}}async function b(C){const O="https://semaphor.cloud/api/v1/subscriptions/delete";o(C);try{await s.postRequestRegular(O,(c==null?void 0:c.accessToken)||"",{id:C}),T(),setTimeout(()=>{o(null)},2e3)}catch(S){console.error(S),o(null),a("error"),r(S.message)}}return{data:p,isLoading:f,isFetching:x,isError:j,isDeleting:l,refetch:T,handleScheduleSubscription:g,handleDeleteSubscription:b,status:t,error:n}}function We(){const{authToken:t,tokenProps:a}=s.useSemaphorContext();let n=null;a&&(a.endUserId&&a.endUserEmail&&a.tenantId?n={id:a.endUserId,name:a.endUserEmail?String(a.displayName):"",email:a.endUserEmail?String(a.endUserEmail):"",type:"tenant",tenantId:a.tenantId}:a.orgUserId&&a.orgUserEmail&&(n={id:a.orgUserId,name:a.orgUserEmail?String(a.displayName):"",email:a.orgUserEmail?String(a.orgUserEmail):"",type:"organization"}));const{data:r,isLoading:l,isError:o}=s.useQuery({queryKey:["userInfo",n==null?void 0:n.id],queryFn:async()=>{if(!(n!=null&&n.id))return;const i=await fetch(`https://semaphor.cloud/api/management/v1/unified-users/${n.id}`,{headers:{Authorization:`Bearer ${(t==null?void 0:t.accessToken)||""}`,"Content-Type":"application/json"}});if(!i.ok)throw new Error("Failed to fetch user info");return(await i.json()).user},enabled:!!(t!=null&&t.accessToken)&&!!(n!=null&&n.id)});return{currentUser:n?{...n,...r||{}}:null,isLoading:l,isError:o}}function ht(){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,a)=>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"})})})]})]})},a))})]})})}function ua({visual:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onAddVisual:o,onEditVisual:c,onUpdateVisual:i,onDeleteClick:d,onDuplicateVisual:m,onShareVisual:h,formatDate:u}){var S;const{selectVisual:p}=s.useManagementActions(),f=s.useIsVisualSelected(t.id),[j,x]=A.useState(!1),[T,g]=A.useState(!1);A.useEffect(()=>{n?(x(!0),g(!0)):T&&(x(!1),g(!1))},[n,T]);const b=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(nt,{className:"h-3 w-3 text-purple-500"}):e.jsx(me,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(fe,{className:"h-3.5 w-3.5 text-slate-500"}),C=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4 text-slate-400"}),O=()=>{p(t),c==null||c(t)};return e.jsxs("div",{className:s.cn("group relative flex cursor-pointer items-start gap-3 px-4 py-3 dark:border-slate-800","cursor-pointer transition-colors duration-150 hover:bg-slate-50 dark:hover:bg-slate-900/50",t.ownership.isOwner&&"border-blue-200 dark:border-blue-800",f&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:O,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-slate-100 dark:bg-slate-800",children:C()})}),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(s.EditableText,{inputClassName:"text-sm font-medium text-slate-900 dark:text-slate-100",value:t.title,onSave:E=>i==null?void 0:i(t.id,{title:E}),isEditable:t.ownership.isOwner&&f,isPending:r,placeholder:"Untitled Visual",displayClassName:"line-clamp-1 max-w-[150px] text-sm font-medium text-slate-900 dark:text-slate-100"})}),e.jsx("div",{className:"shrink-0",children:b()})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx(s.EditableText,{inputClassName:"line-clamp-1 text-xs text-slate-500 dark:text-slate-400",value:t.description||"",onSave:E=>i==null?void 0:i(t.id,{description:E}),isEditable:t.ownership.isOwner&&f,isPending:l,placeholder:"No description",displayClassName:"mt-0.5 max-w-[220px] line-clamp-1 text-xs text-slate-500 dark:text-slate-400"})})]}),e.jsx("div",{className:"absolute right-3 top-2 flex items-center justify-between text-xs text-muted-foreground",children:e.jsxs("div",{className:s.cn("flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100"),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:E=>{E.stopPropagation(),o(t)},children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:j,onOpenChange:x,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:E=>E.stopPropagation(),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:E=>{E.stopPropagation(),o(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:E=>{E.preventDefault(),E.stopPropagation(),m(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:E=>{E.stopPropagation(),c==null||c(t)},children:[e.jsx(Yn,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:E=>{E.stopPropagation(),h(t)},children:[e.jsx(me,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:E=>{E.stopPropagation(),d(t)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(fe,{className:"h-3 w-3"}),e.jsx("span",{children:((S=t.ownership.createdBy)==null?void 0:S.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:u(t.lastModified)})]})]})]})]})]})})]})]},t.id)}function xt({value:t,onChange:a,placeholder:n="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:n,value:t,onChange:r=>a(r.target.value),className:"pl-9"})]})}function Pe({currentRole:t,onRoleChange:a,roleOptions:n,disabled:r=!1,className:l="",allowDropdown:o=!0}){var d;const c=((d=n.find(m=>m.value===t))==null?void 0:d.label)||t,i=n.filter(m=>m.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}`,onClick:()=>console.log("Badge clicked:",{currentRole:t,disabled:r,allowDropdown:o}),children:c})}),e.jsx(s.DropdownMenuContent,{className:"z-[51]",children:i.map(m=>e.jsx(s.DropdownMenuItem,{onClick:()=>{console.log("Dropdown item clicked:",{currentRole:t,newRole:m.value,disabled:r}),a(m.value)},disabled:r,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.description})]})},m.value))})]}):e.jsx(s.Badge,{variant:"outline",className:`text-xs ${l}`,children:c})}function pt({selectedUsers:t,selectedUserObjects:a,onRemove:n,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=>n(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:a.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(Pe,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:d=>r(o.id,d),roleOptions:i}),e.jsx("button",{onClick:()=>n(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 ft({usersToRemove:t,allUsers:a,onRemove:n}){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=>n(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:a.filter(r=>t.includes(r.id)).map(r=>e.jsxs(s.Badge,{variant:"destructive",className:"gap-1",children:[r.name,e.jsx("button",{onClick:()=>n(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 gt({usersToUpdate:t,allUsers:a,onRemove:n,getRoleOptions:r}){if(t.length===0)return null;const l=r("tenant"),o=i=>{const d=a.find(m=>m.id===i);return(d==null?void 0:d.name)||"Unknown User"},c=i=>{const d=l.find(m=>m.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(me,{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:()=>n(i.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},i.id))})]})}function ma(t,a={}){const{enabled:n=!0,eventType:r="mousedown"}=a,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 n&&document.addEventListener(r,o),()=>{document.removeEventListener(r,o)}},[t,n,r]),l}function de(t,a){var n;return((n=a.find(r=>r.value===t))==null?void 0:n.label)||t}function ha(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function jt(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function xa(t,a,n){const r=jt(t),l=(n==null?void 0:n.type)||"organization";if(!(!a||!a.shares))if(l==="organization")if(r==="organization"){if("specificOrgUsers"in a.shares)return(a.shares.specificOrgUsers||[]).find(i=>i.orgUserId===t.id)}else return(a.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id);else return(a.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id)}function pa({user:t}){return jt(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 fa({user:t,userShare:a,usersToUpdate:n,currentUser:r,getRoleOptions:l,handleUpdateAccess:o}){if(!(a!=null&&a.role))return null;const c=ha((r==null?void 0:r.type)||""),i=n.some(u=>u.id===t.id),d=n.find(u=>u.id===t.id),m=d?d.newRole:a==null?void 0:a.role,h=l(t.type);return a?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(Pe,{currentRole:m,onRoleChange:u=>{o(t.id,a.role,u)},roleOptions:h,disabled:!c,allowDropdown:c,className:i?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:de(m,h)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function ga({hasAccess:t,isUserRemoving:a,isSelected:n,hasAccessFromAPI:r}){return e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[t&&!a&&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"]}),a&&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"]}),n&&!r&&e.jsxs(s.Badge,{variant:"outline",className:"border-blue-200 bg-blue-50 text-xs text-blue-700",children:[e.jsx(Me,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function ja({isUserRemoving:t,isSelected:a,hasAccess:n,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"}),a&&!n&&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 ya({existingShares:t,allUsers:a,getRoleOptions:n,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||[],m=c.orgWide||[],h=c.orgUsersOnly||[],u=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,f)=>{var g,b;const j=((g=a.find(C=>C.id===p.orgUserId))==null?void 0:g.name)||"Unknown User",x=((b=a.find(C=>C.id===p.orgUserId))==null?void 0:b.type)||"",T=de(p.role,n(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:j}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:T})]},f)}),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,f)=>{var g,b;const j=((g=a.find(C=>C.id===p.tenantUserId))==null?void 0:g.name)||"Unknown User",x=((b=a.find(C=>C.id===p.tenantUserId))==null?void 0:b.type)||"",T=de(p.role,n(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:j}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:T})]},f)}),d.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",d.length-3," more users"]})]})]}),m.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:m.map((p,f)=>{const j=de(p.role,n(""));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:j})]},f)})})]}),h.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:h.map((p,f)=>{const j=de(p.role,n(""));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:j})]},f)})})]}),u.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:u.map((p,f)=>{const j=de(p.role,n(""));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:j})]},f)})})]}),!i.length&&!d.length&&!m.length&&!h.length&&!u.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,m)=>{var f,j;const h=((f=a.find(x=>x.id===d.tenantUserId))==null?void 0:f.name)||"Unknown User",u=((j=a.find(x=>x.id===d.tenantUserId))==null?void 0:j.type)||"",p=de(d.role,n(u));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:h}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:p})]},m)}),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,m)=>{const h=de(d.role,n(""));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:h})]},m)})})]}),!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,f;const m=((p=a.find(j=>j.id===i.tenantUserId))==null?void 0:p.name)||"Unknown User",h=((f=a.find(j=>j.id===i.tenantUserId))==null?void 0:f.type)||"",u=de(i.role,n(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:u})]},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 m=de(i.role,n(""));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})]},d)})})]}),!o.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function va({isInitialLoading:t,searchQuery:a,availableUsers:n}){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..."})]})}):n.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:a?"No users found matching your search.":"No users available to share with."}):null}function ba({user:t,userShare:a,isUserRemoving:n,hasAccess:r,hasAccessFromAPI:l,isSelected:o,selectedUser:c,roleOptions:i,currentUser:d,usersToUpdate:m,handleUserToggle:h,handleRemoveAccess:u,handleUpdateAccess:p,handleUserRoleChange:f}){return e.jsxs("div",{className:s.cn("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!n?"border border-green-200 bg-green-50":n?"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?!n:o,disabled:t.id===(d==null?void 0:d.id),onCheckedChange:()=>{l?n?h(t.id):u(t.id):h(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(pa,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!n?e.jsx(Pe,{currentRole:a==null?void 0:a.role,onRoleChange:j=>p(t.id,a.role,j),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(fa,{user:t,userShare:a,usersToUpdate:m,currentUser:d,getRoleOptions:()=>i,handleUpdateAccess:p}),o&&!l&&e.jsx("div",{onClick:j=>j.stopPropagation(),children:e.jsx(Pe,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:j=>f(t.id,j),roleOptions:i,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(ga,{hasAccess:r,isUserRemoving:n,isSelected:o,hasAccessFromAPI:l}),e.jsx(ja,{isUserRemoving:n,isSelected:o,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function yt({existingShares:t,isInitialLoading:a,isSearching:n,getRoleOptions:r,allUsers:l=[],currentUser:o,handleUserToggle:c,handleUserRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:m}){const h=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),f=s.useShareSearchQuery(),j=s.useShareManagementActions(),x=c||(S=>{const E=h.some(D=>D.id===S),N=u.includes(S);E?j.removeSelectedUser(S):N?j.removeUserFromRemove(S):j.addSelectedUser({id:S,role:"VIEWER"})}),T=i||j.updateSelectedUserRole,g=d||j.addUserToRemove,b=m||((S,E,N)=>{j.addUserToUpdate({id:S,currentRole:E,newRole:N})}),C=l,O=u;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 (",(C??[]).length,")"]}),e.jsx(s.TooltipProvider$1,{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(ya,{existingShares:t,allUsers:l,getRoleOptions:r,currentUser:o})})]})})]}),(C==null?void 0:C.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{h.length===C.length?j.setSelectedUsers([]):j.setSelectedUsers(C.map(S=>({id:S.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:h.length===C.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(va,{isInitialLoading:a,isSearching:n,searchQuery:f,availableUsers:C||[]}),!a&&!n&&(C==null?void 0:C.length)>0&&C.map(S=>{const E=t?xa(S,t,o):void 0,N=O.includes(S.id),D=!!E,w=D&&!N,M=h.some(I=>I.id===S.id),k=h.find(I=>I.id===S.id),R=r(S.type);return e.jsx(ba,{user:S,userShare:E,isUserRemoving:N,hasAccess:w,hasAccessFromAPI:D,isSelected:M,selectedUser:k,roleOptions:R,currentUser:o,usersToUpdate:p,handleUserToggle:x,handleRemoveAccess:g,handleUpdateAccess:b,handleUserRoleChange:T},S.id)})]})]})}function vt({shareType:t,onShareTypeChange:a,currentUser:n,options:r}){const l=(n==null?void 0:n.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:a,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(fe,{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 ve=()=>[{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 Na({currentUser:t,currentShare:a,isSharing:n,onUpdateAccess:r,allUsersToUpdate:l=null,allUsersToRemove:o=!1,isUpdating:c=!1,isRemoving:i=!1}){const d=s.useShareCurrentMode(),m=ve().filter(b=>b.value==="VIEWER"||b.value==="EDITOR"||b.value==="CONTRIBUTOR"),h=a.role!=="NONE"?a.role:"NONE",u=l?l.newRole:h,p=a.role!=="NONE"&&!o&&(!l||l.newRole===h),f=l!==null&&l.newRole!==h,j=o,x=h==="NONE"||!h,T=b=>{switch(b){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(Zn,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},g=b=>{r(h,b)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",f&&!j&&!x?"border-orange-300 bg-orange-50":p?"border-green-300 bg-green-50":j||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(me,{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"}),f&&e.jsx(s.Badge,{variant:"secondary",className:"ml-2 border-orange-400 bg-orange-100 text-orange-800",children:"Pending Update"}),(j||x)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:j||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:m.map(b=>e.jsxs(s.Button,{variant:u===b.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>g(b.value),disabled:n||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[T(b.value),e.jsx("span",{className:"font-medium",children:b.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:b.description})]},b.value))})]})})]})})}function bt({currentUser:t,currentShare:a,isSharing:n,isUpdating:r,isRemoving:l,onUpdateAccess:o,onRemoveAccess:c,allUsersToUpdate:i,allUsersToRemove:d}){const m=x=>x==="OWNER"?"CONTRIBUTOR":x,u=a?{role:m(a.role)}:{role:"NONE"},p=i?{currentRole:m(i.currentRole),newRole:m(i.newRole)}:null,f=(x,T)=>{o(x,T)},j=()=>{c()};return e.jsx(Na,{currentUser:t,currentShare:u,isSharing:n,isUpdating:r,isRemoving:l,onUpdateAccess:f,onRemoveAccess:j,allUsersToUpdate:p,allUsersToRemove:d})}const Ca=async(t,a={})=>{const n={};return a.search&&(n.search=a.search),a.type&&(n.type=a.type),a.active!==void 0&&(n.active=a.active.toString()),a.tenantId&&(n.tenantId=a.tenantId),a.limit&&(n.limit=a.limit.toString()),a.offset&&(n.offset=a.offset.toString()),a.page&&(n.page=a.page.toString()),a.pageSize&&(n.pageSize=a.pageSize.toString()),await s.getRequest("https://semaphor.cloud/api/management/v1/unified-users",t,n)};function Sa(t={}){var r,l,o;const{authToken:a}=s.useSemaphorContext(),n=s.useQuery({queryKey:["unified-users",t],queryFn:()=>Ca((a==null?void 0:a.accessToken)||"",t),enabled:!!(a!=null&&a.accessToken),retry:(c,i)=>i instanceof Error&&i.message.includes("401")||i instanceof Error&&i.message.includes("403")?!1:c<2,retryDelay:c=>Math.min(1e3*2**c,3e4)});return{users:((r=n.data)==null?void 0:r.users)||[],userContext:(l=n.data)==null?void 0:l.userContext,total:((o=n.data)==null?void 0:o.total)||0,isLoading:n.isLoading,isError:n.isError,isFetching:n.isFetching,error:n.error,refetch:n.refetch}}function ge(t){const{debouncedSearchQuery:a,resourceId:n,resourceType:r=s.ResourceType.DASHBOARD,userType:l,tenantId:o}=t,c=A.useMemo(()=>({search:a,active:!0,...l?{type:l}:{},...l==="tenant"&&o?{tenantId:o}:{}}),[a,l,o]),{users:i,isLoading:d,isError:m}=Sa(c),h=s.useResourceShares(r,n);return{allUsers:i,isLoadingUsers:d,isErrorLoadingUsers:m,existingShares:h.data,isLoadingShares:h.isLoading,isErrorLoadingShares:h.isError,isFetchingShares:h.isFetching}}function wa({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var Y,V;const i=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:m,setSearchQuery:h,debouncedSearchQuery:u}=s.useShareSearchWithDebounce(),p=s.useShareSelectedUsers(),f=s.useShareUsersToRemove(),j=s.useShareUsersToUpdate(),x=s.useShareCurrentMode(),T=s.useShareOrgWideRole(),g=s.useShareManagementActions(),[b,C]=A.useState("specific_users"),O=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},S=()=>{if(i==="tenant"&&d)return d},{allUsers:E,existingShares:N,isLoadingUsers:D}=ge({debouncedSearchQuery:u,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:O(),tenantId:S()});A.useEffect(()=>{g.setCurrentContext("org-tab"),g.setCurrentMode(b==="all_users"?"allOrgUsers":"specificOrgUsers")},[g,b]);const w=q=>{var U,H;const $=q;if(C($),r==null||r($),g.setCurrentContext("org-tab"),$==="specific_users")g.setCurrentMode("specificOrgUsers");else if($==="all_users"){g.setCurrentMode("allOrgUsers");const W=(H=(U=N==null?void 0:N.shares)==null?void 0:U.orgUsersOnly)==null?void 0:H[0];W&&W.role!==void 0&&g.setOrgWideRole(W.role)}},M=E.filter(q=>q.name.toLowerCase().includes(m.toLowerCase())||q.email.toLowerCase().includes(m.toLowerCase())),k=E.filter(q=>p.some($=>$.id===q.id)),R=q=>{var W,G;const $=p.some(Z=>Z.id===q),U=f.includes(q),H=(G=(W=N==null?void 0:N.shares)==null?void 0:W.specificOrgUsers)==null?void 0:G.some(Z=>Z.orgUserId===q);$?g.removeSelectedUser(q):U?g.removeUserFromRemove(q):H||g.addSelectedUser({id:q,role:"VIEWER"})},I=(q,$)=>{g.updateSelectedUserRole(q,$)},v=q=>{g.addUserToRemove(q),g.removeSelectedUser(q)},y=q=>{g.removeUserFromRemove(q)},L=q=>{g.removeUserFromUpdate(q)},F=(q,$)=>{g.setOrgWideRole($)},P=()=>{g.setOrgWideRole((_==null?void 0:_.role)||"NONE")},_=(V=(Y=N==null?void 0:N.shares)==null?void 0:Y.orgUsersOnly)==null?void 0:V[0];A.useEffect(()=>{b==="all_users"&&_&&_.role!==void 0&&g.setOrgWideRole(_.role)},[b,_,g]);const z=D,Q=!1;return n?e.jsxs(e.Fragment,{children:[e.jsx(vt,{shareType:b,onShareTypeChange:w,currentUser:n,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(fe,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(n==null?void 0:n.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(me,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role??"")}]}),b==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(xt,{value:m,onChange:h}),e.jsx(pt,{selectedUsers:p,selectedUserObjects:k,onRemove:R,onRoleChange:I,getRoleOptions:ve}),e.jsx(ft,{usersToRemove:f,allUsers:M,onRemove:y}),e.jsx(gt,{usersToUpdate:j,allUsers:M,onRemove:L,getRoleOptions:ve}),e.jsx(yt,{existingShares:N,isInitialLoading:z,isSearching:Q,resource:t,onShare:()=>{},getRoleOptions:ve,allUsers:M,currentUser:n,handleUserToggle:R,handleUserRoleChange:I,handleRemoveAccess:v,handleUpdateAccess:(q,$,U)=>{g.addUserToUpdate({id:q,currentRole:$,newRole:U})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(bt,{currentUser:n,currentShare:_,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:F,onRemoveAccess:P,allUsersToUpdate:x==="allOrgUsers"&&T!==((_==null?void 0:_.role)||"NONE")?{currentRole:(_==null?void 0:_.role)||"NONE",newRole:T}:null,allUsersToRemove:x==="allOrgUsers"&&(_==null?void 0:_.role)===void 0})})]}):null}function qs({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var W;const{searchQuery:i,debouncedSearchQuery:d,setSearchQuery:m}=s.useShareSearchWithDebounce(),h=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),f=s.useShareCurrentMode(),j=s.useShareTenantWideRole(),x=s.useShareAllTenantsRole(),T=s.useShareSelectedTenant(),g=s.useShareManagementActions(),{data:b,isLoading:C}=s.useTenants({enabled:(n==null?void 0:n.type)==="organization"}),[O,S]=A.useState((n==null?void 0:n.type)==="organization"?"all_tenants":"specific_tenant_users");A.useEffect(()=>{(n==null?void 0:n.type)==="tenant"?(g.setCurrentContext("tenant-dialog"),g.setCurrentMode("specificTenantUsers")):(g.setCurrentContext("tenant-tab"),g.setCurrentMode("allTenants"))},[g,n==null?void 0:n.type]);const E=G=>{var se,ne,ee,ae;S(G);let Z;if(G==="specific_tenant_users"?Z="specific_users":G==="all_tenant_users"||G==="all_tenants"?Z="all_users":Z="specific_users",r==null||r(Z),(n==null?void 0:n.type)==="tenant"?(g.setCurrentContext("tenant-dialog"),G==="specific_tenant_users"?g.setCurrentMode("specificTenantUsers"):G==="all_tenant_users"&&(g.setCurrentMode("allTenantUsers"),n!=null&&n.tenantId&&g.setSelectedTenant(n.tenantId))):(g.setCurrentContext("tenant-tab"),G==="specific_tenant_users"?g.setCurrentMode("specificTenantUsers"):G==="all_tenant_users"?g.setCurrentMode("allTenantUsers"):G==="all_tenants"&&g.setCurrentMode("allTenants")),G==="all_tenant_users"){const J=(ne=(se=w==null?void 0:w.shares)==null?void 0:se.tenantWide)==null?void 0:ne[0];J&&J.role!==void 0&&g.setTenantWideRole(J.role)}else if(G==="all_tenants"){const J=(ae=(ee=w==null?void 0:w.shares)==null?void 0:ee.allTenantsOnly)==null?void 0:ae[0];J&&J.role!==void 0&&g.setAllTenantsRole(J.role)}},N=G=>{g.setSelectedTenant(G)},{allUsers:D,existingShares:w,isLoadingUsers:M,isErrorLoadingUsers:k,isLoadingShares:R,isErrorLoadingShares:I}=ge({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant",tenantId:(n==null?void 0:n.type)==="tenant"?n.tenantId:T}),v=G=>{var ee,ae;const Z=h.some(J=>J.id===G),se=u.includes(G),ne=(ae=(ee=w==null?void 0:w.shares)==null?void 0:ee.specificTenantUsers)==null?void 0:ae.some(J=>J.tenantUserId===G);Z?g.removeSelectedUser(G):se?g.removeUserFromRemove(G):ne||g.addSelectedUser({id:G,role:"VIEWER"})},y=(G,Z)=>{g.updateSelectedUserRole(G,Z)},L=G=>{g.addUserToRemove(G),g.removeSelectedUser(G)},F=G=>{g.removeUserFromRemove(G)},P=G=>{g.removeUserFromUpdate(G)},_=(G,Z,se)=>{g.addUserToUpdate({id:G,currentRole:Z,newRole:se})},z=(G,Z)=>{O==="all_tenant_users"?g.setTenantWideRole(Z):O==="all_tenants"&&g.setAllTenantsRole(Z)},Q=()=>{O==="all_tenant_users"?g.setTenantWideRole("VIEWER"):O==="all_tenants"&&g.setAllTenantsRole("VIEWER")},V=(()=>{var G,Z,se,ne;return f==="allTenants"?(Z=(G=w==null?void 0:w.shares)==null?void 0:G.allTenantsOnly)==null?void 0:Z[0]:f==="allTenantUsers"?(ne=(se=w==null?void 0:w.shares)==null?void 0:se.tenantWide)==null?void 0:ne[0]:null})();A.useEffect(()=>{var G,Z,se,ne;if(O==="all_tenant_users"){const ee=(Z=(G=w==null?void 0:w.shares)==null?void 0:G.tenantWide)==null?void 0:Z[0];ee&&ee.role!==void 0&&g.setTenantWideRole(ee.role)}else if(O==="all_tenants"){const ee=(ne=(se=w==null?void 0:w.shares)==null?void 0:se.allTenantsOnly)==null?void 0:ne[0];ee&&ee.role!==void 0&&g.setAllTenantsRole(ee.role)}},[O,w,g]);const q=D.filter(G=>h.some(Z=>Z.id===G.id)),$=M||R,U=k||I,H=()=>(n==null?void 0:n.type)==="tenant"||O==="all_tenants"?!0:T&&(O==="specific_tenant_users"||O==="all_tenant_users");return e.jsxs(e.Fragment,{children:[U&&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"})]})}),!U&&n&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(vt,{shareType:O,onShareTypeChange:E,currentUser:n,options:(n==null?void 0:n.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:e.jsx(me,{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(fe,{className:"mb-3 h-6 w-6 text-orange-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(fe,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(n==null?void 0:n.type)==="organization"&&(O==="specific_tenant_users"||O==="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:N,disabled:C,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:C?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(W=b==null?void 0:b.tenants)==null?void 0:W.map(G=>e.jsx(s.SelectItem,{value:G.id,children:G.name},G.id))})]})]}),H()?e.jsx(e.Fragment,{children:O==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(xt,{value:i,onChange:m}),e.jsx(pt,{selectedUsers:h,selectedUserObjects:q,onRemove:G=>v(G),onRoleChange:y,getRoleOptions:ve}),e.jsx(ft,{usersToRemove:u,allUsers:D,onRemove:F}),e.jsx(gt,{usersToUpdate:p,allUsers:D,onRemove:P,getRoleOptions:ve}),e.jsx(yt,{existingShares:w,isInitialLoading:!!$,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:ve,allUsers:D,currentUser:n,handleUserToggle:v,handleUserRoleChange:y,handleRemoveAccess:L,handleUpdateAccess:_})]}):O==="all_tenant_users"||O==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(bt,{currentUser:n,currentShare:V,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:z,onRemoveAccess:Q,allUsersToUpdate:f==="allTenantUsers"&&((V==null?void 0:V.role)===void 0||j!==V.role)||f==="allTenants"&&((V==null?void 0:V.role)===void 0||x!==V.role)?{currentRole:(V==null?void 0:V.role)||"VIEWER",newRole:f==="allTenantUsers"?j:x}:null,allUsersToRemove:f==="allTenantUsers"&&(V==null?void 0:V.role)===void 0||f==="allTenants"&&(V==null?void 0:V.role)===void 0})}):null}):(n==null?void 0:n.type)==="organization"&&(O==="specific_tenant_users"||O==="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"})]})})]})]})}const Nt=()=>{const t=s.useShareCurrentContext(),a=s.useShareCurrentMode(),n=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),l=s.useShareUsersToUpdate(),o=s.useShareSelectedTenant(),c=s.useShareOrgWideRole(),i=s.useShareAllTenantsRole(),d=s.useShareTenantWideRole(),m=A.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:l,selectedTenant:o,orgWideRole:c,allTenantsRole:i,tenantWideRole:d}),[t,a,n,r,l,o,c,i,d]),h=A.useMemo(()=>p=>s.validateShareData(p),[]),u=A.useMemo(()=>{if(!t||!a)return!1;switch(t){case"org-tab":return a==="specificOrgUsers"?n.length>0||r.length>0||l.length>0:!0;case"tenant-tab":if(a==="allTenantUsers"){if(!o)return!1}else if(a==="specificTenantUsers")return o?n.length>0||r.length>0||l.length>0:!1;return!0;case"tenant-dialog":return a==="specificTenantUsers"?n.length>0||r.length>0||l.length>0:!0}return!1},[t,a,n,r,l,o]);return{buildShareData:m,validateShareData:h,isCurrentStateValid:u,currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:l,selectedTenant:o,orgWideRole:c,allTenantsRole:i,tenantWideRole:d}};function $s({resource:t,existingShares:a,isSharing:n,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllUsersShare:d,onRemoveAccess:m}){const h=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const f=s.useShareSelectedTenant();s.useShareSelectedTab();const j=s.useShareOrgWideRole(),x=s.useShareAllTenantsRole(),T=s.useShareTenantWideRole(),{buildShareData:g,validateShareData:b,isCurrentStateValid:C}=Nt(),O=n||r||l,S=()=>{var M,k,R,I;if(O)return"Updating...";if(i==="specific_users"){if(h.length===0&&u.length===0&&p.length===0)return"Select users to share with";const v=h.length+u.length+p.length;return v===0?"Select users to share with":h.length>0&&u.length>0?`Update access for ${v} user${v!==1?"s":""}`:u.length>0&&h.length===0&&p.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:h.length>0&&u.length===0&&p.length===0?`Share with ${h.length} user${h.length!==1?"s":""}`:p.length>0&&h.length===0&&u.length===0?`Update access for ${p.length} user${p.length!==1?"s":""}`:`Update access for ${v} user${v!==1?"s":""}`}else if(i==="all_users"){if(!d||d.role===void 0)return"Share with All Users";const v=d.role;return j===v?"Remove Access":"Update Access"}else if(i==="all_tenants"){const v=(k=(M=a==null?void 0:a.shares)==null?void 0:M.allTenantsOnly)==null?void 0:k[0];if(!v||v.role===void 0)return"Share with All Tenants";const y=v.role;return x===y?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const v=(I=(R=a==null?void 0:a.shares)==null?void 0:R.tenantWide)==null?void 0:I[0];if(!v||v.role===void 0)return"Share with All Tenant Users";const y=v.role;return T===y?"Remove Access":"Update Access"}else if(i==="specific_tenant_users"){if(h.length===0&&u.length===0&&p.length===0)return"Select users to share with";const v=h.length+u.length+p.length;return v===0?"Select users to share with":h.length>0&&u.length>0?`Update access for ${v} user${v!==1?"s":""}`:u.length>0&&h.length===0&&p.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:h.length>0&&u.length===0&&p.length===0?`Share with ${h.length} user${h.length!==1?"s":""}`:p.length>0&&h.length===0&&u.length===0?`Update access for ${p.length} user${p.length!==1?"s":""}`:`Update access for ${v} user${v!==1?"s":""}`}return"Share"},E=()=>O||!t||i==="all_tenant_users"&&!f||i==="specific_tenant_users"&&!f?!0:!C,N=()=>{const M=g();M&&b(M)&&o(M)},D=()=>{var M,k,R,I;if(i==="all_users")if(!d||d.role===void 0){const v=g();v&&b(v)&&o(v)}else{const v=d.role;if(j===v)m==null||m();else{const L=g();if(L&&b(L)){const F={...L,updateAccess:!0};o(F)}}}else if(i==="all_tenants"){const v=(k=(M=a==null?void 0:a.shares)==null?void 0:M.allTenantsOnly)==null?void 0:k[0];if(!v||v.role===void 0){const y=g();y&&b(y)&&o(y)}else{const y=v.role;if(x===y)m==null||m();else{const F=g();if(F&&b(F)){const P={...F,updateAccess:!0};o(P)}}}}else if(i==="all_tenant_users"){const v=(I=(R=a==null?void 0:a.shares)==null?void 0:R.tenantWide)==null?void 0:I[0];if(!v||v.role===void 0){const y=g();y&&b(y)&&o(y)}else{const y=v.role;if(T===y)m==null||m();else{const F=g();if(F&&b(F)){const P={...F,updateAccess:!0};o(P)}}}}},w=()=>{var M,k,R,I;if(i==="all_users"){if(!d||d.role===void 0)return"default";const v=d.role;return j===v?"destructive":"default"}else if(i==="all_tenants"){const v=(k=(M=a==null?void 0:a.shares)==null?void 0:M.allTenantsOnly)==null?void 0:k[0];if(!v||v.role===void 0)return"default";const y=v.role;return x===y?"destructive":"default"}else if(i==="all_tenant_users"){const v=(I=(R=a==null?void 0:a.shares)==null?void 0:R.tenantWide)==null?void 0:I[0];if(!v||v.role===void 0)return"default";const y=v.role;return T===y?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:O,children:"Close"}),(i==="specific_users"||i==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(h.length>0||u.length>0||p.length>0)&&e.jsxs(s.Button,{onClick:N,disabled:!t||O,variant:"default",children:[O?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Me,{className:"mr-2 h-4 w-4"}),!O&&S()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:D,disabled:E(),variant:w(),children:[O?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(me,{className:"mr-2 h-4 w-4"}),!O&&S()]})]})}function Ta({resource:t,isSharing:a,isRemoving:n,isUpdating:r,onShare:l,onClose:o,shareTabType:c,currentAllUsersShare:i}){const d=s.useShareSelectedUsers(),m=s.useShareUsersToRemove(),h=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const u=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:p,validateShareData:f,isCurrentStateValid:j}=Nt(),x=a||n||r,T=()=>{if(x)return"Updating...";if(c==="specific_users"){if(d.length===0&&m.length===0&&h.length===0)return"Select users to share with";const S=d.length+m.length+h.length;return S===0?"Select users to share with":d.length>0&&m.length>0?`Update access for ${S} user${S!==1?"s":""}`:m.length>0&&d.length===0&&h.length===0?`Remove access for ${m.length} user${m.length!==1?"s":""}`:d.length>0&&m.length===0&&h.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:h.length>0&&d.length===0&&m.length===0?`Update access for ${h.length} user${h.length!==1?"s":""}`:`Update access for ${S} user${S!==1?"s":""}`}else if(c==="all_users"){if(!i||i.role==="NONE")return"Share with All Users";const S=i.role;return u===S?"Remove Access":"Update Access"}return"Share"},g=()=>x||!t?!0:!j,b=()=>{const S=p();S&&f(S)&&l(S)},C=()=>{if(!i||i.role==="NONE"){const S=p();S&&f(S)&&l(S)}else{const S=i.role;if(u===S){const N=p();if(N&&f(N)){const D={...N,removeAccess:!0};l(D)}}else{const N=p();if(N&&f(N)){const D={...N,updateAccess:!0};l(D)}}}},O=()=>!i||i.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:o,disabled:x,children:"Close"}),c==="specific_users"&&e.jsx(e.Fragment,{children:(d.length>0||m.length>0||h.length>0)&&e.jsxs(s.Button,{onClick:b,disabled:!t||x,variant:"default",children:[x?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Me,{className:"mr-2 h-4 w-4"}),!x&&T()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:C,disabled:g(),variant:O(),children:[x?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Me,{className:"mr-2 h-4 w-4"}),!x&&T()]})]})}function Ct({resource:t,resourceType:a,isSharing:n,isRemoving:r,isUpdating:l,onClose:o,onShare:c,onRemoveAccess:i}){var N,D,w,M;const{currentUser:d}=We(),[m,h]=A.useState("specific_users"),[u,p]=A.useState("specific_users"),f=s.useShareManagementActions(),j=s.useShareSelectedTab(),x=s.useShareCurrentMode(),{existingShares:T}=ge({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant"}),{existingShares:g}=ge({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"organization"}),b=(D=(N=T==null?void 0:T.shares)==null?void 0:N.tenantWide)==null?void 0:D[0],C=(M=(w=g==null?void 0:g.shares)==null?void 0:w.orgUsersOnly)==null?void 0:M[0],O=()=>{if(j==="org")return u;switch(x){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},S=A.useCallback(()=>{f.resetShareState(),o()},[f,o]),E=(d==null?void 0:d.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:S,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(Me,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:E?"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."})]}),E?e.jsxs(s.Tabs,{value:j,onValueChange:k=>{const R=k;f.setSelectedTab(R),f.resetUserSelections()},className:"mb-4 min-h-0 flex-1",children:[e.jsxs(s.TabsList,{className:"mb-2 grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"org",children:"Org Users"}),e.jsx(s.TabsTrigger,{value:"tenant",children:"Tenant Users"})]}),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(wa,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:p,isSharing:n,isUpdating:l,isRemoving:r})})}),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(qs,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:k=>h(k),isSharing:n,isUpdating:l,isRemoving:r})})})]}):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(qs,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:k=>h(k),isSharing:n,isUpdating:l,isRemoving:r})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:E?j==="org"?e.jsx($s,{resource:t,existingShares:g,isSharing:n,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:u,currentAllUsersShare:C,onRemoveAccess:i}):e.jsx($s,{resource:t,existingShares:T,isSharing:n,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:O(),currentAllUsersShare:b,onRemoveAccess:i}):e.jsx(Ta,{resource:t,isSharing:n,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:m,currentAllUsersShare:b,onRemoveAccess:i})})]})})}function ie(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function pe(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function St(t,a){const{resourceType:n,resourceId:r,shareMutation:l,removeMutation:o,existingShares:c,resetUserSelections:i}=a;if(r)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const d=ie(n,r,[{scope:"org_users_only",role:t.orgWideRole}]);l(d,{onSuccess:()=>{i()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:d,usersToRemove:m,usersToUpdate:h}=t;if(d&&d.length>0){const u=ie(n,r,d.map(p=>({scope:"specific_org_user",orgUserId:p.id,role:p.role})));l(u,{onSuccess:()=>{i()}})}if(m&&m.length>0){const u=pe(n,r,m.map(p=>{var j,x;const f=(x=(j=c==null?void 0:c.shares)==null?void 0:j.specificOrgUsers)==null?void 0:x.find(T=>T.orgUserId===p);return{scope:"specific_org_user",orgUserId:p,role:(f==null?void 0:f.role)||"VIEWER"}}));o(u,{onSuccess:()=>{i()}})}h&&h.length>0&&h.forEach(u=>{const p=ie(n,r,[{scope:"specific_org_user",orgUserId:u.id,role:u.newRole}]);l(p,{onSuccess:()=>{i()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const d=ie(n,r,[{scope:"all_tenants_only",role:t.allTenantsRole}]);l(d,{onSuccess:()=>{i()}})}else if(t.mode==="allTenantUsers"){const d=ie(n,r,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);l(d,{onSuccess:()=>{i()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:d,usersToRemove:m,usersToUpdate:h,tenantId:u}=t;if(m&&m.length>0){const p=pe(n,r,m.map(f=>{var x,T;const j=(T=(x=c==null?void 0:c.shares)==null?void 0:x.specificTenantUsers)==null?void 0:T.find(g=>g.tenantUserId===f);return{scope:"specific_tenant_user",tenantUserId:f,tenantId:u,role:(j==null?void 0:j.role)||"VIEWER"}}));o(p,{onSuccess:()=>{i()}})}if(h&&h.length>0&&h.forEach(p=>{const f=ie(n,r,[{scope:"specific_tenant_user",tenantUserId:p.id,tenantId:u,role:p.newRole}]);l(f,{onSuccess:()=>{i()}})}),d&&d.length>0){const p=ie(n,r,d.map(f=>({scope:"specific_tenant_user",tenantUserId:f.id,tenantId:u,role:f.role})));l(p,{onSuccess:()=>{i()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const d=pe(n,r,[{scope:"all_tenant_users",role:"VIEWER"}]);o(d,{onSuccess:()=>{i()}})}else if(t.updateAccess){const d=ie(n,r,[{scope:"all_tenant_users",role:t.tenantWideRole}]);l(d,{onSuccess:()=>{i()}})}else{const d=ie(n,r,[{scope:"all_tenant_users",role:t.tenantWideRole}]);l(d,{onSuccess:()=>{i()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:d,usersToRemove:m,usersToUpdate:h}=t;if(d&&d.length>0){const u=ie(n,r,d.map(p=>({scope:"specific_tenant_user",tenantUserId:p.id,role:p.role})));l(u,{onSuccess:()=>{i()}})}if(m&&m.length>0){const u=pe(n,r,m.map(p=>{var j,x;const f=(x=(j=c==null?void 0:c.shares)==null?void 0:j.specificTenantUsers)==null?void 0:x.find(T=>T.tenantUserId===p);return{scope:"specific_tenant_user",tenantUserId:p,role:(f==null?void 0:f.role)||"VIEWER"}}));o(u,{onSuccess:()=>{i()}})}h&&h.length>0&&h.forEach(u=>{const p=ie(n,r,[{scope:"specific_tenant_user",tenantUserId:u.id,role:u.newRole}]);l(p,{onSuccess:()=>{i()}})})}break}}function wt(t,a,n,r){var m,h,u,p,f,j;const{resourceType:l,resourceId:o,removeMutation:c,existingShares:i,resetUserSelections:d}=r;if(o)if(t.length>0){const x=pe(l,o,t.map(T=>{var b,C;const g=(C=(b=i==null?void 0:i.shares)==null?void 0:b.specificTenantUsers)==null?void 0:C.find(O=>O.tenantUserId===T);return{scope:"specific_tenant_user",tenantUserId:T,role:(g==null?void 0:g.role)||"VIEWER"}}));c(x,{onSuccess:()=>{d()},onError:T=>{console.error("Remove access failed:",T)}})}else{const x=a==="tenant"&&n==="allTenants",T=a==="tenant"&&n==="allTenantUsers";if(x){const g=(h=(m=i==null?void 0:i.shares)==null?void 0:m.allTenantsOnly)==null?void 0:h[0];if(g){const b=pe(l,o,[{scope:"all_tenants_only",role:g.role}]);c(b,{onSuccess:()=>{d()},onError:C=>{console.error("Remove all-tenants access failed:",C)}})}}else if(T){const g=(p=(u=i==null?void 0:i.shares)==null?void 0:u.tenantWide)==null?void 0:p[0];if(g){const b=pe(l,o,[{scope:"all_tenant_users",role:g.role}]);c(b,{onSuccess:()=>{d()},onError:C=>{console.error("Remove all-tenant-users access failed:",C)}})}}else{const g=(j=(f=i==null?void 0:i.shares)==null?void 0:f.orgUsersOnly)==null?void 0:j[0];if(g){const b=pe(l,o,[{scope:"org_users_only",role:g.role}]);c(b,{onSuccess:()=>{d()},onError:C=>{console.error("Remove org-wide access failed:",C)}})}}}}function ka(t,a,n){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),o=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{existingShares:i}=ge({debouncedSearchQuery:"",resourceId:t||"",resourceType:s.ResourceType.DASHBOARD,userType:"tenant"}),d=A.useCallback(()=>{r.resetUserSelections()},[r]),m=A.useCallback(u=>{if(!t)return;const p={resourceType:s.ResourceType.DASHBOARD,resourceId:t,shareMutation:a,removeMutation:n,existingShares:i,resetUserSelections:d};St(u,p)},[t,a,n,i,d]),h=A.useCallback(()=>{if(!t)return;const u={resourceType:s.ResourceType.DASHBOARD,resourceId:t,removeMutation:n,existingShares:i,resetUserSelections:d};wt(l,o||"",c||"",u)},[t,a,n,i,d,l,o,c]);return{handleShareSubmit:m,handleRemoveAccess:h}}function Da(t,a,n){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),o=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{existingShares:i}=ge({debouncedSearchQuery:"",resourceId:t||"",resourceType:s.ResourceType.VISUAL,userType:"tenant"}),d=A.useCallback(()=>{r.resetUserSelections()},[r]),m=A.useCallback(u=>{if(!t)return;const p={resourceType:s.ResourceType.VISUAL,resourceId:t,shareMutation:a,removeMutation:n,existingShares:i,resetUserSelections:d};St(u,p)},[t,a,n,i,d]),h=A.useCallback(()=>{if(!t)return;const u={resourceType:s.ResourceType.VISUAL,resourceId:t,removeMutation:n,existingShares:i,resetUserSelections:d};wt(l,o||"",c||"",u)},[t,a,n,i,d,l,o,c]);return{handleShareSubmit:m,handleRemoveAccess:h}}function Ea(){const[t,a]=A.useState(""),[n,r]=A.useState(!1),[l,o]=A.useState(""),[c,i]=A.useState(""),[d,m]=A.useState(!1),[h,u]=A.useState(null),[p,f]=A.useState(!1),[j,x]=A.useState(null),[T,g]=A.useState(null),{setIsDashboardEditing:b,setIsVisualEditing:C}=s.useDashboardActions(),{handleEditLibraryVisual:O,handleAddLibraryVisual:S}=s.useVisualUtils(),{resources:E,isLoading:N,isError:D,createResource:w,updateResource:M,deleteResource:k,duplicateResource:R,shareResource:I,isCreating:v,isDeleting:y,removeResourceShares:L,isSharing:F,isRemovingShares:P,isUpdatingShares:_}=s.useVisualManagement(()=>{f(!1),x(null)},()=>{r(!1),o(""),i("")}),{handleShareSubmit:z,handleRemoveAccess:Q}=Da((h==null?void 0:h.id)||null,I,L);We();const Y=E.filter(B=>{var K,re;return((K=B==null?void 0:B.title)==null?void 0:K.toLowerCase().includes(t.toLowerCase()))||((re=B==null?void 0:B.description)==null?void 0:re.toLowerCase().includes(t.toLowerCase()))}),V=B=>new Date(B).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),q=()=>{l.trim()&&w({title:l,description:c,isPrivate:!1})},$=B=>{x(B),f(!0)},U=()=>{j&&k(j.id)},{startUpdating:H,stopUpdating:W,isUpdating:G}=s.useResourceUpdateState(),Z=(B,K)=>{const re=K.title!==void 0?"title":"description";H(B,re),M({resourceId:B,data:K},{onSuccess:()=>{W(B,re)},onError:()=>{W(B,re)}})},se=B=>{g(B),R(B,{onSettled:()=>g(null)})},ne=B=>{O(B)},ee=B=>{S(B)},ae=B=>{const K=E.find(re=>re.id===B);K&&M({resourceId:B,data:{isPrivate:!K.isPrivate}})},J=B=>{u(B),m(!0)};return s.useShareUsersToRemove(),s.useShareManagementActions(),ge({debouncedSearchQuery:"",resourceId:(h==null?void 0:h.id)||"",resourceType:s.ResourceType.VISUAL,userType:"tenant"}),N?e.jsx(ht,{}):D?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:n?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:B=>o(B.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:B=>i(B.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:!l.trim()||v,children:v?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),o(""),i("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:v,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>r(!0),className:"h-8 w-full",size:"sm",disabled:v,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),v?"Creating...":"Create New Visual"]})}),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:B=>a(B.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:"py-8 text-center text-muted-foreground",children:[e.jsx(He,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No visuals found"})]}):Y.map(B=>e.jsx(ua,{visual:B,onAddVisual:ee,onEditVisual:ne,onUpdateVisual:Z,onDeleteClick:$,onDuplicateVisual:se,onTogglePrivacy:ae,onShareVisual:J,isDeleting:y,isDuplicating:T===B.id,isTitleUpdating:G(B.id,"title"),isDescriptionUpdating:G(B.id,"description"),formatDate:V},B.id))})}),d&&h&&e.jsx(Ct,{resource:h,resourceType:s.ResourceType.VISUAL,onShare:z,isSharing:F,isRemoving:P,isUpdating:_,onClose:()=>{m(!1),u(null)},onRemoveAccess:Q}),e.jsx(s.AlertDialog,{open:p,onOpenChange:B=>{!B&&y||(f(B),B||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 "',j==null?void 0:j.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:y,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:B=>{B.preventDefault(),B.stopPropagation(),U()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:y,children:y?"Deleting...":"Delete"})]})]})})]})}function Ia({dashboard:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onLoadDashboard:o,onUpdateDashboard:c,onDeleteClick:i,onDuplicateDashboard:d,onShareDashboard:m,formatDate:h}){var O;const{selectDashboard:u}=s.useManagementActions(),p=s.useIsDashboardSelected(t.id),[f,j]=A.useState(!1),[x,T]=A.useState(!1);A.useEffect(()=>{n?(j(!0),T(!0)):x&&(j(!1),T(!1))},[n,x]);const g=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(nt,{className:"h-3 w-3 text-purple-500"}):e.jsx(me,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(fe,{className:"h-3.5 w-3.5 text-slate-500"}),b=()=>e.jsx(s.LayoutDashboard,{className:"h-4 w-4 text-slate-400"}),C=()=>{u(t),o(t.id)};return e.jsxs("div",{className:s.cn("group relative flex cursor-pointer items-start gap-3 px-4 py-3 dark:border-slate-800","cursor-pointer transition-colors duration-150 hover:bg-slate-50 dark:hover:bg-slate-900/50",t.ownership.isOwner&&"border-blue-200 dark:border-blue-800",p&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:C,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-slate-100 dark:bg-slate-800",children:b()})}),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(s.EditableText,{inputClassName:"text-sm font-medium text-slate-900 dark:text-slate-100",value:t.title,onSave:S=>c==null?void 0:c(t.id,{title:S}),isEditable:t.permissions.canEdit&&p,isPending:r,placeholder:"Untitled Dashboard",displayClassName:"line-clamp-1 max-w-[220px] text-sm font-medium text-slate-900 dark:text-slate-100"})}),e.jsx("div",{className:"shrink-0",children:g()})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx(s.EditableText,{inputClassName:"line-clamp-1 text-xs text-slate-500 dark:text-slate-400",value:t.description||"",onSave:S=>c==null?void 0:c(t.id,{description:S}),isEditable:t.permissions.canEdit&&p,isPending:l,placeholder:"No description",displayClassName:"mt-0.5 max-w-[250px] line-clamp-1 text-xs text-slate-500 dark:text-slate-400"})})]}),e.jsx("div",{className:"absolute right-3 top-2 flex items-center justify-between text-xs text-muted-foreground",children:e.jsx("div",{className:s.cn("flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100"),children:e.jsxs(s.DropdownMenu,{modal:!1,open:f,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 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:S=>S.stopPropagation(),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:S=>{S.preventDefault(),S.stopPropagation(),d(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),m(t)},children:[e.jsx(me,{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:S=>{S.stopPropagation(),i(t)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(fe,{className:"h-3 w-3"}),e.jsx("span",{children:((O=t.ownership.createdBy)==null?void 0:O.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 Aa({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 Ma(t){const[a,n]=A.useState(""),[r,l]=A.useState(!1),[o,c]=A.useState(""),[i,d]=A.useState(""),[m,h]=A.useState(!1),[u,p]=A.useState(null),[f,j]=A.useState(!1),[x,T]=A.useState(null),[g,b]=A.useState(null),C=s.useManagementStore(J=>J.lastSelectedDashboard),O=s.useManagementStore(J=>J.actions.selectDashboard);s.useShareManagementActions(),s.useShareUsersToRemove(),s.useShareSelectedTab(),s.useShareCurrentMode();const{resources:S,isLoading:E,isError:N,createResource:D,updateResource:w,deleteResource:M,duplicateResource:k,isCreating:R,isDeleting:I,isSharing:v,isRemovingShares:y,isUpdatingShares:L,shareResource:F,removeResourceShares:P}=s.useDashboardManagement(()=>{j(!1),T(null),C&&O(C)},()=>{l(!1),c(""),d("")}),{handleShareSubmit:_,handleRemoveAccess:z}=ka((u==null?void 0:u.id)||null,F,P),{currentUser:Q}=We(),Y=S.filter(J=>{var B,K;return((B=J==null?void 0:J.title)==null?void 0:B.toLowerCase().includes(a.toLowerCase()))||((K=J==null?void 0:J.description)==null?void 0:K.toLowerCase().includes(a.toLowerCase()))}),V=J=>new Date(J).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),q=()=>{o.trim()&&D({title:o,description:i,isPrivate:!1})},$=J=>{var B;(B=t.onLoadDashboard)==null||B.call(t,J)},U=J=>{T(J),j(!0)},H=()=>{x&&M(x.id)},W=J=>{b(J),k(J,{onSettled:()=>b(null)})},{startUpdating:G,stopUpdating:Z,isUpdating:se}=s.useResourceUpdateState(),ne=(J,B)=>{const K=B.title!==void 0?"title":"description";G(J,K),w({resourceId:J,data:B},{onSuccess:()=>{Z(J,K)},onError:()=>{Z(J,K)}})},ee=J=>{const B=S.find(K=>K.id===J);B&&w({resourceId:J,data:{isPrivate:!B.isPrivate}})},ae=J=>{p(J),Q==null||Q.type,h(!0)};return ge({debouncedSearchQuery:"",resourceId:(u==null?void 0:u.id)||"",resourceType:s.ResourceType.DASHBOARD,userType:"tenant"}),E?e.jsx(ht,{}):N?e.jsx(Aa,{onRetry:()=>window.location.reload()}):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: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:J=>c(J.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:J=>d(J.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:"h-8 w-full",size:"sm",disabled:R,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),R?"Creating...":"Create New Dashboard"]})}),e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:a,onChange:J=>n(J.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:"py-8 text-center text-muted-foreground",children:[e.jsx(On,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No dashboards found"})]}):Y.map(J=>e.jsx(Ia,{dashboard:J,isDeleting:I,isDuplicating:g===J.id,isTitleUpdating:se(J.id,"title"),isDescriptionUpdating:se(J.id,"description"),onLoadDashboard:$,onEditDashboard:t.onEditDashboard,onUpdateDashboard:ne,onDeleteClick:U,onDuplicateDashboard:W,onTogglePrivacy:ee,onShareDashboard:ae,formatDate:V},J.id))})}),m&&u&&e.jsx(Ct,{resource:u,resourceType:s.ResourceType.DASHBOARD,onShare:_,isSharing:v,isRemoving:y,isUpdating:L,onClose:()=>{h(!1),p(null)},onRemoveAccess:z}),e.jsx(s.AlertDialog,{open:f,onOpenChange:J=>{!J&&I||(j(J),J||T(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:I,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:J=>{J.preventDefault(),J.stopPropagation(),H()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:I,children:I?"Deleting...":"Delete"})]})]})})]})}function Tt({isOpen:t,onClose:a,className:n}){s.useDashboardStore(u=>u.dashboard);const{setDashboard:r,addSheet:l}=s.useDashboardStore(u=>u.actions),{currentUser:o}=We(),c=o,[i,d]=s.useLocalStorageState("resource-management-active-tab","dashboards"),m=u=>{},h=u=>{console.log("Editing dashboard:",u)};return e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{className:s.cn("absolute inset-y-0 left-0 z-[51] flex w-96 flex-col border-r bg-background shadow-lg transition-transform duration-300 ease-in-out",t?"translate-x-0":"-translate-x-full",n),children:[e.jsxs("div",{className:"flex items-center justify-between p-4",children:[e.jsx("div",{className:"flex items-center gap-3",children:c&&e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-muted bg-muted/30 px-2 py-1",children:[e.jsxs(s.Avatar,{className:"h-5 w-5",children:[e.jsx(s.AvatarImage,{alt:c.name}),e.jsx(s.AvatarFallback,{className:"text-xs",children:c.name.charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-xs font-medium",children:c.name})]})}),e.jsx(s.TooltipContent,{side:"bottom",className:"ml-2 max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"font-medium",children:c.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:c.email}),c.role&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Role:"," ",s.toTitleCase(c.role.replace(/_/g," "))]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",c.id]})]})})]})})}),e.jsx(s.IconButton,{className:"h-6 p-1 text-muted-foreground hover:text-foreground",onClick:a,tooltip:"Hide Dashboard Management",children:e.jsx(s.X,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:i,onValueChange:d,className:"flex h-9 grow flex-col",children:[e.jsx("div",{className:"px-5",children:e.jsxs(s.TabsList,{className:"grid h-8 w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"dashboards",className:"h-6",children:"Dashboards"}),e.jsx(s.TabsTrigger,{value:"visuals",className:"h-6",children:"Visuals"})]})}),e.jsx(s.TabsContent,{value:"dashboards",className:"flex-1",children:e.jsx(Ma,{onLoadDashboard:m,onEditDashboard:h})}),e.jsx(s.TabsContent,{value:"visuals",className:"flex-1",children:e.jsx(Ea,{})})]})})]})})}function La(){const{authToken:t}=s.useSemaphorContext();s.useDashboardStore(v=>v.theme);const a=s.useDashboardStore(v=>v.lenses),n=s.useDashboardStore(v=>v.selectedLensId),r=a==null?void 0:a.find(v=>v.id===n),l=s.useDashboardStore(v=>v.dashboard);s.useDashboardStore(v=>v.selectedSheetId);const o=s.useDashboardStore(v=>v.isDashboardEditing),c=s.useEditorStore(v=>v.card),i=s.useEditorStore(v=>v.selectedConnectionId),[d,m]=A.useState(!1),h=s.useDashboardStore(v=>v.isDashboardPanelOpen),u=s.useDashboardStore(v=>v.actions.setIsDashboardPanelOpen),p=s.useDashboardStore(v=>v.filterValues),f=s.useDashboardStore(v=>v.isVisualEditing),j=s.useDashboardStore(v=>v.showFilters);s.useDashboardStore(v=>v.showDashboardJSON);const x=s.useDashboardStore(v=>v.onSaveFunction),T=s.useDashboardStore(v=>v.actions.setShowFilters),{addFrame:g,setSelectedFrameId:b}=s.useDashboardStore(v=>v.actions),{getSelectedSheet:C,setIsDashboardEditing:O,setShowDashboardJSON:S}=s.useDashboardStore(v=>v.actions),E=C(),{tenantId:N,endUserId:D}=A.useMemo(()=>s.getTenantAndEndUserId(t==null?void 0:t.accessToken),[t==null?void 0:t.accessToken]),w=A.useMemo(()=>N||D,[N,D]),M=()=>{if(!o||!E)return;const v={dataSource:c.dataSource,mode:"explorer",connectionId:i,id:s.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},y={id:s.v4(),cards:[v],activeCardId:v.id};g(E.id,y),b(y.id)},k=()=>{O(!0)};async function R(){if(m(!0),!n||!r)return;const v=vs(l),y=JSON.stringify(v),L={...r,template:y,filterValues:p};await rs(L,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),x==null||x(v),m(!1)}if(f)return null;const I=(r==null?void 0:r.name)||l.title;return e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b py-1 pl-3 pr-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:"Manage Dashboards",onClick:()=>u(!0),className:"h-7 p-2",children:e.jsx(zn,{className:"h-4 w-4"})}),!f&&e.jsx(s.Label,{children:I})]}),e.jsxs("div",{className:"flex gap-2",children:[!1,!f&&e.jsx(ca,{}),!f&&e.jsx(mt,{}),o&&!f&&w&&e.jsx(oa,{}),!f&&w&&e.jsx(ia,{}),o&&!f&&e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",disabled:!o,onClick:M,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!f&&e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2",onClick:k,size:"sm",children:e.jsx(s.Pencil,{className:"h-4 w-4"})}),o&&!f&&e.jsx(s.IconButton,{className:"h-7 p-2",onClick:()=>{O(!1),S(!1)},children:e.jsx(s.Cross2Icon,{className:"h-4 w-4"})}),o&&!f&&w&&e.jsx(s.Button,{className:"h-7 p-2",variant:"ghost",disabled:d,onClick:R,size:"sm",children:e.jsx(s.Save,{className:"h-4 w-4"})}),!j&&!f&&o&&e.jsx(s.Button,{className:"h-7 p-2",variant:"ghost",onClick:()=>T(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!f&&o&&!1,!f&&!1,!f&&e.jsx(Tt,{isOpen:h,onClose:()=>u(!1)})]})]})}function Oa({name:t,items:a,value:n,onChange:r,isLoading:l,isError:o,refetch:c,className:i,icon:d,showNone:m=!1}){const h=ye.useRef(null),[u,p]=ye.useState(!1),[f,j]=ye.useState("100%"),x=m?[...a||[],{id:"none",name:"None"}]:a;ye.useLayoutEffect(()=>{h.current&&j(h.current.offsetWidth)},[]);function T(){var b;return l?"Loading...":o?"Error":n?(b=a==null?void 0:a.find(C=>C.id===n))==null?void 0:b.name:`Select ${t}`}function g(b,C){r(C),p(!1)}return e.jsxs(s.Popover,{open:u,onOpenChange:p,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{ref:h,variant:"outline",role:"combobox","aria-expanded":u,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:T()})]}),e.jsx(s.ChevronDown,{className:"size-4 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-full p-0",style:{minWidth:f},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(at,{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(b=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:b.name,onSelect:C=>g(C,b.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",n===b.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:b.name,children:b.name})]})},b.id))})]})]})})]})}function ke({title:t,items:a,value:n,isLoading:r,isError:l,refetch:o,onChange:c,showNone:i=!1,className:d,disabled:m=!1,type:h="combobox"}){const u=r?"Loading...":l?"Error":n;function p(){if(t==="Connection")return e.jsx(Kn,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(Wn,{className:"size-4"});if(t==="Table")return e.jsx(Je,{className:"size-4"});if(t==="Model")return e.jsx(yn,{className:"size-4"})}function f(){return e.jsxs(s.Select,{disabled:m,value:u,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(at,{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"),a&&a.map((x,T)=>e.jsx(s.SelectItem,{value:x.id,children:x.name},T))]}),(r||l)&&e.jsx(s.SelectItem,{value:u,children:u})]})})]})}function j(){return e.jsx(Oa,{icon:p(),items:a,value:u,onChange:c||(()=>{}),isLoading:r,isError:l,refetch:o,name:t,showNone:i})}return e.jsx(s.TooltipProvider$1,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:h==="select"?f():j()})})}function Ra({column:t}){const[a,n]=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:m}=s.useEditorAside(),h=s.useEditorStore(x=>x.actions.setSqlGen),u=s.useEditorStore(x=>x.actions.setCardSql),p=s.useEditorStore(x=>x.actions.setRunSql);function f(x,T){var O;const g=s.createSqlGenConfig(x,i,T),b=(O=d==null?void 0:d.find(S=>S.id===c))==null?void 0:O.name;h(g);const C=s.getSql(g,s.fmt(l||""),s.fmt(r),b||"",m,o||"");C&&(u(C),p(!0)),n(!1)}function j(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>f(t,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>f(t,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>f(t,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>f(t,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>f(t,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return e.jsxs(s.HoverCard,{openDelay:0,open:a,onOpenChange:n,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:j()})]})}function bs({column:t}){return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger$1,{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(fs,{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(ot,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(vn,{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 Qe({column:t,className:a}){return e.jsxs("div",{className:s.cn("flex min-h-8 grow items-center space-x-2 px-2 text-sm",a),children:[e.jsx(bs,{column:t}),e.jsx("span",{children:t.column_name})]})}function Ba({id:t,children:a,type:n="column"}){const{attributes:r,listeners:l,setNodeRef:o,transform:c}=s.useDraggable({id:t,data:{type:n}}),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:a})}function Fa({onClick:t,column:a}){const n=s.useDndStore(h=>h.activeId),r=s.useEditorStore(h=>{var u;return(u=h.card.queryConfig)==null?void 0:u.groupByColumns}),l=s.useEditorStore(h=>{var u;return(u=h.card.queryConfig)==null?void 0:u.metricColumns}),o=s.useEditorStore(h=>{var u;return(u=h.card.queryConfig)==null?void 0:u.filterColumns});function c(h){return i(h)||d(h)||m(h)}function i(h){return r==null?void 0:r.some(u=>u.name===h.column_name)}function d(h){return l==null?void 0:l.some(u=>u.name===h.column_name)}function m(h){return o==null?void 0:o.some(u=>u.name===h.column_name)}return e.jsxs("div",{onClick:()=>t(a),className:s.cn("relative grow overflow-x-hidden overflow-y-hidden rounded-md active:border active:border-dashed active:border-muted-foreground",{"bg-muted-foreground/10":c(a)}),children:[n===a.column_name&&e.jsx(s.DragOverlay,{children:e.jsx(Qe,{column:a,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),n===a.column_name&&e.jsx("div",{className:"absolute inset-0",children:n===a.column_name&&e.jsx(Qe,{column:a})}),e.jsx(Ba,{id:a.column_name,type:"column",children:e.jsx(Qe,{column:a})})]})}const Xe={id:"__placeholder__",role:"groupby",type:"string"},Ze={id:"__placeholder__",role:"groupby",type:"string"},es={id:"__placeholder__",role:"metric",type:"number"},ss={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},kt={id:"__placeholder__"},be="droppable-group-by",Ne="droppable-metrics",Ce="droppable-pivot-by",_e="sortable-group-by",ls="sortable-metrics",Ve="sortable-pivot-by",os="droppable-filters",is="sortable-filters",Ns="sortable-order-by";function za(){const t=s.useDndStore(v=>v.insertIndex),a=s.useEditorStore(v=>{var y;return((y=v.card.queryConfig)==null?void 0:y.groupByColumns)||[]}),n=s.useEditorStore(v=>{var y;return((y=v.card.queryConfig)==null?void 0:y.metricColumns)||[]}),r=s.useEditorStore(v=>{var y;return((y=v.card.queryConfig)==null?void 0:y.filterColumns)||[]}),l=s.useEditorStore(v=>{var y;return((y=v.card.queryConfig)==null?void 0:y.orderBy)||[]}),o=s.useEditorStore(v=>{var y;return((y=v.card.queryConfig)==null?void 0:y.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:i,setPreviewGroupByColumns:d,setPreviewMetricColumns:m,setPreviewFilterColumns:h,setPreviewPivotColumns:u}=s.useDndActions(),{setGroupByColumns:p,setMetricColumns:f,setFilterColumns:j,setOrderByColumns:x,setPivotByColumns:T}=s.useEditorActions(),{columns:g}=s.useDataColumns(),{formattedTableName:b}=s.useEditorAside(),C=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),O=v=>{var F;const{active:y,over:L}=v;if(((F=y.data.current)==null?void 0:F.type)==="column"&&L){const P=L.id,_=g.find(V=>V.column_name===y.id);if(!_)return;const z=s.isNumberDataType(_.data_type),Q=s.isTextDataType(_.data_type),Y=s.isDateDataType(_.data_type);if(Q||Y){if(a.some(q=>q.id===P)){const q=a.findIndex(U=>U.id===P);c(q);const $=a.filter(U=>U.id!==Xe.id);$.splice(q,0,Xe),d($)}else if(L.id===be){c(a.length);const q=[...a,Xe];d(q),m(n),h(r)}}if(Q||Y){if(o.some(q=>q.id===P)){const q=o.findIndex(U=>U.id===P);c(q);const $=o.filter(U=>U.id!==Ze.id);$.splice(q,0,Ze),u($)}else if(L.id===Ce){c(o.length);const q=[...o,Ze];u(q),d(a),m(n),h(r)}}if(z||Q){if(n.some(q=>q.id===P)){console.log("isOverMetricSortable",P);const q=n.findIndex(U=>U.id===P);c(q);const $=n.filter(U=>U.id!==es.id);$.splice(q,0,es),m($)}else if(L.id===Ne){c(n.length);const q=[...n,es];m(q),h(r),d(a),u(o)}}if(E(_)){if(r.some(q=>q.id===P)){const q=r.findIndex(U=>U.id===P);c(q);const $=r.filter(U=>U.id!==ss.id);$.splice(q,0,ss),h($)}else if(L.id===os){c(r.length);const q=[...r,ss];h(q),m(n),d(a),u(o)}}}else d(a),m(n),h(r),u(o)};function S(v){i(v.active.id),c(null),d(a),m(n),h(r),u(o)}function E(v){return!r.some(y=>y.name===v.column_name)}function N(v,y="SUM"){const{column_name:L,data_type:F}=v,P=[...n],_=t!==null?t:n.length,z={...v,id:ue(L),name:L,label:Le(L,y),type:F,role:"metric",aggregate:y};P.splice(_,0,z),f(P)}function D(v){const y=s.isTextDataType(v.data_type);s.isDateDataType(v.data_type);const L=[...o],F=t!==null?t:o.length;let P;y?P={...v,id:ue(v.column_name),name:v.column_name,type:v.data_type,role:"groupby"}:P={...v,id:ue(v.column_name),name:v.column_name,type:v.data_type,role:"groupby",label:De(v.column_name,"month"),granularity:"month"},L.splice(F,0,P),T(L)}function w(v){const y=s.isTextDataType(v.data_type);s.isDateDataType(v.data_type);const L=[...a],F=t!==null?t:a.length;let P;y?P={...v,id:ue(v.column_name),name:v.column_name,type:v.data_type,role:"groupby"}:P={...v,id:ue(v.column_name),name:v.column_name,type:v.data_type,role:"groupby",label:De(v.column_name,"month"),granularity:"month"},L.splice(F,0,P),p(L)}function M(v){const y=[...r],L=t!==null?t:r.length,F={...v,id:ue(v.column_name),name:v.column_name,type:v.data_type,sql:s.getDefaultFilterSql(v.data_type,b,s.fmt(v.column_name)),role:"filter"};y.splice(L,0,F),j(y)}function k(v){var P,_,z,Q,Y,V,q,$;const{active:y,over:L}=v,F=y.data.current;if((F==null?void 0:F.type)==="column"&&L){const U=g.find(Z=>Z.column_name===y.id);if(!U)return;const H=s.isNumberDataType(U.data_type),W=s.isTextDataType(U.data_type),G=s.isDateDataType(U.data_type);(W||G)&&(L.id===be||((P=L.data.current)==null?void 0:P.type)===_e)&&w(U),(W||G)&&(L.id===Ce||((_=L.data.current)==null?void 0:_.type)===Ve)?D(U):(H||W)&&(L.id===Ne||((z=L.data.current)==null?void 0:z.type)===ls)?(H&&N(U),W&&N(U,"COUNT")):E(U)&&(L.id===os||((Q=L.data.current)==null?void 0:Q.type)===is)&&M(U)}if(L&&((Y=L.data.current)==null?void 0:Y.type)===_e&&a.some(U=>U.id===y.id)){const U=a.findIndex(W=>W.id===y.id),H=a.findIndex(W=>W.id===L.id);if(U!==-1&&H!==-1&&U!==H){const W=[...a],[G]=W.splice(U,1);W.splice(H,0,G),p(W)}}if(L&&((V=L.data.current)==null?void 0:V.type)===Ve&&o.some(U=>U.id===y.id)){const U=o.findIndex(W=>W.id===y.id),H=o.findIndex(W=>W.id===L.id);if(U!==-1&&H!==-1&&U!==H){const W=[...o],[G]=W.splice(U,1);W.splice(H,0,G),T(W)}}if(L&&((q=L.data.current)==null?void 0:q.type)===ls&&n.some(U=>U.id===y.id)){const U=n.findIndex(W=>W.id===y.id),H=n.findIndex(W=>W.id===L.id);if(U!==-1&&H!==-1&&U!==H){const W=[...n],[G]=W.splice(U,1);W.splice(H,0,G),f(W)}}if(L&&(($=L.data.current)==null?void 0:$.type)===is&&r.some(U=>U.id===y.id)){const U=r.findIndex(W=>W.id===y.id),H=r.findIndex(W=>W.id===L.id);if(U!==-1&&H!==-1&&U!==H){const W=[...r],[G]=W.splice(U,1);W.splice(H,0,G),j(W)}}R(v),i(null),c(null),d(a),m(n),h(r),u(o)}function R(v){const{active:y,over:L}=v,F=y.data.current;if((F==null?void 0:F.type)===Ns&&L){const P=l.findIndex(z=>Ie(z.columnId)===y.id),_=l.findIndex(z=>Ie(z.columnId)===L.id);if(P!==-1&&_!==-1&&P!==_){const z=[...l],[Q]=z.splice(P,1);z.splice(_,0,Q),x(z)}}}function I(){i(null),c(null),d(a),m(n),h(r)}return{handleDragOver:O,handleDragEnd:k,handleDragStart:S,handleDragCancel:I,sensors:C}}function ue(t){return`${t}-${s.v4()}`}function Le(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function Ie(t){return`${Ns}-${t}`}function De(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function Pa({schemaName:t,tableName:a,columns:n,status:r}){const l=s.useEditorStore(y=>y.sqlGen),o=s.useEditorStore(y=>y.isDevMode),c=s.useEditorStore(y=>y.selectedConnectionId),i=s.useEditorStore(y=>{var L,F;return(F=(L=y.card)==null?void 0:L.queryConfig)==null?void 0:F.metricColumns});s.useEditorStore(y=>{var L,F;return(F=(L=y.card)==null?void 0:L.queryConfig)==null?void 0:F.groupByColumns});const d=s.useEditorStore(y=>y.selectedDatabaseName),m=s.useEditorStore(y=>y.selectedSchemaName),h=s.useEditorStore(y=>y.selectedTableName),u=s.useEditorStore(y=>y.selectedDatamodelId),p=s.useDashboardStore(y=>y.dashboard.aiScopeTables),{addToAIScope:f,removeFromAIScope:j}=s.useDashboardActions(),{addColumnToMetricColumns:x,addColumnToGroupBy:T,setCardSql:g,setRunSql:b,setSqlGen:C,setIsShowingVisual:O}=s.useEditorActions(),{connectionType:S,modelItems:E,selectedDatamodelName:N}=s.useEditorAside();function D(y){var L;if(o){const F=s.createSqlGenConfig(y,l);C(F);const P=(L=E==null?void 0:E.find(z=>z.id===u))==null?void 0:L.name,_=s.getSql(F,s.fmt(t),s.fmt(a),P||"",S,d||"");_&&(g(_),b(!0))}if(!o){if(s.isTextDataType(y.data_type))if(i&&i.length>0){const F={...y,role:"groupby",id:ue(y.column_name),name:y.column_name,type:y.data_type};T(F)}else{const F={...y,role:"metric",id:ue(y.column_name),name:y.column_name,label:Le(y.column_name,"COUNT"),type:y.data_type,aggregate:"COUNT"};x(F)}if(s.isDateDataType(y.data_type)){const F={...y,role:"groupby",id:ue(y.column_name),name:y.column_name,type:y.data_type,label:De(y.column_name,"month"),granularity:"month"};T(F)}if(s.isNumberDataType(y.data_type)){const F={...y,role:"metric",id:ue(y.column_name),name:y.column_name,label:Le(y.column_name,"SUM"),type:y.data_type,aggregate:"SUM"};x(F)}}}function w(y){y===!0&&(h||N)&&c?(f({connectionId:c,connectionType:S==="S3"||S==="API"?"DuckDb":S||"",databaseName:d||"",schemaName:m||"",tableName:h||"",datamodelName:s.resolveDatamodelName(N),datamodelId:u||""}),s.ue.success("Added to Assistant Scope",{position:"top-right",duration:2500,richColors:!0})):(j({connectionId:c||"",connectionType:S||"",tableName:h||"",datamodelName:s.resolveDatamodelName(N),datamodelId:u||"",databaseName:d||"",schemaName:m||""}),s.ue("Removed from Assistant Scope",{position:"top-right",duration:2e3,richColors:!0}))}function M(){const y=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:N,connectionType:S,databaseName:d||""});O(!1);const L=S==="MSSQL"?`SELECT top 10 * FROM ${y}`:`SELECT * FROM ${y} LIMIT 10`;g(L),b(!0)}function k(){const y=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:N,connectionType:S,databaseName:d||""});g(`SELECT COUNT(*) as count FROM ${y}`),b(!0)}function R(){return(p==null?void 0:p.find(y=>y.connectionId===c&&(y.tableName===h||y.datamodelName===N)))!==void 0}function I(y){return o?e.jsxs("div",{className:"flex grow items-center justify-between space-x-2 rounded-md px-2 py-1",onClick:()=>D(y),children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(bs,{column:y}),e.jsx("span",{children:y.column_name})]}),e.jsx("div",{onClick:L=>L.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(y.data_type)&&e.jsx(Ra,{column:y})})]}):e.jsx(Fa,{onClick:D,column:y})}function v(){return e.jsxs(e.Fragment,{children:[e.jsxs(s.Toggle,{title:`${R()?"Remove from":"Add to"} Assistant Scope`,pressed:R(),onPressedChange:w,variant:"outline",className:s.cn("h-9 px-2",{}),children:[e.jsx(s.Plus,{className:s.cn("mr-1 size-4",{"text-green-400":R(),"text-muted-foreground":!R()})}),"AI"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:M,size:"sm",variant:"secondary",className:"flex",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(qn,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:k,size:"sm",variant:"secondary",className:"w-full",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(rt,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-6",children:Array.from({length:3}).map((y,L)=>e.jsx(s.Skeleton,{className:"h-7 w-full"},L))}):e.jsxs("div",{className:"flex grow flex-col space-y-4 px-4",children:[o&&e.jsx("div",{className:"mx-2 flex items-center justify-center gap-2",children:v()}),e.jsxs(s.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-2 py-0",children:[e.jsx("div",{className:"flex flex-col gap-1",children:n==null?void 0:n.map(y=>e.jsx("div",{className:s.cn("mr-2 cursor-pointer rounded-md text-sm transition-colors hover:bg-muted"),children:I(y)},y.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Dt({ColumnsComponent:t,type:a}){var je;const n=s.useEditorStore(te=>te.card),r=s.useEditorStore(te=>te.selectedConnectionId),l=s.useDashboardStore(te=>te.showFilters),o=s.useEditorStore(te=>te.selectedDatamodelId),c=s.useEditorStore(te=>te.selectedDatabaseName),i=s.useEditorStore(te=>te.selectedSchemaName),d=s.useEditorStore(te=>te.selectedTableName),m=s.useEditorStore(te=>te.isDevMode),{setSelectedTableName:h,setIsDevMode:u,setCardSql:p}=s.useEditorActions(),{connectionItems:f,modelItems:j,schemaItems:x,databaseItems:T,tableItems:g,columns:b,isConnectionsLoading:C,isModelsLoading:O,isConnectionsError:S,isModelsError:E,isDatabasesLoadingOrFetching:N,isDatabaseError:D,isSchemaLoadingOrFetching:w,isSchemaError:M,isColumnsError:k,isColumnsLoadingOrFetching:R,isTableLoadingOrFetching:I,isTableError:v,connectionType:y,isNonDbConnection:L,refetchDatabases:F,refetchModels:P,refetchSchemas:_,refetchTables:z,refetchColumns:Q,refetchConnections:Y,handleConnectionChange:V,handleDatabaseChange:q,handleSchemaChange:$,handleDatamodelChange:U,handleTableChange:H,tableName:W,schemaName:G}=s.useEditorAside(),{data:Z,refetch:se}=s.useDashboardCardQuery(n);function ne(){return t?t(G,W,b):e.jsx(Pa,{schemaName:G,tableName:W,columns:b,status:R?"Loading...":k?"Error":"Success"})}function ee(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function ae(te){te===!0?Z&&(p(Z.userSql),setTimeout(()=>{se()},100)):p(""),u(te)}function J(){if(!r||y==="S3"||y==="API")return null;if(!o||o==="none")return e.jsx(ke,{refetch:F,showNone:!0,onChange:q,isError:D,isLoading:N,items:T,value:c||"",title:"Database",type:"combobox"})}function B(){if(r&&!L&&(!c||c==="none")&&(!o||o==="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 K(){if(!r||y==="S3"||y==="API")return null;if(!c||c==="none")return e.jsx(ke,{refetch:P,showNone:!0,onChange:U,isError:E,isLoading:O,items:j,value:o||"",title:"Model",type:"combobox"})}function re(){return!r||y==="S3"||y==="API"||!c||c==="none"?null:e.jsx(ke,{refetch:_,onChange:$,isError:M,isLoading:w,items:x,value:i||"",title:"Schema",type:"combobox"})}function he(){function te(){let le=!1;return y==="API"?(le=!1,le):((y==="S3"||r&&c&&c!=="none"&&i)&&(le=!0),le)}return te()?e.jsx(ke,{refetch:z,onChange:H,isError:v,items:g,isLoading:I,value:d||"",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]":!l}),children:[e.jsxs("section",{className:"space-y-3 px-6 py-4",children:[e.jsx(ke,{refetch:Y,items:f,title:"Connection",value:r||"",onChange:V,isLoading:C,isError:S,type:"combobox",connectionTooltip:((je=f==null?void 0:f.find(te=>te.id===r))==null?void 0:je.type)||""}),J(),B(),K(),re(),he()]}),ne(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:a==="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:m,onCheckedChange:ae,id:"dev-mode"}),e.jsx(s.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(s.Button,{onClick:ee,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(Hn,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function Et({error:t,className:a="",textClassName:n="",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 m(p){(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),d())}function h(){const p=window.getSelection();if(p&&p.toString().trim()!==""){const f=p.toString();navigator.clipboard.writeText(f),o(!0),i.current=!0,setTimeout(()=>{o(!1),i.current=!1},1e3)}else i.current=!1}function u(){o(!1),i.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${a}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:c,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${n}`,onClick:d,onKeyDown:m,onMouseUp:h,onMouseDown:u,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 It({sql:t,error:a,onDebugWithAssistant:n}){const r=s.useEditorStore(d=>d.isDevMode),{setIsDevMode:l,setCardSql:o,setRunSql:c}=s.useEditorActions();function i(){l(!r),o(t),setTimeout(()=>{c(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-2",children:[e.jsxs(s.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[a&&e.jsx(Et,{error:a}),t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"rounded-md",children:e.jsx(s.CodeHighlighter,{code:t,language:"sql"})})})]}),!r&&t&&e.jsxs(s.Button,{onClick:i,variant:"secondary",size:"sm",children:[e.jsx(In,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),a&&n&&e.jsxs(s.Button,{onClick:n,size:"sm",variant:"secondary",children:[e.jsx(Fn,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function At({sql:t,error:a,onDebugWithAssistant:n}){return e.jsxs(s.HoverCard,{openDelay:a?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:a?e.jsx(st,{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-[600px]",children:e.jsx(It,{sql:t,error:a,onDebugWithAssistant:n})})]})}var Mt={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},Gs=A.createContext&&A.createContext(Mt),_a=["attr","size","title"];function Va(t,a){if(t==null)return{};var n=Ua(t,a),r,l;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);for(l=0;l<o.length;l++)r=o[l],!(a.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(n[r]=t[r])}return n}function Ua(t,a){if(t==null)return{};var n={};for(var r in t)if(Object.prototype.hasOwnProperty.call(t,r)){if(a.indexOf(r)>=0)continue;n[r]=t[r]}return n}function Ue(){return Ue=Object.assign?Object.assign.bind():function(t){for(var a=1;a<arguments.length;a++){var n=arguments[a];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},Ue.apply(this,arguments)}function Hs(t,a){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);a&&(r=r.filter(function(l){return Object.getOwnPropertyDescriptor(t,l).enumerable})),n.push.apply(n,r)}return n}function qe(t){for(var a=1;a<arguments.length;a++){var n=arguments[a]!=null?arguments[a]:{};a%2?Hs(Object(n),!0).forEach(function(r){qa(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Hs(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function qa(t,a,n){return a=$a(a),a in t?Object.defineProperty(t,a,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[a]=n,t}function $a(t){var a=Ga(t,"string");return typeof a=="symbol"?a:a+""}function Ga(t,a){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,a);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(a==="string"?String:Number)(t)}function Lt(t){return t&&t.map((a,n)=>A.createElement(a.tag,qe({key:n},a.attr),Lt(a.child)))}function Se(t){return a=>A.createElement(Ha,Ue({attr:qe({},t.attr)},a),Lt(t.child))}function Ha(t){var a=n=>{var{attr:r,size:l,title:o}=t,c=Va(t,_a),i=l||n.size||"1em",d;return n.className&&(d=n.className),t.className&&(d=(d?d+" ":"")+t.className),A.createElement("svg",Ue({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,c,{className:d,style:qe(qe({color:t.color||n.color},n.style),t.style),height:i,width:i,xmlns:"http://www.w3.org/2000/svg"}),o&&A.createElement("title",null,o),t.children)};return Gs!==void 0?A.createElement(Gs.Consumer,null,n=>a(n)):a(Mt)}function Ja(t){return Se({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 Ot(t){const{theme:a}=s.useTheme(),n=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:m}=s.useEditorActions(),h=A.useRef(),u=A.useRef({}),p=r.cards.find(x=>x.id===o),f=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(h.current&&c){const x=h.current.getModel();x&&(u.current[l.id]=x);let T=u.current[o];if(!T){const g=f();T=c.editor.createModel(g,t),u.current[o]=T}h.current.setModel(T)}d(o,l),m(!0)}},[o,l,d,c,m,t,f]),A.useEffect(()=>{if(!c)return;const x=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",T=n==="system"?x:n;c.editor.defineTheme("default",{base:T==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":T==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[a,n,c]),A.useEffect(()=>{const x=h.current;x&&c&&l&&x.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return i(),!1})},[c,i,l]);function j(x,T){if(h.current=x,!u.current[l.id]){const g=x.getModel(),b=f();u.current[l.id]=g||(T==null?void 0:T.editor.createModel(b,t))||x.getModel()}x.setModel(u.current[l.id])}return{handleEditorDidMount:j}}function Wa(){const t=s.useEditorStore(c=>c.card.sql),a=s.useEditorStore(c=>c.sqlGen),{setCardSql:n,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=Ot("sql");function o(c){n(c),s.isObjectEmpty(a)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:o,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function Ya(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:a}=s.useEditorActions(),{handleEditorDidMount:n}=Ot("python");function r(l){a(l)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:n})}function Ka({jsonString:t}){return e.jsx(s.Ft,{theme:"default",defaultLanguage:"json",className:"mt-1 min-h-[220px]",value:t,options:{readOnly:!0,minimap:{enabled:!1},lineNumbers:"off",glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})}function Qa(){const t=s.useQueryClient(),[a,n]=A.useState(!1),[r,l]=A.useState(!1);s.useEditorStore(z=>z.frame);const o=s.useEditorStore(z=>z.card);s.useEditorStore(z=>z.isShowingVisual),s.useEditorStore(z=>z.selectedConnectionId),s.useEditorStore(z=>z.tempQueryData),s.useEditorStore(z=>z.selectedDatabaseName),s.useEditorStore(z=>z.selectedDatamodelId),s.useEditorStore(z=>z.selectedSchemaName);const c=s.useEditorStore(z=>z.showAIDialog);s.useEditorStore(z=>z.selectedTableName);const i=s.useEditorStore(z=>{var Q;return(Q=z==null?void 0:z.card)==null?void 0:Q.sql}),d=s.useEditorStore(z=>{var Q;return(Q=z==null?void 0:z.card)==null?void 0:Q.python}),{sheetFilterValues:m}=s.useSheetFilterValues(),{setCardCustomCfg:h,setQueryResultColumns:u,setCardSql:p,setTempQueryData:f,setPythonStdOut:j,setCardPreferences:x,setCardType:T,setCardPython:g,runAssistant:b,setShowAIDialog:C}=s.useEditorActions();s.useEditorStore(z=>z.onSave),s.useEditorStore(z=>z.onClose),s.useEditorStore(z=>z.actions.setSqlGen);const O=s.useEditorStore(z=>z.runSql),S=s.useEditorStore(z=>z.actions.setRunSql),E=s.useEditorStore(z=>z.actions.setIsSqlRunning),{data:N,isLoading:D,isFetching:w,isSuccess:M,isError:k,error:R,queryKey:I,refetch:v,errorMessage:y}=s.useDashboardCardQuery(o);A.useEffect(()=>{if(N&&(N.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),j((N==null?void 0:N.output)||""),N.records.length>0)){const{dimensionKeys:z}=s.getKeys(N.records);u(z)}},[N,u,j]),A.useEffect(()=>{(D||w)&&E(!0),(k||M)&&E(!1),k&&(u([]),j(""))},[D,w,N,j,k,M,E,u,R]),A.useEffect(()=>{O&&(t.getQueryData(I)||v(),S(!1))},[O,v,S,I,t]);async function L(){const z=`Can you help me debug this query in the current table scope?
401
+ */const me=s.createLucideIcon("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);function vs(t){var a;return{...t,sheets:(a=t==null?void 0:t.sheets)==null?void 0:a.map(n=>{var r;return{...n,frames:(r=n.frames)==null?void 0:r.map(l=>{var o;return{...l,cards:(o=l.cards)==null?void 0:o.map(c=>ct(c))}})}})}}function ct(t){return{...t,customCfg:ra(t.customCfg),data:[]}}function ra(t){var a,n;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(n=(a=t==null?void 0:t.data)==null?void 0:a.datasets)==null?void 0:n.map(r=>({...r,data:[]}))}}:null}async function la(t,a,n,r){if(!r)return null;const l=JSON.stringify(a);return await s.postRequest("https://semaphor.cloud/api/v1/lens",r,{name:t,template:l,filterValues:n,operation:"create"})}async function rs(t,a){if(!a)return null;const{id:n,template:r,filterValues:l,isDefault:o,shared:c}=t;return await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{lensId:n,template:r,filterValues:l,isDefault:o,shared:c,operation:"update"})}async function oa(t,a){return a?await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{operation:"delete",lensId:t}):null}function ia(){const[t,a]=M.useState(""),[n,r]=M.useState(!1),l=s.useDashboardStore(x=>x.lenses),{setLenses:o,setSelectedLensId:c}=s.useDashboardActions(),[i,d]=M.useState(!1),[m,h]=M.useState(!1),u=s.useDashboardStore(x=>x.dashboard),p=s.useDashboardStore(x=>x.filterValues),{authToken:j}=s.useSemaphorContext();async function f(){d(!0);const x=vs(u),S=await la(t,x,p,j==null?void 0:j.accessToken);S&&(o([...l||[],S]),c(S.id),h(!1)),d(!1)}return e.jsxs(s.Dialog,{open:m,onOpenChange:h,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:x=>{a(x.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),n&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{size:"sm",variant:"outline",type:"submit",onClick:f,disabled:i,children:i?"Creating...":"Add"})})]})]})}function ca(){const[t,a]=M.useState(!1),n=s.useDashboardStore(h=>h.lenses),r=s.useDashboardStore(h=>h.selectedLensId),{setLenses:l,setSelectedLensId:o}=s.useDashboardActions(),{authToken:c}=s.useSemaphorContext();async function i(h){o(h)}async function d(h){if(await oa(h,c==null?void 0:c.accessToken)){const p=n==null?void 0:n.filter(j=>j.id!==h);l(p||[]),o("original")}}async function m(h){const u=n==null?void 0:n.map(f=>f.id===h.id?{...f,isDefault:!h.isDefault}:{...f,isDefault:!1});l(u||[]);const p={...h,isDefault:!h.isDefault};await rs(p,c==null?void 0:c.accessToken);const j=n==null?void 0:n.find(f=>f.isDefault);if(j&&j.id!==h.id){const f={...j,isDefault:!1};await rs(f,c==null?void 0:c.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:a,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(Bn,{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:i,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),n==null?void 0:n.map(h=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:h.id,children:[e.jsx("p",{children:h.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:u=>{u.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:u=>{u.preventDefault(),d(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 dt(){var o;const t=s.useDashboardStore.getState().authToken,a=s.useDashboardStore.getState().theme,n=s.useDashboardStore.getState().filterValues,r=(o=s.useDashboardStore.getState().dashboard)==null?void 0:o.title,l=s.useDashboardStore.getState().selectedSheetId;return{authToken:t,theme:a||"light",filterValues:n,dashboardTitle:r||"",selectedSheetId:l||""}}async function ut(){const t=s.useDashboardStore.getState().isDownloadingPdf,{authToken:a,theme:n,filterValues:r,dashboardTitle:l,selectedSheetId:o}=dt();if(t)return;const c=new URLSearchParams;c.set("token",(a==null?void 0:a.accessToken)||""),c.set("theme",n),c.set("filterValues",JSON.stringify(r)),c.set("selectedSheetId",o||"");const i=`https://semaphor.cloud/api/v1/generate-pdf?params=${encodeURIComponent(c.toString())}`;s.useDashboardStore.setState({isDownloadingPdf:!0});const h=(await(await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${a==null?void 0:a.accessToken}`}})).json()).url,u=document.createElement("a");u.href=h;const p=`${l}-${new Date().toISOString()}.pdf`;u.download=p,u.click(),s.useDashboardStore.setState({isDownloadingPdf:!1})}function da({iconClassName:t}){const{authToken:a}=s.useSemaphorContext();s.useDashboardStore(l=>{var o;return(o=l.dashboard)==null?void 0:o.title}),s.useDashboardStore(l=>l.theme),s.useDashboardStore(l=>l.filterValues);const n=s.useDashboardStore(l=>l.isDownloadingPdf);async function r(){await ut()}return e.jsx(s.IconButton,{tooltip:"Download PDF",className:"h-7 p-2",onClick:r,children:n?e.jsx(s.LoaderCircle,{className:s.cn("size-3.5 animate-spin",t)}):e.jsx(s.Download,{className:s.cn("size-4",t)})})}function ce({defaultValue:t,label:a,options:n,value:r,onValueChange:l,className:o,icon:c,showPlaceholderLabel:i=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:l,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",o),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),i&&e.jsx(s.SelectValue,{placeholder:a})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:a}),n.map(d=>e.jsx(s.SelectItem,{value:d.value,children:d.label},d.value))]})})]})}const Vs=[{value:"daily",label:"Daily"},{value:"weekly",label:"Weekly"},{value:"biweekly",label:"Bi-Weekly"},{value:"monthly",label:"Monthly"}];function mt({triggerButtonClassName:t}){const{data:a,handleScheduleSubscription:n,handleDeleteSubscription:r,status:l,error:o,isDeleting:c}=ua(),[i,d]=M.useState(""),[m,h]=M.useState(Vs[0].value),[u,p]=M.useState("06:00"),[j,f]=M.useState("");return e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Schedule Dashboard",className:s.cn("h-7 p-2",t),children:e.jsx(s.Clock,{className:"size-4"})})}),e.jsx(s.PopoverContent,{align:"end",className:"w-80",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Schedule Subscription"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribe to receive dashboard via email"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"email",children:"Email"}),e.jsx(s.Input,{id:"email",value:i,onChange:x=>d(x.target.value),className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"subject",children:"Subject"}),e.jsx(s.Input,{id:"subject",placeholder:"Monthly Sales Report",value:j,onChange:x=>{f(x.target.value.replace(/[^a-zA-Z0-9\s-_]/g,""))},className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"frequency",children:"Frequency"}),e.jsx(ce,{className:"col-span-2 h-8",label:"Select Frequency",options:Vs,value:m,onValueChange:x=>h(x)})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"time",children:"Time"}),e.jsx(s.Input,{id:"time",type:"time",value:u,onChange:x=>p(x.target.value),className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsx("div",{className:"mt-2 flex justify-end",children:e.jsxs(s.Button,{onClick:async()=>{await n({email:i,frequency:m,time:u,subject:j}),p("00:00"),d(""),f("")},className:"h-8 p-2",disabled:l==="loading"||!i,children:[l==="loading"&&e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin"}),l==="success"&&e.jsx(s.Check,{className:"mr-2 size-4"}),l==="error"&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{children:e.jsx(st,{className:"mr-2 size-4 text-destructive"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{children:o})})]}),"Schedule"]})}),a&&a.length>0&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Subscriptions"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Active email subscriptions"})]}),s.isDevEnv]})}),e.jsx("div",{className:"grid gap-2",children:a==null?void 0:a.map(x=>e.jsxs("div",{className:"group grid grid-cols-5 gap-3",children:[e.jsx("div",{className:"col-span-3 text-sm",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"boder-border rounded-md border bg-muted px-2 py-1",children:[s.titleCase(x.frequency)," "]}),e.jsx(s.Label,{children:x.time})]})}),e.jsxs("div",{className:"col-span-2 flex items-center justify-end gap-4",children:[e.jsx(Us,{tooltip:`Next Run: ${new Date(x.nextRun).toLocaleString()} ${x.timezone}`,children:e.jsx(Sn,{className:"size-3.5"})}),e.jsx(Us,{tooltip:`${x.endUserEmail}`,children:e.jsx(Gn,{className:"size-3.5"})}),c===x.id?e.jsx(s.LoaderCircle,{className:"size-3.5 animate-spin"}):e.jsx(s.Trash2,{onClick:()=>r(x.id),className:"size-3.5 cursor-pointer"})]})]},x.id))})]})]})]})})]})})}const Us=({children:t,tooltip:a})=>e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:t}),e.jsx(s.TooltipContent,{children:a})]})});function ua(){const[t,a]=M.useState("idle"),[n,r]=M.useState(""),[l,o]=M.useState(null),c=s.useDashboardStore(N=>N.authToken),i=s.useDashboardStore(N=>N.dashboard.id),d=s.useDashboardStore(N=>N.dashboard.title),{endUserId:m}=s.getTenantAndEndUserId((c==null?void 0:c.accessToken)||""),h="https://semaphor.cloud/api/v1/subscriptions/get",u={dashboardId:i,endUserId:m},{data:p,isLoading:j,isError:f,isFetching:x,refetch:S}=s.useQuery({queryKey:["subscriptions",i,m],queryFn:()=>s.getRequest(h,(c==null?void 0:c.accessToken)||"",u),enabled:!!(c!=null&&c.accessToken)&&!!i&&!!m});async function g({email:N,subject:O,frequency:C,time:D}){const{authToken:b,...k}=dt(),w=Intl.DateTimeFormat().resolvedOptions().timeZone,L={email:N,frequency:C,time:D,timezone:w,endUserId:m,endUserEmail:N,subject:O||d||"Scheduled Dashboard",dashboardId:i,dashboardParams:k};a("loading");const T="https://semaphor.cloud/api/v1/subscriptions/create";try{const R=await s.postRequestRegular(T,(b==null?void 0:b.accessToken)||"",{...L});a("success"),r(""),S(),setTimeout(()=>{a("idle")},2e3)}catch(R){console.error(R),a("error"),r(R.message)}}async function v(N){const O="https://semaphor.cloud/api/v1/subscriptions/delete";o(N);try{await s.postRequestRegular(O,(c==null?void 0:c.accessToken)||"",{id:N}),S(),setTimeout(()=>{o(null)},2e3)}catch(C){console.error(C),o(null),a("error"),r(C.message)}}return{data:p,isLoading:j,isFetching:x,isError:f,isDeleting:l,refetch:S,handleScheduleSubscription:g,handleDeleteSubscription:v,status:t,error:n}}function We(){const{authToken:t,tokenProps:a}=s.useSemaphorContext();let n=null;a&&(a.endUserId&&a.endUserEmail&&a.tenantId?n={id:a.endUserId,name:a.endUserEmail?String(a.displayName):"",email:a.endUserEmail?String(a.endUserEmail):"",type:"tenant",tenantId:a.tenantId}:a.orgUserId&&a.orgUserEmail&&(n={id:a.orgUserId,name:a.orgUserEmail?String(a.displayName):"",email:a.orgUserEmail?String(a.orgUserEmail):"",type:"organization"}));const{data:r,isLoading:l,isError:o}=s.useQuery({queryKey:["userInfo",n==null?void 0:n.id],queryFn:async()=>{if(!(n!=null&&n.id))return;const i=await fetch(`https://semaphor.cloud/api/management/v1/unified-users/${n.id}`,{headers:{Authorization:`Bearer ${(t==null?void 0:t.accessToken)||""}`,"Content-Type":"application/json"}});if(!i.ok)throw new Error("Failed to fetch user info");return(await i.json()).user},enabled:!!(t!=null&&t.accessToken)&&!!(n!=null&&n.id)});return{currentUser:n?{...n,...r||{}}:null,isLoading:l,isError:o}}function ht(){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,a)=>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"})})})]})]})},a))})]})})}function ma({visual:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onAddVisual:o,onEditVisual:c,onUpdateVisual:i,onDeleteClick:d,onDuplicateVisual:m,onShareVisual:h,formatDate:u}){var C;const{selectVisual:p}=s.useManagementActions(),j=s.useIsVisualSelected(t.id),[f,x]=M.useState(!1),[S,g]=M.useState(!1);M.useEffect(()=>{n?(x(!0),g(!0)):S&&(x(!1),g(!1))},[n,S]);const v=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(nt,{className:"h-3 w-3 text-purple-500"}):e.jsx(me,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(fe,{className:"h-3.5 w-3.5 text-slate-500"}),N=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4 text-slate-400"}),O=()=>{p(t),c==null||c(t)};return e.jsxs("div",{className:s.cn("group relative flex cursor-pointer items-start gap-3 px-4 py-3 dark:border-slate-800","cursor-pointer transition-colors duration-150 hover:bg-slate-50 dark:hover:bg-slate-900/50",t.ownership.isOwner&&"border-blue-200 dark:border-blue-800",j&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:O,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-slate-100 dark:bg-slate-800",children:N()})}),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(s.EditableText,{inputClassName:"text-sm font-medium text-slate-900 dark:text-slate-100",value:t.title,onSave:D=>i==null?void 0:i(t.id,{title:D}),isEditable:t.ownership.isOwner&&j,isPending:r,placeholder:"Untitled Visual",displayClassName:"line-clamp-1 max-w-[150px] text-sm font-medium text-slate-900 dark:text-slate-100"})}),e.jsx("div",{className:"shrink-0",children:v()})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx(s.EditableText,{inputClassName:"line-clamp-1 text-xs text-slate-500 dark:text-slate-400",value:t.description||"",onSave:D=>i==null?void 0:i(t.id,{description:D}),isEditable:t.ownership.isOwner&&j,isPending:l,placeholder:"No description",displayClassName:"mt-0.5 max-w-[220px] line-clamp-1 text-xs text-slate-500 dark:text-slate-400"})})]}),e.jsx("div",{className:"absolute right-3 top-2 flex items-center justify-between text-xs text-muted-foreground",children:e.jsxs("div",{className:s.cn("flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100"),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:D=>{D.stopPropagation(),o(t)},children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:f,onOpenChange:x,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:D=>D.stopPropagation(),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:D=>{D.stopPropagation(),o(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:D=>{D.preventDefault(),D.stopPropagation(),m(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:D=>{D.stopPropagation(),c==null||c(t)},children:[e.jsx(Kn,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:D=>{D.stopPropagation(),h(t)},children:[e.jsx(me,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:D=>{D.stopPropagation(),d(t)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(fe,{className:"h-3 w-3"}),e.jsx("span",{children:((C=t.ownership.createdBy)==null?void 0:C.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:u(t.lastModified)})]})]})]})]})]})})]})]},t.id)}function xt({value:t,onChange:a,placeholder:n="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:n,value:t,onChange:r=>a(r.target.value),className:"pl-9"})]})}function Pe({currentRole:t,onRoleChange:a,roleOptions:n,disabled:r=!1,className:l="",allowDropdown:o=!0}){var d;const c=((d=n.find(m=>m.value===t))==null?void 0:d.label)||t,i=n.filter(m=>m.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}`,onClick:()=>console.log("Badge clicked:",{currentRole:t,disabled:r,allowDropdown:o}),children:c})}),e.jsx(s.DropdownMenuContent,{className:"z-[51]",children:i.map(m=>e.jsx(s.DropdownMenuItem,{onClick:()=>{console.log("Dropdown item clicked:",{currentRole:t,newRole:m.value,disabled:r}),a(m.value)},disabled:r,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.description})]})},m.value))})]}):e.jsx(s.Badge,{variant:"outline",className:`text-xs ${l}`,children:c})}function pt({selectedUsers:t,selectedUserObjects:a,onRemove:n,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=>n(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:a.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(Pe,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:d=>r(o.id,d),roleOptions:i}),e.jsx("button",{onClick:()=>n(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 ft({usersToRemove:t,allUsers:a,onRemove:n}){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=>n(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:a.filter(r=>t.includes(r.id)).map(r=>e.jsxs(s.Badge,{variant:"destructive",className:"gap-1",children:[r.name,e.jsx("button",{onClick:()=>n(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 gt({usersToUpdate:t,allUsers:a,onRemove:n,getRoleOptions:r}){if(t.length===0)return null;const l=r("tenant"),o=i=>{const d=a.find(m=>m.id===i);return(d==null?void 0:d.name)||"Unknown User"},c=i=>{const d=l.find(m=>m.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(me,{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:()=>n(i.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},i.id))})]})}function jt(t,a={}){const{enabled:n=!0,eventType:r="mousedown"}=a,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 n&&document.addEventListener(r,o),()=>{document.removeEventListener(r,o)}},[t,n,r]),l}function de(t,a){var n;return((n=a.find(r=>r.value===t))==null?void 0:n.label)||t}function ha(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function yt(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function xa(t,a,n){const r=yt(t),l=(n==null?void 0:n.type)||"organization";if(!(!a||!a.shares))if(l==="organization")if(r==="organization"){if("specificOrgUsers"in a.shares)return(a.shares.specificOrgUsers||[]).find(i=>i.orgUserId===t.id)}else return(a.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id);else return(a.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id)}function pa({user:t}){return yt(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 fa({user:t,userShare:a,usersToUpdate:n,currentUser:r,getRoleOptions:l,handleUpdateAccess:o}){if(!(a!=null&&a.role))return null;const c=ha((r==null?void 0:r.type)||""),i=n.some(u=>u.id===t.id),d=n.find(u=>u.id===t.id),m=d?d.newRole:a==null?void 0:a.role,h=l(t.type);return a?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(Pe,{currentRole:m,onRoleChange:u=>{o(t.id,a.role,u)},roleOptions:h,disabled:!c,allowDropdown:c,className:i?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:de(m,h)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function ga({hasAccess:t,isUserRemoving:a,isSelected:n,hasAccessFromAPI:r}){return e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[t&&!a&&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"]}),a&&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"]}),n&&!r&&e.jsxs(s.Badge,{variant:"outline",className:"border-blue-200 bg-blue-50 text-xs text-blue-700",children:[e.jsx(Me,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function ja({isUserRemoving:t,isSelected:a,hasAccess:n,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"}),a&&!n&&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 ya({existingShares:t,allUsers:a,getRoleOptions:n,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||[],m=c.orgWide||[],h=c.orgUsersOnly||[],u=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,j)=>{var g,v;const f=((g=a.find(N=>N.id===p.orgUserId))==null?void 0:g.name)||"Unknown User",x=((v=a.find(N=>N.id===p.orgUserId))==null?void 0:v.type)||"",S=de(p.role,n(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:f}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:S})]},j)}),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,j)=>{var g,v;const f=((g=a.find(N=>N.id===p.tenantUserId))==null?void 0:g.name)||"Unknown User",x=((v=a.find(N=>N.id===p.tenantUserId))==null?void 0:v.type)||"",S=de(p.role,n(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:f}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:S})]},j)}),d.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",d.length-3," more users"]})]})]}),m.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:m.map((p,j)=>{const f=de(p.role,n(""));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:f})]},j)})})]}),h.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:h.map((p,j)=>{const f=de(p.role,n(""));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:f})]},j)})})]}),u.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:u.map((p,j)=>{const f=de(p.role,n(""));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:f})]},j)})})]}),!i.length&&!d.length&&!m.length&&!h.length&&!u.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,m)=>{var j,f;const h=((j=a.find(x=>x.id===d.tenantUserId))==null?void 0:j.name)||"Unknown User",u=((f=a.find(x=>x.id===d.tenantUserId))==null?void 0:f.type)||"",p=de(d.role,n(u));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:h}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:p})]},m)}),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,m)=>{const h=de(d.role,n(""));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:h})]},m)})})]}),!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,j;const m=((p=a.find(f=>f.id===i.tenantUserId))==null?void 0:p.name)||"Unknown User",h=((j=a.find(f=>f.id===i.tenantUserId))==null?void 0:j.type)||"",u=de(i.role,n(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:u})]},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 m=de(i.role,n(""));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})]},d)})})]}),!o.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function va({isInitialLoading:t,searchQuery:a,availableUsers:n}){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..."})]})}):n.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:a?"No users found matching your search.":"No users available to share with."}):null}function ba({user:t,userShare:a,isUserRemoving:n,hasAccess:r,hasAccessFromAPI:l,isSelected:o,selectedUser:c,roleOptions:i,currentUser:d,usersToUpdate:m,handleUserToggle:h,handleRemoveAccess:u,handleUpdateAccess:p,handleUserRoleChange:j}){return e.jsxs("div",{className:s.cn("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!n?"border border-green-200 bg-green-50":n?"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?!n:o,disabled:t.id===(d==null?void 0:d.id),onCheckedChange:()=>{l?n?h(t.id):u(t.id):h(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(pa,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!n?e.jsx(Pe,{currentRole:a==null?void 0:a.role,onRoleChange:f=>p(t.id,a.role,f),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(fa,{user:t,userShare:a,usersToUpdate:m,currentUser:d,getRoleOptions:()=>i,handleUpdateAccess:p}),o&&!l&&e.jsx("div",{onClick:f=>f.stopPropagation(),children:e.jsx(Pe,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:f=>j(t.id,f),roleOptions:i,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(ga,{hasAccess:r,isUserRemoving:n,isSelected:o,hasAccessFromAPI:l}),e.jsx(ja,{isUserRemoving:n,isSelected:o,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function vt({existingShares:t,isInitialLoading:a,isSearching:n,getRoleOptions:r,allUsers:l=[],currentUser:o,handleUserToggle:c,handleUserRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:m}){const h=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),j=s.useShareSearchQuery(),f=s.useShareManagementActions(),x=c||(C=>{const D=h.some(k=>k.id===C),b=u.includes(C);D?f.removeSelectedUser(C):b?f.removeUserFromRemove(C):f.addSelectedUser({id:C,role:"VIEWER"})}),S=i||f.updateSelectedUserRole,g=d||f.addUserToRemove,v=m||((C,D,b)=>{f.addUserToUpdate({id:C,currentRole:D,newRole:b})}),N=l,O=u;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 (",(N??[]).length,")"]}),e.jsx(s.TooltipProvider$1,{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(ya,{existingShares:t,allUsers:l,getRoleOptions:r,currentUser:o})})]})})]}),(N==null?void 0:N.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{h.length===N.length?f.setSelectedUsers([]):f.setSelectedUsers(N.map(C=>({id:C.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:h.length===N.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(va,{isInitialLoading:a,isSearching:n,searchQuery:j,availableUsers:N||[]}),!a&&!n&&(N==null?void 0:N.length)>0&&N.map(C=>{const D=t?xa(C,t,o):void 0,b=O.includes(C.id),k=!!D,w=k&&!b,L=h.some(A=>A.id===C.id),T=h.find(A=>A.id===C.id),R=r(C.type);return e.jsx(ba,{user:C,userShare:D,isUserRemoving:b,hasAccess:w,hasAccessFromAPI:k,isSelected:L,selectedUser:T,roleOptions:R,currentUser:o,usersToUpdate:p,handleUserToggle:x,handleRemoveAccess:g,handleUpdateAccess:v,handleUserRoleChange:S},C.id)})]})]})}function bt({shareType:t,onShareTypeChange:a,currentUser:n,options:r}){const l=(n==null?void 0:n.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:a,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(fe,{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 ve=()=>[{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 Na({currentUser:t,currentShare:a,isSharing:n,onUpdateAccess:r,allUsersToUpdate:l=null,allUsersToRemove:o=!1,isUpdating:c=!1,isRemoving:i=!1}){const d=s.useShareCurrentMode(),m=ve().filter(v=>v.value==="VIEWER"||v.value==="EDITOR"||v.value==="CONTRIBUTOR"),h=a.role!=="NONE"?a.role:"NONE",u=l?l.newRole:h,p=a.role!=="NONE"&&!o&&(!l||l.newRole===h),j=l!==null&&l.newRole!==h,f=o,x=h==="NONE"||!h,S=v=>{switch(v){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(ea,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},g=v=>{r(h,v)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",j&&!f&&!x?"border-orange-300 bg-orange-50":p?"border-green-300 bg-green-50":f||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(me,{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"}),j&&e.jsx(s.Badge,{variant:"secondary",className:"ml-2 border-orange-400 bg-orange-100 text-orange-800",children:"Pending Update"}),(f||x)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:f||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:m.map(v=>e.jsxs(s.Button,{variant:u===v.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>g(v.value),disabled:n||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[S(v.value),e.jsx("span",{className:"font-medium",children:v.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:v.description})]},v.value))})]})})]})})}function Nt({currentUser:t,currentShare:a,isSharing:n,isUpdating:r,isRemoving:l,onUpdateAccess:o,onRemoveAccess:c,allUsersToUpdate:i,allUsersToRemove:d}){const m=x=>x==="OWNER"?"CONTRIBUTOR":x,u=a?{role:m(a.role)}:{role:"NONE"},p=i?{currentRole:m(i.currentRole),newRole:m(i.newRole)}:null,j=(x,S)=>{o(x,S)},f=()=>{c()};return e.jsx(Na,{currentUser:t,currentShare:u,isSharing:n,isUpdating:r,isRemoving:l,onUpdateAccess:j,onRemoveAccess:f,allUsersToUpdate:p,allUsersToRemove:d})}const Ca=async(t,a={})=>{const n={};return a.search&&(n.search=a.search),a.type&&(n.type=a.type),a.active!==void 0&&(n.active=a.active.toString()),a.tenantId&&(n.tenantId=a.tenantId),a.limit&&(n.limit=a.limit.toString()),a.offset&&(n.offset=a.offset.toString()),a.page&&(n.page=a.page.toString()),a.pageSize&&(n.pageSize=a.pageSize.toString()),await s.getRequest("https://semaphor.cloud/api/management/v1/unified-users",t,n)};function Sa(t={}){var r,l,o;const{authToken:a}=s.useSemaphorContext(),n=s.useQuery({queryKey:["unified-users",t],queryFn:()=>Ca((a==null?void 0:a.accessToken)||"",t),enabled:!!(a!=null&&a.accessToken),retry:(c,i)=>i instanceof Error&&i.message.includes("401")||i instanceof Error&&i.message.includes("403")?!1:c<2,retryDelay:c=>Math.min(1e3*2**c,3e4)});return{users:((r=n.data)==null?void 0:r.users)||[],userContext:(l=n.data)==null?void 0:l.userContext,total:((o=n.data)==null?void 0:o.total)||0,isLoading:n.isLoading,isError:n.isError,isFetching:n.isFetching,error:n.error,refetch:n.refetch}}function ge(t){const{debouncedSearchQuery:a,resourceId:n,resourceType:r=s.ResourceType.DASHBOARD,userType:l,tenantId:o}=t,c=M.useMemo(()=>({search:a,active:!0,...l?{type:l}:{},...l==="tenant"&&o?{tenantId:o}:{}}),[a,l,o]),{users:i,isLoading:d,isError:m}=Sa(c),h=s.useResourceShares(r,n);return{allUsers:i,isLoadingUsers:d,isErrorLoadingUsers:m,existingShares:h.data,isLoadingShares:h.isLoading,isErrorLoadingShares:h.isError,isFetchingShares:h.isFetching}}function wa({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var Y,V;const i=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:m,setSearchQuery:h,debouncedSearchQuery:u}=s.useShareSearchWithDebounce(),p=s.useShareSelectedUsers(),j=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate(),x=s.useShareCurrentMode(),S=s.useShareOrgWideRole(),g=s.useShareManagementActions(),[v,N]=M.useState("specific_users"),O=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},C=()=>{if(i==="tenant"&&d)return d},{allUsers:D,existingShares:b,isLoadingUsers:k}=ge({debouncedSearchQuery:u,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:O(),tenantId:C()});M.useEffect(()=>{g.setCurrentContext("org-tab"),g.setCurrentMode(v==="all_users"?"allOrgUsers":"specificOrgUsers")},[g,v]);const w=q=>{var U,H;const $=q;if(N($),r==null||r($),g.setCurrentContext("org-tab"),$==="specific_users")g.setCurrentMode("specificOrgUsers");else if($==="all_users"){g.setCurrentMode("allOrgUsers");const W=(H=(U=b==null?void 0:b.shares)==null?void 0:U.orgUsersOnly)==null?void 0:H[0];W&&W.role!==void 0&&g.setOrgWideRole(W.role)}},L=D.filter(q=>q.name.toLowerCase().includes(m.toLowerCase())||q.email.toLowerCase().includes(m.toLowerCase())),T=D.filter(q=>p.some($=>$.id===q.id)),R=q=>{var W,G;const $=p.some(Z=>Z.id===q),U=j.includes(q),H=(G=(W=b==null?void 0:b.shares)==null?void 0:W.specificOrgUsers)==null?void 0:G.some(Z=>Z.orgUserId===q);$?g.removeSelectedUser(q):U?g.removeUserFromRemove(q):H||g.addSelectedUser({id:q,role:"VIEWER"})},A=(q,$)=>{g.updateSelectedUserRole(q,$)},I=q=>{g.addUserToRemove(q),g.removeSelectedUser(q)},y=q=>{g.removeUserFromRemove(q)},E=q=>{g.removeUserFromUpdate(q)},F=(q,$)=>{g.setOrgWideRole($)},z=()=>{g.setOrgWideRole((_==null?void 0:_.role)||"NONE")},_=(V=(Y=b==null?void 0:b.shares)==null?void 0:Y.orgUsersOnly)==null?void 0:V[0];M.useEffect(()=>{v==="all_users"&&_&&_.role!==void 0&&g.setOrgWideRole(_.role)},[v,_,g]);const P=k,Q=!1;return n?e.jsxs(e.Fragment,{children:[e.jsx(bt,{shareType:v,onShareTypeChange:w,currentUser:n,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(fe,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(n==null?void 0:n.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(me,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role??"")}]}),v==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(xt,{value:m,onChange:h}),e.jsx(pt,{selectedUsers:p,selectedUserObjects:T,onRemove:R,onRoleChange:A,getRoleOptions:ve}),e.jsx(ft,{usersToRemove:j,allUsers:L,onRemove:y}),e.jsx(gt,{usersToUpdate:f,allUsers:L,onRemove:E,getRoleOptions:ve}),e.jsx(vt,{existingShares:b,isInitialLoading:P,isSearching:Q,resource:t,onShare:()=>{},getRoleOptions:ve,allUsers:L,currentUser:n,handleUserToggle:R,handleUserRoleChange:A,handleRemoveAccess:I,handleUpdateAccess:(q,$,U)=>{g.addUserToUpdate({id:q,currentRole:$,newRole:U})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(Nt,{currentUser:n,currentShare:_,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:F,onRemoveAccess:z,allUsersToUpdate:x==="allOrgUsers"&&S!==((_==null?void 0:_.role)||"NONE")?{currentRole:(_==null?void 0:_.role)||"NONE",newRole:S}:null,allUsersToRemove:x==="allOrgUsers"&&(_==null?void 0:_.role)===void 0})})]}):null}function qs({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var W;const{searchQuery:i,debouncedSearchQuery:d,setSearchQuery:m}=s.useShareSearchWithDebounce(),h=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),j=s.useShareCurrentMode(),f=s.useShareTenantWideRole(),x=s.useShareAllTenantsRole(),S=s.useShareSelectedTenant(),g=s.useShareManagementActions(),{data:v,isLoading:N}=s.useTenants({enabled:(n==null?void 0:n.type)==="organization"}),[O,C]=M.useState((n==null?void 0:n.type)==="organization"?"all_tenants":"specific_tenant_users");M.useEffect(()=>{(n==null?void 0:n.type)==="tenant"?(g.setCurrentContext("tenant-dialog"),g.setCurrentMode("specificTenantUsers")):(g.setCurrentContext("tenant-tab"),g.setCurrentMode("allTenants"))},[g,n==null?void 0:n.type]);const D=G=>{var se,ne,ee,ae;C(G);let Z;if(G==="specific_tenant_users"?Z="specific_users":G==="all_tenant_users"||G==="all_tenants"?Z="all_users":Z="specific_users",r==null||r(Z),(n==null?void 0:n.type)==="tenant"?(g.setCurrentContext("tenant-dialog"),G==="specific_tenant_users"?g.setCurrentMode("specificTenantUsers"):G==="all_tenant_users"&&(g.setCurrentMode("allTenantUsers"),n!=null&&n.tenantId&&g.setSelectedTenant(n.tenantId))):(g.setCurrentContext("tenant-tab"),G==="specific_tenant_users"?g.setCurrentMode("specificTenantUsers"):G==="all_tenant_users"?g.setCurrentMode("allTenantUsers"):G==="all_tenants"&&g.setCurrentMode("allTenants")),G==="all_tenant_users"){const J=(ne=(se=w==null?void 0:w.shares)==null?void 0:se.tenantWide)==null?void 0:ne[0];J&&J.role!==void 0&&g.setTenantWideRole(J.role)}else if(G==="all_tenants"){const J=(ae=(ee=w==null?void 0:w.shares)==null?void 0:ee.allTenantsOnly)==null?void 0:ae[0];J&&J.role!==void 0&&g.setAllTenantsRole(J.role)}},b=G=>{g.setSelectedTenant(G)},{allUsers:k,existingShares:w,isLoadingUsers:L,isErrorLoadingUsers:T,isLoadingShares:R,isErrorLoadingShares:A}=ge({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant",tenantId:(n==null?void 0:n.type)==="tenant"?n.tenantId:S}),I=G=>{var ee,ae;const Z=h.some(J=>J.id===G),se=u.includes(G),ne=(ae=(ee=w==null?void 0:w.shares)==null?void 0:ee.specificTenantUsers)==null?void 0:ae.some(J=>J.tenantUserId===G);Z?g.removeSelectedUser(G):se?g.removeUserFromRemove(G):ne||g.addSelectedUser({id:G,role:"VIEWER"})},y=(G,Z)=>{g.updateSelectedUserRole(G,Z)},E=G=>{g.addUserToRemove(G),g.removeSelectedUser(G)},F=G=>{g.removeUserFromRemove(G)},z=G=>{g.removeUserFromUpdate(G)},_=(G,Z,se)=>{g.addUserToUpdate({id:G,currentRole:Z,newRole:se})},P=(G,Z)=>{O==="all_tenant_users"?g.setTenantWideRole(Z):O==="all_tenants"&&g.setAllTenantsRole(Z)},Q=()=>{O==="all_tenant_users"?g.setTenantWideRole("VIEWER"):O==="all_tenants"&&g.setAllTenantsRole("VIEWER")},V=(()=>{var G,Z,se,ne;return j==="allTenants"?(Z=(G=w==null?void 0:w.shares)==null?void 0:G.allTenantsOnly)==null?void 0:Z[0]:j==="allTenantUsers"?(ne=(se=w==null?void 0:w.shares)==null?void 0:se.tenantWide)==null?void 0:ne[0]:null})();M.useEffect(()=>{var G,Z,se,ne;if(O==="all_tenant_users"){const ee=(Z=(G=w==null?void 0:w.shares)==null?void 0:G.tenantWide)==null?void 0:Z[0];ee&&ee.role!==void 0&&g.setTenantWideRole(ee.role)}else if(O==="all_tenants"){const ee=(ne=(se=w==null?void 0:w.shares)==null?void 0:se.allTenantsOnly)==null?void 0:ne[0];ee&&ee.role!==void 0&&g.setAllTenantsRole(ee.role)}},[O,w,g]);const q=k.filter(G=>h.some(Z=>Z.id===G.id)),$=L||R,U=T||A,H=()=>(n==null?void 0:n.type)==="tenant"||O==="all_tenants"?!0:S&&(O==="specific_tenant_users"||O==="all_tenant_users");return e.jsxs(e.Fragment,{children:[U&&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"})]})}),!U&&n&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(bt,{shareType:O,onShareTypeChange:D,currentUser:n,options:(n==null?void 0:n.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:e.jsx(me,{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(fe,{className:"mb-3 h-6 w-6 text-orange-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(fe,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(n==null?void 0:n.type)==="organization"&&(O==="specific_tenant_users"||O==="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:S||"",onValueChange:b,disabled:N,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:N?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(W=v==null?void 0:v.tenants)==null?void 0:W.map(G=>e.jsx(s.SelectItem,{value:G.id,children:G.name},G.id))})]})]}),H()?e.jsx(e.Fragment,{children:O==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(xt,{value:i,onChange:m}),e.jsx(pt,{selectedUsers:h,selectedUserObjects:q,onRemove:G=>I(G),onRoleChange:y,getRoleOptions:ve}),e.jsx(ft,{usersToRemove:u,allUsers:k,onRemove:F}),e.jsx(gt,{usersToUpdate:p,allUsers:k,onRemove:z,getRoleOptions:ve}),e.jsx(vt,{existingShares:w,isInitialLoading:!!$,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:ve,allUsers:k,currentUser:n,handleUserToggle:I,handleUserRoleChange:y,handleRemoveAccess:E,handleUpdateAccess:_})]}):O==="all_tenant_users"||O==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(Nt,{currentUser:n,currentShare:V,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:P,onRemoveAccess:Q,allUsersToUpdate:j==="allTenantUsers"&&((V==null?void 0:V.role)===void 0||f!==V.role)||j==="allTenants"&&((V==null?void 0:V.role)===void 0||x!==V.role)?{currentRole:(V==null?void 0:V.role)||"VIEWER",newRole:j==="allTenantUsers"?f:x}:null,allUsersToRemove:j==="allTenantUsers"&&(V==null?void 0:V.role)===void 0||j==="allTenants"&&(V==null?void 0:V.role)===void 0})}):null}):(n==null?void 0:n.type)==="organization"&&(O==="specific_tenant_users"||O==="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"})]})})]})]})}const Ct=()=>{const t=s.useShareCurrentContext(),a=s.useShareCurrentMode(),n=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),l=s.useShareUsersToUpdate(),o=s.useShareSelectedTenant(),c=s.useShareOrgWideRole(),i=s.useShareAllTenantsRole(),d=s.useShareTenantWideRole(),m=M.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:l,selectedTenant:o,orgWideRole:c,allTenantsRole:i,tenantWideRole:d}),[t,a,n,r,l,o,c,i,d]),h=M.useMemo(()=>p=>s.validateShareData(p),[]),u=M.useMemo(()=>{if(!t||!a)return!1;switch(t){case"org-tab":return a==="specificOrgUsers"?n.length>0||r.length>0||l.length>0:!0;case"tenant-tab":if(a==="allTenantUsers"){if(!o)return!1}else if(a==="specificTenantUsers")return o?n.length>0||r.length>0||l.length>0:!1;return!0;case"tenant-dialog":return a==="specificTenantUsers"?n.length>0||r.length>0||l.length>0:!0}return!1},[t,a,n,r,l,o]);return{buildShareData:m,validateShareData:h,isCurrentStateValid:u,currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:l,selectedTenant:o,orgWideRole:c,allTenantsRole:i,tenantWideRole:d}};function $s({resource:t,existingShares:a,isSharing:n,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllUsersShare:d,onRemoveAccess:m}){const h=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const j=s.useShareSelectedTenant();s.useShareSelectedTab();const f=s.useShareOrgWideRole(),x=s.useShareAllTenantsRole(),S=s.useShareTenantWideRole(),{buildShareData:g,validateShareData:v,isCurrentStateValid:N}=Ct(),O=n||r||l,C=()=>{var L,T,R,A;if(O)return"Updating...";if(i==="specific_users"){if(h.length===0&&u.length===0&&p.length===0)return"Select users to share with";const I=h.length+u.length+p.length;return I===0?"Select users to share with":h.length>0&&u.length>0?`Update access for ${I} user${I!==1?"s":""}`:u.length>0&&h.length===0&&p.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:h.length>0&&u.length===0&&p.length===0?`Share with ${h.length} user${h.length!==1?"s":""}`:p.length>0&&h.length===0&&u.length===0?`Update access for ${p.length} user${p.length!==1?"s":""}`:`Update access for ${I} user${I!==1?"s":""}`}else if(i==="all_users"){if(!d||d.role===void 0)return"Share with All Users";const I=d.role;return f===I?"Remove Access":"Update Access"}else if(i==="all_tenants"){const I=(T=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:T[0];if(!I||I.role===void 0)return"Share with All Tenants";const y=I.role;return x===y?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const I=(A=(R=a==null?void 0:a.shares)==null?void 0:R.tenantWide)==null?void 0:A[0];if(!I||I.role===void 0)return"Share with All Tenant Users";const y=I.role;return S===y?"Remove Access":"Update Access"}else if(i==="specific_tenant_users"){if(h.length===0&&u.length===0&&p.length===0)return"Select users to share with";const I=h.length+u.length+p.length;return I===0?"Select users to share with":h.length>0&&u.length>0?`Update access for ${I} user${I!==1?"s":""}`:u.length>0&&h.length===0&&p.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:h.length>0&&u.length===0&&p.length===0?`Share with ${h.length} user${h.length!==1?"s":""}`:p.length>0&&h.length===0&&u.length===0?`Update access for ${p.length} user${p.length!==1?"s":""}`:`Update access for ${I} user${I!==1?"s":""}`}return"Share"},D=()=>O||!t||i==="all_tenant_users"&&!j||i==="specific_tenant_users"&&!j?!0:!N,b=()=>{const L=g();L&&v(L)&&o(L)},k=()=>{var L,T,R,A;if(i==="all_users")if(!d||d.role===void 0){const I=g();I&&v(I)&&o(I)}else{const I=d.role;if(f===I)m==null||m();else{const E=g();if(E&&v(E)){const F={...E,updateAccess:!0};o(F)}}}else if(i==="all_tenants"){const I=(T=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:T[0];if(!I||I.role===void 0){const y=g();y&&v(y)&&o(y)}else{const y=I.role;if(x===y)m==null||m();else{const F=g();if(F&&v(F)){const z={...F,updateAccess:!0};o(z)}}}}else if(i==="all_tenant_users"){const I=(A=(R=a==null?void 0:a.shares)==null?void 0:R.tenantWide)==null?void 0:A[0];if(!I||I.role===void 0){const y=g();y&&v(y)&&o(y)}else{const y=I.role;if(S===y)m==null||m();else{const F=g();if(F&&v(F)){const z={...F,updateAccess:!0};o(z)}}}}},w=()=>{var L,T,R,A;if(i==="all_users"){if(!d||d.role===void 0)return"default";const I=d.role;return f===I?"destructive":"default"}else if(i==="all_tenants"){const I=(T=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:T[0];if(!I||I.role===void 0)return"default";const y=I.role;return x===y?"destructive":"default"}else if(i==="all_tenant_users"){const I=(A=(R=a==null?void 0:a.shares)==null?void 0:R.tenantWide)==null?void 0:A[0];if(!I||I.role===void 0)return"default";const y=I.role;return S===y?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:O,children:"Close"}),(i==="specific_users"||i==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(h.length>0||u.length>0||p.length>0)&&e.jsxs(s.Button,{onClick:b,disabled:!t||O,variant:"default",children:[O?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Me,{className:"mr-2 h-4 w-4"}),!O&&C()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:k,disabled:D(),variant:w(),children:[O?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(me,{className:"mr-2 h-4 w-4"}),!O&&C()]})]})}function Ta({resource:t,isSharing:a,isRemoving:n,isUpdating:r,onShare:l,onClose:o,shareTabType:c,currentAllUsersShare:i}){const d=s.useShareSelectedUsers(),m=s.useShareUsersToRemove(),h=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const u=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:p,validateShareData:j,isCurrentStateValid:f}=Ct(),x=a||n||r,S=()=>{if(x)return"Updating...";if(c==="specific_users"){if(d.length===0&&m.length===0&&h.length===0)return"Select users to share with";const C=d.length+m.length+h.length;return C===0?"Select users to share with":d.length>0&&m.length>0?`Update access for ${C} user${C!==1?"s":""}`:m.length>0&&d.length===0&&h.length===0?`Remove access for ${m.length} user${m.length!==1?"s":""}`:d.length>0&&m.length===0&&h.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:h.length>0&&d.length===0&&m.length===0?`Update access for ${h.length} user${h.length!==1?"s":""}`:`Update access for ${C} user${C!==1?"s":""}`}else if(c==="all_users"){if(!i||i.role==="NONE")return"Share with All Users";const C=i.role;return u===C?"Remove Access":"Update Access"}return"Share"},g=()=>x||!t?!0:!f,v=()=>{const C=p();C&&j(C)&&l(C)},N=()=>{if(!i||i.role==="NONE"){const C=p();C&&j(C)&&l(C)}else{const C=i.role;if(u===C){const b=p();if(b&&j(b)){const k={...b,removeAccess:!0};l(k)}}else{const b=p();if(b&&j(b)){const k={...b,updateAccess:!0};l(k)}}}},O=()=>!i||i.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:o,disabled:x,children:"Close"}),c==="specific_users"&&e.jsx(e.Fragment,{children:(d.length>0||m.length>0||h.length>0)&&e.jsxs(s.Button,{onClick:v,disabled:!t||x,variant:"default",children:[x?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Me,{className:"mr-2 h-4 w-4"}),!x&&S()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:N,disabled:g(),variant:O(),children:[x?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Me,{className:"mr-2 h-4 w-4"}),!x&&S()]})]})}function St({resource:t,resourceType:a,isSharing:n,isRemoving:r,isUpdating:l,onClose:o,onShare:c,onRemoveAccess:i}){var b,k,w,L;const{currentUser:d}=We(),[m,h]=M.useState("specific_users"),[u,p]=M.useState("specific_users"),j=s.useShareManagementActions(),f=s.useShareSelectedTab(),x=s.useShareCurrentMode(),{existingShares:S}=ge({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant"}),{existingShares:g}=ge({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"organization"}),v=(k=(b=S==null?void 0:S.shares)==null?void 0:b.tenantWide)==null?void 0:k[0],N=(L=(w=g==null?void 0:g.shares)==null?void 0:w.orgUsersOnly)==null?void 0:L[0],O=()=>{if(f==="org")return u;switch(x){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},C=M.useCallback(()=>{j.resetShareState(),o()},[j,o]),D=(d==null?void 0:d.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:C,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(Me,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:D?"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."})]}),D?e.jsxs(s.Tabs,{value:f,onValueChange:T=>{const R=T;j.setSelectedTab(R),j.resetUserSelections()},className:"mb-4 min-h-0 flex-1",children:[e.jsxs(s.TabsList,{className:"mb-2 grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"org",children:"Org Users"}),e.jsx(s.TabsTrigger,{value:"tenant",children:"Tenant Users"})]}),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(wa,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:p,isSharing:n,isUpdating:l,isRemoving:r})})}),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(qs,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:T=>h(T),isSharing:n,isUpdating:l,isRemoving:r})})})]}):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(qs,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:T=>h(T),isSharing:n,isUpdating:l,isRemoving:r})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:D?f==="org"?e.jsx($s,{resource:t,existingShares:g,isSharing:n,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:u,currentAllUsersShare:N,onRemoveAccess:i}):e.jsx($s,{resource:t,existingShares:S,isSharing:n,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:O(),currentAllUsersShare:v,onRemoveAccess:i}):e.jsx(Ta,{resource:t,isSharing:n,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:m,currentAllUsersShare:v,onRemoveAccess:i})})]})})}function ie(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function pe(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function wt(t,a){const{resourceType:n,resourceId:r,shareMutation:l,removeMutation:o,existingShares:c,resetUserSelections:i}=a;if(r)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const d=ie(n,r,[{scope:"org_users_only",role:t.orgWideRole}]);l(d,{onSuccess:()=>{i()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:d,usersToRemove:m,usersToUpdate:h}=t;if(d&&d.length>0){const u=ie(n,r,d.map(p=>({scope:"specific_org_user",orgUserId:p.id,role:p.role})));l(u,{onSuccess:()=>{i()}})}if(m&&m.length>0){const u=pe(n,r,m.map(p=>{var f,x;const j=(x=(f=c==null?void 0:c.shares)==null?void 0:f.specificOrgUsers)==null?void 0:x.find(S=>S.orgUserId===p);return{scope:"specific_org_user",orgUserId:p,role:(j==null?void 0:j.role)||"VIEWER"}}));o(u,{onSuccess:()=>{i()}})}h&&h.length>0&&h.forEach(u=>{const p=ie(n,r,[{scope:"specific_org_user",orgUserId:u.id,role:u.newRole}]);l(p,{onSuccess:()=>{i()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const d=ie(n,r,[{scope:"all_tenants_only",role:t.allTenantsRole}]);l(d,{onSuccess:()=>{i()}})}else if(t.mode==="allTenantUsers"){const d=ie(n,r,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);l(d,{onSuccess:()=>{i()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:d,usersToRemove:m,usersToUpdate:h,tenantId:u}=t;if(m&&m.length>0){const p=pe(n,r,m.map(j=>{var x,S;const f=(S=(x=c==null?void 0:c.shares)==null?void 0:x.specificTenantUsers)==null?void 0:S.find(g=>g.tenantUserId===j);return{scope:"specific_tenant_user",tenantUserId:j,tenantId:u,role:(f==null?void 0:f.role)||"VIEWER"}}));o(p,{onSuccess:()=>{i()}})}if(h&&h.length>0&&h.forEach(p=>{const j=ie(n,r,[{scope:"specific_tenant_user",tenantUserId:p.id,tenantId:u,role:p.newRole}]);l(j,{onSuccess:()=>{i()}})}),d&&d.length>0){const p=ie(n,r,d.map(j=>({scope:"specific_tenant_user",tenantUserId:j.id,tenantId:u,role:j.role})));l(p,{onSuccess:()=>{i()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const d=pe(n,r,[{scope:"all_tenant_users",role:"VIEWER"}]);o(d,{onSuccess:()=>{i()}})}else if(t.updateAccess){const d=ie(n,r,[{scope:"all_tenant_users",role:t.tenantWideRole}]);l(d,{onSuccess:()=>{i()}})}else{const d=ie(n,r,[{scope:"all_tenant_users",role:t.tenantWideRole}]);l(d,{onSuccess:()=>{i()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:d,usersToRemove:m,usersToUpdate:h}=t;if(d&&d.length>0){const u=ie(n,r,d.map(p=>({scope:"specific_tenant_user",tenantUserId:p.id,role:p.role})));l(u,{onSuccess:()=>{i()}})}if(m&&m.length>0){const u=pe(n,r,m.map(p=>{var f,x;const j=(x=(f=c==null?void 0:c.shares)==null?void 0:f.specificTenantUsers)==null?void 0:x.find(S=>S.tenantUserId===p);return{scope:"specific_tenant_user",tenantUserId:p,role:(j==null?void 0:j.role)||"VIEWER"}}));o(u,{onSuccess:()=>{i()}})}h&&h.length>0&&h.forEach(u=>{const p=ie(n,r,[{scope:"specific_tenant_user",tenantUserId:u.id,role:u.newRole}]);l(p,{onSuccess:()=>{i()}})})}break}}function Tt(t,a,n,r){var m,h,u,p,j,f;const{resourceType:l,resourceId:o,removeMutation:c,existingShares:i,resetUserSelections:d}=r;if(o)if(t.length>0){const x=pe(l,o,t.map(S=>{var v,N;const g=(N=(v=i==null?void 0:i.shares)==null?void 0:v.specificTenantUsers)==null?void 0:N.find(O=>O.tenantUserId===S);return{scope:"specific_tenant_user",tenantUserId:S,role:(g==null?void 0:g.role)||"VIEWER"}}));c(x,{onSuccess:()=>{d()},onError:S=>{console.error("Remove access failed:",S)}})}else{const x=a==="tenant"&&n==="allTenants",S=a==="tenant"&&n==="allTenantUsers";if(x){const g=(h=(m=i==null?void 0:i.shares)==null?void 0:m.allTenantsOnly)==null?void 0:h[0];if(g){const v=pe(l,o,[{scope:"all_tenants_only",role:g.role}]);c(v,{onSuccess:()=>{d()},onError:N=>{console.error("Remove all-tenants access failed:",N)}})}}else if(S){const g=(p=(u=i==null?void 0:i.shares)==null?void 0:u.tenantWide)==null?void 0:p[0];if(g){const v=pe(l,o,[{scope:"all_tenant_users",role:g.role}]);c(v,{onSuccess:()=>{d()},onError:N=>{console.error("Remove all-tenant-users access failed:",N)}})}}else{const g=(f=(j=i==null?void 0:i.shares)==null?void 0:j.orgUsersOnly)==null?void 0:f[0];if(g){const v=pe(l,o,[{scope:"org_users_only",role:g.role}]);c(v,{onSuccess:()=>{d()},onError:N=>{console.error("Remove org-wide access failed:",N)}})}}}}function ka(t,a,n){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),o=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{existingShares:i}=ge({debouncedSearchQuery:"",resourceId:t||"",resourceType:s.ResourceType.DASHBOARD,userType:"tenant"}),d=M.useCallback(()=>{r.resetUserSelections()},[r]),m=M.useCallback(u=>{if(!t)return;const p={resourceType:s.ResourceType.DASHBOARD,resourceId:t,shareMutation:a,removeMutation:n,existingShares:i,resetUserSelections:d};wt(u,p)},[t,a,n,i,d]),h=M.useCallback(()=>{if(!t)return;const u={resourceType:s.ResourceType.DASHBOARD,resourceId:t,removeMutation:n,existingShares:i,resetUserSelections:d};Tt(l,o||"",c||"",u)},[t,a,n,i,d,l,o,c]);return{handleShareSubmit:m,handleRemoveAccess:h}}function Da(t,a,n){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),o=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{existingShares:i}=ge({debouncedSearchQuery:"",resourceId:t||"",resourceType:s.ResourceType.VISUAL,userType:"tenant"}),d=M.useCallback(()=>{r.resetUserSelections()},[r]),m=M.useCallback(u=>{if(!t)return;const p={resourceType:s.ResourceType.VISUAL,resourceId:t,shareMutation:a,removeMutation:n,existingShares:i,resetUserSelections:d};wt(u,p)},[t,a,n,i,d]),h=M.useCallback(()=>{if(!t)return;const u={resourceType:s.ResourceType.VISUAL,resourceId:t,removeMutation:n,existingShares:i,resetUserSelections:d};Tt(l,o||"",c||"",u)},[t,a,n,i,d,l,o,c]);return{handleShareSubmit:m,handleRemoveAccess:h}}function Ea(){const[t,a]=M.useState(""),[n,r]=M.useState(!1),[l,o]=M.useState(""),[c,i]=M.useState(""),[d,m]=M.useState(!1),[h,u]=M.useState(null),[p,j]=M.useState(!1),[f,x]=M.useState(null),[S,g]=M.useState(null),{setIsDashboardEditing:v,setIsVisualEditing:N}=s.useDashboardActions(),{handleEditLibraryVisual:O,handleAddLibraryVisual:C}=s.useVisualUtils(),{resources:D,isLoading:b,isError:k,createResource:w,updateResource:L,deleteResource:T,duplicateResource:R,shareResource:A,isCreating:I,isDeleting:y,removeResourceShares:E,isSharing:F,isRemovingShares:z,isUpdatingShares:_}=s.useVisualManagement(()=>{j(!1),x(null)},()=>{r(!1),o(""),i("")}),{handleShareSubmit:P,handleRemoveAccess:Q}=Da((h==null?void 0:h.id)||null,A,E);We();const Y=D.filter(B=>{var K,re;return((K=B==null?void 0:B.title)==null?void 0:K.toLowerCase().includes(t.toLowerCase()))||((re=B==null?void 0:B.description)==null?void 0:re.toLowerCase().includes(t.toLowerCase()))}),V=B=>new Date(B).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),q=()=>{l.trim()&&w({title:l,description:c,isPrivate:!1})},$=B=>{x(B),j(!0)},U=()=>{f&&T(f.id)},{startUpdating:H,stopUpdating:W,isUpdating:G}=s.useResourceUpdateState(),Z=(B,K)=>{const re=K.title!==void 0?"title":"description";H(B,re),L({resourceId:B,data:K},{onSuccess:()=>{W(B,re)},onError:()=>{W(B,re)}})},se=B=>{g(B),R(B,{onSettled:()=>g(null)})},ne=B=>{O(B)},ee=B=>{C(B)},ae=B=>{const K=D.find(re=>re.id===B);K&&L({resourceId:B,data:{isPrivate:!K.isPrivate}})},J=B=>{u(B),m(!0)};return s.useShareUsersToRemove(),s.useShareManagementActions(),ge({debouncedSearchQuery:"",resourceId:(h==null?void 0:h.id)||"",resourceType:s.ResourceType.VISUAL,userType:"tenant"}),b?e.jsx(ht,{}):k?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:n?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:B=>o(B.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:B=>i(B.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:!l.trim()||I,children:I?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),o(""),i("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:I,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>r(!0),className:"h-8 w-full",size:"sm",disabled:I,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),I?"Creating...":"Create New Visual"]})}),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:B=>a(B.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:"py-8 text-center text-muted-foreground",children:[e.jsx(He,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No visuals found"})]}):Y.map(B=>e.jsx(ma,{visual:B,onAddVisual:ee,onEditVisual:ne,onUpdateVisual:Z,onDeleteClick:$,onDuplicateVisual:se,onTogglePrivacy:ae,onShareVisual:J,isDeleting:y,isDuplicating:S===B.id,isTitleUpdating:G(B.id,"title"),isDescriptionUpdating:G(B.id,"description"),formatDate:V},B.id))})}),d&&h&&e.jsx(St,{resource:h,resourceType:s.ResourceType.VISUAL,onShare:P,isSharing:F,isRemoving:z,isUpdating:_,onClose:()=>{m(!1),u(null)},onRemoveAccess:Q}),e.jsx(s.AlertDialog,{open:p,onOpenChange:B=>{!B&&y||(j(B),B||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 "',f==null?void 0:f.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:y,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:B=>{B.preventDefault(),B.stopPropagation(),U()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:y,children:y?"Deleting...":"Delete"})]})]})})]})}function Ia({dashboard:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onLoadDashboard:o,onUpdateDashboard:c,onDeleteClick:i,onDuplicateDashboard:d,onShareDashboard:m,formatDate:h}){var O;const{selectDashboard:u}=s.useManagementActions(),p=s.useIsDashboardSelected(t.id),[j,f]=M.useState(!1),[x,S]=M.useState(!1);M.useEffect(()=>{n?(f(!0),S(!0)):x&&(f(!1),S(!1))},[n,x]);const g=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(nt,{className:"h-3 w-3 text-purple-500"}):e.jsx(me,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(fe,{className:"h-3.5 w-3.5 text-slate-500"}),v=()=>e.jsx(s.LayoutDashboard,{className:"h-4 w-4 text-slate-400"}),N=()=>{u(t),o(t.id)};return e.jsxs("div",{className:s.cn("group relative flex cursor-pointer items-start gap-3 px-4 py-3 dark:border-slate-800","cursor-pointer transition-colors duration-150 hover:bg-slate-50 dark:hover:bg-slate-900/50",t.ownership.isOwner&&"border-blue-200 dark:border-blue-800",p&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:N,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-slate-100 dark:bg-slate-800",children:v()})}),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(s.EditableText,{inputClassName:"text-sm font-medium text-slate-900 dark:text-slate-100",value:t.title,onSave:C=>c==null?void 0:c(t.id,{title:C}),isEditable:t.permissions.canEdit&&p,isPending:r,placeholder:"Untitled Dashboard",displayClassName:"line-clamp-1 max-w-[220px] text-sm font-medium text-slate-900 dark:text-slate-100"})}),e.jsx("div",{className:"shrink-0",children:g()})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx(s.EditableText,{inputClassName:"line-clamp-1 text-xs text-slate-500 dark:text-slate-400",value:t.description||"",onSave:C=>c==null?void 0:c(t.id,{description:C}),isEditable:t.permissions.canEdit&&p,isPending:l,placeholder:"No description",displayClassName:"mt-0.5 max-w-[250px] line-clamp-1 text-xs text-slate-500 dark:text-slate-400"})})]}),e.jsx("div",{className:"absolute right-3 top-2 flex items-center justify-between text-xs text-muted-foreground",children:e.jsx("div",{className:s.cn("flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100"),children: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 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:C=>C.stopPropagation(),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:C=>{C.preventDefault(),C.stopPropagation(),d(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:C=>{C.stopPropagation(),m(t)},children:[e.jsx(me,{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:C=>{C.stopPropagation(),i(t)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(fe,{className:"h-3 w-3"}),e.jsx("span",{children:((O=t.ownership.createdBy)==null?void 0:O.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 Aa({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 Ma(t){const[a,n]=M.useState(""),[r,l]=M.useState(!1),[o,c]=M.useState(""),[i,d]=M.useState(""),[m,h]=M.useState(!1),[u,p]=M.useState(null),[j,f]=M.useState(!1),[x,S]=M.useState(null),[g,v]=M.useState(null),N=s.useManagementStore(J=>J.lastSelectedDashboard),O=s.useManagementStore(J=>J.actions.selectDashboard);s.useShareManagementActions(),s.useShareUsersToRemove(),s.useShareSelectedTab(),s.useShareCurrentMode();const{resources:C,isLoading:D,isError:b,createResource:k,updateResource:w,deleteResource:L,duplicateResource:T,isCreating:R,isDeleting:A,isSharing:I,isRemovingShares:y,isUpdatingShares:E,shareResource:F,removeResourceShares:z}=s.useDashboardManagement(()=>{f(!1),S(null),N&&O(N)},()=>{l(!1),c(""),d("")}),{handleShareSubmit:_,handleRemoveAccess:P}=ka((u==null?void 0:u.id)||null,F,z),{currentUser:Q}=We(),Y=C.filter(J=>{var B,K;return((B=J==null?void 0:J.title)==null?void 0:B.toLowerCase().includes(a.toLowerCase()))||((K=J==null?void 0:J.description)==null?void 0:K.toLowerCase().includes(a.toLowerCase()))}),V=J=>new Date(J).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),q=()=>{o.trim()&&k({title:o,description:i,isPrivate:!1})},$=J=>{var B;(B=t.onLoadDashboard)==null||B.call(t,J)},U=J=>{S(J),f(!0)},H=()=>{x&&L(x.id)},W=J=>{v(J),T(J,{onSettled:()=>v(null)})},{startUpdating:G,stopUpdating:Z,isUpdating:se}=s.useResourceUpdateState(),ne=(J,B)=>{const K=B.title!==void 0?"title":"description";G(J,K),w({resourceId:J,data:B},{onSuccess:()=>{Z(J,K)},onError:()=>{Z(J,K)}})},ee=J=>{const B=C.find(K=>K.id===J);B&&w({resourceId:J,data:{isPrivate:!B.isPrivate}})},ae=J=>{p(J),Q==null||Q.type,h(!0)};return ge({debouncedSearchQuery:"",resourceId:(u==null?void 0:u.id)||"",resourceType:s.ResourceType.DASHBOARD,userType:"tenant"}),D?e.jsx(ht,{}):b?e.jsx(Aa,{onRetry:()=>window.location.reload()}):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: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:J=>c(J.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:J=>d(J.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:"h-8 w-full",size:"sm",disabled:R,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),R?"Creating...":"Create New Dashboard"]})}),e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:a,onChange:J=>n(J.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:"py-8 text-center text-muted-foreground",children:[e.jsx(Rn,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No dashboards found"})]}):Y.map(J=>e.jsx(Ia,{dashboard:J,isDeleting:A,isDuplicating:g===J.id,isTitleUpdating:se(J.id,"title"),isDescriptionUpdating:se(J.id,"description"),onLoadDashboard:$,onEditDashboard:t.onEditDashboard,onUpdateDashboard:ne,onDeleteClick:U,onDuplicateDashboard:W,onTogglePrivacy:ee,onShareDashboard:ae,formatDate:V},J.id))})}),m&&u&&e.jsx(St,{resource:u,resourceType:s.ResourceType.DASHBOARD,onShare:_,isSharing:I,isRemoving:y,isUpdating:E,onClose:()=>{h(!1),p(null)},onRemoveAccess:P}),e.jsx(s.AlertDialog,{open:j,onOpenChange:J=>{!J&&A||(f(J),J||S(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:J=>{J.preventDefault(),J.stopPropagation(),H()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:A,children:A?"Deleting...":"Delete"})]})]})})]})}function kt({isOpen:t,onClose:a,className:n}){s.useDashboardStore(p=>p.dashboard);const{setDashboard:r,addSheet:l}=s.useDashboardStore(p=>p.actions),{currentUser:o}=We(),c=o,[i,d]=s.useLocalStorageState("resource-management-active-tab","dashboards"),m=jt(a,{enabled:t}),h=p=>{},u=p=>{console.log("Editing dashboard:",p)};return e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{ref:m,className:s.cn("absolute inset-y-0 left-0 z-[51] flex w-96 flex-col border-r bg-background shadow-lg transition-transform duration-300 ease-in-out",t?"translate-x-0":"-translate-x-full",n),children:[e.jsxs("div",{className:"flex items-center justify-between p-4",children:[e.jsx("div",{className:"flex items-center gap-3",children:c&&e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-muted bg-muted/30 px-2 py-1",children:[e.jsxs(s.Avatar,{className:"h-5 w-5",children:[e.jsx(s.AvatarImage,{alt:c.name}),e.jsx(s.AvatarFallback,{className:"text-xs",children:c.name.charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-xs font-medium",children:c.name})]})}),e.jsx(s.TooltipContent,{side:"bottom",className:"ml-2 max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"font-medium",children:c.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:c.email}),c.role&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Role:"," ",s.toTitleCase(c.role.replace(/_/g," "))]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",c.id]})]})})]})})}),e.jsx(s.IconButton,{className:"h-6 p-1 text-muted-foreground hover:text-foreground",onClick:a,tooltip:"Hide Dashboard Management",children:e.jsx(s.X,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:i,onValueChange:d,className:"flex h-9 grow flex-col",children:[e.jsx("div",{className:"px-5",children:e.jsxs(s.TabsList,{className:"grid h-8 w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"dashboards",className:"h-6",children:"Dashboards"}),e.jsx(s.TabsTrigger,{value:"visuals",className:"h-6",children:"Visuals"})]})}),e.jsx(s.TabsContent,{value:"dashboards",className:"flex-1",children:e.jsx(Ma,{onLoadDashboard:h,onEditDashboard:u})}),e.jsx(s.TabsContent,{value:"visuals",className:"flex-1",children:e.jsx(Ea,{})})]})})]})})}function La(){const{authToken:t,tokenProps:a}=s.useSemaphorContext();s.useDashboardStore(E=>E.theme);const n=s.useDashboardStore(E=>E.lenses),r=s.useDashboardStore(E=>E.selectedLensId),l=n==null?void 0:n.find(E=>E.id===r),o=s.useDashboardStore(E=>E.dashboard);s.useDashboardStore(E=>E.selectedSheetId);const c=s.useDashboardStore(E=>E.isDashboardEditing),i=s.useEditorStore(E=>E.card),d=s.useEditorStore(E=>E.selectedConnectionId),[m,h]=M.useState(!1),u=s.useDashboardStore(E=>E.isDashboardPanelOpen),p=s.useDashboardStore(E=>E.actions.setIsDashboardPanelOpen),j=s.useDashboardStore(E=>E.filterValues),f=s.useDashboardStore(E=>E.isVisualEditing),x=s.useDashboardStore(E=>E.showFilters);s.useDashboardStore(E=>E.showDashboardJSON);const S=s.useDashboardStore(E=>E.onSaveFunction),g=s.useDashboardStore(E=>E.actions.setShowFilters),{addFrame:v,setSelectedFrameId:N}=s.useDashboardStore(E=>E.actions),{getSelectedSheet:O,setIsDashboardEditing:C,setShowDashboardJSON:D}=s.useDashboardStore(E=>E.actions),b=O(),{tenantId:k,endUserId:w}=M.useMemo(()=>s.getTenantAndEndUserId(t==null?void 0:t.accessToken),[t==null?void 0:t.accessToken]),L=M.useMemo(()=>k||w,[k,w]),T=()=>{if(!c||!b)return;const E={dataSource:i.dataSource,mode:"explorer",connectionId:d,id:s.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},F={id:s.v4(),cards:[E],activeCardId:E.id};v(b.id,F),N(F.id)},R=()=>{C(!0)};async function A(){if(h(!0),!r||!l)return;const E=vs(o),F=JSON.stringify(E),z={...l,template:F,filterValues:j};await rs(z,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),S==null||S(E),h(!1)}if(f)return null;const I=(l==null?void 0:l.name)||o.title,y=a.orgUserId||a.tenantId&&a.endUserId&&a.endUserEmail;return e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b py-1 pl-3 pr-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[y&&e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:"Manage Dashboards",onClick:()=>p(!0),className:"h-7 p-2",children:e.jsx(Pn,{className:"h-4 w-4"})}),!f&&e.jsx(s.Label,{children:I})]}),e.jsxs("div",{className:"flex gap-2",children:[!1,!f&&e.jsx(da,{}),!f&&e.jsx(mt,{}),c&&!f&&L&&e.jsx(ia,{}),!f&&L&&e.jsx(ca,{}),c&&!f&&e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",disabled:!c,onClick:T,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!f&&e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2",onClick:R,size:"sm",children:e.jsx(s.Pencil,{className:"h-4 w-4"})}),c&&!f&&e.jsx(s.IconButton,{className:"h-7 p-2",onClick:()=>{C(!1),D(!1)},children:e.jsx(s.Cross2Icon,{className:"h-4 w-4"})}),c&&!f&&L&&e.jsx(s.Button,{className:"h-7 p-2",variant:"ghost",disabled:m,onClick:A,size:"sm",children:e.jsx(s.Save,{className:"h-4 w-4"})}),!x&&!f&&c&&e.jsx(s.Button,{className:"h-7 p-2",variant:"ghost",onClick:()=>g(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!f&&c&&!1,!f&&!1,!f&&e.jsx(kt,{isOpen:u,onClose:()=>p(!1)})]})]})}function Oa({name:t,items:a,value:n,onChange:r,isLoading:l,isError:o,refetch:c,className:i,icon:d,showNone:m=!1}){const h=ye.useRef(null),[u,p]=ye.useState(!1),[j,f]=ye.useState("100%"),x=m?[...a||[],{id:"none",name:"None"}]:a;ye.useLayoutEffect(()=>{h.current&&f(h.current.offsetWidth)},[]);function S(){var v;return l?"Loading...":o?"Error":n?(v=a==null?void 0:a.find(N=>N.id===n))==null?void 0:v.name:`Select ${t}`}function g(v,N){r(N),p(!1)}return e.jsxs(s.Popover,{open:u,onOpenChange:p,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{ref:h,variant:"outline",role:"combobox","aria-expanded":u,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:S()})]}),e.jsx(s.ChevronDown,{className:"size-4 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-full p-0",style:{minWidth:j},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(at,{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(v=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:v.name,onSelect:N=>g(N,v.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",n===v.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:v.name,children:v.name})]})},v.id))})]})]})})]})}function ke({title:t,items:a,value:n,isLoading:r,isError:l,refetch:o,onChange:c,showNone:i=!1,className:d,disabled:m=!1,type:h="combobox"}){const u=r?"Loading...":l?"Error":n;function p(){if(t==="Connection")return e.jsx(Qn,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(Yn,{className:"size-4"});if(t==="Table")return e.jsx(Je,{className:"size-4"});if(t==="Model")return e.jsx(vn,{className:"size-4"})}function j(){return e.jsxs(s.Select,{disabled:m,value:u,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(at,{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"),a&&a.map((x,S)=>e.jsx(s.SelectItem,{value:x.id,children:x.name},S))]}),(r||l)&&e.jsx(s.SelectItem,{value:u,children:u})]})})]})}function f(){return e.jsx(Oa,{icon:p(),items:a,value:u,onChange:c||(()=>{}),isLoading:r,isError:l,refetch:o,name:t,showNone:i})}return e.jsx(s.TooltipProvider$1,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:h==="select"?j():f()})})}function Ra({column:t}){const[a,n]=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:m}=s.useEditorAside(),h=s.useEditorStore(x=>x.actions.setSqlGen),u=s.useEditorStore(x=>x.actions.setCardSql),p=s.useEditorStore(x=>x.actions.setRunSql);function j(x,S){var O;const g=s.createSqlGenConfig(x,i,S),v=(O=d==null?void 0:d.find(C=>C.id===c))==null?void 0:O.name;h(g);const N=s.getSql(g,s.fmt(l||""),s.fmt(r),v||"",m,o||"");N&&(u(N),p(!0)),n(!1)}function f(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>j(t,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>j(t,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>j(t,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>j(t,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>j(t,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return e.jsxs(s.HoverCard,{openDelay:0,open:a,onOpenChange:n,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:f()})]})}function bs({column:t}){return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger$1,{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(fs,{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(ot,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(bn,{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 Qe({column:t,className:a}){return e.jsxs("div",{className:s.cn("flex min-h-8 grow items-center space-x-2 px-2 text-sm",a),children:[e.jsx(bs,{column:t}),e.jsx("span",{children:t.column_name})]})}function Ba({id:t,children:a,type:n="column"}){const{attributes:r,listeners:l,setNodeRef:o,transform:c}=s.useDraggable({id:t,data:{type:n}}),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:a})}function Fa({onClick:t,column:a}){const n=s.useDndStore(h=>h.activeId),r=s.useEditorStore(h=>{var u;return(u=h.card.queryConfig)==null?void 0:u.groupByColumns}),l=s.useEditorStore(h=>{var u;return(u=h.card.queryConfig)==null?void 0:u.metricColumns}),o=s.useEditorStore(h=>{var u;return(u=h.card.queryConfig)==null?void 0:u.filterColumns});function c(h){return i(h)||d(h)||m(h)}function i(h){return r==null?void 0:r.some(u=>u.name===h.column_name)}function d(h){return l==null?void 0:l.some(u=>u.name===h.column_name)}function m(h){return o==null?void 0:o.some(u=>u.name===h.column_name)}return e.jsxs("div",{onClick:()=>t(a),className:s.cn("relative grow overflow-x-hidden overflow-y-hidden rounded-md active:border active:border-dashed active:border-muted-foreground",{"bg-muted-foreground/10":c(a)}),children:[n===a.column_name&&e.jsx(s.DragOverlay,{children:e.jsx(Qe,{column:a,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),n===a.column_name&&e.jsx("div",{className:"absolute inset-0",children:n===a.column_name&&e.jsx(Qe,{column:a})}),e.jsx(Ba,{id:a.column_name,type:"column",children:e.jsx(Qe,{column:a})})]})}const Xe={id:"__placeholder__",role:"groupby",type:"string"},Ze={id:"__placeholder__",role:"groupby",type:"string"},es={id:"__placeholder__",role:"metric",type:"number"},ss={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},Dt={id:"__placeholder__"},be="droppable-group-by",Ne="droppable-metrics",Ce="droppable-pivot-by",_e="sortable-group-by",ls="sortable-metrics",Ve="sortable-pivot-by",os="droppable-filters",is="sortable-filters",Ns="sortable-order-by";function za(){const t=s.useDndStore(I=>I.insertIndex),a=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.groupByColumns)||[]}),n=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.metricColumns)||[]}),r=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.filterColumns)||[]}),l=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.orderBy)||[]}),o=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:i,setPreviewGroupByColumns:d,setPreviewMetricColumns:m,setPreviewFilterColumns:h,setPreviewPivotColumns:u}=s.useDndActions(),{setGroupByColumns:p,setMetricColumns:j,setFilterColumns:f,setOrderByColumns:x,setPivotByColumns:S}=s.useEditorActions(),{columns:g}=s.useDataColumns(),{formattedTableName:v}=s.useEditorAside(),N=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),O=I=>{var F;const{active:y,over:E}=I;if(((F=y.data.current)==null?void 0:F.type)==="column"&&E){const z=E.id,_=g.find(V=>V.column_name===y.id);if(!_)return;const P=s.isNumberDataType(_.data_type),Q=s.isTextDataType(_.data_type),Y=s.isDateDataType(_.data_type);if(Q||Y){if(a.some(q=>q.id===z)){const q=a.findIndex(U=>U.id===z);c(q);const $=a.filter(U=>U.id!==Xe.id);$.splice(q,0,Xe),d($)}else if(E.id===be){c(a.length);const q=[...a,Xe];d(q),m(n),h(r)}}if(Q||Y){if(o.some(q=>q.id===z)){const q=o.findIndex(U=>U.id===z);c(q);const $=o.filter(U=>U.id!==Ze.id);$.splice(q,0,Ze),u($)}else if(E.id===Ce){c(o.length);const q=[...o,Ze];u(q),d(a),m(n),h(r)}}if(P||Q){if(n.some(q=>q.id===z)){console.log("isOverMetricSortable",z);const q=n.findIndex(U=>U.id===z);c(q);const $=n.filter(U=>U.id!==es.id);$.splice(q,0,es),m($)}else if(E.id===Ne){c(n.length);const q=[...n,es];m(q),h(r),d(a),u(o)}}if(D(_)){if(r.some(q=>q.id===z)){const q=r.findIndex(U=>U.id===z);c(q);const $=r.filter(U=>U.id!==ss.id);$.splice(q,0,ss),h($)}else if(E.id===os){c(r.length);const q=[...r,ss];h(q),m(n),d(a),u(o)}}}else d(a),m(n),h(r),u(o)};function C(I){i(I.active.id),c(null),d(a),m(n),h(r),u(o)}function D(I){return!r.some(y=>y.name===I.column_name)}function b(I,y="SUM"){const{column_name:E,data_type:F}=I,z=[...n],_=t!==null?t:n.length,P={...I,id:ue(E),name:E,label:Le(E,y),type:F,role:"metric",aggregate:y};z.splice(_,0,P),j(z)}function k(I){const y=s.isTextDataType(I.data_type);s.isDateDataType(I.data_type);const E=[...o],F=t!==null?t:o.length;let z;y?z={...I,id:ue(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:z={...I,id:ue(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:De(I.column_name,"month"),granularity:"month"},E.splice(F,0,z),S(E)}function w(I){const y=s.isTextDataType(I.data_type);s.isDateDataType(I.data_type);const E=[...a],F=t!==null?t:a.length;let z;y?z={...I,id:ue(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:z={...I,id:ue(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:De(I.column_name,"month"),granularity:"month"},E.splice(F,0,z),p(E)}function L(I){const y=[...r],E=t!==null?t:r.length,F={...I,id:ue(I.column_name),name:I.column_name,type:I.data_type,sql:s.getDefaultFilterSql(I.data_type,v,s.fmt(I.column_name)),role:"filter"};y.splice(E,0,F),f(y)}function T(I){var z,_,P,Q,Y,V,q,$;const{active:y,over:E}=I,F=y.data.current;if((F==null?void 0:F.type)==="column"&&E){const U=g.find(Z=>Z.column_name===y.id);if(!U)return;const H=s.isNumberDataType(U.data_type),W=s.isTextDataType(U.data_type),G=s.isDateDataType(U.data_type);(W||G)&&(E.id===be||((z=E.data.current)==null?void 0:z.type)===_e)&&w(U),(W||G)&&(E.id===Ce||((_=E.data.current)==null?void 0:_.type)===Ve)?k(U):(H||W)&&(E.id===Ne||((P=E.data.current)==null?void 0:P.type)===ls)?(H&&b(U),W&&b(U,"COUNT")):D(U)&&(E.id===os||((Q=E.data.current)==null?void 0:Q.type)===is)&&L(U)}if(E&&((Y=E.data.current)==null?void 0:Y.type)===_e&&a.some(U=>U.id===y.id)){const U=a.findIndex(W=>W.id===y.id),H=a.findIndex(W=>W.id===E.id);if(U!==-1&&H!==-1&&U!==H){const W=[...a],[G]=W.splice(U,1);W.splice(H,0,G),p(W)}}if(E&&((V=E.data.current)==null?void 0:V.type)===Ve&&o.some(U=>U.id===y.id)){const U=o.findIndex(W=>W.id===y.id),H=o.findIndex(W=>W.id===E.id);if(U!==-1&&H!==-1&&U!==H){const W=[...o],[G]=W.splice(U,1);W.splice(H,0,G),S(W)}}if(E&&((q=E.data.current)==null?void 0:q.type)===ls&&n.some(U=>U.id===y.id)){const U=n.findIndex(W=>W.id===y.id),H=n.findIndex(W=>W.id===E.id);if(U!==-1&&H!==-1&&U!==H){const W=[...n],[G]=W.splice(U,1);W.splice(H,0,G),j(W)}}if(E&&(($=E.data.current)==null?void 0:$.type)===is&&r.some(U=>U.id===y.id)){const U=r.findIndex(W=>W.id===y.id),H=r.findIndex(W=>W.id===E.id);if(U!==-1&&H!==-1&&U!==H){const W=[...r],[G]=W.splice(U,1);W.splice(H,0,G),f(W)}}R(I),i(null),c(null),d(a),m(n),h(r),u(o)}function R(I){const{active:y,over:E}=I,F=y.data.current;if((F==null?void 0:F.type)===Ns&&E){const z=l.findIndex(P=>Ie(P.columnId)===y.id),_=l.findIndex(P=>Ie(P.columnId)===E.id);if(z!==-1&&_!==-1&&z!==_){const P=[...l],[Q]=P.splice(z,1);P.splice(_,0,Q),x(P)}}}function A(){i(null),c(null),d(a),m(n),h(r)}return{handleDragOver:O,handleDragEnd:T,handleDragStart:C,handleDragCancel:A,sensors:N}}function ue(t){return`${t}-${s.v4()}`}function Le(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function Ie(t){return`${Ns}-${t}`}function De(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function Pa({schemaName:t,tableName:a,columns:n,status:r}){const l=s.useEditorStore(y=>y.sqlGen),o=s.useEditorStore(y=>y.isDevMode),c=s.useEditorStore(y=>y.selectedConnectionId),i=s.useEditorStore(y=>{var E,F;return(F=(E=y.card)==null?void 0:E.queryConfig)==null?void 0:F.metricColumns});s.useEditorStore(y=>{var E,F;return(F=(E=y.card)==null?void 0:E.queryConfig)==null?void 0:F.groupByColumns});const d=s.useEditorStore(y=>y.selectedDatabaseName),m=s.useEditorStore(y=>y.selectedSchemaName),h=s.useEditorStore(y=>y.selectedTableName),u=s.useEditorStore(y=>y.selectedDatamodelId),p=s.useDashboardStore(y=>y.dashboard.aiScopeTables),{addToAIScope:j,removeFromAIScope:f}=s.useDashboardActions(),{addColumnToMetricColumns:x,addColumnToGroupBy:S,setCardSql:g,setRunSql:v,setSqlGen:N,setIsShowingVisual:O}=s.useEditorActions(),{connectionType:C,modelItems:D,selectedDatamodelName:b}=s.useEditorAside();function k(y){var E;if(o){const F=s.createSqlGenConfig(y,l);N(F);const z=(E=D==null?void 0:D.find(P=>P.id===u))==null?void 0:E.name,_=s.getSql(F,s.fmt(t),s.fmt(a),z||"",C,d||"");_&&(g(_),v(!0))}if(!o){if(s.isTextDataType(y.data_type))if(i&&i.length>0){const F={...y,role:"groupby",id:ue(y.column_name),name:y.column_name,type:y.data_type};S(F)}else{const F={...y,role:"metric",id:ue(y.column_name),name:y.column_name,label:Le(y.column_name,"COUNT"),type:y.data_type,aggregate:"COUNT"};x(F)}if(s.isDateDataType(y.data_type)){const F={...y,role:"groupby",id:ue(y.column_name),name:y.column_name,type:y.data_type,label:De(y.column_name,"month"),granularity:"month"};S(F)}if(s.isNumberDataType(y.data_type)){const F={...y,role:"metric",id:ue(y.column_name),name:y.column_name,label:Le(y.column_name,"SUM"),type:y.data_type,aggregate:"SUM"};x(F)}}}function w(y){y===!0&&(h||b)&&c?(j({connectionId:c,connectionType:C==="S3"||C==="API"?"DuckDb":C||"",databaseName:d||"",schemaName:m||"",tableName:h||"",datamodelName:s.resolveDatamodelName(b),datamodelId:u||""}),s.ue.success("Added to Assistant Scope",{position:"top-right",duration:2500,richColors:!0})):(f({connectionId:c||"",connectionType:C||"",tableName:h||"",datamodelName:s.resolveDatamodelName(b),datamodelId:u||"",databaseName:d||"",schemaName:m||""}),s.ue("Removed from Assistant Scope",{position:"top-right",duration:2e3,richColors:!0}))}function L(){const y=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:b,connectionType:C,databaseName:d||""});O(!1);const E=C==="MSSQL"?`SELECT top 10 * FROM ${y}`:`SELECT * FROM ${y} LIMIT 10`;g(E),v(!0)}function T(){const y=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:b,connectionType:C,databaseName:d||""});g(`SELECT COUNT(*) as count FROM ${y}`),v(!0)}function R(){return(p==null?void 0:p.find(y=>y.connectionId===c&&(y.tableName===h||y.datamodelName===b)))!==void 0}function A(y){return o?e.jsxs("div",{className:"flex grow items-center justify-between space-x-2 rounded-md px-2 py-1",onClick:()=>k(y),children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(bs,{column:y}),e.jsx("span",{children:y.column_name})]}),e.jsx("div",{onClick:E=>E.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(y.data_type)&&e.jsx(Ra,{column:y})})]}):e.jsx(Fa,{onClick:k,column:y})}function I(){return e.jsxs(e.Fragment,{children:[e.jsxs(s.Toggle,{title:`${R()?"Remove from":"Add to"} Assistant Scope`,pressed:R(),onPressedChange:w,variant:"outline",className:s.cn("h-9 px-2",{}),children:[e.jsx(s.Plus,{className:s.cn("mr-1 size-4",{"text-green-400":R(),"text-muted-foreground":!R()})}),"AI"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:L,size:"sm",variant:"secondary",className:"flex",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx($n,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:T,size:"sm",variant:"secondary",className:"w-full",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(rt,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-6",children:Array.from({length:3}).map((y,E)=>e.jsx(s.Skeleton,{className:"h-7 w-full"},E))}):e.jsxs("div",{className:"flex grow flex-col space-y-4 px-4",children:[o&&e.jsx("div",{className:"mx-2 flex items-center justify-center gap-2",children:I()}),e.jsxs(s.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-2 py-0",children:[e.jsx("div",{className:"flex flex-col gap-1",children:n==null?void 0:n.map(y=>e.jsx("div",{className:s.cn("mr-2 cursor-pointer rounded-md text-sm transition-colors hover:bg-muted"),children:A(y)},y.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Et({ColumnsComponent:t,type:a}){var je;const n=s.useEditorStore(te=>te.card),r=s.useEditorStore(te=>te.selectedConnectionId),l=s.useDashboardStore(te=>te.showFilters),o=s.useEditorStore(te=>te.selectedDatamodelId),c=s.useEditorStore(te=>te.selectedDatabaseName),i=s.useEditorStore(te=>te.selectedSchemaName),d=s.useEditorStore(te=>te.selectedTableName),m=s.useEditorStore(te=>te.isDevMode),{setSelectedTableName:h,setIsDevMode:u,setCardSql:p}=s.useEditorActions(),{connectionItems:j,modelItems:f,schemaItems:x,databaseItems:S,tableItems:g,columns:v,isConnectionsLoading:N,isModelsLoading:O,isConnectionsError:C,isModelsError:D,isDatabasesLoadingOrFetching:b,isDatabaseError:k,isSchemaLoadingOrFetching:w,isSchemaError:L,isColumnsError:T,isColumnsLoadingOrFetching:R,isTableLoadingOrFetching:A,isTableError:I,connectionType:y,isNonDbConnection:E,refetchDatabases:F,refetchModels:z,refetchSchemas:_,refetchTables:P,refetchColumns:Q,refetchConnections:Y,handleConnectionChange:V,handleDatabaseChange:q,handleSchemaChange:$,handleDatamodelChange:U,handleTableChange:H,tableName:W,schemaName:G}=s.useEditorAside(),{data:Z,refetch:se}=s.useDashboardCardQuery(n);function ne(){return t?t(G,W,v):e.jsx(Pa,{schemaName:G,tableName:W,columns:v,status:R?"Loading...":T?"Error":"Success"})}function ee(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function ae(te){te===!0?Z&&(p(Z.userSql),setTimeout(()=>{se()},100)):p(""),u(te)}function J(){if(!r||y==="S3"||y==="API")return null;if(!o||o==="none")return e.jsx(ke,{refetch:F,showNone:!0,onChange:q,isError:k,isLoading:b,items:S,value:c||"",title:"Database",type:"combobox"})}function B(){if(r&&!E&&(!c||c==="none")&&(!o||o==="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 K(){if(!r||y==="S3"||y==="API")return null;if(!c||c==="none")return e.jsx(ke,{refetch:z,showNone:!0,onChange:U,isError:D,isLoading:O,items:f,value:o||"",title:"Model",type:"combobox"})}function re(){return!r||y==="S3"||y==="API"||!c||c==="none"?null:e.jsx(ke,{refetch:_,onChange:$,isError:L,isLoading:w,items:x,value:i||"",title:"Schema",type:"combobox"})}function he(){function te(){let le=!1;return y==="API"?(le=!1,le):((y==="S3"||r&&c&&c!=="none"&&i)&&(le=!0),le)}return te()?e.jsx(ke,{refetch:P,onChange:H,isError:I,items:g,isLoading:A,value:d||"",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]":!l}),children:[e.jsxs("section",{className:"space-y-3 px-6 py-4",children:[e.jsx(ke,{refetch:Y,items:j,title:"Connection",value:r||"",onChange:V,isLoading:N,isError:C,type:"combobox",connectionTooltip:((je=j==null?void 0:j.find(te=>te.id===r))==null?void 0:je.type)||""}),J(),B(),K(),re(),he()]}),ne(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:a==="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:m,onCheckedChange:ae,id:"dev-mode"}),e.jsx(s.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(s.Button,{onClick:ee,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(Jn,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function It({error:t,className:a="",textClassName:n="",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 m(p){(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),d())}function h(){const p=window.getSelection();if(p&&p.toString().trim()!==""){const j=p.toString();navigator.clipboard.writeText(j),o(!0),i.current=!0,setTimeout(()=>{o(!1),i.current=!1},1e3)}else i.current=!1}function u(){o(!1),i.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${a}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:c,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${n}`,onClick:d,onKeyDown:m,onMouseUp:h,onMouseDown:u,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 At({sql:t,error:a,onDebugWithAssistant:n}){const r=s.useEditorStore(d=>d.isDevMode),{setIsDevMode:l,setCardSql:o,setRunSql:c}=s.useEditorActions();function i(){l(!r),o(t),setTimeout(()=>{c(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-2",children:[e.jsxs(s.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[a&&e.jsx(It,{error:a}),t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"rounded-md",children:e.jsx(s.CodeHighlighter,{code:t,language:"sql"})})})]}),!r&&t&&e.jsxs(s.Button,{onClick:i,variant:"secondary",size:"sm",children:[e.jsx(An,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),a&&n&&e.jsxs(s.Button,{onClick:n,size:"sm",variant:"secondary",children:[e.jsx(zn,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function Mt({sql:t,error:a,onDebugWithAssistant:n}){return e.jsxs(s.HoverCard,{openDelay:a?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:a?e.jsx(st,{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-[600px]",children:e.jsx(At,{sql:t,error:a,onDebugWithAssistant:n})})]})}var Lt={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},Gs=M.createContext&&M.createContext(Lt),_a=["attr","size","title"];function Va(t,a){if(t==null)return{};var n=Ua(t,a),r,l;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);for(l=0;l<o.length;l++)r=o[l],!(a.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(n[r]=t[r])}return n}function Ua(t,a){if(t==null)return{};var n={};for(var r in t)if(Object.prototype.hasOwnProperty.call(t,r)){if(a.indexOf(r)>=0)continue;n[r]=t[r]}return n}function Ue(){return Ue=Object.assign?Object.assign.bind():function(t){for(var a=1;a<arguments.length;a++){var n=arguments[a];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},Ue.apply(this,arguments)}function Hs(t,a){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);a&&(r=r.filter(function(l){return Object.getOwnPropertyDescriptor(t,l).enumerable})),n.push.apply(n,r)}return n}function qe(t){for(var a=1;a<arguments.length;a++){var n=arguments[a]!=null?arguments[a]:{};a%2?Hs(Object(n),!0).forEach(function(r){qa(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Hs(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function qa(t,a,n){return a=$a(a),a in t?Object.defineProperty(t,a,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[a]=n,t}function $a(t){var a=Ga(t,"string");return typeof a=="symbol"?a:a+""}function Ga(t,a){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,a);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(a==="string"?String:Number)(t)}function Ot(t){return t&&t.map((a,n)=>M.createElement(a.tag,qe({key:n},a.attr),Ot(a.child)))}function Se(t){return a=>M.createElement(Ha,Ue({attr:qe({},t.attr)},a),Ot(t.child))}function Ha(t){var a=n=>{var{attr:r,size:l,title:o}=t,c=Va(t,_a),i=l||n.size||"1em",d;return n.className&&(d=n.className),t.className&&(d=(d?d+" ":"")+t.className),M.createElement("svg",Ue({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,c,{className:d,style:qe(qe({color:t.color||n.color},n.style),t.style),height:i,width:i,xmlns:"http://www.w3.org/2000/svg"}),o&&M.createElement("title",null,o),t.children)};return Gs!==void 0?M.createElement(Gs.Consumer,null,n=>a(n)):a(Lt)}function Ja(t){return Se({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 Rt(t){const{theme:a}=s.useTheme(),n=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:m}=s.useEditorActions(),h=M.useRef(),u=M.useRef({}),p=r.cards.find(x=>x.id===o),j=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(h.current&&c){const x=h.current.getModel();x&&(u.current[l.id]=x);let S=u.current[o];if(!S){const g=j();S=c.editor.createModel(g,t),u.current[o]=S}h.current.setModel(S)}d(o,l),m(!0)}},[o,l,d,c,m,t,j]),M.useEffect(()=>{if(!c)return;const x=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",S=n==="system"?x:n;c.editor.defineTheme("default",{base:S==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":S==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[a,n,c]),M.useEffect(()=>{const x=h.current;x&&c&&l&&x.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return i(),!1})},[c,i,l]);function f(x,S){if(h.current=x,!u.current[l.id]){const g=x.getModel(),v=j();u.current[l.id]=g||(S==null?void 0:S.editor.createModel(v,t))||x.getModel()}x.setModel(u.current[l.id])}return{handleEditorDidMount:f}}function Wa(){const t=s.useEditorStore(c=>c.card.sql),a=s.useEditorStore(c=>c.sqlGen),{setCardSql:n,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=Rt("sql");function o(c){n(c),s.isObjectEmpty(a)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:o,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function Ya(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:a}=s.useEditorActions(),{handleEditorDidMount:n}=Rt("python");function r(l){a(l)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:n})}function Ka({jsonString:t}){return e.jsx(s.Ft,{theme:"default",defaultLanguage:"json",className:"mt-1 min-h-[220px]",value:t,options:{readOnly:!0,minimap:{enabled:!1},lineNumbers:"off",glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})}function Qa(){const t=s.useQueryClient(),[a,n]=M.useState(!1),[r,l]=M.useState(!1);s.useEditorStore(P=>P.frame);const o=s.useEditorStore(P=>P.card);s.useEditorStore(P=>P.isShowingVisual),s.useEditorStore(P=>P.selectedConnectionId),s.useEditorStore(P=>P.tempQueryData),s.useEditorStore(P=>P.selectedDatabaseName),s.useEditorStore(P=>P.selectedDatamodelId),s.useEditorStore(P=>P.selectedSchemaName);const c=s.useEditorStore(P=>P.showAIDialog);s.useEditorStore(P=>P.selectedTableName);const i=s.useEditorStore(P=>{var Q;return(Q=P==null?void 0:P.card)==null?void 0:Q.sql}),d=s.useEditorStore(P=>{var Q;return(Q=P==null?void 0:P.card)==null?void 0:Q.python}),{sheetFilterValues:m}=s.useSheetFilterValues(),{setCardCustomCfg:h,setQueryResultColumns:u,setCardSql:p,setTempQueryData:j,setPythonStdOut:f,setCardPreferences:x,setCardType:S,setCardPython:g,runAssistant:v,setShowAIDialog:N}=s.useEditorActions();s.useEditorStore(P=>P.onSave),s.useEditorStore(P=>P.onClose),s.useEditorStore(P=>P.actions.setSqlGen);const O=s.useEditorStore(P=>P.runSql),C=s.useEditorStore(P=>P.actions.setRunSql),D=s.useEditorStore(P=>P.actions.setIsSqlRunning),{data:b,isLoading:k,isFetching:w,isSuccess:L,isError:T,error:R,queryKey:A,refetch:I,errorMessage:y}=s.useDashboardCardQuery(o);M.useEffect(()=>{if(b&&(b.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),f((b==null?void 0:b.output)||""),b.records.length>0)){const{dimensionKeys:P}=s.getKeys(b.records);u(P)}},[b,u,f]),M.useEffect(()=>{(k||w)&&D(!0),(T||L)&&D(!1),T&&(u([]),f(""))},[k,w,b,f,T,L,D,u,R]),M.useEffect(()=>{O&&(t.getQueryData(A)||I(),C(!1))},[O,I,C,A,t]);async function E(){const P=`Can you help me debug this query in the current table scope?
402
402
 
403
403
  Error:
404
404
 
@@ -410,11 +410,11 @@
410
410
 
411
411
  ${d?`Python:
412
412
  ${d}`:""}
413
- `;b(z)}function F(){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(Ka,{jsonString:JSON.stringify(m,null,2)})})}),m&&m.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 P(){return e.jsxs(s.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(s.ResizablePanel,{id:"1",order:1,defaultSize:a?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(Wa,{})}),a&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),a&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(s.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:[e.jsx("div",{id:"python-container",className:"relative flex w-[99%] pt-0",children:e.jsx(Ya,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function _(){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:D||w,onClick:()=>{v()},className:"h-8 shrink-0",size:"sm",children:[D||w?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(At,{sql:N==null?void 0:N.sql,error:y,onDebugWithAssistant:L}),e.jsx(s.EditorClearButton,{}),e.jsx(s.Toggle,{pressed:a,onPressedChange:z=>n(z),className:"",size:"sm",children:e.jsx(Ja,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:c,onClick:()=>{C(!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(s.EditorCancelButton,{}),e.jsx(s.EditorAcceptButton,{})]})]})}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:[P(),F()]}),_()]})}function Xa({data:t}){var c;const[a,n]=A.useState([]),l=Object.keys(t[0]).map(i=>({accessorKey:i,header:({column:d})=>{const m=d.getIsSorted();return e.jsx("div",{className:"flex gap-2",children:e.jsxs("div",{className:"flex cursor-pointer items-center",onClick:()=>d.toggleSorting(d.getIsSorted()==="asc"),children:[i,m==="asc"?e.jsx(s.TriangleUpIcon,{className:"ml-2 h-5 w-5"}):m==="desc"?e.jsx(s.TriangleDownIcon,{className:"ml-2 h-5 w-5"}):null]})})}})),o=s.useReactTable({data:t,columns:l,getCoreRowModel:s.getCoreRowModel(),getPaginationRowModel:s.getPaginationRowModel(),onSortingChange:n,getSortedRowModel:s.getSortedRowModel(),manualPagination:!0,state:{sorting:a}});return e.jsxs(s.CustomScrollArea,{className:"grow overflow-auto font-mono text-xs text-foreground/95",children:[e.jsxs("table",{className:"w-full",children:[e.jsx(s.TableHeader,{className:"sticky top-0 z-50 h-0 bg-muted",children:o.getHeaderGroups().map(i=>e.jsx(s.TableRow,{className:"",children:i.headers.map(d=>e.jsx(s.TableHead,{className:"h-11 font-semibold text-foreground",children:d.isPlaceholder?null:s.flexRender(d.column.columnDef.header,d.getContext())},d.id))},i.id))}),e.jsx(s.TableBody,{children:(c=o.getRowModel().rows)!=null&&c.length?o.getRowModel().rows.map(i=>e.jsx(s.TableRow,{className:"h-11 whitespace-nowrap py-2","data-state":i.getIsSelected()&&"selected",children:i.getVisibleCells().map(d=>e.jsx(s.TableCell,{className:"py-2",children:s.flexRender(d.column.columnDef.cell,d.getContext())},d.id))},i.id)):e.jsx(s.TableRow,{children:e.jsx(s.TableCell,{colSpan:l.length,className:"h-24 text-center",children:"No results."})})})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Za({card:t}){var b,C,O,S,E,N,D,w,M,k,R;const[a,n]=A.useState(!1),[r,l]=A.useState([]),{authToken:o}=s.useSemaphorContext(),c=s.getTokenParams(o==null?void 0:o.accessToken),i=s.useDashboardStore(I=>I.themeStyle),d={colors:((C=(b=i==null?void 0:i.chart)==null?void 0:b.dataset)==null?void 0:C.backgroundColor)||[]};(O=t.customCardPreferences)!=null&&O.inputData;const{getCard:m}=s.useCustomVisual(((S=t.customCardPreferences)==null?void 0:S.url)||""),h=((E=t.customCardPreferences)==null?void 0:E.visualType)||"single",u=s.useEditorStore(I=>I.frame),{setCustomCardPreferences:p}=s.useEditorActions(),{data:f}=s.useDashboardCardQuery(t),j=A.useCallback((I,v)=>{l(y=>({...y,[I]:v}))},[]);if(!((N=t.customCardPreferences)!=null&&N.componentName))return null;const x=m((D=t.customCardPreferences)==null?void 0:D.componentName);function T(I){n(I)}const g=Object.keys(((w=t.customCardPreferences)==null?void 0:w.dataInputCardIds)||{}).map(I=>{var L,F,P;const v=(F=(L=t.customCardPreferences)==null?void 0:L.dataInputCardIds)==null?void 0:F[I].cardId,y=(P=u==null?void 0:u.cards)==null?void 0:P.find(_=>_.id===v);return y||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:[x&&h==="single"&&e.jsx(x,{editing:!0,params:c,theme:d,settings:(M=t.customCardPreferences)==null?void 0:M.settings,onDataChange:j,data:(f==null?void 0:f.records)||[]}),x&&h==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((k=t.customCardPreferences)==null?void 0:k.dataInputCardIds)||{}).map(I=>{var L,F,P;const v=(F=(L=t.customCardPreferences)==null?void 0:L.dataInputCardIds)==null?void 0:F[I].cardId,y=(P=u==null?void 0:u.cards)==null?void 0:P.find(_=>_.id===v);if(y)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:T,onDataChange:j,dataInputIndex:I,card:y},y.id+I)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(x,{theme:d,onDataChange:j,settings:g.map(I=>{var v;return(v=I==null?void 0:I.customCardPreferences)==null?void 0:v.settings}),data:g.map(I=>I!=null&&I.id?r==null?void 0:r[I.id]:[])})})]})]},(R=t.customCardPreferences)==null?void 0:R.componentName)})}function Rt({className:t,...a}){var b;const n=s.useEditorStore(C=>C.card),r=s.isExplorerCard(n),l=((b=n.customCardPreferences)==null?void 0:b.showCardHeader)??!0,o=s.useEditorStore(C=>C.frame),c=s.useDashboardStore(C=>C.dashboard.filters);s.useEditorStore(C=>C.actions.setRunSql);const{updateFilter:i}=s.useDashboardActions(),d=c==null?void 0:c.find(C=>C.id===o.filterId),{data:m,isLoading:h,isFetching:u,errorMessage:p}=s.useDashboardCardQuery(n),{setCard:f}=s.useEditorActions(),{data:j}=s.useTopoJson(n),x=A.useMemo(()=>!n.id||!(m!=null&&m.records)?null:s.createChartConfig({card:n,data:m==null?void 0:m.records,cardType:n.type,queryConfig:n.queryConfig,customCfg:n.customCfg,preferences:n.preferences,topoJson:j}),[n.id,m==null?void 0:m.records,n.type,n.queryConfig,n.customCfg,n.preferences,j]);function T(C){return e.jsx(Za,{card:C})}function g(){if(m!=null&&m.records&&(m==null?void 0:m.records.length)===0&&!h&&!u)return p?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(!n.id)return null;if(n.type==="custom")return T(n);if(!["table","custom"].includes(n.type)&&x)return e.jsx(e.Fragment,{children:h||u?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:x})});if(n.type==="table"&&(m!=null&&m.records)&&(m==null?void 0:m.records.length)>0)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:n,data:m==null?void 0:m.records})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...a,children:[l&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{children:[e.jsx(s.Editable,{enabled:!0,text:n.title,onSave:C=>f({...n,title:C}),children:e.jsx("div",{className:"flex items-center gap-5",children:e.jsx(s.CardTitle,{className:"text-base",children:n.title||"Add title"})})},n.title),e.jsx(s.Editable,{enabled:!0,text:n.description||"",onSave:C=>f({...n,description:C}),children:e.jsx(s.CardDescription,{children:n.description||"Add description"})},n.description)]}),d&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Editable,{enabled:!0,className:"my-1",text:d.title||d.column,onSave:C=>i({...d,title:C}),children:e.jsx(s.Label,{children:d.title})}),e.jsx(s.FilterComponent,{filter:d})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:g()})]})}const ts=({language:t,value:a,onChange:n,readonly:r})=>e.jsx(s.Ft,{className:"h-full w-full overflow-hidden text-xs",theme:"default",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,lineHeight:16,renderLineHighlight:"none",readOnly:r},defaultLanguage:t,value:a,onChange:n}),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:a,mergedConfig:n,onConfigChange:r,onCodeChange:l})=>e.jsxs(s.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(s.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(s.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(s.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(s.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(s.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ts,{language:"json",value:n,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ts,{readonly:!0,language:"json",value:a,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ts,{language:"javascript",value:t,onChange:l})})]}),tr=({error:t,hasCardCustomConfig:a,onReset:n,onApply:r,onClose:l})=>e.jsxs(s.DialogFooter,{className:"flex items-center",children:[e.jsx(s.Label,{className:"mr-2 text-red-500",children:t}),e.jsx(s.Button,{disabled:!a,onClick:n,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:l,variant:"outline",children:"Close"})]});function nr(){const[t,a]=A.useState(!1),[n,r]=A.useState(""),[l,o]=A.useState(""),[c,i]=A.useState(""),[d,m]=A.useState(""),h=s.useEditorStore(S=>S.card),u=s.useEditorStore(S=>S.card.customCfg),p=u?JSON.stringify(u,null,2):"",{data:f}=s.useDashboardCardQuery(h),{data:j}=s.useTopoJson(h),{setCardCustomCfg:x,setCustomVisualCode:T}=s.useEditorActions(),g=S=>{var E,N;return JSON.stringify({...S,data:{...S.data,datasets:(N=(E=S.data)==null?void 0:E.datasets)==null?void 0:N.map(D=>({...D,data:[]}))}},null,2)},b=()=>{var E,N;if(!((E=f==null?void 0:f.records)!=null&&E.length))return;const S=s.createChartConfig({card:h,data:f.records,cardType:h.type,queryConfig:h.queryConfig,preferences:h.preferences,topoJson:j});if(S){r(g(S)),i(((N=h.preferences)==null?void 0:N.customVisualCode)||"");const D=s.merge(S,u);o(g(D))}},C=()=>{try{if(c&&T(c),l){const S=JSON.parse(l),E=s.getObjectDiff(JSON.parse(n),S);x(E),m("")}}catch{m("Invalid JSON configuration")}},O=Object.keys(u||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:a,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:b,className:O?"":"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.FallbackEditorCard,children:e.jsx(Rt,{className:"w-1/2 rounded shadow-none"})}),e.jsx(sr,{customCode:c,cardCustomCfgString:p,mergedConfig:l,onConfigChange:S=>o(S??""),onCodeChange:S=>i(S??"")})]}),e.jsx(tr,{error:d,hasCardCustomConfig:!!u,onReset:()=>{o(n),x(null)},onApply:C,onClose:()=>a(!1)})]})]})}function Ye(t){const[a,n]=A.useState(null);return a}function Cs(){const{authToken:t}=s.useSemaphorContext(),{data:a,isLoading:n,isFetching:r,isError:l}=s.useQuery({queryKey:["plugins",t==null?void 0:t.accessToken],queryFn:()=>s.getPlugins(t==null?void 0:t.accessToken)});return{data:a,isLoading:n,isFetching:r,isError:l}}function ar({onChartTypeChange:t}){const[a,n]=A.useState([]),{setCardCustomCfg:r,setCardPreferences:l,setCardType:o,setCustomCardPreferences:c}=s.useEditorActions(),{data:i}=Cs();function d(m,h){r(null),l({}),o(m),h&&c({type:"component",visualType:"single",url:h.url,componentName:h.name,icon:h.icon}),t==null||t()}return A.useEffect(()=>{(async()=>{var h;if(i){const p=(await Promise.all((h=i==null?void 0:i.plugins)==null?void 0:h.map(async f=>(await s.loadManifest(f.value)).visuals.map(T=>({name:T.name,icon:T.icon,url:f.value}))))).flat();n(p)}})()},[i]),a.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:a.map((m,h)=>e.jsx(rr,{text:m.name,onClick:()=>d("custom",m),icon:m.icon},m.url+m.name+h))})]})}const rr=({text:t,icon:a,onClick:n})=>{const r=Ye(),l=t.charAt(0).toUpperCase();return e.jsx(s.IconButton,{onClick:n,tooltip:t,children:r?e.jsx(r,{className:"h-4 w-4"}):l})};function Ss(t){return Se({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm87.63,96H191.48A64.1,64.1,0,0,0,136,64.52V40.37A88.13,88.13,0,0,1,215.63,120ZM120,120H80.68A48.09,48.09,0,0,1,120,80.68Zm0,16v39.32A48.09,48.09,0,0,1,80.68,136Zm16,0h39.32A48.09,48.09,0,0,1,136,175.32Zm0-16V80.68A48.09,48.09,0,0,1,175.32,120ZM120,40.37V64.52A64.1,64.1,0,0,0,64.52,120H40.37A88.13,88.13,0,0,1,120,40.37ZM40.37,136H64.52A64.1,64.1,0,0,0,120,191.48v24.15A88.13,88.13,0,0,1,40.37,136ZM136,215.63V191.48A64.1,64.1,0,0,0,191.48,136h24.15A88.13,88.13,0,0,1,136,215.63Z"},child:[]}]})(t)}function lr(t){return Se({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M48,180c0,11,7.18,20,16,20a14.24,14.24,0,0,0,10.22-4.66A8,8,0,0,1,85.78,206.4,30.06,30.06,0,0,1,64,216c-17.65,0-32-16.15-32-36s14.35-36,32-36a30.06,30.06,0,0,1,21.78,9.6,8,8,0,0,1-11.56,11.06A14.24,14.24,0,0,0,64,160C55.18,160,48,169,48,180Zm79.6-8.69c-4-1.16-8.14-2.35-10.45-3.84-1.25-.81-1.23-1-1.12-1.9a4.57,4.57,0,0,1,2-3.67c4.6-3.12,15.34-1.73,19.82-.56A8,8,0,0,0,142,145.86c-2.12-.55-21-5.22-32.84,2.76a20.58,20.58,0,0,0-9,14.95c-2,15.88,13.65,20.41,23,23.11,12.06,3.49,13.12,4.92,12.78,7.59-.31,2.41-1.26,3.34-2.14,3.93-4.6,3.06-15.17,1.56-19.55.36A8,8,0,0,0,109.94,214a61.34,61.34,0,0,0,15.19,2c5.82,0,12.3-1,17.49-4.46a20.82,20.82,0,0,0,9.19-15.23C154,179,137.49,174.17,127.6,171.31Zm83.09-26.84a8,8,0,0,0-10.23,4.84L188,184.21l-12.47-34.9a8,8,0,0,0-15.07,5.38l20,56a8,8,0,0,0,15.07,0l20-56A8,8,0,0,0,210.69,144.47ZM216,88v24a8,8,0,0,1-16,0V96H152a8,8,0,0,1-8-8V40H56v72a8,8,0,0,1-16,0V40A16,16,0,0,1,56,24h96a8,8,0,0,1,5.66,2.34l56,56A8,8,0,0,1,216,88Zm-27.31-8L160,51.31V80Z"},child:[]}]})(t)}function ws(t){return Se({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M6 16m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"},child:[]},{tag:"path",attr:{d:"M16 19m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"},child:[]},{tag:"path",attr:{d:"M14.5 7.5m-4.5 0a4.5 4.5 0 1 0 9 0a4.5 4.5 0 1 0 -9 0"},child:[]}]})(t)}function Ts(t){return Se({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M4.387 3h15.226a1 1 0 0 1 .948 1.316l-5.105 15.316a2 2 0 0 1 -1.898 1.368h-3.116a2 2 0 0 1 -1.898 -1.368l-5.104 -15.316a1 1 0 0 1 .947 -1.316"},child:[]},{tag:"path",attr:{d:"M5 9h14"},child:[]},{tag:"path",attr:{d:"M7 15h10"},child:[]}]})(t)}function ks(t){return Se({attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"m2 19.99 7.5-7.51 4 4 7.09-7.97L22 9.92l-8.5 9.56-4-4-6 6.01-1.5-1.5zm1.5-4.5 6-6.01 4 4L22 3.92l-1.41-1.41-7.09 7.97-4-4L2 13.99l1.5 1.5z"},child:[]}]})(t)}function Ds(t){return Se({attr:{version:"1.2",baseProfile:"tiny",viewBox:"0 0 24 24"},child:[{tag:"path",attr:{d:"M4 18c-.552 0-1-.448-1-1v-6.382l-.553.276c-.495.248-1.095.046-1.342-.447-.247-.494-.046-1.094.448-1.342l2-1c.31-.155.678-.139.973.044.294.183.474.504.474.851v8c0 .552-.448 1-1 1zM13 18h-5c-.404 0-.769-.244-.924-.617-.155-.374-.069-.804.217-1.09l4-4c.254-.254.394-.591.394-.95 0-.358-.14-.695-.394-.949-.508-.508-1.39-.508-1.9.001-.253.252-.393.589-.393.948 0 .552-.448 1-1 1s-1-.448-1-1c0-.894.348-1.733.98-2.364 1.265-1.263 3.464-1.263 4.727.001.632.631.979 1.471.979 2.363 0 .893-.348 1.733-.979 2.364l-2.293 2.293h2.586c.552 0 1 .448 1 1s-.448 1-1 1zM20.955 12.377c.338-.457.545-1.016.545-1.627 0-1.517-1.234-2.75-2.75-2.75-1.031 0-1.966.569-2.44 1.484-.254.49-.063 1.094.428 1.348.49.254 1.094.062 1.348-.428.128-.249.383-.404.664-.404.414 0 .75.336.75.75s-.336.75-.75.75c-.552 0-1 .448-1 1s.448 1 1 1c.689 0 1.25.561 1.25 1.25s-.561 1.25-1.25 1.25-1.25-.561-1.25-1.25c0-.552-.448-1-1-1s-1 .448-1 1c0 1.792 1.458 3.25 3.25 3.25s3.25-1.458 3.25-3.25c0-.939-.406-1.779-1.045-2.373z"},child:[]}]})(t)}function Bt({onChartTypeChange:t,iconClassName:a}){const{setCardType:n,setCardPreferences:r,setIsDevMode:l}=s.useEditorStore(h=>h.actions),{setCardCustomCfg:o,setCustomCardPreferences:c,setQueryConfig:i}=s.useEditorActions();function d(h,u){o(null),r({}),n(h),["custom","text","map"].includes(h)&&(l(!0),i(void 0)),t==null||t()}const m=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(s.IconButton,{openDelay:m,tooltip:"Table",onClick:()=>d("table"),className:"h-10 p-4",children:e.jsx(Je,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Bar Chart",onClick:()=>d("bar"),className:"h-10 p-4",children:e.jsx($e,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Line Chart",onClick:()=>d("line"),className:"h-10 p-4",children:e.jsx(Ge,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Stacked Bar Chart",onClick:()=>d("stackedBar"),className:"h-10 p-4",children:e.jsx(ms,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Stacked Line Chart",onClick:()=>d("stackedLine"),className:"h-10 p-4",children:e.jsx(ks,{className:s.cn("size-5",a),strokeWidth:0})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Scatter Chart",onClick:()=>d("scatter"),className:"h-10 p-4",children:e.jsx(xs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Bubble Chart",onClick:()=>d("bubble"),className:"h-10 p-4",children:e.jsx(ws,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Pie Chart",onClick:()=>d("pie"),className:"h-10 p-4",children:e.jsx(He,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Doughnut Chart",onClick:()=>d("doughnut"),className:"h-10 p-4",children:e.jsx(ps,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Funnel Chart",onClick:()=>d("funnel"),className:"h-10 p-4",children:e.jsx(Ts,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Radar Chart",onClick:()=>d("radar"),className:"h-10 p-4",children:e.jsx(js,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Polar Area Chart",onClick:()=>d("polarArea"),className:"h-10 p-4",children:e.jsx(Ss,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Tornado Chart",onClick:()=>d("tornado"),className:"h-10 p-4",children:e.jsx(ys,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Range Chart",onClick:()=>d("range"),className:"h-10 p-4",children:e.jsx(hs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"KPI",onClick:()=>d("kpi"),className:"h-10 p-4",children:e.jsx(Ds,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Text",onClick:()=>d("text"),className:"h-10 p-4",children:e.jsx(Zs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Map",onClick:()=>d("map"),className:"h-10 p-4",children:e.jsx(gs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Custom",onClick:()=>d("custom"),className:"h-10 p-4",children:e.jsx(Ae,{className:s.cn("size-5",a)})})]})}function or({chartType:t,className:a,customIcon:n,componentName:r}){const l=Ye();switch(t){case"bar":return e.jsx($e,{className:a});case"line":return e.jsx(Ge,{className:a});case"pie":return e.jsx(He,{className:a});case"radar":return e.jsx(js,{className:a});case"scatter":return e.jsx(xs,{className:a});case"bubble":return e.jsx(ws,{className:a});case"doughnut":return e.jsx(ps,{className:a});case"stackedBar":return e.jsx(ms,{className:a});case"stackedLine":return e.jsx(ks,{className:a});case"polarArea":return e.jsx(Ss,{className:a});case"funnel":return e.jsx(Ts,{className:a});case"tornado":case"pyramid":return e.jsx(ys,{className:a});case"range":return e.jsx(hs,{className:a});case"kpi":return e.jsx(Ds,{className:a});case"text":return e.jsx(it,{className:a});case"map":return e.jsx(gs,{className:a});case"custom":return n&&l?e.jsx(l,{className:a}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(Ae,{className:a});default:return e.jsx(Je,{className:a})}}function Ft({variant:t="ghost"}){var o,c;const[a,n]=A.useState(!1),r=s.useEditorStore(i=>i.card),l=r.type;return s.useDashboardStore(i=>i.isVisualEditing),e.jsxs(s.Popover,{open:a,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(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:"w-72 p-1",children:[e.jsx(Bt,{onChartTypeChange:()=>n(!1)}),e.jsx(ar,{onChartTypeChange:()=>n(!1)})]})]})}const Oe="focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0";function Js(t,a){var r,l,o;const n=s.getNumberAxis(t,{});return["pie","doughnut","polarArea","funnel"].includes(a)?"category":((o=(l=(r=t==null?void 0:t.chartOptions)==null?void 0:r.scales)==null?void 0:l[n])==null?void 0:o.type)||"linear"}function ir(){var L,F,P,_,z,Q;const[t,a]=A.useState(!1),n=s.useEditorStore(Y=>{var V;return(V=Y.card)==null?void 0:V.preferences}),r=s.useEditorStore(Y=>{var V;return(V=Y.card)==null?void 0:V.type}),l=s.getNumberAxis(n,{}),[o,c]=A.useState(Js(n,r)),[i,d]=A.useState(((P=(F=(L=n==null?void 0:n.chartOptions)==null?void 0:L.scales)==null?void 0:F[l])==null?void 0:P.min)||""),[m,h]=A.useState(((Q=(z=(_=n==null?void 0:n.chartOptions)==null?void 0:_.scales)==null?void 0:z[l])==null?void 0:Q.max)||""),[u,p]=A.useState(i||m?"custom":"auto"),[f,j]=A.useState(""),[x,T]=A.useState(0),[g,b]=A.useState(""),[C,O]=A.useState(""),[S,E]=A.useState(""),N=s.useEditorStore(Y=>Y.actions.setCardPreferences),{updateCardInFrame:D}=s.useEditorActions(),w=s.useEditorStore(Y=>Y.card),M=["pie","doughnut","polarArea","funnel"].includes(r);A.useEffect(()=>{var Y,V,q,$,U,H,W,G,Z,se,ne,ee,ae,J;c(Js(n,r)),d(((q=(V=(Y=n==null?void 0:n.chartOptions)==null?void 0:Y.scales)==null?void 0:V[l])==null?void 0:q.min)===0?0:""),h(((H=(U=($=n==null?void 0:n.chartOptions)==null?void 0:$.scales)==null?void 0:U[l])==null?void 0:H.max)||""),j(((se=(Z=(G=(W=n==null?void 0:n.chartOptions)==null?void 0:W.scales)==null?void 0:G[l])==null?void 0:Z.ticks)==null?void 0:se.stepSize)||""),T(((ne=n==null?void 0:n.numberAxisFormat)==null?void 0:ne.decimalPlaces)||0),b(((ee=n==null?void 0:n.numberAxisFormat)==null?void 0:ee.suffix)||""),O(((ae=n==null?void 0:n.numberAxisFormat)==null?void 0:ae.currency)||""),E(((J=n==null?void 0:n.numberAxisFormat)==null?void 0:J.locale)||"")},[t,n,l,r]);function k(Y,V){return V===""||/^[0-9\b]+$/.test(V)?Number(V):Number(Y)}function R(){const Y=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(V=>V.currency))];return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-6 items-center gap-2",children:[e.jsx(s.Label,{className:"col-span-2 hover:cursor-pointer hover:underline",htmlFor:"currency",children:e.jsx("a",{target:"_blank",href:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat",children:"Currency"})}),e.jsxs(s.Select,{value:C||"none",onValueChange:V=>O(V==="none"?"":V),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 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"}),Y.map(V=>e.jsx(s.SelectItem,{value:V,children:V},V))]})})]}),e.jsxs(s.Select,{value:S,onValueChange:V=>E(V),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 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:"Locale"}),s.LOCALE_CURRENCY_PAIRS.map(V=>e.jsx(s.SelectItem,{value:V.locale,children:V.locale},V.locale))]})})]})]}),e.jsxs("div",{className:"grid grid-cols-9 items-center gap-2",children:[e.jsx(s.Label,{className:"col-span-3",htmlFor:"format",children:"Decimals"}),e.jsx(s.Input,{value:x,onChange:V=>T(Number(V.target.value)),id:"format",className:`col-span-6 h-8 w-full tracking-wide ${Oe}`})]})]})}function I(){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-4 space-y-2",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the scale for number axis"})}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 items-center gap-2",children:[e.jsx(s.Label,{htmlFor:"scale",children:"Type"}),e.jsxs(s.Select,{disabled:M,value:o,onValueChange:Y=>c(Y),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{id:"type",children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Option"}),e.jsx(s.SelectItem,{value:"linear",children:"Linear"}),e.jsx(s.SelectItem,{value:"logarithmic",children:"Logarithmic"}),e.jsx(s.SelectItem,{value:"category",children:"Category"})]})})]})]}),o=="linear"&&e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2 py-1",children:[e.jsx(s.Label,{htmlFor:"scale-option",children:"Setup"}),e.jsxs(s.RadioGroup,{disabled:M,id:"scale-option",value:u,onValueChange:Y=>p(Y),className:"col-span-2 flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"auto",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Auto"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"custom",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Custom"})]})]})]}),u==="custom"&&o=="linear"&&v()]})}function v(){return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(s.Label,{htmlFor:"range",children:"Range"}),e.jsx(s.Input,{id:"min",value:i,onChange:Y=>d(V=>k(V,Y.target.value)),className:`col-span-1 h-8 w-full ${Oe}`}),e.jsx(s.Input,{value:m,onChange:Y=>h(V=>k(V,Y.target.value)),id:"max",className:`col-span-1 h-8 w-full ${Oe}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(s.Label,{htmlFor:"step-size",children:"Step Size"}),e.jsx(s.Input,{value:f,onChange:Y=>j(V=>k(V,Y.target.value)),id:"step-size",className:`col-span-1 h-8 w-full ${Oe}`})]})]})}function y(){var $;let Y={};u==="custom"&&(Y={min:i,max:m,ticks:{stepSize:f}});const V={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,scales:{...($=n==null?void 0:n.chartOptions)==null?void 0:$.scales,[l]:{type:o,...o==="linear"?Y:{}}}},numberAxisFormat:{decimalPlaces:x,suffix:g,currency:C,locale:S}};console.log(V),N(V);const q={...w,preferences:V};D(q)}return e.jsxs(s.Popover,{onOpenChange:Y=>a(Y),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Format Number",children:e.jsx(Dn,{className:"size-4"})})}),e.jsx(s.PopoverContentCustom,{align:"end",className:"max-w-65 z-[51]",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Format Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the format for number axis"})]}),e.jsxs("div",{className:"grid gap-2",children:[R(),I(),e.jsx(s.SelectSeparator,{}),e.jsx("div",{className:"grid grid-cols-3",children:e.jsx(s.Button,{onClick:y,variant:"secondary",className:"col-span-1 col-start-3 h-8 w-full",children:"Apply"})})]})]})})]})}function cr(){const t=s.useEditorStore(i=>{var d,m,h,u;return(u=(h=(m=(d=i.card.preferences)==null?void 0:d.chartOptions)==null?void 0:m.plugins)==null?void 0:h.legend)==null?void 0:u.position}),a=s.useEditorStore(i=>{var d,m,h,u;return(u=(h=(m=(d=i.card.preferences)==null?void 0:d.chartOptions)==null?void 0:m.plugins)==null?void 0:h.legend)==null?void 0:u.align}),n=s.useEditorStore(i=>{var d,m,h,u;return(u=(h=(m=(d=i.card.preferences)==null?void 0:d.chartOptions)==null?void 0:m.plugins)==null?void 0:h.legend)==null?void 0:u.display}),{setLegendOptions:r}=s.useEditorActions(),l=i=>{r({display:i,position:t,align:a})},o=i=>{r({display:n,position:i,align:a})},c=i=>{r({display:n,position:t,align:i})};return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Legend Settings",children:e.jsx(Pn,{className:"size-4"})})}),e.jsx(s.PopoverContentCustom,{align:"end",className:"z-[51] w-72",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Legend Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the legend options for the chart."})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"displayLegend",children:"Display"}),e.jsx("div",{className:"col-span-2 flex h-8 items-center",children:e.jsx(s.SmallSwitch,{checked:n,onCheckedChange:l,id:"displayLegend"})})]}),n&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"position",children:"Position"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(s.IconButton,{tooltip:"Top",onClick:()=>o("top"),children:e.jsx(s.ArrowUp,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Left",onClick:()=>o("left"),children:e.jsx(hn,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Bottom",onClick:()=>o("bottom"),children:e.jsx(s.ArrowDown,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Right",onClick:()=>o("right"),children:e.jsx(xn,{className:"size-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"align",children:"Align"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(s.IconButton,{tooltip:"Start",onClick:()=>c("start"),children:e.jsx(on,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Center",onClick:()=>c("center"),children:e.jsx(ln,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"End",onClick:()=>c("end"),children:e.jsx(cn,{className:"size-4"})})]})]})]})]})]})})]})}function dr(){const t=s.useEditorStore(o=>{var c,i;return(i=(c=o.card.preferences)==null?void 0:c.chartOptions)==null?void 0:i.indexAxis}),a=s.useEditorStore(o=>o.card.type),{setChartOrientation:n}=s.useEditorStore(o=>o.actions);function r(){return e.jsx(s.IconButton,{onClick:()=>{n(t==="x"||t===void 0?"y":"x")},tooltip:"Chart Orientation",children:t==="x"||t===void 0?e.jsx(_s,{className:"size-4"}):e.jsx(Ps,{className:"size-4"})})}function l(){return e.jsx(s.IconButton,{onClick:()=>{n(t==="y"||t===void 0?"x":"y")},tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(_s,{className:"size-4"}):e.jsx(Ps,{className:"size-4"})})}return e.jsx(e.Fragment,{children:a==="funnel"?l():r()})}function zt(){const t=s.useEditorStore(c=>c.card),a=s.useEditorStore(c=>c.isShowingVisual),n=s.useEditorStore(c=>{var i,d;return(d=(i=c.card)==null?void 0:i.preferences)==null?void 0:d.chartOptions}),r=s.getChartGridStyle(n),{setChartGrid:l}=s.useEditorActions();function o(){const c=["xy","none","x","y"],d=(c.indexOf(r)+1)%c.length;l(c[d])}return a?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(dr,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsxs(e.Fragment,{children:[e.jsx(ir,{}),e.jsx(cr,{})]}),!["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(Bn,{className:"size-4"}),r==="x"&&e.jsx(wn,{className:"size-4"}),r==="y"&&e.jsx(Qn,{className:"size-4"}),r==="none"&&e.jsx(ta,{className:"size-4"})]})]}):null}function ur(){const t=s.useEditorStore(j=>j.frame),a=s.useEditorStore(j=>j.card),{setFrame:n,setActiveTabCardId:r,setCard:l,updateCardInFrame:o}=s.useEditorActions(),c=(j,x)=>{j.dataTransfer.setData("tabIndex",x.toString())},i=j=>{j.preventDefault()},d=(j,x)=>{const T=j.dataTransfer.getData("tabIndex");if(T===x.toString())return;const g=Array.from(t.cards),[b]=g.splice(parseInt(T),1);g.splice(x,0,b),n({...t,cards:g})};function m(j){const x=t.cards.filter(b=>b.id!==j),T=x[0],g={...t,cards:x,activeCardId:T.id};n(g),r(T.id),l(T)}function h(j,x){const T={...t,cards:[...t.cards,x],activeCardId:j.id};n(T),r(x.id)}function u(){const j={...a,id:s.v4(),title:`${a.title} Copy`,tabTitle:`${a.tabTitle||a.title} Copy`};h(a,j)}function p(j){const x={dataSource:j.dataSource,connectionId:j.connectionId,lastSelectedDatabase:j.lastSelectedDatabase,lastSelectedSchema:j.lastSelectedSchema,lastSelectedTable:j.lastSelectedTable,lastSelectedDatamodelId:j.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};h(j,x)}function f(j,x){return j.cards.length===1&&(x.displayTab===!0||x.displayTab===void 0)||j.activeCardId!==x.id&&(x.displayTab===!0||x.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const T=x.displayTab===void 0?!1:!x.displayTab;l({...x,displayTab:T}),o({...x,displayTab:T})},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(En,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(s.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[t.cards.map((j,x)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:T=>c(T,x),onDragOver:i,onDrop:T=>d(T,x),className:"",value:j.id,children:[f(t,j),e.jsx(s.Editable,{enabled:t.activeCardId===j.id,text:j.tabTitle||j.title,onSave:T=>{l({...a,tabTitle:T}),o({...a,tabTitle:T})},children:j.tabTitle||j.title},j.id),t.activeCardId===j.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>m(j.id)})]},j.id)),e.jsx(s.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>p(a),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:u,children:e.jsx(kn,{className:"h-4 w-4"})})]})})}function Pt(){const t=s.useEditorStore(x=>x.frame),a=s.useEditorStore(x=>x.card),n=s.useEditorStore(x=>x.isSqlRunning),r=s.useEditorStore(x=>x.isDevMode),{setFrame:l,setActiveTabCardId:o,setCard:c,setIsDevMode:i,setRunSql:d}=s.useEditorActions(),{data:m,isLoading:h,isFetching:u}=s.useDashboardCardQuery(a);function p(x){const T=t.cards.find(g=>g.id===x);if(T!=null&&T.sql){r||i(!0),o(x);return}if(T!=null&&T.queryConfig){r&&i(!1),f(x),o(x);return}r||f(x),o(x)}function f(x){const T={...t,cards:t.cards.map(b=>b.id===a.id?a:b),activeCardId:x};l(T);const g=T.cards.find(b=>b.id===x);g.sql&&d(!0),c(g)}function j(){return a.type==="kpi"?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.KPICard,{card:a,data:m==null?void 0:m.records,isPending:h})})}):a.type==="text"?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:n,card:a,data:m==null?void 0:m.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackEditorCard,children:e.jsx(Rt,{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:j()},x.id)),e.jsx(ur,{})]})}function Re({children:t}){s.useEditorStore(b=>b.frame);const a=s.useEditorStore(b=>b.card),n=s.useEditorStore(b=>b.isDevMode),r=s.useEditorStore(b=>b.isShowingVisual),l=s.useDashboardStore(b=>b.isVisualEditing),o=s.useEditorStore(b=>b.pythonStdOut);s.useEditorStore(b=>b.actions.setRunSql);const{setFrame:c,setCard:i,setActiveTabCardId:d,runAssistant:m,setIsDevMode:h}=s.useEditorActions(),{data:u,isLoading:p,isFetching:f,errorMessage:j}=s.useDashboardCardQuery(a);function x(){const b=JSON.stringify(u==null?void 0:u.records,null,2),C=new Blob([b],{type:"application/json"}),O=URL.createObjectURL(C),S=document.createElement("a");S.href=O,S.download=`${a.title}.json`,S.click()}function T(){const C=[Object.keys(u==null?void 0:u.records.reduce((N,D)=>({...N,...D}),{})).join(","),...((u==null?void 0:u.records)||[]).map(N=>Object.values(N).join(","))].join(`
414
- `),O=new Blob([C],{type:"text/csv"}),S=URL.createObjectURL(O),E=document.createElement("a");E.href=S,E.download=`${a.title}.csv`,E.click()}function g(){const b=`Can you get the documentation for ${a.type} chart?`;m(b)}return a?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[(p||f)&&e.jsx("div",{className:"absolute bottom-0 left-0 right-0 top-0 z-50 m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),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(Ft,{}),l&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:g,children:e.jsx(jn,{className:"size-4"})}),!["table","custom"].includes(a.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:T,children:e.jsx(lr,{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:x,children:e.jsx(An,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(u==null?void 0:u.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(zt,{})]}),n&&e.jsx(hr,{})]}),r?e.jsx(Pt,{}):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:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:[(u==null?void 0:u.records)&&(u==null?void 0:u.records.length)>0&&e.jsx(Xa,{data:(u==null?void 0:u.records)||[]}),j&&e.jsx(Et,{error:j})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function mr(){const t=s.useEditorStore(n=>n.pythonStdOut);if(!t)return null;const a=t.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col border-r",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center border-b bg-muted px-3 font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(s.ScrollArea,{className:"overflow-y-auto px-2 pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:a}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function hr(){const t=s.useEditorStore(n=>n.isShowingVisual),a=s.useEditorStore(n=>n.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(s.SmallSwitch,{checked:t,onCheckedChange:()=>a(!t),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function xr(){var x,T;const t=s.useEditorStore(g=>g.card.customCardPreferences),{data:a}=Cs(),n=(a==null?void 0:a.plugins)||[],r=s.useEditorStore(g=>g.card),l=s.useEditorStore(g=>g.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)||""),m=(x=d==null?void 0:d.visuals)==null?void 0:x.find(g=>g.name===(t==null?void 0:t.componentName));function h(g,b){if(!t)return;const O={...(t==null?void 0:t.dataInputCardIds)||{},[g]:{cardId:b,hookRef:null}};c({...t,dataInputCardIds:O})}function u(g){var C,O;const b=(C=l==null?void 0:l.cards)==null?void 0:C.filter(S=>{var E;return((E=S==null?void 0:S.customCardPreferences)==null?void 0:E.visualType)!=="multiple"}).map(S=>({value:S.id,label:S.tabTitle||S.title}));return e.jsx("div",{className:"space-y-2",children:(O=g==null?void 0:g.dataInputs)==null?void 0:O.map((S,E)=>{var N,D;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:S}),e.jsx(ce,{className:"col-span-6 h-8 w-full justify-between",label:"",options:b||[],value:((D=(N=t==null?void 0:t.dataInputCardIds)==null?void 0:N[E])==null?void 0:D.cardId)||"",onValueChange:w=>h(E,w)})]},E+Math.random())})})}function p(g,b,C=[],O=""){var S,E;return t?g==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((S=t==null?void 0:t.settings)==null?void 0:S[b])||O,onChange:N=>{c({...t,settings:{...t==null?void 0:t.settings,[b]:N.target.value}})}},b):g==="select"?e.jsx(ce,{className:"h-8 w-full",label:"",options:C,value:((E=t==null?void 0:t.settings)==null?void 0:E[b])||O,onValueChange:N=>{c({...t,settings:{...t==null?void 0:t.settings,[b]:N}})}}):null:null}function f(g){const b=Object.entries((g==null?void 0:g.settings)||{});return e.jsx("div",{className:"space-y-3",children:b.map(([C,O])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:O.title}),p(O.ui,C,O.options,O.defaultValue)]},C))})}function j(g){t&&c({...t,visualType:g,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(gn,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(t==null?void 0:t.url)||"",onValueChange:g=>c({...t||{url:"",componentName:""},url:g})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:o,onValueChange:j,children:e.jsxs(s.TabsList,{className:"h-9 w-full",children:[e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&e.jsx(e.Fragment,{children:i&&e.jsx(ce,{icon:e.jsx(Tn,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(i==null?void 0:i.filter(g=>g.type===o).map(g=>({value:g.name,label:g.name})))||[],value:t.componentName,onValueChange:g=>{console.log("changing value",g),c({...t,componentName:g})}})})]})})]}),((T=r==null?void 0:r.customCardPreferences)==null?void 0:T.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{children:[m&&m.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:u(m)})]}),m&&m.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:f(m)})})]})]})]})}function we(){const[t,a]=A.useState([]),n=s.useEditorStore(m=>m.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:l}=s.useEditorStore(m=>m.actions),o=s.useEditorStore(m=>m.queryResultColumns);s.useEditorStore(m=>{var h;return(h=m.card.preferences)==null?void 0:h.filterOnClickColumnIndex}),A.useEffect(()=>{o&&a(new Array(o.length).fill(!1))},[o]);function c(m,h){var u,p;h?n!=null&&n.onClickFilter&&((u=n==null?void 0:n.onClickFilter)==null?void 0:u.length)>0?l({...n,onClickFilter:[...n.onClickFilter,{columnIndex:m,expression:""}]}):l({...n,onClickFilter:[{columnIndex:m,expression:""}]}):(l({...n,onClickFilter:(p=n==null?void 0:n.onClickFilter)==null?void 0:p.filter(f=>f.columnIndex!==m)}),a(f=>{const j=[...f];return j[m]=!1,j}))}function i(m,h){var p;const u=(p=n==null?void 0:n.onClickFilter)==null?void 0:p.map(f=>f.columnIndex===m?{...f,expression:h.target.value}:f);l({...n,onClickFilter:u})}function d(m){var h,u,p,f;if(t!=null&&t[m]||(u=(h=n==null?void 0:n.onClickFilter)==null?void 0:h.find(j=>j.columnIndex===m))!=null&&u.expression)return e.jsx(s.Input,{value:(f=(p=n==null?void 0:n.onClickFilter)==null?void 0:p.find(j=>j.columnIndex===m))==null?void 0:f.expression,onChange:j=>i(m,j),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsxs("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:[e.jsx(s.Label,{children:"On Click"}),o==null?void 0:o.map((m,h)=>{var u,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:!!((u=n==null?void 0:n.onClickFilter)!=null&&u.find(f=>f.columnIndex===h)),onCheckedChange:f=>c(h,f)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:m}),e.jsx("div",{className:"flex items-center gap-2",children:((p=n==null?void 0:n.onClickFilter)==null?void 0:p.find(f=>f.columnIndex===h))&&e.jsx(s.Pencil,{onClick:()=>{a(f=>{const j=[...f];return j[h]=!f[h],j})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(h)]})},m)})]})}function pr({idx:t}){var i;const a=s.useEditorStore(d=>{var m;return(m=d.card)==null?void 0:m.preferences}),n=s.useEditorStore(d=>{var m;return(m=d.card.preferences)==null?void 0:m.datasetOptions}),r=s.useEditorStore(d=>d.actions.setCardPreferences),l=(i=a==null?void 0:a.chartOptions)==null?void 0:i.indexAxis,o=n==null?void 0:n.find(d=>d.idx===t);function c(d,m){(d==="end"||d==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const h={display:d!=="none",align:d,anchor:d,clamp:!0};if(!o)r({...a,datasetOptions:[...n||[],{idx:m,datalabels:h}]});else{const u={...o};u.datalabels=h;const p=n==null?void 0:n.map(f=>f.idx===m?u:f);r({...a,datasetOptions:p})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(lt,{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(_n,{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(Un,{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(Vn,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function fr(){const t=s.useEditorStore(o=>o.card),{data:a}=s.useDashboardCardQuery(t),{keys:n}=s.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(o=>!s.METADATA_KEYS.includes(o));let l=r;if(["stackedBar","stackedLine"].includes(t.type)){const o=s.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:c}=s.getKeys(o);l=c.slice(1)}return{transformedMetricKeys:l,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}function Es({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function _t(){const t=s.useEditorStore(d=>d.card),a=s.useEditorStore(d=>{var m,h,u;return(u=(h=(m=d==null?void 0:d.card)==null?void 0:m.preferences)==null?void 0:h.chartOptions)==null?void 0:u.indexAxis}),{data:n}=s.useDashboardCardQuery(t),r=a==="y"?"Metric":"Dimension",l=a==="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:Vt(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,m)=>e.jsx(Ut,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:d,idx:m},d))})]})]})}function Vt(t,a=30){return t.length>a?t.slice(0,a)+"...":t}function Ut({col:t,idx:a,className:n,iconClassName:r,children:l}){const o=s.useEditorStore(h=>{var u;return(u=h.card)==null?void 0:u.preferences}),c=s.useEditorStore(h=>{var u,p;return(p=(u=h.card)==null?void 0:u.preferences)==null?void 0:p.datasetOptions}),i=c==null?void 0:c.find(h=>h.idx===a),{setCardPreferences:d}=s.useEditorStore(h=>h.actions);function m(h){if(!i)d({...o,datasetOptions:[...c||[],{idx:a,type:h==="area"?"line":h,fill:h==="area"?"origin":""}]});else{const u={...i};u.type=h==="area"?"line":h,u.fill=h==="area"?"origin":"";const p=c==null?void 0:c.map(f=>f.idx===a?u:f);d({...o,datasetOptions:p})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[l||e.jsx(Es,{className:"max-w-[100px]",title:t,children:Vt(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($e,{onClick:()=>m("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(Ge,{onClick:()=>m("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(et,{onClick:()=>m("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(pr,{idx:a})]})]})}function qt(){const t=s.useEditorStore(f=>f.selectedConnectionId),a=s.useEditorStore(f=>f.selectedDatamodelId),n=s.useEditorStore(f=>f.selectedDatabaseName),r=s.useEditorStore(f=>f.selectedSchemaName),l=s.useEditorStore(f=>f.selectedTableName),o=s.useDashboardStore(f=>f.dashboard.filters)||[],c=s.useDashboardStore(f=>f.actions.addFilter),i=s.useDashboardStore(f=>f.actions.removeFilter),{removeFilterValues:d}=s.useDashboardActions(),{modelItems:m,tableName:h,connectionType:u}=s.useEditorAside();function p(f,j="dashboard"){var N;const x=s.fmt(f.column_name),T=s.fmt(n||""),g=s.fmt(r||""),b=s.fmt(h);let C=s.getQualifiedTableName({schemaName:g,tableName:b,connectionType:u,databaseName:T}),O=`${C}.${x}`;const S=(N=m==null?void 0:m.find(D=>D.id===a))==null?void 0:N.name;a&&a!=="none"&&(O=`${s.DATAMODEL_NAMESPCACE}.${S}.${x}`,C=`${s.DATAMODEL_NAMESPCACE}.${S}`);const E=o==null?void 0:o.find(D=>D.column===O&&D.table===b&&(D.database===T||D.database===n));if(E)d(E.id),i(E.id);else{const D=s.v4();return h==="api"&&t?(c({location:j,id:D,column:O,title:f.column_name,dataType:f.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(f.data_type,C,x)}),D):(c({id:D,location:j,column:O,title:f.column_name,dataType:f.data_type,table:l||"",database:n||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(f.data_type,C,x)}),D)}}return{assignFilter:p}}function Ee(){const t=s.useDashboardStore(i=>i.dashboard.filters),a=s.useEditorStore(i=>i.frame),{setFrame:n}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=qt();function o(i){const d=l(i,"frame");n({...a,filterId:d})}const c=t==null?void 0:t.find(i=>i.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(gr,{onSelect:o,columns:r}),c&&e.jsx(s.FilterHeader,{filter:c})]})}function gr({columns:t,onSelect:a}){var c;const[n,r]=ye.useState(!1),[l,o]=ye.useState("");return e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[l?(c=t.find(i=>i.column_name===l))==null?void 0:c.column_name:"Select Column...",e.jsx(s.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No framework found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(i=>e.jsxs(s.CommandItem,{value:i.column_name,onSelect:d=>{const m=d===l?"":d;o(m),r(!1),m&&a(i)},children:[i.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",l===i.column_name?"opacity-100":"opacity-0")})]},i.column_name))})]})]})})]})}function 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:a=>a.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(_t,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(we,{}),e.jsx(Ee,{})]})]})]})})}function Ke(){const t=s.useEditorStore(i=>i.card.type),a=s.useEditorStore(i=>i.isDevMode),n=s.useEditorStore(i=>i.card.preferences),{setCardPreferences:r}=s.useEditorStore(i=>i.actions);function l(i){var h;const d={datalabels:{display:i!=="none",align:i,anchor:i,clamp:!0}},m={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(h=n==null?void 0:n.chartOptions)==null?void 0:h.plugins,...d}}};r(m)}function o(){var i,d,m;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((m=(d=(i=n==null?void 0:n.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:m.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,m;return e.jsx("div",{children:e.jsxs(s.Select,{value:((m=(d=(i=n==null?void 0:n.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:m.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(s.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:a?o():c()})}function yr({cardType:t}){function a(n){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:n==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),n==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:o=>o.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsx(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:a(t)})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"px-2",children:e.jsx(Ke,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(we,{}),e.jsx(Ee,{})]})]})]})})}const vr={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},br={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function Nr(){const t=s.useEditorStore(a=>a.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:Cr(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ke,{}),e.jsx(we,{}),e.jsx(Ee,{})]})]})}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(br,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(){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(s.FormatNumberSetting,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function ns({children:t,summary:a,open:n,className:r}){return e.jsxs("details",{open:n,className:s.cn("space-y-4 [&_summary>svg]:open:-rotate-180",r),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(s.Label,{children:a}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const wr=[{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 Dr(){var d,m,h,u,p,f,j,x,T,g,b,C,O,S,E,N,D,w;const t=s.useEditorStore(M=>M.card),a=(m=(d=t==null?void 0:t.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:m.topoJsonUrl,[n,r]=A.useState(((u=(h=t==null?void 0:t.preferences)==null?void 0:h.mapVisualOptions)==null?void 0:u.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:o}=s.useTopoJson(t),c=Object.keys((o==null?void 0:o.objects)||{}).map(M=>({label:M,value:M}))||[],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(ns,{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(ns,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(ce,{className:"h-9",options:i,onValueChange:M=>{console.log("value",M),l({...t.preferences,mapVisualOptions:{topoJsonUrl:M}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(s.Input,{onChange:M=>{r(M.target.value)},onBlur:()=>{var M;console.log("onBlur",n),l({...t.preferences,mapVisualOptions:{...(M=t.preferences)==null?void 0:M.mapVisualOptions,customTopoJsonUrl:n}})},value:n,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),o&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(ce,{className:"h-9",options:c,value:((f=(p=t.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:f.objectKey)||"",label:"Map Object",onValueChange:M=>{var k;l({...t.preferences,mapVisualOptions:{...(k=t.preferences)==null?void 0:k.mapVisualOptions,objectKey:M}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(ce,{className:"h-9",options:wr,value:((x=(j=t.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:x.projection)||"",label:"Projection",onValueChange:M=>{var k;l({...t.preferences,mapVisualOptions:{...(k=t.preferences)==null?void 0:k.mapVisualOptions,projection:M}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(ce,{className:"h-9",options:kr,value:((g=(T=t.preferences)==null?void 0:T.mapVisualOptions)==null?void 0:g.colorScale)||"",label:"Select Color Scale",onValueChange:M=>{var k;l({...t.preferences,mapVisualOptions:{...(k=t.preferences)==null?void 0:k.mapVisualOptions,colorScale:M}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(ns,{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:((C=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:C.projectionScale)||1,onChange:M=>{var k;l({...t.preferences,mapVisualOptions:{...(k=t.preferences)==null?void 0:k.mapVisualOptions,projectionScale:Number(M.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((E=(S=(O=t.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:S.projectionOffset)==null?void 0:E[0])||0,onChange:M=>{var k,R,I,v;l({...t.preferences,mapVisualOptions:{...(k=t.preferences)==null?void 0:k.mapVisualOptions,projectionOffset:[Number(M.target.value),((v=(I=(R=t.preferences)==null?void 0:R.mapVisualOptions)==null?void 0:I.projectionOffset)==null?void 0:v[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((w=(D=(N=t.preferences)==null?void 0:N.mapVisualOptions)==null?void 0:D.projectionOffset)==null?void 0:w[1])||0,onChange:M=>{var k,R,I,v;l({...t.preferences,mapVisualOptions:{...(k=t.preferences)==null?void 0:k.mapVisualOptions,projectionOffset:[((v=(I=(R=t.preferences)==null?void 0:R.mapVisualOptions)==null?void 0:I.projectionOffset)==null?void 0:v[0])||0,Number(M.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(we,{})]})}function Er(){var r;const t=s.useEditorStore(l=>l.card.preferences),{setCardPreferences:a}=s.useEditorStore(l=>l.actions);function n(l){a({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:l==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:n,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function Be({cardType:t,docContent:a,suffix:n="Chart"}){let r="pie-donut-polar";return t==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} ${n}`}),e.jsx(s.AccordionContent,{children:a||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:l=>l.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),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:[t!=="text"&&e.jsx(Ke,{}),t==="text"&&e.jsx(Er,{})]})]}),!["range","text"].includes(t)&&e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(we,{}),e.jsx(Ee,{})]})]})]})})}function Ir(){const t=s.useEditorStore(r=>{var l,o;return(o=(l=r==null?void 0:r.card)==null?void 0:l.preferences)==null?void 0:o.sortChart}),{setSortChart:a}=s.useEditorActions();function n(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(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=>{a(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[n(),e.jsx(_t,{})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(we,{}),e.jsx(Ee,{})]})]})]})})}function Ar({cardType:t="table"}){console.log("cardType",t);const a=s.useEditorStore(l=>{var o;return(o=l.card)==null?void 0:o.preferences}),n=s.useEditorStore(l=>l.actions.setCardPreferences),r=l=>{n({...a,allowDownload:l})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(we,{}),e.jsx(Ee,{})]})]})}),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"})]})]})}const Mr=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."]})]}),Lr=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."]})]}),Or=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 Rr(){const t=s.useEditorStore(n=>n.card.type);function a(n){switch(n){case"stackedBar":case"stackedLine":return e.jsx(Ir,{});case"tornado":case"pyramid":return e.jsx(Be,{docContent:Mr,cardType:n});case"kpi":return e.jsx(Sr,{});case"line":case"bar":return e.jsx(jr,{cardType:n});case"range":return e.jsx(Be,{docContent:Lr,cardType:n});case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return e.jsx(Be,{cardType:n});case"bubble":case"scatter":return e.jsx(yr,{cardType:n});case"table":return e.jsx(Ar,{cardType:n});case"text":return e.jsx(Be,{docContent:Or,cardType:n,suffix:"Visual"});case"map":return e.jsx(Dr,{});case"custom":return e.jsx(xr,{});default:return e.jsx(Nr,{})}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[a(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function $t({label:t,column:a,functions:n,onFunctionChange:r}){let l=n[0];"aggregate"in a?l=n.find(c=>c.value===a.aggregate)||n[0]:"granularity"in a&&(l=n.find(c=>c.value===a.granularity)||n[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:n,value:l.value,onValueChange:c=>o(c),label:t,showPlaceholderLabel:!1})}const Br=[{label:"Sum",value:"SUM",logo:e.jsx(rt,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(fs,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(Ln,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(mn,{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 Fr({column:t}){const{updateMetricColumnOld:a}=s.useEditorActions();let n=Br;s.isTextDataType(t.type)&&(n=n.filter(l=>["COUNT","DISTINCT"].includes(l.value))),s.isNumberDataType(t.type)&&(n=n.filter(l=>!["DISTINCT"].includes(l.value)));function r(l){const o={...t,aggregate:l,label:Le(t.name,l)};a(t.id,o)}return e.jsx($t,{column:t,functions:n,onFunctionChange:l=>r(l),label:"Aggregation"})}const zr=[{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 Pr({column:t}){const{updateGroupByColumnOld:a}=s.useEditorActions();function n(r){const l={...t,granularity:r,label:De(t.name,r)};a(t.id,l)}return e.jsx($t,{column:t,functions:zr,onFunctionChange:r=>n(r),label:"Granularity"})}function _r({col:t,onChange:a,droppableId:n}){const{columns:r}=s.useDataColumns(),l=A.useMemo(()=>{let i=[];(n===be||n===Ne||n===Ce)&&(i=r);const d=i==null?void 0:i.filter(m=>m.column_name!==t.name);return d==null?void 0:d.map(m=>({id:m.column_name,value:m.column_name}))},[r,n,t.name]),o=[{id:t.name,value:t.name}];function c(i){const d=r==null?void 0:r.find(m=>{var h;return m.column_name===((h=i[0])==null?void 0:h.id)});d&&a(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 Gt({column:t}){const a=s.useEditorStore(d=>d.card.type),n=s.useEditorStore(d=>{var m,h;return(h=(m=d.card)==null?void 0:m.config)==null?void 0:h.metricColumns}),r=(n==null?void 0:n.map(d=>d.label))||[],l=r==null?void 0:r.find(d=>d===t.label||d===t.name),o=l?r.indexOf(l):-1;function c(){return e.jsx("div",{className:"pr-1",children:l&&e.jsx(Ut,{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(Ke,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&c(),["pie","doughnut"].includes(a)&&i()]})}function Vr({column:t,type:a,onRemoveColumn:n,droppableId:r}){const[l,o]=A.useState(!1),{updateGroupByColumnOld:c,updateMetricColumnOld:i,updatePivotByColumnOld:d}=s.useEditorActions(),{attributes:m,listeners:h,setNodeRef:u,transform:p,transition:f,isDragging:j}=s.useSortable({id:t.id,data:{type:a}}),x=p?{opacity:j?.5:void 0,transform:s.CSS.Translate.toString(p),transition:f}:void 0,T=s.isTextDataType(t.type);function g(E){const N=s.isNumberDataType(E.data_type),D=s.isTextDataType(E.data_type),w=s.isDateDataType(E.data_type),M=N?"number":D?"string":w?"date":"string";if(r===be){if(D){const k={id:t.id,name:E.column_name,type:M,role:"groupby"};c(t.id,k)}if(w){const k={id:t.id,name:E.column_name,type:M,role:"groupby",label:De(E.column_name,"month"),granularity:"month"};c(t.id,k)}}if(r===Ce){if(D){const k={id:t.id,name:E.column_name,type:M,role:"groupby"};d(t.id,k)}if(w){const k={id:t.id,name:E.column_name,type:M,label:De(E.column_name,"month"),granularity:"month",role:"groupby"};d(t.id,k)}}if(r===Ne){const k={id:t.id,name:E.column_name,type:M,role:"metric",label:Le(E.column_name,"SUM"),aggregate:N?"SUM":"COUNT"};i(t.id,k)}}function b(){if(r===Ne)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(Gt,{column:t})})}function C(){const E=s.isDateDataType(t.type);if(r===Ne)return e.jsx(Fr,{column:t});if((r===be||r===Ce)&&E)return e.jsx(Pr,{column:t})}function O(){return e.jsx("div",{className:s.cn("grow",{"pl-3":(r===be||r===Ce)&&T}),children:e.jsx(_r,{col:t,onChange:g,droppableId:r})})}function S(){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(ea,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(tt,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...h,...m,ref:u,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:[S(),C(),O()]}),l&&b()]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:l}),children:e.jsx("button",{onClick:()=>n(t.id),children:e.jsx(s.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function as({id:t,label:a,columns:n,previewColumns:r,sortableType:l,onRemoveColumn:o}){var x,T;const{setNodeRef:c,isOver:i,over:d}=s.useDroppable({id:t}),m=s.useDndStore(g=>g.activeId),h=s.useEditorStore(g=>{var b;return(b=g.card)==null?void 0:b.type}),u=i||((T=(x=d==null?void 0:d.data)==null?void 0:x.current)==null?void 0:T.type)===l,p=m?r:n,f=l===_e?"Rows":l===Ve?"Pivot Columns":"Columns";function j(){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:n==null?void 0:n.map(g=>g.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md p-4",u&&"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:a}),h!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:f})]}),j(),e.jsx("div",{className:"space-y-2",children:p==null?void 0:p.map(g=>g.id===kt.id?e.jsx(Ur,{},g.id):e.jsx(Vr,{droppableId:t,type:l,column:g,onRemoveColumn:o},g.id))})]})})}function Ur(){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 Ht({children:t,id:a,type:n}){const{attributes:r,listeners:l,setNodeRef:o,transform:c,transition:i,isDragging:d}=s.useSortable({id:a,data:{type:n}}),m=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:m,children:t})}function qr(){const t=s.useEditorStore(g=>{var b;return(b=g.card.queryConfig)==null?void 0:b.orderBy})||[],a=s.useEditorStore(g=>{var b;return(b=g.card.queryConfig)==null?void 0:b.groupByColumns})||[],n=s.useEditorStore(g=>{var b;return(b=g.card.queryConfig)==null?void 0:b.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:l,updateOrderByColumn:o}=s.useEditorActions(),c=[...a,...n];if(c.length===0)return e.jsx(e.Fragment,{});const i=e.jsx(fn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx(un,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=e.jsx(pn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=e.jsx(dn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=c==null?void 0:c.filter(g=>!t.some(b=>b.columnId===g.id)).map(g=>({id:g.id,value:g.label||g.name}));function p(g,b){const C=f(g);return C?C.role==="metric"?b==="asc"?m:h:b==="asc"?i:d:null}function f(g){return c.find(b=>b.id===g)}function j(g){const b=t.find(C=>C.columnId===g);if(b){const C={...b,direction:b.direction==="asc"?"desc":"asc"};o(C)}}const x=g=>{r({columnId:g.id,direction:"asc"})};function T(g){const b=t.find(C=>C.columnId===g);b&&l(b)}return e.jsx(s.SortableContext,{items:t.map(g=>Ie(g.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"}),u.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(s.ComboBox2,{multiple:!1,options:u,selectedOptions:[],onChange:g=>x(g[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),t.map(g=>{var b,C;return e.jsx(Ht,{id:Ie(g.columnId),type:Ns,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(tt,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(Es,{className:"w-[175px] text-sm",children:((b=f(g.columnId))==null?void 0:b.label)||((C=f(g.columnId))==null?void 0:C.name)})]}),e.jsx("button",{title:g.direction==="asc"?"Ascending":"Descending",onClick:()=>j(g.columnId),className:"rounded-sm p-0",children:p(g.columnId,g.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>T(g.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"})})})]})},g.columnId)},Ie(g.columnId))})]})})}function $r(){const t=s.useEditorStore(T=>{var g;return((g=T.card.queryConfig)==null?void 0:g.groupByColumns)||[]}),a=s.useEditorStore(T=>T.card.type),n=s.useDndStore(T=>T.previewGroupByColumns),r=s.useEditorStore(T=>{var g;return((g=T.card.queryConfig)==null?void 0:g.metricColumns)||[]}),l=s.useDndStore(T=>T.previewMetricColumns),o=s.useEditorStore(T=>{var g;return((g=T.card.queryConfig)==null?void 0:g.pivotColumns)||[]}),c=s.useDndStore(T=>T.previewPivotColumns),{removeColumnFromGroupBy:i,removeColumnFromMetricColumns:d,removeColumnFromPivotBy:m}=s.useEditorActions();function h(T){i(T)}function u(T){d(T)}function p(T){m(T)}let f="Group By",j="Metrics",x="Stack By";return a==="table"&&(f="Rows",j="Metrics",x="Columns"),e.jsxs("div",{className:"flex h-full w-full flex-col gap-3 py-4",children:[e.jsx(Bt,{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(as,{onRemoveColumn:h,sortableType:_e,id:be,label:f,columns:t,previewColumns:n}),e.jsx(as,{onRemoveColumn:p,sortableType:Ve,id:Ce,label:x,columns:o,previewColumns:c}),e.jsx(as,{onRemoveColumn:u,sortableType:ls,id:Ne,label:j,columns:r,previewColumns:l}),e.jsx(qr,{})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Is({children:t,column:a,id:n,sortableType:r,className:l}){const[o,c]=A.useState(!1),{removeEditorFilter:i,clearEditorFilter:d}=s.useEditorActions(),m=s.useEditorStore(u=>{var p,f;return(f=(p=u.card.queryConfig)==null?void 0:p.filters)==null?void 0:f.some(j=>j.filterColumnName===a.name)});function h(u){i(u)}return e.jsx(Ht,{id:n,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:a.name}),m&&e.jsx("button",{onClick:()=>d(a),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:()=>h(a),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 Gr({column:t,sortableType:a}){const n=s.useDashboardStore(C=>C.themeStyle),r=s.useEditorStore(C=>{var O,S;return(S=(O=C.card)==null?void 0:O.queryConfig)==null?void 0:S.filters}),l=s.useEditorStore(C=>{var O,S;return(S=(O=C.card.queryConfig)==null?void 0:O.filterColumns)==null?void 0:S.find(E=>E.name===t.name)}),{selectedConnectionId:o,selectedDatabaseName:c,selectedTableName:i}=s.useEditorAside(),d=A.useMemo(()=>{var C;return(C=r==null?void 0:r.find(O=>O.filterColumnName===t.name))==null?void 0:C.filterValue},[r,t.name]),m=A.useMemo(()=>Array.isArray(d)?d.map(C=>({id:C,value:C})):[],[d]),{updateEditorFilterValue:h}=s.useEditorActions(),u={column:t.name,sql:t.sql,id:t.name,connectionId:o,dataType:t.type},{data:p,isLoading:f,isFetching:j,isError:x}=s.useFilterQuery(u),T=A.useMemo(()=>{var O;return u.column?(O=p==null?void 0:p.records)==null?void 0:O.map(S=>{let E=u.column.split(".").slice(-1)[0].replace(/"/g,"");return S[E]===void 0&&(E=E.toLowerCase()),{id:S[E],value:S[E]}}):[]},[p,u.column]);function g(C){const O=C.map(S=>S.id);h(t.name,O)}function b(){return f||j?e.jsx(s.Skeleton,{style:{borderRadius:n==null?void 0:n.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(Hr,{columnName:t.name}),showNegativeIndicator:(l==null?void 0:l.mode)==="exclude",options:T,onChange:g,selectedOptions:m,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(Is,{className:"w-60",id:t.id,sortableType:a,column:t,children:b()})}function Hr({columnName:t}){const{setEditorFilterMode:a}=s.useEditorActions(),n=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(){(n==null?void 0:n.mode)==="exclude"?a(t,"include"):a(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((n==null?void 0:n.mode)==="exclude"?"exclude":"include")})}function Jr({column:t,sortableType:a}){const[n,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:m,isError:h,data:u}=s.useFilterQuery(i),p=u==null?void 0:u.records,{dateRange:f,setDateRange:j,initialDateRange:x}=s.useDateRangeFromRecords(p),{updateEditorFilterValue:T}=s.useEditorActions();function g(O){var E,N;const S={gte:(E=O==null?void 0:O.from)==null?void 0:E.toISOString(),lte:(N=O==null?void 0:O.to)==null?void 0:N.toISOString()};T(t.name,S)}function b(){T(t.name,null,!0),j(x)}function C(){return d||m?e.jsx("div",{children:e.jsx(s.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):h?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):p?e.jsx(s.DateRangePopover,{title:i.title,open:n,inputClassName:"h-8",setOpen:r,dateRange:f,setDateRange:j,onApply:g,onClear:b}):e.jsx(s.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(Is,{className:"w-72",id:t.id,sortableType:a,column:t,children:C()})}function Wr({id:t,label:a,columns:n,previewColumns:r,sortableType:l}){var j,x;const{setNodeRef:o,isOver:c,over:i}=s.useDroppable({id:t}),d=s.useDndStore(T=>T.activeId),m={},h=c||((x=(j=i==null?void 0:i.data)==null?void 0:j.current)==null?void 0:x.type)===l;function u(){if(!f||f.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(T){const g=s.isDateDataType(T.type);return T.id===kt.id?e.jsx(Is,{id:T.id,sortableType:l,column:T,children:e.jsx(Yr,{})},T.id):g?e.jsx(Jr,{droppableId:t,sortableType:l,column:T},T.id):e.jsx(Gr,{droppableId:t,sortableType:l,column:T},T.id)}const f=d?r:n;return e.jsx(s.SortableContext,{items:n==null?void 0:n.map(T=>T.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",h&&"border border-muted-foreground/20"),ref:o,style:m,children:[e.jsx(s.Label,{className:"text-sm",children:a}),u(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:f==null?void 0:f.map(T=>p(T))})]})})}function Yr(){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 Kr(){const t=s.useEditorStore(l=>{var o;return((o=l.card.queryConfig)==null?void 0:o.filterColumns)||[]}),a=s.useDndStore(l=>l.previewFilterColumns),{removeColumnFromFilterColumns:n}=s.useEditorActions();function r(l){n(l)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(Wr,{onRemoveColumn:r,sortableType:is,id:os,label:"Filters",columns:t,previewColumns:a})})}function Qr(){const t=s.useEditorStore(o=>o.card),a=s.useEditorStore(o=>o.showAIDialog),{setShowAIDialog:n}=s.useEditorActions(),{data:r,errorMessage:l}=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(s.EditorClearButton,{}),!a&&e.jsxs(s.Button,{onClick:()=>n(!0),variant:"secondary",size:"sm",children:[e.jsx(Jn,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(At,{sql:r==null?void 0:r.sql,error:l})]}),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(s.EditorCancelButton,{}),e.jsx(s.EditorAcceptButton,{variant:"default"})]})]})}function Xr(){const t=A.useRef(null),a=A.useRef(null),n=s.useEditorStore(i=>i.isShowingVisual),r=s.useEditorStore(i=>i.showAIDialog),l=s.useEditorStore(i=>i.isDevMode);A.useEffect(()=>{var i,d,m,h;r?((i=t.current)==null||i.resize(0),(d=a.current)==null||d.resize(0)):((m=t.current)==null||m.resize(25),(h=a.current)==null||h.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(Qa,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:n&&!r?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:t,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(Rr,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(Re,{})})]}):e.jsx(Re,{})})]})}function c(){return e.jsx(e.Fragment,{children:e.jsx("div",{className:"grow","data-biz-mode-container":"",children:n?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:a,defaultSize:25,maxSize:30,children:e.jsx($r,{})})}),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(Qr,{}),e.jsx(Kr,{})]}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(Re,{})})]})})]}):e.jsx(Re,{})})})}return e.jsx(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:l?o():c()})}function Zr(t){const a=s.useAIInteractionStore(B=>B.currentAIContext),[n,r]=A.useState(""),[l,o]=A.useState(null),{authToken:c}=s.useSemaphorContext(),i=s.useEditorStore(B=>{var K;return(K=B==null?void 0:B.card)==null?void 0:K.sql}),d=s.useEditorStore(B=>B.isDevMode),m=s.useEditorStore(B=>{var K;return(K=B==null?void 0:B.card)==null?void 0:K.python}),{setCardPython:h,setCardSql:u,setRunSql:p,switchCardType:f,setQueryConfig:j}=s.useEditorActions(),x=s.useEditorStore(B=>B.currentAssitantScope)||[],T=s.useEditorStore(B=>B.userInputForAI),g=s.useEditorStore(B=>B.triggerAIRun),b=s.useEditorStore(B=>B.card),C=s.useEditorStore(B=>B.selectedDatabaseName),O=s.useEditorStore(B=>B.selectedTableName),S=s.useEditorStore(B=>B.selectedConnectionId),E=s.useEditorStore(B=>B.selectedSchemaName),N=s.useDashboardStore(B=>B.dashboard.aiScopeTables),{errorMessage:D,refetch:w,data:M}=s.useDashboardCardQuery(b),{setTriggerAIRun:k,setCurrentAssitantScope:R,setCardConfig:I}=s.useEditorActions(),{selectedDatamodelName:v,connectionType:y,selectedDatamodelId:L}=s.useEditorAside(),{messages:F,setMessages:P,reload:_,error:z,append:Q,input:Y,setInput:V,status:q,handleInputChange:$,handleSubmit:U,stop:H}=s.useChat({api:"https://semaphor.cloud/api/v1/assistant",headers:{Authorization:`Bearer ${c==null?void 0:c.accessToken}`},body:{random:Math.random(),assistantId:"editor-assistant",isDevMode:d,aiContext:a},maxSteps:10,onError:B=>{console.log("on error",B)},onToolCall:W,onFinish(B,K){G(K.usage),r(""),K.finishReason==="stop"&&r("")}});A.useEffect(()=>{g&&T&&(Q({role:"user",content:T}),k(!1))},[g,T,Q,k]);async function W({toolCall:B}){var K,re,he,je;if(["createChartFromSql","createForecast"].includes(B.toolName)){const te=B.args.sql,le=B.args.python,oe=B.args.chartType;return f(oe),u(te),h(le),p(!0),{status:"success",message:"Let the user know that chart is created"}}else if(B.toolName==="getTableColumns")r("Getting table columns...");else{if(B.toolName==="getUserSql")return i?{status:"success",sql:i,python:m||""}:{status:"error",message:"No SQL found"};if(B.toolName==="getCurrentTableScope")return r("Getting table scope..."),ee(),{status:"success",tables:x};if(B.toolName==="generateQueryConfig"){r("Generating query config...");const te=B.args.chartType,le=B.args.queryConfig;B.args.cardConfig,f(te),I(le),u(void 0),h(void 0);const oe=await w();return(K=oe==null?void 0:oe.data)!=null&&K.error?{status:"error",queryConfig:le,message:(re=oe==null?void 0:oe.data)==null?void 0:re.error.message}:(he=oe==null?void 0:oe.data)!=null&&he.records?{status:"success",queryConfig:le,message:"The data has been visualized"}:{status:"success",queryConfig:le,message:"The data has been visualized",records:(je=oe==null?void 0:oe.data)==null?void 0:je.records}}else r("Analyzing...")}}function G(B){o(K=>K?{promptTokens:K.promptTokens+B.promptTokens,completionTokens:K.completionTokens+B.completionTokens,totalTokens:K.totalTokens+B.totalTokens}:B)}function Z(B){const K=s.removeFromScopeArray(x,B);se(K)}function se(B){const K=s.sanitizeAIScope(B);R(K),P(re=>[...re,{id:crypto.randomUUID(),role:"system",content:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(K)}`}])}function ne(){const B={databaseName:C||"",schemaName:E||"",tableName:O||"",datamodelId:L||"",datamodelName:s.resolveDatamodelName(v),connectionId:S||"",connectionType:y||""},K=s.dedup([...x,B]);se(K)}function ee(){const B={databaseName:C||"",schemaName:E||"",tableName:O||"",datamodelName:s.resolveDatamodelName(v),connectionId:S||"",connectionType:y||"",datamodelId:L||""};if(!s.isInAiScopeArray([...N||[],...x],B)||x.length===0){const re=s.dedup([...N||[],...x,B]).filter(he=>he.connectionId===B.connectionId);se(re)}}const ae=!["ready","error"].includes(q),J=s.getErrorMessage(z);return{messages:F,setMessages:P,reload:_,append:Q,input:Y,setInput:V,isLoading:ae,handleSetAIScope:ee,handleAddCurrentTableToScope:ne,removeFromCurrentSelections:Z,currentAssitantScope:x,setCurrentAssitantScope:R,handleInputChange:$,handleSubmit:U,stop:H,chatStatus:q,toolStatus:n,llmUsage:l,onFinish:t,errorMessage:J}}const el=[{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),a=A.useRef(null),[n,r]=A.useState(!1),[l,o]=A.useState(s.isDevEnv),[c,i]=A.useState(!1),[d,m]=A.useState(!1),h=s.useCurrentAIContext(),{setCurrentAIContext:u}=s.useAIActions(),p=s.useDashboardStore(H=>H.dashboard.aiContext),f=s.useEditorStore(H=>H.card.dataSource),j=s.useEditorStore(H=>H.actions.setCardSql),x=s.useEditorStore(H=>H.actions.setRunSql),T=s.useEditorStore(H=>H.showAIDialog),g=s.useDashboardStore(H=>H.handleOpenAssistantProfile),{setShowAIDialog:b,setCardPython:C}=s.useEditorActions(),{setDataSource:O}=s.useEditorActions(),{assistantProfile:S}=s.useAssistantProfile(),{messages:E,setMessages:N,reload:D,append:w,input:M,setInput:k,isLoading:R,handleInputChange:I,handleSubmit:v,stop:y,chatStatus:L,llmUsage:F,errorMessage:P}=Zr();s.useAssistantScroll({scrollContainerRef:t,inputRef:a,messages:E}),A.useEffect(()=>{var H;T&&((H=a.current)==null||H.focus(),u({selectedEntities:(f==null?void 0:f.selectedEntities)||[]}))},[T,f,u]);function _(H,W){W==="sql"?(j(H),x(!0)):W==="python"&&(C(H),x(!0))}function z(){var H;(H=p==null?void 0:p.selectedEntities)==null||H[0],m(!0)}function Q(){h.selectedEntities.length===0&&u({selectedEntities:(p==null?void 0:p.selectedEntities)||[]})}function Y(H){Q();const W={role:"user",content:H.title+" "+H.subtitle};w(W)}function V(H){Q(),w({role:"user",content:H})}function q(){return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuLabel,{children:"Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx(s.DropdownMenuCheckboxItem,{checked:n,onCheckedChange:r,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:o,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:i,children:"System Message"})]})]})}function $(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const U=(M==null?void 0:M.length)===0&&(E==null?void 0:E.filter(H=>H.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:[$(),g&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:g,children:(S==null?void 0:S.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center gap-2",children:[q(),e.jsx(s.IconButton,{tooltip:"Add Context",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:z,children:e.jsx(s.Settings,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{N([]),D()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-8 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{b(!1)},children:e.jsx(s.EyeOff,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:t,className:"mt-2 flex w-full grow basis-0",children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[e.jsx(s.PrintMessages,{messages:E,showTools:l,handleRun:_,showSystemMessage:c}),e.jsx(s.ChatStatus,{messages:E,chatStatus:L,errorMessage:P})]})}),e.jsxs("div",{className:"mb-3",children:[U&&!S&&e.jsx(s.Placeholders,{onClick:Y,placeholders:el}),e.jsx("div",{children:U&&S&&e.jsx(s.SeedQuestions,{seedQuestions:S.seedQuestions||[],handleSeedQuestionClick:V})})]}),e.jsx(s.ChatInputWithContext,{ref:a,setInput:k,stop:y,input:M,handleInputChange:I,handleSubmit:H=>{Q(),v(H)},isLoading:R,onFocus:()=>{}}),F&&n&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",F.promptTokens," prompt tokens,"," ",F.completionTokens," completion tokens,"," ",F.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(f==null?void 0:f.selectedEntities)||[],open:d,onOpenChange:m,dataSource:f||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function Jt(t,a){return`${t}-${a.qualifiedEntityName}-${a.name}-${Date.now()}`}function Wt(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function sl(t,a){const n=s.getDataType(t.dataType);return n==="number"?"metrics":n==="date"||n==="string"?"groupBy":"metrics"}function cs(t,a){const n=Jt(a,t),r=s.getDataType(t.dataType),l=r==="date",o={id:n,name:t.name,dataType:t.dataType,label:s.toLabel(t.name),qualifiedEntityName:t.qualifiedEntityName,entityId:t.entityId,entityName:t.entityName,entityType:t.entityType};if(a==="metrics"){const c=r==="number"?"SUM":"COUNT",i=Wt(t.label,c);return{...o,role:"metric",label:i,aggregate:c}}return a==="groupBy"?{...o,role:"groupby",...l&&{granularity:"month",dateFormat:"YYYY-MM"}}:a==="pivotBy"?{...o,role:"pivotby"}:a==="sortBy"?{...o,role:"sortby",label:t.label,direction:"asc"}:null}function Yt(t,a,n){var r;return!n||!((r=n.baseEntity)!=null&&r.name)||!n.joins?!1:t===a||t===n.baseEntity.name||a===n.baseEntity.name?!0:n.joins.some(l=>{const o=s.getQualifiedEntityName(l.source),c=s.getQualifiedEntityName(l.target);return o===t&&c===a||o===a&&c===t})}function tl(t,a,n){if(a.length===0)return{isValid:!0};const r=a[0].qualifiedEntityName;if(!r)return{isValid:!0};if(r!==t.qualifiedEntityName&&t.qualifiedEntityName)if(n){if(!Yt(r,t.qualifiedEntityName,n))return{isValid:!1,showError:!0}}else return{isValid:!1,showError:!0};return{isValid:!0}}function ds(){s.ue.error("Join Configuration Required",{richColors:!0,description:"To combine fields from two different tables, you need to define a join between them first.",position:"top-center",duration:4e3})}function us(t,a){return a.some(n=>n.name===t.name&&n.qualifiedEntityName===t.qualifiedEntityName)}const As=t=>{var k;const{updateCardConfig:a,updateGroupByColumn:n,updateMetricColumn:r,updatePivotByColumn:l,updateSortByColumn:o,removeGroupByColumn:c,removeMetricColumn:i,removePivotByColumn:d,removeSortByColumn:m}=s.useEditorActions(),h=s.useEditorStore(R=>R.card.type),u=t==null?void 0:t.id,p=A.useCallback(R=>{if(!(t!=null&&t.config))return[];switch(R){case"groupBy":return(t.config.groupByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType,dateFormat:I.dateFormat,customFormat:I.customFormat,granularity:I.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType,direction:I.direction}));case"source":return[];default:return[]}},[t]),f=A.useCallback((R,I)=>{if(u)switch(R){case"groupBy":{a(u,{groupByColumns:I});break}case"metrics":{a(u,{metricColumns:I});break}case"pivotBy":{a(u,{pivotByColumns:I});break}case"sortBy":{a(u,{sortByColumns:I});break}}},[u,a]),j=A.useCallback((R,I,v)=>{if(!u)return;const L=p(R)[I];if(L)switch(R){case"groupBy":n(u,L.id,{label:v});break;case"metrics":r(u,L.id,{label:v});break;case"pivotBy":l(u,L.id,{label:v});break;case"sortBy":o(u,L.id,{label:v});break}},[u,p,n,r,l,o]),x=A.useCallback((R,I)=>{if(!u)return;const y=p("metrics")[R];y&&r(u,y.id,{aggregate:I,label:Wt(y.name,I)})},[u,p,r]),T=A.useCallback((R,I,v)=>{if(!u)return;const L=p("groupBy")[R];if(!L)return;const F={dateFormat:I};I==="custom"&&v?F.customFormat=v:F.customFormat=void 0,n(u,L.id,F)},[u,p,n]),g=A.useCallback((R,I)=>{if(!u)return;const y=p("groupBy")[R];y&&n(u,y.id,{granularity:I})},[u,p,n]),b=A.useCallback((R,I)=>{if(!u)return;const y=p("metrics")[R];y&&r(u,y.id,{aliasTemplate:I})},[u,p,r]),C=A.useCallback((R,I)=>{if(console.log("handleValueAliasesChange",R,I),!u)return;console.log("handleValueAliasesChange",R,I);const y=p("metrics")[R];y&&(console.log("handleValueAliasesChange",I),r(u,y.id,{valueAliases:I}))},[u,p,r]),O=A.useCallback(R=>{u&&a(u,{comparisonType:R})},[u,a]),S=A.useCallback(R=>{u&&a(u,{showTrendline:R})},[u,a]),E=A.useCallback(R=>{u&&a(u,{trendlineWindow:R})},[u,a]),N=A.useCallback(R=>{u&&a(u,{trendlineGranularity:R})},[u,a]),D=A.useCallback(R=>{u&&a(u,{targetValue:R})},[u,a]),w=A.useCallback(R=>{var _;if(!u)return;const I=[...p("groupBy"),...p("pivotBy"),...p("metrics"),...p("sortBy")],v=(_=t==null?void 0:t.config)==null?void 0:_.joinPlan,y=tl(R,I,v);if(!y.isValid){y.showError&&ds();return}const L=sl(R),F=p(L);if(us(R,F))return;const P=cs(R,L);P&&f(L,[...F,P])},[u,(k=t==null?void 0:t.config)==null?void 0:k.joinPlan,p,f]),M=A.useCallback((R,I)=>{if(!u)return;const y=p(R)[I];if(y){if(R!=="sortBy"){const L=p("sortBy"),F=L.filter(P=>!(P.name===y.name&&P.qualifiedEntityName===y.qualifiedEntityName));F.length!==L.length&&a(u,{sortByColumns:F})}switch(R){case"groupBy":c(u,y.id);break;case"metrics":i(u,y.id);break;case"pivotBy":d(u,y.id);break;case"sortBy":m(u,y.id);break}}},[u,p,c,i,d,m,a]);return{getFieldsForContainer:p,setFieldsForContainer:f,updateLabel:j,handleAggregationChange:x,handleDateFormatChange:T,handleGranularityChange:g,handleAliasTemplateChange:b,handleValueAliasesChange:C,removeField:M,handleFieldClick:w,handleKpiComparisonTypeChange:O,handleKpiShowTrendlineChange:S,handleKpiTrendlineWindowChange:E,handleKpiTrendlineGranularityChange:N,handleKpiTargetValueChange:D,cardType:h}};function nl({field:t}){const{attributes:a,listeners:n,setNodeRef:r,transform:l,transition:o,isDragging:c}=s.useSortable({id:t.id}),[i,d]=A.useState(!1),m=s.useEditorStore(x=>x.card),{handleFieldClick:h}=As(m),u={transform:s.CSS.Transform.toString(l),transition:o},p=s.getDataType(t.dataType),j=(x=>{const T=(x||"").toLowerCase();switch(s.getDataType(T)){case"number":return fs;case"date":return s.Calendar;case"boolean":return ot;case"json":return Sn;case"geo":return Gn;default:return it}})(t.dataType);return e.jsxs("div",{ref:r,style:u,...a,...n,className:`group/container overflow-hidden rounded-lg transition-all ${c?"scale-95 opacity-50":"border border-transparent hover:border-blue-200 hover:bg-blue-50 dark:hover:border-blue-800 dark:hover:bg-blue-950"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1 p-2",onClick:()=>h(t),children:[e.jsx("div",{className:"flex-shrink-0 hover:cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"invisible size-3.5 text-gray-400 group-hover/container:visible"})}),e.jsx(j,{className:s.cn("size-3.5 flex-shrink-0 text-gray-500",p==="string"?"text-blue-500":"",p==="number"?"text-green-500":"",p==="date"?"text-purple-500":"",p==="boolean"?"text-orange-500":"")}),e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:e.jsx("span",{className:`block text-sm text-foreground/90 hover:text-foreground dark:text-muted-foreground ${i?"whitespace-normal break-words":"truncate"}`,children:t.name})})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:t.label||t.name}),t.description&&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:t.description})]}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"mr-2 text-muted-foreground",children:"Name:"}),e.jsx("span",{className:"font-mono text-muted-foreground",children:t.name})]}),e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"mr-2 text-muted-foreground",children:"Type:"}),e.jsx("span",{className:"font-mono text-muted-foreground",children:t.dataType})]}),t.qualifiedEntityName&&e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[t.entityType?t.entityType.charAt(0).toUpperCase()+t.entityType.slice(1):"Entity",":"]}),e.jsx("span",{className:"font-mono text-muted-foreground",children:t.qualifiedEntityName})]})]})]})})]})})]}),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(lt,{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(na,{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 al(){const[t,a]=A.useState(""),[n,r]=A.useState("all"),l=s.useEditorStore(C=>C.card.dataSource),{columns:o=[],columnGroups:c=[],isLoading:i,error:d}=s.useColumns(),m=o.filter(C=>C.name.toLowerCase().includes(t.toLowerCase())||C.dataType.toLowerCase().includes(t.toLowerCase())||C.qualifiedEntityName&&C.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),h=C=>{if(C.dataType==="number"||C.dataType==="integer"||C.dataType==="float"||C.dataType==="decimal"||C.dataType==="currency")return"metrics";const O=s.getDataType(C.dataType);return["date","string","boolean"].includes(O)?"dimensions":O==="number"?"metrics":"dimensions"},p=(n==="all"?m:m.filter(C=>h(C)===n)).reduce((C,O)=>{const S=O.qualifiedEntityName||"Other Fields";return C[S]||(C[S]={label:s.toLabel(O.entityName),fields:[]}),C[S].fields.push(O),C},{}),j=Object.keys(p),x=m.filter(C=>h(C)==="dimensions").length,T=m.filter(C=>h(C)==="metrics").length,g=m.filter(C=>h(C)==="calculated").length,b=m.length>0;return i?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-gray-400"}),e.jsx("span",{className:"mt-2 text-sm text-gray-500",children:"Loading fields..."})]}):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.jsx("div",{className:"mb-4",children:e.jsx(s.Input$1,{type:"text",placeholder:"Search fields...",value:t,onChange:C=>a(C.target.value)})}),b&&e.jsx(s.Tabs,{defaultValue:"all",value:n,onValueChange:C=>r(C),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: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: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:T})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(bn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:g})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:j,className:"space-y-2",children:Object.entries(p).map(([C,O])=>{const S=c.find(E=>E.entityName===C)||{entityName:C,label:O.label};return e.jsxs(s.AccordionItem,{value:C,className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"group rounded-md px-3 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-primary",children:S.label||S.entityName}),e.jsx(s.Badge,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:O.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:O.fields.map(E=>e.jsx(nl,{field:E},E.id))})})]},C)})}),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 rl(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(al,{})," "]})}function ll({initialJoinPlan:t,availableDataSources:a}){const[n,r]=A.useState(t),[l,o]=A.useState(new Set),c=()=>{const E=n.joins.length>0?Math.max(...n.joins.map(D=>D.sequence))+1:1,N={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:E,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...n,joins:[...n.joins,N]}),o(new Set([...l,N.id]))},i=E=>{r({...n,joins:n.joins.filter(N=>N.id!==E)}),o(new Set([...l].filter(N=>N!==E)))},d=(E,N)=>{var k,R;const D=n.joins.find(I=>I.id===E);if(!D)return;const w={...D,...N},M=n.joins.map(I=>I.id===E?w:I);if((k=w.source)!=null&&k.name&&((R=w.target)!=null&&R.name)&&w.joinKeyGroups[0].keys.length===0){const I=a.find(F=>{var P;return F.name===((P=w.source)==null?void 0:P.name)}),v=a.find(F=>{var P;return F.name===((P=w.target)==null?void 0:P.name)}),y={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(I==null?void 0:I.name)||"",entityName:(I==null?void 0:I.name)||"",entityType:(I==null?void 0:I.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(v==null?void 0:v.name)||"",entityName:(v==null?void 0:v.name)||"",entityType:(v==null?void 0:v.type)||"table"},operator:"="},L=[...w.joinKeyGroups];L[0]={...L[0],keys:[y]},w.joinKeyGroups=L,M[M.findIndex(F=>F.id===E)]=w}r({...n,joins:M})};return{joinPlan:n,expandedJoins:l,setJoinPlan:r,addJoin:c,removeJoin:i,updateJoin:d,moveJoinUp:E=>{const N=n.joins.findIndex(D=>D.id===E);if(N>0){const D=[...n.joins],w={...D[N]},M={...D[N-1]};D[N]=M,D[N-1]=w,D.forEach((R,I)=>{R.sequence=I+1});const k={...n,joins:D};r(k)}},moveJoinDown:E=>{const N=n.joins.findIndex(D=>D.id===E);if(N<n.joins.length-1){const D=[...n.joins],w={...D[N]},M={...D[N+1]};D[N]=M,D[N+1]=w,D.forEach((R,I)=>{R.sequence=I+1});const k={...n,joins:D};r(k)}},toggleJoinExpansion:E=>{const N=new Set(l);N.has(E)?N.delete(E):N.add(E),o(N)},getAvailableSourceEntities:E=>{if(n.joins.length===0)return a;const N=n.joins.findIndex(w=>w.id===E);if(N===0)return a;const D=new Set;return n.baseEntity.name&&D.add(n.baseEntity.name),n.joins.slice(0,N).forEach(w=>{D.add(w.source.name),D.add(w.target.name)}),a.filter(w=>D.has(w.name))},getAvailableTargetEntities:E=>a.filter(N=>N.name!==E),addJoinKeyGroup:E=>{const N=n.joins.find(w=>w.id===E);if(!N)return;const D=[...N.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];d(E,{joinKeyGroups:D})},updateGroupOperator:(E,N,D)=>{const w=n.joins.find(k=>k.id===E);if(!w)return;const M=[...w.joinKeyGroups];M[N]={...M[N],operator:D},d(E,{joinKeyGroups:M})},removeJoinKeyGroup:(E,N)=>{const D=n.joins.find(M=>M.id===E);if(!D)return;const w=[...D.joinKeyGroups];w.splice(N,1),d(E,{joinKeyGroups:w})},addJoinKey:(E,N)=>{const D=n.joins.find(I=>I.id===E);if(!D)return;const w=a.find(I=>I.name===D.source.name),M=a.find(I=>I.name===D.target.name),k=[...D.joinKeyGroups],R={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(w==null?void 0:w.name)||"",entityName:(w==null?void 0:w.name)||"",entityType:(w==null?void 0:w.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(M==null?void 0:M.name)||"",entityName:(M==null?void 0:M.name)||"",entityType:(M==null?void 0:M.type)||"table"},operator:"="};k[N]={...k[N],keys:[...k[N].keys,R]},d(E,{joinKeyGroups:k})},updateJoinKey:(E,N,D,w,M)=>{const k=n.joins.find(L=>L.id===E);if(!k)return;const R=a.find(L=>L.name===k.source.name),I=a.find(L=>L.name===k.target.name),v=[...k.joinKeyGroups],y=v[N].keys[D];w==="sourceColumnName"&&R?v[N].keys[D]={...y,source:{...y.source,name:M}}:w==="targetColumnName"&&I?v[N].keys[D]={...y,target:{...y.target,name:M}}:w==="operator"&&(v[N].keys[D]={...y,operator:M}),d(E,{joinKeyGroups:v})},removeJoinKey:(E,N,D)=>{const w=n.joins.find(k=>k.id===E);if(!w)return;const M=[...w.joinKeyGroups];M[N].keys.splice(D,1),d(E,{joinKeyGroups:M})},generateSQLPreview:()=>{const E=[...n.joins].sort((w,M)=>w.sequence-M.sequence),N=n.baseEntity;if(!N.name)return"SELECT * FROM table -- Please select a base entity";let D=`SELECT *
415
- FROM ${N.name}`;return E.forEach(w=>{const M=a.find(I=>I.name===w.target.name);if(!M)return;const k=w.joinKeyGroups.filter(I=>I.keys&&I.keys.length>0).map(I=>{const v=I.keys.filter(y=>{var L,F,P,_;return((L=y.source)==null?void 0:L.name)&&((F=y.target)==null?void 0:F.name)&&((P=y.source)==null?void 0:P.entityName)&&((_=y.target)==null?void 0:_.entityName)}).map(y=>`${y.source.entityName}.${y.source.name} ${y.operator} ${y.target.entityName}.${y.target.name}`);return v.length>1?`(${v.join(` ${I.operator} `)})`:v[0]}).filter(Boolean),R=k.length>1?k.join(" OR "):k[0]||"condition_here";D+=`
416
- ${w.joinType} JOIN ${M.name}
417
- ON ${R}`}),D},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(w=>!w.source.name||!w.target.name)||n.joins.some(w=>w.joinKeyGroups.some(M=>M.keys.length===0))||n.joins.some(w=>w.joinKeyGroups.some(M=>M.keys.some(k=>!k.source.name||!k.target.name||!k.operator))))}}function ol({joinPlan:t,availableDataSources:a,onSave:n,onRemove:r,onCancel:l}){const{setCardConfig:o}=s.useEditorActions();s.useEditorStore(k=>k.card.config);const{columnGroups:c}=s.useColumns(),{joinPlan:i,expandedJoins:d,setJoinPlan:m,addJoin:h,removeJoin:u,updateJoin:p,moveJoinUp:f,moveJoinDown:j,toggleJoinExpansion:x,getAvailableSourceEntities:T,getAvailableTargetEntities:g,addJoinKeyGroup:b,updateGroupOperator:C,removeJoinKeyGroup:O,addJoinKey:S,updateJoinKey:E,removeJoinKey:N,generateSQLPreview:D,isValidConfiguration:w}=ll({initialJoinPlan:t,availableDataSources:a}),M=k=>{const R=c.find(I=>I.entityName===k);return(R==null?void 0:R.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:k=>{const R=a.find(I=>I.name===k);m({...i,baseEntity:{connectionId:(R==null?void 0:R.connectionId)||"",connectionType:(R==null?void 0:R.connectionType)||"none",type:(R==null?void 0:R.type)||"table",name:k,database:R==null?void 0:R.database,schema:R==null?void 0:R.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:a.map(k=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:k.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:k.type}),k.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},k.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:D()})]}),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:h,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(k=>{const R=a.find(y=>y.name===k.source.name),I=a.find(y=>y.name===k.target.name),v=d.has(k.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:k.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",k.sequence,R&&I&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",R.name," → ",I.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>f(k.id),disabled:k.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>j(k.id),disabled:k.sequence===i.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>x(k.id),children:v?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:()=>u(k.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),v&&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:k.source.name,onValueChange:y=>{const L=a.find(F=>F.name===y);p(k.id,{source:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:y,database:L==null?void 0:L.database,schema:L==null?void 0:L.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:T(k.id).map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:y.type}),y.name]})},y.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:k.joinType,onValueChange:y=>p(k.id,{joinType:y}),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Target"}),e.jsxs(s.Select,{value:k.target.name,onValueChange:y=>{const L=a.find(F=>F.name===y);p(k.id,{target:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:y,database:L==null?void 0:L.database,schema:L==null?void 0:L.schema}})},disabled:!k.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:k.source.name?g(k.source.name).map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:y.type}),y.name,y.name===k.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},y.name)):[]})]})]})]}),k.source.name&&k.target.name&&R&&I&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>b(k.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),k.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:k.joinKeyGroups.map((y,L)=>e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{children:["Group ",L+1]}),L>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(s.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Select,{value:y.operator,onValueChange:F=>C(k.id,L,F),children:[e.jsx(s.SelectTrigger,{className:"w-[100px]",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>O(k.id,L),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[y.keys.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-sm text-gray-500",children:"No conditions in this group. Add conditions to specify join criteria."}):e.jsx("div",{className:"space-y-2",children:y.keys.map((F,P)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[P>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:y.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:F.source.name,onValueChange:_=>E(k.id,L,P,"sourceColumnName",_),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:M(k.source.name).map(_=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:_.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:_.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:_.dataType})]})},_.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:F.operator,onValueChange:_=>E(k.id,L,P,"operator",_),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:F.target.name,onValueChange:_=>E(k.id,L,P,"targetColumnName",_),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:M(k.target.name).map(_=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:_.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:_.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:_.dataType})]})},_.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>N(k.id,L,P),children:e.jsx(s.X,{className:"size-3.5"})})]},F.id||P))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>S(k.id,L),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},y.id))})]})]})]},k.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),l()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:l,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>n(i),disabled:!w(),children:"Save"})]})]})}function Ys({children:t,open:a,onOpenChange:n,joinPlan:r,availableDataSources:l,onRemove:o,onSave:c,onCancel:i}){return e.jsxs(s.Dialog,{open:a,onOpenChange:n,children:[e.jsxs(s.DialogContent,{className:"max-w-4xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Join Configuration"}),e.jsx(s.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(ol,{joinPlan:r,availableDataSources:l,onSave:c,onCancel:i,onRemove:o})]}),t]})}function il({joins:t,baseEntityId:a,availableDataSources:n,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[t.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const l=[...t].sort((c,i)=>c.sequence-i.sequence),o=n.find(c=>c.name===a);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:o==null?void 0:o.type}),e.jsx("span",{className:"text-xs font-medium",children:o==null?void 0:o.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),l.map(c=>{const i=n.find(d=>d.name===c.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name})]})]},c.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",t.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...t].sort((l,o)=>l.sequence-o.sequence).map((l,o)=>{const c=n.find(d=>d.name===l.source.name),i=n.find(d=>d.name===l.target.name);return e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted p-2 text-left",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:o+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:l.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[c==null?void 0:c.name," → ",i==null?void 0:i.name]}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto text-xs",children:[l.joinKeyGroups.reduce((d,m)=>d+m.keys.length,0)," ","condition",l.joinKeyGroups.reduce((d,m)=>d+m.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 cl(){var h,u;const t=s.useEditorStore(p=>p.card),a=s.useEditorStore(p=>p.actions.updateCardConfig),n=((h=t==null?void 0:t.config)==null?void 0:h.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[r,l]=A.useState(!1),o=((u=t==null?void 0:t.dataSource)==null?void 0:u.selectedEntities)||[],c=p=>{a(t.id,{...t==null?void 0:t.config,joinPlan:p}),l(!1)},i=()=>{a(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},d=()=>{l(!1)},m=()=>{const p=[...n.joins].sort((x,T)=>x.sequence-T.sequence),f=n.baseEntity;if(!f.name)return"SELECT * FROM table -- Please select a base entity";let j=`SELECT *
418
- FROM ${f.name}`;return p.forEach(x=>{const T=o.find(C=>C.name===x.target.name);if(!T)return;const g=x.joinKeyGroups.filter(C=>C.keys&&C.keys.length>0).map(C=>{const O=C.keys.filter(S=>{var E,N,D,w;return((E=S.source)==null?void 0:E.name)&&((N=S.target)==null?void 0:N.name)&&((D=S.source)==null?void 0:D.entityName)&&((w=S.target)==null?void 0:w.entityName)}).map(S=>`${S.source.entityName}.${S.source.name} ${S.operator} ${S.target.entityName}.${S.target.name}`);return O.length>1?`(${O.join(` ${C.operator} `)})`:O[0]}).filter(Boolean),b=g.length>1?g.join(" OR "):g[0]||"condition_here";j+=`
419
- ${x.joinType} JOIN ${T.name}
420
- ON ${b}`}),j};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:[n.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TooltipProvider$1,{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":n.joins.length>0,"text-gray-500":n.joins.length===0})}),"Join",n.joins.length>1?"s":""," (",n.joins.length,")"]})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(il,{joins:n.joins,baseEntityId:n.baseEntity.name,availableDataSources:o,generateSQLPreview:m})})]})}),e.jsx(Ys,{open:r,onOpenChange:l,joinPlan:n,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsx("div",{})})]}),n.joins.length===0&&e.jsx(Ys,{open:r,onOpenChange:l,joinPlan:n,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsxs(s.Button,{onClick:()=>l(!0),variant:"outline",className:"h-6 text-xs font-semibold",children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Configure Join"]})})]})})})}function dl({entity:t,title:a,maxDetails:n=10}){const l=s.getEntityDetails(t).slice(0,n),o=l.find(i=>i.label==="Description"),c=l.filter(i=>i.label==="Description"?!1:!["Connection","Database","Schema"].includes(i.label));return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:a||s.getDisplayName(t)}),o&&e.jsxs("div",{className:"border-t border-border pt-2",children:[e.jsx("div",{className:"mb-1 text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:o.value})]}),c.length>0&&e.jsx("div",{className:"space-y-0.5",children:c.map((i,d)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[i.label,":"]}),e.jsx("span",{className:"font-mono",children:i.value})]},d))})]})})}function ul({entities:t}){return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:[t.length," more entities"]}),e.jsx("div",{className:"space-y-1",children:t.map((a,n)=>{const r=s.getEntityDetails(a),l=r.find(c=>c.label==="Description"),o=r.filter(c=>c.label==="Description"?!1:!["Connection","Database","Schema"].includes(c.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(a)}),l&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:l.value})]}),o.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:o.map((c,i)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[c.label,":"]}),e.jsx("span",{className:"font-mono",children:c.value})]},i))})]},`remaining-${a.type}-${a.name}-${n}`)})})]})})}function ml({isVisible:t,onToggleVisibility:a}){const[n,r]=A.useState(!1),[l,o]=A.useState(!0),c=s.useEditorStore(h=>h.card.dataSource),{updateDataSource:i}=s.useEditorActions(),d={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},m={...d,...c,selectedEntities:(c==null?void 0:c.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden border-r bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[e.jsxs("div",{children:[e.jsx("div",{className:s.cn("p-4 px-6",{"pb-0":!l}),children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex cursor-pointer items-center gap-2",onClick:()=>o(!l),children:[l?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronRight,{className:"h-4 w-4"}),e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Data Source"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:a,title:"Hide Data Source Panel",children:e.jsx(s.EyeOff,{className:"h-3.5 w-3.5"})}),e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7",onClick:()=>r(!0),children:[e.jsx(s.Plus,{className:"mr-1 h-3.5 w-3.5"}),"Add"]})]})]})}),e.jsxs("div",{className:`overflow-hidden px-6 ${l?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[m.selectedEntities.length>0&&e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[m.selectedEntities.slice(0,3).map((h,u)=>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:p=>{p.stopPropagation();const f=m.selectedEntities.filter(j=>!(j.name===h.name&&j.type===h.type));i({...d,...c,selectedEntities:f})},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(dl,{entity:h})]},`${h.type}-${h.name}-${u}`)),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(ul,{entities:m.selectedEntities.slice(3)})]})]})}),e.jsx(cl,{})]})]}),e.jsx(rl,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(c==null?void 0:c.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:r,dataSource:m,fallbackDataSource:d})]})}const ze=[{id:"table",icon:Je,label:"Table"},{id:"bar",icon:$e,label:"Bar Chart"},{id:"line",icon:Ge,label:"Line Chart"},{id:"area",icon:et,label:"Area Chart"},{id:"stackedBar",icon:ms,label:"Stacked Bar Chart"},{id:"combo",icon:Nn,label:"Combo Chart"},{id:"stackedLine",icon:ks,label:"Stacked Line Chart"},{id:"scatter",icon:xs,label:"Scatter Chart"},{id:"bubble",icon:ws,label:"Bubble Chart"},{id:"pie",icon:He,label:"Pie Chart"},{id:"doughnut",icon:ps,label:"Doughnut Chart"},{id:"funnel",icon:Ts,label:"Funnel Chart"},{id:"radar",icon:js,label:"Radar Chart"},{id:"polarArea",icon:Ss,label:"Polar Area Chart"},{id:"tornado",icon:ys,label:"Tornado Chart"},{id:"range",icon:hs,label:"Range Chart"},{id:"kpi",icon:Ds,label:"KPI"},{id:"text",icon:Zs,label:"Text"},{id:"map",icon:gs,label:"Map"}],Ms=t=>{const a=t.toLowerCase();for(const n of ze)if(n.id==="doughnut"){if(a.includes("doughnut")||a.includes("donut")){const r=n.icon;return A.createElement(r,{className:"h-4 w-4"})}}else if(a.includes(n.id.toLowerCase())){const r=n.icon;return A.createElement(r,{className:"h-4 w-4"})}return null},hl="chart-selector-standard-first";function xl(){const[t,a]=s.useLocalStorageState(hl,!0);return{standardFirst:t,updatePreference:a}}const Ks=({pluginVisual:t,index:a,onSelect:n})=>{const r=Ye(t.icon||""),l=t.name.charAt(0).toUpperCase(),o=Ms(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:n,className:"group flex items-center gap-2",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(r,{className:"h-4 w-4"}):o||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:l}),e.jsx("span",{children:t.name})]}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:"opacity-0 outline-none transition-opacity group-hover:opacity-100",children:e.jsx(s.Info,{className:"ml-1 h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"right",children:t.pluginName})]})]})},`${t.url}-${t.name}-${a}`)},Qs=["default","standardPlugin","customPlugin"];function pl({selectedChart:t,onChartChange:a}){var E;const[n,r]=A.useState([]),[l,o]=A.useState(!1),{data:c}=Cs();xl();const d=((E=s.useEditorStore(N=>N.card).customCardPreferences)==null?void 0:E.url)||"";s.useRemoteChartStore(d);const{setCardType:m,setCardPreferences:h,setIsDevMode:u}=s.useEditorStore(N=>N.actions),{setCardCustomCfg:p,setCustomCardPreferences:f,setQueryConfig:j}=s.useEditorActions(),[x,T]=s.useLocalStorageState("chart-section-active",null),g=A.useMemo(()=>x?[x,...Qs.filter(N=>N!==x)]:Qs,[x]);A.useEffect(()=>{(async()=>{if(c){const w=(await Promise.allSettled(c.plugins.map(async M=>{try{return(await s.loadManifest(M.value)).visuals.map(R=>({name:R.name,icon:R.icon,url:M.value,pluginName:M.label,pluginType:M.type,chartType:R.chartType,componentType:R.componentType}))}catch(k){return console.error(`Failed to load manifest for plugin ${M.label}`,k),[]}}))).filter(M=>M.status==="fulfilled").flatMap(M=>M.value);r(w)}})()},[c]);function b(N){p(null),h({}),m(N),["custom","text","map"].includes(N)&&(u(!0),j(void 0)),a(N),o(!1)}function C(N){p(null),h({}),m("custom"),f({type:"component",visualType:"single",url:N.url,componentName:N.name,icon:N.icon,pluginChartType:N.chartType}),j(void 0),a("custom"),o(!1)}const O=()=>{var D;if(t==="custom"){const w=s.useEditorStore.getState().card;return((D=w==null?void 0:w.customCardPreferences)==null?void 0:D.componentName)||"Custom Visual"}const N=ze.find(w=>w.id===t);return(N==null?void 0:N.label)||"Select chart type"},S=()=>{var D,w;if(t==="custom"){const M=s.useEditorStore.getState().card,k=(D=M==null?void 0:M.customCardPreferences)==null?void 0:D.icon,R=(w=M==null?void 0:M.customCardPreferences)==null?void 0:w.componentName;if(k&&R)return e.jsx(fl,{icon:k,componentName:R});if(R){const I=Ms(R);if(I)return I}return e.jsx(Ae,{className:"h-4 w-4"})}const N=ze.find(M=>M.id===t);if(N){const M=N.icon;return e.jsx(M,{className:"h-4 w-4"})}return e.jsx(Ae,{className:"h-4 w-4"})};return e.jsx("div",{className:"mb-6",children:e.jsxs(s.Popover,{open:l,onOpenChange:o,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":l,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[S(),e.jsx("span",{children:O()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[335px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search chart types..."}),e.jsxs(s.CommandList,{className:"mb-2 max-h-[300px]",children:[e.jsx(s.CommandEmpty,{children:"No chart type found."}),g.map(N=>{if(N==="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:x==="default",onCheckedChange:D=>T(D?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:ze.map(D=>{const w=D.icon;return e.jsx(s.CommandItem,{value:`${D.label} ${D.id} chart graph visualization`,onSelect:()=>b(D.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(w,{className:"h-4 w-4"}),e.jsx("span",{children:D.label})]})},D.id)})},"default");if(N==="standardPlugin"){const D=n.filter(w=>w.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:x==="standardPlugin",onCheckedChange:w=>T(w?"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(w=>w.componentType==="chart").map((w,M)=>e.jsx(Ks,{pluginVisual:w,index:M,onSelect:()=>C(w)},`${w.url}-${w.name}-${M}`))},"standardPlugin"):null}if(N==="customPlugin"){const D=n.filter(w=>w.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:x==="customPlugin",onCheckedChange:w=>T(w?"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((w,M)=>e.jsx(Ks,{pluginVisual:w,index:M,onSelect:()=>C(w)},`${w.url}-${w.name}-${M}`))},"customPlugin"):null}return null})]})]})})]})})}const fl=({icon:t,componentName:a})=>{const n=Ye(),r=Ms(a);return n?e.jsx(n,{className:"h-4 w-4"}):r||e.jsx(Ae,{className:"h-4 w-4"})},Kt=({dataType:t})=>{const a=s.getDataType(t);return a==="string"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-blue-500 text-xs text-white",children:"T"}):a==="number"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-green-500 text-xs text-white",children:"#"}):a==="date"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-purple-500 text-xs text-white",children:"D"}):a==="boolean"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-orange-500 text-xs text-white",children:"B"}):e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-gray-500 text-xs text-white",children:"?"})};function gl({aliasTemplate:t,onAliasTemplateChange:a}){var d;const[n,r]=A.useState(t),[l,o]=A.useState(!1),c=(d=s.useEditorStore(m=>{var h;return(h=m.card.config)==null?void 0:h.pivotByColumns}))==null?void 0:d[0],i=c?`e.g. Min Sales in {{${c.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Input$1,{placeholder:i,value:l?n:t,onChange:m=>{r(m.target.value),o(!0)},onFocus:()=>o(!0),onPointerDown:m=>m.stopPropagation(),className:"h-8 text-xs",onKeyDown:m=>{m.key==="Enter"&&l&&n!==t?(a(n),o(!1)):m.key==="Escape"&&(r(t),o(!1))},"aria-label":"Edit alias template"}),l&&n!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{a(n),o(!1)},children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(t),o(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function jl({valueAliases:t,onValueAliasesChange:a}){const[n,r]=A.useState(null),[l,o]=A.useState(""),[c,i]=A.useState(""),d=()=>{a({...t,"":""})},m=u=>{const p={...t};delete p[u],a(p)},h=u=>{const p={...t};delete p[u],p[l]=c,a(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(([u,p],f)=>e.jsx("div",{className:"flex items-center gap-2",children:n===u?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:l,onChange:j=>o(j.target.value),className:"h-8 w-24 text-xs",onPointerDown:j=>j.stopPropagation(),onKeyDown:j=>{j.key==="Enter"?h(u):j.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:j=>i(j.target.value),className:"h-8 w-24 text-xs",onPointerDown:j=>j.stopPropagation(),onKeyDown:j=>{j.key==="Enter"?h(u):j.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>h(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 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:u,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(u),o(u),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(u),o(u),i(p)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>m(u),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},u+f)),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 Xs({value:t,onSave:a,placeholder:n="",type:r="text",className:l=""}){const[o,c]=A.useState(t??""),[i,d]=A.useState(!1);A.useEffect(()=>{c(t??"")},[t]);const m=()=>{a(o),d(!1)},h=()=>{c(t??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${l}`,children:[e.jsx(s.Input$1,{placeholder:n,type:r,value:i?o:t??"",onChange:u=>{c(u.target.value),d(!0)},onFocus:()=>d(!0),onClick:u=>u.stopPropagation(),className:"h-8 text-xs",onPointerDown:u=>u.stopPropagation(),onKeyDown:u=>{u.stopPropagation(),u.key==="Enter"&&i&&o!==t?m():u.key==="Escape"&&h()},"aria-label":n||"Edit field"}),i&&o!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:m,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:h,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function yl({field:t,zone:a,index:n,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:o=!1,cardType:c}){var Rs;const{attributes:i,listeners:d,setNodeRef:m,transform:h,transition:u,isDragging:p}=s.useSortable({id:t.id}),f=s.useEditorStore(X=>X.card),{updateLabel:j,handleAggregationChange:x,handleDateFormatChange:T,handleGranularityChange:g,handleAliasTemplateChange:b,handleValueAliasesChange:C,removeField:O,handleKpiComparisonTypeChange:S,handleKpiShowTrendlineChange:E,handleKpiTrendlineWindowChange:N,handleKpiTrendlineGranularityChange:D,handleKpiTargetValueChange:w}=As(f),[M,k]=A.useState(!1),[R,I]=A.useState(t.dateFormat||"YYYY-MM-DD"),[v,y]=A.useState(t.customFormat||""),[L,F]=A.useState(!!t.customFormat),[P,_]=A.useState(t.granularity||"day"),[z,Q]=A.useState(t.aliasTemplate||""),[Y,V]=A.useState(t.valueAliases||{}),q=X=>{X==="custom"?F(!0):(F(!1),I(X),a==="groupBy"&&T(n,X,""))},$=X=>{y(X),a==="groupBy"&&T(n,"custom",X)},U=X=>{_(X),a==="groupBy"&&g(n,X)},H=X=>{Q(X),a==="metrics"&&b(n,X)},W=X=>{V(X),a==="metrics"&&C(n,X)},G=X=>{j(a,n,X)},Z=()=>{O(a,n)},se={transform:s.CSS.Transform.toString(h),transition:u},ne=s.getDataType(t.dataType),ee=ne==="date",ae=c==="kpi",J=[{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..."}],B=!ae&&a!=="pivotBy",K=ae&&ee&&a==="groupBy",re=!ae&&ee&&a==="groupBy",he=ae&&ee&&a==="groupBy",je=ae&&a==="metrics"&&((Rs=f.config)==null?void 0:Rs.comparisonType)==="target",te=a==="metrics",le=()=>e.jsx("div",{onPointerDown:X=>{X.stopPropagation()},className:"cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),oe=()=>B?e.jsx(Xs,{value:t.label??"",onSave:G,placeholder:"Display label...",type:"text"}):null,Os=()=>K?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:P,onValueChange:U,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"}),e.jsx(s.SelectItem,{value:"quarter",children:"Quarter"}),e.jsx(s.SelectItem,{value:"year",children:"Year"})]})]})]}):null,Zt=()=>re?e.jsxs(e.Fragment,{children:[Os(),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:L?"custom":R,onValueChange:q,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:J.map(X=>e.jsx(s.SelectItem,{value:X.value,children:X.label},X.value))})]}),L&&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:v,onChange:X=>{X.stopPropagation(),$(X.target.value)},onClick:X=>X.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,en=()=>{var X,xe,Te,Bs,Fs;return he?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:((X=f.config)==null?void 0:X.comparisonType)||"none",onValueChange:S,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:((xe=f.config)==null?void 0:xe.showTrendline)||!1,onCheckedChange:E})]})}),((Te=f.config)==null?void 0:Te.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:((Bs=f.config)==null?void 0:Bs.trendlineWindow)||30,onChange:nn=>{const an=parseInt(nn.target.value)||30;N(an)},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:((Fs=f.config)==null?void 0:Fs.trendlineGranularity)||"day",onValueChange:D,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},sn=()=>{var X,xe;return je?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(Xs,{value:((X=f.config)==null?void 0:X.targetValue)!==void 0&&((xe=f.config)==null?void 0:xe.targetValue)!==null?String(f.config.targetValue):"",onSave:Te=>{!isNaN(Number(Te))&&Te!==null?w(Number(Te)):w(0)},placeholder:"Enter target value...",type:"text"})]}):null},tn=()=>te?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:X=>{x(n,X)},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,{value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsx(Gt,{column:t}),o&&e.jsxs(e.Fragment,{children:[e.jsx(gl,{aliasTemplate:z,onAliasTemplateChange:H}),e.jsx(jl,{valueAliases:Y,onValueAliasesChange:W})]})]}):null;return e.jsxs("div",{ref:m,style:se,...i,...d,className:`group mx-auto flex w-full max-w-[300px] 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"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.GripVertical,{className:"h-3 w-3"}),e.jsx(Kt,{dataType:ne}),e.jsx(Es,{className:"max-w-[180px] flex-1 text-sm",children:t.label||t.name}),a!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:X=>{X.stopPropagation(),k(!M)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${M?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 group-hover:opacity-100",onClick:X=>{X.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const xe=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",xe),l(xe)},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 opacity-0 group-hover:opacity-100",onClick:X=>{X.stopPropagation(),Z()},children:e.jsx(s.X,{className:"h-3 w-3"})})]}),M&&e.jsxs("div",{className:"space-y-3",children:[le(),oe(),Os(),Zt(),en(),sn(),tn()]})]})}function vl({concept:t}){const a=()=>{switch(t){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-100 text-xs font-medium dark:bg-blue-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/50 text-xs font-medium dark:bg-blue-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/30 text-xs font-medium dark:bg-blue-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/20 text-xs font-medium dark:bg-blue-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metrics = Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});default:return null}};return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(s.TooltipContent,{side:"right",align:"start",className:"p-3",children:a()})]})})}function Fe({zone:t,fields:a,label:n,placeholder:r,shouldShow:l,hasPivotColumns:o=!1}){const{isOver:c,setNodeRef:i}=s.useDroppable({id:t}),{updateSortByColumn:d}=s.useEditorActions(),m=s.useEditorStore(j=>j.card),h=s.useEditorStore(j=>j.card.type),u=a.length>0,p=(j,x)=>{var g;!((g=m.config)!=null&&g.sortByColumns)||m.config.sortByColumns.findIndex(b=>b.id===j)===-1||d(m.id,j,{direction:x})};if(t==="sortBy"&&l===!1)return null;const f=t!=="sortBy"&&h!=="kpi";return e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:n}),f&&e.jsx(vl,{concept:t})]}),e.jsx("div",{ref:i,className:`min-h-[60px] rounded-lg border-2 border-dashed p-3 transition-all ${c?"border-blue-500 bg-blue-50 dark:bg-blue-950":"border-muted-foreground/20 bg-muted/50"}`,children:a.length===0?e.jsxs("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),r]}):e.jsx(s.SortableContext,{items:a.map(j=>j.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map((j,x)=>{const g=j.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(yl,{field:j,zone:t,index:x,sortDirection:g,onSortDirectionChange:b=>p(j.id,b),hasPivotColumns:o,cardType:h})})},j.id)})})})})]})}function bl({groupByFields:t,pivotByFields:a,metricsFields:n,sortByFields:r}){const l=s.useEditorStore(u=>u.card),o=l==null?void 0:l.type,c=t.length>0||n.length>0,i=o!=="kpi",d=o!=="kpi"&&c,m=()=>o==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},h=()=>o==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Fe,{zone:"groupBy",fields:t,label:m().label,placeholder:m().placeholder}),i&&e.jsx(Fe,{zone:"pivotBy",fields:a,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(Fe,{zone:"metrics",fields:n,label:h().label,placeholder:h().placeholder,hasPivotColumns:a.length>0}),d&&e.jsx(Fe,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})}function Nl({selectedChart:t,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:o}){const c=s.useEditorStore(u=>u.showAIDialog),i=n.length>0||r.length>0||l.length>0,{setShowAIDialog:d}=s.useEditorActions(),m=s.useEditorStore(u=>u.card),{data:h}=s.useDashboardCardQuery(m);return e.jsxs("div",{className:"flex w-96 flex-col border-r bg-background",children:[e.jsxs("div",{className:"space-y-4 border-b px-6 py-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h2",{className:"font-semibold",children:"Chart Configuration"})}),e.jsx(pl,{selectedChart:t,onChartChange:a})]}),e.jsxs("div",{className:s.cn("flex justify-end gap-2 px-6 pt-6"),children:[e.jsx("div",{className:s.cn("invisible",{visible:i||h}),children:e.jsx(s.EditorClearButton,{})}),!c&&e.jsxs(s.Button,{onClick:()=>d(!c),variant:"outline",className:"h-8",size:"sm",children:[e.jsx(sa,{className:"mr-2 size-4"}),"AI"]})]}),e.jsxs(s.ScrollArea,{className:"flex-1 basis-0 px-6",children:[e.jsx(bl,{groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:o}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Cl({initialFilters:t,availableFields:a}={}){const[n,r]=A.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(S=>S.card.dataSource);const{columns:l,isLoading:o}=s.useColumns(),i=a||l||[],d={id:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},m=S=>{const E=N=>{if(N.id===S){const D=i[0]||d;return{...N,conditions:[...N.conditions,{id:`condition-${Date.now()}`,field:D,operator:"=",value:""}]}}return{...N,groups:N.groups.map(E)}};r(E(n))},h=S=>{const E=N=>{if(N.id===S){const D=i[0]||d;return{...N,groups:[...N.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:D,operator:"=",value:""}],groups:[]}]}}return{...N,groups:N.groups.map(E)}};r(E(n))},u=(S,E)=>{const N=D=>D.id===S?{...D,conditions:D.conditions.filter(w=>w.id!==E)}:{...D,groups:D.groups.map(N)};r(N(n))},p=(S,E)=>{const N=D=>D.id===S?{...D,groups:D.groups.filter(w=>w.id!==E)}:{...D,groups:D.groups.map(N)};r(N(n))},f=(S,E,N,D)=>{if(N==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const w=M=>M.id===S?{...M,conditions:M.conditions.map(k=>k.id===E?{...k,[N]:D}:k)}:{...M,groups:M.groups.map(w)};r(w(n))},j=(S,E,N)=>{const D=w=>w.id===S?{...w,conditions:w.conditions.map(M=>M.id===E?{...M,...N}:M)}:{...w,groups:w.groups.map(D)};r(D(n))},x=(S,E)=>{const N=D=>D.id===S?{...D,logicalOperator:E}:{...D,groups:D.groups.map(N)};r(N(n))},T=(S,E)=>{const N=D=>D.id===S?{...D,negate:E}:{...D,groups:D.groups.map(N)};r(N(n))},g=(S,E,N)=>{const D=w=>w.id===S?{...w,conditions:s.arrayMove(w.conditions,E,N)}:{...w,groups:w.groups.map(D)};r(D(n))},b=(S,E,N)=>{const D=w=>w.id===S?{...w,groups:s.arrayMove(w.groups,E,N)}:{...w,groups:w.groups.map(D)};r(D(n))},C=S=>{if(!S||S.conditions.length===0&&S.groups.length===0)return"-- No filters defined";const E=D=>{let w="";typeof D.field=="object"?w=D.field.entityName?`${D.field.entityName}.${D.field.name}`:D.field.name:w=String(D.field);const M=D.operator;let k=D.value;if(D.field.dataType==="string"&&!["in","not in"].includes(D.operator))typeof k=="string"?k=`'${k}'`:Array.isArray(k)&&(k=`'${k.join(", ")}'`);else if(D.field.dataType==="date")(typeof k=="string"||k instanceof Date)&&(k=`DATE('${k}')`);else if(["in","not in"].includes(D.operator)){let R=[];Array.isArray(k)?R=k.map(I=>typeof I=="string"?`'${I}'`:String(I)):typeof k=="string"?R=k.split(",").map(I=>{const v=I.trim();return D.field.dataType==="string"?`'${v}'`:v}):typeof k=="number"&&(R=[String(k)]),k=`(${R.join(", ")})`}switch(M){case"contains":return typeof k=="string"?`${w} LIKE '%${k.replace(/'/g,"")}'`:`${w} LIKE '%${String(k)}'`;case"startsWith":return typeof k=="string"?`${w} LIKE '${k.replace(/'/g,"")}%'`:`${w} LIKE '${String(k)}%'`;case"endsWith":return typeof k=="string"?`${w} LIKE '%${k.replace(/'/g,"")}'`:`${w} LIKE '%${String(k)}'`;default:return`${w} ${M} ${k}`}},N=D=>{const w=D.conditions.map(E),M=D.groups.map(v=>N(v)),k=[...w,...M].filter(Boolean);if(k.length===0)return"";const R=k.join(` ${D.logicalOperator} `),I=k.length>1?`(${R})`:R;return D.negate?`NOT ${I}`:I};return N(S)},O=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:i,isLoading:o,addCondition:m,addGroup:h,removeCondition:u,removeGroup:p,updateCondition:f,updateConditionFields:j,updateGroupOperator:x,updateGroupNegate:T,reorderConditions:g,reorderGroups:b,generateSQLPreview:C,hasAnyFilters:O}}function Sl({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const wl=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(Mn,{className:"h-3 w-3"});default:return e.jsx(s.Table,{className:"h-3 w-3"})}},Tl=t=>{if(t.qualifiedEntityName){const a=t.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function kl({value:t,onValueChange:a,availableFields:n,placeholder:r="Select field",className:l="w-64"}){const[o,c]=A.useState(!1),i=A.useMemo(()=>{const d={};return n.forEach(m=>{const h=Tl(m);d[h]||(d[h]={}),d[h][m.entityId]||(d[h][m.entityId]=[]),d[h][m.entityId].push(m)}),d},[n]);return e.jsxs(s.Popover,{modal:!0,open:o,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:s.cn("justify-between",!t&&"text-muted-foreground",l),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Sl,{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,m])=>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(m).map(([h,u])=>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:[wl(u[0].entityType),e.jsx("span",{children:u[0].entityName})]}),u.map((p,f)=>e.jsxs(s.CommandItem,{value:p.id,onSelect:()=>{a(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+f))]},`${d}-${h}`))},d))})]})})]})}function Ls(t){var j;const a=s.useEditorStore(x=>x.card),{authToken:n}=s.useSemaphorContext(),r=s.useEditorStore(x=>x.card.config),l=r==null?void 0:r.joinPlan,o={...t,alias:t.name,label:"value",role:"groupby"},c={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},i={...o,role:"sortby",direction:"asc"},d={joinPlan:l,groupByColumns:[o],metricColumns:[c],sortByColumns:[i]},m=((j=a.dataSource)==null?void 0:j.connectionId)||a.connectionId,{data:h,isPending:u,error:p}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(n==null?void 0:n.accessToken)||"",{connection_id:m,cardConfig:d,cardDataSource:a.dataSource})}catch(x){console.log(t),console.error("error",x)}},enabled:!!m,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((h==null?void 0:h.records)||[]).map(x=>({label:x[t.name]||"BLANK",value:x[t.name]||"BLANK",count:(x==null?void 0:x.count)||0})),isPending:u,error:p}}function Dl({field:t,selected:a,onChange:n,placeholder:r="Select items...",className:l}){const[o,c]=ye.useState(!1),{filterValues:i}=Ls(t),d=h=>{n(a.filter(u=>u!==h))},m=h=>{a.includes(h)?n(a.filter(u=>u!==h)):n([...a,h])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open:o,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(h=>{const u=i.find(p=>p.value===h);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[u==null?void 0:u.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(h)},onMouseDown:p=>{p.preventDefault(),p.stopPropagation()},onClick:p=>{p.stopPropagation(),d(h)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},h)}):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((h,u)=>e.jsxs(s.CommandItem,{onSelect:()=>m(h.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",a.includes(h.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:h.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:h.count})]})]},h.value+u))})]})]})})]})})}const Qt=t=>{if(!t)return 0;let a=t.conditions.length;return t.groups.forEach(n=>{a+=Qt(n)}),a};function El({field:t,value:a,onChange:n,placeholder:r="Select value...",className:l}){const{filterValues:o,isPending:c,error:i}=Ls(t);return c?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):i?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:a,onValueChange:n,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:a})}),e.jsx(s.SelectContent,{children:o.map((d,m)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+m))})]})}const Il=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in"],Al=["=","!=","contains","startsWith","endsWith","in","not in"],Ml=["=","!=",">",">=","<","<=","in","not in"],Ll=["=","!="],Ol=["=","!=",">",">=","<","<=","in","not in"];function Rl(t){switch(t){case"string":return Al;case"number":return Ml;case"boolean":return Ll;case"date":return Ol;default:return Il}}function Xt({condition:t,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:o,onUpdateGroupOperator:c,availableFields:i,updateConditionFields:d}){const{attributes:m,listeners:h,setNodeRef:u,transform:p,transition:f,isDragging:j}=s.useSortable({id:t.id}),{isPending:x,error:T}=Ls(t.field),g={transform:s.CSS.Transform.toString(p),transition:f};return e.jsxs("div",{ref:u,style:g,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${j?"z-50 opacity-50":""}`,children:[e.jsx("div",{...m,...h,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(s.Select,{value:r,onValueChange:b=>c(n,b),children:[e.jsx(s.SelectTrigger,{className:"w-24",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(kl,{value:t.field,onValueChange:b=>{d(n,t.id,{field:b,value:""})},availableFields:i,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:b=>{b==="in"||b==="not in"?d(n,t.id,{operator:b,value:[]}):d(n,t.id,{operator:b,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-28",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Rl(s.getDataType(t.field.dataType)).map(b=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:b,children:b},b))})]}),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..."]}):T?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(Dl,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(b=>typeof b=="string")?t.value:[],onChange:b=>d(n,t.id,{value:b}),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:b=>d(n,t.id,{value:b.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(El,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:b=>d(n,t.id,{value:b}),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:b=>d(n,t.id,{value:b==="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"})]})]}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:b=>l(n,t.id,"value",b.target.value),className:"flex-1",placeholder:t.operator==="in"||t.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>o(n,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function Bl({group:t,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:o,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onReorderConditions:m,onReorderGroups:h,onAddCondition:u,onAddGroup:p,availableFields:f,renderFilterGroup:j,updateConditionFields:x}){const{attributes:T,listeners:g,setNodeRef:b,transform:C,transition:O,isDragging:S}=s.useSortable({id:t.id}),E={transform:s.CSS.Transform.toString(C),transition:O},N=w=>{const{active:M,over:k}=w;if(k&&M.id!==k.id){const R=t.conditions.findIndex(v=>v.id===M.id),I=t.conditions.findIndex(v=>v.id===k.id);R!==-1&&I!==-1&&m(t.id,R,I)}},D=w=>{const{active:M,over:k}=w;if(k&&M.id!==k.id&&n){const R=t.groups.findIndex(v=>v.id===M.id),I=t.groups.findIndex(v=>v.id===k.id);R!==-1&&I!==-1&&h(n,R,I)}};return e.jsxs("div",{ref:b,style:E,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${S?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...T,...g,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:w=>r(t.id,w),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>n&&o(n,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:N,children:e.jsx(s.SortableContext,{items:t.conditions.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((w,M)=>e.jsx(Xt,{condition:w,index:M,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:f,updateConditionFields:x},w.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:D,children:e.jsx(s.SortableContext,{items:t.groups.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(w=>j(w,a+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>u(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 Fl({filters:t,availableFields:a,onSave:n,onClearAll:r,onCancel:l}){const{currentFilters:o,availableFields:c,isLoading:i,addCondition:d,addGroup:m,removeCondition:h,removeGroup:u,updateCondition:p,updateConditionFields:f,updateGroupOperator:j,updateGroupNegate:x,reorderConditions:T,reorderGroups:g,generateSQLPreview:b,hasAnyFilters:C,setCurrentFilters:O}=Cl({initialFilters:t,availableFields:a}),S=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[E,N]=A.useState(!1),D=(k,R,I)=>{const v=y=>y.id===k?{...y,conditions:y.conditions.map(L=>L.id===R?{...L,field:I,dataType:I.dataType}:L)}:{...y,groups:y.groups.map(v)};O(v(o))},w=(k,R=0,I)=>R===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:S,collisionDetection:s.closestCenter,onDragEnd:v=>{const{active:y,over:L}=v;if(L&&y.id!==L.id){const F=k.conditions.findIndex(_=>_.id===y.id),P=k.conditions.findIndex(_=>_.id===L.id);F!==-1&&P!==-1&&T(k.id,F,P)}},children:e.jsx(s.SortableContext,{items:k.conditions.map(v=>v.id),strategy:s.verticalListSortingStrategy,children:k.conditions.map((v,y)=>e.jsx(Xt,{condition:v,index:y,groupId:k.id,groupLogicalOperator:k.logicalOperator,onUpdateCondition:p,onUpdateField:D,onRemoveCondition:h,onUpdateGroupOperator:j,availableFields:c,updateConditionFields:f},v.id))})}),e.jsx(s.DndContext,{sensors:S,collisionDetection:s.closestCenter,onDragEnd:v=>{const{active:y,over:L}=v;if(L&&y.id!==L.id){const F=k.groups.findIndex(_=>_.id===y.id),P=k.groups.findIndex(_=>_.id===L.id);F!==-1&&P!==-1&&g(k.id,F,P)}},children:e.jsx(s.SortableContext,{items:k.groups.map(v=>v.id),strategy:s.verticalListSortingStrategy,children:k.groups.map(v=>w(v,R+1,k.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(k.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),E&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>m(k.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},k.id):e.jsx(Bl,{group:k,depth:R,parentGroupId:I,onUpdateGroupOperator:j,onUpdateGroupNegate:x,onRemoveGroup:u,onUpdateCondition:p,onUpdateField:D,onRemoveCondition:h,onReorderConditions:T,onReorderGroups:g,onAddCondition:d,onAddGroup:m,availableFields:c,renderFilterGroup:w,updateConditionFields:f},k.id),M=Qt(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..."})]}):w(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.Checkbox,{id:"advanced-mode",checked:E,onCheckedChange:k=>N(!!k)}),e.jsx("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)"})]})}),C&&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:b(o)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:l,children:"Cancel"}),M>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>n(C?o:null),children:"Apply Filters"})]})]})}function zl({cardId:t,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:l,isOpen:o,onOpenChange:c}){const i=m=>{n(t,m),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:m=>{m.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(Fl,{filters:a,availableFields:l,onSave:i,onCancel:()=>c(!1),onClearAll:d})]})]})}function Pl({activeCardId:t,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var f;const[l,o]=A.useState(null),c=s.useEditorStore(j=>j.card),i=(f=c==null?void 0:c.config)==null?void 0:f.joinPlan,d=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],m=A.useCallback(j=>j.startsWith("card-")?null:j.startsWith("source-")||a.find(x=>x.id===j)?"source":n("groupBy").find(x=>x.id===j)?"groupBy":n("metrics").find(x=>x.id===j)?"metrics":n("pivotBy").find(x=>x.id===j)?"pivotBy":n("sortBy").find(x=>x.id===j)?"sortBy":null,[a,n]),h=A.useCallback(j=>{o(j.active.id)},[]),u=A.useCallback(j=>{const{active:x,over:T}=j;if(!T||!t){o(null);return}const g=x.id,b=T.id,C=m(g),O=m(b)||b;if(C==="source"&&O==="sortBy"){o(null);return}if(C==="source"&&O!=="source"&&O!=="sortBy"){const S=[...a].find(w=>w.id===g);if(!S){o(null);return}const E=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(E.length>0){const w=E[0].qualifiedEntityName;if(!w){o(null);return}if(w!==S.qualifiedEntityName&&S.qualifiedEntityName)if(i){if(!Yt(w,S.qualifiedEntityName,i)){ds(),o(null);return}}else{ds(),o(null);return}}const N=n(O);if(us(S,N)){o(null);return}const D=cs(S,O);o(null),r(O,[...N,D]);return}if(C&&O&&C!=="source"&&O!=="source"&&C!==O){const S=n(C),E=n(O),N=S.find(M=>M.id===g);if(!N){o(null);return}const D=cs(N,O);if(o(null),O==="sortBy"){if(C==="pivotBy"){o(null);return}us(N,E)||r(O,[...E,D]);return}const w=S.filter(M=>M.id!==g);r(C,w),r(O,[...E,D]);return}if(C&&O&&C===O&&C!=="source"){const S=n(C),E=S.findIndex(D=>D.id===g),N=S.findIndex(D=>D.id===b);if(E!==N){const D=s.arrayMove(S,E,N);r(C,D)}}o(null)},[t,a,n,r,m,i]),p=l?d.find(j=>j.id===l):null;return{activeId:l,activeField:p,handleDragStart:h,handleDragEnd:u}}function _l({activeView:t,onViewChange:a}){const n=s.useEditorStore(l=>l.card),{errorMessage:r}=s.useDashboardCardQuery(n);return e.jsx(s.Tabs,{value:t,onValueChange:l=>a(l),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-2 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),n.type!=="kpi"&&e.jsx(s.TabsTrigger,{value:"sql",className:s.cn("rounded-md transition data-[state=active]:bg-muted",r&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:r?"Error":"Query"})]})})}const Vl=[{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 Ul(){var d,m;const t=s.useEditorStore(h=>h.card),{updateRowLimit:a}=s.useEditorActions(),[n,r]=A.useState(!1),[l,o]=A.useState(""),c=h=>{if(h==="custom"){r(!0);return}r(!1),a(t.id,parseInt(h))},i=h=>{const u=h.target.value;o(u),u&&!isNaN(parseInt(u))&&a(t.id,parseInt(u))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(s.Input,{type:"number",value:l,onChange:i,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((m=(d=t.config)==null?void 0:d.rowLimit)==null?void 0:m.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:Vl.map(h=>e.jsx(s.SelectItem,{value:h.value,children:h.label},h.value))})]})})}function ql({isOpen:t,onClose:a}){const n=ma(a,{enabled:t}),r=s.useEditorStore(h=>{var u;return((u=h.card.customCardPreferences)==null?void 0:u.url)||""}),l=s.useEditorStore(h=>h.card),o=s.useEditorStore(h=>{var u;return((u=h.card.customCardPreferences)==null?void 0:u.pluginChartType)||""}),c=s.useEditorStore(h=>{var u;return((u=h.card.customCardPreferences)==null?void 0:u.settings)||{}}),{data:i}=s.useDashboardCardQuery(l),{getCard:d}=s.useCustomVisual(r),m=A.useMemo(()=>!r||r.trim()===""?null:d("Chart Settings"),[d,r]);return e.jsx("div",{ref:n,className:s.cn("absolute right-0 top-0 z-40 h-full w-[350px] border-l bg-background shadow-lg transition-transform duration-300",t?"translate-x-0":"translate-x-full"),style:{willChange:"transform"},tabIndex:t?0:-1,"aria-hidden":!t,children:e.jsxs("div",{className:"flex h-full flex-col p-4 px-5 pr-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Chart Settings"}),e.jsx(s.IconButton,{"aria-label":"Hide Chart Settings",tooltip:"Hide",onClick:a,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:m&&e.jsx(A.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(m,{chartData:(i==null?void 0:i.records)||[],chartType:o,settings:c})})})]})})}function $l({activeView:t,onViewChange:a,showDebug:n,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:d,activeCard:m,columns:h,columnsLoading:u,columnsError:p}){var R;const f=s.useEditorStore(I=>I.card),j=s.useDashboardStore(I=>I.filterValues),{updateCardConfig:x}=s.useEditorActions(),T=s.useEditorStore(I=>I.showAIDialog),[g,b]=A.useState(!1),C=s.useEditorStore(I=>{var v;return((v=I.card.customCardPreferences)==null?void 0:v.url)&&I.card.type==="custom"}),{data:O,errorMessage:S,isPending:E,isLoading:N,isFetching:D}=s.useDashboardCardQuery(m);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(f.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(j||{},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(m.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",h.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:u?"Loading...":p?"Error loading columns":JSON.stringify(h.slice(0,5),null,2)})]})]})})}const M=I=>{if(!f.config)return;if(!I.length){x(f.id,{...f.config,sortByColumns:[]});return}const v=f.config,y=I.map(({id:L,desc:F})=>{var Q,Y;const P=(Q=v.metricColumns)==null?void 0:Q.find(V=>V.label===L),_=(Y=v.groupByColumns)==null?void 0:Y.find(V=>V.label===L),z=P||_;return z?{id:Jt("sortBy",z),name:z.name,dataType:z.dataType,label:z.label,qualifiedEntityName:z.qualifiedEntityName,entityId:z.entityId,entityName:z.entityName,entityType:z.entityType,role:"sortby",direction:F?"desc":"asc"}:null}).filter(L=>L!==null);x(f.id,{...v,sortByColumns:y})},k=A.useMemo(()=>{var I,v;return(v=(I=f.config)==null?void 0:I.sortByColumns)==null?void 0:v.map(y=>({id:y.label,desc:y.direction==="desc"}))},[(R=f.config)==null?void 0:R.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[e.jsx(s.ExplorerHeader,{showDebug:n,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:d}),n&&w(),e.jsx(s.Separator,{}),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"&&T&&e.jsx(Ft,{variant:"outline"}),e.jsx(_l,{activeView:t,onViewChange:a}),i&&e.jsxs(s.IconButton,{tooltip:"Card Filters",className:"h-8 gap-1",onClick:i,children:[e.jsx(s.Filter,{className:"h-3.5 w-3.5"}),d>0&&e.jsx("span",{className:"ml-1 rounded-full bg-blue-100 px-1.5 py-0.5 text-xs text-blue-800",children:d})]}),e.jsx("div",{className:"ml-2",children:e.jsx(Ul,{})})]}),e.jsx("div",{className:s.cn("flex grow items-center justify-end"),children:t==="chart"&&e.jsx(zt,{})})]}),!g&&C&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>b(!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(Xn,{className:"size-4"})}),e.jsxs("div",{className:"flex grow flex-col",children:[t==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:N||D?e.jsx("div",{className:"m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx(Pt,{})}),t==="table"&&(O==null?void 0:O.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:[(N||D)&&e.jsx("div",{className:"absolute flex h-full w-full items-center justify-between",children:e.jsx("div",{className:"z-10 m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}),e.jsx(s.TableVisual,{card:m,data:O==null?void 0:O.records,onSortChange:M,sortState:k})]}),t==="sql"&&e.jsx("div",{className:"p-6",children:e.jsxs("div",{className:"rounded-md border bg-background p-4",children:[(O==null?void 0:O.sql)&&e.jsx("h3",{className:"mb-3 text-sm font-medium",children:"Generated SQL Query"}),e.jsx(It,{sql:O==null?void 0:O.sql,error:S})]})})]}),e.jsx(ql,{isOpen:g,onClose:()=>b(!1)})]})]})}function Gl({activeField:t}){const[a,n]=A.useState(!0);return A.useEffect(()=>{t&&n(!0)},[t]),t?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${a?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(s.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(Kt,{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 Hl=()=>{const t=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||t.apply(console,r)};const a=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},n=r=>{var l;if((l=r.reason)!=null&&l.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=t,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function Jl(){var V,q;const[t,a]=A.useState("chart"),[n,r]=A.useState(!1),[l,o]=A.useState(!1),[c,i]=A.useState(!0),d=s.useEditorStore($=>$.showAIDialog),m=s.useDashboardStore($=>$.isVisualEditing),{setCardType:h}=s.useEditorActions(),u=s.useEditorStore($=>$.card.type);A.useEffect(()=>Hl(),[]);const p=()=>{console.log("Accept clicked - would save/apply current configuration")},f=()=>{console.log("Clear clicked - would reset all configurations")},j=()=>{console.log("Advanced mode toggled")},x=()=>{o(!0)},T=$=>{h($)},g=s.useEditorStore($=>$.frame),b=s.useEditorStore($=>$.card);s.useEditorStore($=>$.activeTabCardId),s.useEditorStore($=>$.actions.getAvailableFields);const{addCard:C,removeCard:O,updateCard:S,setActiveCard:E,updateFilters:N}=s.useEditorActions(),{columns:D=[],isLoading:w,error:M}=s.useColumns(),k=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),R=b,{getFieldsForContainer:I,setFieldsForContainer:v}=As(R),{activeField:y,handleDragStart:L,handleDragEnd:F}=Pl({activeCardId:g.activeCardId,sourceFields:D,getFieldsForContainer:I,setFieldsForContainer:v}),P=($,U)=>{U&&N($,U)},_=$=>{var U;S($,{config:{...(U=g.cards.find(H=>H.id===$))==null?void 0:U.config,filters:void 0}})},z=D,Q=$=>{if(!$)return 0;let U=$.conditions.length;return $.groups.forEach(H=>{U+=Q(H)}),U},Y=Q(((V=R==null?void 0:R.config)==null?void 0:V.filters)||null);return e.jsxs(s.DndContext,{sensors:k,collisionDetection:s.closestCenter,onDragStart:L,onDragEnd:F,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(ml,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(Nl,{selectedChart:u,onChartChange:T,groupByFields:I("groupBy"),pivotByFields:I("pivotBy"),metricsFields:I("metrics"),sortByFields:I("sortBy")}),e.jsx($l,{selectedChart:u,activeView:t,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onAccept:p,onClear:f,onAdvancedToggle:j,onFiltersClick:x,filterCount:Y,activeCard:R,dataSourceState:b.dataSource||s.EMPTY_DATA_SOURCE,columns:D,columnsLoading:w,columnsError:M,getFieldsForContainer:I,cards:g.cards,activeCardId:g.activeCardId,addCard:C,setActiveCard:E})]}),!c&&m&&e.jsx("div",{className:"fixed bottom-4 left-4 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"})})})]}),R&&e.jsx(zl,{cardId:R.id,filters:((q=R.config)==null?void 0:q.filters)||null,onFiltersChange:P,onClearFilters:_,availableFields:z,isOpen:l,onOpenChange:o}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Gl,{activeField:y||null})})]})}function Wl({authToken:t,onSave:a,onClose:n}){const r=A.useRef(null),l=s.useEditorStore(b=>b.showAIDialog),o=s.useEditorStore(b=>b.isDevMode),{setAuthToken:c}=s.useDashboardActions(),{setShowAIDialog:i,setOnSave:d,setOnClose:m}=s.useEditorActions(),{handleDragOver:h,handleDragEnd:u,handleDragStart:p,handleDragCancel:f,sensors:j}=za();A.useEffect(()=>{a&&d(a),n&&m(n)},[a,d,n,m]),A.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),A.useEffect(()=>{var b,C;l?((b=r.current)==null||b.resize(40),i(!0)):(i(!1),(C=r.current)==null||C.resize(0))},[l,i]);function x(b){b<1?i(!1):l||i(!0)}function T(){return e.jsxs(e.Fragment,{children:[e.jsx(Dt,{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(Xr,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(Ws,{})})]})]})}function g(){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(Jl,{})}),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:j,onDragStart:p,onDragEnd:u,onDragOver:h,onDragCancel:f,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:T()})}):g()})}function Yl(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:a}=s.useDashboardStore(c=>c.actions),n=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function l(c){t&&(r(t,c),a(!1))}function o(){a(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!n}),children:e.jsx(Wl,{onSave:l,onClose:o})})}function Kl(){const t=s.useEditorStore(o=>o.selectedDatabaseName),a=s.useEditorStore(o=>o.selectedTableName),n=s.useDashboardStore(o=>o.dashboard.filters)||[],{columns:r}=s.useEditorAside(),{assignFilter:l}=qt();return e.jsx(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(o=>{const c=n==null?void 0:n.find(i=>i.column===s.fmt(o.column_name)&&i.table===a&&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(bs,{column:o}),e.jsx("span",{children:o.column_name})]})},o.column_name)})})}function Ql(){s.useDashboardStore(a=>a.showFilters);const t=s.useDashboardStore(a=>a.actions.setShowFilters);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:e.jsx(Dt,{type:"filter",ColumnsComponent:()=>e.jsx(Kl,{})})})]})}function Xl(){const t=s.useDashboardStore(r=>r.dashboard.filters),a=s.useDashboardStore(r=>r.theme),n=t==null?void 0:t.filter(r=>r.hide);return n!=null&&n.length?e.jsx("div",{className:s.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":a==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":a==="dark"}),children:n==null?void 0:n.map(r=>e.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[e.jsx(s.FilterHeader,{filter:r}),e.jsx(s.FilterComponent,{filter:r})]},r.id))}):null}function Zl(){const t=s.useDashboardStore(r=>r.showFilters),a=s.useDashboardStore(r=>r.isVisualEditing),n=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":a,"flex grow overflow-auto":!a}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[n&&e.jsx(Xl,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Ql,{})})]})}function eo(){const t=s.useDashboardStore(l=>l.dashboard),a=s.useDashboardStore(l=>l.actions.setDashboard),n=s.useDashboardStore(l=>l.showDashboardJSON),r=s.useDashboardStore(l=>l.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!n}),children:[e.jsxs(s.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(s.de,{onChange:l=>{if(l)try{JSON.parse(l),a(JSON.parse(l))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(t,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function so({showControls:t=!1,showFooter:a=!0,...n}){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:n,children:[e.jsx(s.$e,{}),e.jsxs(s.UXProvider,{children:[e.jsx(eo,{}),e.jsxs("main",{className:"flex h-full flex-col",children:[t&&e.jsx(La,{}),e.jsxs(s.DashboardPanel,{...n,children:[e.jsx(Yl,{}),e.jsx(Zl,{})]})]})]})]})})}exports.DashboardPlus=so;exports.ResourceManagementPanel=Tt;exports.ScheduleDashboard=mt;exports.SelectComponent=ke;exports.cleanCard=ct;exports.downloadPdf=ut;exports.getDashbaordStateWithoutData=vs;
413
+ `;v(P)}function F(){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(Ka,{jsonString:JSON.stringify(m,null,2)})})}),m&&m.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 z(){return e.jsxs(s.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(s.ResizablePanel,{id:"1",order:1,defaultSize:a?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(Wa,{})}),a&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),a&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(s.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:[e.jsx("div",{id:"python-container",className:"relative flex w-[99%] pt-0",children:e.jsx(Ya,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function _(){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:k||w,onClick:()=>{I()},className:"h-8 shrink-0",size:"sm",children:[k||w?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(Mt,{sql:b==null?void 0:b.sql,error:y,onDebugWithAssistant:E}),e.jsx(s.EditorClearButton,{}),e.jsx(s.Toggle,{pressed:a,onPressedChange:P=>n(P),className:"",size:"sm",children:e.jsx(Ja,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:c,onClick:()=>{N(!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(s.EditorCancelButton,{}),e.jsx(s.EditorAcceptButton,{})]})]})}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:[z(),F()]}),_()]})}function Xa({data:t}){var c;const[a,n]=M.useState([]),l=Object.keys(t[0]).map(i=>({accessorKey:i,header:({column:d})=>{const m=d.getIsSorted();return e.jsx("div",{className:"flex gap-2",children:e.jsxs("div",{className:"flex cursor-pointer items-center",onClick:()=>d.toggleSorting(d.getIsSorted()==="asc"),children:[i,m==="asc"?e.jsx(s.TriangleUpIcon,{className:"ml-2 h-5 w-5"}):m==="desc"?e.jsx(s.TriangleDownIcon,{className:"ml-2 h-5 w-5"}):null]})})}})),o=s.useReactTable({data:t,columns:l,getCoreRowModel:s.getCoreRowModel(),getPaginationRowModel:s.getPaginationRowModel(),onSortingChange:n,getSortedRowModel:s.getSortedRowModel(),manualPagination:!0,state:{sorting:a}});return e.jsxs(s.CustomScrollArea,{className:"grow overflow-auto font-mono text-xs text-foreground/95",children:[e.jsxs("table",{className:"w-full",children:[e.jsx(s.TableHeader,{className:"sticky top-0 z-50 h-0 bg-muted",children:o.getHeaderGroups().map(i=>e.jsx(s.TableRow,{className:"",children:i.headers.map(d=>e.jsx(s.TableHead,{className:"h-11 font-semibold text-foreground",children:d.isPlaceholder?null:s.flexRender(d.column.columnDef.header,d.getContext())},d.id))},i.id))}),e.jsx(s.TableBody,{children:(c=o.getRowModel().rows)!=null&&c.length?o.getRowModel().rows.map(i=>e.jsx(s.TableRow,{className:"h-11 whitespace-nowrap py-2","data-state":i.getIsSelected()&&"selected",children:i.getVisibleCells().map(d=>e.jsx(s.TableCell,{className:"py-2",children:s.flexRender(d.column.columnDef.cell,d.getContext())},d.id))},i.id)):e.jsx(s.TableRow,{children:e.jsx(s.TableCell,{colSpan:l.length,className:"h-24 text-center",children:"No results."})})})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Za({card:t}){var v,N,O,C,D,b,k,w,L,T,R;const[a,n]=M.useState(!1),[r,l]=M.useState([]),{authToken:o}=s.useSemaphorContext(),c=s.getTokenParams(o==null?void 0:o.accessToken),i=s.useDashboardStore(A=>A.themeStyle),d={colors:((N=(v=i==null?void 0:i.chart)==null?void 0:v.dataset)==null?void 0:N.backgroundColor)||[]};(O=t.customCardPreferences)!=null&&O.inputData;const{getCard:m}=s.useCustomVisual(((C=t.customCardPreferences)==null?void 0:C.url)||""),h=((D=t.customCardPreferences)==null?void 0:D.visualType)||"single",u=s.useEditorStore(A=>A.frame),{setCustomCardPreferences:p}=s.useEditorActions(),{data:j}=s.useDashboardCardQuery(t),f=M.useCallback((A,I)=>{l(y=>({...y,[A]:I}))},[]);if(!((b=t.customCardPreferences)!=null&&b.componentName))return null;const x=m((k=t.customCardPreferences)==null?void 0:k.componentName);function S(A){n(A)}const g=Object.keys(((w=t.customCardPreferences)==null?void 0:w.dataInputCardIds)||{}).map(A=>{var E,F,z;const I=(F=(E=t.customCardPreferences)==null?void 0:E.dataInputCardIds)==null?void 0:F[A].cardId,y=(z=u==null?void 0:u.cards)==null?void 0:z.find(_=>_.id===I);return y||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:[x&&h==="single"&&e.jsx(x,{editing:!0,params:c,theme:d,settings:(L=t.customCardPreferences)==null?void 0:L.settings,onDataChange:f,data:(j==null?void 0:j.records)||[]}),x&&h==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((T=t.customCardPreferences)==null?void 0:T.dataInputCardIds)||{}).map(A=>{var E,F,z;const I=(F=(E=t.customCardPreferences)==null?void 0:E.dataInputCardIds)==null?void 0:F[A].cardId,y=(z=u==null?void 0:u.cards)==null?void 0:z.find(_=>_.id===I);if(y)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:S,onDataChange:f,dataInputIndex:A,card:y},y.id+A)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(x,{theme:d,onDataChange:f,settings:g.map(A=>{var I;return(I=A==null?void 0:A.customCardPreferences)==null?void 0:I.settings}),data:g.map(A=>A!=null&&A.id?r==null?void 0:r[A.id]:[])})})]})]},(R=t.customCardPreferences)==null?void 0:R.componentName)})}function Bt({className:t,...a}){var v;const n=s.useEditorStore(N=>N.card),r=s.isExplorerCard(n),l=((v=n.customCardPreferences)==null?void 0:v.showCardHeader)??!0,o=s.useEditorStore(N=>N.frame),c=s.useDashboardStore(N=>N.dashboard.filters);s.useEditorStore(N=>N.actions.setRunSql);const{updateFilter:i}=s.useDashboardActions(),d=c==null?void 0:c.find(N=>N.id===o.filterId),{data:m,isLoading:h,isFetching:u,errorMessage:p}=s.useDashboardCardQuery(n),{setCard:j}=s.useEditorActions(),{data:f}=s.useTopoJson(n),x=M.useMemo(()=>!n.id||!(m!=null&&m.records)?null:s.createChartConfig({card:n,data:m==null?void 0:m.records,cardType:n.type,queryConfig:n.queryConfig,customCfg:n.customCfg,preferences:n.preferences,topoJson:f}),[n.id,m==null?void 0:m.records,n.type,n.queryConfig,n.customCfg,n.preferences,f]);function S(N){return e.jsx(Za,{card:N})}function g(){if(m!=null&&m.records&&(m==null?void 0:m.records.length)===0&&!h&&!u)return p?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(!n.id)return null;if(n.type==="custom")return S(n);if(!["table","custom"].includes(n.type)&&x)return e.jsx(e.Fragment,{children:h||u?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:x})});if(n.type==="table"&&(m!=null&&m.records)&&(m==null?void 0:m.records.length)>0)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:n,data:m==null?void 0:m.records})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...a,children:[l&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{children:[e.jsx(s.Editable,{enabled:!0,text:n.title,onSave:N=>j({...n,title:N}),children:e.jsx("div",{className:"flex items-center gap-5",children:e.jsx(s.CardTitle,{className:"text-base",children:n.title||"Add title"})})},n.title),e.jsx(s.Editable,{enabled:!0,text:n.description||"",onSave:N=>j({...n,description:N}),children:e.jsx(s.CardDescription,{children:n.description||"Add description"})},n.description)]}),d&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Editable,{enabled:!0,className:"my-1",text:d.title||d.column,onSave:N=>i({...d,title:N}),children:e.jsx(s.Label,{children:d.title})}),e.jsx(s.FilterComponent,{filter:d})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:g()})]})}const ts=({language:t,value:a,onChange:n,readonly:r})=>e.jsx(s.Ft,{className:"h-full w-full overflow-hidden text-xs",theme:"default",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,lineHeight:16,renderLineHighlight:"none",readOnly:r},defaultLanguage:t,value:a,onChange:n}),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:a,mergedConfig:n,onConfigChange:r,onCodeChange:l})=>e.jsxs(s.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(s.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(s.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(s.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(s.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(s.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ts,{language:"json",value:n,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ts,{readonly:!0,language:"json",value:a,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ts,{language:"javascript",value:t,onChange:l})})]}),tr=({error:t,hasCardCustomConfig:a,onReset:n,onApply:r,onClose:l})=>e.jsxs(s.DialogFooter,{className:"flex items-center",children:[e.jsx(s.Label,{className:"mr-2 text-red-500",children:t}),e.jsx(s.Button,{disabled:!a,onClick:n,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:l,variant:"outline",children:"Close"})]});function nr(){const[t,a]=M.useState(!1),[n,r]=M.useState(""),[l,o]=M.useState(""),[c,i]=M.useState(""),[d,m]=M.useState(""),h=s.useEditorStore(C=>C.card),u=s.useEditorStore(C=>C.card.customCfg),p=u?JSON.stringify(u,null,2):"",{data:j}=s.useDashboardCardQuery(h),{data:f}=s.useTopoJson(h),{setCardCustomCfg:x,setCustomVisualCode:S}=s.useEditorActions(),g=C=>{var D,b;return JSON.stringify({...C,data:{...C.data,datasets:(b=(D=C.data)==null?void 0:D.datasets)==null?void 0:b.map(k=>({...k,data:[]}))}},null,2)},v=()=>{var D,b;if(!((D=j==null?void 0:j.records)!=null&&D.length))return;const C=s.createChartConfig({card:h,data:j.records,cardType:h.type,queryConfig:h.queryConfig,preferences:h.preferences,topoJson:f});if(C){r(g(C)),i(((b=h.preferences)==null?void 0:b.customVisualCode)||"");const k=s.merge(C,u);o(g(k))}},N=()=>{try{if(c&&S(c),l){const C=JSON.parse(l),D=s.getObjectDiff(JSON.parse(n),C);x(D),m("")}}catch{m("Invalid JSON configuration")}},O=Object.keys(u||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:a,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:v,className:O?"":"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.FallbackEditorCard,children:e.jsx(Bt,{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:!!u,onReset:()=>{o(n),x(null)},onApply:N,onClose:()=>a(!1)})]})]})}function Ye(t){const[a,n]=M.useState(null);return a}function Cs(){const{authToken:t}=s.useSemaphorContext(),{data:a,isLoading:n,isFetching:r,isError:l}=s.useQuery({queryKey:["plugins",t==null?void 0:t.accessToken],queryFn:()=>s.getPlugins(t==null?void 0:t.accessToken)});return{data:a,isLoading:n,isFetching:r,isError:l}}function ar({onChartTypeChange:t}){const[a,n]=M.useState([]),{setCardCustomCfg:r,setCardPreferences:l,setCardType:o,setCustomCardPreferences:c}=s.useEditorActions(),{data:i}=Cs();function d(m,h){r(null),l({}),o(m),h&&c({type:"component",visualType:"single",url:h.url,componentName:h.name,icon:h.icon}),t==null||t()}return M.useEffect(()=>{(async()=>{var h;if(i){const p=(await Promise.all((h=i==null?void 0:i.plugins)==null?void 0:h.map(async j=>(await s.loadManifest(j.value)).visuals.map(S=>({name:S.name,icon:S.icon,url:j.value}))))).flat();n(p)}})()},[i]),a.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:a.map((m,h)=>e.jsx(rr,{text:m.name,onClick:()=>d("custom",m),icon:m.icon},m.url+m.name+h))})]})}const rr=({text:t,icon:a,onClick:n})=>{const r=Ye(),l=t.charAt(0).toUpperCase();return e.jsx(s.IconButton,{onClick:n,tooltip:t,children:r?e.jsx(r,{className:"h-4 w-4"}):l})};function Ss(t){return Se({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm87.63,96H191.48A64.1,64.1,0,0,0,136,64.52V40.37A88.13,88.13,0,0,1,215.63,120ZM120,120H80.68A48.09,48.09,0,0,1,120,80.68Zm0,16v39.32A48.09,48.09,0,0,1,80.68,136Zm16,0h39.32A48.09,48.09,0,0,1,136,175.32Zm0-16V80.68A48.09,48.09,0,0,1,175.32,120ZM120,40.37V64.52A64.1,64.1,0,0,0,64.52,120H40.37A88.13,88.13,0,0,1,120,40.37ZM40.37,136H64.52A64.1,64.1,0,0,0,120,191.48v24.15A88.13,88.13,0,0,1,40.37,136ZM136,215.63V191.48A64.1,64.1,0,0,0,191.48,136h24.15A88.13,88.13,0,0,1,136,215.63Z"},child:[]}]})(t)}function lr(t){return Se({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M48,180c0,11,7.18,20,16,20a14.24,14.24,0,0,0,10.22-4.66A8,8,0,0,1,85.78,206.4,30.06,30.06,0,0,1,64,216c-17.65,0-32-16.15-32-36s14.35-36,32-36a30.06,30.06,0,0,1,21.78,9.6,8,8,0,0,1-11.56,11.06A14.24,14.24,0,0,0,64,160C55.18,160,48,169,48,180Zm79.6-8.69c-4-1.16-8.14-2.35-10.45-3.84-1.25-.81-1.23-1-1.12-1.9a4.57,4.57,0,0,1,2-3.67c4.6-3.12,15.34-1.73,19.82-.56A8,8,0,0,0,142,145.86c-2.12-.55-21-5.22-32.84,2.76a20.58,20.58,0,0,0-9,14.95c-2,15.88,13.65,20.41,23,23.11,12.06,3.49,13.12,4.92,12.78,7.59-.31,2.41-1.26,3.34-2.14,3.93-4.6,3.06-15.17,1.56-19.55.36A8,8,0,0,0,109.94,214a61.34,61.34,0,0,0,15.19,2c5.82,0,12.3-1,17.49-4.46a20.82,20.82,0,0,0,9.19-15.23C154,179,137.49,174.17,127.6,171.31Zm83.09-26.84a8,8,0,0,0-10.23,4.84L188,184.21l-12.47-34.9a8,8,0,0,0-15.07,5.38l20,56a8,8,0,0,0,15.07,0l20-56A8,8,0,0,0,210.69,144.47ZM216,88v24a8,8,0,0,1-16,0V96H152a8,8,0,0,1-8-8V40H56v72a8,8,0,0,1-16,0V40A16,16,0,0,1,56,24h96a8,8,0,0,1,5.66,2.34l56,56A8,8,0,0,1,216,88Zm-27.31-8L160,51.31V80Z"},child:[]}]})(t)}function ws(t){return Se({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M6 16m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"},child:[]},{tag:"path",attr:{d:"M16 19m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"},child:[]},{tag:"path",attr:{d:"M14.5 7.5m-4.5 0a4.5 4.5 0 1 0 9 0a4.5 4.5 0 1 0 -9 0"},child:[]}]})(t)}function Ts(t){return Se({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M4.387 3h15.226a1 1 0 0 1 .948 1.316l-5.105 15.316a2 2 0 0 1 -1.898 1.368h-3.116a2 2 0 0 1 -1.898 -1.368l-5.104 -15.316a1 1 0 0 1 .947 -1.316"},child:[]},{tag:"path",attr:{d:"M5 9h14"},child:[]},{tag:"path",attr:{d:"M7 15h10"},child:[]}]})(t)}function ks(t){return Se({attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"m2 19.99 7.5-7.51 4 4 7.09-7.97L22 9.92l-8.5 9.56-4-4-6 6.01-1.5-1.5zm1.5-4.5 6-6.01 4 4L22 3.92l-1.41-1.41-7.09 7.97-4-4L2 13.99l1.5 1.5z"},child:[]}]})(t)}function Ds(t){return Se({attr:{version:"1.2",baseProfile:"tiny",viewBox:"0 0 24 24"},child:[{tag:"path",attr:{d:"M4 18c-.552 0-1-.448-1-1v-6.382l-.553.276c-.495.248-1.095.046-1.342-.447-.247-.494-.046-1.094.448-1.342l2-1c.31-.155.678-.139.973.044.294.183.474.504.474.851v8c0 .552-.448 1-1 1zM13 18h-5c-.404 0-.769-.244-.924-.617-.155-.374-.069-.804.217-1.09l4-4c.254-.254.394-.591.394-.95 0-.358-.14-.695-.394-.949-.508-.508-1.39-.508-1.9.001-.253.252-.393.589-.393.948 0 .552-.448 1-1 1s-1-.448-1-1c0-.894.348-1.733.98-2.364 1.265-1.263 3.464-1.263 4.727.001.632.631.979 1.471.979 2.363 0 .893-.348 1.733-.979 2.364l-2.293 2.293h2.586c.552 0 1 .448 1 1s-.448 1-1 1zM20.955 12.377c.338-.457.545-1.016.545-1.627 0-1.517-1.234-2.75-2.75-2.75-1.031 0-1.966.569-2.44 1.484-.254.49-.063 1.094.428 1.348.49.254 1.094.062 1.348-.428.128-.249.383-.404.664-.404.414 0 .75.336.75.75s-.336.75-.75.75c-.552 0-1 .448-1 1s.448 1 1 1c.689 0 1.25.561 1.25 1.25s-.561 1.25-1.25 1.25-1.25-.561-1.25-1.25c0-.552-.448-1-1-1s-1 .448-1 1c0 1.792 1.458 3.25 3.25 3.25s3.25-1.458 3.25-3.25c0-.939-.406-1.779-1.045-2.373z"},child:[]}]})(t)}function Ft({onChartTypeChange:t,iconClassName:a}){const{setCardType:n,setCardPreferences:r,setIsDevMode:l}=s.useEditorStore(h=>h.actions),{setCardCustomCfg:o,setCustomCardPreferences:c,setQueryConfig:i}=s.useEditorActions();function d(h,u){o(null),r({}),n(h),["custom","text","map"].includes(h)&&(l(!0),i(void 0)),t==null||t()}const m=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(s.IconButton,{openDelay:m,tooltip:"Table",onClick:()=>d("table"),className:"h-10 p-4",children:e.jsx(Je,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Bar Chart",onClick:()=>d("bar"),className:"h-10 p-4",children:e.jsx($e,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Line Chart",onClick:()=>d("line"),className:"h-10 p-4",children:e.jsx(Ge,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Stacked Bar Chart",onClick:()=>d("stackedBar"),className:"h-10 p-4",children:e.jsx(ms,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Stacked Line Chart",onClick:()=>d("stackedLine"),className:"h-10 p-4",children:e.jsx(ks,{className:s.cn("size-5",a),strokeWidth:0})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Scatter Chart",onClick:()=>d("scatter"),className:"h-10 p-4",children:e.jsx(xs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Bubble Chart",onClick:()=>d("bubble"),className:"h-10 p-4",children:e.jsx(ws,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Pie Chart",onClick:()=>d("pie"),className:"h-10 p-4",children:e.jsx(He,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Doughnut Chart",onClick:()=>d("doughnut"),className:"h-10 p-4",children:e.jsx(ps,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Funnel Chart",onClick:()=>d("funnel"),className:"h-10 p-4",children:e.jsx(Ts,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Radar Chart",onClick:()=>d("radar"),className:"h-10 p-4",children:e.jsx(js,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Polar Area Chart",onClick:()=>d("polarArea"),className:"h-10 p-4",children:e.jsx(Ss,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Tornado Chart",onClick:()=>d("tornado"),className:"h-10 p-4",children:e.jsx(ys,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Range Chart",onClick:()=>d("range"),className:"h-10 p-4",children:e.jsx(hs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"KPI",onClick:()=>d("kpi"),className:"h-10 p-4",children:e.jsx(Ds,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Text",onClick:()=>d("text"),className:"h-10 p-4",children:e.jsx(Zs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Map",onClick:()=>d("map"),className:"h-10 p-4",children:e.jsx(gs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Custom",onClick:()=>d("custom"),className:"h-10 p-4",children:e.jsx(Ae,{className:s.cn("size-5",a)})})]})}function or({chartType:t,className:a,customIcon:n,componentName:r}){const l=Ye();switch(t){case"bar":return e.jsx($e,{className:a});case"line":return e.jsx(Ge,{className:a});case"pie":return e.jsx(He,{className:a});case"radar":return e.jsx(js,{className:a});case"scatter":return e.jsx(xs,{className:a});case"bubble":return e.jsx(ws,{className:a});case"doughnut":return e.jsx(ps,{className:a});case"stackedBar":return e.jsx(ms,{className:a});case"stackedLine":return e.jsx(ks,{className:a});case"polarArea":return e.jsx(Ss,{className:a});case"funnel":return e.jsx(Ts,{className:a});case"tornado":case"pyramid":return e.jsx(ys,{className:a});case"range":return e.jsx(hs,{className:a});case"kpi":return e.jsx(Ds,{className:a});case"text":return e.jsx(it,{className:a});case"map":return e.jsx(gs,{className:a});case"custom":return n&&l?e.jsx(l,{className:a}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(Ae,{className:a});default:return e.jsx(Je,{className:a})}}function zt({variant:t="ghost"}){var o,c;const[a,n]=M.useState(!1),r=s.useEditorStore(i=>i.card),l=r.type;return s.useDashboardStore(i=>i.isVisualEditing),e.jsxs(s.Popover,{open:a,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(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:"w-72 p-1",children:[e.jsx(Ft,{onChartTypeChange:()=>n(!1)}),e.jsx(ar,{onChartTypeChange:()=>n(!1)})]})]})}const Oe="focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0";function Js(t,a){var r,l,o;const n=s.getNumberAxis(t,{});return["pie","doughnut","polarArea","funnel"].includes(a)?"category":((o=(l=(r=t==null?void 0:t.chartOptions)==null?void 0:r.scales)==null?void 0:l[n])==null?void 0:o.type)||"linear"}function ir(){var E,F,z,_,P,Q;const[t,a]=M.useState(!1),n=s.useEditorStore(Y=>{var V;return(V=Y.card)==null?void 0:V.preferences}),r=s.useEditorStore(Y=>{var V;return(V=Y.card)==null?void 0:V.type}),l=s.getNumberAxis(n,{}),[o,c]=M.useState(Js(n,r)),[i,d]=M.useState(((z=(F=(E=n==null?void 0:n.chartOptions)==null?void 0:E.scales)==null?void 0:F[l])==null?void 0:z.min)||""),[m,h]=M.useState(((Q=(P=(_=n==null?void 0:n.chartOptions)==null?void 0:_.scales)==null?void 0:P[l])==null?void 0:Q.max)||""),[u,p]=M.useState(i||m?"custom":"auto"),[j,f]=M.useState(""),[x,S]=M.useState(0),[g,v]=M.useState(""),[N,O]=M.useState(""),[C,D]=M.useState(""),b=s.useEditorStore(Y=>Y.actions.setCardPreferences),{updateCardInFrame:k}=s.useEditorActions(),w=s.useEditorStore(Y=>Y.card),L=["pie","doughnut","polarArea","funnel"].includes(r);M.useEffect(()=>{var Y,V,q,$,U,H,W,G,Z,se,ne,ee,ae,J;c(Js(n,r)),d(((q=(V=(Y=n==null?void 0:n.chartOptions)==null?void 0:Y.scales)==null?void 0:V[l])==null?void 0:q.min)===0?0:""),h(((H=(U=($=n==null?void 0:n.chartOptions)==null?void 0:$.scales)==null?void 0:U[l])==null?void 0:H.max)||""),f(((se=(Z=(G=(W=n==null?void 0:n.chartOptions)==null?void 0:W.scales)==null?void 0:G[l])==null?void 0:Z.ticks)==null?void 0:se.stepSize)||""),S(((ne=n==null?void 0:n.numberAxisFormat)==null?void 0:ne.decimalPlaces)||0),v(((ee=n==null?void 0:n.numberAxisFormat)==null?void 0:ee.suffix)||""),O(((ae=n==null?void 0:n.numberAxisFormat)==null?void 0:ae.currency)||""),D(((J=n==null?void 0:n.numberAxisFormat)==null?void 0:J.locale)||"")},[t,n,l,r]);function T(Y,V){return V===""||/^[0-9\b]+$/.test(V)?Number(V):Number(Y)}function R(){const Y=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(V=>V.currency))];return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-6 items-center gap-2",children:[e.jsx(s.Label,{className:"col-span-2 hover:cursor-pointer hover:underline",htmlFor:"currency",children:e.jsx("a",{target:"_blank",href:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat",children:"Currency"})}),e.jsxs(s.Select,{value:N||"none",onValueChange:V=>O(V==="none"?"":V),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 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"}),Y.map(V=>e.jsx(s.SelectItem,{value:V,children:V},V))]})})]}),e.jsxs(s.Select,{value:C,onValueChange:V=>D(V),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 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:"Locale"}),s.LOCALE_CURRENCY_PAIRS.map(V=>e.jsx(s.SelectItem,{value:V.locale,children:V.locale},V.locale))]})})]})]}),e.jsxs("div",{className:"grid grid-cols-9 items-center gap-2",children:[e.jsx(s.Label,{className:"col-span-3",htmlFor:"format",children:"Decimals"}),e.jsx(s.Input,{value:x,onChange:V=>S(Number(V.target.value)),id:"format",className:`col-span-6 h-8 w-full tracking-wide ${Oe}`})]})]})}function A(){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-4 space-y-2",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the scale for number axis"})}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 items-center gap-2",children:[e.jsx(s.Label,{htmlFor:"scale",children:"Type"}),e.jsxs(s.Select,{disabled:L,value:o,onValueChange:Y=>c(Y),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{id:"type",children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Option"}),e.jsx(s.SelectItem,{value:"linear",children:"Linear"}),e.jsx(s.SelectItem,{value:"logarithmic",children:"Logarithmic"}),e.jsx(s.SelectItem,{value:"category",children:"Category"})]})})]})]}),o=="linear"&&e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2 py-1",children:[e.jsx(s.Label,{htmlFor:"scale-option",children:"Setup"}),e.jsxs(s.RadioGroup,{disabled:L,id:"scale-option",value:u,onValueChange:Y=>p(Y),className:"col-span-2 flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"auto",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Auto"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"custom",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Custom"})]})]})]}),u==="custom"&&o=="linear"&&I()]})}function I(){return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(s.Label,{htmlFor:"range",children:"Range"}),e.jsx(s.Input,{id:"min",value:i,onChange:Y=>d(V=>T(V,Y.target.value)),className:`col-span-1 h-8 w-full ${Oe}`}),e.jsx(s.Input,{value:m,onChange:Y=>h(V=>T(V,Y.target.value)),id:"max",className:`col-span-1 h-8 w-full ${Oe}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(s.Label,{htmlFor:"step-size",children:"Step Size"}),e.jsx(s.Input,{value:j,onChange:Y=>f(V=>T(V,Y.target.value)),id:"step-size",className:`col-span-1 h-8 w-full ${Oe}`})]})]})}function y(){var $;let Y={};u==="custom"&&(Y={min:i,max:m,ticks:{stepSize:j}});const V={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,scales:{...($=n==null?void 0:n.chartOptions)==null?void 0:$.scales,[l]:{type:o,...o==="linear"?Y:{}}}},numberAxisFormat:{decimalPlaces:x,suffix:g,currency:N,locale:C}};console.log(V),b(V);const q={...w,preferences:V};k(q)}return e.jsxs(s.Popover,{onOpenChange:Y=>a(Y),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Format Number",children:e.jsx(En,{className:"size-4"})})}),e.jsx(s.PopoverContentCustom,{align:"end",className:"max-w-65 z-[51]",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Format Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the format for number axis"})]}),e.jsxs("div",{className:"grid gap-2",children:[R(),A(),e.jsx(s.SelectSeparator,{}),e.jsx("div",{className:"grid grid-cols-3",children:e.jsx(s.Button,{onClick:y,variant:"secondary",className:"col-span-1 col-start-3 h-8 w-full",children:"Apply"})})]})]})})]})}function cr(){const t=s.useEditorStore(i=>{var d,m,h,u;return(u=(h=(m=(d=i.card.preferences)==null?void 0:d.chartOptions)==null?void 0:m.plugins)==null?void 0:h.legend)==null?void 0:u.position}),a=s.useEditorStore(i=>{var d,m,h,u;return(u=(h=(m=(d=i.card.preferences)==null?void 0:d.chartOptions)==null?void 0:m.plugins)==null?void 0:h.legend)==null?void 0:u.align}),n=s.useEditorStore(i=>{var d,m,h,u;return(u=(h=(m=(d=i.card.preferences)==null?void 0:d.chartOptions)==null?void 0:m.plugins)==null?void 0:h.legend)==null?void 0:u.display}),{setLegendOptions:r}=s.useEditorActions(),l=i=>{r({display:i,position:t,align:a})},o=i=>{r({display:n,position:i,align:a})},c=i=>{r({display:n,position:t,align:i})};return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Legend Settings",children:e.jsx(_n,{className:"size-4"})})}),e.jsx(s.PopoverContentCustom,{align:"end",className:"z-[51] w-72",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Legend Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the legend options for the chart."})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"displayLegend",children:"Display"}),e.jsx("div",{className:"col-span-2 flex h-8 items-center",children:e.jsx(s.SmallSwitch,{checked:n,onCheckedChange:l,id:"displayLegend"})})]}),n&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"position",children:"Position"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(s.IconButton,{tooltip:"Top",onClick:()=>o("top"),children:e.jsx(s.ArrowUp,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Left",onClick:()=>o("left"),children:e.jsx(xn,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Bottom",onClick:()=>o("bottom"),children:e.jsx(s.ArrowDown,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Right",onClick:()=>o("right"),children:e.jsx(pn,{className:"size-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"align",children:"Align"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(s.IconButton,{tooltip:"Start",onClick:()=>c("start"),children:e.jsx(cn,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Center",onClick:()=>c("center"),children:e.jsx(on,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"End",onClick:()=>c("end"),children:e.jsx(dn,{className:"size-4"})})]})]})]})]})]})})]})}function dr(){const t=s.useEditorStore(o=>{var c,i;return(i=(c=o.card.preferences)==null?void 0:c.chartOptions)==null?void 0:i.indexAxis}),a=s.useEditorStore(o=>o.card.type),{setChartOrientation:n}=s.useEditorStore(o=>o.actions);function r(){return e.jsx(s.IconButton,{onClick:()=>{n(t==="x"||t===void 0?"y":"x")},tooltip:"Chart Orientation",children:t==="x"||t===void 0?e.jsx(_s,{className:"size-4"}):e.jsx(Ps,{className:"size-4"})})}function l(){return e.jsx(s.IconButton,{onClick:()=>{n(t==="y"||t===void 0?"x":"y")},tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(_s,{className:"size-4"}):e.jsx(Ps,{className:"size-4"})})}return e.jsx(e.Fragment,{children:a==="funnel"?l():r()})}function Pt(){const t=s.useEditorStore(c=>c.card),a=s.useEditorStore(c=>c.isShowingVisual),n=s.useEditorStore(c=>{var i,d;return(d=(i=c.card)==null?void 0:i.preferences)==null?void 0:d.chartOptions}),r=s.getChartGridStyle(n),{setChartGrid:l}=s.useEditorActions();function o(){const c=["xy","none","x","y"],d=(c.indexOf(r)+1)%c.length;l(c[d])}return a?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(dr,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsxs(e.Fragment,{children:[e.jsx(ir,{}),e.jsx(cr,{})]}),!["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(Fn,{className:"size-4"}),r==="x"&&e.jsx(Tn,{className:"size-4"}),r==="y"&&e.jsx(Xn,{className:"size-4"}),r==="none"&&e.jsx(na,{className:"size-4"})]})]}):null}function ur(){const t=s.useEditorStore(f=>f.frame),a=s.useEditorStore(f=>f.card),{setFrame:n,setActiveTabCardId:r,setCard:l,updateCardInFrame:o}=s.useEditorActions(),c=(f,x)=>{f.dataTransfer.setData("tabIndex",x.toString())},i=f=>{f.preventDefault()},d=(f,x)=>{const S=f.dataTransfer.getData("tabIndex");if(S===x.toString())return;const g=Array.from(t.cards),[v]=g.splice(parseInt(S),1);g.splice(x,0,v),n({...t,cards:g})};function m(f){const x=t.cards.filter(v=>v.id!==f),S=x[0],g={...t,cards:x,activeCardId:S.id};n(g),r(S.id),l(S)}function h(f,x){const S={...t,cards:[...t.cards,x],activeCardId:f.id};n(S),r(x.id)}function u(){const f={...a,id:s.v4(),title:`${a.title} Copy`,tabTitle:`${a.tabTitle||a.title} Copy`};h(a,f)}function p(f){const x={dataSource:f.dataSource,connectionId:f.connectionId,lastSelectedDatabase:f.lastSelectedDatabase,lastSelectedSchema:f.lastSelectedSchema,lastSelectedTable:f.lastSelectedTable,lastSelectedDatamodelId:f.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};h(f,x)}function j(f,x){return f.cards.length===1&&(x.displayTab===!0||x.displayTab===void 0)||f.activeCardId!==x.id&&(x.displayTab===!0||x.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const S=x.displayTab===void 0?!1:!x.displayTab;l({...x,displayTab:S}),o({...x,displayTab:S})},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(In,{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((f,x)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:S=>c(S,x),onDragOver:i,onDrop:S=>d(S,x),className:"",value:f.id,children:[j(t,f),e.jsx(s.Editable,{enabled:t.activeCardId===f.id,text:f.tabTitle||f.title,onSave:S=>{l({...a,tabTitle:S}),o({...a,tabTitle:S})},children:f.tabTitle||f.title},f.id),t.activeCardId===f.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>m(f.id)})]},f.id)),e.jsx(s.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>p(a),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:u,children:e.jsx(Dn,{className:"h-4 w-4"})})]})})}function _t(){const t=s.useEditorStore(x=>x.frame),a=s.useEditorStore(x=>x.card),n=s.useEditorStore(x=>x.isSqlRunning),r=s.useEditorStore(x=>x.isDevMode),{setFrame:l,setActiveTabCardId:o,setCard:c,setIsDevMode:i,setRunSql:d}=s.useEditorActions(),{data:m,isLoading:h,isFetching:u}=s.useDashboardCardQuery(a);function p(x){const S=t.cards.find(g=>g.id===x);if(S!=null&&S.sql){r||i(!0),o(x);return}if(S!=null&&S.queryConfig){r&&i(!1),j(x),o(x);return}r||j(x),o(x)}function j(x){const S={...t,cards:t.cards.map(v=>v.id===a.id?a:v),activeCardId:x};l(S);const g=S.cards.find(v=>v.id===x);g.sql&&d(!0),c(g)}function f(){return a.type==="kpi"?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.KPICard,{card:a,data:m==null?void 0:m.records,isPending:h})})}):a.type==="text"?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:n,card:a,data:m==null?void 0:m.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackEditorCard,children:e.jsx(Bt,{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:f()},x.id)),e.jsx(ur,{})]})}function Re({children:t}){s.useEditorStore(v=>v.frame);const a=s.useEditorStore(v=>v.card),n=s.useEditorStore(v=>v.isDevMode),r=s.useEditorStore(v=>v.isShowingVisual),l=s.useDashboardStore(v=>v.isVisualEditing),o=s.useEditorStore(v=>v.pythonStdOut);s.useEditorStore(v=>v.actions.setRunSql);const{setFrame:c,setCard:i,setActiveTabCardId:d,runAssistant:m,setIsDevMode:h}=s.useEditorActions(),{data:u,isLoading:p,isFetching:j,errorMessage:f}=s.useDashboardCardQuery(a);function x(){const v=JSON.stringify(u==null?void 0:u.records,null,2),N=new Blob([v],{type:"application/json"}),O=URL.createObjectURL(N),C=document.createElement("a");C.href=O,C.download=`${a.title}.json`,C.click()}function S(){const N=[Object.keys(u==null?void 0:u.records.reduce((b,k)=>({...b,...k}),{})).join(","),...((u==null?void 0:u.records)||[]).map(b=>Object.values(b).join(","))].join(`
414
+ `),O=new Blob([N],{type:"text/csv"}),C=URL.createObjectURL(O),D=document.createElement("a");D.href=C,D.download=`${a.title}.csv`,D.click()}function g(){const v=`Can you get the documentation for ${a.type} chart?`;m(v)}return a?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[(p||j)&&e.jsx("div",{className:"absolute bottom-0 left-0 right-0 top-0 z-50 m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),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(zt,{}),l&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:g,children:e.jsx(yn,{className:"size-4"})}),!["table","custom"].includes(a.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:S,children:e.jsx(lr,{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:x,children:e.jsx(Mn,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(u==null?void 0:u.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(Pt,{})]}),n&&e.jsx(hr,{})]}),r?e.jsx(_t,{}):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:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:[(u==null?void 0:u.records)&&(u==null?void 0:u.records.length)>0&&e.jsx(Xa,{data:(u==null?void 0:u.records)||[]}),f&&e.jsx(It,{error:f})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function mr(){const t=s.useEditorStore(n=>n.pythonStdOut);if(!t)return null;const a=t.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col border-r",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center border-b bg-muted px-3 font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(s.ScrollArea,{className:"overflow-y-auto px-2 pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:a}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function hr(){const t=s.useEditorStore(n=>n.isShowingVisual),a=s.useEditorStore(n=>n.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(s.SmallSwitch,{checked:t,onCheckedChange:()=>a(!t),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function xr(){var x,S;const t=s.useEditorStore(g=>g.card.customCardPreferences),{data:a}=Cs(),n=(a==null?void 0:a.plugins)||[],r=s.useEditorStore(g=>g.card),l=s.useEditorStore(g=>g.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)||""),m=(x=d==null?void 0:d.visuals)==null?void 0:x.find(g=>g.name===(t==null?void 0:t.componentName));function h(g,v){if(!t)return;const O={...(t==null?void 0:t.dataInputCardIds)||{},[g]:{cardId:v,hookRef:null}};c({...t,dataInputCardIds:O})}function u(g){var N,O;const v=(N=l==null?void 0:l.cards)==null?void 0:N.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:(O=g==null?void 0:g.dataInputs)==null?void 0:O.map((C,D)=>{var b,k;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:v||[],value:((k=(b=t==null?void 0:t.dataInputCardIds)==null?void 0:b[D])==null?void 0:k.cardId)||"",onValueChange:w=>h(D,w)})]},D+Math.random())})})}function p(g,v,N=[],O=""){var C,D;return t?g==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((C=t==null?void 0:t.settings)==null?void 0:C[v])||O,onChange:b=>{c({...t,settings:{...t==null?void 0:t.settings,[v]:b.target.value}})}},v):g==="select"?e.jsx(ce,{className:"h-8 w-full",label:"",options:N,value:((D=t==null?void 0:t.settings)==null?void 0:D[v])||O,onValueChange:b=>{c({...t,settings:{...t==null?void 0:t.settings,[v]:b}})}}):null:null}function j(g){const v=Object.entries((g==null?void 0:g.settings)||{});return e.jsx("div",{className:"space-y-3",children:v.map(([N,O])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:O.title}),p(O.ui,N,O.options,O.defaultValue)]},N))})}function f(g){t&&c({...t,visualType:g,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(jn,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(t==null?void 0:t.url)||"",onValueChange:g=>c({...t||{url:"",componentName:""},url:g})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:o,onValueChange:f,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(kn,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(i==null?void 0:i.filter(g=>g.type===o).map(g=>({value:g.name,label:g.name})))||[],value:t.componentName,onValueChange:g=>{console.log("changing value",g),c({...t,componentName:g})}})})]})})]}),((S=r==null?void 0:r.customCardPreferences)==null?void 0:S.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{children:[m&&m.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:u(m)})]}),m&&m.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:j(m)})})]})]})]})}function we(){const[t,a]=M.useState([]),n=s.useEditorStore(m=>m.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:l}=s.useEditorStore(m=>m.actions),o=s.useEditorStore(m=>m.queryResultColumns);s.useEditorStore(m=>{var h;return(h=m.card.preferences)==null?void 0:h.filterOnClickColumnIndex}),M.useEffect(()=>{o&&a(new Array(o.length).fill(!1))},[o]);function c(m,h){var u,p;h?n!=null&&n.onClickFilter&&((u=n==null?void 0:n.onClickFilter)==null?void 0:u.length)>0?l({...n,onClickFilter:[...n.onClickFilter,{columnIndex:m,expression:""}]}):l({...n,onClickFilter:[{columnIndex:m,expression:""}]}):(l({...n,onClickFilter:(p=n==null?void 0:n.onClickFilter)==null?void 0:p.filter(j=>j.columnIndex!==m)}),a(j=>{const f=[...j];return f[m]=!1,f}))}function i(m,h){var p;const u=(p=n==null?void 0:n.onClickFilter)==null?void 0:p.map(j=>j.columnIndex===m?{...j,expression:h.target.value}:j);l({...n,onClickFilter:u})}function d(m){var h,u,p,j;if(t!=null&&t[m]||(u=(h=n==null?void 0:n.onClickFilter)==null?void 0:h.find(f=>f.columnIndex===m))!=null&&u.expression)return e.jsx(s.Input,{value:(j=(p=n==null?void 0:n.onClickFilter)==null?void 0:p.find(f=>f.columnIndex===m))==null?void 0:j.expression,onChange:f=>i(m,f),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.jsxs("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:[e.jsx(s.Label,{children:"On Click"}),o==null?void 0:o.map((m,h)=>{var u,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:!!((u=n==null?void 0:n.onClickFilter)!=null&&u.find(j=>j.columnIndex===h)),onCheckedChange:j=>c(h,j)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:m}),e.jsx("div",{className:"flex items-center gap-2",children:((p=n==null?void 0:n.onClickFilter)==null?void 0:p.find(j=>j.columnIndex===h))&&e.jsx(s.Pencil,{onClick:()=>{a(j=>{const f=[...j];return f[h]=!j[h],f})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(h)]})},m)})]})}function pr({idx:t}){var i;const a=s.useEditorStore(d=>{var m;return(m=d.card)==null?void 0:m.preferences}),n=s.useEditorStore(d=>{var m;return(m=d.card.preferences)==null?void 0:m.datasetOptions}),r=s.useEditorStore(d=>d.actions.setCardPreferences),l=(i=a==null?void 0:a.chartOptions)==null?void 0:i.indexAxis,o=n==null?void 0:n.find(d=>d.idx===t);function c(d,m){(d==="end"||d==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const h={display:d!=="none",align:d,anchor:d,clamp:!0};if(!o)r({...a,datasetOptions:[...n||[],{idx:m,datalabels:h}]});else{const u={...o};u.datalabels=h;const p=n==null?void 0:n.map(j=>j.idx===m?u:j);r({...a,datasetOptions:p})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(lt,{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(Vn,{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(qn,{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(Un,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function fr(){const t=s.useEditorStore(o=>o.card),{data:a}=s.useDashboardCardQuery(t),{keys:n}=s.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(o=>!s.METADATA_KEYS.includes(o));let l=r;if(["stackedBar","stackedLine"].includes(t.type)){const o=s.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:c}=s.getKeys(o);l=c.slice(1)}return{transformedMetricKeys:l,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}function Es({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function Vt(){const t=s.useEditorStore(d=>d.card),a=s.useEditorStore(d=>{var m,h,u;return(u=(h=(m=d==null?void 0:d.card)==null?void 0:m.preferences)==null?void 0:h.chartOptions)==null?void 0:u.indexAxis}),{data:n}=s.useDashboardCardQuery(t),r=a==="y"?"Metric":"Dimension",l=a==="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:Ut(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,m)=>e.jsx(qt,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:d,idx:m},d))})]})]})}function Ut(t,a=30){return t.length>a?t.slice(0,a)+"...":t}function qt({col:t,idx:a,className:n,iconClassName:r,children:l}){const o=s.useEditorStore(h=>{var u;return(u=h.card)==null?void 0:u.preferences}),c=s.useEditorStore(h=>{var u,p;return(p=(u=h.card)==null?void 0:u.preferences)==null?void 0:p.datasetOptions}),i=c==null?void 0:c.find(h=>h.idx===a),{setCardPreferences:d}=s.useEditorStore(h=>h.actions);function m(h){if(!i)d({...o,datasetOptions:[...c||[],{idx:a,type:h==="area"?"line":h,fill:h==="area"?"origin":""}]});else{const u={...i};u.type=h==="area"?"line":h,u.fill=h==="area"?"origin":"";const p=c==null?void 0:c.map(j=>j.idx===a?u:j);d({...o,datasetOptions:p})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[l||e.jsx(Es,{className:"max-w-[100px]",title:t,children:Ut(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($e,{onClick:()=>m("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(Ge,{onClick:()=>m("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(et,{onClick:()=>m("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(pr,{idx:a})]})]})}function $t(){const t=s.useEditorStore(j=>j.selectedConnectionId),a=s.useEditorStore(j=>j.selectedDatamodelId),n=s.useEditorStore(j=>j.selectedDatabaseName),r=s.useEditorStore(j=>j.selectedSchemaName),l=s.useEditorStore(j=>j.selectedTableName),o=s.useDashboardStore(j=>j.dashboard.filters)||[],c=s.useDashboardStore(j=>j.actions.addFilter),i=s.useDashboardStore(j=>j.actions.removeFilter),{removeFilterValues:d}=s.useDashboardActions(),{modelItems:m,tableName:h,connectionType:u}=s.useEditorAside();function p(j,f="dashboard"){var b;const x=s.fmt(j.column_name),S=s.fmt(n||""),g=s.fmt(r||""),v=s.fmt(h);let N=s.getQualifiedTableName({schemaName:g,tableName:v,connectionType:u,databaseName:S}),O=`${N}.${x}`;const C=(b=m==null?void 0:m.find(k=>k.id===a))==null?void 0:b.name;a&&a!=="none"&&(O=`${s.DATAMODEL_NAMESPCACE}.${C}.${x}`,N=`${s.DATAMODEL_NAMESPCACE}.${C}`);const D=o==null?void 0:o.find(k=>k.column===O&&k.table===v&&(k.database===S||k.database===n));if(D)d(D.id),i(D.id);else{const k=s.v4();return h==="api"&&t?(c({location:f,id:k,column:O,title:j.column_name,dataType:j.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(j.data_type,N,x)}),k):(c({id:k,location:f,column:O,title:j.column_name,dataType:j.data_type,table:l||"",database:n||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(j.data_type,N,x)}),k)}}return{assignFilter:p}}function Ee(){const t=s.useDashboardStore(i=>i.dashboard.filters),a=s.useEditorStore(i=>i.frame),{setFrame:n}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=$t();function o(i){const d=l(i,"frame");n({...a,filterId:d})}const c=t==null?void 0:t.find(i=>i.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(gr,{onSelect:o,columns:r}),c&&e.jsx(s.FilterHeader,{filter:c})]})}function gr({columns:t,onSelect:a}){var c;const[n,r]=ye.useState(!1),[l,o]=ye.useState("");return e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[l?(c=t.find(i=>i.column_name===l))==null?void 0:c.column_name:"Select Column...",e.jsx(s.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No framework found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(i=>e.jsxs(s.CommandItem,{value:i.column_name,onSelect:d=>{const m=d===l?"":d;o(m),r(!1),m&&a(i)},children:[i.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",l===i.column_name?"opacity-100":"opacity-0")})]},i.column_name))})]})]})})]})}function 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:a=>a.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(Vt,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(we,{}),e.jsx(Ee,{})]})]})]})})}function Ke(){const t=s.useEditorStore(i=>i.card.type),a=s.useEditorStore(i=>i.isDevMode),n=s.useEditorStore(i=>i.card.preferences),{setCardPreferences:r}=s.useEditorStore(i=>i.actions);function l(i){var h;const d={datalabels:{display:i!=="none",align:i,anchor:i,clamp:!0}},m={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(h=n==null?void 0:n.chartOptions)==null?void 0:h.plugins,...d}}};r(m)}function o(){var i,d,m;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((m=(d=(i=n==null?void 0:n.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:m.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,m;return e.jsx("div",{children:e.jsxs(s.Select,{value:((m=(d=(i=n==null?void 0:n.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:m.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(s.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:a?o():c()})}function yr({cardType:t}){function a(n){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:n==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),n==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:o=>o.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsx(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:a(t)})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"px-2",children:e.jsx(Ke,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(we,{}),e.jsx(Ee,{})]})]})]})})}const vr={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},br={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function Nr(){const t=s.useEditorStore(a=>a.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:Cr(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ke,{}),e.jsx(we,{}),e.jsx(Ee,{})]})]})}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(br,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(){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(s.FormatNumberSetting,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function ns({children:t,summary:a,open:n,className:r}){return e.jsxs("details",{open:n,className:s.cn("space-y-4 [&_summary>svg]:open:-rotate-180",r),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(s.Label,{children:a}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const wr=[{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 Dr(){var d,m,h,u,p,j,f,x,S,g,v,N,O,C,D,b,k,w;const t=s.useEditorStore(L=>L.card),a=(m=(d=t==null?void 0:t.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:m.topoJsonUrl,[n,r]=M.useState(((u=(h=t==null?void 0:t.preferences)==null?void 0:h.mapVisualOptions)==null?void 0:u.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:o}=s.useTopoJson(t),c=Object.keys((o==null?void 0:o.objects)||{}).map(L=>({label:L,value:L}))||[],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(ns,{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(ns,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(ce,{className:"h-9",options:i,onValueChange:L=>{console.log("value",L),l({...t.preferences,mapVisualOptions:{topoJsonUrl:L}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(s.Input,{onChange:L=>{r(L.target.value)},onBlur:()=>{var L;console.log("onBlur",n),l({...t.preferences,mapVisualOptions:{...(L=t.preferences)==null?void 0:L.mapVisualOptions,customTopoJsonUrl:n}})},value:n,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),o&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(ce,{className:"h-9",options:c,value:((j=(p=t.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:j.objectKey)||"",label:"Map Object",onValueChange:L=>{var T;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,objectKey:L}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(ce,{className:"h-9",options:wr,value:((x=(f=t.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:x.projection)||"",label:"Projection",onValueChange:L=>{var T;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,projection:L}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(ce,{className:"h-9",options:kr,value:((g=(S=t.preferences)==null?void 0:S.mapVisualOptions)==null?void 0:g.colorScale)||"",label:"Select Color Scale",onValueChange:L=>{var T;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,colorScale:L}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(ns,{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:((N=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:N.projectionScale)||1,onChange:L=>{var T;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,projectionScale:Number(L.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=(O=t.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:C.projectionOffset)==null?void 0:D[0])||0,onChange:L=>{var T,R,A,I;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,projectionOffset:[Number(L.target.value),((I=(A=(R=t.preferences)==null?void 0:R.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:I[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((w=(k=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:k.projectionOffset)==null?void 0:w[1])||0,onChange:L=>{var T,R,A,I;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,projectionOffset:[((I=(A=(R=t.preferences)==null?void 0:R.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:I[0])||0,Number(L.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(we,{})]})}function Er(){var r;const t=s.useEditorStore(l=>l.card.preferences),{setCardPreferences:a}=s.useEditorStore(l=>l.actions);function n(l){a({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:l==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:n,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function Be({cardType:t,docContent:a,suffix:n="Chart"}){let r="pie-donut-polar";return t==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} ${n}`}),e.jsx(s.AccordionContent,{children:a||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:l=>l.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),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:[t!=="text"&&e.jsx(Ke,{}),t==="text"&&e.jsx(Er,{})]})]}),!["range","text"].includes(t)&&e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(we,{}),e.jsx(Ee,{})]})]})]})})}function Ir(){const t=s.useEditorStore(r=>{var l,o;return(o=(l=r==null?void 0:r.card)==null?void 0:l.preferences)==null?void 0:o.sortChart}),{setSortChart:a}=s.useEditorActions();function n(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(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=>{a(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[n(),e.jsx(Vt,{})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(we,{}),e.jsx(Ee,{})]})]})]})})}function Ar({cardType:t="table"}){console.log("cardType",t);const a=s.useEditorStore(l=>{var o;return(o=l.card)==null?void 0:o.preferences}),n=s.useEditorStore(l=>l.actions.setCardPreferences),r=l=>{n({...a,allowDownload:l})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(we,{}),e.jsx(Ee,{})]})]})}),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"})]})]})}const Mr=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."]})]}),Lr=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."]})]}),Or=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 Rr(){const t=s.useEditorStore(n=>n.card.type);function a(n){switch(n){case"stackedBar":case"stackedLine":return e.jsx(Ir,{});case"tornado":case"pyramid":return e.jsx(Be,{docContent:Mr,cardType:n});case"kpi":return e.jsx(Sr,{});case"line":case"bar":return e.jsx(jr,{cardType:n});case"range":return e.jsx(Be,{docContent:Lr,cardType:n});case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return e.jsx(Be,{cardType:n});case"bubble":case"scatter":return e.jsx(yr,{cardType:n});case"table":return e.jsx(Ar,{cardType:n});case"text":return e.jsx(Be,{docContent:Or,cardType:n,suffix:"Visual"});case"map":return e.jsx(Dr,{});case"custom":return e.jsx(xr,{});default:return e.jsx(Nr,{})}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[a(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Gt({label:t,column:a,functions:n,onFunctionChange:r}){let l=n[0];"aggregate"in a?l=n.find(c=>c.value===a.aggregate)||n[0]:"granularity"in a&&(l=n.find(c=>c.value===a.granularity)||n[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:n,value:l.value,onValueChange:c=>o(c),label:t,showPlaceholderLabel:!1})}const Br=[{label:"Sum",value:"SUM",logo:e.jsx(rt,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(fs,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(On,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(hn,{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 Fr({column:t}){const{updateMetricColumnOld:a}=s.useEditorActions();let n=Br;s.isTextDataType(t.type)&&(n=n.filter(l=>["COUNT","DISTINCT"].includes(l.value))),s.isNumberDataType(t.type)&&(n=n.filter(l=>!["DISTINCT"].includes(l.value)));function r(l){const o={...t,aggregate:l,label:Le(t.name,l)};a(t.id,o)}return e.jsx(Gt,{column:t,functions:n,onFunctionChange:l=>r(l),label:"Aggregation"})}const zr=[{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 Pr({column:t}){const{updateGroupByColumnOld:a}=s.useEditorActions();function n(r){const l={...t,granularity:r,label:De(t.name,r)};a(t.id,l)}return e.jsx(Gt,{column:t,functions:zr,onFunctionChange:r=>n(r),label:"Granularity"})}function _r({col:t,onChange:a,droppableId:n}){const{columns:r}=s.useDataColumns(),l=M.useMemo(()=>{let i=[];(n===be||n===Ne||n===Ce)&&(i=r);const d=i==null?void 0:i.filter(m=>m.column_name!==t.name);return d==null?void 0:d.map(m=>({id:m.column_name,value:m.column_name}))},[r,n,t.name]),o=[{id:t.name,value:t.name}];function c(i){const d=r==null?void 0:r.find(m=>{var h;return m.column_name===((h=i[0])==null?void 0:h.id)});d&&a(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 Ht({column:t}){const a=s.useEditorStore(d=>d.card.type),n=s.useEditorStore(d=>{var m,h;return(h=(m=d.card)==null?void 0:m.config)==null?void 0:h.metricColumns}),r=(n==null?void 0:n.map(d=>d.label))||[],l=r==null?void 0:r.find(d=>d===t.label||d===t.name),o=l?r.indexOf(l):-1;function c(){return e.jsx("div",{className:"pr-1",children:l&&e.jsx(qt,{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(Ke,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&c(),["pie","doughnut"].includes(a)&&i()]})}function Vr({column:t,type:a,onRemoveColumn:n,droppableId:r}){const[l,o]=M.useState(!1),{updateGroupByColumnOld:c,updateMetricColumnOld:i,updatePivotByColumnOld:d}=s.useEditorActions(),{attributes:m,listeners:h,setNodeRef:u,transform:p,transition:j,isDragging:f}=s.useSortable({id:t.id,data:{type:a}}),x=p?{opacity:f?.5:void 0,transform:s.CSS.Translate.toString(p),transition:j}:void 0,S=s.isTextDataType(t.type);function g(D){const b=s.isNumberDataType(D.data_type),k=s.isTextDataType(D.data_type),w=s.isDateDataType(D.data_type),L=b?"number":k?"string":w?"date":"string";if(r===be){if(k){const T={id:t.id,name:D.column_name,type:L,role:"groupby"};c(t.id,T)}if(w){const T={id:t.id,name:D.column_name,type:L,role:"groupby",label:De(D.column_name,"month"),granularity:"month"};c(t.id,T)}}if(r===Ce){if(k){const T={id:t.id,name:D.column_name,type:L,role:"groupby"};d(t.id,T)}if(w){const T={id:t.id,name:D.column_name,type:L,label:De(D.column_name,"month"),granularity:"month",role:"groupby"};d(t.id,T)}}if(r===Ne){const T={id:t.id,name:D.column_name,type:L,role:"metric",label:Le(D.column_name,"SUM"),aggregate:b?"SUM":"COUNT"};i(t.id,T)}}function v(){if(r===Ne)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(Ht,{column:t})})}function N(){const D=s.isDateDataType(t.type);if(r===Ne)return e.jsx(Fr,{column:t});if((r===be||r===Ce)&&D)return e.jsx(Pr,{column:t})}function O(){return e.jsx("div",{className:s.cn("grow",{"pl-3":(r===be||r===Ce)&&S}),children:e.jsx(_r,{col:t,onChange:g,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(sa,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(tt,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...h,...m,ref:u,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(),N(),O()]}),l&&v()]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:l}),children:e.jsx("button",{onClick:()=>n(t.id),children:e.jsx(s.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function as({id:t,label:a,columns:n,previewColumns:r,sortableType:l,onRemoveColumn:o}){var x,S;const{setNodeRef:c,isOver:i,over:d}=s.useDroppable({id:t}),m=s.useDndStore(g=>g.activeId),h=s.useEditorStore(g=>{var v;return(v=g.card)==null?void 0:v.type}),u=i||((S=(x=d==null?void 0:d.data)==null?void 0:x.current)==null?void 0:S.type)===l,p=m?r:n,j=l===_e?"Rows":l===Ve?"Pivot Columns":"Columns";function f(){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:n==null?void 0:n.map(g=>g.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md p-4",u&&"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:a}),h!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:j})]}),f(),e.jsx("div",{className:"space-y-2",children:p==null?void 0:p.map(g=>g.id===Dt.id?e.jsx(Ur,{},g.id):e.jsx(Vr,{droppableId:t,type:l,column:g,onRemoveColumn:o},g.id))})]})})}function Ur(){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 Jt({children:t,id:a,type:n}){const{attributes:r,listeners:l,setNodeRef:o,transform:c,transition:i,isDragging:d}=s.useSortable({id:a,data:{type:n}}),m=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:m,children:t})}function qr(){const t=s.useEditorStore(g=>{var v;return(v=g.card.queryConfig)==null?void 0:v.orderBy})||[],a=s.useEditorStore(g=>{var v;return(v=g.card.queryConfig)==null?void 0:v.groupByColumns})||[],n=s.useEditorStore(g=>{var v;return(v=g.card.queryConfig)==null?void 0:v.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:l,updateOrderByColumn:o}=s.useEditorActions(),c=[...a,...n];if(c.length===0)return e.jsx(e.Fragment,{});const i=e.jsx(gn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx(mn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=e.jsx(fn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=e.jsx(un,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=c==null?void 0:c.filter(g=>!t.some(v=>v.columnId===g.id)).map(g=>({id:g.id,value:g.label||g.name}));function p(g,v){const N=j(g);return N?N.role==="metric"?v==="asc"?m:h:v==="asc"?i:d:null}function j(g){return c.find(v=>v.id===g)}function f(g){const v=t.find(N=>N.columnId===g);if(v){const N={...v,direction:v.direction==="asc"?"desc":"asc"};o(N)}}const x=g=>{r({columnId:g.id,direction:"asc"})};function S(g){const v=t.find(N=>N.columnId===g);v&&l(v)}return e.jsx(s.SortableContext,{items:t.map(g=>Ie(g.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"}),u.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(s.ComboBox2,{multiple:!1,options:u,selectedOptions:[],onChange:g=>x(g[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),t.map(g=>{var v,N;return e.jsx(Jt,{id:Ie(g.columnId),type:Ns,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(tt,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(Es,{className:"w-[175px] text-sm",children:((v=j(g.columnId))==null?void 0:v.label)||((N=j(g.columnId))==null?void 0:N.name)})]}),e.jsx("button",{title:g.direction==="asc"?"Ascending":"Descending",onClick:()=>f(g.columnId),className:"rounded-sm p-0",children:p(g.columnId,g.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>S(g.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"})})})]})},g.columnId)},Ie(g.columnId))})]})})}function $r(){const t=s.useEditorStore(S=>{var g;return((g=S.card.queryConfig)==null?void 0:g.groupByColumns)||[]}),a=s.useEditorStore(S=>S.card.type),n=s.useDndStore(S=>S.previewGroupByColumns),r=s.useEditorStore(S=>{var g;return((g=S.card.queryConfig)==null?void 0:g.metricColumns)||[]}),l=s.useDndStore(S=>S.previewMetricColumns),o=s.useEditorStore(S=>{var g;return((g=S.card.queryConfig)==null?void 0:g.pivotColumns)||[]}),c=s.useDndStore(S=>S.previewPivotColumns),{removeColumnFromGroupBy:i,removeColumnFromMetricColumns:d,removeColumnFromPivotBy:m}=s.useEditorActions();function h(S){i(S)}function u(S){d(S)}function p(S){m(S)}let j="Group By",f="Metrics",x="Stack By";return a==="table"&&(j="Rows",f="Metrics",x="Columns"),e.jsxs("div",{className:"flex h-full w-full flex-col gap-3 py-4",children:[e.jsx(Ft,{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(as,{onRemoveColumn:h,sortableType:_e,id:be,label:j,columns:t,previewColumns:n}),e.jsx(as,{onRemoveColumn:p,sortableType:Ve,id:Ce,label:x,columns:o,previewColumns:c}),e.jsx(as,{onRemoveColumn:u,sortableType:ls,id:Ne,label:f,columns:r,previewColumns:l}),e.jsx(qr,{})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Is({children:t,column:a,id:n,sortableType:r,className:l}){const[o,c]=M.useState(!1),{removeEditorFilter:i,clearEditorFilter:d}=s.useEditorActions(),m=s.useEditorStore(u=>{var p,j;return(j=(p=u.card.queryConfig)==null?void 0:p.filters)==null?void 0:j.some(f=>f.filterColumnName===a.name)});function h(u){i(u)}return e.jsx(Jt,{id:n,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:a.name}),m&&e.jsx("button",{onClick:()=>d(a),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:()=>h(a),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 Gr({column:t,sortableType:a}){const n=s.useDashboardStore(N=>N.themeStyle),r=s.useEditorStore(N=>{var O,C;return(C=(O=N.card)==null?void 0:O.queryConfig)==null?void 0:C.filters}),l=s.useEditorStore(N=>{var O,C;return(C=(O=N.card.queryConfig)==null?void 0:O.filterColumns)==null?void 0:C.find(D=>D.name===t.name)}),{selectedConnectionId:o,selectedDatabaseName:c,selectedTableName:i}=s.useEditorAside(),d=M.useMemo(()=>{var N;return(N=r==null?void 0:r.find(O=>O.filterColumnName===t.name))==null?void 0:N.filterValue},[r,t.name]),m=M.useMemo(()=>Array.isArray(d)?d.map(N=>({id:N,value:N})):[],[d]),{updateEditorFilterValue:h}=s.useEditorActions(),u={column:t.name,sql:t.sql,id:t.name,connectionId:o,dataType:t.type},{data:p,isLoading:j,isFetching:f,isError:x}=s.useFilterQuery(u),S=M.useMemo(()=>{var O;return u.column?(O=p==null?void 0:p.records)==null?void 0:O.map(C=>{let D=u.column.split(".").slice(-1)[0].replace(/"/g,"");return C[D]===void 0&&(D=D.toLowerCase()),{id:C[D],value:C[D]}}):[]},[p,u.column]);function g(N){const O=N.map(C=>C.id);h(t.name,O)}function v(){return j||f?e.jsx(s.Skeleton,{style:{borderRadius:n==null?void 0:n.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(Hr,{columnName:t.name}),showNegativeIndicator:(l==null?void 0:l.mode)==="exclude",options:S,onChange:g,selectedOptions:m,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(Is,{className:"w-60",id:t.id,sortableType:a,column:t,children:v()})}function Hr({columnName:t}){const{setEditorFilterMode:a}=s.useEditorActions(),n=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(){(n==null?void 0:n.mode)==="exclude"?a(t,"include"):a(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((n==null?void 0:n.mode)==="exclude"?"exclude":"include")})}function Jr({column:t,sortableType:a}){const[n,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:m,isError:h,data:u}=s.useFilterQuery(i),p=u==null?void 0:u.records,{dateRange:j,setDateRange:f,initialDateRange:x}=s.useDateRangeFromRecords(p),{updateEditorFilterValue:S}=s.useEditorActions();function g(O){var D,b;const C={gte:(D=O==null?void 0:O.from)==null?void 0:D.toISOString(),lte:(b=O==null?void 0:O.to)==null?void 0:b.toISOString()};S(t.name,C)}function v(){S(t.name,null,!0),f(x)}function N(){return d||m?e.jsx("div",{children:e.jsx(s.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):h?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):p?e.jsx(s.DateRangePopover,{title:i.title,open:n,inputClassName:"h-8",setOpen:r,dateRange:j,setDateRange:f,onApply:g,onClear:v}):e.jsx(s.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(Is,{className:"w-72",id:t.id,sortableType:a,column:t,children:N()})}function Wr({id:t,label:a,columns:n,previewColumns:r,sortableType:l}){var f,x;const{setNodeRef:o,isOver:c,over:i}=s.useDroppable({id:t}),d=s.useDndStore(S=>S.activeId),m={},h=c||((x=(f=i==null?void 0:i.data)==null?void 0:f.current)==null?void 0:x.type)===l;function u(){if(!j||j.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(S){const g=s.isDateDataType(S.type);return S.id===Dt.id?e.jsx(Is,{id:S.id,sortableType:l,column:S,children:e.jsx(Yr,{})},S.id):g?e.jsx(Jr,{droppableId:t,sortableType:l,column:S},S.id):e.jsx(Gr,{droppableId:t,sortableType:l,column:S},S.id)}const j=d?r:n;return e.jsx(s.SortableContext,{items:n==null?void 0:n.map(S=>S.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",h&&"border border-muted-foreground/20"),ref:o,style:m,children:[e.jsx(s.Label,{className:"text-sm",children:a}),u(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:j==null?void 0:j.map(S=>p(S))})]})})}function Yr(){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 Kr(){const t=s.useEditorStore(l=>{var o;return((o=l.card.queryConfig)==null?void 0:o.filterColumns)||[]}),a=s.useDndStore(l=>l.previewFilterColumns),{removeColumnFromFilterColumns:n}=s.useEditorActions();function r(l){n(l)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(Wr,{onRemoveColumn:r,sortableType:is,id:os,label:"Filters",columns:t,previewColumns:a})})}function Qr(){const t=s.useEditorStore(o=>o.card),a=s.useEditorStore(o=>o.showAIDialog),{setShowAIDialog:n}=s.useEditorActions(),{data:r,errorMessage:l}=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(s.EditorClearButton,{}),!a&&e.jsxs(s.Button,{onClick:()=>n(!0),variant:"secondary",size:"sm",children:[e.jsx(Wn,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(Mt,{sql:r==null?void 0:r.sql,error:l})]}),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(s.EditorCancelButton,{}),e.jsx(s.EditorAcceptButton,{variant:"default"})]})]})}function Xr(){const t=M.useRef(null),a=M.useRef(null),n=s.useEditorStore(i=>i.isShowingVisual),r=s.useEditorStore(i=>i.showAIDialog),l=s.useEditorStore(i=>i.isDevMode);M.useEffect(()=>{var i,d,m,h;r?((i=t.current)==null||i.resize(0),(d=a.current)==null||d.resize(0)):((m=t.current)==null||m.resize(25),(h=a.current)==null||h.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(Qa,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:n&&!r?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:t,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(Rr,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(Re,{})})]}):e.jsx(Re,{})})]})}function c(){return e.jsx(e.Fragment,{children:e.jsx("div",{className:"grow","data-biz-mode-container":"",children:n?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:a,defaultSize:25,maxSize:30,children:e.jsx($r,{})})}),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(Qr,{}),e.jsx(Kr,{})]}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(Re,{})})]})})]}):e.jsx(Re,{})})})}return e.jsx(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:l?o():c()})}function Zr(t){const a=s.useAIInteractionStore(B=>B.currentAIContext),[n,r]=M.useState(""),[l,o]=M.useState(null),{authToken:c}=s.useSemaphorContext(),i=s.useEditorStore(B=>{var K;return(K=B==null?void 0:B.card)==null?void 0:K.sql}),d=s.useEditorStore(B=>B.isDevMode),m=s.useEditorStore(B=>{var K;return(K=B==null?void 0:B.card)==null?void 0:K.python}),{setCardPython:h,setCardSql:u,setRunSql:p,switchCardType:j,setQueryConfig:f}=s.useEditorActions(),x=s.useEditorStore(B=>B.currentAssitantScope)||[],S=s.useEditorStore(B=>B.userInputForAI),g=s.useEditorStore(B=>B.triggerAIRun),v=s.useEditorStore(B=>B.card),N=s.useEditorStore(B=>B.selectedDatabaseName),O=s.useEditorStore(B=>B.selectedTableName),C=s.useEditorStore(B=>B.selectedConnectionId),D=s.useEditorStore(B=>B.selectedSchemaName),b=s.useDashboardStore(B=>B.dashboard.aiScopeTables),{errorMessage:k,refetch:w,data:L}=s.useDashboardCardQuery(v),{setTriggerAIRun:T,setCurrentAssitantScope:R,setCardConfig:A}=s.useEditorActions(),{selectedDatamodelName:I,connectionType:y,selectedDatamodelId:E}=s.useEditorAside(),{messages:F,setMessages:z,reload:_,error:P,append:Q,input:Y,setInput:V,status:q,handleInputChange:$,handleSubmit:U,stop:H}=s.useChat({api:"https://semaphor.cloud/api/v1/assistant",headers:{Authorization:`Bearer ${c==null?void 0:c.accessToken}`},body:{random:Math.random(),assistantId:"editor-assistant",isDevMode:d,aiContext:a},maxSteps:10,onError:B=>{console.log("on error",B)},onToolCall:W,onFinish(B,K){G(K.usage),r(""),K.finishReason==="stop"&&r("")}});M.useEffect(()=>{g&&S&&(Q({role:"user",content:S}),T(!1))},[g,S,Q,T]);async function W({toolCall:B}){var K,re,he,je;if(["createChartFromSql","createForecast"].includes(B.toolName)){const te=B.args.sql,le=B.args.python,oe=B.args.chartType;return j(oe),u(te),h(le),p(!0),{status:"success",message:"Let the user know that chart is created"}}else if(B.toolName==="getTableColumns")r("Getting table columns...");else{if(B.toolName==="getUserSql")return i?{status:"success",sql:i,python:m||""}:{status:"error",message:"No SQL found"};if(B.toolName==="getCurrentTableScope")return r("Getting table scope..."),ee(),{status:"success",tables:x};if(B.toolName==="generateQueryConfig"){r("Generating query config...");const te=B.args.chartType,le=B.args.queryConfig;B.args.cardConfig,j(te),A(le),u(void 0),h(void 0);const oe=await w();return(K=oe==null?void 0:oe.data)!=null&&K.error?{status:"error",queryConfig:le,message:(re=oe==null?void 0:oe.data)==null?void 0:re.error.message}:(he=oe==null?void 0:oe.data)!=null&&he.records?{status:"success",queryConfig:le,message:"The data has been visualized"}:{status:"success",queryConfig:le,message:"The data has been visualized",records:(je=oe==null?void 0:oe.data)==null?void 0:je.records}}else r("Analyzing...")}}function G(B){o(K=>K?{promptTokens:K.promptTokens+B.promptTokens,completionTokens:K.completionTokens+B.completionTokens,totalTokens:K.totalTokens+B.totalTokens}:B)}function Z(B){const K=s.removeFromScopeArray(x,B);se(K)}function se(B){const K=s.sanitizeAIScope(B);R(K),z(re=>[...re,{id:crypto.randomUUID(),role:"system",content:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(K)}`}])}function ne(){const B={databaseName:N||"",schemaName:D||"",tableName:O||"",datamodelId:E||"",datamodelName:s.resolveDatamodelName(I),connectionId:C||"",connectionType:y||""},K=s.dedup([...x,B]);se(K)}function ee(){const B={databaseName:N||"",schemaName:D||"",tableName:O||"",datamodelName:s.resolveDatamodelName(I),connectionId:C||"",connectionType:y||"",datamodelId:E||""};if(!s.isInAiScopeArray([...b||[],...x],B)||x.length===0){const re=s.dedup([...b||[],...x,B]).filter(he=>he.connectionId===B.connectionId);se(re)}}const ae=!["ready","error"].includes(q),J=s.getErrorMessage(P);return{messages:F,setMessages:z,reload:_,append:Q,input:Y,setInput:V,isLoading:ae,handleSetAIScope:ee,handleAddCurrentTableToScope:ne,removeFromCurrentSelections:Z,currentAssitantScope:x,setCurrentAssitantScope:R,handleInputChange:$,handleSubmit:U,stop:H,chatStatus:q,toolStatus:n,llmUsage:l,onFinish:t,errorMessage:J}}const el=[{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),a=M.useRef(null),[n,r]=M.useState(!1),[l,o]=M.useState(s.isDevEnv),[c,i]=M.useState(!1),[d,m]=M.useState(!1),h=s.useCurrentAIContext(),{setCurrentAIContext:u}=s.useAIActions(),p=s.useDashboardStore(H=>H.dashboard.aiContext),j=s.useEditorStore(H=>H.card.dataSource),f=s.useEditorStore(H=>H.actions.setCardSql),x=s.useEditorStore(H=>H.actions.setRunSql),S=s.useEditorStore(H=>H.showAIDialog),g=s.useDashboardStore(H=>H.handleOpenAssistantProfile),{setShowAIDialog:v,setCardPython:N}=s.useEditorActions(),{setDataSource:O}=s.useEditorActions(),{assistantProfile:C}=s.useAssistantProfile(),{messages:D,setMessages:b,reload:k,append:w,input:L,setInput:T,isLoading:R,handleInputChange:A,handleSubmit:I,stop:y,chatStatus:E,llmUsage:F,errorMessage:z}=Zr();s.useAssistantScroll({scrollContainerRef:t,inputRef:a,messages:D}),M.useEffect(()=>{var H;S&&((H=a.current)==null||H.focus(),u({selectedEntities:(j==null?void 0:j.selectedEntities)||[]}))},[S,j,u]);function _(H,W){W==="sql"?(f(H),x(!0)):W==="python"&&(N(H),x(!0))}function P(){var H;(H=p==null?void 0:p.selectedEntities)==null||H[0],m(!0)}function Q(){h.selectedEntities.length===0&&u({selectedEntities:(p==null?void 0:p.selectedEntities)||[]})}function Y(H){Q();const W={role:"user",content:H.title+" "+H.subtitle};w(W)}function V(H){Q(),w({role:"user",content:H})}function q(){return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuLabel,{children:"Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx(s.DropdownMenuCheckboxItem,{checked:n,onCheckedChange:r,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:o,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:i,children:"System Message"})]})]})}function $(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const U=(L==null?void 0:L.length)===0&&(D==null?void 0:D.filter(H=>H.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:[$(),g&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:g,children:(C==null?void 0:C.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center gap-2",children:[q(),e.jsx(s.IconButton,{tooltip:"Add Context",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:P,children:e.jsx(s.Settings,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{b([]),k()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-8 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{v(!1)},children:e.jsx(s.EyeOff,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:t,className:"mt-2 flex w-full grow basis-0",children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[e.jsx(s.PrintMessages,{messages:D,showTools:l,handleRun:_,showSystemMessage:c}),e.jsx(s.ChatStatus,{messages:D,chatStatus:E,errorMessage:z})]})}),e.jsxs("div",{className:"mb-3",children:[U&&!C&&e.jsx(s.Placeholders,{onClick:Y,placeholders:el}),e.jsx("div",{children:U&&C&&e.jsx(s.SeedQuestions,{seedQuestions:C.seedQuestions||[],handleSeedQuestionClick:V})})]}),e.jsx(s.ChatInputWithContext,{ref:a,setInput:T,stop:y,input:L,handleInputChange:A,handleSubmit:H=>{Q(),I(H)},isLoading:R,onFocus:()=>{}}),F&&n&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",F.promptTokens," prompt tokens,"," ",F.completionTokens," completion tokens,"," ",F.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(j==null?void 0:j.selectedEntities)||[],open:d,onOpenChange:m,dataSource:j||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function Wt(t,a){return`${t}-${a.qualifiedEntityName}-${a.name}-${Date.now()}`}function Yt(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function sl(t,a){const n=s.getDataType(t.dataType);return n==="number"?"metrics":n==="date"||n==="string"?"groupBy":"metrics"}function cs(t,a){const n=Wt(a,t),r=s.getDataType(t.dataType),l=r==="date",o={id:n,name:t.name,dataType:t.dataType,label:s.toLabel(t.name),qualifiedEntityName:t.qualifiedEntityName,entityId:t.entityId,entityName:t.entityName,entityType:t.entityType};if(a==="metrics"){const c=r==="number"?"SUM":"COUNT",i=Yt(t.label,c);return{...o,role:"metric",label:i,aggregate:c}}return a==="groupBy"?{...o,role:"groupby",...l&&{granularity:"month",dateFormat:"YYYY-MM"}}:a==="pivotBy"?{...o,role:"pivotby"}:a==="sortBy"?{...o,role:"sortby",label:t.label,direction:"asc"}:null}function Kt(t,a,n){var r;return!n||!((r=n.baseEntity)!=null&&r.name)||!n.joins?!1:t===a||t===n.baseEntity.name||a===n.baseEntity.name?!0:n.joins.some(l=>{const o=s.getQualifiedEntityName(l.source),c=s.getQualifiedEntityName(l.target);return o===t&&c===a||o===a&&c===t})}function tl(t,a,n){if(a.length===0)return{isValid:!0};const r=a[0].qualifiedEntityName;if(!r)return{isValid:!0};if(r!==t.qualifiedEntityName&&t.qualifiedEntityName)if(n){if(!Kt(r,t.qualifiedEntityName,n))return{isValid:!1,showError:!0}}else return{isValid:!1,showError:!0};return{isValid:!0}}function ds(){s.ue.error("Join Configuration Required",{richColors:!0,description:"To combine fields from two different tables, you need to define a join between them first.",position:"top-center",duration:4e3})}function us(t,a){return a.some(n=>n.name===t.name&&n.qualifiedEntityName===t.qualifiedEntityName)}const As=t=>{var T;const{updateCardConfig:a,updateGroupByColumn:n,updateMetricColumn:r,updatePivotByColumn:l,updateSortByColumn:o,removeGroupByColumn:c,removeMetricColumn:i,removePivotByColumn:d,removeSortByColumn:m}=s.useEditorActions(),h=s.useEditorStore(R=>R.card.type),u=t==null?void 0:t.id,p=M.useCallback(R=>{if(!(t!=null&&t.config))return[];switch(R){case"groupBy":return(t.config.groupByColumns||[]).map(A=>({id:A.id,name:A.name,dataType:A.dataType,label:A.label!==void 0?A.label:A.name,qualifiedEntityName:A.qualifiedEntityName,entityId:A.entityId,entityName:A.entityName,entityType:A.entityType,dateFormat:A.dateFormat,customFormat:A.customFormat,granularity:A.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(A=>({id:A.id,name:A.name,dataType:A.dataType,label:A.label!==void 0?A.label:A.name,qualifiedEntityName:A.qualifiedEntityName,entityId:A.entityId,entityName:A.entityName,entityType:A.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(A=>({id:A.id,name:A.name,dataType:A.dataType,label:A.label!==void 0?A.label:A.name,qualifiedEntityName:A.qualifiedEntityName,entityId:A.entityId,entityName:A.entityName,entityType:A.entityType,direction:A.direction}));case"source":return[];default:return[]}},[t]),j=M.useCallback((R,A)=>{if(u)switch(R){case"groupBy":{a(u,{groupByColumns:A});break}case"metrics":{a(u,{metricColumns:A});break}case"pivotBy":{a(u,{pivotByColumns:A});break}case"sortBy":{a(u,{sortByColumns:A});break}}},[u,a]),f=M.useCallback((R,A,I)=>{if(!u)return;const E=p(R)[A];if(E)switch(R){case"groupBy":n(u,E.id,{label:I});break;case"metrics":r(u,E.id,{label:I});break;case"pivotBy":l(u,E.id,{label:I});break;case"sortBy":o(u,E.id,{label:I});break}},[u,p,n,r,l,o]),x=M.useCallback((R,A)=>{if(!u)return;const y=p("metrics")[R];y&&r(u,y.id,{aggregate:A,label:Yt(y.name,A)})},[u,p,r]),S=M.useCallback((R,A,I)=>{if(!u)return;const E=p("groupBy")[R];if(!E)return;const F={dateFormat:A};A==="custom"&&I?F.customFormat=I:F.customFormat=void 0,n(u,E.id,F)},[u,p,n]),g=M.useCallback((R,A)=>{if(!u)return;const y=p("groupBy")[R];y&&n(u,y.id,{granularity:A})},[u,p,n]),v=M.useCallback((R,A)=>{if(!u)return;const y=p("metrics")[R];y&&r(u,y.id,{aliasTemplate:A})},[u,p,r]),N=M.useCallback((R,A)=>{if(console.log("handleValueAliasesChange",R,A),!u)return;console.log("handleValueAliasesChange",R,A);const y=p("metrics")[R];y&&(console.log("handleValueAliasesChange",A),r(u,y.id,{valueAliases:A}))},[u,p,r]),O=M.useCallback(R=>{u&&a(u,{comparisonType:R})},[u,a]),C=M.useCallback(R=>{u&&a(u,{showTrendline:R})},[u,a]),D=M.useCallback(R=>{u&&a(u,{trendlineWindow:R})},[u,a]),b=M.useCallback(R=>{u&&a(u,{trendlineGranularity:R})},[u,a]),k=M.useCallback(R=>{u&&a(u,{targetValue:R})},[u,a]),w=M.useCallback(R=>{var _;if(!u)return;const A=[...p("groupBy"),...p("pivotBy"),...p("metrics"),...p("sortBy")],I=(_=t==null?void 0:t.config)==null?void 0:_.joinPlan,y=tl(R,A,I);if(!y.isValid){y.showError&&ds();return}const E=sl(R),F=p(E);if(us(R,F))return;const z=cs(R,E);z&&j(E,[...F,z])},[u,(T=t==null?void 0:t.config)==null?void 0:T.joinPlan,p,j]),L=M.useCallback((R,A)=>{if(!u)return;const y=p(R)[A];if(y){if(R!=="sortBy"){const E=p("sortBy"),F=E.filter(z=>!(z.name===y.name&&z.qualifiedEntityName===y.qualifiedEntityName));F.length!==E.length&&a(u,{sortByColumns:F})}switch(R){case"groupBy":c(u,y.id);break;case"metrics":i(u,y.id);break;case"pivotBy":d(u,y.id);break;case"sortBy":m(u,y.id);break}}},[u,p,c,i,d,m,a]);return{getFieldsForContainer:p,setFieldsForContainer:j,updateLabel:f,handleAggregationChange:x,handleDateFormatChange:S,handleGranularityChange:g,handleAliasTemplateChange:v,handleValueAliasesChange:N,removeField:L,handleFieldClick:w,handleKpiComparisonTypeChange:O,handleKpiShowTrendlineChange:C,handleKpiTrendlineWindowChange:D,handleKpiTrendlineGranularityChange:b,handleKpiTargetValueChange:k,cardType:h}};function nl({field:t}){const{attributes:a,listeners:n,setNodeRef:r,transform:l,transition:o,isDragging:c}=s.useSortable({id:t.id}),[i,d]=M.useState(!1),m=s.useEditorStore(x=>x.card),{handleFieldClick:h}=As(m),u={transform:s.CSS.Transform.toString(l),transition:o},p=s.getDataType(t.dataType),f=(x=>{const S=(x||"").toLowerCase();switch(s.getDataType(S)){case"number":return fs;case"date":return s.Calendar;case"boolean":return ot;case"json":return wn;case"geo":return Hn;default:return it}})(t.dataType);return e.jsxs("div",{ref:r,style:u,...a,...n,className:`group/container overflow-hidden rounded-lg transition-all ${c?"scale-95 opacity-50":"border border-transparent hover:border-blue-200 hover:bg-blue-50 dark:hover:border-blue-800 dark:hover:bg-blue-950"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1 p-2",onClick:()=>h(t),children:[e.jsx("div",{className:"flex-shrink-0 hover:cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"invisible size-3.5 text-gray-400 group-hover/container:visible"})}),e.jsx(f,{className:s.cn("size-3.5 flex-shrink-0 text-gray-500",p==="string"?"text-blue-500":"",p==="number"?"text-green-500":"",p==="date"?"text-purple-500":"",p==="boolean"?"text-orange-500":"")}),e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:e.jsx("span",{className:`block text-sm text-foreground/90 hover:text-foreground dark:text-muted-foreground ${i?"whitespace-normal break-words":"truncate"}`,children:t.name})})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:t.label||t.name}),t.description&&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:t.description})]}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"mr-2 text-muted-foreground",children:"Name:"}),e.jsx("span",{className:"font-mono text-muted-foreground",children:t.name})]}),e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"mr-2 text-muted-foreground",children:"Type:"}),e.jsx("span",{className:"font-mono text-muted-foreground",children:t.dataType})]}),t.qualifiedEntityName&&e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[t.entityType?t.entityType.charAt(0).toUpperCase()+t.entityType.slice(1):"Entity",":"]}),e.jsx("span",{className:"font-mono text-muted-foreground",children:t.qualifiedEntityName})]})]})]})})]})})]}),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(lt,{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(aa,{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 al(){const[t,a]=M.useState(""),[n,r]=M.useState("all"),l=s.useEditorStore(N=>N.card.dataSource),{columns:o=[],columnGroups:c=[],isLoading:i,error:d}=s.useColumns(),m=o.filter(N=>N.name.toLowerCase().includes(t.toLowerCase())||N.dataType.toLowerCase().includes(t.toLowerCase())||N.qualifiedEntityName&&N.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),h=N=>{if(N.dataType==="number"||N.dataType==="integer"||N.dataType==="float"||N.dataType==="decimal"||N.dataType==="currency")return"metrics";const O=s.getDataType(N.dataType);return["date","string","boolean"].includes(O)?"dimensions":O==="number"?"metrics":"dimensions"},p=(n==="all"?m:m.filter(N=>h(N)===n)).reduce((N,O)=>{const C=O.qualifiedEntityName||"Other Fields";return N[C]||(N[C]={label:s.toLabel(O.entityName),fields:[]}),N[C].fields.push(O),N},{}),f=Object.keys(p),x=m.filter(N=>h(N)==="dimensions").length,S=m.filter(N=>h(N)==="metrics").length,g=m.filter(N=>h(N)==="calculated").length,v=m.length>0;return i?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-gray-400"}),e.jsx("span",{className:"mt-2 text-sm text-gray-500",children:"Loading fields..."})]}):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.jsx("div",{className:"mb-4",children:e.jsx(s.Input$1,{type:"text",placeholder:"Search fields...",value:t,onChange:N=>a(N.target.value)})}),v&&e.jsx(s.Tabs,{defaultValue:"all",value:n,onValueChange:N=>r(N),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: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: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:S})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(Nn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:g})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:f,className:"space-y-2",children:Object.entries(p).map(([N,O])=>{const C=c.find(D=>D.entityName===N)||{entityName:N,label:O.label};return e.jsxs(s.AccordionItem,{value:N,className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"group rounded-md px-3 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"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:O.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:O.fields.map(D=>e.jsx(nl,{field:D},D.id))})})]},N)})}),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 rl(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(al,{})," "]})}function ll({initialJoinPlan:t,availableDataSources:a}){const[n,r]=M.useState(t),[l,o]=M.useState(new Set),c=()=>{const D=n.joins.length>0?Math.max(...n.joins.map(k=>k.sequence))+1:1,b={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({...n,joins:[...n.joins,b]}),o(new Set([...l,b.id]))},i=D=>{r({...n,joins:n.joins.filter(b=>b.id!==D)}),o(new Set([...l].filter(b=>b!==D)))},d=(D,b)=>{var T,R;const k=n.joins.find(A=>A.id===D);if(!k)return;const w={...k,...b},L=n.joins.map(A=>A.id===D?w:A);if((T=w.source)!=null&&T.name&&((R=w.target)!=null&&R.name)&&w.joinKeyGroups[0].keys.length===0){const A=a.find(F=>{var z;return F.name===((z=w.source)==null?void 0:z.name)}),I=a.find(F=>{var z;return F.name===((z=w.target)==null?void 0:z.name)}),y={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(A==null?void 0:A.name)||"",entityName:(A==null?void 0:A.name)||"",entityType:(A==null?void 0:A.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(I==null?void 0:I.name)||"",entityName:(I==null?void 0:I.name)||"",entityType:(I==null?void 0:I.type)||"table"},operator:"="},E=[...w.joinKeyGroups];E[0]={...E[0],keys:[y]},w.joinKeyGroups=E,L[L.findIndex(F=>F.id===D)]=w}r({...n,joins:L})};return{joinPlan:n,expandedJoins:l,setJoinPlan:r,addJoin:c,removeJoin:i,updateJoin:d,moveJoinUp:D=>{const b=n.joins.findIndex(k=>k.id===D);if(b>0){const k=[...n.joins],w={...k[b]},L={...k[b-1]};k[b]=L,k[b-1]=w,k.forEach((R,A)=>{R.sequence=A+1});const T={...n,joins:k};r(T)}},moveJoinDown:D=>{const b=n.joins.findIndex(k=>k.id===D);if(b<n.joins.length-1){const k=[...n.joins],w={...k[b]},L={...k[b+1]};k[b]=L,k[b+1]=w,k.forEach((R,A)=>{R.sequence=A+1});const T={...n,joins:k};r(T)}},toggleJoinExpansion:D=>{const b=new Set(l);b.has(D)?b.delete(D):b.add(D),o(b)},getAvailableSourceEntities:D=>{if(n.joins.length===0)return a;const b=n.joins.findIndex(w=>w.id===D);if(b===0)return a;const k=new Set;return n.baseEntity.name&&k.add(n.baseEntity.name),n.joins.slice(0,b).forEach(w=>{k.add(w.source.name),k.add(w.target.name)}),a.filter(w=>k.has(w.name))},getAvailableTargetEntities:D=>a.filter(b=>b.name!==D),addJoinKeyGroup:D=>{const b=n.joins.find(w=>w.id===D);if(!b)return;const k=[...b.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];d(D,{joinKeyGroups:k})},updateGroupOperator:(D,b,k)=>{const w=n.joins.find(T=>T.id===D);if(!w)return;const L=[...w.joinKeyGroups];L[b]={...L[b],operator:k},d(D,{joinKeyGroups:L})},removeJoinKeyGroup:(D,b)=>{const k=n.joins.find(L=>L.id===D);if(!k)return;const w=[...k.joinKeyGroups];w.splice(b,1),d(D,{joinKeyGroups:w})},addJoinKey:(D,b)=>{const k=n.joins.find(A=>A.id===D);if(!k)return;const w=a.find(A=>A.name===k.source.name),L=a.find(A=>A.name===k.target.name),T=[...k.joinKeyGroups],R={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(w==null?void 0:w.name)||"",entityName:(w==null?void 0:w.name)||"",entityType:(w==null?void 0:w.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(L==null?void 0:L.name)||"",entityName:(L==null?void 0:L.name)||"",entityType:(L==null?void 0:L.type)||"table"},operator:"="};T[b]={...T[b],keys:[...T[b].keys,R]},d(D,{joinKeyGroups:T})},updateJoinKey:(D,b,k,w,L)=>{const T=n.joins.find(E=>E.id===D);if(!T)return;const R=a.find(E=>E.name===T.source.name),A=a.find(E=>E.name===T.target.name),I=[...T.joinKeyGroups],y=I[b].keys[k];w==="sourceColumnName"&&R?I[b].keys[k]={...y,source:{...y.source,name:L}}:w==="targetColumnName"&&A?I[b].keys[k]={...y,target:{...y.target,name:L}}:w==="operator"&&(I[b].keys[k]={...y,operator:L}),d(D,{joinKeyGroups:I})},removeJoinKey:(D,b,k)=>{const w=n.joins.find(T=>T.id===D);if(!w)return;const L=[...w.joinKeyGroups];L[b].keys.splice(k,1),d(D,{joinKeyGroups:L})},generateSQLPreview:()=>{const D=[...n.joins].sort((w,L)=>w.sequence-L.sequence),b=n.baseEntity;if(!b.name)return"SELECT * FROM table -- Please select a base entity";let k=`SELECT *
415
+ FROM ${b.name}`;return D.forEach(w=>{const L=a.find(A=>A.name===w.target.name);if(!L)return;const T=w.joinKeyGroups.filter(A=>A.keys&&A.keys.length>0).map(A=>{const I=A.keys.filter(y=>{var E,F,z,_;return((E=y.source)==null?void 0:E.name)&&((F=y.target)==null?void 0:F.name)&&((z=y.source)==null?void 0:z.entityName)&&((_=y.target)==null?void 0:_.entityName)}).map(y=>`${y.source.entityName}.${y.source.name} ${y.operator} ${y.target.entityName}.${y.target.name}`);return I.length>1?`(${I.join(` ${A.operator} `)})`:I[0]}).filter(Boolean),R=T.length>1?T.join(" OR "):T[0]||"condition_here";k+=`
416
+ ${w.joinType} JOIN ${L.name}
417
+ ON ${R}`}),k},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(w=>!w.source.name||!w.target.name)||n.joins.some(w=>w.joinKeyGroups.some(L=>L.keys.length===0))||n.joins.some(w=>w.joinKeyGroups.some(L=>L.keys.some(T=>!T.source.name||!T.target.name||!T.operator))))}}function ol({joinPlan:t,availableDataSources:a,onSave:n,onRemove:r,onCancel:l}){const{setCardConfig:o}=s.useEditorActions();s.useEditorStore(T=>T.card.config);const{columnGroups:c}=s.useColumns(),{joinPlan:i,expandedJoins:d,setJoinPlan:m,addJoin:h,removeJoin:u,updateJoin:p,moveJoinUp:j,moveJoinDown:f,toggleJoinExpansion:x,getAvailableSourceEntities:S,getAvailableTargetEntities:g,addJoinKeyGroup:v,updateGroupOperator:N,removeJoinKeyGroup:O,addJoinKey:C,updateJoinKey:D,removeJoinKey:b,generateSQLPreview:k,isValidConfiguration:w}=ll({initialJoinPlan:t,availableDataSources:a}),L=T=>{const R=c.find(A=>A.entityName===T);return(R==null?void 0:R.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:T=>{const R=a.find(A=>A.name===T);m({...i,baseEntity:{connectionId:(R==null?void 0:R.connectionId)||"",connectionType:(R==null?void 0:R.connectionType)||"none",type:(R==null?void 0:R.type)||"table",name:T,database:R==null?void 0:R.database,schema:R==null?void 0:R.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:a.map(T=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:T.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:T.type}),T.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},T.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:k()})]}),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:h,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(T=>{const R=a.find(y=>y.name===T.source.name),A=a.find(y=>y.name===T.target.name),I=d.has(T.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:T.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",T.sequence,R&&A&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",R.name," → ",A.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>j(T.id),disabled:T.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>f(T.id),disabled:T.sequence===i.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>x(T.id),children:I?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:()=>u(T.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),I&&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:T.source.name,onValueChange:y=>{const E=a.find(F=>F.name===y);p(T.id,{source:{connectionId:(E==null?void 0:E.connectionId)||"",connectionType:(E==null?void 0:E.connectionType)||"none",type:(E==null?void 0:E.type)||"table",name:y,database:E==null?void 0:E.database,schema:E==null?void 0:E.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:S(T.id).map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:y.type}),y.name]})},y.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:T.joinType,onValueChange:y=>p(T.id,{joinType:y}),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Target"}),e.jsxs(s.Select,{value:T.target.name,onValueChange:y=>{const E=a.find(F=>F.name===y);p(T.id,{target:{connectionId:(E==null?void 0:E.connectionId)||"",connectionType:(E==null?void 0:E.connectionType)||"none",type:(E==null?void 0:E.type)||"table",name:y,database:E==null?void 0:E.database,schema:E==null?void 0:E.schema}})},disabled:!T.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:T.source.name?g(T.source.name).map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:y.type}),y.name,y.name===T.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},y.name)):[]})]})]})]}),T.source.name&&T.target.name&&R&&A&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>v(T.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),T.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:T.joinKeyGroups.map((y,E)=>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 ",E+1]}),E>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(s.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Select,{value:y.operator,onValueChange:F=>N(T.id,E,F),children:[e.jsx(s.SelectTrigger,{className:"w-[100px]",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>O(T.id,E),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[y.keys.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-sm text-gray-500",children:"No conditions in this group. Add conditions to specify join criteria."}):e.jsx("div",{className:"space-y-2",children:y.keys.map((F,z)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[z>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:y.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:F.source.name,onValueChange:_=>D(T.id,E,z,"sourceColumnName",_),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:L(T.source.name).map(_=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:_.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:_.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:_.dataType})]})},_.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:F.operator,onValueChange:_=>D(T.id,E,z,"operator",_),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:F.target.name,onValueChange:_=>D(T.id,E,z,"targetColumnName",_),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:L(T.target.name).map(_=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:_.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:_.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:_.dataType})]})},_.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>b(T.id,E,z),children:e.jsx(s.X,{className:"size-3.5"})})]},F.id||z))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>C(T.id,E),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},y.id))})]})]})]},T.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),l()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:l,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>n(i),disabled:!w(),children:"Save"})]})]})}function Ys({children:t,open:a,onOpenChange:n,joinPlan:r,availableDataSources:l,onRemove:o,onSave:c,onCancel:i}){return e.jsxs(s.Dialog,{open:a,onOpenChange:n,children:[e.jsxs(s.DialogContent,{className:"max-w-4xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Join Configuration"}),e.jsx(s.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(ol,{joinPlan:r,availableDataSources:l,onSave:c,onCancel:i,onRemove:o})]}),t]})}function il({joins:t,baseEntityId:a,availableDataSources:n,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[t.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const l=[...t].sort((c,i)=>c.sequence-i.sequence),o=n.find(c=>c.name===a);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:o==null?void 0:o.type}),e.jsx("span",{className:"text-xs font-medium",children:o==null?void 0:o.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),l.map(c=>{const i=n.find(d=>d.name===c.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name})]})]},c.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",t.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...t].sort((l,o)=>l.sequence-o.sequence).map((l,o)=>{const c=n.find(d=>d.name===l.source.name),i=n.find(d=>d.name===l.target.name);return e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted p-2 text-left",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:o+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:l.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[c==null?void 0:c.name," → ",i==null?void 0:i.name]}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto text-xs",children:[l.joinKeyGroups.reduce((d,m)=>d+m.keys.length,0)," ","condition",l.joinKeyGroups.reduce((d,m)=>d+m.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 cl(){var h,u;const t=s.useEditorStore(p=>p.card),a=s.useEditorStore(p=>p.actions.updateCardConfig),n=((h=t==null?void 0:t.config)==null?void 0:h.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[r,l]=M.useState(!1),o=((u=t==null?void 0:t.dataSource)==null?void 0:u.selectedEntities)||[],c=p=>{a(t.id,{...t==null?void 0:t.config,joinPlan:p}),l(!1)},i=()=>{a(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},d=()=>{l(!1)},m=()=>{const p=[...n.joins].sort((x,S)=>x.sequence-S.sequence),j=n.baseEntity;if(!j.name)return"SELECT * FROM table -- Please select a base entity";let f=`SELECT *
418
+ FROM ${j.name}`;return p.forEach(x=>{const S=o.find(N=>N.name===x.target.name);if(!S)return;const g=x.joinKeyGroups.filter(N=>N.keys&&N.keys.length>0).map(N=>{const O=N.keys.filter(C=>{var D,b,k,w;return((D=C.source)==null?void 0:D.name)&&((b=C.target)==null?void 0:b.name)&&((k=C.source)==null?void 0:k.entityName)&&((w=C.target)==null?void 0:w.entityName)}).map(C=>`${C.source.entityName}.${C.source.name} ${C.operator} ${C.target.entityName}.${C.target.name}`);return O.length>1?`(${O.join(` ${N.operator} `)})`:O[0]}).filter(Boolean),v=g.length>1?g.join(" OR "):g[0]||"condition_here";f+=`
419
+ ${x.joinType} JOIN ${S.name}
420
+ ON ${v}`}),f};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:[n.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TooltipProvider$1,{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":n.joins.length>0,"text-gray-500":n.joins.length===0})}),"Join",n.joins.length>1?"s":""," (",n.joins.length,")"]})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(il,{joins:n.joins,baseEntityId:n.baseEntity.name,availableDataSources:o,generateSQLPreview:m})})]})}),e.jsx(Ys,{open:r,onOpenChange:l,joinPlan:n,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsx("div",{})})]}),n.joins.length===0&&e.jsx(Ys,{open:r,onOpenChange:l,joinPlan:n,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsxs(s.Button,{onClick:()=>l(!0),variant:"outline",className:"h-6 text-xs font-semibold",children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Configure Join"]})})]})})})}function dl({entity:t,title:a,maxDetails:n=10}){const l=s.getEntityDetails(t).slice(0,n),o=l.find(i=>i.label==="Description"),c=l.filter(i=>i.label==="Description"?!1:!["Connection","Database","Schema"].includes(i.label));return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:a||s.getDisplayName(t)}),o&&e.jsxs("div",{className:"border-t border-border pt-2",children:[e.jsx("div",{className:"mb-1 text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:o.value})]}),c.length>0&&e.jsx("div",{className:"space-y-0.5",children:c.map((i,d)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[i.label,":"]}),e.jsx("span",{className:"font-mono",children:i.value})]},d))})]})})}function ul({entities:t}){return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:[t.length," more entities"]}),e.jsx("div",{className:"space-y-1",children:t.map((a,n)=>{const r=s.getEntityDetails(a),l=r.find(c=>c.label==="Description"),o=r.filter(c=>c.label==="Description"?!1:!["Connection","Database","Schema"].includes(c.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(a)}),l&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:l.value})]}),o.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:o.map((c,i)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[c.label,":"]}),e.jsx("span",{className:"font-mono",children:c.value})]},i))})]},`remaining-${a.type}-${a.name}-${n}`)})})]})})}function ml({isVisible:t,onToggleVisibility:a}){const[n,r]=M.useState(!1),[l,o]=M.useState(!0),c=s.useEditorStore(h=>h.card.dataSource),{updateDataSource:i}=s.useEditorActions(),d={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},m={...d,...c,selectedEntities:(c==null?void 0:c.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden border-r bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[e.jsxs("div",{children:[e.jsx("div",{className:s.cn("p-4 px-6",{"pb-0":!l}),children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex cursor-pointer items-center gap-2",onClick:()=>o(!l),children:[l?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronRight,{className:"h-4 w-4"}),e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Data Source"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:a,title:"Hide Data Source Panel",children:e.jsx(s.EyeOff,{className:"h-3.5 w-3.5"})}),e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7",onClick:()=>r(!0),children:[e.jsx(s.Plus,{className:"mr-1 h-3.5 w-3.5"}),"Add"]})]})]})}),e.jsxs("div",{className:`overflow-hidden px-6 ${l?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[m.selectedEntities.length>0&&e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[m.selectedEntities.slice(0,3).map((h,u)=>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:p=>{p.stopPropagation();const j=m.selectedEntities.filter(f=>!(f.name===h.name&&f.type===h.type));i({...d,...c,selectedEntities:j})},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 hover:bg-red-100",children:e.jsx(s.X,{className:"h-2.5 w-2.5 group-hover:text-red-500"})})]})}),e.jsx(dl,{entity:h})]},`${h.type}-${h.name}-${u}`)),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(ul,{entities:m.selectedEntities.slice(3)})]})]})}),e.jsx(cl,{})]})]}),e.jsx(rl,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(c==null?void 0:c.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:r,dataSource:m,fallbackDataSource:d})]})}const ze=[{id:"table",icon:Je,label:"Table"},{id:"bar",icon:$e,label:"Bar Chart"},{id:"line",icon:Ge,label:"Line Chart"},{id:"area",icon:et,label:"Area Chart"},{id:"stackedBar",icon:ms,label:"Stacked Bar Chart"},{id:"combo",icon:Cn,label:"Combo Chart"},{id:"stackedLine",icon:ks,label:"Stacked Line Chart"},{id:"scatter",icon:xs,label:"Scatter Chart"},{id:"bubble",icon:ws,label:"Bubble Chart"},{id:"pie",icon:He,label:"Pie Chart"},{id:"doughnut",icon:ps,label:"Doughnut Chart"},{id:"funnel",icon:Ts,label:"Funnel Chart"},{id:"radar",icon:js,label:"Radar Chart"},{id:"polarArea",icon:Ss,label:"Polar Area Chart"},{id:"tornado",icon:ys,label:"Tornado Chart"},{id:"range",icon:hs,label:"Range Chart"},{id:"kpi",icon:Ds,label:"KPI"},{id:"text",icon:Zs,label:"Text"},{id:"map",icon:gs,label:"Map"}],Ms=t=>{const a=t.toLowerCase();for(const n of ze)if(n.id==="doughnut"){if(a.includes("doughnut")||a.includes("donut")){const r=n.icon;return M.createElement(r,{className:"h-4 w-4"})}}else if(a.includes(n.id.toLowerCase())){const r=n.icon;return M.createElement(r,{className:"h-4 w-4"})}return null},hl="chart-selector-standard-first";function xl(){const[t,a]=s.useLocalStorageState(hl,!0);return{standardFirst:t,updatePreference:a}}const Ks=({pluginVisual:t,index:a,onSelect:n})=>{const r=Ye(t.icon||""),l=t.name.charAt(0).toUpperCase(),o=Ms(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:n,className:"group flex items-center gap-2",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(r,{className:"h-4 w-4"}):o||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:l}),e.jsx("span",{children:t.name})]}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:"opacity-0 outline-none transition-opacity group-hover:opacity-100",children:e.jsx(s.Info,{className:"ml-1 h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"right",children:t.pluginName})]})]})},`${t.url}-${t.name}-${a}`)},Qs=["default","standardPlugin","customPlugin"];function pl({selectedChart:t,onChartChange:a}){var D;const[n,r]=M.useState([]),[l,o]=M.useState(!1),{data:c}=Cs();xl();const d=((D=s.useEditorStore(b=>b.card).customCardPreferences)==null?void 0:D.url)||"";s.useRemoteChartStore(d);const{setCardType:m,setCardPreferences:h,setIsDevMode:u}=s.useEditorStore(b=>b.actions),{setCardCustomCfg:p,setCustomCardPreferences:j,setQueryConfig:f}=s.useEditorActions(),[x,S]=s.useLocalStorageState("chart-section-active",null),g=M.useMemo(()=>x?[x,...Qs.filter(b=>b!==x)]:Qs,[x]);M.useEffect(()=>{(async()=>{if(c){const w=(await Promise.allSettled(c.plugins.map(async L=>{try{return(await s.loadManifest(L.value)).visuals.map(R=>({name:R.name,icon:R.icon,url:L.value,pluginName:L.label,pluginType:L.type,chartType:R.chartType,componentType:R.componentType}))}catch(T){return console.error(`Failed to load manifest for plugin ${L.label}`,T),[]}}))).filter(L=>L.status==="fulfilled").flatMap(L=>L.value);r(w)}})()},[c]);function v(b){p(null),h({}),m(b),["custom","text","map"].includes(b)&&(u(!0),f(void 0)),a(b),o(!1)}function N(b){p(null),h({}),m("custom"),j({type:"component",visualType:"single",url:b.url,componentName:b.name,icon:b.icon,pluginChartType:b.chartType}),f(void 0),a("custom"),o(!1)}const O=()=>{var k;if(t==="custom"){const w=s.useEditorStore.getState().card;return((k=w==null?void 0:w.customCardPreferences)==null?void 0:k.componentName)||"Custom Visual"}const b=ze.find(w=>w.id===t);return(b==null?void 0:b.label)||"Select chart type"},C=()=>{var k,w;if(t==="custom"){const L=s.useEditorStore.getState().card,T=(k=L==null?void 0:L.customCardPreferences)==null?void 0:k.icon,R=(w=L==null?void 0:L.customCardPreferences)==null?void 0:w.componentName;if(T&&R)return e.jsx(fl,{icon:T,componentName:R});if(R){const A=Ms(R);if(A)return A}return e.jsx(Ae,{className:"h-4 w-4"})}const b=ze.find(L=>L.id===t);if(b){const L=b.icon;return e.jsx(L,{className:"h-4 w-4"})}return e.jsx(Ae,{className:"h-4 w-4"})};return e.jsx("div",{className:"mb-6",children:e.jsxs(s.Popover,{open:l,onOpenChange:o,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":l,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[C(),e.jsx("span",{children:O()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[335px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search chart types..."}),e.jsxs(s.CommandList,{className:"mb-2 max-h-[300px]",children:[e.jsx(s.CommandEmpty,{children:"No chart type found."}),g.map(b=>{if(b==="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:x==="default",onCheckedChange:k=>S(k?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:ze.map(k=>{const w=k.icon;return e.jsx(s.CommandItem,{value:`${k.label} ${k.id} chart graph visualization`,onSelect:()=>v(k.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(w,{className:"h-4 w-4"}),e.jsx("span",{children:k.label})]})},k.id)})},"default");if(b==="standardPlugin"){const k=n.filter(w=>w.pluginType==="standard");return k.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:x==="standardPlugin",onCheckedChange:w=>S(w?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:k.filter(w=>w.componentType==="chart").map((w,L)=>e.jsx(Ks,{pluginVisual:w,index:L,onSelect:()=>N(w)},`${w.url}-${w.name}-${L}`))},"standardPlugin"):null}if(b==="customPlugin"){const k=n.filter(w=>w.pluginType==="custom");return k.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:x==="customPlugin",onCheckedChange:w=>S(w?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:k.map((w,L)=>e.jsx(Ks,{pluginVisual:w,index:L,onSelect:()=>N(w)},`${w.url}-${w.name}-${L}`))},"customPlugin"):null}return null})]})]})})]})})}const fl=({icon:t,componentName:a})=>{const n=Ye(),r=Ms(a);return n?e.jsx(n,{className:"h-4 w-4"}):r||e.jsx(Ae,{className:"h-4 w-4"})},Qt=({dataType:t})=>{const a=s.getDataType(t);return a==="string"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-blue-500 text-xs text-white",children:"T"}):a==="number"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-green-500 text-xs text-white",children:"#"}):a==="date"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-purple-500 text-xs text-white",children:"D"}):a==="boolean"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-orange-500 text-xs text-white",children:"B"}):e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-gray-500 text-xs text-white",children:"?"})};function gl({aliasTemplate:t,onAliasTemplateChange:a}){var d;const[n,r]=M.useState(t),[l,o]=M.useState(!1),c=(d=s.useEditorStore(m=>{var h;return(h=m.card.config)==null?void 0:h.pivotByColumns}))==null?void 0:d[0],i=c?`e.g. Min Sales in {{${c.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Input$1,{placeholder:i,value:l?n:t,onChange:m=>{r(m.target.value),o(!0)},onFocus:()=>o(!0),onPointerDown:m=>m.stopPropagation(),className:"h-8 text-xs",onKeyDown:m=>{m.key==="Enter"&&l&&n!==t?(a(n),o(!1)):m.key==="Escape"&&(r(t),o(!1))},"aria-label":"Edit alias template"}),l&&n!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{a(n),o(!1)},children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(t),o(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function jl({valueAliases:t,onValueAliasesChange:a}){const[n,r]=M.useState(null),[l,o]=M.useState(""),[c,i]=M.useState(""),d=()=>{a({...t,"":""})},m=u=>{const p={...t};delete p[u],a(p)},h=u=>{const p={...t};delete p[u],p[l]=c,a(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(([u,p],j)=>e.jsx("div",{className:"flex items-center gap-2",children:n===u?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:l,onChange:f=>o(f.target.value),className:"h-8 w-24 text-xs",onPointerDown:f=>f.stopPropagation(),onKeyDown:f=>{f.key==="Enter"?h(u):f.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:f=>i(f.target.value),className:"h-8 w-24 text-xs",onPointerDown:f=>f.stopPropagation(),onKeyDown:f=>{f.key==="Enter"?h(u):f.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:()=>h(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 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:u,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(u),o(u),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(u),o(u),i(p)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>m(u),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},u+j)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:d,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function Xs({value:t,onSave:a,placeholder:n="",type:r="text",className:l=""}){const[o,c]=M.useState(t??""),[i,d]=M.useState(!1);M.useEffect(()=>{c(t??"")},[t]);const m=()=>{a(o),d(!1)},h=()=>{c(t??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${l}`,children:[e.jsx(s.Input$1,{placeholder:n,type:r,value:i?o:t??"",onChange:u=>{c(u.target.value),d(!0)},onFocus:()=>d(!0),onClick:u=>u.stopPropagation(),className:"h-8 text-xs",onPointerDown:u=>u.stopPropagation(),onKeyDown:u=>{u.stopPropagation(),u.key==="Enter"&&i&&o!==t?m():u.key==="Escape"&&h()},"aria-label":n||"Edit field"}),i&&o!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:m,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:h,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function yl({field:t,zone:a,index:n,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:o=!1,cardType:c}){var Rs;const{attributes:i,listeners:d,setNodeRef:m,transform:h,transition:u,isDragging:p}=s.useSortable({id:t.id}),j=s.useEditorStore(X=>X.card),{updateLabel:f,handleAggregationChange:x,handleDateFormatChange:S,handleGranularityChange:g,handleAliasTemplateChange:v,handleValueAliasesChange:N,removeField:O,handleKpiComparisonTypeChange:C,handleKpiShowTrendlineChange:D,handleKpiTrendlineWindowChange:b,handleKpiTrendlineGranularityChange:k,handleKpiTargetValueChange:w}=As(j),[L,T]=M.useState(!1),[R,A]=M.useState(t.dateFormat||"YYYY-MM-DD"),[I,y]=M.useState(t.customFormat||""),[E,F]=M.useState(!!t.customFormat),[z,_]=M.useState(t.granularity||"day"),[P,Q]=M.useState(t.aliasTemplate||""),[Y,V]=M.useState(t.valueAliases||{}),q=X=>{X==="custom"?F(!0):(F(!1),A(X),a==="groupBy"&&S(n,X,""))},$=X=>{y(X),a==="groupBy"&&S(n,"custom",X)},U=X=>{_(X),a==="groupBy"&&g(n,X)},H=X=>{Q(X),a==="metrics"&&v(n,X)},W=X=>{V(X),a==="metrics"&&N(n,X)},G=X=>{f(a,n,X)},Z=()=>{O(a,n)},se={transform:s.CSS.Transform.toString(h),transition:u},ne=s.getDataType(t.dataType),ee=ne==="date",ae=c==="kpi",J=[{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..."}],B=!ae&&a!=="pivotBy",K=ae&&ee&&a==="groupBy",re=!ae&&ee&&a==="groupBy",he=ae&&ee&&a==="groupBy",je=ae&&a==="metrics"&&((Rs=j.config)==null?void 0:Rs.comparisonType)==="target",te=a==="metrics",le=()=>e.jsx("div",{onPointerDown:X=>{X.stopPropagation()},className:"cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),oe=()=>B?e.jsx(Xs,{value:t.label??"",onSave:G,placeholder:"Display label...",type:"text"}):null,Os=()=>K?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(s.Select,{value:z,onValueChange:U,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"}),e.jsx(s.SelectItem,{value:"quarter",children:"Quarter"}),e.jsx(s.SelectItem,{value:"year",children:"Year"})]})]})]}):null,en=()=>re?e.jsxs(e.Fragment,{children:[Os(),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:E?"custom":R,onValueChange:q,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:J.map(X=>e.jsx(s.SelectItem,{value:X.value,children:X.label},X.value))})]}),E&&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:I,onChange:X=>{X.stopPropagation(),$(X.target.value)},onClick:X=>X.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,sn=()=>{var X,xe,Te,Bs,Fs;return he?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:((X=j.config)==null?void 0:X.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:((xe=j.config)==null?void 0:xe.showTrendline)||!1,onCheckedChange:D})]})}),((Te=j.config)==null?void 0:Te.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:((Bs=j.config)==null?void 0:Bs.trendlineWindow)||30,onChange:an=>{const rn=parseInt(an.target.value)||30;b(rn)},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:((Fs=j.config)==null?void 0:Fs.trendlineGranularity)||"day",onValueChange:k,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},tn=()=>{var X,xe;return je?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(Xs,{value:((X=j.config)==null?void 0:X.targetValue)!==void 0&&((xe=j.config)==null?void 0:xe.targetValue)!==null?String(j.config.targetValue):"",onSave:Te=>{!isNaN(Number(Te))&&Te!==null?w(Number(Te)):w(0)},placeholder:"Enter target value...",type:"text"})]}):null},nn=()=>te?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:X=>{x(n,X)},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,{value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsx(Ht,{column:t}),o&&e.jsxs(e.Fragment,{children:[e.jsx(gl,{aliasTemplate:P,onAliasTemplateChange:H}),e.jsx(jl,{valueAliases:Y,onValueAliasesChange:W})]})]}):null;return e.jsxs("div",{ref:m,style:se,...i,...d,className:`group mx-auto flex w-full max-w-[300px] 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"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.GripVertical,{className:"h-3 w-3"}),e.jsx(Qt,{dataType:ne}),e.jsx(Es,{className:"max-w-[180px] flex-1 text-sm",children:t.label||t.name}),a!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:X=>{X.stopPropagation(),T(!L)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${L?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 group-hover:opacity-100",onClick:X=>{X.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const xe=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",xe),l(xe)},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 opacity-0 group-hover:opacity-100",onClick:X=>{X.stopPropagation(),Z()},children:e.jsx(s.X,{className:"h-3 w-3"})})]}),L&&e.jsxs("div",{className:"space-y-3",children:[le(),oe(),Os(),en(),sn(),tn(),nn()]})]})}function vl({concept:t}){const a=()=>{switch(t){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-100 text-xs font-medium dark:bg-blue-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/50 text-xs font-medium dark:bg-blue-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/30 text-xs font-medium dark:bg-blue-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/20 text-xs font-medium dark:bg-blue-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metrics = Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});default:return null}};return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(s.TooltipContent,{side:"right",align:"start",className:"p-3",children:a()})]})})}function Fe({zone:t,fields:a,label:n,placeholder:r,shouldShow:l,hasPivotColumns:o=!1}){const{isOver:c,setNodeRef:i}=s.useDroppable({id:t}),{updateSortByColumn:d}=s.useEditorActions(),m=s.useEditorStore(f=>f.card),h=s.useEditorStore(f=>f.card.type),u=a.length>0,p=(f,x)=>{var g;!((g=m.config)!=null&&g.sortByColumns)||m.config.sortByColumns.findIndex(v=>v.id===f)===-1||d(m.id,f,{direction:x})};if(t==="sortBy"&&l===!1)return null;const j=t!=="sortBy"&&h!=="kpi";return e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:n}),j&&e.jsx(vl,{concept:t})]}),e.jsx("div",{ref:i,className:`min-h-[60px] rounded-lg border-2 border-dashed p-3 transition-all ${c?"border-blue-500 bg-blue-50 dark:bg-blue-950":"border-muted-foreground/20 bg-muted/50"}`,children:a.length===0?e.jsxs("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),r]}):e.jsx(s.SortableContext,{items:a.map(f=>f.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map((f,x)=>{const g=f.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(yl,{field:f,zone:t,index:x,sortDirection:g,onSortDirectionChange:v=>p(f.id,v),hasPivotColumns:o,cardType:h})})},f.id)})})})})]})}function bl({groupByFields:t,pivotByFields:a,metricsFields:n,sortByFields:r}){const l=s.useEditorStore(u=>u.card),o=l==null?void 0:l.type,c=t.length>0||n.length>0,i=o!=="kpi",d=o!=="kpi"&&c,m=()=>o==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},h=()=>o==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Fe,{zone:"groupBy",fields:t,label:m().label,placeholder:m().placeholder}),i&&e.jsx(Fe,{zone:"pivotBy",fields:a,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(Fe,{zone:"metrics",fields:n,label:h().label,placeholder:h().placeholder,hasPivotColumns:a.length>0}),d&&e.jsx(Fe,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})}function Nl({selectedChart:t,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:o}){const c=s.useEditorStore(u=>u.showAIDialog),i=n.length>0||r.length>0||l.length>0,{setShowAIDialog:d}=s.useEditorActions(),m=s.useEditorStore(u=>u.card),{data:h}=s.useDashboardCardQuery(m);return e.jsxs("div",{className:"flex w-96 flex-col border-r bg-background",children:[e.jsxs("div",{className:"space-y-4 border-b px-6 py-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h2",{className:"font-semibold",children:"Chart Configuration"})}),e.jsx(pl,{selectedChart:t,onChartChange:a})]}),e.jsxs("div",{className:s.cn("flex justify-end gap-2 px-6 pt-6"),children:[e.jsx("div",{className:s.cn("invisible",{visible:i||h}),children:e.jsx(s.EditorClearButton,{})}),!c&&e.jsxs(s.Button,{onClick:()=>d(!c),variant:"outline",className:"h-8",size:"sm",children:[e.jsx(ta,{className:"mr-2 size-4"}),"AI"]})]}),e.jsxs(s.ScrollArea,{className:"flex-1 basis-0 px-6",children:[e.jsx(bl,{groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:o}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Cl({initialFilters:t,availableFields:a}={}){const[n,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=a||l||[],d={id:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},m=C=>{const D=b=>{if(b.id===C){const k=i[0]||d;return{...b,conditions:[...b.conditions,{id:`condition-${Date.now()}`,field:k,operator:"=",value:""}]}}return{...b,groups:b.groups.map(D)}};r(D(n))},h=C=>{const D=b=>{if(b.id===C){const k=i[0]||d;return{...b,groups:[...b.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:k,operator:"=",value:""}],groups:[]}]}}return{...b,groups:b.groups.map(D)}};r(D(n))},u=(C,D)=>{const b=k=>k.id===C?{...k,conditions:k.conditions.filter(w=>w.id!==D)}:{...k,groups:k.groups.map(b)};r(b(n))},p=(C,D)=>{const b=k=>k.id===C?{...k,groups:k.groups.filter(w=>w.id!==D)}:{...k,groups:k.groups.map(b)};r(b(n))},j=(C,D,b,k)=>{if(b==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const w=L=>L.id===C?{...L,conditions:L.conditions.map(T=>T.id===D?{...T,[b]:k}:T)}:{...L,groups:L.groups.map(w)};r(w(n))},f=(C,D,b)=>{const k=w=>w.id===C?{...w,conditions:w.conditions.map(L=>L.id===D?{...L,...b}:L)}:{...w,groups:w.groups.map(k)};r(k(n))},x=(C,D)=>{const b=k=>k.id===C?{...k,logicalOperator:D}:{...k,groups:k.groups.map(b)};r(b(n))},S=(C,D)=>{const b=k=>k.id===C?{...k,negate:D}:{...k,groups:k.groups.map(b)};r(b(n))},g=(C,D,b)=>{const k=w=>w.id===C?{...w,conditions:s.arrayMove(w.conditions,D,b)}:{...w,groups:w.groups.map(k)};r(k(n))},v=(C,D,b)=>{const k=w=>w.id===C?{...w,groups:s.arrayMove(w.groups,D,b)}:{...w,groups:w.groups.map(k)};r(k(n))},N=C=>{if(!C||C.conditions.length===0&&C.groups.length===0)return"-- No filters defined";const D=k=>{let w="";typeof k.field=="object"?w=k.field.entityName?`${k.field.entityName}.${k.field.name}`:k.field.name:w=String(k.field);const L=k.operator;let T=k.value;if(k.field.dataType==="string"&&!["in","not in"].includes(k.operator))typeof T=="string"?T=`'${T}'`:Array.isArray(T)&&(T=`'${T.join(", ")}'`);else if(k.field.dataType==="date")(typeof T=="string"||T instanceof Date)&&(T=`DATE('${T}')`);else if(["in","not in"].includes(k.operator)){let R=[];Array.isArray(T)?R=T.map(A=>typeof A=="string"?`'${A}'`:String(A)):typeof T=="string"?R=T.split(",").map(A=>{const I=A.trim();return k.field.dataType==="string"?`'${I}'`:I}):typeof T=="number"&&(R=[String(T)]),T=`(${R.join(", ")})`}switch(L){case"contains":return typeof T=="string"?`${w} LIKE '%${T.replace(/'/g,"")}'`:`${w} LIKE '%${String(T)}'`;case"startsWith":return typeof T=="string"?`${w} LIKE '${T.replace(/'/g,"")}%'`:`${w} LIKE '${String(T)}%'`;case"endsWith":return typeof T=="string"?`${w} LIKE '%${T.replace(/'/g,"")}'`:`${w} LIKE '%${String(T)}'`;default:return`${w} ${L} ${T}`}},b=k=>{const w=k.conditions.map(D),L=k.groups.map(I=>b(I)),T=[...w,...L].filter(Boolean);if(T.length===0)return"";const R=T.join(` ${k.logicalOperator} `),A=T.length>1?`(${R})`:R;return k.negate?`NOT ${A}`:A};return b(C)},O=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:i,isLoading:o,addCondition:m,addGroup:h,removeCondition:u,removeGroup:p,updateCondition:j,updateConditionFields:f,updateGroupOperator:x,updateGroupNegate:S,reorderConditions:g,reorderGroups:v,generateSQLPreview:N,hasAnyFilters:O}}function Sl({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const wl=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(Ln,{className:"h-3 w-3"});default:return e.jsx(s.Table,{className:"h-3 w-3"})}},Tl=t=>{if(t.qualifiedEntityName){const a=t.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function kl({value:t,onValueChange:a,availableFields:n,placeholder:r="Select field",className:l="w-64"}){const[o,c]=M.useState(!1),i=M.useMemo(()=>{const d={};return n.forEach(m=>{const h=Tl(m);d[h]||(d[h]={}),d[h][m.entityId]||(d[h][m.entityId]=[]),d[h][m.entityId].push(m)}),d},[n]);return e.jsxs(s.Popover,{modal:!0,open:o,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:s.cn("justify-between",!t&&"text-muted-foreground",l),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Sl,{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,m])=>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(m).map(([h,u])=>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:[wl(u[0].entityType),e.jsx("span",{children:u[0].entityName})]}),u.map((p,j)=>e.jsxs(s.CommandItem,{value:p.id,onSelect:()=>{a(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+j))]},`${d}-${h}`))},d))})]})})]})}function Ls(t){var f;const a=s.useEditorStore(x=>x.card),{authToken:n}=s.useSemaphorContext(),r=s.useEditorStore(x=>x.card.config),l=r==null?void 0:r.joinPlan,o={...t,alias:t.name,label:"value",role:"groupby"},c={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},i={...o,role:"sortby",direction:"asc"},d={joinPlan:l,groupByColumns:[o],metricColumns:[c],sortByColumns:[i]},m=((f=a.dataSource)==null?void 0:f.connectionId)||a.connectionId,{data:h,isPending:u,error:p}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(n==null?void 0:n.accessToken)||"",{connection_id:m,cardConfig:d,cardDataSource:a.dataSource})}catch(x){console.log(t),console.error("error",x)}},enabled:!!m,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((h==null?void 0:h.records)||[]).map(x=>({label:x[t.name]||"BLANK",value:x[t.name]||"BLANK",count:(x==null?void 0:x.count)||0})),isPending:u,error:p}}function Dl({field:t,selected:a,onChange:n,placeholder:r="Select items...",className:l}){const[o,c]=ye.useState(!1),{filterValues:i}=Ls(t),d=h=>{n(a.filter(u=>u!==h))},m=h=>{a.includes(h)?n(a.filter(u=>u!==h)):n([...a,h])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open:o,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(h=>{const u=i.find(p=>p.value===h);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[u==null?void 0:u.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(h)},onMouseDown:p=>{p.preventDefault(),p.stopPropagation()},onClick:p=>{p.stopPropagation(),d(h)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},h)}):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((h,u)=>e.jsxs(s.CommandItem,{onSelect:()=>m(h.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",a.includes(h.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:h.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:h.count})]})]},h.value+u))})]})]})})]})})}const Xt=t=>{if(!t)return 0;let a=t.conditions.length;return t.groups.forEach(n=>{a+=Xt(n)}),a};function El({field:t,value:a,onChange:n,placeholder:r="Select value...",className:l}){const{filterValues:o,isPending:c,error:i}=Ls(t);return c?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):i?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:a,onValueChange:n,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:a})}),e.jsx(s.SelectContent,{children:o.map((d,m)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+m))})]})}const Il=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in"],Al=["=","!=","contains","startsWith","endsWith","in","not in"],Ml=["=","!=",">",">=","<","<=","in","not in"],Ll=["=","!="],Ol=["=","!=",">",">=","<","<=","in","not in"];function Rl(t){switch(t){case"string":return Al;case"number":return Ml;case"boolean":return Ll;case"date":return Ol;default:return Il}}function Zt({condition:t,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:o,onUpdateGroupOperator:c,availableFields:i,updateConditionFields:d}){const{attributes:m,listeners:h,setNodeRef:u,transform:p,transition:j,isDragging:f}=s.useSortable({id:t.id}),{isPending:x,error:S}=Ls(t.field),g={transform:s.CSS.Transform.toString(p),transition:j};return e.jsxs("div",{ref:u,style:g,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${f?"z-50 opacity-50":""}`,children:[e.jsx("div",{...m,...h,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(s.Select,{value:r,onValueChange:v=>c(n,v),children:[e.jsx(s.SelectTrigger,{className:"w-24",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(kl,{value:t.field,onValueChange:v=>{d(n,t.id,{field:v,value:""})},availableFields:i,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:v=>{v==="in"||v==="not in"?d(n,t.id,{operator:v,value:[]}):d(n,t.id,{operator:v,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-28",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Rl(s.getDataType(t.field.dataType)).map(v=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:v,children:v},v))})]}),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..."]}):S?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(Dl,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(v=>typeof v=="string")?t.value:[],onChange:v=>d(n,t.id,{value:v}),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:v=>d(n,t.id,{value:v.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(El,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:v=>d(n,t.id,{value:v}),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:v=>d(n,t.id,{value:v==="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"})]})]}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:v=>l(n,t.id,"value",v.target.value),className:"flex-1",placeholder:t.operator==="in"||t.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>o(n,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function Bl({group:t,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:o,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onReorderConditions:m,onReorderGroups:h,onAddCondition:u,onAddGroup:p,availableFields:j,renderFilterGroup:f,updateConditionFields:x}){const{attributes:S,listeners:g,setNodeRef:v,transform:N,transition:O,isDragging:C}=s.useSortable({id:t.id}),D={transform:s.CSS.Transform.toString(N),transition:O},b=w=>{const{active:L,over:T}=w;if(T&&L.id!==T.id){const R=t.conditions.findIndex(I=>I.id===L.id),A=t.conditions.findIndex(I=>I.id===T.id);R!==-1&&A!==-1&&m(t.id,R,A)}},k=w=>{const{active:L,over:T}=w;if(T&&L.id!==T.id&&n){const R=t.groups.findIndex(I=>I.id===L.id),A=t.groups.findIndex(I=>I.id===T.id);R!==-1&&A!==-1&&h(n,R,A)}};return e.jsxs("div",{ref:v,style:D,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${C?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...S,...g,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:w=>r(t.id,w),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>n&&o(n,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:b,children:e.jsx(s.SortableContext,{items:t.conditions.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((w,L)=>e.jsx(Zt,{condition:w,index:L,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:j,updateConditionFields:x},w.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:k,children:e.jsx(s.SortableContext,{items:t.groups.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(w=>f(w,a+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>u(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 Fl({filters:t,availableFields:a,onSave:n,onClearAll:r,onCancel:l}){const{currentFilters:o,availableFields:c,isLoading:i,addCondition:d,addGroup:m,removeCondition:h,removeGroup:u,updateCondition:p,updateConditionFields:j,updateGroupOperator:f,updateGroupNegate:x,reorderConditions:S,reorderGroups:g,generateSQLPreview:v,hasAnyFilters:N,setCurrentFilters:O}=Cl({initialFilters:t,availableFields:a}),C=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[D,b]=M.useState(!1),k=(T,R,A)=>{const I=y=>y.id===T?{...y,conditions:y.conditions.map(E=>E.id===R?{...E,field:A,dataType:A.dataType}:E)}:{...y,groups:y.groups.map(I)};O(I(o))},w=(T,R=0,A)=>R===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:I=>{const{active:y,over:E}=I;if(E&&y.id!==E.id){const F=T.conditions.findIndex(_=>_.id===y.id),z=T.conditions.findIndex(_=>_.id===E.id);F!==-1&&z!==-1&&S(T.id,F,z)}},children:e.jsx(s.SortableContext,{items:T.conditions.map(I=>I.id),strategy:s.verticalListSortingStrategy,children:T.conditions.map((I,y)=>e.jsx(Zt,{condition:I,index:y,groupId:T.id,groupLogicalOperator:T.logicalOperator,onUpdateCondition:p,onUpdateField:k,onRemoveCondition:h,onUpdateGroupOperator:f,availableFields:c,updateConditionFields:j},I.id))})}),e.jsx(s.DndContext,{sensors:C,collisionDetection:s.closestCenter,onDragEnd:I=>{const{active:y,over:E}=I;if(E&&y.id!==E.id){const F=T.groups.findIndex(_=>_.id===y.id),z=T.groups.findIndex(_=>_.id===E.id);F!==-1&&z!==-1&&g(T.id,F,z)}},children:e.jsx(s.SortableContext,{items:T.groups.map(I=>I.id),strategy:s.verticalListSortingStrategy,children:T.groups.map(I=>w(I,R+1,T.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(T.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:()=>m(T.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},T.id):e.jsx(Bl,{group:T,depth:R,parentGroupId:A,onUpdateGroupOperator:f,onUpdateGroupNegate:x,onRemoveGroup:u,onUpdateCondition:p,onUpdateField:k,onRemoveCondition:h,onReorderConditions:S,onReorderGroups:g,onAddCondition:d,onAddGroup:m,availableFields:c,renderFilterGroup:w,updateConditionFields:j},T.id),L=Xt(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..."})]}):w(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.Checkbox,{id:"advanced-mode",checked:D,onCheckedChange:T=>b(!!T)}),e.jsx("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)"})]})}),N&&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:v(o)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:l,children:"Cancel"}),L>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>n(N?o:null),children:"Apply Filters"})]})]})}function zl({cardId:t,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:l,isOpen:o,onOpenChange:c}){const i=m=>{n(t,m),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:m=>{m.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(Fl,{filters:a,availableFields:l,onSave:i,onCancel:()=>c(!1),onClearAll:d})]})]})}function Pl({activeCardId:t,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var j;const[l,o]=M.useState(null),c=s.useEditorStore(f=>f.card),i=(j=c==null?void 0:c.config)==null?void 0:j.joinPlan,d=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],m=M.useCallback(f=>f.startsWith("card-")?null:f.startsWith("source-")||a.find(x=>x.id===f)?"source":n("groupBy").find(x=>x.id===f)?"groupBy":n("metrics").find(x=>x.id===f)?"metrics":n("pivotBy").find(x=>x.id===f)?"pivotBy":n("sortBy").find(x=>x.id===f)?"sortBy":null,[a,n]),h=M.useCallback(f=>{o(f.active.id)},[]),u=M.useCallback(f=>{const{active:x,over:S}=f;if(!S||!t){o(null);return}const g=x.id,v=S.id,N=m(g),O=m(v)||v;if(N==="source"&&O==="sortBy"){o(null);return}if(N==="source"&&O!=="source"&&O!=="sortBy"){const C=[...a].find(w=>w.id===g);if(!C){o(null);return}const D=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(D.length>0){const w=D[0].qualifiedEntityName;if(!w){o(null);return}if(w!==C.qualifiedEntityName&&C.qualifiedEntityName)if(i){if(!Kt(w,C.qualifiedEntityName,i)){ds(),o(null);return}}else{ds(),o(null);return}}const b=n(O);if(us(C,b)){o(null);return}const k=cs(C,O);o(null),r(O,[...b,k]);return}if(N&&O&&N!=="source"&&O!=="source"&&N!==O){const C=n(N),D=n(O),b=C.find(L=>L.id===g);if(!b){o(null);return}const k=cs(b,O);if(o(null),O==="sortBy"){if(N==="pivotBy"){o(null);return}us(b,D)||r(O,[...D,k]);return}const w=C.filter(L=>L.id!==g);r(N,w),r(O,[...D,k]);return}if(N&&O&&N===O&&N!=="source"){const C=n(N),D=C.findIndex(k=>k.id===g),b=C.findIndex(k=>k.id===v);if(D!==b){const k=s.arrayMove(C,D,b);r(N,k)}}o(null)},[t,a,n,r,m,i]),p=l?d.find(f=>f.id===l):null;return{activeId:l,activeField:p,handleDragStart:h,handleDragEnd:u}}function _l({activeView:t,onViewChange:a}){const n=s.useEditorStore(l=>l.card),{errorMessage:r}=s.useDashboardCardQuery(n);return e.jsx(s.Tabs,{value:t,onValueChange:l=>a(l),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-2 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),n.type!=="kpi"&&e.jsx(s.TabsTrigger,{value:"sql",className:s.cn("rounded-md transition data-[state=active]:bg-muted",r&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:r?"Error":"Query"})]})})}const Vl=[{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 Ul(){var d,m;const t=s.useEditorStore(h=>h.card),{updateRowLimit:a}=s.useEditorActions(),[n,r]=M.useState(!1),[l,o]=M.useState(""),c=h=>{if(h==="custom"){r(!0);return}r(!1),a(t.id,parseInt(h))},i=h=>{const u=h.target.value;o(u),u&&!isNaN(parseInt(u))&&a(t.id,parseInt(u))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(s.Input,{type:"number",value:l,onChange:i,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((m=(d=t.config)==null?void 0:d.rowLimit)==null?void 0:m.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:Vl.map(h=>e.jsx(s.SelectItem,{value:h.value,children:h.label},h.value))})]})})}function ql({isOpen:t,onClose:a}){const n=jt(a,{enabled:t}),r=s.useEditorStore(h=>{var u;return((u=h.card.customCardPreferences)==null?void 0:u.url)||""}),l=s.useEditorStore(h=>h.card),o=s.useEditorStore(h=>{var u;return((u=h.card.customCardPreferences)==null?void 0:u.pluginChartType)||""}),c=s.useEditorStore(h=>{var u;return((u=h.card.customCardPreferences)==null?void 0:u.settings)||{}}),{data:i}=s.useDashboardCardQuery(l),{getCard:d}=s.useCustomVisual(r),m=M.useMemo(()=>!r||r.trim()===""?null:d("Chart Settings"),[d,r]);return e.jsx("div",{ref:n,className:s.cn("absolute right-0 top-0 z-40 h-full w-[350px] border-l bg-background shadow-lg transition-transform duration-300",t?"translate-x-0":"translate-x-full"),style:{willChange:"transform"},tabIndex:t?0:-1,"aria-hidden":!t,children:e.jsxs("div",{className:"flex h-full flex-col p-4 px-5 pr-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Chart Settings"}),e.jsx(s.IconButton,{"aria-label":"Hide Chart Settings",tooltip:"Hide",onClick:a,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:m&&e.jsx(M.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(m,{chartData:(i==null?void 0:i.records)||[],chartType:o,settings:c})})})]})})}function $l({activeView:t,onViewChange:a,showDebug:n,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:d,activeCard:m,columns:h,columnsLoading:u,columnsError:p}){var R;const j=s.useEditorStore(A=>A.card),f=s.useDashboardStore(A=>A.filterValues),{updateCardConfig:x}=s.useEditorActions(),S=s.useEditorStore(A=>A.showAIDialog),[g,v]=M.useState(!1),N=s.useEditorStore(A=>{var I;return((I=A.card.customCardPreferences)==null?void 0:I.url)&&A.card.type==="custom"}),{data:O,errorMessage:C,isPending:D,isLoading:b,isFetching:k}=s.useDashboardCardQuery(m);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(j.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(f||{},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(m.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",h.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:u?"Loading...":p?"Error loading columns":JSON.stringify(h.slice(0,5),null,2)})]})]})})}const L=A=>{if(!j.config)return;if(!A.length){x(j.id,{...j.config,sortByColumns:[]});return}const I=j.config,y=A.map(({id:E,desc:F})=>{var Q,Y;const z=(Q=I.metricColumns)==null?void 0:Q.find(V=>V.label===E),_=(Y=I.groupByColumns)==null?void 0:Y.find(V=>V.label===E),P=z||_;return P?{id:Wt("sortBy",P),name:P.name,dataType:P.dataType,label:P.label,qualifiedEntityName:P.qualifiedEntityName,entityId:P.entityId,entityName:P.entityName,entityType:P.entityType,role:"sortby",direction:F?"desc":"asc"}:null}).filter(E=>E!==null);x(j.id,{...I,sortByColumns:y})},T=M.useMemo(()=>{var A,I;return(I=(A=j.config)==null?void 0:A.sortByColumns)==null?void 0:I.map(y=>({id:y.label,desc:y.direction==="desc"}))},[(R=j.config)==null?void 0:R.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[e.jsx(s.ExplorerHeader,{showDebug:n,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:d}),n&&w(),e.jsx(s.Separator,{}),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"&&S&&e.jsx(zt,{variant:"outline"}),e.jsx(_l,{activeView:t,onViewChange:a}),i&&e.jsxs(s.IconButton,{tooltip:"Card Filters",className:"h-8 gap-1",onClick:i,children:[e.jsx(s.Filter,{className:"h-3.5 w-3.5"}),d>0&&e.jsx("span",{className:"ml-1 rounded-full bg-blue-100 px-1.5 py-0.5 text-xs text-blue-800",children:d})]}),e.jsx("div",{className:"ml-2",children:e.jsx(Ul,{})}),S&&e.jsx(s.EditorClearButton,{})]}),e.jsx("div",{className:s.cn("flex grow items-center justify-end"),children:t==="chart"&&e.jsx(Pt,{})})]}),!g&&N&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>v(!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(Zn,{className:"size-4"})}),e.jsxs("div",{className:"flex grow flex-col",children:[t==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:b||k?e.jsx("div",{className:"m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx(_t,{})}),t==="table"&&(O==null?void 0:O.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:[(b||k)&&e.jsx("div",{className:"absolute flex h-full w-full items-center justify-between",children:e.jsx("div",{className:"z-10 m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}),e.jsx(s.TableVisual,{card:m,data:O==null?void 0:O.records,onSortChange:L,sortState:T})]}),t==="sql"&&e.jsx("div",{className:"p-6",children:e.jsxs("div",{className:"rounded-md border bg-background p-4",children:[(O==null?void 0:O.sql)&&e.jsx("h3",{className:"mb-3 text-sm font-medium",children:"Generated SQL Query"}),e.jsx(At,{sql:O==null?void 0:O.sql,error:C})]})})]}),e.jsx(ql,{isOpen:g,onClose:()=>v(!1)})]})]})}function Gl({activeField:t}){const[a,n]=M.useState(!0);return M.useEffect(()=>{t&&n(!0)},[t]),t?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${a?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(s.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(Qt,{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 Hl=()=>{const t=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||t.apply(console,r)};const a=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},n=r=>{var l;if((l=r.reason)!=null&&l.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=t,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function Jl(){var V,q;const[t,a]=M.useState("chart"),[n,r]=M.useState(!1),[l,o]=M.useState(!1),[c,i]=M.useState(!0),d=s.useEditorStore($=>$.showAIDialog),m=s.useDashboardStore($=>$.isVisualEditing),{setCardType:h}=s.useEditorActions(),u=s.useEditorStore($=>$.card.type);M.useEffect(()=>Hl(),[]);const p=()=>{console.log("Accept clicked - would save/apply current configuration")},j=()=>{console.log("Clear clicked - would reset all configurations")},f=()=>{console.log("Advanced mode toggled")},x=()=>{o(!0)},S=$=>{h($)},g=s.useEditorStore($=>$.frame),v=s.useEditorStore($=>$.card);s.useEditorStore($=>$.activeTabCardId),s.useEditorStore($=>$.actions.getAvailableFields);const{addCard:N,removeCard:O,updateCard:C,setActiveCard:D,updateFilters:b}=s.useEditorActions(),{columns:k=[],isLoading:w,error:L}=s.useColumns(),T=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),R=v,{getFieldsForContainer:A,setFieldsForContainer:I}=As(R),{activeField:y,handleDragStart:E,handleDragEnd:F}=Pl({activeCardId:g.activeCardId,sourceFields:k,getFieldsForContainer:A,setFieldsForContainer:I}),z=($,U)=>{U&&b($,U)},_=$=>{var U;C($,{config:{...(U=g.cards.find(H=>H.id===$))==null?void 0:U.config,filters:void 0}})},P=k,Q=$=>{if(!$)return 0;let U=$.conditions.length;return $.groups.forEach(H=>{U+=Q(H)}),U},Y=Q(((V=R==null?void 0:R.config)==null?void 0:V.filters)||null);return e.jsxs(s.DndContext,{sensors:T,collisionDetection:s.closestCenter,onDragStart:E,onDragEnd:F,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(ml,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(Nl,{selectedChart:u,onChartChange:S,groupByFields:A("groupBy"),pivotByFields:A("pivotBy"),metricsFields:A("metrics"),sortByFields:A("sortBy")}),e.jsx($l,{selectedChart:u,activeView:t,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onAccept:p,onClear:j,onAdvancedToggle:f,onFiltersClick:x,filterCount:Y,activeCard:R,dataSourceState:v.dataSource||s.EMPTY_DATA_SOURCE,columns:k,columnsLoading:w,columnsError:L,getFieldsForContainer:A,cards:g.cards,activeCardId:g.activeCardId,addCard:N,setActiveCard:D})]}),!c&&m&&e.jsx("div",{className:"fixed bottom-4 left-4 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"})})})]}),R&&e.jsx(zl,{cardId:R.id,filters:((q=R.config)==null?void 0:q.filters)||null,onFiltersChange:z,onClearFilters:_,availableFields:P,isOpen:l,onOpenChange:o}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Gl,{activeField:y||null})})]})}function Wl({authToken:t,onSave:a,onClose:n}){const r=M.useRef(null),l=s.useEditorStore(v=>v.showAIDialog),o=s.useEditorStore(v=>v.isDevMode),{setAuthToken:c}=s.useDashboardActions(),{setShowAIDialog:i,setOnSave:d,setOnClose:m}=s.useEditorActions(),{handleDragOver:h,handleDragEnd:u,handleDragStart:p,handleDragCancel:j,sensors:f}=za();M.useEffect(()=>{a&&d(a),n&&m(n)},[a,d,n,m]),M.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),M.useEffect(()=>{var v,N;l?((v=r.current)==null||v.resize(40),i(!0)):(i(!1),(N=r.current)==null||N.resize(0))},[l,i]);function x(v){v<1?i(!1):l||i(!0)}function S(){return e.jsxs(e.Fragment,{children:[e.jsx(Et,{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(Xr,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(Ws,{})})]})]})}function g(){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(Jl,{})}),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:f,onDragStart:p,onDragEnd:u,onDragOver:h,onDragCancel:j,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:S()})}):g()})}function Yl(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:a}=s.useDashboardStore(c=>c.actions),n=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function l(c){t&&(r(t,c),a(!1))}function o(){a(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!n}),children:e.jsx(Wl,{onSave:l,onClose:o})})}function Kl(){const t=s.useEditorStore(o=>o.selectedDatabaseName),a=s.useEditorStore(o=>o.selectedTableName),n=s.useDashboardStore(o=>o.dashboard.filters)||[],{columns:r}=s.useEditorAside(),{assignFilter:l}=$t();return e.jsx(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(o=>{const c=n==null?void 0:n.find(i=>i.column===s.fmt(o.column_name)&&i.table===a&&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(bs,{column:o}),e.jsx("span",{children:o.column_name})]})},o.column_name)})})}function Ql(){s.useDashboardStore(a=>a.showFilters);const t=s.useDashboardStore(a=>a.actions.setShowFilters);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:e.jsx(Et,{type:"filter",ColumnsComponent:()=>e.jsx(Kl,{})})})]})}function Xl(){const t=s.useDashboardStore(r=>r.dashboard.filters),a=s.useDashboardStore(r=>r.theme),n=t==null?void 0:t.filter(r=>r.hide);return n!=null&&n.length?e.jsx("div",{className:s.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":a==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":a==="dark"}),children:n==null?void 0:n.map(r=>e.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[e.jsx(s.FilterHeader,{filter:r}),e.jsx(s.FilterComponent,{filter:r})]},r.id))}):null}function Zl(){const t=s.useDashboardStore(r=>r.showFilters),a=s.useDashboardStore(r=>r.isVisualEditing),n=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":a,"flex grow overflow-auto":!a}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[n&&e.jsx(Xl,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Ql,{})})]})}function eo(){const t=s.useDashboardStore(l=>l.dashboard),a=s.useDashboardStore(l=>l.actions.setDashboard),n=s.useDashboardStore(l=>l.showDashboardJSON),r=s.useDashboardStore(l=>l.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!n}),children:[e.jsxs(s.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(s.de,{onChange:l=>{if(l)try{JSON.parse(l),a(JSON.parse(l))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(t,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function so({showControls:t=!1,showFooter:a=!0,...n}){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:n,children:[e.jsx(s.$e,{}),e.jsxs(s.UXProvider,{children:[e.jsx(eo,{}),e.jsxs("main",{className:"flex h-full flex-col",children:[t&&e.jsx(La,{}),e.jsxs(s.DashboardPanel,{...n,children:[e.jsx(Yl,{}),e.jsx(Zl,{})]})]})]})]})})}exports.DashboardPlus=so;exports.ResourceManagementPanel=kt;exports.ScheduleDashboard=mt;exports.SelectComponent=ke;exports.cleanCard=ct;exports.downloadPdf=ut;exports.getDashbaordStateWithoutData=vs;