react-semaphor 0.0.569 → 0.0.570
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{dashboard-plus-Ckqg8oKf.js → dashboard-plus-BkxAX-Ul.js} +3157 -3021
- package/dist/chunks/{dashboard-plus-YJK5a-bc.js → dashboard-plus-Dno0l45j.js} +74 -59
- package/dist/chunks/{index-D320FIng.js → index-D7PtTugN.js} +89 -89
- package/dist/chunks/{index-DFXc_ZKX.js → index-DfutYe81.js} +7723 -7723
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +2 -2
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +1 -1
- package/package.json +1 -1
|
@@ -1,64 +1,64 @@
|
|
|
1
|
-
"use strict";var lt=t=>{throw TypeError(t)};var fs=(t,a,n)=>a.has(t)||lt("Cannot "+n);var re=(t,a,n)=>(fs(t,a,"read from private field"),n?n.call(t):a.get(t)),Fe=(t,a,n)=>a.has(t)?lt("Cannot add the same private member more than once"):a instanceof WeakSet?a.add(t):a.set(t,n),Pe=(t,a,n,r)=>(fs(t,a,"write to private field"),r?r.call(t,n):a.set(t,n),n),ze=(t,a,n)=>(fs(t,a,"access private method"),n);const e=require("react/jsx-runtime"),s=require("./index-
|
|
1
|
+
"use strict";var lt=t=>{throw TypeError(t)};var fs=(t,a,n)=>a.has(t)||lt("Cannot "+n);var re=(t,a,n)=>(fs(t,a,"read from private field"),n?n.call(t):a.get(t)),Fe=(t,a,n)=>a.has(t)?lt("Cannot add the same private member more than once"):a instanceof WeakSet?a.add(t):a.set(t,n),Pe=(t,a,n,r)=>(fs(t,a,"write to private field"),r?r.call(t,n):a.set(t,n),n),ze=(t,a,n)=>(fs(t,a,"access private method"),n);const e=require("react/jsx-runtime"),s=require("./index-D7PtTugN.js"),A=require("react");require("react-dom");function zn(t){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(a,n,r.get?r:{enumerable:!0,get:()=>t[n]})}}return a.default=t,Object.freeze(a)}const ue=zn(A);var Se,we,de,ye,be,ss,ws,kt,Vn=(kt=class extends s.Subscribable{constructor(a,n){super();Fe(this,be);Fe(this,Se);Fe(this,we);Fe(this,de);Fe(this,ye);Pe(this,Se,a),this.setOptions(n),this.bindMethods(),ze(this,be,ss).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(a){var r;const n=this.options;this.options=re(this,Se).defaultMutationOptions(a),s.shallowEqualObjects(this.options,n)||re(this,Se).getMutationCache().notify({type:"observerOptionsUpdated",mutation:re(this,de),observer:this}),n!=null&&n.mutationKey&&this.options.mutationKey&&s.hashKey(n.mutationKey)!==s.hashKey(this.options.mutationKey)?this.reset():((r=re(this,de))==null?void 0:r.state.status)==="pending"&&re(this,de).setOptions(this.options)}onUnsubscribe(){var a;this.hasListeners()||(a=re(this,de))==null||a.removeObserver(this)}onMutationUpdate(a){ze(this,be,ss).call(this),ze(this,be,ws).call(this,a)}getCurrentResult(){return re(this,we)}reset(){var a;(a=re(this,de))==null||a.removeObserver(this),Pe(this,de,void 0),ze(this,be,ss).call(this),ze(this,be,ws).call(this)}mutate(a,n){var r;return Pe(this,ye,n),(r=re(this,de))==null||r.removeObserver(this),Pe(this,de,re(this,Se).getMutationCache().build(re(this,Se),this.options)),re(this,de).addObserver(this),re(this,de).execute(a)}},Se=new WeakMap,we=new WeakMap,de=new WeakMap,ye=new WeakMap,be=new WeakSet,ss=function(){var n;const a=((n=re(this,de))==null?void 0:n.state)??s.getDefaultState();Pe(this,we,{...a,isPending:a.status==="pending",isSuccess:a.status==="success",isError:a.status==="error",isIdle:a.status==="idle",mutate:this.mutate,reset:this.reset})},ws=function(a){s.notifyManager.batch(()=>{var n,r,l,o,c,i,d,m;if(re(this,ye)&&this.hasListeners()){const u=re(this,we).variables,h=re(this,we).context;(a==null?void 0:a.type)==="success"?((r=(n=re(this,ye)).onSuccess)==null||r.call(n,a.data,u,h),(o=(l=re(this,ye)).onSettled)==null||o.call(l,a.data,null,u,h)):(a==null?void 0:a.type)==="error"&&((i=(c=re(this,ye)).onError)==null||i.call(c,a.error,u,h),(m=(d=re(this,ye)).onSettled)==null||m.call(d,void 0,a.error,u,h))}this.listeners.forEach(u=>{u(re(this,we))})})},kt);function Oe(t,a){const n=s.useQueryClient(),[r]=ue.useState(()=>new Vn(n,t));ue.useEffect(()=>{r.setOptions(t)},[r,t]);const l=ue.useSyncExternalStore(ue.useCallback(c=>r.subscribe(s.notifyManager.batchCalls(c)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),o=ue.useCallback((c,i)=>{r.mutate(c,i).catch(s.noop)},[r]);if(l.error&&s.shouldThrowError(r.options.throwOnError,[l.error]))throw l.error;return{...l,mutate:o,mutateAsync:l.mutate}}/**
|
|
2
2
|
* @license lucide-react v0.453.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
5
5
|
* See the LICENSE file in the root directory of this source tree.
|
|
6
|
-
*/const
|
|
6
|
+
*/const _n=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
|
|
11
|
+
*/const Un=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
|
|
16
|
+
*/const $n=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
|
|
21
|
+
*/const qn=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
|
|
26
|
+
*/const Yn=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
|
|
31
|
+
*/const Gn=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
|
|
36
|
+
*/const Hn=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
|
|
41
|
+
*/const Kn=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
|
|
46
|
+
*/const Qn=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
|
|
51
|
+
*/const Wn=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
|
|
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
|
|
61
|
+
*/const Xn=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
|
|
71
|
+
*/const Zn=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
|
|
76
|
+
*/const ea=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.
|
|
@@ -108,12 +108,12 @@
|
|
|
108
108
|
*
|
|
109
109
|
* This source code is licensed under the ISC license.
|
|
110
110
|
* See the LICENSE file in the root directory of this source tree.
|
|
111
|
-
*/const
|
|
111
|
+
*/const sa=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.
|
|
115
115
|
* See the LICENSE file in the root directory of this source tree.
|
|
116
|
-
*/const
|
|
116
|
+
*/const Os=s.createLucideIcon("ChartNoAxesGantt",[["path",{d:"M8 6h10",key:"9lnwnk"}],["path",{d:"M6 12h9",key:"1g9pqf"}],["path",{d:"M11 18h7",key:"c8dzvl"}]]);/**
|
|
117
117
|
* @license lucide-react v0.453.0 - ISC
|
|
118
118
|
*
|
|
119
119
|
* This source code is licensed under the ISC license.
|
|
@@ -123,12 +123,12 @@
|
|
|
123
123
|
*
|
|
124
124
|
* This source code is licensed under the ISC license.
|
|
125
125
|
* See the LICENSE file in the root directory of this source tree.
|
|
126
|
-
*/const
|
|
126
|
+
*/const Rs=s.createLucideIcon("ChartScatter",[["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}],["circle",{cx:"18.5",cy:"5.5",r:".5",fill:"currentColor",key:"lysivs"}],["circle",{cx:"11.5",cy:"11.5",r:".5",fill:"currentColor",key:"byv1b8"}],["circle",{cx:"7.5",cy:"16.5",r:".5",fill:"currentColor",key:"nkw3mc"}],["circle",{cx:"17.5",cy:"14.5",r:".5",fill:"currentColor",key:"1gjh6j"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}]]);/**
|
|
127
127
|
* @license lucide-react v0.453.0 - ISC
|
|
128
128
|
*
|
|
129
129
|
* This source code is licensed under the ISC license.
|
|
130
130
|
* See the LICENSE file in the root directory of this source tree.
|
|
131
|
-
*/const
|
|
131
|
+
*/const ta=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.
|
|
@@ -143,27 +143,27 @@
|
|
|
143
143
|
*
|
|
144
144
|
* This source code is licensed under the ISC license.
|
|
145
145
|
* See the LICENSE file in the root directory of this source tree.
|
|
146
|
-
*/const
|
|
146
|
+
*/const na=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
|
|
151
|
+
*/const aa=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
|
|
156
|
+
*/const ra=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
|
|
161
|
+
*/const la=s.createLucideIcon("DatabaseZap",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 15 21.84",key:"14ibmq"}],["path",{d:"M21 5V8",key:"1marbg"}],["path",{d:"M21 12L18 17H22L19 22",key:"zafso"}],["path",{d:"M3 12A9 3 0 0 0 14.59 14.87",key:"1y4wr8"}]]);/**
|
|
162
162
|
* @license lucide-react v0.453.0 - ISC
|
|
163
163
|
*
|
|
164
164
|
* This source code is licensed under the ISC license.
|
|
165
165
|
* See the LICENSE file in the root directory of this source tree.
|
|
166
|
-
*/const
|
|
166
|
+
*/const oa=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"}]]);/**
|
|
167
167
|
* @license lucide-react v0.453.0 - ISC
|
|
168
168
|
*
|
|
169
169
|
* This source code is licensed under the ISC license.
|
|
@@ -178,47 +178,47 @@
|
|
|
178
178
|
*
|
|
179
179
|
* This source code is licensed under the ISC license.
|
|
180
180
|
* See the LICENSE file in the root directory of this source tree.
|
|
181
|
-
*/const
|
|
181
|
+
*/const ia=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"}]]);/**
|
|
182
182
|
* @license lucide-react v0.453.0 - ISC
|
|
183
183
|
*
|
|
184
184
|
* This source code is licensed under the ISC license.
|
|
185
185
|
* See the LICENSE file in the root directory of this source tree.
|
|
186
|
-
*/const
|
|
186
|
+
*/const ca=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"}]]);/**
|
|
187
187
|
* @license lucide-react v0.453.0 - ISC
|
|
188
188
|
*
|
|
189
189
|
* This source code is licensed under the ISC license.
|
|
190
190
|
* See the LICENSE file in the root directory of this source tree.
|
|
191
|
-
*/const
|
|
191
|
+
*/const da=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"}]]);/**
|
|
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
|
|
196
|
+
*/const ua=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"}]]);/**
|
|
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
|
|
201
|
+
*/const ma=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"}]]);/**
|
|
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
|
|
206
|
+
*/const ha=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"}]]);/**
|
|
207
207
|
* @license lucide-react v0.453.0 - ISC
|
|
208
208
|
*
|
|
209
209
|
* This source code is licensed under the ISC license.
|
|
210
210
|
* See the LICENSE file in the root directory of this source tree.
|
|
211
|
-
*/const
|
|
211
|
+
*/const xa=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"}]]);/**
|
|
212
212
|
* @license lucide-react v0.453.0 - ISC
|
|
213
213
|
*
|
|
214
214
|
* This source code is licensed under the ISC license.
|
|
215
215
|
* See the LICENSE file in the root directory of this source tree.
|
|
216
|
-
*/const
|
|
216
|
+
*/const pa=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"}]]);/**
|
|
217
217
|
* @license lucide-react v0.453.0 - ISC
|
|
218
218
|
*
|
|
219
219
|
* This source code is licensed under the ISC license.
|
|
220
220
|
* See the LICENSE file in the root directory of this source tree.
|
|
221
|
-
*/const
|
|
221
|
+
*/const fa=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"}]]);/**
|
|
222
222
|
* @license lucide-react v0.453.0 - ISC
|
|
223
223
|
*
|
|
224
224
|
* This source code is licensed under the ISC license.
|
|
@@ -228,12 +228,12 @@
|
|
|
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
|
|
231
|
+
*/const ga=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"}]]);/**
|
|
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
|
|
236
|
+
*/const Lt=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"}]]);/**
|
|
237
237
|
* @license lucide-react v0.453.0 - ISC
|
|
238
238
|
*
|
|
239
239
|
* This source code is licensed under the ISC license.
|
|
@@ -253,17 +253,22 @@
|
|
|
253
253
|
*
|
|
254
254
|
* This source code is licensed under the ISC license.
|
|
255
255
|
* See the LICENSE file in the root directory of this source tree.
|
|
256
|
-
*/const
|
|
256
|
+
*/const va=s.createLucideIcon("List",[["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 18h.01",key:"1tta3j"}],["path",{d:"M3 6h.01",key:"1rqtza"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 18h13",key:"1lx6n3"}],["path",{d:"M8 6h13",key:"ik3vkj"}]]);/**
|
|
257
257
|
* @license lucide-react v0.453.0 - ISC
|
|
258
258
|
*
|
|
259
259
|
* This source code is licensed under the ISC license.
|
|
260
260
|
* See the LICENSE file in the root directory of this source tree.
|
|
261
|
-
*/const
|
|
261
|
+
*/const Ot=s.createLucideIcon("Lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]]);/**
|
|
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 Na=s.createLucideIcon("
|
|
266
|
+
*/const Na=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"}]]);/**
|
|
267
|
+
* @license lucide-react v0.453.0 - ISC
|
|
268
|
+
*
|
|
269
|
+
* This source code is licensed under the ISC license.
|
|
270
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
271
|
+
*/const Ca=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"}]]);/**
|
|
267
272
|
* @license lucide-react v0.453.0 - ISC
|
|
268
273
|
*
|
|
269
274
|
* This source code is licensed under the ISC license.
|
|
@@ -278,12 +283,12 @@
|
|
|
278
283
|
*
|
|
279
284
|
* This source code is licensed under the ISC license.
|
|
280
285
|
* See the LICENSE file in the root directory of this source tree.
|
|
281
|
-
*/const
|
|
286
|
+
*/const Sa=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"}]]);/**
|
|
282
287
|
* @license lucide-react v0.453.0 - ISC
|
|
283
288
|
*
|
|
284
289
|
* This source code is licensed under the ISC license.
|
|
285
290
|
* See the LICENSE file in the root directory of this source tree.
|
|
286
|
-
*/const
|
|
291
|
+
*/const wa=s.createLucideIcon("MessageCircle",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]]);/**
|
|
287
292
|
* @license lucide-react v0.453.0 - ISC
|
|
288
293
|
*
|
|
289
294
|
* This source code is licensed under the ISC license.
|
|
@@ -298,17 +303,22 @@
|
|
|
298
303
|
*
|
|
299
304
|
* This source code is licensed under the ISC license.
|
|
300
305
|
* See the LICENSE file in the root directory of this source tree.
|
|
301
|
-
*/const
|
|
306
|
+
*/const Da=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"}]]);/**
|
|
307
|
+
* @license lucide-react v0.453.0 - ISC
|
|
308
|
+
*
|
|
309
|
+
* This source code is licensed under the ISC license.
|
|
310
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
311
|
+
*/const ka=s.createLucideIcon("Palette",[["circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor",key:"1okk4w"}],["circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor",key:"f64h9f"}],["circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor",key:"fotxhn"}],["circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor",key:"qy21gx"}],["path",{d:"M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z",key:"12rzf8"}]]);/**
|
|
302
312
|
* @license lucide-react v0.453.0 - ISC
|
|
303
313
|
*
|
|
304
314
|
* This source code is licensed under the ISC license.
|
|
305
315
|
* See the LICENSE file in the root directory of this source tree.
|
|
306
|
-
*/const
|
|
316
|
+
*/const Ea=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"}]]);/**
|
|
307
317
|
* @license lucide-react v0.453.0 - ISC
|
|
308
318
|
*
|
|
309
319
|
* This source code is licensed under the ISC license.
|
|
310
320
|
* See the LICENSE file in the root directory of this source tree.
|
|
311
|
-
*/const
|
|
321
|
+
*/const Ta=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"}]]);/**
|
|
312
322
|
* @license lucide-react v0.453.0 - ISC
|
|
313
323
|
*
|
|
314
324
|
* This source code is licensed under the ISC license.
|
|
@@ -323,7 +333,7 @@
|
|
|
323
333
|
*
|
|
324
334
|
* This source code is licensed under the ISC license.
|
|
325
335
|
* See the LICENSE file in the root directory of this source tree.
|
|
326
|
-
*/const
|
|
336
|
+
*/const Ia=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"}]]);/**
|
|
327
337
|
* @license lucide-react v0.453.0 - ISC
|
|
328
338
|
*
|
|
329
339
|
* This source code is licensed under the ISC license.
|
|
@@ -333,7 +343,7 @@
|
|
|
333
343
|
*
|
|
334
344
|
* This source code is licensed under the ISC license.
|
|
335
345
|
* See the LICENSE file in the root directory of this source tree.
|
|
336
|
-
*/const
|
|
346
|
+
*/const Aa=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"}]]);/**
|
|
337
347
|
* @license lucide-react v0.453.0 - ISC
|
|
338
348
|
*
|
|
339
349
|
* This source code is licensed under the ISC license.
|
|
@@ -348,27 +358,32 @@
|
|
|
348
358
|
*
|
|
349
359
|
* This source code is licensed under the ISC license.
|
|
350
360
|
* See the LICENSE file in the root directory of this source tree.
|
|
351
|
-
*/const
|
|
361
|
+
*/const Ma=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"}]]);/**
|
|
362
|
+
* @license lucide-react v0.453.0 - ISC
|
|
363
|
+
*
|
|
364
|
+
* This source code is licensed under the ISC license.
|
|
365
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
366
|
+
*/const La=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"}]]);/**
|
|
352
367
|
* @license lucide-react v0.453.0 - ISC
|
|
353
368
|
*
|
|
354
369
|
* This source code is licensed under the ISC license.
|
|
355
370
|
* See the LICENSE file in the root directory of this source tree.
|
|
356
|
-
*/const
|
|
371
|
+
*/const Bt=s.createLucideIcon("Sigma",[["path",{d:"M18 7V5a1 1 0 0 0-1-1H6.5a.5.5 0 0 0-.4.8l4.5 6a2 2 0 0 1 0 2.4l-4.5 6a.5.5 0 0 0 .4.8H17a1 1 0 0 0 1-1v-2",key:"wuwx1p"}]]);/**
|
|
357
372
|
* @license lucide-react v0.453.0 - ISC
|
|
358
373
|
*
|
|
359
374
|
* This source code is licensed under the ISC license.
|
|
360
375
|
* See the LICENSE file in the root directory of this source tree.
|
|
361
|
-
*/const
|
|
376
|
+
*/const Oa=s.createLucideIcon("SlidersHorizontal",[["line",{x1:"21",x2:"14",y1:"4",y2:"4",key:"obuewd"}],["line",{x1:"10",x2:"3",y1:"4",y2:"4",key:"1q6298"}],["line",{x1:"21",x2:"12",y1:"12",y2:"12",key:"1iu8h1"}],["line",{x1:"8",x2:"3",y1:"12",y2:"12",key:"ntss68"}],["line",{x1:"21",x2:"16",y1:"20",y2:"20",key:"14d8ph"}],["line",{x1:"12",x2:"3",y1:"20",y2:"20",key:"m0wm8r"}],["line",{x1:"14",x2:"14",y1:"2",y2:"6",key:"14e1ph"}],["line",{x1:"8",x2:"8",y1:"10",y2:"14",key:"1i6ji0"}],["line",{x1:"16",x2:"16",y1:"18",y2:"22",key:"1lctlv"}]]);/**
|
|
362
377
|
* @license lucide-react v0.453.0 - ISC
|
|
363
378
|
*
|
|
364
379
|
* This source code is licensed under the ISC license.
|
|
365
380
|
* See the LICENSE file in the root directory of this source tree.
|
|
366
|
-
*/const
|
|
381
|
+
*/const Ra=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"}]]);/**
|
|
367
382
|
* @license lucide-react v0.453.0 - ISC
|
|
368
383
|
*
|
|
369
384
|
* This source code is licensed under the ISC license.
|
|
370
385
|
* See the LICENSE file in the root directory of this source tree.
|
|
371
|
-
*/const
|
|
386
|
+
*/const Ba=s.createLucideIcon("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/**
|
|
372
387
|
* @license lucide-react v0.453.0 - ISC
|
|
373
388
|
*
|
|
374
389
|
* This source code is licensed under the ISC license.
|
|
@@ -378,12 +393,12 @@
|
|
|
378
393
|
*
|
|
379
394
|
* This source code is licensed under the ISC license.
|
|
380
395
|
* See the LICENSE file in the root directory of this source tree.
|
|
381
|
-
*/const
|
|
396
|
+
*/const Ft=s.createLucideIcon("Tag",[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]]);/**
|
|
382
397
|
* @license lucide-react v0.453.0 - ISC
|
|
383
398
|
*
|
|
384
399
|
* This source code is licensed under the ISC license.
|
|
385
400
|
* See the LICENSE file in the root directory of this source tree.
|
|
386
|
-
*/const
|
|
401
|
+
*/const Fa=s.createLucideIcon("Terminal",[["polyline",{points:"4 17 10 11 4 5",key:"akl6gq"}],["line",{x1:"12",x2:"20",y1:"19",y2:"19",key:"q2wloq"}]]);/**
|
|
387
402
|
* @license lucide-react v0.453.0 - ISC
|
|
388
403
|
*
|
|
389
404
|
* This source code is licensed under the ISC license.
|
|
@@ -413,7 +428,7 @@
|
|
|
413
428
|
*
|
|
414
429
|
* This source code is licensed under the ISC license.
|
|
415
430
|
* See the LICENSE file in the root directory of this source tree.
|
|
416
|
-
*/const Oa=s.createLucideIcon("View",[["path",{d:"M21 17v2a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-2",key:"mrq65r"}],["path",{d:"M21 7V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2",key:"be3xqs"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["path",{d:"M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0",key:"11ak4c"}]]);function as(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=>Ft(c))}})}})}}function Ft(t){return{...t,customCfg:Ba(t.customCfg),data:[]}}function Ba(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 Fa(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 ks(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 Pa(t,a){return a?await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{operation:"delete",lensId:t}):null}function za(){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,u]=A.useState(!1),h=s.useDashboardStore(x=>x.dashboard),p=s.useDashboardStore(x=>x.filterValues),{authToken:f}=s.useSemaphorContext();async function j(){d(!0);const x=as(h),y=await Fa(t,x,p,f==null?void 0:f.accessToken);y&&(o([...l||[],y]),c(y.id),u(!1)),d(!1)}return e.jsxs(s.Dialog,{open:m,onOpenChange:u,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 Va(){const[t,a]=A.useState(!1),n=s.useDashboardStore(u=>u.lenses),r=s.useDashboardStore(u=>u.selectedLensId),{setLenses:l,setSelectedLensId:o}=s.useDashboardActions(),{authToken:c}=s.useSemaphorContext();async function i(u){o(u)}async function d(u){if(await Pa(u,c==null?void 0:c.accessToken)){const p=n==null?void 0:n.filter(f=>f.id!==u);l(p||[]),o("original")}}async function m(u){const h=n==null?void 0:n.map(j=>j.id===u.id?{...j,isDefault:!u.isDefault}:{...j,isDefault:!1});l(h||[]);const p={...u,isDefault:!u.isDefault};await ks(p,c==null?void 0:c.accessToken);const f=n==null?void 0:n.find(j=>j.isDefault);if(f&&f.id!==u.id){const j={...f,isDefault:!1};await ks(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(ha,{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(u=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:u.id,children:[e.jsx("p",{children:u.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:h=>{h.preventDefault(),m(u)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!u.isDefault,"text-green-500":u.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:h=>{h.preventDefault(),d(u.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},u.id))]})]})]})}function Pt(){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 zt(){const t=s.useDashboardStore.getState().isDownloadingPdf,{authToken:a,theme:n,filterValues:r,dashboardTitle:l,selectedSheetId:o}=Pt();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 u=(await(await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${a==null?void 0:a.accessToken}`}})).json()).url,h=document.createElement("a");h.href=u;const p=`${l}-${new Date().toISOString()}.pdf`;h.download=p,h.click(),s.useDashboardStore.setState({isDownloadingPdf:!1})}function _a({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 zt()}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 he({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 mt=[{value:"daily",label:"Daily"},{value:"weekly",label:"Weekly"},{value:"biweekly",label:"Bi-Weekly"},{value:"monthly",label:"Monthly"}];function Vt({triggerButtonClassName:t}){const{data:a,handleScheduleSubscription:n,handleDeleteSubscription:r,status:l,error:o,isDeleting:c}=Ua(),[i,d]=A.useState(""),[m,u]=A.useState(mt[0].value),[h,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(he,{className:"col-span-2 h-8",label:"Select Frequency",options:mt,value:m,onValueChange:x=>u(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:h,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:h,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(At,{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(ht,{tooltip:`Next Run: ${new Date(x.nextRun).toLocaleString()} ${x.timezone}`,children:e.jsx(sa,{className:"size-3.5"})}),e.jsx(ht,{tooltip:`${x.endUserEmail}`,children:e.jsx(Na,{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 ht=({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]=A.useState("idle"),[n,r]=A.useState(""),[l,o]=A.useState(null),c=s.useDashboardStore(E=>E.authToken),i=s.useDashboardStore(E=>E.dashboard.id),d=s.useDashboardStore(E=>E.dashboard.title),{endUserId:m}=s.getTenantAndEndUserId((c==null?void 0:c.accessToken)||""),u="https://semaphor.cloud/api/v1/subscriptions/get",h={dashboardId:i,endUserId:m},{data:p,isLoading:f,isError:j,isFetching:x,refetch:y}=s.useQuery({queryKey:["subscriptions",i,m],queryFn:()=>s.getRequest(u,(c==null?void 0:c.accessToken)||"",h),enabled:!!(c!=null&&c.accessToken)&&!!i&&!!m});async function g({email:E,subject:R,frequency:S,time:N}){const{authToken:b,...T}=Pt(),k=Intl.DateTimeFormat().resolvedOptions().timeZone,L={email:E,frequency:S,time:N,timezone:k,endUserId:m,endUserEmail:E,subject:R||d||"Scheduled Dashboard",dashboardId:i,dashboardParams:T};a("loading");const w="https://semaphor.cloud/api/v1/subscriptions/create";try{const B=await s.postRequestRegular(w,(b==null?void 0:b.accessToken)||"",{...L});a("success"),r(""),y(),setTimeout(()=>{a("idle")},2e3)}catch(B){console.error(B),a("error"),r(B.message)}}async function C(E){const R="https://semaphor.cloud/api/v1/subscriptions/delete";o(E);try{await s.postRequestRegular(R,(c==null?void 0:c.accessToken)||"",{id:E}),y(),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:y,handleScheduleSubscription:g,handleDeleteSubscription:C,status:t,error:n}}function Ne(){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 _t(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4",children:[e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"space-y-2",children:[...Array(4)].map((t,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))})]})})}var ee=(t=>(t.DASHBOARD="dashboard",t.VISUAL="visual",t))(ee||{});const $a=async(t,a,n,r,l,o)=>{const c={},i={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${i[a]}`,t,c)},qa=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${r[a]}`,t,n)},Ya=async(t,a,n,r)=>{const l={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"},o=await fetch(`https://semaphor.cloud/api/management/v1/${l[a]}/${n}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!o.ok){const c=await o.json();throw new Error((c==null?void 0:c.error)||`HTTP error! status: ${o.status}`)}return o.json()},Ga=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"},l=await fetch(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`}});if(!l.ok){const o=await l.json();throw new Error((o==null?void 0:o.error)||`HTTP error! status: ${l.status}`)}return l.json()},Ha=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}/duplicate`,t,{})},Ka=async(t,a,n,r)=>{const l={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${l[a]}/${n}/share`,t,r)},Qa=async(t,a,n,r)=>{const l={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"},o=await fetch(`https://semaphor.cloud/api/management/v1/${l[a]}/${n}/share`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!o.ok){const c=await o.json();throw new Error((c==null?void 0:c.error)||`HTTP error! status: ${o.status}`)}return o.json()},Wa=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}/shares`,t)},Ja=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}`,t)};function Xa(t){const{authToken:a}=s.useSemaphorContext();return s.useQuery({queryKey:["tenants"],queryFn:()=>s.getRequest("https://semaphor.cloud/api/management/v1/tenants",(a==null?void 0:a.accessToken)||""),enabled:(t==null?void 0:t.enabled)!==void 0?t.enabled&&!!(a!=null&&a.accessToken):!!(a!=null&&a.accessToken)})}function Za(t,a,n,r,l){const{authToken:o}=s.useSemaphorContext(),{currentUser:c}=Ne();return s.useQuery({queryKey:[t,a,n,r,l],queryFn:()=>$a((o==null?void 0:o.accessToken)||"",t),enabled:!!(o!=null&&o.accessToken)&&!!c})}function er(t,a){const{authToken:n}=s.useSemaphorContext(),r=s.useQueryClient();return Re({mutationFn:l=>qa((n==null?void 0:n.accessToken)||"",t,l),onMutate:async()=>{await r.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await r.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} created successfully`),a==null||a()},onError:l=>{s.ue.error(`Failed to create ${s.toTitleCase(t)}: ${l.message}`)}})}function Ut(t){const{authToken:a}=s.useSemaphorContext(),n=s.useQueryClient();return Re({mutationFn:({resourceId:r,data:l})=>Ya((a==null?void 0:a.accessToken)||"",t,r,l),onMutate:async()=>{await n.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await n.invalidateQueries({queryKey:[t]})},onError:r=>{s.ue.error(`Failed to update ${s.toTitleCase(t)}: ${r.message}`)}})}function sr(t,a){const{authToken:n}=s.useSemaphorContext(),r=s.useQueryClient();return Re({mutationFn:l=>Ga((n==null?void 0:n.accessToken)||"",t,l),onMutate:async()=>{await r.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await r.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} deleted successfully`),a==null||a()},onError:l=>{s.ue.error(`Failed to delete ${s.toTitleCase(t)}: ${l.message}`)}})}function tr(t){const{authToken:a}=s.useSemaphorContext(),n=s.useQueryClient();return Re({mutationFn:r=>Ha((a==null?void 0:a.accessToken)||"",t,r),onMutate:async()=>{await n.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await n.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} duplicated successfully`)},onError:r=>{s.ue.error(`Failed to duplicate ${s.toTitleCase(t)}: ${r.message}`)}})}function nr(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Re({mutationFn:({resourceType:n,resourceId:r,data:l})=>Ka((t==null?void 0:t.accessToken)||"",n,r,l),onMutate:async n=>{await a.cancelQueries({queryKey:["resource-shares",n.resourceType,n.resourceId]})},onSuccess:async(n,r)=>{await a.invalidateQueries({queryKey:["resource-shares",r.resourceType,r.resourceId]}),a.invalidateQueries({queryKey:[r.resourceType]})},onError:n=>{s.ue.error(`Failed to share resource: ${n.message}`)}})}function ar(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Re({mutationFn:({resourceType:n,resourceId:r,data:l})=>Qa((t==null?void 0:t.accessToken)||"",n,r,l),onMutate:async n=>{await a.cancelQueries({queryKey:["resource-shares",n.resourceType,n.resourceId]})},onSuccess:async(n,r)=>{await a.invalidateQueries({queryKey:["resource-shares",r.resourceType,r.resourceId]}),a.invalidateQueries({queryKey:[r.resourceType]})},onError:n=>{s.ue.error(`Failed to remove resource shares: ${n.message}`)}})}function rr(t,a){const{authToken:n}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-shares",t,a],queryFn:()=>Wa((n==null?void 0:n.accessToken)||"",t,a),enabled:!!(n!=null&&n.accessToken)&&!!a})}function lr(t,a,n){const{authToken:r}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-by-id",t,a],queryFn:()=>Ja((r==null?void 0:r.accessToken)||"",t,a),enabled:(n==null?void 0:n.enabled)!==void 0?n.enabled&&!!(r!=null&&r.accessToken)&&!!a:!!(r!=null&&r.accessToken)&&!!a})}function or(t,a){return lr(ee.VISUAL,t,a)}function $t(){const[t,a]=A.useState(new Map),n=A.useCallback((o,c)=>{a(i=>{const d=new Map(i),m=new Set(d.get(o)||[]);return c?m.add(c):(m.add("title"),m.add("description")),d.set(o,m),d})},[]),r=A.useCallback((o,c)=>{a(i=>{const d=new Map(i),m=new Set(d.get(o)||[]);return c?m.delete(c):m.clear(),m.size===0?d.delete(o):d.set(o,m),d})},[]),l=A.useCallback((o,c)=>{const i=t.get(o);return i?c?i.has(c):i.size>0:!1},[t]);return{startUpdating:n,stopUpdating:r,isUpdating:l}}function Vs(t,a,n){var h;const r=Za(t),l=er(t,n),o=Ut(t),c=sr(t,a),i=tr(t),d=nr(),m=ar(),u={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return{resources:((h=r.data)==null?void 0:h[u[t]])||[],isLoading:r.isLoading,isError:r.isError,isFetching:r.isFetching,error:r.error,createResource:l.mutate,updateResource:o.mutate,deleteResource:c.mutate,duplicateResource:i.mutate,shareResource:d.mutate,removeResourceShares:m.mutate,isCreating:l.isPending,isUpdating:o.isPending,isDeleting:c.isPending,isDuplicating:i.isPending,isSharing:d.isPending,isRemovingShares:m.isPending,isUpdatingShares:d.isPending,refetch:r.refetch}}function ir(t,a){return Vs(ee.DASHBOARD,t,a)}function cr(t,a){return Vs(ee.VISUAL,t,a)}function dr(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Re({mutationFn:async({visualId:n,data:r})=>{const l=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${n}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t==null?void 0:t.accessToken}`},body:JSON.stringify(r)});if(!l.ok)throw new Error("Failed to update visual");return l.json()},onSuccess:()=>{s.ue.success("Visual updated successfully"),a.invalidateQueries({queryKey:["visuals"]})},onError:()=>{s.ue.error("Failed to update visual")}})}function ur({visual:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onAddVisual:o,onEditVisual:c,onUpdateVisual:i,onDeleteClick:d,onDuplicateVisual:m,onShareVisual:u,formatDate:h}){var N;const{selectVisual:p}=s.useManagementActions(),f=s.useIsVisualSelected(t.id),j=s.useDashboardStore(b=>b.actions.setIsDashboardPanelOpen),[x,y]=A.useState(!1),[g,C]=A.useState(!1);A.useEffect(()=>{n?(y(!0),C(!0)):g&&(y(!1),C(!1))},[n,g]);const E=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(Lt,{className:"h-3 w-3 text-purple-500"}):e.jsx(ve,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(ke,{className:"h-3.5 w-3.5 text-slate-500"}),R=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4 text-slate-400"}),S=()=>{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:S,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:R()})}),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:b=>i==null?void 0:i(t.id,{title:b}),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:E()})]}),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:b=>i==null?void 0:i(t.id,{description:b}),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:b=>{b.stopPropagation(),o(t)},children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:x,onOpenChange:y,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:b=>b.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:b=>{b.stopPropagation(),o(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:b=>{b.preventDefault(),b.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:b=>{b.stopPropagation(),c==null||c(t)},children:[e.jsx(Da,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:b=>{b.stopPropagation(),u(t)},children:[e.jsx(ve,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:b=>{b.stopPropagation(),d(t),j(!1)},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(ke,{className:"h-3 w-3"}),e.jsx("span",{children:((N=t.ownership.createdBy)==null?void 0:N.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 qt({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 rs({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 Yt({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(rs,{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 Gt({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 Ht({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(ve,{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 Kt(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 pe(t,a){var n;return((n=a.find(r=>r.value===t))==null?void 0:n.label)||t}function mr(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function Qt(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function hr(t,a,n){const r=Qt(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 xr({user:t}){return Qt(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 pr({user:t,userShare:a,usersToUpdate:n,currentUser:r,getRoleOptions:l,handleUpdateAccess:o}){if(!(a!=null&&a.role))return null;const c=mr((r==null?void 0:r.type)||""),i=n.some(h=>h.id===t.id),d=n.find(h=>h.id===t.id),m=d?d.newRole:a==null?void 0:a.role,u=l(t.type);return a?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(rs,{currentRole:m,onRoleChange:h=>{o(t.id,a.role,h)},roleOptions:u,disabled:!c,allowDropdown:c,className:i?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:pe(m,u)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function fr({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(Ke,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function gr({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 jr({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||[],u=c.orgUsersOnly||[],h=c.allTenantsOnly||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Org Users (",i.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[i.slice(0,3).map((p,f)=>{var g,C;const j=((g=a.find(E=>E.id===p.orgUserId))==null?void 0:g.name)||"Unknown User",x=((C=a.find(E=>E.id===p.orgUserId))==null?void 0:C.type)||"",y=pe(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:y})]},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,C;const j=((g=a.find(E=>E.id===p.tenantUserId))==null?void 0:g.name)||"Unknown User",x=((C=a.find(E=>E.id===p.tenantUserId))==null?void 0:C.type)||"",y=pe(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:y})]},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=pe(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)})})]}),u.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:u.map((p,f)=>{const j=pe(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)})})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-indigo-600",children:"All Tenants"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:h.map((p,f)=>{const j=pe(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&&!u.length&&!h.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const c=t.shares.specificTenantUsers||[],i=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",c.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[c.slice(0,3).map((d,m)=>{var f,j;const u=((f=a.find(x=>x.id===d.tenantUserId))==null?void 0:f.name)||"Unknown User",h=((j=a.find(x=>x.id===d.tenantUserId))==null?void 0:j.type)||"",p=pe(d.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:u}),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 u=pe(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:u})]},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",u=((f=a.find(j=>j.id===i.tenantUserId))==null?void 0:f.type)||"",h=pe(i.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:m}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},d)}),o.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",o.length-3," more users"]})]})]}),c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:c.map((i,d)=>{const m=pe(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 yr({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 br({user:t,userShare:a,isUserRemoving:n,hasAccess:r,hasAccessFromAPI:l,isSelected:o,selectedUser:c,roleOptions:i,currentUser:d,usersToUpdate:m,handleUserToggle:u,handleRemoveAccess:h,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?u(t.id):h(t.id):u(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(xr,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!n?e.jsx(rs,{currentRole:a==null?void 0:a.role,onRoleChange:j=>p(t.id,a.role,j),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(pr,{user:t,userShare:a,usersToUpdate:m,currentUser:d,getRoleOptions:()=>i,handleUpdateAccess:p}),o&&!l&&e.jsx("div",{onClick:j=>j.stopPropagation(),children:e.jsx(rs,{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(fr,{hasAccess:r,isUserRemoving:n,isSelected:o,hasAccessFromAPI:l}),e.jsx(gr,{isUserRemoving:n,isSelected:o,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function Wt({existingShares:t,isInitialLoading:a,isSearching:n,getRoleOptions:r,allUsers:l=[],currentUser:o,handleUserToggle:c,handleUserRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:m}){const u=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),f=s.useShareSearchQuery(),j=s.useShareManagementActions(),x=c||(S=>{const N=u.some(T=>T.id===S),b=h.includes(S);N?j.removeSelectedUser(S):b?j.removeUserFromRemove(S):j.addSelectedUser({id:S,role:"VIEWER"})}),y=i||j.updateSelectedUserRole,g=d||j.addUserToRemove,C=m||((S,N,b)=>{j.addUserToUpdate({id:S,currentRole:N,newRole:b})}),E=l,R=h;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["All Users (",(E??[]).length,")"]}),e.jsx(s.TooltipProvider$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(jr,{existingShares:t,allUsers:l,getRoleOptions:r,currentUser:o})})]})})]}),(E==null?void 0:E.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{u.length===E.length?j.setSelectedUsers([]):j.setSelectedUsers(E.map(S=>({id:S.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:u.length===E.length?"Deselect all":"Select all"})]}),e.jsxs("div",{className:"max-h-60 space-y-1 overflow-y-auto rounded-md border p-2",children:[e.jsx(yr,{isInitialLoading:a,isSearching:n,searchQuery:f,availableUsers:E||[]}),!a&&!n&&(E==null?void 0:E.length)>0&&E.map(S=>{const N=t?hr(S,t,o):void 0,b=R.includes(S.id),T=!!N,k=T&&!b,L=u.some(D=>D.id===S.id),w=u.find(D=>D.id===S.id),B=r(S.type);return e.jsx(br,{user:S,userShare:N,isUserRemoving:b,hasAccess:k,hasAccessFromAPI:T,isSelected:L,selectedUser:w,roleOptions:B,currentUser:o,usersToUpdate:p,handleUserToggle:x,handleRemoveAccess:g,handleUpdateAccess:C,handleUserRoleChange:y},S.id)})]})]})}function Jt({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(ke,{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 Ie=()=>[{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 vr({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=Ie().filter(C=>C.value==="VIEWER"||C.value==="EDITOR"||C.value==="CONTRIBUTOR"),u=a.role!=="NONE"?a.role:"NONE",h=l?l.newRole:u,p=a.role!=="NONE"&&!o&&(!l||l.newRole===u),f=l!==null&&l.newRole!==u,j=o,x=u==="NONE"||!u,y=C=>{switch(C){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(Ia,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},g=C=>{r(u,C)};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(ve,{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(C=>e.jsxs(s.Button,{variant:h===C.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>g(C.value),disabled:n||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[y(C.value),e.jsx("span",{className:"font-medium",children:C.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:C.description})]},C.value))})]})})]})})}function Xt({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,h=a?{role:m(a.role)}:{role:"NONE"},p=i?{currentRole:m(i.currentRole),newRole:m(i.newRole)}:null,f=(x,y)=>{o(x,y)},j=()=>{c()};return e.jsx(vr,{currentUser:t,currentShare:h,isSharing:n,isUpdating:r,isRemoving:l,onUpdateAccess:f,onRemoveAccess:j,allUsersToUpdate:p,allUsersToRemove:d})}const Nr=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 Cr(t={}){var o,c,i;const{authToken:a,tokenProps:n}=s.useSemaphorContext(),r=(n==null?void 0:n.endUserId)||(n==null?void 0:n.orgUserId),l=s.useQuery({queryKey:["unified-users",t],queryFn:()=>Nr((a==null?void 0:a.accessToken)||"",t),enabled:!!(a!=null&&a.accessToken)&&!!r,retry:(d,m)=>m instanceof Error&&m.message.includes("401")||m instanceof Error&&m.message.includes("403")?!1:d<2,retryDelay:d=>Math.min(1e3*2**d,3e4)});return{users:((o=l.data)==null?void 0:o.users)||[],userContext:(c=l.data)==null?void 0:c.userContext,total:((i=l.data)==null?void 0:i.total)||0,isLoading:l.isLoading,isError:l.isError,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function Ee(t){const{debouncedSearchQuery:a,resourceId:n,resourceType:r=ee.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}=Cr(c),u=rr(r,n);return{allUsers:i,isLoadingUsers:d,isErrorLoadingUsers:m,existingShares:u.data,isLoadingShares:u.isLoading,isErrorLoadingShares:u.isError,isFetchingShares:u.isFetching}}function Sr({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var Q,U;const i=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:m,setSearchQuery:u,debouncedSearchQuery:h}=s.useShareSearchWithDebounce(),p=s.useShareSelectedUsers(),f=s.useShareUsersToRemove(),j=s.useShareUsersToUpdate(),x=s.useShareCurrentMode(),y=s.useShareOrgWideRole(),g=s.useShareManagementActions(),[C,E]=A.useState("specific_users"),R=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},S=()=>{if(i==="tenant"&&d)return d},{allUsers:N,existingShares:b,isLoadingUsers:T}=Ee({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:R(),tenantId:S()});A.useEffect(()=>{g.setCurrentContext("org-tab"),g.setCurrentMode(C==="all_users"?"allOrgUsers":"specificOrgUsers")},[g,C]);const k=q=>{var $,P;const Y=q;if(E(Y),r==null||r(Y),g.setCurrentContext("org-tab"),Y==="specific_users")g.setCurrentMode("specificOrgUsers");else if(Y==="all_users"){g.setCurrentMode("allOrgUsers");const G=(P=($=b==null?void 0:b.shares)==null?void 0:$.orgUsersOnly)==null?void 0:P[0];G&&G.role!==void 0&&g.setOrgWideRole(G.role)}},L=N.filter(q=>q.name.toLowerCase().includes(m.toLowerCase())||q.email.toLowerCase().includes(m.toLowerCase())),w=N.filter(q=>p.some(Y=>Y.id===q.id)),B=q=>{var G,H;const Y=p.some(Z=>Z.id===q),$=f.includes(q),P=(H=(G=b==null?void 0:b.shares)==null?void 0:G.specificOrgUsers)==null?void 0:H.some(Z=>Z.orgUserId===q);Y?g.removeSelectedUser(q):$?g.removeUserFromRemove(q):P||g.addSelectedUser({id:q,role:"VIEWER"})},D=(q,Y)=>{g.updateSelectedUserRole(q,Y)},I=q=>{g.addUserToRemove(q),g.removeSelectedUser(q)},v=q=>{g.removeUserFromRemove(q)},M=q=>{g.removeUserFromUpdate(q)},F=(q,Y)=>{g.setOrgWideRole(Y)},O=()=>{g.setOrgWideRole((V==null?void 0:V.role)||"NONE")},V=(U=(Q=b==null?void 0:b.shares)==null?void 0:Q.orgUsersOnly)==null?void 0:U[0];A.useEffect(()=>{C==="all_users"&&V&&V.role!==void 0&&g.setOrgWideRole(V.role)},[C,V,g]);const _=T,W=!1;return n?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{shareType:C,onShareTypeChange:k,currentUser:n,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(ke,{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(ve,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role??"")}]}),C==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(qt,{value:m,onChange:u}),e.jsx(Yt,{selectedUsers:p,selectedUserObjects:w,onRemove:B,onRoleChange:D,getRoleOptions:Ie}),e.jsx(Gt,{usersToRemove:f,allUsers:L,onRemove:v}),e.jsx(Ht,{usersToUpdate:j,allUsers:L,onRemove:M,getRoleOptions:Ie}),e.jsx(Wt,{existingShares:b,isInitialLoading:_,isSearching:W,resource:t,onShare:()=>{},getRoleOptions:Ie,allUsers:L,currentUser:n,handleUserToggle:B,handleUserRoleChange:D,handleRemoveAccess:I,handleUpdateAccess:(q,Y,$)=>{g.addUserToUpdate({id:q,currentRole:Y,newRole:$})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(Xt,{currentUser:n,currentShare:V,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:F,onRemoveAccess:O,allUsersToUpdate:x==="allOrgUsers"&&y!==((V==null?void 0:V.role)||"NONE")?{currentRole:(V==null?void 0:V.role)||"NONE",newRole:y}:null,allUsersToRemove:x==="allOrgUsers"&&(V==null?void 0:V.role)===void 0})})]}):null}function xt({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var G;const{searchQuery:i,debouncedSearchQuery:d,setSearchQuery:m}=s.useShareSearchWithDebounce(),u=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),f=s.useShareCurrentMode(),j=s.useShareTenantWideRole(),x=s.useShareAllTenantsRole(),y=s.useShareSelectedTenant(),g=s.useShareManagementActions(),{data:C,isLoading:E}=Xa({enabled:(n==null?void 0:n.type)==="organization"}),[R,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 N=H=>{var se,ae,te,le;S(H);let Z;if(H==="specific_tenant_users"?Z="specific_users":H==="all_tenant_users"||H==="all_tenants"?Z="all_users":Z="specific_users",r==null||r(Z),(n==null?void 0:n.type)==="tenant"?(g.setCurrentContext("tenant-dialog"),H==="specific_tenant_users"?g.setCurrentMode("specificTenantUsers"):H==="all_tenant_users"&&(g.setCurrentMode("allTenantUsers"),n!=null&&n.tenantId&&g.setSelectedTenant(n.tenantId))):(g.setCurrentContext("tenant-tab"),H==="specific_tenant_users"?g.setCurrentMode("specificTenantUsers"):H==="all_tenant_users"?g.setCurrentMode("allTenantUsers"):H==="all_tenants"&&g.setCurrentMode("allTenants")),H==="all_tenant_users"){const K=(ae=(se=k==null?void 0:k.shares)==null?void 0:se.tenantWide)==null?void 0:ae[0];K&&K.role!==void 0&&g.setTenantWideRole(K.role)}else if(H==="all_tenants"){const K=(le=(te=k==null?void 0:k.shares)==null?void 0:te.allTenantsOnly)==null?void 0:le[0];K&&K.role!==void 0&&g.setAllTenantsRole(K.role)}},b=H=>{g.setSelectedTenant(H)},{allUsers:T,existingShares:k,isLoadingUsers:L,isErrorLoadingUsers:w,isLoadingShares:B,isErrorLoadingShares:D}=Ee({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant",tenantId:(n==null?void 0:n.type)==="tenant"?n.tenantId:y}),I=H=>{var te,le;const Z=u.some(K=>K.id===H),se=h.includes(H),ae=(le=(te=k==null?void 0:k.shares)==null?void 0:te.specificTenantUsers)==null?void 0:le.some(K=>K.tenantUserId===H);Z?g.removeSelectedUser(H):se?g.removeUserFromRemove(H):ae||g.addSelectedUser({id:H,role:"VIEWER"})},v=(H,Z)=>{g.updateSelectedUserRole(H,Z)},M=H=>{g.addUserToRemove(H),g.removeSelectedUser(H)},F=H=>{g.removeUserFromRemove(H)},O=H=>{g.removeUserFromUpdate(H)},V=(H,Z,se)=>{g.addUserToUpdate({id:H,currentRole:Z,newRole:se})},_=(H,Z)=>{R==="all_tenant_users"?g.setTenantWideRole(Z):R==="all_tenants"&&g.setAllTenantsRole(Z)},W=()=>{R==="all_tenant_users"?g.setTenantWideRole("VIEWER"):R==="all_tenants"&&g.setAllTenantsRole("VIEWER")},U=(()=>{var H,Z,se,ae;return f==="allTenants"?(Z=(H=k==null?void 0:k.shares)==null?void 0:H.allTenantsOnly)==null?void 0:Z[0]:f==="allTenantUsers"?(ae=(se=k==null?void 0:k.shares)==null?void 0:se.tenantWide)==null?void 0:ae[0]:null})();A.useEffect(()=>{var H,Z,se,ae;if(R==="all_tenant_users"){const te=(Z=(H=k==null?void 0:k.shares)==null?void 0:H.tenantWide)==null?void 0:Z[0];te&&te.role!==void 0&&g.setTenantWideRole(te.role)}else if(R==="all_tenants"){const te=(ae=(se=k==null?void 0:k.shares)==null?void 0:se.allTenantsOnly)==null?void 0:ae[0];te&&te.role!==void 0&&g.setAllTenantsRole(te.role)}},[R,k,g]);const q=T.filter(H=>u.some(Z=>Z.id===H.id)),Y=L||B,$=w||D,P=()=>(n==null?void 0:n.type)==="tenant"||R==="all_tenants"?!0:y&&(R==="specific_tenant_users"||R==="all_tenant_users");return e.jsxs(e.Fragment,{children:[$&&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"})]})}),!$&&n&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(Jt,{shareType:R,onShareTypeChange:N,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(ve,{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(ke,{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(ot,{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(ke,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(n==null?void 0:n.type)==="organization"&&(R==="specific_tenant_users"||R==="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:y||"",onValueChange:b,disabled:E,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:E?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(G=C==null?void 0:C.tenants)==null?void 0:G.map(H=>e.jsx(s.SelectItem,{value:H.id,children:H.name},H.id))})]})]}),P()?e.jsx(e.Fragment,{children:R==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(qt,{value:i,onChange:m}),e.jsx(Yt,{selectedUsers:u,selectedUserObjects:q,onRemove:H=>I(H),onRoleChange:v,getRoleOptions:Ie}),e.jsx(Gt,{usersToRemove:h,allUsers:T,onRemove:F}),e.jsx(Ht,{usersToUpdate:p,allUsers:T,onRemove:O,getRoleOptions:Ie}),e.jsx(Wt,{existingShares:k,isInitialLoading:!!Y,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:Ie,allUsers:T,currentUser:n,handleUserToggle:I,handleUserRoleChange:v,handleRemoveAccess:M,handleUpdateAccess:V})]}):R==="all_tenant_users"||R==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(Xt,{currentUser:n,currentShare:U,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:_,onRemoveAccess:W,allUsersToUpdate:f==="allTenantUsers"&&((U==null?void 0:U.role)===void 0||j!==U.role)||f==="allTenants"&&((U==null?void 0:U.role)===void 0||x!==U.role)?{currentRole:(U==null?void 0:U.role)||"VIEWER",newRole:f==="allTenantUsers"?j:x}:null,allUsersToRemove:f==="allTenantUsers"&&(U==null?void 0:U.role)===void 0||f==="allTenants"&&(U==null?void 0:U.role)===void 0})}):null}):(n==null?void 0:n.type)==="organization"&&(R==="specific_tenant_users"||R==="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(ot,{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 Zt=()=>{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]),u=A.useMemo(()=>p=>s.validateShareData(p),[]),h=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:u,isCurrentStateValid:h,currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:l,selectedTenant:o,orgWideRole:c,allTenantsRole:i,tenantWideRole:d}};function pt({resource:t,existingShares:a,isSharing:n,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllUsersShare:d,onRemoveAccess:m}){const u=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const f=s.useShareSelectedTenant();s.useShareSelectedTab();const j=s.useShareOrgWideRole(),x=s.useShareAllTenantsRole(),y=s.useShareTenantWideRole(),{buildShareData:g,validateShareData:C,isCurrentStateValid:E}=Zt(),R=n||r||l,S=()=>{var L,w,B,D;if(R)return"Updating...";if(i==="specific_users"){if(u.length===0&&h.length===0&&p.length===0)return"Select users to share with";const I=u.length+h.length+p.length;return I===0?"Select users to share with":u.length>0&&h.length>0?`Update access for ${I} user${I!==1?"s":""}`:h.length>0&&u.length===0&&p.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:u.length>0&&h.length===0&&p.length===0?`Share with ${u.length} user${u.length!==1?"s":""}`:p.length>0&&u.length===0&&h.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 j===I?"Remove Access":"Update Access"}else if(i==="all_tenants"){const I=(w=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:w[0];if(!I||I.role===void 0)return"Share with All Tenants";const v=I.role;return x===v?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const I=(D=(B=a==null?void 0:a.shares)==null?void 0:B.tenantWide)==null?void 0:D[0];if(!I||I.role===void 0)return"Share with All Tenant Users";const v=I.role;return y===v?"Remove Access":"Update Access"}else if(i==="specific_tenant_users"){if(u.length===0&&h.length===0&&p.length===0)return"Select users to share with";const I=u.length+h.length+p.length;return I===0?"Select users to share with":u.length>0&&h.length>0?`Update access for ${I} user${I!==1?"s":""}`:h.length>0&&u.length===0&&p.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:u.length>0&&h.length===0&&p.length===0?`Share with ${u.length} user${u.length!==1?"s":""}`:p.length>0&&u.length===0&&h.length===0?`Update access for ${p.length} user${p.length!==1?"s":""}`:`Update access for ${I} user${I!==1?"s":""}`}return"Share"},N=()=>R||!t||i==="all_tenant_users"&&!f||i==="specific_tenant_users"&&!f?!0:!E,b=()=>{const L=g();L&&C(L)&&o(L)},T=()=>{var L,w,B,D;if(i==="all_users")if(!d||d.role===void 0){const I=g();I&&C(I)&&o(I)}else{const I=d.role;if(j===I)m==null||m();else{const M=g();if(M&&C(M)){const F={...M,updateAccess:!0};o(F)}}}else if(i==="all_tenants"){const I=(w=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:w[0];if(!I||I.role===void 0){const v=g();v&&C(v)&&o(v)}else{const v=I.role;if(x===v)m==null||m();else{const F=g();if(F&&C(F)){const O={...F,updateAccess:!0};o(O)}}}}else if(i==="all_tenant_users"){const I=(D=(B=a==null?void 0:a.shares)==null?void 0:B.tenantWide)==null?void 0:D[0];if(!I||I.role===void 0){const v=g();v&&C(v)&&o(v)}else{const v=I.role;if(y===v)m==null||m();else{const F=g();if(F&&C(F)){const O={...F,updateAccess:!0};o(O)}}}}},k=()=>{var L,w,B,D;if(i==="all_users"){if(!d||d.role===void 0)return"default";const I=d.role;return j===I?"destructive":"default"}else if(i==="all_tenants"){const I=(w=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:w[0];if(!I||I.role===void 0)return"default";const v=I.role;return x===v?"destructive":"default"}else if(i==="all_tenant_users"){const I=(D=(B=a==null?void 0:a.shares)==null?void 0:B.tenantWide)==null?void 0:D[0];if(!I||I.role===void 0)return"default";const v=I.role;return y===v?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:R,children:"Close"}),(i==="specific_users"||i==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(u.length>0||h.length>0||p.length>0)&&e.jsxs(s.Button,{onClick:b,disabled:!t||R,variant:"default",children:[R?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ke,{className:"mr-2 h-4 w-4"}),!R&&S()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:T,disabled:N(),variant:k(),children:[R?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(ve,{className:"mr-2 h-4 w-4"}),!R&&S()]})]})}function wr({resource:t,isSharing:a,isRemoving:n,isUpdating:r,onShare:l,onClose:o,shareTabType:c,currentAllUsersShare:i}){const d=s.useShareSelectedUsers(),m=s.useShareUsersToRemove(),u=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const h=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:p,validateShareData:f,isCurrentStateValid:j}=Zt(),x=a||n||r,y=()=>{if(x)return"Updating...";if(c==="specific_users"){if(d.length===0&&m.length===0&&u.length===0)return"Select users to share with";const S=d.length+m.length+u.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&&u.length===0?`Remove access for ${m.length} user${m.length!==1?"s":""}`:d.length>0&&m.length===0&&u.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:u.length>0&&d.length===0&&m.length===0?`Update access for ${u.length} user${u.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 h===S?"Remove Access":"Update Access"}return"Share"},g=()=>x||!t?!0:!j,C=()=>{const S=p();S&&f(S)&&l(S)},E=()=>{if(!i||i.role==="NONE"){const S=p();S&&f(S)&&l(S)}else{const S=i.role;if(h===S){const b=p();if(b&&f(b)){const T={...b,removeAccess:!0};l(T)}}else{const b=p();if(b&&f(b)){const T={...b,updateAccess:!0};l(T)}}}},R=()=>!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||u.length>0)&&e.jsxs(s.Button,{onClick:C,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(Ke,{className:"mr-2 h-4 w-4"}),!x&&y()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:E,disabled:g(),variant:R(),children:[x?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ke,{className:"mr-2 h-4 w-4"}),!x&&y()]})]})}function en({resource:t,resourceType:a,isSharing:n,isRemoving:r,isUpdating:l,onClose:o,onShare:c,onRemoveAccess:i}){var b,T,k,L;const{currentUser:d}=Ne(),[m,u]=A.useState("specific_users"),[h,p]=A.useState("specific_users"),f=s.useShareManagementActions(),j=s.useShareSelectedTab(),x=s.useShareCurrentMode(),{existingShares:y}=Ee({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant"}),{existingShares:g}=Ee({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"organization"}),C=(T=(b=y==null?void 0:y.shares)==null?void 0:b.tenantWide)==null?void 0:T[0],E=(L=(k=g==null?void 0:g.shares)==null?void 0:k.orgUsersOnly)==null?void 0:L[0],R=()=>{if(j==="org")return h;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]),N=(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(Ke,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:N?"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."})]}),N?e.jsxs(s.Tabs,{value:j,onValueChange:w=>{const B=w;f.setSelectedTab(B),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(Sr,{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(xt,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:w=>u(w),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(xt,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:w=>u(w),isSharing:n,isUpdating:l,isRemoving:r})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:N?j==="org"?e.jsx(pt,{resource:t,existingShares:g,isSharing:n,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:h,currentAllUsersShare:E,onRemoveAccess:i}):e.jsx(pt,{resource:t,existingShares:y,isSharing:n,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:R(),currentAllUsersShare:C,onRemoveAccess:i}):e.jsx(wr,{resource:t,isSharing:n,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:m,currentAllUsersShare:C,onRemoveAccess:i})})]})})}function me(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function De(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function sn(t,a,n){const{resourceType:r,resourceId:l,shareMutation:o,removeMutation:c,existingShares:i,resetUserSelections:d}=a;if(l)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const m=me(r,l,[{scope:"org_users_only",role:t.orgWideRole}]);o(m,{onSuccess:()=>{d()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:m,usersToRemove:u,usersToUpdate:h}=t;if(m&&m.length>0){const p=me(r,l,m.map(f=>({scope:"specific_org_user",orgUserId:f.id,role:f.role})));o(p,{onSuccess:()=>{d()}})}if(u&&u.length>0){const p=De(r,l,u.map(f=>{var x,y;const j=(y=(x=i==null?void 0:i.shares)==null?void 0:x.specificOrgUsers)==null?void 0:y.find(g=>g.orgUserId===f);return{scope:"specific_org_user",orgUserId:f,role:(j==null?void 0:j.role)||"VIEWER"}}));c(p,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(p=>{const f=me(r,l,[{scope:"specific_org_user",orgUserId:p.id,role:p.newRole}]);o(f,{onSuccess:()=>{d()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const m=me(r,l,[{scope:"all_tenants_only",role:t.allTenantsRole}]);o(m,{onSuccess:()=>{d()}})}else if(t.mode==="allTenantUsers"){const m=me(r,l,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);o(m,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:m,usersToRemove:u,usersToUpdate:h,tenantId:p}=t;if(u&&u.length>0){const f=De(r,l,u.map(j=>{var y,g;const x=(g=(y=i==null?void 0:i.shares)==null?void 0:y.specificTenantUsers)==null?void 0:g.find(C=>C.tenantUserId===j);return{scope:"specific_tenant_user",tenantUserId:j,tenantId:p,role:(x==null?void 0:x.role)||"VIEWER"}}));c(f,{onSuccess:()=>{d()}})}if(h&&h.length>0&&h.forEach(f=>{const j=me(r,l,[{scope:"specific_tenant_user",tenantUserId:f.id,tenantId:p,role:f.newRole}]);o(j,{onSuccess:()=>{d()}})}),m&&m.length>0){const f=me(r,l,m.map(j=>({scope:"specific_tenant_user",tenantUserId:j.id,tenantId:p,role:j.role})));o(f,{onSuccess:()=>{d()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const m=De(r,l,[{scope:"all_tenant_users",role:"VIEWER"}]);c(m,{onSuccess:()=>{d()}})}else if(t.updateAccess){const m=me(r,l,[{scope:"all_tenant_users",tenantId:n==null?void 0:n.tenantId,role:t.tenantWideRole}]);o(m,{onSuccess:()=>{d()}})}else{const m=me(r,l,[{scope:"all_tenant_users",tenantId:n==null?void 0:n.tenantId,role:t.tenantWideRole}]);o(m,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:m,usersToRemove:u,usersToUpdate:h}=t;if(m&&m.length>0){const p=me(r,l,m.map(f=>({scope:"specific_tenant_user",tenantUserId:f.id,role:f.role})));o(p,{onSuccess:()=>{d()}})}if(u&&u.length>0){const p=De(r,l,u.map(f=>{var x,y;const j=(y=(x=i==null?void 0:i.shares)==null?void 0:x.specificTenantUsers)==null?void 0:y.find(g=>g.tenantUserId===f);return{scope:"specific_tenant_user",tenantUserId:f,role:(j==null?void 0:j.role)||"VIEWER"}}));c(p,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(p=>{const f=me(r,l,[{scope:"specific_tenant_user",tenantUserId:p.id,role:p.newRole}]);o(f,{onSuccess:()=>{d()}})})}break}}function tn(t,a,n,r){var m,u,h,p,f,j;const{resourceType:l,resourceId:o,removeMutation:c,existingShares:i,resetUserSelections:d}=r;if(o)if(t.length>0){const x=De(l,o,t.map(y=>{var C,E;const g=(E=(C=i==null?void 0:i.shares)==null?void 0:C.specificTenantUsers)==null?void 0:E.find(R=>R.tenantUserId===y);return{scope:"specific_tenant_user",tenantUserId:y,role:(g==null?void 0:g.role)||"VIEWER"}}));c(x,{onSuccess:()=>{d()},onError:y=>{console.error("Remove access failed:",y)}})}else{const x=a==="tenant"&&n==="allTenants",y=a==="tenant"&&n==="allTenantUsers";if(x){const g=(u=(m=i==null?void 0:i.shares)==null?void 0:m.allTenantsOnly)==null?void 0:u[0];if(g){const C=De(l,o,[{scope:"all_tenants_only",role:g.role}]);c(C,{onSuccess:()=>{d()},onError:E=>{console.error("Remove all-tenants access failed:",E)}})}}else if(y){const g=(p=(h=i==null?void 0:i.shares)==null?void 0:h.tenantWide)==null?void 0:p[0];if(g){const C=De(l,o,[{scope:"all_tenant_users",role:g.role}]);c(C,{onSuccess:()=>{d()},onError:E=>{console.error("Remove all-tenant-users access failed:",E)}})}}else{const g=(j=(f=i==null?void 0:i.shares)==null?void 0:f.orgUsersOnly)==null?void 0:j[0];if(g){const C=De(l,o,[{scope:"org_users_only",role:g.role}]);c(C,{onSuccess:()=>{d()},onError:E=>{console.error("Remove org-wide access failed:",E)}})}}}}function Dr(t,a,n){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),o=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{currentUser:i}=Ne(),{existingShares:d}=Ee({debouncedSearchQuery:"",resourceId:t||"",resourceType:ee.DASHBOARD,userType:"tenant"}),m=A.useCallback(()=>{r.resetUserSelections()},[r]),u=A.useCallback(p=>{if(!t)return;const f={resourceType:ee.DASHBOARD,resourceId:t,shareMutation:a,removeMutation:n,existingShares:d,resetUserSelections:m};sn(p,f,i)},[t,a,n,d,m,i]),h=A.useCallback(()=>{if(!t)return;const p={resourceType:ee.DASHBOARD,resourceId:t,removeMutation:n,existingShares:d,resetUserSelections:m};tn(l,o||"",c||"",p)},[t,a,n,d,m,l,o,c]);return{handleShareSubmit:u,handleRemoveAccess:h}}function kr(t,a,n){const{currentUser:r}=Ne(),l=s.useShareManagementActions(),o=s.useShareUsersToRemove(),c=s.useShareSelectedTab(),i=s.useShareCurrentMode(),{existingShares:d}=Ee({debouncedSearchQuery:"",resourceId:t||"",resourceType:ee.VISUAL,userType:"tenant"}),m=A.useCallback(()=>{l.resetUserSelections()},[l]),u=A.useCallback(p=>{if(!t)return;const f={resourceType:ee.VISUAL,resourceId:t,shareMutation:a,removeMutation:n,existingShares:d,resetUserSelections:m};sn(p,f,r)},[t,a,n,d,m,r]),h=A.useCallback(()=>{if(!t)return;const p={resourceType:ee.VISUAL,resourceId:t,removeMutation:n,existingShares:d,resetUserSelections:m};tn(o,c||"",i||"",p)},[t,a,n,d,m,o,c,i]);return{handleShareSubmit:u,handleRemoveAccess:h}}function Er(t){const a=t.toUpperCase().indexOf("WHERE"),n=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),l=t.toUpperCase().indexOf("ORDER BY");let o=t.length;if(l!==-1&&(o=l),r!==-1&&r<o&&(o=r),a!==-1){const c=t.substring(0,a),i=t.substring(a);return`${c} {{ filters | where }} AND ${i.substring(6)}`}else if(n!==-1){const c=t.substring(0,n),i=t.substring(n);return`${c} {{ filters | where }} ${i}`}else{const c=t.substring(0,o),i=t.substring(o);return console.log("beforeClause",c),console.log("afterClause",i),i?`${c} {{ filters | where }} ${i}`:`${c.replace(/;$/,"")} {{ filters | where }}`}}function _s(t){const[a,n]=A.useState(null),[r,l]=A.useState(null);return A.useEffect(()=>{if(!t||t.trim()===""){n(null),l(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const i=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(i,{method:"HEAD"})).ok)throw new Error(`Module not found at ${i}`)}catch{}const d=await import(i);if(typeof d.useChartStore!="function")throw new Error("useChartStore is not a function");n(()=>d.useChartStore),l(null)}catch(c){const i=c instanceof Error?c.message:"Unknown error";console.error("Failed to load remote chart store:",i),l(i),n(null)}})()},[t]),a}function Tr(t,a){if(t.length===0)return"";if(a){const n=t.find(r=>r.id===a);if(n){const r=n.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const o=r.split("__")[0],c=t.find(i=>i.tabTitle===o);return c?c.id:t[0].id}return a}}return t[0].id}async function ft(t,a,n){if(!t||!a)throw new Error("Missing auth token or visual ID");const r=["resource-by-id","visual",a],l=n.getQueryData(r);if(l)return console.log("Using cached visual data for:",a),{data:l,fromCache:!0};console.log("Fetching visual data from network for:",a);const o=s.ue.loading("Loading visual...",{position:"top-center"});try{const c=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${a}`,{headers:{Authorization:`Bearer ${t}`}});if(!c.ok)throw new Error("Failed to load visual");const i=await c.json();return n.setQueryData(r,i),s.ue.dismiss(o),{data:i,fromCache:!1}}catch(c){throw s.ue.dismiss(o),c}}function Ir(t,a,n,r,l){const o=t.frameObject;a(o);const c=o.cards.find(i=>i.id===o.activeCardId);c&&n(c),r(!0),l(!0)}function Ar(){var p;const{setCardSql:t}=s.useEditorActions(),a=s.useEditorStore(f=>f.frame),n=s.useEditorStore(f=>f.card),r=_s(((p=n.customCardPreferences)==null?void 0:p.url)||""),l=s.useEditorStore(f=>f.selectedSchemaName),o=s.useEditorStore(f=>f.selectedDatamodelId),c=s.useEditorStore(f=>f.selectedDatabaseName),i=s.useEditorStore(f=>f.selectedTableName),d=s.useEditorStore(f=>f.selectedConnectionId),m=s.useEditorStore(f=>f.isShowingVisual),u=n.sql;return{getUpdatedFrame:A.useCallback(()=>{var g;let f=u;u&&!u.includes("{{")&&(f=Er(u),t(f));const j=(g=r==null?void 0:r.getState())==null?void 0:g.settings,x={...n,dataSource:n.dataSource||{mode:"directSource"},lastSelectedSchema:l,lastSelectedDatamodelId:o,lastSelectedDatabase:c,lastSelectedTable:i,connectionId:d,sql:f,customCfg:m?n.customCfg:null,...j&&{customCardPreferences:{...n.customCardPreferences,settings:j}}},y=a.cards.map(C=>C.id===n.id?x:C);return{...a,cards:y,activeCardId:Tr(y,a.activeCardId)}},[n,a,m,l,o,c,i,d,t,r,u])}}function Us(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient(),n=s.useSelectedVisual(),{selectVisual:r}=s.useManagementActions(),{setFrame:l,setCard:o}=s.useEditorActions(),{setIsDashboardEditing:c,setIsVisualEditing:i,setSelectedFrameId:d,addFrame:m,setIsDashboardPanelOpen:u}=s.useDashboardActions(),h=s.useDashboardStore(x=>x.selectedSheetId),p=or((n==null?void 0:n.id)||"",{enabled:!!(n!=null&&n.id)&&!!(t!=null&&t.accessToken)}),f=A.useCallback(async x=>{try{r(x);const{data:y,fromCache:g}=await ft((t==null?void 0:t.accessToken)||"",x.id,a);return Ir(y,l,o,c,i),{success:!0,fromCache:g}}catch(y){return console.error("Error editing visual:",y),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,a,r,l,o,c,i]),j=A.useCallback(async x=>{try{if(r(x),!h)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:y,fromCache:g}=await ft((t==null?void 0:t.accessToken)||"",x.id,a),C=y.frameObject;if(!C)return{success:!1,error:"Visual has no frame data"};const E={...C,id:s.v4()};return m(h,E,"end"),c(!0),d(E.id),u(!1),{success:!0,fromCache:g}}catch(y){return console.error("Error adding visual:",y),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,a,r,h,m,c,d,u]);return{visual:p.data,isLoading:p.isLoading,isError:p.isError,error:p.error,handleEditLibraryVisual:f,handleAddLibraryVisual:j,getUpdatedFrame:Ar().getUpdatedFrame,refetch:p.refetch}}function Mr(){const[t,a]=A.useState(""),[n,r]=A.useState(!1),[l,o]=A.useState(""),[c,i]=A.useState(""),[d,m]=A.useState(!1),[u,h]=A.useState(null),[p,f]=A.useState(!1),[j,x]=A.useState(null),[y,g]=A.useState(null),{setIsDashboardEditing:C,setIsVisualEditing:E}=s.useDashboardActions(),{handleEditLibraryVisual:R,handleAddLibraryVisual:S}=Us(),{resources:N,isLoading:b,isError:T,createResource:k,updateResource:L,deleteResource:w,duplicateResource:B,shareResource:D,isCreating:I,isDeleting:v,removeResourceShares:M,isSharing:F,isRemovingShares:O,isUpdatingShares:V}=cr(()=>{f(!1),x(null)},()=>{r(!1),o(""),i("")}),{handleShareSubmit:_,handleRemoveAccess:W}=kr((u==null?void 0:u.id)||null,D,M);Ne();const Q=N.filter(z=>{var X,oe;return((X=z==null?void 0:z.title)==null?void 0:X.toLowerCase().includes(t.toLowerCase()))||((oe=z==null?void 0:z.description)==null?void 0:oe.toLowerCase().includes(t.toLowerCase()))}),U=z=>new Date(z).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),q=()=>{l.trim()&&k({title:l,description:c,isPrivate:!1})},Y=z=>{x(z),f(!0)},$=()=>{j&&w(j.id)},{startUpdating:P,stopUpdating:G,isUpdating:H}=$t(),Z=(z,X)=>{const oe=X.title!==void 0?"title":"description";P(z,oe),L({resourceId:z,data:X},{onSuccess:()=>{G(z,oe)},onError:()=>{G(z,oe)}})},se=z=>{g(z),B(z,{onSettled:()=>g(null)})},ae=z=>{R(z)},te=z=>{S(z)},le=z=>{const X=N.find(oe=>oe.id===z);X&&L({resourceId:z,data:{isPrivate:!X.isPrivate}})},K=z=>{h(z),m(!0)};return s.useShareUsersToRemove(),s.useShareManagementActions(),Ee({debouncedSearchQuery:"",resourceId:(u==null?void 0:u.id)||"",resourceType:ee.VISUAL,userType:"tenant"}),b?e.jsx(_t,{}):T?e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load visuals"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]})}):e.jsxs("div",{className:"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:z=>o(z.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter visual description...",value:c,onChange:z=>i(z.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:q,size:"sm",className:"h-7 text-xs",disabled:!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:z=>a(z.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:Q.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(ms,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No visuals found"})]}):Q.map(z=>e.jsx(ur,{visual:z,onAddVisual:te,onEditVisual:ae,onUpdateVisual:Z,onDeleteClick:Y,onDuplicateVisual:se,onTogglePrivacy:le,onShareVisual:K,isDeleting:v,isDuplicating:y===z.id,isTitleUpdating:H(z.id,"title"),isDescriptionUpdating:H(z.id,"description"),formatDate:U},z.id))})}),d&&u&&e.jsx(en,{resource:u,resourceType:ee.VISUAL,onShare:_,isSharing:F,isRemoving:O,isUpdating:V,onClose:()=>{m(!1),h(null)},onRemoveAccess:W}),e.jsx(s.AlertDialog,{open:p,onOpenChange:z=>{!z&&v||(f(z),z||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:v,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:z=>{z.preventDefault(),z.stopPropagation(),$()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:v,children:v?"Deleting...":"Delete"})]})]})})]})}function Lr({dashboard:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onLoadDashboard:o,onUpdateDashboard:c,onDeleteClick:i,onDuplicateDashboard:d,onShareDashboard:m,formatDate:u,onDashboardItemClick:h}){var N;const{selectDashboard:p}=s.useManagementActions(),f=s.useIsDashboardSelected(t.id),[j,x]=A.useState(!1),[y,g]=A.useState(!1),C=s.useDashboardStore(b=>b.actions.setIsDashboardPanelOpen);A.useEffect(()=>{n?(x(!0),g(!0)):y&&(x(!1),g(!1))},[n,y]);const E=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(Lt,{className:"h-3 w-3 text-purple-500"}):e.jsx(ve,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(ke,{className:"h-3.5 w-3.5 text-slate-500"}),R=()=>e.jsx(s.LayoutDashboard,{className:"h-4 w-4 text-slate-400"}),S=()=>{p(t),o(t.id),h==null||h(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",f&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:S,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:R()})}),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:b=>c==null?void 0:c(t.id,{title:b}),isEditable:t.permissions.canEdit&&f,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:E()})]}),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:b=>c==null?void 0:c(t.id,{description:b}),isEditable:t.permissions.canEdit&&f,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: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:b=>b.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:b=>{b.preventDefault(),b.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:b=>{b.stopPropagation(),m(t)},children:[e.jsx(ve,{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:b=>{b.stopPropagation(),i(t),C(!1)},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(ke,{className:"h-3 w-3"}),e.jsx("span",{children:((N=t.ownership.createdBy)==null?void 0:N.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 Rr({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 Or(t){const[a,n]=A.useState(""),[r,l]=A.useState(!1),[o,c]=A.useState(""),[i,d]=A.useState(""),[m,u]=A.useState(!1),[h,p]=A.useState(null),[f,j]=A.useState(!1),[x,y]=A.useState(null),[g,C]=A.useState(null),E=s.useManagementStore(K=>K.lastSelectedDashboard),R=s.useManagementStore(K=>K.actions.selectDashboard);s.useShareManagementActions(),s.useShareUsersToRemove(),s.useShareSelectedTab(),s.useShareCurrentMode();const{resources:S,isLoading:N,isError:b,createResource:T,updateResource:k,deleteResource:L,duplicateResource:w,isCreating:B,isDeleting:D,isSharing:I,isRemovingShares:v,isUpdatingShares:M,shareResource:F,removeResourceShares:O}=ir(()=>{j(!1),y(null),E&&R(E)},()=>{l(!1),c(""),d("")}),{handleShareSubmit:V,handleRemoveAccess:_}=Dr((h==null?void 0:h.id)||null,F,O),{currentUser:W}=Ne(),Q=S.filter(K=>{var z,X;return((z=K==null?void 0:K.title)==null?void 0:z.toLowerCase().includes(a.toLowerCase()))||((X=K==null?void 0:K.description)==null?void 0:X.toLowerCase().includes(a.toLowerCase()))}),U=K=>new Date(K).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),q=()=>{o.trim()&&T({title:o,description:i,isPrivate:!1})},Y=K=>{var z;(z=t.onLoadDashboard)==null||z.call(t,K)},$=K=>{y(K),j(!0)},P=()=>{x&&L(x.id)},G=K=>{C(K),w(K,{onSettled:()=>C(null)})},{startUpdating:H,stopUpdating:Z,isUpdating:se}=$t(),ae=(K,z)=>{const X=z.title!==void 0?"title":"description";H(K,X),k({resourceId:K,data:z},{onSuccess:()=>{Z(K,X)},onError:()=>{Z(K,X)}})},te=K=>{const z=S.find(X=>X.id===K);z&&k({resourceId:K,data:{isPrivate:!z.isPrivate}})},le=K=>{p(K),W==null||W.type,u(!0)};return Ee({debouncedSearchQuery:"",resourceId:(h==null?void 0:h.id)||"",resourceType:ee.DASHBOARD,userType:"tenant"}),N?e.jsx(_t,{}):b?e.jsx(Rr,{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:K=>c(K.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:K=>d(K.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()||B,children:B?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{l(!1),c(""),d("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:B,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>l(!0),className:"h-8 w-full",size:"sm",disabled:B,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),B?"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:K=>n(K.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:Q.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(ma,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No dashboards found"})]}):Q.map(K=>e.jsx(Lr,{dashboard:K,isDeleting:D,isDuplicating:g===K.id,isTitleUpdating:se(K.id,"title"),isDescriptionUpdating:se(K.id,"description"),onLoadDashboard:Y,onEditDashboard:t.onEditDashboard,onUpdateDashboard:ae,onDeleteClick:$,onDuplicateDashboard:G,onTogglePrivacy:te,onShareDashboard:le,formatDate:U,onDashboardItemClick:t.onDashboardItemClick},K.id))})}),m&&h&&e.jsx(en,{resource:h,resourceType:ee.DASHBOARD,onShare:V,isSharing:I,isRemoving:v,isUpdating:M,onClose:()=>{u(!1),p(null)},onRemoveAccess:_}),e.jsx(s.AlertDialog,{open:f,onOpenChange:K=>{!K&&D||(j(K),K||y(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:D,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:K=>{K.preventDefault(),K.stopPropagation(),P()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:D,children:D?"Deleting...":"Delete"})]})]})})]})}function nn({isOpen:t,onClose:a,className:n,onDashboardItemClick:r}){s.useDashboardStore(f=>f.dashboard);const{setDashboard:l,addSheet:o}=s.useDashboardStore(f=>f.actions),{currentUser:c}=Ne(),i=c,[d,m]=s.useLocalStorageState("resource-management-active-tab","dashboards"),u=Kt(a,{enabled:t}),h=f=>{},p=f=>{console.log("Editing dashboard:",f)};return e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{ref:u,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":"hidden -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:i&&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:i.name}),e.jsx(s.AvatarFallback,{className:"text-xs",children:i.name.charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-xs font-medium",children:i.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:i.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:i.email}),i.role&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Role:"," ",s.toTitleCase(i.role.replace(/_/g," "))]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",i.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:d,onValueChange:m,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(Or,{onLoadDashboard:h,onEditDashboard:p,onDashboardItemClick:r})}),e.jsx(s.TabsContent,{value:"visuals",className:"flex-1",children:e.jsx(Mr,{})})]})})]})})}function Br(){var Y,$;const{authToken:t,tokenProps:a}=s.useSemaphorContext();s.useDashboardStore(P=>P.theme);const n=s.useDashboardStore(P=>P.lenses),r=s.useDashboardStore(P=>P.selectedLensId),l=n==null?void 0:n.find(P=>P.id===r),o=s.useDashboardStore(P=>P.dashboard);s.useDashboardStore(P=>P.selectedSheetId);const c=s.useDashboardStore(P=>P.isDashboardEditing),i=s.useEditorStore(P=>P.card),d=s.useEditorStore(P=>P.selectedConnectionId),[m,u]=A.useState(!1),h=s.useDashboardStore(P=>P.isDashboardPanelOpen),p=s.useDashboardStore(P=>P.actions.setIsDashboardPanelOpen),f=s.useDashboardStore(P=>P.filterValues),j=s.useDashboardStore(P=>P.isVisualEditing),x=s.useManagementStore(P=>P.selectedDashboard),y=s.useManagementStore(P=>P.initialDashboard),g=x?($=x==null?void 0:x.permissions)==null?void 0:$.canEdit:(Y=y==null?void 0:y.permissions)==null?void 0:Y.canEdit,C=s.useDashboardStore(P=>P.showFilters);s.useDashboardStore(P=>P.showDashboardJSON);const E=s.useDashboardStore(P=>P.onSaveFunction),R=s.useDashboardStore(P=>P.actions.setShowFilters),{addFrame:S,setSelectedFrameId:N}=s.useDashboardStore(P=>P.actions),{getSelectedSheet:b,setIsDashboardEditing:T,setShowDashboardJSON:k}=s.useDashboardStore(P=>P.actions),L=b(),{setInitialDashboard:w}=s.useManagementStore(P=>P.actions),{resources:B}=Vs(ee.DASHBOARD);A.useEffect(()=>{if(B&&B.length>0){const P=o==null?void 0:o.id;if(P){const G=B.find(H=>H.id===P);G&&w(G)}}},[B,o==null?void 0:o.id,w]);const D=a.orgUserId||a.tenantId,I=c&&!j&&D&&g;function v(){var Z,se;const P=i.dataSource;if(P)return P;const G=(se=(Z=o.aiContext)==null?void 0:Z.selectedEntities)==null?void 0:se[0],H=G==null?void 0:G.type;if(G)return{connectionId:G.connectionId,connectionType:G.connectionType,type:H,selectedEntities:[G]}}const M=()=>{if(!c||!L)return;const G={dataSource:v(),mode:"explorer",connectionId:d,id:s.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},H={id:s.v4(),cards:[G],activeCardId:G.id};S(L.id,H),N(H.id)},F=()=>{T(!0)},[O,V]=A.useState(!1),_=Ut(ee.DASHBOARD);async function W(){const P=as(o);V(!0);const G={template:P};_.mutate({resourceId:P.id,data:G},{onSuccess:()=>{V(!1),s.ue.success("Dashboard saved!")},onError:()=>{V(!1),s.ue.error("Failed to save dashboard")}})}async function Q(){if(u(!0),!r||!l)return;const P=as(o),G=JSON.stringify(P),H={...l,template:G,filterValues:f};await ks(H,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),E==null||E(P),u(!1)}if(j)return null;const U=(l==null?void 0:l.name)||o.title,q=a.orgUserId||a.tenantId&&a.endUserId&&a.endUserEmail;return e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b py-2 pl-3 pr-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[q&&e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:"Manage Dashboards",onClick:()=>p(!0),className:"h-7 p-2",children:e.jsx(fa,{className:"h-4 w-4"})}),!j&&e.jsx(s.Label,{children:U})]}),e.jsxs("div",{className:"flex gap-2",children:[!1,!j&&e.jsx(_a,{}),!j&&e.jsx(Vt,{}),c&&!j&&D&&e.jsx(za,{}),!j&&D&&e.jsx(Va,{}),c&&!j&&e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",disabled:!c,onClick:M,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!j&&!c&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:F,size:"sm",children:[e.jsx(s.Pencil,{className:"mr-2 h-4 w-4"}),"Edit"]}),c&&!j&&e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",onClick:()=>{T(!1),k(!1)},children:[e.jsx(s.Cross2Icon,{className:"mr-2 h-4 w-4"}),"Close"]}),c&&!j&&D&&l&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:m,onClick:Q,size:"sm",children:[e.jsx(Ds,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),I&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"outline",disabled:O,onClick:W,size:"sm",children:[O?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Ds,{className:"mr-2 h-4 w-4"}),O?"Saving...":"Save"]}),!C&&!j&&c&&e.jsx(s.Button,{className:"h-7 p-2",variant:"ghost",onClick:()=>R(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!j&&c&&!1,!j&&!1,!j&&e.jsx(nn,{isOpen:h,onClose:()=>p(!1)})]})]})}function Fr({name:t,items:a,value:n,onChange:r,isLoading:l,isError:o,refetch:c,className:i,icon:d,showNone:m=!1}){const u=ue.useRef(null),[h,p]=ue.useState(!1),[f,j]=ue.useState("100%"),x=m?[...a||[],{id:"none",name:"None"}]:a;ue.useLayoutEffect(()=>{u.current&&j(u.current.offsetWidth)},[]);function y(){var C;return l?"Loading...":o?"Error":n?(C=a==null?void 0:a.find(E=>E.id===n))==null?void 0:C.name:`Select ${t}`}function g(C,E){r(E),p(!1)}return e.jsxs(s.Popover,{open:h,onOpenChange:p,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{ref:u,variant:"outline",role:"combobox","aria-expanded":h,className:s.cn("flex h-9 w-full justify-between",i),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[d&&e.jsx("div",{className:"mr-2",children:d}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children:y()})]}),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(Rt,{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(C=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:C.name,onSelect:E=>g(E,C.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",n===C.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:C.name,children:C.name})]})},C.id))})]})]})})]})}function Ve({title:t,items:a,value:n,isLoading:r,isError:l,refetch:o,onChange:c,showNone:i=!1,className:d,disabled:m=!1,type:u="combobox"}){const h=r?"Loading...":l?"Error":n;function p(){if(t==="Connection")return e.jsx(ka,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(wa,{className:"size-4"});if(t==="Table")return e.jsx(_e,{className:"size-4"});if(t==="Model")return e.jsx(Xn,{className:"size-4"})}function f(){return e.jsxs(s.Select,{disabled:m,value:h,onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:s.cn("h-9 w-full border-muted focus:ring-1 focus:ring-offset-0",d),children:e.jsx(s.SelectValue,{placeholder:r?"Loading...":l?"Error":`Select ${t}`})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[r?e.jsx(s.SelectLabel,{children:"Loading..."}):e.jsxs(s.SelectLabel,{className:"flex items-center justify-between gap-2",children:[t,e.jsx(Rt,{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,y)=>e.jsx(s.SelectItem,{value:x.id,children:x.name},y))]}),(r||l)&&e.jsx(s.SelectItem,{value:h,children:h})]})})]})}function j(){return e.jsx(Fr,{icon:p(),items:a,value:h,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:u==="select"?f():j()})})}function Pr({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(),u=s.useEditorStore(x=>x.actions.setSqlGen),h=s.useEditorStore(x=>x.actions.setCardSql),p=s.useEditorStore(x=>x.actions.setRunSql);function f(x,y){var R;const g=s.createSqlGenConfig(x,i,y),C=(R=d==null?void 0:d.find(S=>S.id===c))==null?void 0:R.name;u(g);const E=s.getSql(g,s.fmt(l||""),s.fmt(r),C||"",m,o||"");E&&(h(E),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 $s({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(Ge,{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(ns,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(Zn,{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 gs({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($s,{column:t}),e.jsx("span",{children:t.column_name})]})}function zr({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 Vr({onClick:t,column:a}){const n=s.useDndStore(u=>u.activeId),r=s.useEditorStore(u=>{var h;return(h=u.card.queryConfig)==null?void 0:h.groupByColumns}),l=s.useEditorStore(u=>{var h;return(h=u.card.queryConfig)==null?void 0:h.metricColumns}),o=s.useEditorStore(u=>{var h;return(h=u.card.queryConfig)==null?void 0:h.filterColumns});function c(u){return i(u)||d(u)||m(u)}function i(u){return r==null?void 0:r.some(h=>h.name===u.column_name)}function d(u){return l==null?void 0:l.some(h=>h.name===u.column_name)}function m(u){return o==null?void 0:o.some(h=>h.name===u.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(gs,{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(gs,{column:a})}),e.jsx(zr,{id:a.column_name,type:"column",children:e.jsx(gs,{column:a})})]})}const js={id:"__placeholder__",role:"groupby",type:"string"},ys={id:"__placeholder__",role:"groupby",type:"string"},bs={id:"__placeholder__",role:"metric",type:"number"},vs={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},an={id:"__placeholder__"},Ae="droppable-group-by",Me="droppable-metrics",Le="droppable-pivot-by",ls="sortable-group-by",Es="sortable-metrics",os="sortable-pivot-by",Ts="droppable-filters",Is="sortable-filters",qs="sortable-order-by";function _r(){const t=s.useDndStore(I=>I.insertIndex),a=s.useEditorStore(I=>{var v;return((v=I.card.queryConfig)==null?void 0:v.groupByColumns)||[]}),n=s.useEditorStore(I=>{var v;return((v=I.card.queryConfig)==null?void 0:v.metricColumns)||[]}),r=s.useEditorStore(I=>{var v;return((v=I.card.queryConfig)==null?void 0:v.filterColumns)||[]}),l=s.useEditorStore(I=>{var v;return((v=I.card.queryConfig)==null?void 0:v.orderBy)||[]}),o=s.useEditorStore(I=>{var v;return((v=I.card.queryConfig)==null?void 0:v.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:i,setPreviewGroupByColumns:d,setPreviewMetricColumns:m,setPreviewFilterColumns:u,setPreviewPivotColumns:h}=s.useDndActions(),{setGroupByColumns:p,setMetricColumns:f,setFilterColumns:j,setOrderByColumns:x,setPivotByColumns:y}=s.useEditorActions(),{columns:g}=s.useDataColumns(),{formattedTableName:C}=s.useEditorAside(),E=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),R=I=>{var F;const{active:v,over:M}=I;if(((F=v.data.current)==null?void 0:F.type)==="column"&&M){const O=M.id,V=g.find(U=>U.column_name===v.id);if(!V)return;const _=s.isNumberDataType(V.data_type),W=s.isTextDataType(V.data_type),Q=s.isDateDataType(V.data_type);if(W||Q){if(a.some(q=>q.id===O)){const q=a.findIndex($=>$.id===O);c(q);const Y=a.filter($=>$.id!==js.id);Y.splice(q,0,js),d(Y)}else if(M.id===Ae){c(a.length);const q=[...a,js];d(q),m(n),u(r)}}if(W||Q){if(o.some(q=>q.id===O)){const q=o.findIndex($=>$.id===O);c(q);const Y=o.filter($=>$.id!==ys.id);Y.splice(q,0,ys),h(Y)}else if(M.id===Le){c(o.length);const q=[...o,ys];h(q),d(a),m(n),u(r)}}if(_||W){if(n.some(q=>q.id===O)){console.log("isOverMetricSortable",O);const q=n.findIndex($=>$.id===O);c(q);const Y=n.filter($=>$.id!==bs.id);Y.splice(q,0,bs),m(Y)}else if(M.id===Me){c(n.length);const q=[...n,bs];m(q),u(r),d(a),h(o)}}if(N(V)){if(r.some(q=>q.id===O)){const q=r.findIndex($=>$.id===O);c(q);const Y=r.filter($=>$.id!==vs.id);Y.splice(q,0,vs),u(Y)}else if(M.id===Ts){c(r.length);const q=[...r,vs];u(q),m(n),d(a),h(o)}}}else d(a),m(n),u(r),h(o)};function S(I){i(I.active.id),c(null),d(a),m(n),u(r),h(o)}function N(I){return!r.some(v=>v.name===I.column_name)}function b(I,v="SUM"){const{column_name:M,data_type:F}=I,O=[...n],V=t!==null?t:n.length,_={...I,id:fe(M),name:M,label:We(M,v),type:F,role:"metric",aggregate:v};O.splice(V,0,_),f(O)}function T(I){const v=s.isTextDataType(I.data_type);s.isDateDataType(I.data_type);const M=[...o],F=t!==null?t:o.length;let O;v?O={...I,id:fe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:O={...I,id:fe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:Ue(I.column_name,"month"),granularity:"month"},M.splice(F,0,O),y(M)}function k(I){const v=s.isTextDataType(I.data_type);s.isDateDataType(I.data_type);const M=[...a],F=t!==null?t:a.length;let O;v?O={...I,id:fe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:O={...I,id:fe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:Ue(I.column_name,"month"),granularity:"month"},M.splice(F,0,O),p(M)}function L(I){const v=[...r],M=t!==null?t:r.length,F={...I,id:fe(I.column_name),name:I.column_name,type:I.data_type,sql:s.getDefaultFilterSql(I.data_type,C,s.fmt(I.column_name)),role:"filter"};v.splice(M,0,F),j(v)}function w(I){var O,V,_,W,Q,U,q,Y;const{active:v,over:M}=I,F=v.data.current;if((F==null?void 0:F.type)==="column"&&M){const $=g.find(Z=>Z.column_name===v.id);if(!$)return;const P=s.isNumberDataType($.data_type),G=s.isTextDataType($.data_type),H=s.isDateDataType($.data_type);(G||H)&&(M.id===Ae||((O=M.data.current)==null?void 0:O.type)===ls)&&k($),(G||H)&&(M.id===Le||((V=M.data.current)==null?void 0:V.type)===os)?T($):(P||G)&&(M.id===Me||((_=M.data.current)==null?void 0:_.type)===Es)?(P&&b($),G&&b($,"COUNT")):N($)&&(M.id===Ts||((W=M.data.current)==null?void 0:W.type)===Is)&&L($)}if(M&&((Q=M.data.current)==null?void 0:Q.type)===ls&&a.some($=>$.id===v.id)){const $=a.findIndex(G=>G.id===v.id),P=a.findIndex(G=>G.id===M.id);if($!==-1&&P!==-1&&$!==P){const G=[...a],[H]=G.splice($,1);G.splice(P,0,H),p(G)}}if(M&&((U=M.data.current)==null?void 0:U.type)===os&&o.some($=>$.id===v.id)){const $=o.findIndex(G=>G.id===v.id),P=o.findIndex(G=>G.id===M.id);if($!==-1&&P!==-1&&$!==P){const G=[...o],[H]=G.splice($,1);G.splice(P,0,H),y(G)}}if(M&&((q=M.data.current)==null?void 0:q.type)===Es&&n.some($=>$.id===v.id)){const $=n.findIndex(G=>G.id===v.id),P=n.findIndex(G=>G.id===M.id);if($!==-1&&P!==-1&&$!==P){const G=[...n],[H]=G.splice($,1);G.splice(P,0,H),f(G)}}if(M&&((Y=M.data.current)==null?void 0:Y.type)===Is&&r.some($=>$.id===v.id)){const $=r.findIndex(G=>G.id===v.id),P=r.findIndex(G=>G.id===M.id);if($!==-1&&P!==-1&&$!==P){const G=[...r],[H]=G.splice($,1);G.splice(P,0,H),j(G)}}B(I),i(null),c(null),d(a),m(n),u(r),h(o)}function B(I){const{active:v,over:M}=I,F=v.data.current;if((F==null?void 0:F.type)===qs&&M){const O=l.findIndex(_=>Ye(_.columnId)===v.id),V=l.findIndex(_=>Ye(_.columnId)===M.id);if(O!==-1&&V!==-1&&O!==V){const _=[...l],[W]=_.splice(O,1);_.splice(V,0,W),x(_)}}}function D(){i(null),c(null),d(a),m(n),u(r)}return{handleDragOver:R,handleDragEnd:w,handleDragStart:S,handleDragCancel:D,sensors:E}}function fe(t){return`${t}-${s.v4()}`}function We(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 Ye(t){return`${qs}-${t}`}function Ue(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 Ur({schemaName:t,tableName:a,columns:n,status:r}){const l=s.useEditorStore(v=>v.sqlGen),o=s.useEditorStore(v=>v.isDevMode),c=s.useEditorStore(v=>v.selectedConnectionId),i=s.useEditorStore(v=>{var M,F;return(F=(M=v.card)==null?void 0:M.queryConfig)==null?void 0:F.metricColumns});s.useEditorStore(v=>{var M,F;return(F=(M=v.card)==null?void 0:M.queryConfig)==null?void 0:F.groupByColumns});const d=s.useEditorStore(v=>v.selectedDatabaseName),m=s.useEditorStore(v=>v.selectedSchemaName),u=s.useEditorStore(v=>v.selectedTableName),h=s.useEditorStore(v=>v.selectedDatamodelId),p=s.useDashboardStore(v=>v.dashboard.aiScopeTables),{addToAIScope:f,removeFromAIScope:j}=s.useDashboardActions(),{addColumnToMetricColumns:x,addColumnToGroupBy:y,setCardSql:g,setRunSql:C,setSqlGen:E,setIsShowingVisual:R}=s.useEditorActions(),{connectionType:S,modelItems:N,selectedDatamodelName:b}=s.useEditorAside();function T(v){var M;if(o){const F=s.createSqlGenConfig(v,l);E(F);const O=(M=N==null?void 0:N.find(_=>_.id===h))==null?void 0:M.name,V=s.getSql(F,s.fmt(t),s.fmt(a),O||"",S,d||"");V&&(g(V),C(!0))}if(!o){if(s.isTextDataType(v.data_type))if(i&&i.length>0){const F={...v,role:"groupby",id:fe(v.column_name),name:v.column_name,type:v.data_type};y(F)}else{const F={...v,role:"metric",id:fe(v.column_name),name:v.column_name,label:We(v.column_name,"COUNT"),type:v.data_type,aggregate:"COUNT"};x(F)}if(s.isDateDataType(v.data_type)){const F={...v,role:"groupby",id:fe(v.column_name),name:v.column_name,type:v.data_type,label:Ue(v.column_name,"month"),granularity:"month"};y(F)}if(s.isNumberDataType(v.data_type)){const F={...v,role:"metric",id:fe(v.column_name),name:v.column_name,label:We(v.column_name,"SUM"),type:v.data_type,aggregate:"SUM"};x(F)}}}function k(v){v===!0&&(u||b)&&c?(f({connectionId:c,connectionType:S==="S3"||S==="API"?"DuckDb":S||"",databaseName:d||"",schemaName:m||"",tableName:u||"",datamodelName:s.resolveDatamodelName(b),datamodelId:h||""}),s.ue.success("Added to Assistant Scope",{position:"top-right",duration:2500,richColors:!0})):(j({connectionId:c||"",connectionType:S||"",tableName:u||"",datamodelName:s.resolveDatamodelName(b),datamodelId:h||"",databaseName:d||"",schemaName:m||""}),s.ue("Removed from Assistant Scope",{position:"top-right",duration:2e3,richColors:!0}))}function L(){const v=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:b,connectionType:S,databaseName:d||""});R(!1);const M=S==="MSSQL"?`SELECT top 10 * FROM ${v}`:`SELECT * FROM ${v} LIMIT 10`;g(M),C(!0)}function w(){const v=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:b,connectionType:S,databaseName:d||""});g(`SELECT COUNT(*) as count FROM ${v}`),C(!0)}function B(){return(p==null?void 0:p.find(v=>v.connectionId===c&&(v.tableName===u||v.datamodelName===b)))!==void 0}function D(v){return o?e.jsxs("div",{className:"flex grow items-center justify-between space-x-2 rounded-md px-2 py-1",onClick:()=>T(v),children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx($s,{column:v}),e.jsx("span",{children:v.column_name})]}),e.jsx("div",{onClick:M=>M.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(v.data_type)&&e.jsx(Pr,{column:v})})]}):e.jsx(Vr,{onClick:T,column:v})}function I(){return e.jsxs(e.Fragment,{children:[e.jsxs(s.Toggle,{title:`${B()?"Remove from":"Add to"} Assistant Scope`,pressed:B(),onPressedChange:k,variant:"outline",className:s.cn("h-9 px-2",{}),children:[e.jsx(s.Plus,{className:s.cn("mr-1 size-4",{"text-green-400":B(),"text-muted-foreground":!B()})}),"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(va,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:w,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(Ot,{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((v,M)=>e.jsx(s.Skeleton,{className:"h-7 w-full"},M))}):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(v=>e.jsx("div",{className:s.cn("mr-2 cursor-pointer rounded-md text-sm transition-colors hover:bg-muted"),children:D(v)},v.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function rn({ColumnsComponent:t,type:a}){var Te;const n=s.useEditorStore(ne=>ne.card),r=s.useEditorStore(ne=>ne.selectedConnectionId),l=s.useDashboardStore(ne=>ne.showFilters),o=s.useEditorStore(ne=>ne.selectedDatamodelId),c=s.useEditorStore(ne=>ne.selectedDatabaseName),i=s.useEditorStore(ne=>ne.selectedSchemaName),d=s.useEditorStore(ne=>ne.selectedTableName),m=s.useEditorStore(ne=>ne.isDevMode),{setSelectedTableName:u,setIsDevMode:h,setCardSql:p}=s.useEditorActions(),{connectionItems:f,modelItems:j,schemaItems:x,databaseItems:y,tableItems:g,columns:C,isConnectionsLoading:E,isModelsLoading:R,isConnectionsError:S,isModelsError:N,isDatabasesLoadingOrFetching:b,isDatabaseError:T,isSchemaLoadingOrFetching:k,isSchemaError:L,isColumnsError:w,isColumnsLoadingOrFetching:B,isTableLoadingOrFetching:D,isTableError:I,connectionType:v,isNonDbConnection:M,refetchDatabases:F,refetchModels:O,refetchSchemas:V,refetchTables:_,refetchColumns:W,refetchConnections:Q,handleConnectionChange:U,handleDatabaseChange:q,handleSchemaChange:Y,handleDatamodelChange:$,handleTableChange:P,tableName:G,schemaName:H}=s.useEditorAside(),{data:Z,refetch:se}=s.useDashboardCardQuery(n);function ae(){return t?t(H,G,C):e.jsx(Ur,{schemaName:H,tableName:G,columns:C,status:B?"Loading...":w?"Error":"Success"})}function te(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function le(ne){ne===!0?Z&&(p(Z.userSql),setTimeout(()=>{se()},100)):p(""),h(ne)}function K(){if(!r||v==="S3"||v==="API")return null;if(!o||o==="none")return e.jsx(Ve,{refetch:F,showNone:!0,onChange:q,isError:T,isLoading:b,items:y,value:c||"",title:"Database",type:"combobox"})}function z(){if(r&&!M&&(!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 X(){if(!r||v==="S3"||v==="API")return null;if(!c||c==="none")return e.jsx(Ve,{refetch:O,showNone:!0,onChange:$,isError:N,isLoading:R,items:j,value:o||"",title:"Model",type:"combobox"})}function oe(){return!r||v==="S3"||v==="API"||!c||c==="none"?null:e.jsx(Ve,{refetch:V,onChange:Y,isError:L,isLoading:k,items:x,value:i||"",title:"Schema",type:"combobox"})}function Ce(){function ne(){let ie=!1;return v==="API"?(ie=!1,ie):((v==="S3"||r&&c&&c!=="none"&&i)&&(ie=!0),ie)}return ne()?e.jsx(Ve,{refetch:_,onChange:P,isError:I,items:g,isLoading:D,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(Ve,{refetch:Q,items:f,title:"Connection",value:r||"",onChange:U,isLoading:E,isError:S,type:"combobox",connectionTooltip:((Te=f==null?void 0:f.find(ne=>ne.id===r))==null?void 0:Te.type)||""}),K(),z(),X(),oe(),Ce()]}),ae(),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:le,id:"dev-mode"}),e.jsx(s.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(s.Button,{onClick:te,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(Ca,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function ln({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 u(){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 h(){o(!1),i.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${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:u,onMouseDown:h,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),l&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function on({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(ln,{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(ia,{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(pa,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function cn({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(At,{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(on,{sql:t,error:a,onDebugWithAssistant:n})})]})}var dn={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},gt=A.createContext&&A.createContext(dn),$r=["attr","size","title"];function qr(t,a){if(t==null)return{};var n=Yr(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 Yr(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 is(){return is=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},is.apply(this,arguments)}function jt(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 cs(t){for(var a=1;a<arguments.length;a++){var n=arguments[a]!=null?arguments[a]:{};a%2?jt(Object(n),!0).forEach(function(r){Gr(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):jt(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Gr(t,a,n){return a=Hr(a),a in t?Object.defineProperty(t,a,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[a]=n,t}function Hr(t){var a=Kr(t,"string");return typeof a=="symbol"?a:a+""}function Kr(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 un(t){return t&&t.map((a,n)=>A.createElement(a.tag,cs({key:n},a.attr),un(a.child)))}function Oe(t){return a=>A.createElement(Qr,is({attr:cs({},t.attr)},a),un(t.child))}function Qr(t){var a=n=>{var{attr:r,size:l,title:o}=t,c=qr(t,$r),i=l||n.size||"1em",d;return n.className&&(d=n.className),t.className&&(d=(d?d+" ":"")+t.className),A.createElement("svg",is({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,c,{className:d,style:cs(cs({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 gt!==void 0?A.createElement(gt.Consumer,null,n=>a(n)):a(dn)}function Wr(t){return Oe({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 mn(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(),u=A.useRef(),h=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(u.current&&c){const x=u.current.getModel();x&&(h.current[l.id]=x);let y=h.current[o];if(!y){const g=f();y=c.editor.createModel(g,t),h.current[o]=y}u.current.setModel(y)}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",y=n==="system"?x:n;c.editor.defineTheme("default",{base:y==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":y==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[a,n,c]),A.useEffect(()=>{const x=u.current;x&&c&&l&&x.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return i(),!1})},[c,i,l]);function j(x,y){if(u.current=x,!h.current[l.id]){const g=x.getModel(),C=f();h.current[l.id]=g||(y==null?void 0:y.editor.createModel(C,t))||x.getModel()}x.setModel(h.current[l.id])}return{handleEditorDidMount:j}}function Jr(){const t=s.useEditorStore(c=>c.card.sql),a=s.useEditorStore(c=>c.sqlGen),{setCardSql:n,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=mn("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 Xr(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:a}=s.useEditorActions(),{handleEditorDidMount:n}=mn("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 Zr({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 Ys({variant:t="outline"}){var c;const{setCardSql:a}=s.useEditorActions();s.useEditorStore(i=>i.frame);const n=s.useEditorStore(i=>i.card);_s(((c=n.customCardPreferences)==null?void 0:c.url)||""),s.useEditorStore(i=>i.selectedSchemaName),s.useEditorStore(i=>i.selectedDatamodelId),s.useEditorStore(i=>i.selectedDatabaseName),s.useEditorStore(i=>i.selectedTableName),s.useEditorStore(i=>i.selectedConnectionId),s.useEditorStore(i=>i.isShowingVisual),n.sql;const r=s.useEditorStore(i=>i.onSave),{getUpdatedFrame:l}=Us();function o(){const i=l();r==null||r(i)}return e.jsxs(s.Button,{onClick:o,className:"h-8",size:"sm",variant:t,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function el(){const t=s.useQueryClient(),[a,n]=A.useState(!1),r=s.useDashboardStore(m=>m.actions.setIsDashboardPanelOpen),{setIsVisualEditing:l}=s.useDashboardActions(),{getUpdatedFrame:o}=Us(),c=s.useSelectedVisual(),i=dr(),d=()=>{const m=o();if(!(c!=null&&c.id)){s.ue.error("No visual selected");return}n(!0),i.mutate({visualId:c.id,data:{frameObject:m}},{onSuccess:()=>{n(!1),l(!1),r(!0),s.ue.success("Visual updated successfully"),t.invalidateQueries({queryKey:["resource-by-id","visual",c.id],exact:!0})},onError:()=>{n(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:d,className:"h-8",size:"sm",children:[a&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!a&&e.jsxs(e.Fragment,{children:[e.jsx(Ds,{className:"mr-2 size-4 font-bold"}),"Save"]})]})}function Gs(){const{setTempQueryData:t,setSqlGen:a}=s.useEditorActions(),n=s.useQueryClient(),r=s.useEditorStore(d=>d.tempQueryData),l=s.useEditorStore(d=>d.onClose),o=s.useEditorStore(d=>d.card),{queryKey:c}=s.useDashboardCardQuery(o);function i(){if(r){const{queryKey:d,queryData:m}=r;d&&m&&n.setQueryData(d,m)}a({}),l==null||l()}return e.jsxs(s.Button,{onClick:i,className:"h-8",size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function hs(){const{setTempQueryData:t}=s.useEditorActions(),a=s.useQueryClient(),n=s.useEditorStore(y=>y.isDevMode),r=s.useEditorStore(y=>y.tempQueryData),l=s.useEditorStore(y=>y.card),{queryKey:o}=s.useDashboardCardQuery(l),{setCardSql:c,setSqlGen:i,setCardPython:d,setCardCustomCfg:m,setCardPreferences:u,updateDataSource:h,clearQueryConfig:p,setCardConfig:f,setCardType:j}=s.useEditorActions();function x(){const y=a.getQueryData(o);r!=null&&r.queryData||t({queryKey:o,queryData:y}),a.setQueryData(o,null),a.removeQueries({queryKey:o,exact:!0}),n&&h(s.EMPTY_DATA_SOURCE),c(""),i({}),p(),f(void 0),d(""),m(""),u({}),j("bar")}return e.jsxs(s.Button,{onClick:x,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(s.SquarePen,{className:"mr-2 size-4"}),"Clear"]})}function sl(){const t=s.useQueryClient(),[a,n]=A.useState(!1),[r,l]=A.useState(!1);s.useEditorStore(_=>_.frame);const o=s.useEditorStore(_=>_.card);s.useEditorStore(_=>_.isShowingVisual),s.useEditorStore(_=>_.selectedConnectionId),s.useEditorStore(_=>_.tempQueryData),s.useEditorStore(_=>_.selectedDatabaseName),s.useEditorStore(_=>_.selectedDatamodelId),s.useEditorStore(_=>_.selectedSchemaName);const c=s.useEditorStore(_=>_.showAIDialog);s.useEditorStore(_=>_.selectedTableName);const i=s.useEditorStore(_=>{var W;return(W=_==null?void 0:_.card)==null?void 0:W.sql}),d=s.useEditorStore(_=>{var W;return(W=_==null?void 0:_.card)==null?void 0:W.python}),{sheetFilterValues:m}=s.useSheetFilterValues(),{setCardCustomCfg:u,setQueryResultColumns:h,setCardSql:p,setTempQueryData:f,setPythonStdOut:j,setCardPreferences:x,setCardType:y,setCardPython:g,runAssistant:C,setShowAIDialog:E}=s.useEditorActions();s.useEditorStore(_=>_.onSave),s.useEditorStore(_=>_.onClose),s.useEditorStore(_=>_.actions.setSqlGen);const R=s.useEditorStore(_=>_.runSql),S=s.useEditorStore(_=>_.actions.setRunSql),N=s.useEditorStore(_=>_.actions.setIsSqlRunning),{data:b,isLoading:T,isFetching:k,isSuccess:L,isError:w,error:B,queryKey:D,refetch:I,errorMessage:v}=s.useDashboardCardQuery(o);A.useEffect(()=>{if(b&&(b.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),j((b==null?void 0:b.output)||""),b.records.length>0)){const{dimensionKeys:_}=s.getKeys(b.records);h(_)}},[b,h,j]),A.useEffect(()=>{(T||k)&&N(!0),(w||L)&&N(!1),w&&(h([]),j(""))},[T,k,b,j,w,L,N,h,B]),A.useEffect(()=>{R&&(t.getQueryData(D)||I(),S(!1))},[R,I,S,D,t]);async function M(){const _=`Can you help me debug this query in the current table scope?
|
|
431
|
+
*/const Pa=s.createLucideIcon("View",[["path",{d:"M21 17v2a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-2",key:"mrq65r"}],["path",{d:"M21 7V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2",key:"be3xqs"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["path",{d:"M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0",key:"11ak4c"}]]);function as(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=>Pt(c))}})}})}}function Pt(t){return{...t,customCfg:za(t.customCfg),data:[]}}function za(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 Va(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 ks(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 _a(t,a){return a?await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{operation:"delete",lensId:t}):null}function Ua(){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,u]=A.useState(!1),h=s.useDashboardStore(x=>x.dashboard),p=s.useDashboardStore(x=>x.filterValues),{authToken:f}=s.useSemaphorContext();async function j(){d(!0);const x=as(h),y=await Va(t,x,p,f==null?void 0:f.accessToken);y&&(o([...l||[],y]),c(y.id),u(!1)),d(!1)}return e.jsxs(s.Dialog,{open:m,onOpenChange:u,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 $a(){const[t,a]=A.useState(!1),n=s.useDashboardStore(u=>u.lenses),r=s.useDashboardStore(u=>u.selectedLensId),{setLenses:l,setSelectedLensId:o}=s.useDashboardActions(),{authToken:c}=s.useSemaphorContext();async function i(u){o(u)}async function d(u){if(await _a(u,c==null?void 0:c.accessToken)){const p=n==null?void 0:n.filter(f=>f.id!==u);l(p||[]),o("original")}}async function m(u){const h=n==null?void 0:n.map(j=>j.id===u.id?{...j,isDefault:!u.isDefault}:{...j,isDefault:!1});l(h||[]);const p={...u,isDefault:!u.isDefault};await ks(p,c==null?void 0:c.accessToken);const f=n==null?void 0:n.find(j=>j.isDefault);if(f&&f.id!==u.id){const j={...f,isDefault:!1};await ks(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(xa,{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(u=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:u.id,children:[e.jsx("p",{children:u.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:h=>{h.preventDefault(),m(u)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!u.isDefault,"text-green-500":u.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:h=>{h.preventDefault(),d(u.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},u.id))]})]})]})}function zt(){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 Vt(){const t=s.useDashboardStore.getState().isDownloadingPdf,{authToken:a,theme:n,filterValues:r,dashboardTitle:l,selectedSheetId:o}=zt();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 u=(await(await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${a==null?void 0:a.accessToken}`}})).json()).url,h=document.createElement("a");h.href=u;const p=`${l}-${new Date().toISOString()}.pdf`;h.download=p,h.click(),s.useDashboardStore.setState({isDownloadingPdf:!1})}function qa({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 Vt()}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 he({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 mt=[{value:"daily",label:"Daily"},{value:"weekly",label:"Weekly"},{value:"biweekly",label:"Bi-Weekly"},{value:"monthly",label:"Monthly"}];function _t({triggerButtonClassName:t}){const{data:a,handleScheduleSubscription:n,handleDeleteSubscription:r,status:l,error:o,isDeleting:c}=Ya(),[i,d]=A.useState(""),[m,u]=A.useState(mt[0].value),[h,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(he,{className:"col-span-2 h-8",label:"Select Frequency",options:mt,value:m,onValueChange:x=>u(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:h,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:h,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(At,{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(ht,{tooltip:`Next Run: ${new Date(x.nextRun).toLocaleString()} ${x.timezone}`,children:e.jsx(ta,{className:"size-3.5"})}),e.jsx(ht,{tooltip:`${x.endUserEmail}`,children:e.jsx(Ca,{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 ht=({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 Ya(){const[t,a]=A.useState("idle"),[n,r]=A.useState(""),[l,o]=A.useState(null),c=s.useDashboardStore(E=>E.authToken),i=s.useDashboardStore(E=>E.dashboard.id),d=s.useDashboardStore(E=>E.dashboard.title),{endUserId:m}=s.getTenantAndEndUserId((c==null?void 0:c.accessToken)||""),u="https://semaphor.cloud/api/v1/subscriptions/get",h={dashboardId:i,endUserId:m},{data:p,isLoading:f,isError:j,isFetching:x,refetch:y}=s.useQuery({queryKey:["subscriptions",i,m],queryFn:()=>s.getRequest(u,(c==null?void 0:c.accessToken)||"",h),enabled:!!(c!=null&&c.accessToken)&&!!i&&!!m});async function g({email:E,subject:R,frequency:S,time:N}){const{authToken:b,...I}=zt(),k=Intl.DateTimeFormat().resolvedOptions().timeZone,L={email:E,frequency:S,time:N,timezone:k,endUserId:m,endUserEmail:E,subject:R||d||"Scheduled Dashboard",dashboardId:i,dashboardParams:I};a("loading");const w="https://semaphor.cloud/api/v1/subscriptions/create";try{const B=await s.postRequestRegular(w,(b==null?void 0:b.accessToken)||"",{...L});a("success"),r(""),y(),setTimeout(()=>{a("idle")},2e3)}catch(B){console.error(B),a("error"),r(B.message)}}async function C(E){const R="https://semaphor.cloud/api/v1/subscriptions/delete";o(E);try{await s.postRequestRegular(R,(c==null?void 0:c.accessToken)||"",{id:E}),y(),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:y,handleScheduleSubscription:g,handleDeleteSubscription:C,status:t,error:n}}function Ne(){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 Ut(){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))})]})})}var ee=(t=>(t.DASHBOARD="dashboard",t.VISUAL="visual",t))(ee||{});const Ga=async(t,a,n,r,l,o)=>{const c={},i={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${i[a]}`,t,c)},Ha=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${r[a]}`,t,n)},Ka=async(t,a,n,r)=>{const l={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"},o=await fetch(`https://semaphor.cloud/api/management/v1/${l[a]}/${n}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!o.ok){const c=await o.json();throw new Error((c==null?void 0:c.error)||`HTTP error! status: ${o.status}`)}return o.json()},Qa=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"},l=await fetch(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`}});if(!l.ok){const o=await l.json();throw new Error((o==null?void 0:o.error)||`HTTP error! status: ${l.status}`)}return l.json()},Wa=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}/duplicate`,t,{})},Ja=async(t,a,n,r)=>{const l={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${l[a]}/${n}/share`,t,r)},Xa=async(t,a,n,r)=>{const l={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"},o=await fetch(`https://semaphor.cloud/api/management/v1/${l[a]}/${n}/share`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!o.ok){const c=await o.json();throw new Error((c==null?void 0:c.error)||`HTTP error! status: ${o.status}`)}return o.json()},Za=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}/shares`,t)},er=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}`,t)};function sr(t){const{authToken:a}=s.useSemaphorContext();return s.useQuery({queryKey:["tenants"],queryFn:()=>s.getRequest("https://semaphor.cloud/api/management/v1/tenants",(a==null?void 0:a.accessToken)||""),enabled:(t==null?void 0:t.enabled)!==void 0?t.enabled&&!!(a!=null&&a.accessToken):!!(a!=null&&a.accessToken)})}function tr(t,a,n,r,l){const{authToken:o}=s.useSemaphorContext(),{currentUser:c}=Ne();return s.useQuery({queryKey:[t,a,n,r,l],queryFn:()=>Ga((o==null?void 0:o.accessToken)||"",t),enabled:!!(o!=null&&o.accessToken)&&!!c})}function nr(t,a){const{authToken:n}=s.useSemaphorContext(),r=s.useQueryClient();return Oe({mutationFn:l=>Ha((n==null?void 0:n.accessToken)||"",t,l),onMutate:async()=>{await r.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await r.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} created successfully`),a==null||a()},onError:l=>{s.ue.error(`Failed to create ${s.toTitleCase(t)}: ${l.message}`)}})}function $t(t){const{authToken:a}=s.useSemaphorContext(),n=s.useQueryClient();return Oe({mutationFn:({resourceId:r,data:l})=>Ka((a==null?void 0:a.accessToken)||"",t,r,l),onMutate:async()=>{await n.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await n.invalidateQueries({queryKey:[t]})},onError:r=>{s.ue.error(`Failed to update ${s.toTitleCase(t)}: ${r.message}`)}})}function ar(t,a){const{authToken:n}=s.useSemaphorContext(),r=s.useQueryClient();return Oe({mutationFn:l=>Qa((n==null?void 0:n.accessToken)||"",t,l),onMutate:async()=>{await r.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await r.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} deleted successfully`),a==null||a()},onError:l=>{s.ue.error(`Failed to delete ${s.toTitleCase(t)}: ${l.message}`)}})}function rr(t){const{authToken:a}=s.useSemaphorContext(),n=s.useQueryClient();return Oe({mutationFn:r=>Wa((a==null?void 0:a.accessToken)||"",t,r),onMutate:async()=>{await n.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await n.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} duplicated successfully`)},onError:r=>{s.ue.error(`Failed to duplicate ${s.toTitleCase(t)}: ${r.message}`)}})}function lr(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Oe({mutationFn:({resourceType:n,resourceId:r,data:l})=>Ja((t==null?void 0:t.accessToken)||"",n,r,l),onMutate:async n=>{await a.cancelQueries({queryKey:["resource-shares",n.resourceType,n.resourceId]})},onSuccess:async(n,r)=>{await a.invalidateQueries({queryKey:["resource-shares",r.resourceType,r.resourceId]}),a.invalidateQueries({queryKey:[r.resourceType]})},onError:n=>{s.ue.error(`Failed to share resource: ${n.message}`)}})}function or(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Oe({mutationFn:({resourceType:n,resourceId:r,data:l})=>Xa((t==null?void 0:t.accessToken)||"",n,r,l),onMutate:async n=>{await a.cancelQueries({queryKey:["resource-shares",n.resourceType,n.resourceId]})},onSuccess:async(n,r)=>{await a.invalidateQueries({queryKey:["resource-shares",r.resourceType,r.resourceId]}),a.invalidateQueries({queryKey:[r.resourceType]})},onError:n=>{s.ue.error(`Failed to remove resource shares: ${n.message}`)}})}function ir(t,a){const{authToken:n}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-shares",t,a],queryFn:()=>Za((n==null?void 0:n.accessToken)||"",t,a),enabled:!!(n!=null&&n.accessToken)&&!!a})}function cr(t,a,n){const{authToken:r}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-by-id",t,a],queryFn:()=>er((r==null?void 0:r.accessToken)||"",t,a),enabled:(n==null?void 0:n.enabled)!==void 0?n.enabled&&!!(r!=null&&r.accessToken)&&!!a:!!(r!=null&&r.accessToken)&&!!a})}function dr(t,a){return cr(ee.VISUAL,t,a)}function qt(){const[t,a]=A.useState(new Map),n=A.useCallback((o,c)=>{a(i=>{const d=new Map(i),m=new Set(d.get(o)||[]);return c?m.add(c):(m.add("title"),m.add("description")),d.set(o,m),d})},[]),r=A.useCallback((o,c)=>{a(i=>{const d=new Map(i),m=new Set(d.get(o)||[]);return c?m.delete(c):m.clear(),m.size===0?d.delete(o):d.set(o,m),d})},[]),l=A.useCallback((o,c)=>{const i=t.get(o);return i?c?i.has(c):i.size>0:!1},[t]);return{startUpdating:n,stopUpdating:r,isUpdating:l}}function Vs(t,a,n){var h;const r=tr(t),l=nr(t,n),o=$t(t),c=ar(t,a),i=rr(t),d=lr(),m=or(),u={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return{resources:((h=r.data)==null?void 0:h[u[t]])||[],isLoading:r.isLoading,isError:r.isError,isFetching:r.isFetching,error:r.error,createResource:l.mutate,updateResource:o.mutate,deleteResource:c.mutate,duplicateResource:i.mutate,shareResource:d.mutate,removeResourceShares:m.mutate,isCreating:l.isPending,isUpdating:o.isPending,isDeleting:c.isPending,isDuplicating:i.isPending,isSharing:d.isPending,isRemovingShares:m.isPending,isUpdatingShares:d.isPending,refetch:r.refetch}}function ur(t,a){return Vs(ee.DASHBOARD,t,a)}function mr(t,a){return Vs(ee.VISUAL,t,a)}function hr(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Oe({mutationFn:async({visualId:n,data:r})=>{const l=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${n}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t==null?void 0:t.accessToken}`},body:JSON.stringify(r)});if(!l.ok)throw new Error("Failed to update visual");return l.json()},onSuccess:()=>{s.ue.success("Visual updated successfully"),a.invalidateQueries({queryKey:["visuals"]})},onError:()=>{s.ue.error("Failed to update visual")}})}function xr({visual:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onAddVisual:o,onEditVisual:c,onUpdateVisual:i,onDeleteClick:d,onDuplicateVisual:m,onShareVisual:u,formatDate:h}){var N;const{selectVisual:p}=s.useManagementActions(),f=s.useIsVisualSelected(t.id),j=s.useDashboardStore(b=>b.actions.setIsDashboardPanelOpen),[x,y]=A.useState(!1),[g,C]=A.useState(!1);A.useEffect(()=>{n?(y(!0),C(!0)):g&&(y(!1),C(!1))},[n,g]);const E=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(Ot,{className:"h-3 w-3 text-purple-500"}):e.jsx(ve,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(ke,{className:"h-3.5 w-3.5 text-slate-500"}),R=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4 text-slate-400"}),S=()=>{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:S,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:R()})}),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:b=>i==null?void 0:i(t.id,{title:b}),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:E()})]}),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:b=>i==null?void 0:i(t.id,{description:b}),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:b=>{b.stopPropagation(),o(t)},children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:x,onOpenChange:y,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:b=>b.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:b=>{b.stopPropagation(),o(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:b=>{b.preventDefault(),b.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:b=>{b.stopPropagation(),c==null||c(t)},children:[e.jsx(Ea,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:b=>{b.stopPropagation(),u(t)},children:[e.jsx(ve,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:b=>{b.stopPropagation(),d(t),j(!1)},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(ke,{className:"h-3 w-3"}),e.jsx("span",{children:((N=t.ownership.createdBy)==null?void 0:N.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 Yt({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 rs({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 Gt({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(rs,{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 Ht({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 Kt({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(ve,{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 Qt(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 pe(t,a){var n;return((n=a.find(r=>r.value===t))==null?void 0:n.label)||t}function pr(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function Wt(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function fr(t,a,n){const r=Wt(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 gr({user:t}){return Wt(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 jr({user:t,userShare:a,usersToUpdate:n,currentUser:r,getRoleOptions:l,handleUpdateAccess:o}){if(!(a!=null&&a.role))return null;const c=pr((r==null?void 0:r.type)||""),i=n.some(h=>h.id===t.id),d=n.find(h=>h.id===t.id),m=d?d.newRole:a==null?void 0:a.role,u=l(t.type);return a?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(rs,{currentRole:m,onRoleChange:h=>{o(t.id,a.role,h)},roleOptions:u,disabled:!c,allowDropdown:c,className:i?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:pe(m,u)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function yr({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(Ke,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function br({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 vr({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||[],u=c.orgUsersOnly||[],h=c.allTenantsOnly||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Org Users (",i.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[i.slice(0,3).map((p,f)=>{var g,C;const j=((g=a.find(E=>E.id===p.orgUserId))==null?void 0:g.name)||"Unknown User",x=((C=a.find(E=>E.id===p.orgUserId))==null?void 0:C.type)||"",y=pe(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:y})]},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,C;const j=((g=a.find(E=>E.id===p.tenantUserId))==null?void 0:g.name)||"Unknown User",x=((C=a.find(E=>E.id===p.tenantUserId))==null?void 0:C.type)||"",y=pe(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:y})]},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=pe(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)})})]}),u.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:u.map((p,f)=>{const j=pe(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)})})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-indigo-600",children:"All Tenants"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:h.map((p,f)=>{const j=pe(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&&!u.length&&!h.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const c=t.shares.specificTenantUsers||[],i=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",c.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[c.slice(0,3).map((d,m)=>{var f,j;const u=((f=a.find(x=>x.id===d.tenantUserId))==null?void 0:f.name)||"Unknown User",h=((j=a.find(x=>x.id===d.tenantUserId))==null?void 0:j.type)||"",p=pe(d.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:u}),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 u=pe(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:u})]},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",u=((f=a.find(j=>j.id===i.tenantUserId))==null?void 0:f.type)||"",h=pe(i.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:m}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},d)}),o.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",o.length-3," more users"]})]})]}),c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:c.map((i,d)=>{const m=pe(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 Nr({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 Cr({user:t,userShare:a,isUserRemoving:n,hasAccess:r,hasAccessFromAPI:l,isSelected:o,selectedUser:c,roleOptions:i,currentUser:d,usersToUpdate:m,handleUserToggle:u,handleRemoveAccess:h,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?u(t.id):h(t.id):u(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(gr,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!n?e.jsx(rs,{currentRole:a==null?void 0:a.role,onRoleChange:j=>p(t.id,a.role,j),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(jr,{user:t,userShare:a,usersToUpdate:m,currentUser:d,getRoleOptions:()=>i,handleUpdateAccess:p}),o&&!l&&e.jsx("div",{onClick:j=>j.stopPropagation(),children:e.jsx(rs,{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(yr,{hasAccess:r,isUserRemoving:n,isSelected:o,hasAccessFromAPI:l}),e.jsx(br,{isUserRemoving:n,isSelected:o,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function Jt({existingShares:t,isInitialLoading:a,isSearching:n,getRoleOptions:r,allUsers:l=[],currentUser:o,handleUserToggle:c,handleUserRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:m}){const u=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),f=s.useShareSearchQuery(),j=s.useShareManagementActions(),x=c||(S=>{const N=u.some(I=>I.id===S),b=h.includes(S);N?j.removeSelectedUser(S):b?j.removeUserFromRemove(S):j.addSelectedUser({id:S,role:"VIEWER"})}),y=i||j.updateSelectedUserRole,g=d||j.addUserToRemove,C=m||((S,N,b)=>{j.addUserToUpdate({id:S,currentRole:N,newRole:b})}),E=l,R=h;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["All Users (",(E??[]).length,")"]}),e.jsx(s.TooltipProvider$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(vr,{existingShares:t,allUsers:l,getRoleOptions:r,currentUser:o})})]})})]}),(E==null?void 0:E.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{u.length===E.length?j.setSelectedUsers([]):j.setSelectedUsers(E.map(S=>({id:S.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:u.length===E.length?"Deselect all":"Select all"})]}),e.jsxs("div",{className:"max-h-60 space-y-1 overflow-y-auto rounded-md border p-2",children:[e.jsx(Nr,{isInitialLoading:a,isSearching:n,searchQuery:f,availableUsers:E||[]}),!a&&!n&&(E==null?void 0:E.length)>0&&E.map(S=>{const N=t?fr(S,t,o):void 0,b=R.includes(S.id),I=!!N,k=I&&!b,L=u.some(D=>D.id===S.id),w=u.find(D=>D.id===S.id),B=r(S.type);return e.jsx(Cr,{user:S,userShare:N,isUserRemoving:b,hasAccess:k,hasAccessFromAPI:I,isSelected:L,selectedUser:w,roleOptions:B,currentUser:o,usersToUpdate:p,handleUserToggle:x,handleRemoveAccess:g,handleUpdateAccess:C,handleUserRoleChange:y},S.id)})]})]})}function Xt({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(ke,{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 Ie=()=>[{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 Sr({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=Ie().filter(C=>C.value==="VIEWER"||C.value==="EDITOR"||C.value==="CONTRIBUTOR"),u=a.role!=="NONE"?a.role:"NONE",h=l?l.newRole:u,p=a.role!=="NONE"&&!o&&(!l||l.newRole===u),f=l!==null&&l.newRole!==u,j=o,x=u==="NONE"||!u,y=C=>{switch(C){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(Ma,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},g=C=>{r(u,C)};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(ve,{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(C=>e.jsxs(s.Button,{variant:h===C.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>g(C.value),disabled:n||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[y(C.value),e.jsx("span",{className:"font-medium",children:C.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:C.description})]},C.value))})]})})]})})}function Zt({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,h=a?{role:m(a.role)}:{role:"NONE"},p=i?{currentRole:m(i.currentRole),newRole:m(i.newRole)}:null,f=(x,y)=>{o(x,y)},j=()=>{c()};return e.jsx(Sr,{currentUser:t,currentShare:h,isSharing:n,isUpdating:r,isRemoving:l,onUpdateAccess:f,onRemoveAccess:j,allUsersToUpdate:p,allUsersToRemove:d})}const wr=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 Dr(t={}){var o,c,i;const{authToken:a,tokenProps:n}=s.useSemaphorContext(),r=(n==null?void 0:n.endUserId)||(n==null?void 0:n.orgUserId),l=s.useQuery({queryKey:["unified-users",t],queryFn:()=>wr((a==null?void 0:a.accessToken)||"",t),enabled:!!(a!=null&&a.accessToken)&&!!r,retry:(d,m)=>m instanceof Error&&m.message.includes("401")||m instanceof Error&&m.message.includes("403")?!1:d<2,retryDelay:d=>Math.min(1e3*2**d,3e4)});return{users:((o=l.data)==null?void 0:o.users)||[],userContext:(c=l.data)==null?void 0:c.userContext,total:((i=l.data)==null?void 0:i.total)||0,isLoading:l.isLoading,isError:l.isError,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function Ee(t){const{debouncedSearchQuery:a,resourceId:n,resourceType:r=ee.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}=Dr(c),u=ir(r,n);return{allUsers:i,isLoadingUsers:d,isErrorLoadingUsers:m,existingShares:u.data,isLoadingShares:u.isLoading,isErrorLoadingShares:u.isError,isFetchingShares:u.isFetching}}function kr({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var Q,$;const i=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:m,setSearchQuery:u,debouncedSearchQuery:h}=s.useShareSearchWithDebounce(),p=s.useShareSelectedUsers(),f=s.useShareUsersToRemove(),j=s.useShareUsersToUpdate(),x=s.useShareCurrentMode(),y=s.useShareOrgWideRole(),g=s.useShareManagementActions(),[C,E]=A.useState("specific_users"),R=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},S=()=>{if(i==="tenant"&&d)return d},{allUsers:N,existingShares:b,isLoadingUsers:I}=Ee({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:R(),tenantId:S()});A.useEffect(()=>{g.setCurrentContext("org-tab"),g.setCurrentMode(C==="all_users"?"allOrgUsers":"specificOrgUsers")},[g,C]);const k=q=>{var U,P;const H=q;if(E(H),r==null||r(H),g.setCurrentContext("org-tab"),H==="specific_users")g.setCurrentMode("specificOrgUsers");else if(H==="all_users"){g.setCurrentMode("allOrgUsers");const Y=(P=(U=b==null?void 0:b.shares)==null?void 0:U.orgUsersOnly)==null?void 0:P[0];Y&&Y.role!==void 0&&g.setOrgWideRole(Y.role)}},L=N.filter(q=>q.name.toLowerCase().includes(m.toLowerCase())||q.email.toLowerCase().includes(m.toLowerCase())),w=N.filter(q=>p.some(H=>H.id===q.id)),B=q=>{var Y,G;const H=p.some(X=>X.id===q),U=f.includes(q),P=(G=(Y=b==null?void 0:b.shares)==null?void 0:Y.specificOrgUsers)==null?void 0:G.some(X=>X.orgUserId===q);H?g.removeSelectedUser(q):U?g.removeUserFromRemove(q):P||g.addSelectedUser({id:q,role:"VIEWER"})},D=(q,H)=>{g.updateSelectedUserRole(q,H)},T=q=>{g.addUserToRemove(q),g.removeSelectedUser(q)},v=q=>{g.removeUserFromRemove(q)},M=q=>{g.removeUserFromUpdate(q)},F=(q,H)=>{g.setOrgWideRole(H)},O=()=>{g.setOrgWideRole((V==null?void 0:V.role)||"NONE")},V=($=(Q=b==null?void 0:b.shares)==null?void 0:Q.orgUsersOnly)==null?void 0:$[0];A.useEffect(()=>{C==="all_users"&&V&&V.role!==void 0&&g.setOrgWideRole(V.role)},[C,V,g]);const _=I,W=!1;return n?e.jsxs(e.Fragment,{children:[e.jsx(Xt,{shareType:C,onShareTypeChange:k,currentUser:n,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(ke,{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(ve,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role??"")}]}),C==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(Yt,{value:m,onChange:u}),e.jsx(Gt,{selectedUsers:p,selectedUserObjects:w,onRemove:B,onRoleChange:D,getRoleOptions:Ie}),e.jsx(Ht,{usersToRemove:f,allUsers:L,onRemove:v}),e.jsx(Kt,{usersToUpdate:j,allUsers:L,onRemove:M,getRoleOptions:Ie}),e.jsx(Jt,{existingShares:b,isInitialLoading:_,isSearching:W,resource:t,onShare:()=>{},getRoleOptions:Ie,allUsers:L,currentUser:n,handleUserToggle:B,handleUserRoleChange:D,handleRemoveAccess:T,handleUpdateAccess:(q,H,U)=>{g.addUserToUpdate({id:q,currentRole:H,newRole:U})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(Zt,{currentUser:n,currentShare:V,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:F,onRemoveAccess:O,allUsersToUpdate:x==="allOrgUsers"&&y!==((V==null?void 0:V.role)||"NONE")?{currentRole:(V==null?void 0:V.role)||"NONE",newRole:y}:null,allUsersToRemove:x==="allOrgUsers"&&(V==null?void 0:V.role)===void 0})})]}):null}function xt({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var Y;const{searchQuery:i,debouncedSearchQuery:d,setSearchQuery:m}=s.useShareSearchWithDebounce(),u=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),f=s.useShareCurrentMode(),j=s.useShareTenantWideRole(),x=s.useShareAllTenantsRole(),y=s.useShareSelectedTenant(),g=s.useShareManagementActions(),{data:C,isLoading:E}=sr({enabled:(n==null?void 0:n.type)==="organization"}),[R,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 N=G=>{var se,ae,te,le;S(G);let X;if(G==="specific_tenant_users"?X="specific_users":G==="all_tenant_users"||G==="all_tenants"?X="all_users":X="specific_users",r==null||r(X),(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 K=(ae=(se=k==null?void 0:k.shares)==null?void 0:se.tenantWide)==null?void 0:ae[0];K&&K.role!==void 0&&g.setTenantWideRole(K.role)}else if(G==="all_tenants"){const K=(le=(te=k==null?void 0:k.shares)==null?void 0:te.allTenantsOnly)==null?void 0:le[0];K&&K.role!==void 0&&g.setAllTenantsRole(K.role)}},b=G=>{g.setSelectedTenant(G)},{allUsers:I,existingShares:k,isLoadingUsers:L,isErrorLoadingUsers:w,isLoadingShares:B,isErrorLoadingShares:D}=Ee({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant",tenantId:(n==null?void 0:n.type)==="tenant"?n.tenantId:y}),T=G=>{var te,le;const X=u.some(K=>K.id===G),se=h.includes(G),ae=(le=(te=k==null?void 0:k.shares)==null?void 0:te.specificTenantUsers)==null?void 0:le.some(K=>K.tenantUserId===G);X?g.removeSelectedUser(G):se?g.removeUserFromRemove(G):ae||g.addSelectedUser({id:G,role:"VIEWER"})},v=(G,X)=>{g.updateSelectedUserRole(G,X)},M=G=>{g.addUserToRemove(G),g.removeSelectedUser(G)},F=G=>{g.removeUserFromRemove(G)},O=G=>{g.removeUserFromUpdate(G)},V=(G,X,se)=>{g.addUserToUpdate({id:G,currentRole:X,newRole:se})},_=(G,X)=>{R==="all_tenant_users"?g.setTenantWideRole(X):R==="all_tenants"&&g.setAllTenantsRole(X)},W=()=>{R==="all_tenant_users"?g.setTenantWideRole("VIEWER"):R==="all_tenants"&&g.setAllTenantsRole("VIEWER")},$=(()=>{var G,X,se,ae;return f==="allTenants"?(X=(G=k==null?void 0:k.shares)==null?void 0:G.allTenantsOnly)==null?void 0:X[0]:f==="allTenantUsers"?(ae=(se=k==null?void 0:k.shares)==null?void 0:se.tenantWide)==null?void 0:ae[0]:null})();A.useEffect(()=>{var G,X,se,ae;if(R==="all_tenant_users"){const te=(X=(G=k==null?void 0:k.shares)==null?void 0:G.tenantWide)==null?void 0:X[0];te&&te.role!==void 0&&g.setTenantWideRole(te.role)}else if(R==="all_tenants"){const te=(ae=(se=k==null?void 0:k.shares)==null?void 0:se.allTenantsOnly)==null?void 0:ae[0];te&&te.role!==void 0&&g.setAllTenantsRole(te.role)}},[R,k,g]);const q=I.filter(G=>u.some(X=>X.id===G.id)),H=L||B,U=w||D,P=()=>(n==null?void 0:n.type)==="tenant"||R==="all_tenants"?!0:y&&(R==="specific_tenant_users"||R==="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(Xt,{shareType:R,onShareTypeChange:N,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(ve,{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(ke,{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(ot,{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(ke,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(n==null?void 0:n.type)==="organization"&&(R==="specific_tenant_users"||R==="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:y||"",onValueChange:b,disabled:E,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:E?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(Y=C==null?void 0:C.tenants)==null?void 0:Y.map(G=>e.jsx(s.SelectItem,{value:G.id,children:G.name},G.id))})]})]}),P()?e.jsx(e.Fragment,{children:R==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Yt,{value:i,onChange:m}),e.jsx(Gt,{selectedUsers:u,selectedUserObjects:q,onRemove:G=>T(G),onRoleChange:v,getRoleOptions:Ie}),e.jsx(Ht,{usersToRemove:h,allUsers:I,onRemove:F}),e.jsx(Kt,{usersToUpdate:p,allUsers:I,onRemove:O,getRoleOptions:Ie}),e.jsx(Jt,{existingShares:k,isInitialLoading:!!H,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:Ie,allUsers:I,currentUser:n,handleUserToggle:T,handleUserRoleChange:v,handleRemoveAccess:M,handleUpdateAccess:V})]}):R==="all_tenant_users"||R==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(Zt,{currentUser:n,currentShare:$,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:_,onRemoveAccess:W,allUsersToUpdate:f==="allTenantUsers"&&(($==null?void 0:$.role)===void 0||j!==$.role)||f==="allTenants"&&(($==null?void 0:$.role)===void 0||x!==$.role)?{currentRole:($==null?void 0:$.role)||"VIEWER",newRole:f==="allTenantUsers"?j:x}:null,allUsersToRemove:f==="allTenantUsers"&&($==null?void 0:$.role)===void 0||f==="allTenants"&&($==null?void 0:$.role)===void 0})}):null}):(n==null?void 0:n.type)==="organization"&&(R==="specific_tenant_users"||R==="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(ot,{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 en=()=>{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]),u=A.useMemo(()=>p=>s.validateShareData(p),[]),h=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:u,isCurrentStateValid:h,currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:l,selectedTenant:o,orgWideRole:c,allTenantsRole:i,tenantWideRole:d}};function pt({resource:t,existingShares:a,isSharing:n,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllUsersShare:d,onRemoveAccess:m}){const u=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const f=s.useShareSelectedTenant();s.useShareSelectedTab();const j=s.useShareOrgWideRole(),x=s.useShareAllTenantsRole(),y=s.useShareTenantWideRole(),{buildShareData:g,validateShareData:C,isCurrentStateValid:E}=en(),R=n||r||l,S=()=>{var L,w,B,D;if(R)return"Updating...";if(i==="specific_users"){if(u.length===0&&h.length===0&&p.length===0)return"Select users to share with";const T=u.length+h.length+p.length;return T===0?"Select users to share with":u.length>0&&h.length>0?`Update access for ${T} user${T!==1?"s":""}`:h.length>0&&u.length===0&&p.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:u.length>0&&h.length===0&&p.length===0?`Share with ${u.length} user${u.length!==1?"s":""}`:p.length>0&&u.length===0&&h.length===0?`Update access for ${p.length} user${p.length!==1?"s":""}`:`Update access for ${T} user${T!==1?"s":""}`}else if(i==="all_users"){if(!d||d.role===void 0)return"Share with All Users";const T=d.role;return j===T?"Remove Access":"Update Access"}else if(i==="all_tenants"){const T=(w=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:w[0];if(!T||T.role===void 0)return"Share with All Tenants";const v=T.role;return x===v?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const T=(D=(B=a==null?void 0:a.shares)==null?void 0:B.tenantWide)==null?void 0:D[0];if(!T||T.role===void 0)return"Share with All Tenant Users";const v=T.role;return y===v?"Remove Access":"Update Access"}else if(i==="specific_tenant_users"){if(u.length===0&&h.length===0&&p.length===0)return"Select users to share with";const T=u.length+h.length+p.length;return T===0?"Select users to share with":u.length>0&&h.length>0?`Update access for ${T} user${T!==1?"s":""}`:h.length>0&&u.length===0&&p.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:u.length>0&&h.length===0&&p.length===0?`Share with ${u.length} user${u.length!==1?"s":""}`:p.length>0&&u.length===0&&h.length===0?`Update access for ${p.length} user${p.length!==1?"s":""}`:`Update access for ${T} user${T!==1?"s":""}`}return"Share"},N=()=>R||!t||i==="all_tenant_users"&&!f||i==="specific_tenant_users"&&!f?!0:!E,b=()=>{const L=g();L&&C(L)&&o(L)},I=()=>{var L,w,B,D;if(i==="all_users")if(!d||d.role===void 0){const T=g();T&&C(T)&&o(T)}else{const T=d.role;if(j===T)m==null||m();else{const M=g();if(M&&C(M)){const F={...M,updateAccess:!0};o(F)}}}else if(i==="all_tenants"){const T=(w=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:w[0];if(!T||T.role===void 0){const v=g();v&&C(v)&&o(v)}else{const v=T.role;if(x===v)m==null||m();else{const F=g();if(F&&C(F)){const O={...F,updateAccess:!0};o(O)}}}}else if(i==="all_tenant_users"){const T=(D=(B=a==null?void 0:a.shares)==null?void 0:B.tenantWide)==null?void 0:D[0];if(!T||T.role===void 0){const v=g();v&&C(v)&&o(v)}else{const v=T.role;if(y===v)m==null||m();else{const F=g();if(F&&C(F)){const O={...F,updateAccess:!0};o(O)}}}}},k=()=>{var L,w,B,D;if(i==="all_users"){if(!d||d.role===void 0)return"default";const T=d.role;return j===T?"destructive":"default"}else if(i==="all_tenants"){const T=(w=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:w[0];if(!T||T.role===void 0)return"default";const v=T.role;return x===v?"destructive":"default"}else if(i==="all_tenant_users"){const T=(D=(B=a==null?void 0:a.shares)==null?void 0:B.tenantWide)==null?void 0:D[0];if(!T||T.role===void 0)return"default";const v=T.role;return y===v?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:R,children:"Close"}),(i==="specific_users"||i==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(u.length>0||h.length>0||p.length>0)&&e.jsxs(s.Button,{onClick:b,disabled:!t||R,variant:"default",children:[R?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ke,{className:"mr-2 h-4 w-4"}),!R&&S()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:I,disabled:N(),variant:k(),children:[R?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(ve,{className:"mr-2 h-4 w-4"}),!R&&S()]})]})}function Er({resource:t,isSharing:a,isRemoving:n,isUpdating:r,onShare:l,onClose:o,shareTabType:c,currentAllUsersShare:i}){const d=s.useShareSelectedUsers(),m=s.useShareUsersToRemove(),u=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const h=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:p,validateShareData:f,isCurrentStateValid:j}=en(),x=a||n||r,y=()=>{if(x)return"Updating...";if(c==="specific_users"){if(d.length===0&&m.length===0&&u.length===0)return"Select users to share with";const S=d.length+m.length+u.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&&u.length===0?`Remove access for ${m.length} user${m.length!==1?"s":""}`:d.length>0&&m.length===0&&u.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:u.length>0&&d.length===0&&m.length===0?`Update access for ${u.length} user${u.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 h===S?"Remove Access":"Update Access"}return"Share"},g=()=>x||!t?!0:!j,C=()=>{const S=p();S&&f(S)&&l(S)},E=()=>{if(!i||i.role==="NONE"){const S=p();S&&f(S)&&l(S)}else{const S=i.role;if(h===S){const b=p();if(b&&f(b)){const I={...b,removeAccess:!0};l(I)}}else{const b=p();if(b&&f(b)){const I={...b,updateAccess:!0};l(I)}}}},R=()=>!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||u.length>0)&&e.jsxs(s.Button,{onClick:C,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(Ke,{className:"mr-2 h-4 w-4"}),!x&&y()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:E,disabled:g(),variant:R(),children:[x?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ke,{className:"mr-2 h-4 w-4"}),!x&&y()]})]})}function sn({resource:t,resourceType:a,isSharing:n,isRemoving:r,isUpdating:l,onClose:o,onShare:c,onRemoveAccess:i}){var b,I,k,L;const{currentUser:d}=Ne(),[m,u]=A.useState("specific_users"),[h,p]=A.useState("specific_users"),f=s.useShareManagementActions(),j=s.useShareSelectedTab(),x=s.useShareCurrentMode(),{existingShares:y}=Ee({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant"}),{existingShares:g}=Ee({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"organization"}),C=(I=(b=y==null?void 0:y.shares)==null?void 0:b.tenantWide)==null?void 0:I[0],E=(L=(k=g==null?void 0:g.shares)==null?void 0:k.orgUsersOnly)==null?void 0:L[0],R=()=>{if(j==="org")return h;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]),N=(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(Ke,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:N?"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."})]}),N?e.jsxs(s.Tabs,{value:j,onValueChange:w=>{const B=w;f.setSelectedTab(B),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(kr,{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(xt,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:w=>u(w),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(xt,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:w=>u(w),isSharing:n,isUpdating:l,isRemoving:r})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:N?j==="org"?e.jsx(pt,{resource:t,existingShares:g,isSharing:n,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:h,currentAllUsersShare:E,onRemoveAccess:i}):e.jsx(pt,{resource:t,existingShares:y,isSharing:n,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:R(),currentAllUsersShare:C,onRemoveAccess:i}):e.jsx(Er,{resource:t,isSharing:n,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:m,currentAllUsersShare:C,onRemoveAccess:i})})]})})}function me(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function De(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function tn(t,a,n){const{resourceType:r,resourceId:l,shareMutation:o,removeMutation:c,existingShares:i,resetUserSelections:d}=a;if(l)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const m=me(r,l,[{scope:"org_users_only",role:t.orgWideRole}]);o(m,{onSuccess:()=>{d()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:m,usersToRemove:u,usersToUpdate:h}=t;if(m&&m.length>0){const p=me(r,l,m.map(f=>({scope:"specific_org_user",orgUserId:f.id,role:f.role})));o(p,{onSuccess:()=>{d()}})}if(u&&u.length>0){const p=De(r,l,u.map(f=>{var x,y;const j=(y=(x=i==null?void 0:i.shares)==null?void 0:x.specificOrgUsers)==null?void 0:y.find(g=>g.orgUserId===f);return{scope:"specific_org_user",orgUserId:f,role:(j==null?void 0:j.role)||"VIEWER"}}));c(p,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(p=>{const f=me(r,l,[{scope:"specific_org_user",orgUserId:p.id,role:p.newRole}]);o(f,{onSuccess:()=>{d()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const m=me(r,l,[{scope:"all_tenants_only",role:t.allTenantsRole}]);o(m,{onSuccess:()=>{d()}})}else if(t.mode==="allTenantUsers"){const m=me(r,l,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);o(m,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:m,usersToRemove:u,usersToUpdate:h,tenantId:p}=t;if(u&&u.length>0){const f=De(r,l,u.map(j=>{var y,g;const x=(g=(y=i==null?void 0:i.shares)==null?void 0:y.specificTenantUsers)==null?void 0:g.find(C=>C.tenantUserId===j);return{scope:"specific_tenant_user",tenantUserId:j,tenantId:p,role:(x==null?void 0:x.role)||"VIEWER"}}));c(f,{onSuccess:()=>{d()}})}if(h&&h.length>0&&h.forEach(f=>{const j=me(r,l,[{scope:"specific_tenant_user",tenantUserId:f.id,tenantId:p,role:f.newRole}]);o(j,{onSuccess:()=>{d()}})}),m&&m.length>0){const f=me(r,l,m.map(j=>({scope:"specific_tenant_user",tenantUserId:j.id,tenantId:p,role:j.role})));o(f,{onSuccess:()=>{d()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const m=De(r,l,[{scope:"all_tenant_users",role:"VIEWER"}]);c(m,{onSuccess:()=>{d()}})}else if(t.updateAccess){const m=me(r,l,[{scope:"all_tenant_users",tenantId:n==null?void 0:n.tenantId,role:t.tenantWideRole}]);o(m,{onSuccess:()=>{d()}})}else{const m=me(r,l,[{scope:"all_tenant_users",tenantId:n==null?void 0:n.tenantId,role:t.tenantWideRole}]);o(m,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:m,usersToRemove:u,usersToUpdate:h}=t;if(m&&m.length>0){const p=me(r,l,m.map(f=>({scope:"specific_tenant_user",tenantUserId:f.id,role:f.role})));o(p,{onSuccess:()=>{d()}})}if(u&&u.length>0){const p=De(r,l,u.map(f=>{var x,y;const j=(y=(x=i==null?void 0:i.shares)==null?void 0:x.specificTenantUsers)==null?void 0:y.find(g=>g.tenantUserId===f);return{scope:"specific_tenant_user",tenantUserId:f,role:(j==null?void 0:j.role)||"VIEWER"}}));c(p,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(p=>{const f=me(r,l,[{scope:"specific_tenant_user",tenantUserId:p.id,role:p.newRole}]);o(f,{onSuccess:()=>{d()}})})}break}}function nn(t,a,n,r){var m,u,h,p,f,j;const{resourceType:l,resourceId:o,removeMutation:c,existingShares:i,resetUserSelections:d}=r;if(o)if(t.length>0){const x=De(l,o,t.map(y=>{var C,E;const g=(E=(C=i==null?void 0:i.shares)==null?void 0:C.specificTenantUsers)==null?void 0:E.find(R=>R.tenantUserId===y);return{scope:"specific_tenant_user",tenantUserId:y,role:(g==null?void 0:g.role)||"VIEWER"}}));c(x,{onSuccess:()=>{d()},onError:y=>{console.error("Remove access failed:",y)}})}else{const x=a==="tenant"&&n==="allTenants",y=a==="tenant"&&n==="allTenantUsers";if(x){const g=(u=(m=i==null?void 0:i.shares)==null?void 0:m.allTenantsOnly)==null?void 0:u[0];if(g){const C=De(l,o,[{scope:"all_tenants_only",role:g.role}]);c(C,{onSuccess:()=>{d()},onError:E=>{console.error("Remove all-tenants access failed:",E)}})}}else if(y){const g=(p=(h=i==null?void 0:i.shares)==null?void 0:h.tenantWide)==null?void 0:p[0];if(g){const C=De(l,o,[{scope:"all_tenant_users",role:g.role}]);c(C,{onSuccess:()=>{d()},onError:E=>{console.error("Remove all-tenant-users access failed:",E)}})}}else{const g=(j=(f=i==null?void 0:i.shares)==null?void 0:f.orgUsersOnly)==null?void 0:j[0];if(g){const C=De(l,o,[{scope:"org_users_only",role:g.role}]);c(C,{onSuccess:()=>{d()},onError:E=>{console.error("Remove org-wide access failed:",E)}})}}}}function Tr(t,a,n){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),o=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{currentUser:i}=Ne(),{existingShares:d}=Ee({debouncedSearchQuery:"",resourceId:t||"",resourceType:ee.DASHBOARD,userType:"tenant"}),m=A.useCallback(()=>{r.resetUserSelections()},[r]),u=A.useCallback(p=>{if(!t)return;const f={resourceType:ee.DASHBOARD,resourceId:t,shareMutation:a,removeMutation:n,existingShares:d,resetUserSelections:m};tn(p,f,i)},[t,a,n,d,m,i]),h=A.useCallback(()=>{if(!t)return;const p={resourceType:ee.DASHBOARD,resourceId:t,removeMutation:n,existingShares:d,resetUserSelections:m};nn(l,o||"",c||"",p)},[t,a,n,d,m,l,o,c]);return{handleShareSubmit:u,handleRemoveAccess:h}}function Ir(t,a,n){const{currentUser:r}=Ne(),l=s.useShareManagementActions(),o=s.useShareUsersToRemove(),c=s.useShareSelectedTab(),i=s.useShareCurrentMode(),{existingShares:d}=Ee({debouncedSearchQuery:"",resourceId:t||"",resourceType:ee.VISUAL,userType:"tenant"}),m=A.useCallback(()=>{l.resetUserSelections()},[l]),u=A.useCallback(p=>{if(!t)return;const f={resourceType:ee.VISUAL,resourceId:t,shareMutation:a,removeMutation:n,existingShares:d,resetUserSelections:m};tn(p,f,r)},[t,a,n,d,m,r]),h=A.useCallback(()=>{if(!t)return;const p={resourceType:ee.VISUAL,resourceId:t,removeMutation:n,existingShares:d,resetUserSelections:m};nn(o,c||"",i||"",p)},[t,a,n,d,m,o,c,i]);return{handleShareSubmit:u,handleRemoveAccess:h}}function Ar(t){const a=t.toUpperCase().indexOf("WHERE"),n=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),l=t.toUpperCase().indexOf("ORDER BY");let o=t.length;if(l!==-1&&(o=l),r!==-1&&r<o&&(o=r),a!==-1){const c=t.substring(0,a),i=t.substring(a);return`${c} {{ filters | where }} AND ${i.substring(6)}`}else if(n!==-1){const c=t.substring(0,n),i=t.substring(n);return`${c} {{ filters | where }} ${i}`}else{const c=t.substring(0,o),i=t.substring(o);return console.log("beforeClause",c),console.log("afterClause",i),i?`${c} {{ filters | where }} ${i}`:`${c.replace(/;$/,"")} {{ filters | where }}`}}function _s(t){const[a,n]=A.useState(null),[r,l]=A.useState(null);return A.useEffect(()=>{if(!t||t.trim()===""){n(null),l(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const i=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(i,{method:"HEAD"})).ok)throw new Error(`Module not found at ${i}`)}catch{}const d=await import(i);if(typeof d.useChartStore!="function")throw new Error("useChartStore is not a function");n(()=>d.useChartStore),l(null)}catch(c){const i=c instanceof Error?c.message:"Unknown error";console.error("Failed to load remote chart store:",i),l(i),n(null)}})()},[t]),a}function Mr(t,a){if(t.length===0)return"";if(a){const n=t.find(r=>r.id===a);if(n){const r=n.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const o=r.split("__")[0],c=t.find(i=>i.tabTitle===o);return c?c.id:t[0].id}return a}}return t[0].id}async function ft(t,a,n){if(!t||!a)throw new Error("Missing auth token or visual ID");const r=["resource-by-id","visual",a],l=n.getQueryData(r);if(l)return console.log("Using cached visual data for:",a),{data:l,fromCache:!0};console.log("Fetching visual data from network for:",a);const o=s.ue.loading("Loading visual...",{position:"top-center"});try{const c=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${a}`,{headers:{Authorization:`Bearer ${t}`}});if(!c.ok)throw new Error("Failed to load visual");const i=await c.json();return n.setQueryData(r,i),s.ue.dismiss(o),{data:i,fromCache:!1}}catch(c){throw s.ue.dismiss(o),c}}function Lr(t,a,n,r,l){const o=t.frameObject;a(o);const c=o.cards.find(i=>i.id===o.activeCardId);c&&n(c),r(!0),l(!0)}function Or(){var p;const{setCardSql:t}=s.useEditorActions(),a=s.useEditorStore(f=>f.frame),n=s.useEditorStore(f=>f.card),r=_s(((p=n.customCardPreferences)==null?void 0:p.url)||""),l=s.useEditorStore(f=>f.selectedSchemaName),o=s.useEditorStore(f=>f.selectedDatamodelId),c=s.useEditorStore(f=>f.selectedDatabaseName),i=s.useEditorStore(f=>f.selectedTableName),d=s.useEditorStore(f=>f.selectedConnectionId),m=s.useEditorStore(f=>f.isShowingVisual),u=n.sql;return{getUpdatedFrame:A.useCallback(()=>{var g;let f=u;u&&!u.includes("{{")&&(f=Ar(u),t(f));const j=(g=r==null?void 0:r.getState())==null?void 0:g.settings,x={...n,dataSource:n.dataSource||{mode:"directSource"},lastSelectedSchema:l,lastSelectedDatamodelId:o,lastSelectedDatabase:c,lastSelectedTable:i,connectionId:d,sql:f,customCfg:m?n.customCfg:null,...j&&{customCardPreferences:{...n.customCardPreferences,settings:j}}},y=a.cards.map(C=>C.id===n.id?x:C);return{...a,cards:y,activeCardId:Mr(y,a.activeCardId)}},[n,a,m,l,o,c,i,d,t,r,u])}}function Us(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient(),n=s.useSelectedVisual(),{selectVisual:r}=s.useManagementActions(),{setFrame:l,setCard:o}=s.useEditorActions(),{setIsDashboardEditing:c,setIsVisualEditing:i,setSelectedFrameId:d,addFrame:m,setIsDashboardPanelOpen:u}=s.useDashboardActions(),h=s.useDashboardStore(x=>x.selectedSheetId),p=dr((n==null?void 0:n.id)||"",{enabled:!!(n!=null&&n.id)&&!!(t!=null&&t.accessToken)}),f=A.useCallback(async x=>{try{r(x);const{data:y,fromCache:g}=await ft((t==null?void 0:t.accessToken)||"",x.id,a);return Lr(y,l,o,c,i),{success:!0,fromCache:g}}catch(y){return console.error("Error editing visual:",y),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,a,r,l,o,c,i]),j=A.useCallback(async x=>{try{if(r(x),!h)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:y,fromCache:g}=await ft((t==null?void 0:t.accessToken)||"",x.id,a),C=y.frameObject;if(!C)return{success:!1,error:"Visual has no frame data"};const E={...C,id:s.v4()};return m(h,E,"end"),c(!0),d(E.id),u(!1),{success:!0,fromCache:g}}catch(y){return console.error("Error adding visual:",y),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,a,r,h,m,c,d,u]);return{visual:p.data,isLoading:p.isLoading,isError:p.isError,error:p.error,handleEditLibraryVisual:f,handleAddLibraryVisual:j,getUpdatedFrame:Or().getUpdatedFrame,refetch:p.refetch}}function Rr(){const[t,a]=A.useState(""),[n,r]=A.useState(!1),[l,o]=A.useState(""),[c,i]=A.useState(""),[d,m]=A.useState(!1),[u,h]=A.useState(null),[p,f]=A.useState(!1),[j,x]=A.useState(null),[y,g]=A.useState(null),{setIsDashboardEditing:C,setIsVisualEditing:E}=s.useDashboardActions(),{handleEditLibraryVisual:R,handleAddLibraryVisual:S}=Us(),{resources:N,isLoading:b,isError:I,createResource:k,updateResource:L,deleteResource:w,duplicateResource:B,shareResource:D,isCreating:T,isDeleting:v,removeResourceShares:M,isSharing:F,isRemovingShares:O,isUpdatingShares:V}=mr(()=>{f(!1),x(null)},()=>{r(!1),o(""),i("")}),{handleShareSubmit:_,handleRemoveAccess:W}=Ir((u==null?void 0:u.id)||null,D,M);Ne();const Q=N.filter(z=>{var Z,oe;return((Z=z==null?void 0:z.title)==null?void 0:Z.toLowerCase().includes(t.toLowerCase()))||((oe=z==null?void 0:z.description)==null?void 0:oe.toLowerCase().includes(t.toLowerCase()))}),$=z=>new Date(z).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),q=()=>{l.trim()&&k({title:l,description:c,isPrivate:!1})},H=z=>{x(z),f(!0)},U=()=>{j&&w(j.id)},{startUpdating:P,stopUpdating:Y,isUpdating:G}=qt(),X=(z,Z)=>{const oe=Z.title!==void 0?"title":"description";P(z,oe),L({resourceId:z,data:Z},{onSuccess:()=>{Y(z,oe)},onError:()=>{Y(z,oe)}})},se=z=>{g(z),B(z,{onSettled:()=>g(null)})},ae=z=>{R(z)},te=z=>{S(z)},le=z=>{const Z=N.find(oe=>oe.id===z);Z&&L({resourceId:z,data:{isPrivate:!Z.isPrivate}})},K=z=>{h(z),m(!0)};return s.useShareUsersToRemove(),s.useShareManagementActions(),Ee({debouncedSearchQuery:"",resourceId:(u==null?void 0:u.id)||"",resourceType:ee.VISUAL,userType:"tenant"}),b?e.jsx(Ut,{}):I?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:z=>o(z.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter visual description...",value:c,onChange:z=>i(z.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:q,size:"sm",className:"h-7 text-xs",disabled:!l.trim()||T,children:T?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),o(""),i("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:T,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>r(!0),className:"h-8 w-full",size:"sm",disabled:T,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),T?"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:z=>a(z.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:Q.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(ms,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No visuals found"})]}):Q.map(z=>e.jsx(xr,{visual:z,onAddVisual:te,onEditVisual:ae,onUpdateVisual:X,onDeleteClick:H,onDuplicateVisual:se,onTogglePrivacy:le,onShareVisual:K,isDeleting:v,isDuplicating:y===z.id,isTitleUpdating:G(z.id,"title"),isDescriptionUpdating:G(z.id,"description"),formatDate:$},z.id))})}),d&&u&&e.jsx(sn,{resource:u,resourceType:ee.VISUAL,onShare:_,isSharing:F,isRemoving:O,isUpdating:V,onClose:()=>{m(!1),h(null)},onRemoveAccess:W}),e.jsx(s.AlertDialog,{open:p,onOpenChange:z=>{!z&&v||(f(z),z||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:v,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:z=>{z.preventDefault(),z.stopPropagation(),U()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:v,children:v?"Deleting...":"Delete"})]})]})})]})}function Br({dashboard:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onLoadDashboard:o,onUpdateDashboard:c,onDeleteClick:i,onDuplicateDashboard:d,onShareDashboard:m,formatDate:u,onDashboardItemClick:h}){var N;const{selectDashboard:p}=s.useManagementActions(),f=s.useIsDashboardSelected(t.id),[j,x]=A.useState(!1),[y,g]=A.useState(!1),C=s.useDashboardStore(b=>b.actions.setIsDashboardPanelOpen);A.useEffect(()=>{n?(x(!0),g(!0)):y&&(x(!1),g(!1))},[n,y]);const E=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(Ot,{className:"h-3 w-3 text-purple-500"}):e.jsx(ve,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(ke,{className:"h-3.5 w-3.5 text-slate-500"}),R=()=>e.jsx(s.LayoutDashboard,{className:"h-4 w-4 text-slate-400"}),S=()=>{p(t),o(t.id),h==null||h(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",f&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:S,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:R()})}),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:b=>c==null?void 0:c(t.id,{title:b}),isEditable:t.permissions.canEdit&&f,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:E()})]}),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:b=>c==null?void 0:c(t.id,{description:b}),isEditable:t.permissions.canEdit&&f,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: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:b=>b.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:b=>{b.preventDefault(),b.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:b=>{b.stopPropagation(),m(t)},children:[e.jsx(ve,{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:b=>{b.stopPropagation(),i(t),C(!1)},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(ke,{className:"h-3 w-3"}),e.jsx("span",{children:((N=t.ownership.createdBy)==null?void 0:N.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 Fr({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 Pr(t){const[a,n]=A.useState(""),[r,l]=A.useState(!1),[o,c]=A.useState(""),[i,d]=A.useState(""),[m,u]=A.useState(!1),[h,p]=A.useState(null),[f,j]=A.useState(!1),[x,y]=A.useState(null),[g,C]=A.useState(null),E=s.useManagementStore(K=>K.lastSelectedDashboard),R=s.useManagementStore(K=>K.actions.selectDashboard);s.useShareManagementActions(),s.useShareUsersToRemove(),s.useShareSelectedTab(),s.useShareCurrentMode();const{resources:S,isLoading:N,isError:b,createResource:I,updateResource:k,deleteResource:L,duplicateResource:w,isCreating:B,isDeleting:D,isSharing:T,isRemovingShares:v,isUpdatingShares:M,shareResource:F,removeResourceShares:O}=ur(()=>{j(!1),y(null),E&&R(E)},()=>{l(!1),c(""),d("")}),{handleShareSubmit:V,handleRemoveAccess:_}=Tr((h==null?void 0:h.id)||null,F,O),{currentUser:W}=Ne(),Q=S.filter(K=>{var z,Z;return((z=K==null?void 0:K.title)==null?void 0:z.toLowerCase().includes(a.toLowerCase()))||((Z=K==null?void 0:K.description)==null?void 0:Z.toLowerCase().includes(a.toLowerCase()))}),$=K=>new Date(K).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),q=()=>{o.trim()&&I({title:o,description:i,isPrivate:!1})},H=K=>{var z;(z=t.onLoadDashboard)==null||z.call(t,K)},U=K=>{y(K),j(!0)},P=()=>{x&&L(x.id)},Y=K=>{C(K),w(K,{onSettled:()=>C(null)})},{startUpdating:G,stopUpdating:X,isUpdating:se}=qt(),ae=(K,z)=>{const Z=z.title!==void 0?"title":"description";G(K,Z),k({resourceId:K,data:z},{onSuccess:()=>{X(K,Z)},onError:()=>{X(K,Z)}})},te=K=>{const z=S.find(Z=>Z.id===K);z&&k({resourceId:K,data:{isPrivate:!z.isPrivate}})},le=K=>{p(K),W==null||W.type,u(!0)};return Ee({debouncedSearchQuery:"",resourceId:(h==null?void 0:h.id)||"",resourceType:ee.DASHBOARD,userType:"tenant"}),N?e.jsx(Ut,{}):b?e.jsx(Fr,{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:K=>c(K.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:K=>d(K.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()||B,children:B?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{l(!1),c(""),d("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:B,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>l(!0),className:"h-8 w-full",size:"sm",disabled:B,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),B?"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:K=>n(K.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:Q.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(ha,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No dashboards found"})]}):Q.map(K=>e.jsx(Br,{dashboard:K,isDeleting:D,isDuplicating:g===K.id,isTitleUpdating:se(K.id,"title"),isDescriptionUpdating:se(K.id,"description"),onLoadDashboard:H,onEditDashboard:t.onEditDashboard,onUpdateDashboard:ae,onDeleteClick:U,onDuplicateDashboard:Y,onTogglePrivacy:te,onShareDashboard:le,formatDate:$,onDashboardItemClick:t.onDashboardItemClick},K.id))})}),m&&h&&e.jsx(sn,{resource:h,resourceType:ee.DASHBOARD,onShare:V,isSharing:T,isRemoving:v,isUpdating:M,onClose:()=>{u(!1),p(null)},onRemoveAccess:_}),e.jsx(s.AlertDialog,{open:f,onOpenChange:K=>{!K&&D||(j(K),K||y(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:D,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:K=>{K.preventDefault(),K.stopPropagation(),P()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:D,children:D?"Deleting...":"Delete"})]})]})})]})}function an({isOpen:t,onClose:a,className:n,onDashboardItemClick:r}){s.useDashboardStore(f=>f.dashboard);const{setDashboard:l,addSheet:o}=s.useDashboardStore(f=>f.actions),{currentUser:c}=Ne(),i=c,[d,m]=s.useLocalStorageState("resource-management-active-tab","dashboards"),u=Qt(a,{enabled:t}),h=f=>{},p=f=>{console.log("Editing dashboard:",f)};return e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{ref:u,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":"hidden -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:i&&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:i.name}),e.jsx(s.AvatarFallback,{className:"text-xs",children:i.name.charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-xs font-medium",children:i.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:i.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:i.email}),i.role&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Role:"," ",s.toTitleCase(i.role.replace(/_/g," "))]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",i.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:d,onValueChange:m,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(Pr,{onLoadDashboard:h,onEditDashboard:p,onDashboardItemClick:r})}),e.jsx(s.TabsContent,{value:"visuals",className:"flex-1",children:e.jsx(Rr,{})})]})})]})})}function zr(){var H,U;const{authToken:t,tokenProps:a}=s.useSemaphorContext();s.useDashboardStore(P=>P.theme);const n=s.useDashboardStore(P=>P.lenses),r=s.useDashboardStore(P=>P.selectedLensId),l=n==null?void 0:n.find(P=>P.id===r),o=s.useDashboardStore(P=>P.dashboard);s.useDashboardStore(P=>P.selectedSheetId);const c=s.useDashboardStore(P=>P.isDashboardEditing),i=s.useEditorStore(P=>P.card),d=s.useEditorStore(P=>P.selectedConnectionId),[m,u]=A.useState(!1),h=s.useDashboardStore(P=>P.isDashboardPanelOpen),p=s.useDashboardStore(P=>P.actions.setIsDashboardPanelOpen),f=s.useDashboardStore(P=>P.filterValues),j=s.useDashboardStore(P=>P.isVisualEditing),x=s.useManagementStore(P=>P.selectedDashboard),y=s.useManagementStore(P=>P.initialDashboard),g=x?(U=x==null?void 0:x.permissions)==null?void 0:U.canEdit:(H=y==null?void 0:y.permissions)==null?void 0:H.canEdit,C=s.useDashboardStore(P=>P.showFilters);s.useDashboardStore(P=>P.showDashboardJSON);const E=s.useDashboardStore(P=>P.onSaveFunction),R=s.useDashboardStore(P=>P.actions.setShowFilters),{addFrame:S,setSelectedFrameId:N}=s.useDashboardStore(P=>P.actions),{getSelectedSheet:b,setIsDashboardEditing:I,setShowDashboardJSON:k}=s.useDashboardStore(P=>P.actions),L=b(),{setInitialDashboard:w}=s.useManagementStore(P=>P.actions),{resources:B}=Vs(ee.DASHBOARD);A.useEffect(()=>{if(B&&B.length>0){const P=o==null?void 0:o.id;if(P){const Y=B.find(G=>G.id===P);Y&&w(Y)}}},[B,o==null?void 0:o.id,w]);const D=a.orgUserId||a.tenantId,T=c&&!j&&D&&g;function v(){var X,se;const P=i.dataSource;if(P)return P;const Y=(se=(X=o.aiContext)==null?void 0:X.selectedEntities)==null?void 0:se[0],G=Y==null?void 0:Y.type;if(Y)return{connectionId:Y.connectionId,connectionType:Y.connectionType,type:G,selectedEntities:[Y]}}const M=()=>{if(!c||!L)return;const Y={dataSource:v(),mode:"explorer",connectionId:d,id:s.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},G={id:s.v4(),cards:[Y],activeCardId:Y.id};S(L.id,G),N(G.id)},F=()=>{I(!0)},[O,V]=A.useState(!1),_=$t(ee.DASHBOARD);async function W(){const P=as(o);V(!0);const Y={template:P};_.mutate({resourceId:P.id,data:Y},{onSuccess:()=>{V(!1),s.ue.success("Dashboard saved!")},onError:()=>{V(!1),s.ue.error("Failed to save dashboard")}})}async function Q(){if(u(!0),!r||!l)return;const P=as(o),Y=JSON.stringify(P),G={...l,template:Y,filterValues:f};await ks(G,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),E==null||E(P),u(!1)}if(j)return null;const $=(l==null?void 0:l.name)||o.title,q=a.orgUserId||a.tenantId&&a.endUserId&&a.endUserEmail;return e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b py-2 pl-3 pr-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[q&&e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:"Manage Dashboards",onClick:()=>p(!0),className:"h-7 p-2",children:e.jsx(ga,{className:"h-4 w-4"})}),!j&&e.jsx(s.Label,{children:$})]}),e.jsxs("div",{className:"flex gap-2",children:[!1,!j&&e.jsx(qa,{}),!j&&e.jsx(_t,{}),c&&!j&&D&&e.jsx(Ua,{}),!j&&D&&e.jsx($a,{}),c&&!j&&e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",disabled:!c,onClick:M,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!j&&!c&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:F,size:"sm",children:[e.jsx(s.Pencil,{className:"mr-2 h-4 w-4"}),"Edit"]}),c&&!j&&e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",onClick:()=>{I(!1),k(!1)},children:[e.jsx(s.Cross2Icon,{className:"mr-2 h-4 w-4"}),"Close"]}),c&&!j&&D&&l&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:m,onClick:Q,size:"sm",children:[e.jsx(Ds,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),T&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"outline",disabled:O,onClick:W,size:"sm",children:[O?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Ds,{className:"mr-2 h-4 w-4"}),O?"Saving...":"Save"]}),!C&&!j&&c&&e.jsx(s.Button,{className:"h-7 p-2",variant:"ghost",onClick:()=>R(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!j&&c&&!1,!j&&!1,!j&&e.jsx(an,{isOpen:h,onClose:()=>p(!1)})]})]})}function Vr({name:t,items:a,value:n,onChange:r,isLoading:l,isError:o,refetch:c,className:i,icon:d,showNone:m=!1}){const u=ue.useRef(null),[h,p]=ue.useState(!1),[f,j]=ue.useState("100%"),x=m?[...a||[],{id:"none",name:"None"}]:a;ue.useLayoutEffect(()=>{u.current&&j(u.current.offsetWidth)},[]);function y(){var C;return l?"Loading...":o?"Error":n?(C=a==null?void 0:a.find(E=>E.id===n))==null?void 0:C.name:`Select ${t}`}function g(C,E){r(E),p(!1)}return e.jsxs(s.Popover,{open:h,onOpenChange:p,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{ref:u,variant:"outline",role:"combobox","aria-expanded":h,className:s.cn("flex h-9 w-full justify-between",i),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[d&&e.jsx("div",{className:"mr-2",children:d}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children:y()})]}),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(Rt,{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(C=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:C.name,onSelect:E=>g(E,C.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",n===C.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:C.name,children:C.name})]})},C.id))})]})]})})]})}function Ve({title:t,items:a,value:n,isLoading:r,isError:l,refetch:o,onChange:c,showNone:i=!1,className:d,disabled:m=!1,type:u="combobox"}){const h=r?"Loading...":l?"Error":n;function p(){if(t==="Connection")return e.jsx(Ta,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(Da,{className:"size-4"});if(t==="Table")return e.jsx(_e,{className:"size-4"});if(t==="Model")return e.jsx(Zn,{className:"size-4"})}function f(){return e.jsxs(s.Select,{disabled:m,value:h,onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:s.cn("h-9 w-full border-muted focus:ring-1 focus:ring-offset-0",d),children:e.jsx(s.SelectValue,{placeholder:r?"Loading...":l?"Error":`Select ${t}`})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[r?e.jsx(s.SelectLabel,{children:"Loading..."}):e.jsxs(s.SelectLabel,{className:"flex items-center justify-between gap-2",children:[t,e.jsx(Rt,{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,y)=>e.jsx(s.SelectItem,{value:x.id,children:x.name},y))]}),(r||l)&&e.jsx(s.SelectItem,{value:h,children:h})]})})]})}function j(){return e.jsx(Vr,{icon:p(),items:a,value:h,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:u==="select"?f():j()})})}function _r({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(),u=s.useEditorStore(x=>x.actions.setSqlGen),h=s.useEditorStore(x=>x.actions.setCardSql),p=s.useEditorStore(x=>x.actions.setRunSql);function f(x,y){var R;const g=s.createSqlGenConfig(x,i,y),C=(R=d==null?void 0:d.find(S=>S.id===c))==null?void 0:R.name;u(g);const E=s.getSql(g,s.fmt(l||""),s.fmt(r),C||"",m,o||"");E&&(h(E),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 $s({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(Ge,{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(ns,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(ea,{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 gs({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($s,{column:t}),e.jsx("span",{children:t.column_name})]})}function Ur({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 $r({onClick:t,column:a}){const n=s.useDndStore(u=>u.activeId),r=s.useEditorStore(u=>{var h;return(h=u.card.queryConfig)==null?void 0:h.groupByColumns}),l=s.useEditorStore(u=>{var h;return(h=u.card.queryConfig)==null?void 0:h.metricColumns}),o=s.useEditorStore(u=>{var h;return(h=u.card.queryConfig)==null?void 0:h.filterColumns});function c(u){return i(u)||d(u)||m(u)}function i(u){return r==null?void 0:r.some(h=>h.name===u.column_name)}function d(u){return l==null?void 0:l.some(h=>h.name===u.column_name)}function m(u){return o==null?void 0:o.some(h=>h.name===u.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(gs,{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(gs,{column:a})}),e.jsx(Ur,{id:a.column_name,type:"column",children:e.jsx(gs,{column:a})})]})}const js={id:"__placeholder__",role:"groupby",type:"string"},ys={id:"__placeholder__",role:"groupby",type:"string"},bs={id:"__placeholder__",role:"metric",type:"number"},vs={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},rn={id:"__placeholder__"},Ae="droppable-group-by",Me="droppable-metrics",Le="droppable-pivot-by",ls="sortable-group-by",Es="sortable-metrics",os="sortable-pivot-by",Ts="droppable-filters",Is="sortable-filters",qs="sortable-order-by";function qr(){const t=s.useDndStore(T=>T.insertIndex),a=s.useEditorStore(T=>{var v;return((v=T.card.queryConfig)==null?void 0:v.groupByColumns)||[]}),n=s.useEditorStore(T=>{var v;return((v=T.card.queryConfig)==null?void 0:v.metricColumns)||[]}),r=s.useEditorStore(T=>{var v;return((v=T.card.queryConfig)==null?void 0:v.filterColumns)||[]}),l=s.useEditorStore(T=>{var v;return((v=T.card.queryConfig)==null?void 0:v.orderBy)||[]}),o=s.useEditorStore(T=>{var v;return((v=T.card.queryConfig)==null?void 0:v.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:i,setPreviewGroupByColumns:d,setPreviewMetricColumns:m,setPreviewFilterColumns:u,setPreviewPivotColumns:h}=s.useDndActions(),{setGroupByColumns:p,setMetricColumns:f,setFilterColumns:j,setOrderByColumns:x,setPivotByColumns:y}=s.useEditorActions(),{columns:g}=s.useDataColumns(),{formattedTableName:C}=s.useEditorAside(),E=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),R=T=>{var F;const{active:v,over:M}=T;if(((F=v.data.current)==null?void 0:F.type)==="column"&&M){const O=M.id,V=g.find($=>$.column_name===v.id);if(!V)return;const _=s.isNumberDataType(V.data_type),W=s.isTextDataType(V.data_type),Q=s.isDateDataType(V.data_type);if(W||Q){if(a.some(q=>q.id===O)){const q=a.findIndex(U=>U.id===O);c(q);const H=a.filter(U=>U.id!==js.id);H.splice(q,0,js),d(H)}else if(M.id===Ae){c(a.length);const q=[...a,js];d(q),m(n),u(r)}}if(W||Q){if(o.some(q=>q.id===O)){const q=o.findIndex(U=>U.id===O);c(q);const H=o.filter(U=>U.id!==ys.id);H.splice(q,0,ys),h(H)}else if(M.id===Le){c(o.length);const q=[...o,ys];h(q),d(a),m(n),u(r)}}if(_||W){if(n.some(q=>q.id===O)){console.log("isOverMetricSortable",O);const q=n.findIndex(U=>U.id===O);c(q);const H=n.filter(U=>U.id!==bs.id);H.splice(q,0,bs),m(H)}else if(M.id===Me){c(n.length);const q=[...n,bs];m(q),u(r),d(a),h(o)}}if(N(V)){if(r.some(q=>q.id===O)){const q=r.findIndex(U=>U.id===O);c(q);const H=r.filter(U=>U.id!==vs.id);H.splice(q,0,vs),u(H)}else if(M.id===Ts){c(r.length);const q=[...r,vs];u(q),m(n),d(a),h(o)}}}else d(a),m(n),u(r),h(o)};function S(T){i(T.active.id),c(null),d(a),m(n),u(r),h(o)}function N(T){return!r.some(v=>v.name===T.column_name)}function b(T,v="SUM"){const{column_name:M,data_type:F}=T,O=[...n],V=t!==null?t:n.length,_={...T,id:fe(M),name:M,label:We(M,v),type:F,role:"metric",aggregate:v};O.splice(V,0,_),f(O)}function I(T){const v=s.isTextDataType(T.data_type);s.isDateDataType(T.data_type);const M=[...o],F=t!==null?t:o.length;let O;v?O={...T,id:fe(T.column_name),name:T.column_name,type:T.data_type,role:"groupby"}:O={...T,id:fe(T.column_name),name:T.column_name,type:T.data_type,role:"groupby",label:Ue(T.column_name,"month"),granularity:"month"},M.splice(F,0,O),y(M)}function k(T){const v=s.isTextDataType(T.data_type);s.isDateDataType(T.data_type);const M=[...a],F=t!==null?t:a.length;let O;v?O={...T,id:fe(T.column_name),name:T.column_name,type:T.data_type,role:"groupby"}:O={...T,id:fe(T.column_name),name:T.column_name,type:T.data_type,role:"groupby",label:Ue(T.column_name,"month"),granularity:"month"},M.splice(F,0,O),p(M)}function L(T){const v=[...r],M=t!==null?t:r.length,F={...T,id:fe(T.column_name),name:T.column_name,type:T.data_type,sql:s.getDefaultFilterSql(T.data_type,C,s.fmt(T.column_name)),role:"filter"};v.splice(M,0,F),j(v)}function w(T){var O,V,_,W,Q,$,q,H;const{active:v,over:M}=T,F=v.data.current;if((F==null?void 0:F.type)==="column"&&M){const U=g.find(X=>X.column_name===v.id);if(!U)return;const P=s.isNumberDataType(U.data_type),Y=s.isTextDataType(U.data_type),G=s.isDateDataType(U.data_type);(Y||G)&&(M.id===Ae||((O=M.data.current)==null?void 0:O.type)===ls)&&k(U),(Y||G)&&(M.id===Le||((V=M.data.current)==null?void 0:V.type)===os)?I(U):(P||Y)&&(M.id===Me||((_=M.data.current)==null?void 0:_.type)===Es)?(P&&b(U),Y&&b(U,"COUNT")):N(U)&&(M.id===Ts||((W=M.data.current)==null?void 0:W.type)===Is)&&L(U)}if(M&&((Q=M.data.current)==null?void 0:Q.type)===ls&&a.some(U=>U.id===v.id)){const U=a.findIndex(Y=>Y.id===v.id),P=a.findIndex(Y=>Y.id===M.id);if(U!==-1&&P!==-1&&U!==P){const Y=[...a],[G]=Y.splice(U,1);Y.splice(P,0,G),p(Y)}}if(M&&(($=M.data.current)==null?void 0:$.type)===os&&o.some(U=>U.id===v.id)){const U=o.findIndex(Y=>Y.id===v.id),P=o.findIndex(Y=>Y.id===M.id);if(U!==-1&&P!==-1&&U!==P){const Y=[...o],[G]=Y.splice(U,1);Y.splice(P,0,G),y(Y)}}if(M&&((q=M.data.current)==null?void 0:q.type)===Es&&n.some(U=>U.id===v.id)){const U=n.findIndex(Y=>Y.id===v.id),P=n.findIndex(Y=>Y.id===M.id);if(U!==-1&&P!==-1&&U!==P){const Y=[...n],[G]=Y.splice(U,1);Y.splice(P,0,G),f(Y)}}if(M&&((H=M.data.current)==null?void 0:H.type)===Is&&r.some(U=>U.id===v.id)){const U=r.findIndex(Y=>Y.id===v.id),P=r.findIndex(Y=>Y.id===M.id);if(U!==-1&&P!==-1&&U!==P){const Y=[...r],[G]=Y.splice(U,1);Y.splice(P,0,G),j(Y)}}B(T),i(null),c(null),d(a),m(n),u(r),h(o)}function B(T){const{active:v,over:M}=T,F=v.data.current;if((F==null?void 0:F.type)===qs&&M){const O=l.findIndex(_=>Ye(_.columnId)===v.id),V=l.findIndex(_=>Ye(_.columnId)===M.id);if(O!==-1&&V!==-1&&O!==V){const _=[...l],[W]=_.splice(O,1);_.splice(V,0,W),x(_)}}}function D(){i(null),c(null),d(a),m(n),u(r)}return{handleDragOver:R,handleDragEnd:w,handleDragStart:S,handleDragCancel:D,sensors:E}}function fe(t){return`${t}-${s.v4()}`}function We(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 Ye(t){return`${qs}-${t}`}function Ue(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 Yr({schemaName:t,tableName:a,columns:n,status:r}){const l=s.useEditorStore(v=>v.sqlGen),o=s.useEditorStore(v=>v.isDevMode),c=s.useEditorStore(v=>v.selectedConnectionId),i=s.useEditorStore(v=>{var M,F;return(F=(M=v.card)==null?void 0:M.queryConfig)==null?void 0:F.metricColumns});s.useEditorStore(v=>{var M,F;return(F=(M=v.card)==null?void 0:M.queryConfig)==null?void 0:F.groupByColumns});const d=s.useEditorStore(v=>v.selectedDatabaseName),m=s.useEditorStore(v=>v.selectedSchemaName),u=s.useEditorStore(v=>v.selectedTableName),h=s.useEditorStore(v=>v.selectedDatamodelId),p=s.useDashboardStore(v=>v.dashboard.aiScopeTables),{addToAIScope:f,removeFromAIScope:j}=s.useDashboardActions(),{addColumnToMetricColumns:x,addColumnToGroupBy:y,setCardSql:g,setRunSql:C,setSqlGen:E,setIsShowingVisual:R}=s.useEditorActions(),{connectionType:S,modelItems:N,selectedDatamodelName:b}=s.useEditorAside();function I(v){var M;if(o){const F=s.createSqlGenConfig(v,l);E(F);const O=(M=N==null?void 0:N.find(_=>_.id===h))==null?void 0:M.name,V=s.getSql(F,s.fmt(t),s.fmt(a),O||"",S,d||"");V&&(g(V),C(!0))}if(!o){if(s.isTextDataType(v.data_type))if(i&&i.length>0){const F={...v,role:"groupby",id:fe(v.column_name),name:v.column_name,type:v.data_type};y(F)}else{const F={...v,role:"metric",id:fe(v.column_name),name:v.column_name,label:We(v.column_name,"COUNT"),type:v.data_type,aggregate:"COUNT"};x(F)}if(s.isDateDataType(v.data_type)){const F={...v,role:"groupby",id:fe(v.column_name),name:v.column_name,type:v.data_type,label:Ue(v.column_name,"month"),granularity:"month"};y(F)}if(s.isNumberDataType(v.data_type)){const F={...v,role:"metric",id:fe(v.column_name),name:v.column_name,label:We(v.column_name,"SUM"),type:v.data_type,aggregate:"SUM"};x(F)}}}function k(v){v===!0&&(u||b)&&c?(f({connectionId:c,connectionType:S==="S3"||S==="API"?"DuckDb":S||"",databaseName:d||"",schemaName:m||"",tableName:u||"",datamodelName:s.resolveDatamodelName(b),datamodelId:h||""}),s.ue.success("Added to Assistant Scope",{position:"top-right",duration:2500,richColors:!0})):(j({connectionId:c||"",connectionType:S||"",tableName:u||"",datamodelName:s.resolveDatamodelName(b),datamodelId:h||"",databaseName:d||"",schemaName:m||""}),s.ue("Removed from Assistant Scope",{position:"top-right",duration:2e3,richColors:!0}))}function L(){const v=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:b,connectionType:S,databaseName:d||""});R(!1);const M=S==="MSSQL"?`SELECT top 10 * FROM ${v}`:`SELECT * FROM ${v} LIMIT 10`;g(M),C(!0)}function w(){const v=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:b,connectionType:S,databaseName:d||""});g(`SELECT COUNT(*) as count FROM ${v}`),C(!0)}function B(){return(p==null?void 0:p.find(v=>v.connectionId===c&&(v.tableName===u||v.datamodelName===b)))!==void 0}function D(v){return o?e.jsxs("div",{className:"flex grow items-center justify-between space-x-2 rounded-md px-2 py-1",onClick:()=>I(v),children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx($s,{column:v}),e.jsx("span",{children:v.column_name})]}),e.jsx("div",{onClick:M=>M.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(v.data_type)&&e.jsx(_r,{column:v})})]}):e.jsx($r,{onClick:I,column:v})}function T(){return e.jsxs(e.Fragment,{children:[e.jsxs(s.Toggle,{title:`${B()?"Remove from":"Add to"} Assistant Scope`,pressed:B(),onPressedChange:k,variant:"outline",className:s.cn("h-9 px-2",{}),children:[e.jsx(s.Plus,{className:s.cn("mr-1 size-4",{"text-green-400":B(),"text-muted-foreground":!B()})}),"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(Na,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:w,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(Bt,{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((v,M)=>e.jsx(s.Skeleton,{className:"h-7 w-full"},M))}):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:T()}),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(v=>e.jsx("div",{className:s.cn("mr-2 cursor-pointer rounded-md text-sm transition-colors hover:bg-muted"),children:D(v)},v.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function ln({ColumnsComponent:t,type:a}){var Te;const n=s.useEditorStore(ne=>ne.card),r=s.useEditorStore(ne=>ne.selectedConnectionId),l=s.useDashboardStore(ne=>ne.showFilters),o=s.useEditorStore(ne=>ne.selectedDatamodelId),c=s.useEditorStore(ne=>ne.selectedDatabaseName),i=s.useEditorStore(ne=>ne.selectedSchemaName),d=s.useEditorStore(ne=>ne.selectedTableName),m=s.useEditorStore(ne=>ne.isDevMode),{setSelectedTableName:u,setIsDevMode:h,setCardSql:p}=s.useEditorActions(),{connectionItems:f,modelItems:j,schemaItems:x,databaseItems:y,tableItems:g,columns:C,isConnectionsLoading:E,isModelsLoading:R,isConnectionsError:S,isModelsError:N,isDatabasesLoadingOrFetching:b,isDatabaseError:I,isSchemaLoadingOrFetching:k,isSchemaError:L,isColumnsError:w,isColumnsLoadingOrFetching:B,isTableLoadingOrFetching:D,isTableError:T,connectionType:v,isNonDbConnection:M,refetchDatabases:F,refetchModels:O,refetchSchemas:V,refetchTables:_,refetchColumns:W,refetchConnections:Q,handleConnectionChange:$,handleDatabaseChange:q,handleSchemaChange:H,handleDatamodelChange:U,handleTableChange:P,tableName:Y,schemaName:G}=s.useEditorAside(),{data:X,refetch:se}=s.useDashboardCardQuery(n);function ae(){return t?t(G,Y,C):e.jsx(Yr,{schemaName:G,tableName:Y,columns:C,status:B?"Loading...":w?"Error":"Success"})}function te(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function le(ne){ne===!0?X&&(p(X.userSql),setTimeout(()=>{se()},100)):p(""),h(ne)}function K(){if(!r||v==="S3"||v==="API")return null;if(!o||o==="none")return e.jsx(Ve,{refetch:F,showNone:!0,onChange:q,isError:I,isLoading:b,items:y,value:c||"",title:"Database",type:"combobox"})}function z(){if(r&&!M&&(!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 Z(){if(!r||v==="S3"||v==="API")return null;if(!c||c==="none")return e.jsx(Ve,{refetch:O,showNone:!0,onChange:U,isError:N,isLoading:R,items:j,value:o||"",title:"Model",type:"combobox"})}function oe(){return!r||v==="S3"||v==="API"||!c||c==="none"?null:e.jsx(Ve,{refetch:V,onChange:H,isError:L,isLoading:k,items:x,value:i||"",title:"Schema",type:"combobox"})}function Ce(){function ne(){let ie=!1;return v==="API"?(ie=!1,ie):((v==="S3"||r&&c&&c!=="none"&&i)&&(ie=!0),ie)}return ne()?e.jsx(Ve,{refetch:_,onChange:P,isError:T,items:g,isLoading:D,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(Ve,{refetch:Q,items:f,title:"Connection",value:r||"",onChange:$,isLoading:E,isError:S,type:"combobox",connectionTooltip:((Te=f==null?void 0:f.find(ne=>ne.id===r))==null?void 0:Te.type)||""}),K(),z(),Z(),oe(),Ce()]}),ae(),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:le,id:"dev-mode"}),e.jsx(s.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(s.Button,{onClick:te,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(Sa,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function on({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 u(){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 h(){o(!1),i.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${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:u,onMouseDown:h,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),l&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function cn({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(on,{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(ca,{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(fa,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function dn({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(At,{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(cn,{sql:t,error:a,onDebugWithAssistant:n})})]})}var un={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},gt=A.createContext&&A.createContext(un),Gr=["attr","size","title"];function Hr(t,a){if(t==null)return{};var n=Kr(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 Kr(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 is(){return is=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},is.apply(this,arguments)}function jt(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 cs(t){for(var a=1;a<arguments.length;a++){var n=arguments[a]!=null?arguments[a]:{};a%2?jt(Object(n),!0).forEach(function(r){Qr(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):jt(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Qr(t,a,n){return a=Wr(a),a in t?Object.defineProperty(t,a,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[a]=n,t}function Wr(t){var a=Jr(t,"string");return typeof a=="symbol"?a:a+""}function Jr(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 mn(t){return t&&t.map((a,n)=>A.createElement(a.tag,cs({key:n},a.attr),mn(a.child)))}function Re(t){return a=>A.createElement(Xr,is({attr:cs({},t.attr)},a),mn(t.child))}function Xr(t){var a=n=>{var{attr:r,size:l,title:o}=t,c=Hr(t,Gr),i=l||n.size||"1em",d;return n.className&&(d=n.className),t.className&&(d=(d?d+" ":"")+t.className),A.createElement("svg",is({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,c,{className:d,style:cs(cs({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 gt!==void 0?A.createElement(gt.Consumer,null,n=>a(n)):a(un)}function Zr(t){return Re({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 hn(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(),u=A.useRef(),h=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(u.current&&c){const x=u.current.getModel();x&&(h.current[l.id]=x);let y=h.current[o];if(!y){const g=f();y=c.editor.createModel(g,t),h.current[o]=y}u.current.setModel(y)}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",y=n==="system"?x:n;c.editor.defineTheme("default",{base:y==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":y==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[a,n,c]),A.useEffect(()=>{const x=u.current;x&&c&&l&&x.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return i(),!1})},[c,i,l]);function j(x,y){if(u.current=x,!h.current[l.id]){const g=x.getModel(),C=f();h.current[l.id]=g||(y==null?void 0:y.editor.createModel(C,t))||x.getModel()}x.setModel(h.current[l.id])}return{handleEditorDidMount:j}}function el(){const t=s.useEditorStore(c=>c.card.sql),a=s.useEditorStore(c=>c.sqlGen),{setCardSql:n,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=hn("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 sl(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:a}=s.useEditorActions(),{handleEditorDidMount:n}=hn("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 tl({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 Ys({variant:t="outline"}){var c;const{setCardSql:a}=s.useEditorActions();s.useEditorStore(i=>i.frame);const n=s.useEditorStore(i=>i.card);_s(((c=n.customCardPreferences)==null?void 0:c.url)||""),s.useEditorStore(i=>i.selectedSchemaName),s.useEditorStore(i=>i.selectedDatamodelId),s.useEditorStore(i=>i.selectedDatabaseName),s.useEditorStore(i=>i.selectedTableName),s.useEditorStore(i=>i.selectedConnectionId),s.useEditorStore(i=>i.isShowingVisual),n.sql;const r=s.useEditorStore(i=>i.onSave),{getUpdatedFrame:l}=Us();function o(){const i=l();r==null||r(i)}return e.jsxs(s.Button,{onClick:o,className:"h-8",size:"sm",variant:t,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function nl(){const t=s.useQueryClient(),[a,n]=A.useState(!1),r=s.useDashboardStore(m=>m.actions.setIsDashboardPanelOpen),{setIsVisualEditing:l}=s.useDashboardActions(),{getUpdatedFrame:o}=Us(),c=s.useSelectedVisual(),i=hr(),d=()=>{const m=o();if(!(c!=null&&c.id)){s.ue.error("No visual selected");return}n(!0),i.mutate({visualId:c.id,data:{frameObject:m}},{onSuccess:()=>{n(!1),l(!1),r(!0),s.ue.success("Visual updated successfully"),t.invalidateQueries({queryKey:["resource-by-id","visual",c.id],exact:!0})},onError:()=>{n(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:d,className:"h-8",size:"sm",children:[a&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!a&&e.jsxs(e.Fragment,{children:[e.jsx(Ds,{className:"mr-2 size-4 font-bold"}),"Save"]})]})}function Gs(){const{setTempQueryData:t,setSqlGen:a}=s.useEditorActions(),n=s.useQueryClient(),r=s.useEditorStore(d=>d.tempQueryData),l=s.useEditorStore(d=>d.onClose),o=s.useEditorStore(d=>d.card),{queryKey:c}=s.useDashboardCardQuery(o);function i(){if(r){const{queryKey:d,queryData:m}=r;d&&m&&n.setQueryData(d,m)}a({}),l==null||l()}return e.jsxs(s.Button,{onClick:i,className:"h-8",size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function hs(){const{setTempQueryData:t}=s.useEditorActions(),a=s.useQueryClient(),n=s.useEditorStore(y=>y.isDevMode),r=s.useEditorStore(y=>y.tempQueryData),l=s.useEditorStore(y=>y.card),{queryKey:o}=s.useDashboardCardQuery(l),{setCardSql:c,setSqlGen:i,setCardPython:d,setCardCustomCfg:m,setCardPreferences:u,updateDataSource:h,clearQueryConfig:p,setCardConfig:f,setCardType:j}=s.useEditorActions();function x(){const y=a.getQueryData(o);r!=null&&r.queryData||t({queryKey:o,queryData:y}),a.setQueryData(o,null),a.removeQueries({queryKey:o,exact:!0}),n&&h(s.EMPTY_DATA_SOURCE),c(""),i({}),p(),f(void 0),d(""),m(""),u({}),j("bar")}return e.jsxs(s.Button,{onClick:x,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(s.SquarePen,{className:"mr-2 size-4"}),"Clear"]})}function al(){const t=s.useQueryClient(),[a,n]=A.useState(!1),[r,l]=A.useState(!1);s.useEditorStore(_=>_.frame);const o=s.useEditorStore(_=>_.card);s.useEditorStore(_=>_.isShowingVisual),s.useEditorStore(_=>_.selectedConnectionId),s.useEditorStore(_=>_.tempQueryData),s.useEditorStore(_=>_.selectedDatabaseName),s.useEditorStore(_=>_.selectedDatamodelId),s.useEditorStore(_=>_.selectedSchemaName);const c=s.useEditorStore(_=>_.showAIDialog);s.useEditorStore(_=>_.selectedTableName);const i=s.useEditorStore(_=>{var W;return(W=_==null?void 0:_.card)==null?void 0:W.sql}),d=s.useEditorStore(_=>{var W;return(W=_==null?void 0:_.card)==null?void 0:W.python}),{sheetFilterValues:m}=s.useSheetFilterValues(),{setCardCustomCfg:u,setQueryResultColumns:h,setCardSql:p,setTempQueryData:f,setPythonStdOut:j,setCardPreferences:x,setCardType:y,setCardPython:g,runAssistant:C,setShowAIDialog:E}=s.useEditorActions();s.useEditorStore(_=>_.onSave),s.useEditorStore(_=>_.onClose),s.useEditorStore(_=>_.actions.setSqlGen);const R=s.useEditorStore(_=>_.runSql),S=s.useEditorStore(_=>_.actions.setRunSql),N=s.useEditorStore(_=>_.actions.setIsSqlRunning),{data:b,isLoading:I,isFetching:k,isSuccess:L,isError:w,error:B,queryKey:D,refetch:T,errorMessage:v}=s.useDashboardCardQuery(o);A.useEffect(()=>{if(b&&(b.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),j((b==null?void 0:b.output)||""),b.records.length>0)){const{dimensionKeys:_}=s.getKeys(b.records);h(_)}},[b,h,j]),A.useEffect(()=>{(I||k)&&N(!0),(w||L)&&N(!1),w&&(h([]),j(""))},[I,k,b,j,w,L,N,h,B]),A.useEffect(()=>{R&&(t.getQueryData(D)||T(),S(!1))},[R,T,S,D,t]);async function M(){const _=`Can you help me debug this query in the current table scope?
|
|
417
432
|
|
|
418
433
|
Error:
|
|
419
434
|
|
|
@@ -425,11 +440,11 @@
|
|
|
425
440
|
|
|
426
441
|
${d?`Python:
|
|
427
442
|
${d}`:""}
|
|
428
|
-
`;C(_)}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(Zr,{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 O(){return e.jsxs(s.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(s.ResizablePanel,{id:"1",order:1,defaultSize:a?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(Jr,{})}),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(Xr,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function V(){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:T||k,onClick:()=>{I()},className:"h-8 shrink-0",size:"sm",children:[T||k?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(cn,{sql:b==null?void 0:b.sql,error:v,onDebugWithAssistant:M}),e.jsx(hs,{}),e.jsx(s.Toggle,{pressed:a,onPressedChange:_=>n(_),className:"",size:"sm",children:e.jsx(Wr,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:c,onClick:()=>{E(!0)},className:"h-9 w-full cursor-text px-3 text-left text-sm text-muted-foreground",children:c?"":"Type your question..."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gs,{}),e.jsx(Ys,{})]})]})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsxs("div",{className:"relative flex grow justify-between overflow-y-scroll",children:[O(),F()]}),V()]})}function tl({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 nl({card:t}){var C,E,R,S,N,b,T,k,L,w,B;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(D=>D.themeStyle),d={colors:((E=(C=i==null?void 0:i.chart)==null?void 0:C.dataset)==null?void 0:E.backgroundColor)||[]};(R=t.customCardPreferences)!=null&&R.inputData;const{getCard:m}=s.useCustomVisual(((S=t.customCardPreferences)==null?void 0:S.url)||""),u=((N=t.customCardPreferences)==null?void 0:N.visualType)||"single",h=s.useEditorStore(D=>D.frame),{setCustomCardPreferences:p}=s.useEditorActions(),{data:f}=s.useDashboardCardQuery(t),j=A.useCallback((D,I)=>{l(v=>({...v,[D]:I}))},[]);if(!((b=t.customCardPreferences)!=null&&b.componentName))return null;const x=m((T=t.customCardPreferences)==null?void 0:T.componentName);function y(D){n(D)}const g=Object.keys(((k=t.customCardPreferences)==null?void 0:k.dataInputCardIds)||{}).map(D=>{var M,F,O;const I=(F=(M=t.customCardPreferences)==null?void 0:M.dataInputCardIds)==null?void 0:F[D].cardId,v=(O=h==null?void 0:h.cards)==null?void 0:O.find(V=>V.id===I);return v||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&&u==="single"&&e.jsx(x,{editing:!0,params:c,theme:d,settings:(L=t.customCardPreferences)==null?void 0:L.settings,onDataChange:j,data:(f==null?void 0:f.records)||[]}),x&&u==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((w=t.customCardPreferences)==null?void 0:w.dataInputCardIds)||{}).map(D=>{var M,F,O;const I=(F=(M=t.customCardPreferences)==null?void 0:M.dataInputCardIds)==null?void 0:F[D].cardId,v=(O=h==null?void 0:h.cards)==null?void 0:O.find(V=>V.id===I);if(v)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:y,onDataChange:j,dataInputIndex:D,card:v},v.id+D)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(x,{theme:d,onDataChange:j,settings:g.map(D=>{var I;return(I=D==null?void 0:D.customCardPreferences)==null?void 0:I.settings}),data:g.map(D=>D!=null&&D.id?r==null?void 0:r[D.id]:[])})})]})]},(B=t.customCardPreferences)==null?void 0:B.componentName)})}function hn({className:t,...a}){var T;const n=s.useEditorStore(k=>k.card),r=s.isExplorerCard(n),l=((T=n.customCardPreferences)==null?void 0:T.showCardHeader)??!0,o=s.useEditorStore(k=>k.frame),c=s.useDashboardStore(k=>k.dashboard.filters),i=s.useEditorStore(k=>k.actions.setRunSql),{updateFilter:d}=s.useDashboardActions(),m=c==null?void 0:c.find(k=>k.id===o.filterId),{data:u,isLoading:h,isFetching:p,errorMessage:f,pagination:j,refetch:x}=s.useDashboardCardQuery(n),{setCard:y,updateCardInFrame:g}=s.useEditorActions(),{data:C}=s.useTopoJson(n),E=A.useMemo(()=>n.type==="pivotTable"&&(u!=null&&u.records)&&(u==null?void 0:u.records.length)>0?s.getPivotTableConfig({card:n,data:{records:(u==null?void 0:u.records)||[],columnSubtotalMeta:u==null?void 0:u.columnSubtotalMeta,subtotalColumns:u==null?void 0:u.subtotalColumns,pivotSchema:(u==null?void 0:u.pivotSchema)||[],groupByColumns:u==null?void 0:u.groupByColumns}}):null,[n,u==null?void 0:u.records,u==null?void 0:u.columnSubtotalMeta,u==null?void 0:u.subtotalColumns,u==null?void 0:u.pivotSchema,u==null?void 0:u.groupByColumns]),R=(k,L)=>{var B,D;const w={...n,paginationConfig:{page:k+1,pageSize:L}};y(w),g(w),n.sql&&((D=(B=n.preferences)==null?void 0:B.tablePrefs)!=null&&D.enableDevModePagination)&&i(!0)},S=A.useMemo(()=>!n.id||!(u!=null&&u.records)?null:s.createChartConfig({card:n,data:u==null?void 0:u.records,cardType:n.type,queryConfig:n.queryConfig,customCfg:n.customCfg,preferences:n.preferences,topoJson:C}),[n.id,u==null?void 0:u.records,n.type,n.queryConfig,n.customCfg,n.preferences,C]);function N(k){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(nl,{card:k})})}function b(){if(u!=null&&u.records&&(u==null?void 0:u.records.length)===0&&!h&&!p)return f?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.SearchX,{className:"size-8 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r?"Error fetching data. Please check your chart configuration":"Error fetching data. Please check your SQL or Python code."})]}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((h||p)&&n.type!=="table")return e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!n.id)return null;if(n.type==="custom")return N(n);if(!["table","pivotTable","aggregateTable","custom"].includes(n.type)&&S)return e.jsx(e.Fragment,{children:h||p?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:S})});if(n.type==="table")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:n,data:(u==null?void 0:u.records)||[],paginationMetadata:j,onPaginationChange:R,isLoading:h||p})});if(n.type==="pivotTable"&&E)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.PivotTableVisual,{card:n,data:E.data,options:E.options,onAggregationChange:k=>{const L=s.handleAggregationChange(k,n.config),w={...n,config:L};y(w),g(w)},onAggregationLabelChange:k=>{const L=s.handleAggregationLabelChange(k,n.config),w={...n,config:L};y(w),g(w)}})});if(n.type==="aggregateTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.AggregateTable,{card:n,data:(u==null?void 0:u.records)||[],groupByColumns:u==null?void 0:u.groupByColumns,pivotSchema:u==null?void 0:u.pivotSchema,paginationMetadata:j,onPaginationChange:R,onAggregationChange:k=>{const L=s.handleAggregationChange(k,n.config),w={...n,config:L};y(w),g(w)},isLoading:h||p})})}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:k=>y({...n,title:k}),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:k=>y({...n,description:k}),children:e.jsx(s.CardDescription,{children:n.description||"Add description"})},n.description)]}),m&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Editable,{enabled:!0,className:"my-1",text:m.title||m.column,onSave:k=>d({...m,title:k}),children:e.jsx(s.Label,{children:m.title})}),e.jsx(s.FilterComponent,{filter:m})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:b()})]})}const Ns=({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}),al=()=>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."})]})]}),rl=({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(Ns,{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(Ns,{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(Ns,{language:"javascript",value:t,onChange:l})})]}),ll=({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 ol(){const[t,a]=A.useState(!1),[n,r]=A.useState(""),[l,o]=A.useState(""),[c,i]=A.useState(""),[d,m]=A.useState(""),u=s.useEditorStore(S=>S.card),h=s.useEditorStore(S=>S.card.customCfg),p=h?JSON.stringify(h,null,2):"",{data:f}=s.useDashboardCardQuery(u),{data:j}=s.useTopoJson(u),{setCardCustomCfg:x,setCustomVisualCode:y}=s.useEditorActions(),g=S=>{var N,b;return JSON.stringify({...S,data:{...S.data,datasets:(b=(N=S.data)==null?void 0:N.datasets)==null?void 0:b.map(T=>({...T,data:[]}))}},null,2)},C=()=>{var N,b;if(!((N=f==null?void 0:f.records)!=null&&N.length))return;const S=s.createChartConfig({card:u,data:f.records,cardType:u.type,queryConfig:u.queryConfig,preferences:u.preferences,topoJson:j});if(S){r(g(S)),i(((b=u.preferences)==null?void 0:b.customVisualCode)||"");const T=s.merge(S,h);o(g(T))}},E=()=>{try{if(c&&y(c),l){const S=JSON.parse(l),N=s.getObjectDiff(JSON.parse(n),S);x(N),m("")}}catch{m("Invalid JSON configuration")}},R=Object.keys(h||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:a,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:C,className:R?"":"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(al,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(hn,{className:"w-1/2 rounded shadow-none"})}),e.jsx(rl,{customCode:c,cardCustomCfgString:p,mergedConfig:l,onConfigChange:S=>o(S??""),onCodeChange:S=>i(S??"")})]}),e.jsx(ll,{error:d,hasCardCustomConfig:!!h,onReset:()=>{o(n),x(null)},onApply:E,onClose:()=>a(!1)})]})]})}function xs(t){const[a,n]=A.useState(null);return a}function xn(){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 pn(){const{data:t,isLoading:a,isError:n}=xn(),r=s.useQueries({queries:((t==null?void 0:t.plugins)||[]).map(i=>({queryKey:["manifest",i.value],queryFn:()=>s.loadManifest(i.value),enabled:!!i.value,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:d=>Math.min(1e3*2**d,3e4)}))}),l=[];let o=a,c=n;return r.forEach((i,d)=>{var m;if(i.isLoading&&(o=!0),i.isError&&(c=!0),i.data&&((m=t==null?void 0:t.plugins)!=null&&m[d])){const u=t.plugins[d],h=i.data.visuals.map(p=>({name:p.name,pluginName:u.label,componentType:p.componentType,pluginType:u.type,icon:p.icon,chartType:p.chartType,url:u.value}));l.push(...h)}}),{data:l,isLoading:o,isError:c}}function il({onChartTypeChange:t}){const{setCardCustomCfg:a,setCardPreferences:n,setCardType:r,setCustomCardPreferences:l}=s.useEditorActions(),{data:o,isLoading:c,isError:i}=pn(),d=A.useCallback((m,u)=>{a(null),n({}),r(m),u&&l({type:"component",visualType:"single",url:u.url,componentName:u.name,icon:u.icon}),t==null||t()},[a,n,r,l,t]);return c?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading custom visuals..."})})]}):i?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-destructive",children:"Failed to load custom visuals"})})]}):!o||o.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:o.map((m,u)=>e.jsx(cl,{text:m.name,onClick:()=>d("custom",m),icon:m.icon},`${m.url}-${m.name}-${u}`))})]})}const cl=({text:t,icon:a,onClick:n})=>{const r=xs(),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 Hs(t){return Oe({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 dl(t){return Oe({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 Ks(t){return Oe({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 Qs(t){return Oe({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 Ws(t){return Oe({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 Js(t){return Oe({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 fn({onChartTypeChange:t,iconClassName:a}){const{setCardType:n,setCardPreferences:r,setIsDevMode:l}=s.useEditorStore(u=>u.actions),{setCardCustomCfg:o,setCustomCardPreferences:c,setQueryConfig:i}=s.useEditorActions();function d(u,h){o(null),r({}),n(u),["custom","text","map"].includes(u)&&(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(_e,{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(ds,{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(us,{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(Ls,{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(Ws,{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(Os,{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(Ks,{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(ms,{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(Bs,{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(Qs,{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(Ps,{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(Hs,{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(zs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Range Chart",onClick:()=>d("range"),className:"h-10 p-4",children:e.jsx(Rs,{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(Js,{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(Et,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Map",onClick:()=>d("map"),className:"h-10 p-4",children:e.jsx(Fs,{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(He,{className:s.cn("size-5",a)})})]})}function ul({chartType:t,className:a,customIcon:n,componentName:r}){const l=xs();switch(t){case"bar":return e.jsx(ds,{className:a});case"line":return e.jsx(us,{className:a});case"pie":return e.jsx(ms,{className:a});case"radar":return e.jsx(Ps,{className:a});case"scatter":return e.jsx(Os,{className:a});case"bubble":return e.jsx(Ks,{className:a});case"doughnut":return e.jsx(Bs,{className:a});case"stackedBar":return e.jsx(Ls,{className:a});case"stackedLine":return e.jsx(Ws,{className:a});case"polarArea":return e.jsx(Hs,{className:a});case"funnel":return e.jsx(Qs,{className:a});case"tornado":case"pyramid":return e.jsx(zs,{className:a});case"range":return e.jsx(Rs,{className:a});case"kpi":return e.jsx(Js,{className:a});case"text":return e.jsx(Qe,{className:a});case"map":return e.jsx(Fs,{className:a});case"custom":return n&&l?e.jsx(l,{className:a}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(He,{className:a});default:return e.jsx(_e,{className:a})}}function gn({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(ul,{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(fn,{onChartTypeChange:()=>n(!1)}),e.jsx(il,{onChartTypeChange:()=>n(!1)})]})]})}const Je="focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0";function yt(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 ml(){var M,F,O,V,_,W;const[t,a]=A.useState(!1),n=s.useEditorStore(Q=>{var U;return(U=Q.card)==null?void 0:U.preferences}),r=s.useEditorStore(Q=>{var U;return(U=Q.card)==null?void 0:U.type}),l=s.getNumberAxis(n,{}),[o,c]=A.useState(yt(n,r)),[i,d]=A.useState(((O=(F=(M=n==null?void 0:n.chartOptions)==null?void 0:M.scales)==null?void 0:F[l])==null?void 0:O.min)||""),[m,u]=A.useState(((W=(_=(V=n==null?void 0:n.chartOptions)==null?void 0:V.scales)==null?void 0:_[l])==null?void 0:W.max)||""),[h,p]=A.useState(i||m?"custom":"auto"),[f,j]=A.useState(""),[x,y]=A.useState(0),[g,C]=A.useState(""),[E,R]=A.useState(""),[S,N]=A.useState(""),b=s.useEditorStore(Q=>Q.actions.setCardPreferences),{updateCardInFrame:T}=s.useEditorActions(),k=s.useEditorStore(Q=>Q.card),L=["pie","doughnut","polarArea","funnel"].includes(r);A.useEffect(()=>{var Q,U,q,Y,$,P,G,H,Z,se,ae,te,le,K;c(yt(n,r)),d(((q=(U=(Q=n==null?void 0:n.chartOptions)==null?void 0:Q.scales)==null?void 0:U[l])==null?void 0:q.min)===0?0:""),u(((P=($=(Y=n==null?void 0:n.chartOptions)==null?void 0:Y.scales)==null?void 0:$[l])==null?void 0:P.max)||""),j(((se=(Z=(H=(G=n==null?void 0:n.chartOptions)==null?void 0:G.scales)==null?void 0:H[l])==null?void 0:Z.ticks)==null?void 0:se.stepSize)||""),y(((ae=n==null?void 0:n.numberAxisFormat)==null?void 0:ae.decimalPlaces)||0),C(((te=n==null?void 0:n.numberAxisFormat)==null?void 0:te.suffix)||""),R(((le=n==null?void 0:n.numberAxisFormat)==null?void 0:le.currency)||""),N(((K=n==null?void 0:n.numberAxisFormat)==null?void 0:K.locale)||"")},[t,n,l,r]);function w(Q,U){return U===""||/^[0-9\b]+$/.test(U)?Number(U):Number(Q)}function B(){const Q=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(U=>U.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:E||"none",onValueChange:U=>R(U==="none"?"":U),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"}),Q.map(U=>e.jsx(s.SelectItem,{value:U,children:U},U))]})})]}),e.jsxs(s.Select,{value:S,onValueChange:U=>N(U),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(U=>e.jsx(s.SelectItem,{value:U.locale,children:U.locale},U.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:U=>y(Number(U.target.value)),id:"format",className:`col-span-6 h-8 w-full tracking-wide ${Je}`})]})]})}function D(){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:Q=>c(Q),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:h,onValueChange:Q=>p(Q),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"})]})]})]}),h==="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:Q=>d(U=>w(U,Q.target.value)),className:`col-span-1 h-8 w-full ${Je}`}),e.jsx(s.Input,{value:m,onChange:Q=>u(U=>w(U,Q.target.value)),id:"max",className:`col-span-1 h-8 w-full ${Je}`})]}),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:Q=>j(U=>w(U,Q.target.value)),id:"step-size",className:`col-span-1 h-8 w-full ${Je}`})]})]})}function v(){var Y;let Q={};h==="custom"&&(Q={min:i,max:m,ticks:{stepSize:f}});const U={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,scales:{...(Y=n==null?void 0:n.chartOptions)==null?void 0:Y.scales,[l]:{type:o,...o==="linear"?Q:{}}}},numberAxisFormat:{decimalPlaces:x,suffix:g,currency:E,locale:S}};console.log(U),b(U);const q={...k,preferences:U};T(q)}return e.jsxs(s.Popover,{onOpenChange:Q=>a(Q),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Format Number",children:e.jsx(la,{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:[B(),D(),e.jsx(s.SelectSeparator,{}),e.jsx("div",{className:"grid grid-cols-3",children:e.jsx(s.Button,{onClick:v,variant:"secondary",className:"col-span-1 col-start-3 h-8 w-full",children:"Apply"})})]})]})})]})}function hl(){const t=s.useEditorStore(i=>{var d,m,u,h;return(h=(u=(m=(d=i.card.preferences)==null?void 0:d.chartOptions)==null?void 0:m.plugins)==null?void 0:u.legend)==null?void 0:h.position}),a=s.useEditorStore(i=>{var d,m,u,h;return(h=(u=(m=(d=i.card.preferences)==null?void 0:d.chartOptions)==null?void 0:m.plugins)==null?void 0:u.legend)==null?void 0:h.align}),n=s.useEditorStore(i=>{var d,m,u,h;return(h=(u=(m=(d=i.card.preferences)==null?void 0:d.chartOptions)==null?void 0:m.plugins)==null?void 0:u.legend)==null?void 0:h.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(ga,{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(Gn,{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(Hn,{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(_n,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Center",onClick:()=>c("center"),children:e.jsx(Vn,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"End",onClick:()=>c("end"),children:e.jsx(Un,{className:"size-4"})})]})]})]})]})]})})]})}function xl(){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(ut,{className:"size-4"}):e.jsx(dt,{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(ut,{className:"size-4"}):e.jsx(dt,{className:"size-4"})})}return e.jsx(e.Fragment,{children:a==="funnel"?l():r()})}function jn(){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(xl,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsxs(e.Fragment,{children:[e.jsx(ml,{}),e.jsx(hl,{})]}),!["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(xa,{className:"size-4"}),r==="x"&&e.jsx(ta,{className:"size-4"}),r==="y"&&e.jsx(Ea,{className:"size-4"}),r==="none"&&e.jsx(La,{className:"size-4"})]})]}):null}function pl(){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 y=j.dataTransfer.getData("tabIndex");if(y===x.toString())return;const g=Array.from(t.cards),[C]=g.splice(parseInt(y),1);g.splice(x,0,C),n({...t,cards:g})};function m(j){const x=t.cards.filter(C=>C.id!==j),y=x[0],g={...t,cards:x,activeCardId:y.id};n(g),r(y.id),l(y)}function u(j,x){const y={...t,cards:[...t.cards,x],activeCardId:j.id};n(y),r(x.id)}function h(){const j={...a,id:s.v4(),title:`${a.title} Copy`,tabTitle:`${a.tabTitle||a.title} Copy`};u(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"};u(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 y=x.displayTab===void 0?!1:!x.displayTab;l({...x,displayTab:y}),o({...x,displayTab:y})},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(oa,{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:y=>c(y,x),onDragOver:i,onDrop:y=>d(y,x),className:"",value:j.id,children:[f(t,j),e.jsx(s.Editable,{enabled:t.activeCardId===j.id,text:j.tabTitle||j.title,onSave:y=>{l({...a,tabTitle:y}),o({...a,tabTitle:y})},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:h,children:e.jsx(aa,{className:"h-4 w-4"})})]})})}function yn(){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:u,isFetching:h}=s.useDashboardCardQuery(a);function p(x){const y=t.cards.find(g=>g.id===x);if(y!=null&&y.sql){r||i(!0),o(x);return}if(y!=null&&y.queryConfig){r&&i(!1),f(x),o(x);return}r||f(x),o(x)}function f(x){const y={...t,cards:t.cards.map(C=>C.id===a.id?a:C),activeCardId:x};l(y);const g=y.cards.find(C=>C.id===x);g.sql&&d(!0),c(g)}function j(){return a.type==="kpi"?u||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border border-border",children:e.jsx(s.KPICard,{card:a,data:m==null?void 0:m.records,isPending:u||h})})}):a.type==="text"?u||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:n,card:a,data:m==null?void 0:m.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(hn,{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(pl,{})]})}function Xe({children:t}){var R,S;s.useEditorStore(N=>N.frame);const a=s.useEditorStore(N=>N.card),n=s.useEditorStore(N=>N.isDevMode),r=s.useEditorStore(N=>N.isShowingVisual),l=s.useDashboardStore(N=>N.isVisualEditing),o=s.useEditorStore(N=>N.pythonStdOut);s.useEditorStore(N=>N.actions.setRunSql);const{setFrame:c,setCard:i,setActiveTabCardId:d,runAssistant:m,setIsDevMode:u,setCardPreferences:h}=s.useEditorActions(),{data:p,isLoading:f,isFetching:j,errorMessage:x,refetch:y}=s.useDashboardCardQuery(a);function g(){const N=JSON.stringify(p==null?void 0:p.records,null,2),b=new Blob([N],{type:"application/json"}),T=URL.createObjectURL(b),k=document.createElement("a");k.href=T,k.download=`${a.title}.json`,k.click()}function C(){const b=[Object.keys(p==null?void 0:p.records.reduce((w,B)=>({...w,...B}),{})).join(","),...((p==null?void 0:p.records)||[]).map(w=>Object.values(w).join(","))].join(`
|
|
429
|
-
`),T=new Blob([b],{type:"text/csv"}),k=URL.createObjectURL(T),L=document.createElement("a");L.href=k,L.download=`${a.title}.csv`,L.click()}function E(){const N=`Can you get the documentation for ${a.type} chart?`;m(N)}return a?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[r&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(gn,{}),l&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:E,children:e.jsx(Jn,{className:"size-4"})}),!["table","custom"].includes(a.type)&&l&&e.jsx(ol,{})]}),!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:C,children:e.jsx(dl,{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:g,children:e.jsx(ca,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(p==null?void 0:p.records,null,2),className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t,e.jsx(jn,{})]}),a.type==="table"&&a.sql&&!s.hasValidCardConfig(a.config)&&e.jsxs("div",{className:"mr-2 flex items-center gap-3",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((S=(R=a.preferences)==null?void 0:R.tablePrefs)==null?void 0:S.enableDevModePagination)??!1,onCheckedChange:N=>{var b;h({...a.preferences,tablePrefs:{...(b=a.preferences)==null?void 0:b.tablePrefs,enableDevModePagination:N}}),y()}}),e.jsx(s.Label,{htmlFor:"pagination",children:"Paginate Results"})]}),n&&e.jsx(gl,{})]}),r?e.jsx(yn,{}):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(fl,{})}),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:[(p==null?void 0:p.records)&&(p==null?void 0:p.records.length)>0&&e.jsx(tl,{data:(p==null?void 0:p.records)||[]}),x&&e.jsx(ln,{error:x})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function fl(){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 gl(){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 jl(){var x,y;const t=s.useEditorStore(g=>g.card.customCardPreferences),{data:a}=xn(),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 u(g,C){if(!t)return;const R={...(t==null?void 0:t.dataInputCardIds)||{},[g]:{cardId:C,hookRef:null}};c({...t,dataInputCardIds:R})}function h(g){var E,R;const C=(E=l==null?void 0:l.cards)==null?void 0:E.filter(S=>{var N;return((N=S==null?void 0:S.customCardPreferences)==null?void 0:N.visualType)!=="multiple"}).map(S=>({value:S.id,label:S.tabTitle||S.title}));return e.jsx("div",{className:"space-y-2",children:(R=g==null?void 0:g.dataInputs)==null?void 0:R.map((S,N)=>{var b,T;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(he,{className:"col-span-6 h-8 w-full justify-between",label:"",options:C||[],value:((T=(b=t==null?void 0:t.dataInputCardIds)==null?void 0:b[N])==null?void 0:T.cardId)||"",onValueChange:k=>u(N,k)})]},N+Math.random())})})}function p(g,C,E=[],R=""){var S,N;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[C])||R,onChange:b=>{c({...t,settings:{...t==null?void 0:t.settings,[C]:b.target.value}})}},C):g==="select"?e.jsx(he,{className:"h-8 w-full",label:"",options:E,value:((N=t==null?void 0:t.settings)==null?void 0:N[C])||R,onValueChange:b=>{c({...t,settings:{...t==null?void 0:t.settings,[C]:b}})}}):null:null}function f(g){const C=Object.entries((g==null?void 0:g.settings)||{});return e.jsx("div",{className:"space-y-3",children:C.map(([E,R])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:R.title}),p(R.ui,E,R.options,R.defaultValue)]},E))})}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(he,{icon:e.jsx(Wn,{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(he,{icon:e.jsx(na,{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})}})})]})})]}),((y=r==null?void 0:r.customCardPreferences)==null?void 0:y.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:h(m)})]}),m&&m.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:f(m)})})]})]})]})}function Be(){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 u;return(u=m.card.preferences)==null?void 0:u.filterOnClickColumnIndex}),A.useEffect(()=>{o&&a(new Array(o.length).fill(!1))},[o]);function c(m,u){var h,p;u?n!=null&&n.onClickFilter&&((h=n==null?void 0:n.onClickFilter)==null?void 0:h.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,u){var p;const h=(p=n==null?void 0:n.onClickFilter)==null?void 0:p.map(f=>f.columnIndex===m?{...f,expression:u.target.value}:f);l({...n,onClickFilter:h})}function d(m){var u,h,p,f;if(t!=null&&t[m]||(h=(u=n==null?void 0:n.onClickFilter)==null?void 0:u.find(j=>j.columnIndex===m))!=null&&h.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,u)=>{var h,p;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((h=n==null?void 0:n.onClickFilter)!=null&&h.find(f=>f.columnIndex===u)),onCheckedChange:f=>c(u,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===u))&&e.jsx(s.Pencil,{onClick:()=>{a(f=>{const j=[...f];return j[u]=!f[u],j})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(u)]})},m)})]})}function yl({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 u={display:d!=="none",align:d,anchor:d,clamp:!0};if(!o)r({...a,datasetOptions:[...n||[],{idx:m,datalabels:u}]});else{const h={...o};h.datalabels=u;const p=n==null?void 0:n.map(f=>f.idx===m?h:f);r({...a,datasetOptions:p})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(Bt,{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(ja,{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(ba,{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(ya,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function bl(){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 Xs({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 bn(){const t=s.useEditorStore(d=>d.card),a=s.useEditorStore(d=>{var m,u,h;return(h=(u=(m=d==null?void 0:d.card)==null?void 0:m.preferences)==null?void 0:u.chartOptions)==null?void 0:h.indexAxis}),{data:n}=s.useDashboardCardQuery(t),r=a==="y"?"Metric":"Dimension",l=a==="y"?"Dimension":"Metric",{dimensionKeys:o,transformedMetricKeys:c,keys:i}=bl();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:vn(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(Nn,{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 vn(t,a=30){return t.length>a?t.slice(0,a)+"...":t}function Nn({col:t,idx:a,className:n,iconClassName:r,children:l}){const o=s.useEditorStore(u=>{var h;return(h=u.card)==null?void 0:h.preferences}),c=s.useEditorStore(u=>{var h,p;return(p=(h=u.card)==null?void 0:h.preferences)==null?void 0:p.datasetOptions}),i=c==null?void 0:c.find(u=>u.idx===a),{setCardPreferences:d}=s.useEditorStore(u=>u.actions);function m(u){if(!i)d({...o,datasetOptions:[...c||[],{idx:a,type:u==="area"?"line":u,fill:u==="area"?"origin":""}]});else{const h={...i};h.type=u==="area"?"line":u,h.fill=u==="area"?"origin":"";const p=c==null?void 0:c.map(f=>f.idx===a?h: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(Xs,{className:"max-w-[100px]",title:t,children:vn(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ds,{onClick:()=>m("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(us,{onClick:()=>m("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(It,{onClick:()=>m("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(yl,{idx:a})]})]})}function Cn(){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:u,connectionType:h}=s.useEditorAside();function p(f,j="dashboard"){var b;const x=s.fmt(f.column_name),y=s.fmt(n||""),g=s.fmt(r||""),C=s.fmt(u);let E=s.getQualifiedTableName({schemaName:g,tableName:C,connectionType:h,databaseName:y}),R=`${E}.${x}`;const S=(b=m==null?void 0:m.find(T=>T.id===a))==null?void 0:b.name;a&&a!=="none"&&(R=`${s.DATAMODEL_NAMESPCACE}.${S}.${x}`,E=`${s.DATAMODEL_NAMESPCACE}.${S}`);const N=o==null?void 0:o.find(T=>T.column===R&&T.table===C&&(T.database===y||T.database===n));if(N)d(N.id),i(N.id);else{const T=s.v4();return u==="api"&&t?(c({location:j,id:T,column:R,title:f.column_name,dataType:f.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(f.data_type,E,x)}),T):(c({id:T,location:j,column:R,title:f.column_name,dataType:f.data_type,table:l||"",database:n||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(f.data_type,E,x)}),T)}}return{assignFilter:p}}function $e(){const t=s.useDashboardStore(i=>i.dashboard.filters),a=s.useEditorStore(i=>i.frame),{setFrame:n}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=Cn();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(vl,{onSelect:o,columns:r}),c&&e.jsx(s.FilterHeader,{filter:c})]})}function vl({columns:t,onSelect:a}){var c;const[n,r]=ue.useState(!1),[l,o]=ue.useState("");return e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[l?(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 Nl({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(bn,{})})]}),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(Be,{}),e.jsx($e,{})]})]})]})})}function ps(){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 u;const d={datalabels:{display:i!=="none",align:i,anchor:i,clamp:!0}},m={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(u=n==null?void 0:n.chartOptions)==null?void 0:u.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 Cl({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(ps,{})})]}),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(Be,{}),e.jsx($e,{})]})]})]})})}const Sl={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},wl={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function Dl(){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:kl(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(ps,{}),e.jsx(Be,{}),e.jsx($e,{})]})]})}function kl(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(Sl,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(wl,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 El(){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 Cs({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 Tl=[{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"}],Il=["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"],Al=Il.map(t=>({label:t,value:t}));function Ml(){var d,m,u,h,p,f,j,x,y,g,C,E,R,S,N,b,T,k;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]=A.useState(((h=(u=t==null?void 0:t.preferences)==null?void 0:u.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:o}=s.useTopoJson(t),c=Object.keys((o==null?void 0:o.objects)||{}).map(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(Cs,{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(Cs,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(he,{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(he,{className:"h-9",options:c,value:((f=(p=t.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:f.objectKey)||"",label:"Map Object",onValueChange:L=>{var w;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,objectKey:L}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(he,{className:"h-9",options:Tl,value:((x=(j=t.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:x.projection)||"",label:"Projection",onValueChange:L=>{var w;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,projection:L}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(he,{className:"h-9",options:Al,value:((g=(y=t.preferences)==null?void 0:y.mapVisualOptions)==null?void 0:g.colorScale)||"",label:"Select Color Scale",onValueChange:L=>{var w;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,colorScale:L}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Cs,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:.1,value:((E=(C=t.preferences)==null?void 0:C.mapVisualOptions)==null?void 0:E.projectionScale)||1,onChange:L=>{var w;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.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:((N=(S=(R=t.preferences)==null?void 0:R.mapVisualOptions)==null?void 0:S.projectionOffset)==null?void 0:N[0])||0,onChange:L=>{var w,B,D,I;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,projectionOffset:[Number(L.target.value),((I=(D=(B=t.preferences)==null?void 0:B.mapVisualOptions)==null?void 0:D.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:((k=(T=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:T.projectionOffset)==null?void 0:k[1])||0,onChange:L=>{var w,B,D,I;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,projectionOffset:[((I=(D=(B=t.preferences)==null?void 0:B.mapVisualOptions)==null?void 0:D.projectionOffset)==null?void 0:I[0])||0,Number(L.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Be,{})]})}function Ll(){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 Ze({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(ps,{}),t==="text"&&e.jsx(Ll,{})]})]}),!["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(Be,{}),e.jsx($e,{})]})]})]})})}function Rl(){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(he,{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(bn,{})]})]}),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(Be,{}),e.jsx($e,{})]})]})]})})}function Ol({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(Be,{}),e.jsx($e,{})]})]})}),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 Bl=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."]})]}),Fl=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."]})]}),Pl=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 zl(){const t=s.useEditorStore(n=>n.card.type);function a(n){switch(n){case"stackedBar":case"stackedLine":return e.jsx(Rl,{});case"tornado":case"pyramid":return e.jsx(Ze,{docContent:Bl,cardType:n});case"kpi":return e.jsx(El,{});case"line":case"bar":return e.jsx(Nl,{cardType:n});case"range":return e.jsx(Ze,{docContent:Fl,cardType:n});case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return e.jsx(Ze,{cardType:n});case"bubble":case"scatter":return e.jsx(Cl,{cardType:n});case"table":return e.jsx(Ol,{cardType:n});case"text":return e.jsx(Ze,{docContent:Pl,cardType:n,suffix:"Visual"});case"map":return e.jsx(Ml,{});case"custom":return e.jsx(jl,{});default:return e.jsx(Dl,{})}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[a(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Sn({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(he,{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 Vl=[{label:"Sum",value:"SUM",logo:e.jsx(Ot,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(Ge,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(ua,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(Yn,{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 _l({column:t}){const{updateMetricColumnOld:a}=s.useEditorActions();let n=Vl;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:We(t.name,l)};a(t.id,o)}return e.jsx(Sn,{column:t,functions:n,onFunctionChange:l=>r(l),label:"Aggregation"})}const Ul=[{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 $l({column:t}){const{updateGroupByColumnOld:a}=s.useEditorActions();function n(r){const l={...t,granularity:r,label:Ue(t.name,r)};a(t.id,l)}return e.jsx(Sn,{column:t,functions:Ul,onFunctionChange:r=>n(r),label:"Granularity"})}function ql({col:t,onChange:a,droppableId:n}){const{columns:r}=s.useDataColumns(),l=A.useMemo(()=>{let i=[];(n===Ae||n===Me||n===Le)&&(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 u;return m.column_name===((u=i[0])==null?void 0:u.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 wn({column:t}){const a=s.useEditorStore(d=>d.card.type),n=s.useEditorStore(d=>{var m,u;return(u=(m=d.card)==null?void 0:m.config)==null?void 0:u.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(Nn,{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(ps,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&c(),["pie","doughnut"].includes(a)&&i()]})}function Yl({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:u,setNodeRef:h,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,y=s.isTextDataType(t.type);function g(N){const b=s.isNumberDataType(N.data_type),T=s.isTextDataType(N.data_type),k=s.isDateDataType(N.data_type),L=b?"number":T?"string":k?"date":"string";if(r===Ae){if(T){const w={id:t.id,name:N.column_name,type:L,role:"groupby"};c(t.id,w)}if(k){const w={id:t.id,name:N.column_name,type:L,role:"groupby",label:Ue(N.column_name,"month"),granularity:"month"};c(t.id,w)}}if(r===Le){if(T){const w={id:t.id,name:N.column_name,type:L,role:"groupby"};d(t.id,w)}if(k){const w={id:t.id,name:N.column_name,type:L,label:Ue(N.column_name,"month"),granularity:"month",role:"groupby"};d(t.id,w)}}if(r===Me){const w={id:t.id,name:N.column_name,type:L,role:"metric",label:We(N.column_name,"SUM"),aggregate:b?"SUM":"COUNT"};i(t.id,w)}}function C(){if(r===Me)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(wn,{column:t})})}function E(){const N=s.isDateDataType(t.type);if(r===Me)return e.jsx(_l,{column:t});if((r===Ae||r===Le)&&N)return e.jsx($l,{column:t})}function R(){return e.jsx("div",{className:s.cn("grow",{"pl-3":(r===Ae||r===Le)&&y}),children:e.jsx(ql,{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(Aa,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(Mt,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...u,...m,ref:h,style:x,children:e.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex h-8 grow items-center justify-between rounded-md bg-muted",children:[S(),E(),R()]}),l&&C()]}),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 Ss({id:t,label:a,columns:n,previewColumns:r,sortableType:l,onRemoveColumn:o}){var x,y;const{setNodeRef:c,isOver:i,over:d}=s.useDroppable({id:t}),m=s.useDndStore(g=>g.activeId),u=s.useEditorStore(g=>{var C;return(C=g.card)==null?void 0:C.type}),h=i||((y=(x=d==null?void 0:d.data)==null?void 0:x.current)==null?void 0:y.type)===l,p=m?r:n,f=l===ls?"Rows":l===os?"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",h&&"border border-muted-foreground/20"),ref:c,children:[e.jsxs("div",{className:"flex items-center justify-between pr-5",children:[e.jsx(s.Label,{className:"text-sm",children:a}),u!=="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===an.id?e.jsx(Gl,{},g.id):e.jsx(Yl,{droppableId:t,type:l,column:g,onRemoveColumn:o},g.id))})]})})}function Gl(){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 Dn({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 Hl(){const t=s.useEditorStore(g=>{var C;return(C=g.card.queryConfig)==null?void 0:C.orderBy})||[],a=s.useEditorStore(g=>{var C;return(C=g.card.queryConfig)==null?void 0:C.groupByColumns})||[],n=s.useEditorStore(g=>{var C;return(C=g.card.queryConfig)==null?void 0:C.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(Qn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx(qn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=e.jsx(Kn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=e.jsx($n,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=c==null?void 0:c.filter(g=>!t.some(C=>C.columnId===g.id)).map(g=>({id:g.id,value:g.label||g.name}));function p(g,C){const E=f(g);return E?E.role==="metric"?C==="asc"?m:u:C==="asc"?i:d:null}function f(g){return c.find(C=>C.id===g)}function j(g){const C=t.find(E=>E.columnId===g);if(C){const E={...C,direction:C.direction==="asc"?"desc":"asc"};o(E)}}const x=g=>{r({columnId:g.id,direction:"asc"})};function y(g){const C=t.find(E=>E.columnId===g);C&&l(C)}return e.jsx(s.SortableContext,{items:t.map(g=>Ye(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"}),h.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(s.ComboBox2,{multiple:!1,options:h,selectedOptions:[],onChange:g=>x(g[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),t.map(g=>{var C,E;return e.jsx(Dn,{id:Ye(g.columnId),type:qs,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(Mt,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(Xs,{className:"w-[175px] text-sm",children:((C=f(g.columnId))==null?void 0:C.label)||((E=f(g.columnId))==null?void 0:E.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:()=>y(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)},Ye(g.columnId))})]})})}function Kl(){const t=s.useEditorStore(y=>{var g;return((g=y.card.queryConfig)==null?void 0:g.groupByColumns)||[]}),a=s.useEditorStore(y=>y.card.type),n=s.useDndStore(y=>y.previewGroupByColumns),r=s.useEditorStore(y=>{var g;return((g=y.card.queryConfig)==null?void 0:g.metricColumns)||[]}),l=s.useDndStore(y=>y.previewMetricColumns),o=s.useEditorStore(y=>{var g;return((g=y.card.queryConfig)==null?void 0:g.pivotColumns)||[]}),c=s.useDndStore(y=>y.previewPivotColumns),{removeColumnFromGroupBy:i,removeColumnFromMetricColumns:d,removeColumnFromPivotBy:m}=s.useEditorActions();function u(y){i(y)}function h(y){d(y)}function p(y){m(y)}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(fn,{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(Ss,{onRemoveColumn:u,sortableType:ls,id:Ae,label:f,columns:t,previewColumns:n}),e.jsx(Ss,{onRemoveColumn:p,sortableType:os,id:Le,label:x,columns:o,previewColumns:c}),e.jsx(Ss,{onRemoveColumn:h,sortableType:Es,id:Me,label:j,columns:r,previewColumns:l}),e.jsx(Hl,{})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Zs({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(h=>{var p,f;return(f=(p=h.card.queryConfig)==null?void 0:p.filters)==null?void 0:f.some(j=>j.filterColumnName===a.name)});function u(h){i(h)}return e.jsx(Dn,{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:()=>u(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 Ql({column:t,sortableType:a}){const n=s.useDashboardStore(E=>E.themeStyle),r=s.useEditorStore(E=>{var R,S;return(S=(R=E.card)==null?void 0:R.queryConfig)==null?void 0:S.filters}),l=s.useEditorStore(E=>{var R,S;return(S=(R=E.card.queryConfig)==null?void 0:R.filterColumns)==null?void 0:S.find(N=>N.name===t.name)}),{selectedConnectionId:o,selectedDatabaseName:c,selectedTableName:i}=s.useEditorAside(),d=A.useMemo(()=>{var E;return(E=r==null?void 0:r.find(R=>R.filterColumnName===t.name))==null?void 0:E.filterValue},[r,t.name]),m=A.useMemo(()=>Array.isArray(d)?d.map(E=>({id:E,value:E})):[],[d]),{updateEditorFilterValue:u}=s.useEditorActions(),h={column:t.name,sql:t.sql,id:t.name,connectionId:o,dataType:t.type},{data:p,isLoading:f,isFetching:j,isError:x}=s.useFilterQuery(h),y=A.useMemo(()=>{var R;return h.column?(R=p==null?void 0:p.records)==null?void 0:R.map(S=>{let N=h.column.split(".").slice(-1)[0].replace(/"/g,"");return S[N]===void 0&&(N=N.toLowerCase()),{id:S[N],value:S[N]}}):[]},[p,h.column]);function g(E){const R=E.map(S=>S.id);u(t.name,R)}function C(){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(Wl,{columnName:t.name}),showNegativeIndicator:(l==null?void 0:l.mode)==="exclude",options:y,onChange:g,selectedOptions:m,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(Zs,{className:"w-60",id:t.id,sortableType:a,column:t,children:C()})}function Wl({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 Jl({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:u,data:h}=s.useFilterQuery(i),p=h==null?void 0:h.records,{dateRange:f,setDateRange:j,initialDateRange:x}=s.useDateRangeFromRecords(p),{updateEditorFilterValue:y}=s.useEditorActions();function g(R){var N,b;const S={gte:(N=R==null?void 0:R.from)==null?void 0:N.toISOString(),lte:(b=R==null?void 0:R.to)==null?void 0:b.toISOString()};y(t.name,S)}function C(){y(t.name,null,!0),j(x)}function E(){return d||m?e.jsx("div",{children:e.jsx(s.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):u?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:C}):e.jsx(s.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(Zs,{className:"w-72",id:t.id,sortableType:a,column:t,children:E()})}function Xl({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(y=>y.activeId),m={},u=c||((x=(j=i==null?void 0:i.data)==null?void 0:j.current)==null?void 0:x.type)===l;function h(){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(y){const g=s.isDateDataType(y.type);return y.id===an.id?e.jsx(Zs,{id:y.id,sortableType:l,column:y,children:e.jsx(Zl,{})},y.id):g?e.jsx(Jl,{droppableId:t,sortableType:l,column:y},y.id):e.jsx(Ql,{droppableId:t,sortableType:l,column:y},y.id)}const f=d?r:n;return e.jsx(s.SortableContext,{items:n==null?void 0:n.map(y=>y.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",u&&"border border-muted-foreground/20"),ref:o,style:m,children:[e.jsx(s.Label,{className:"text-sm",children:a}),h(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:f==null?void 0:f.map(y=>p(y))})]})})}function Zl(){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 eo(){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(Xl,{onRemoveColumn:r,sortableType:Is,id:Ts,label:"Filters",columns:t,previewColumns:a})})}function so(){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(hs,{}),!a&&e.jsxs(s.Button,{onClick:()=>n(!0),variant:"secondary",size:"sm",children:[e.jsx(Sa,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(cn,{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(Gs,{}),e.jsx(Ys,{variant:"default"})]})]})}function to(){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,u;r?((i=t.current)==null||i.resize(0),(d=a.current)==null||d.resize(0)):((m=t.current)==null||m.resize(25),(u=a.current)==null||u.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(sl,{})}),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(zl,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(Xe,{})})]}):e.jsx(Xe,{})})]})}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(Kl,{})})}),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(so,{}),e.jsx(eo,{})]}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(Xe,{})})]})})]}):e.jsx(Xe,{})})})}return e.jsx(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:l?o():c()})}function no(t){const a=s.useAIInteractionStore(z=>z.currentAIContext),[n,r]=A.useState(""),[l,o]=A.useState(null),{authToken:c}=s.useSemaphorContext(),i=s.useEditorStore(z=>{var X;return(X=z==null?void 0:z.card)==null?void 0:X.sql}),d=s.useEditorStore(z=>z.isDevMode),m=s.useEditorStore(z=>{var X;return(X=z==null?void 0:z.card)==null?void 0:X.python}),{setCardPython:u,setCardSql:h,setRunSql:p,switchCardType:f,setQueryConfig:j}=s.useEditorActions(),x=s.useEditorStore(z=>z.currentAssitantScope)||[],y=s.useEditorStore(z=>z.userInputForAI),g=s.useEditorStore(z=>z.triggerAIRun),C=s.useEditorStore(z=>z.card),E=s.useEditorStore(z=>z.selectedDatabaseName),R=s.useEditorStore(z=>z.selectedTableName),S=s.useEditorStore(z=>z.selectedConnectionId),N=s.useEditorStore(z=>z.selectedSchemaName),b=s.useDashboardStore(z=>z.dashboard.aiScopeTables),{errorMessage:T,refetch:k,data:L}=s.useDashboardCardQuery(C),{setTriggerAIRun:w,setCurrentAssitantScope:B,setCardConfig:D}=s.useEditorActions(),{selectedDatamodelName:I,connectionType:v,selectedDatamodelId:M}=s.useEditorAside(),{messages:F,setMessages:O,reload:V,error:_,append:W,input:Q,setInput:U,status:q,handleInputChange:Y,handleSubmit:$,stop:P}=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:z=>{console.log("on error",z)},onToolCall:G,onFinish(z,X){H(X.usage),r(""),X.finishReason==="stop"&&r("")}});A.useEffect(()=>{g&&y&&(W({role:"user",content:y}),w(!1))},[g,y,W,w]);async function G({toolCall:z}){var X,oe,Ce,Te;if(["createChartFromSql","createForecast"].includes(z.toolName)){const ne=z.args.sql,ie=z.args.python,ce=z.args.chartType;return f(ce),h(ne),u(ie),p(!0),{status:"success",message:"Let the user know that chart is created"}}else if(z.toolName==="getTableColumns")r("Getting table columns...");else{if(z.toolName==="getUserSql")return i?{status:"success",sql:i,python:m||""}:{status:"error",message:"No SQL found"};if(z.toolName==="getCurrentTableScope")return r("Getting table scope..."),te(),{status:"success",tables:x};if(z.toolName==="generateQueryConfig"){r("Generating query config...");const ne=z.args.chartType,ie=z.args.queryConfig;z.args.cardConfig,f(ne),D(ie),h(void 0),u(void 0);const ce=await k();return(X=ce==null?void 0:ce.data)!=null&&X.error?{status:"error",queryConfig:ie,message:(oe=ce==null?void 0:ce.data)==null?void 0:oe.error.message}:(Ce=ce==null?void 0:ce.data)!=null&&Ce.records?{status:"success",queryConfig:ie,message:"The data has been visualized"}:{status:"success",queryConfig:ie,message:"The data has been visualized",records:(Te=ce==null?void 0:ce.data)==null?void 0:Te.records}}else r("Analyzing...")}}function H(z){o(X=>X?{promptTokens:X.promptTokens+z.promptTokens,completionTokens:X.completionTokens+z.completionTokens,totalTokens:X.totalTokens+z.totalTokens}:z)}function Z(z){const X=s.removeFromScopeArray(x,z);se(X)}function se(z){const X=s.sanitizeAIScope(z);B(X),O(oe=>[...oe,{id:crypto.randomUUID(),role:"system",content:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(X)}`}])}function ae(){const z={databaseName:E||"",schemaName:N||"",tableName:R||"",datamodelId:M||"",datamodelName:s.resolveDatamodelName(I),connectionId:S||"",connectionType:v||""},X=s.dedup([...x,z]);se(X)}function te(){const z={databaseName:E||"",schemaName:N||"",tableName:R||"",datamodelName:s.resolveDatamodelName(I),connectionId:S||"",connectionType:v||"",datamodelId:M||""};if(!s.isInAiScopeArray([...b||[],...x],z)||x.length===0){const oe=s.dedup([...b||[],...x,z]).filter(Ce=>Ce.connectionId===z.connectionId);se(oe)}}const le=!["ready","error"].includes(q),K=s.getErrorMessage(_);return{messages:F,setMessages:O,reload:V,append:W,input:Q,setInput:U,isLoading:le,handleSetAIScope:te,handleAddCurrentTableToScope:ae,removeFromCurrentSelections:Z,currentAssitantScope:x,setCurrentAssitantScope:B,handleInputChange:Y,handleSubmit:$,stop:P,chatStatus:q,toolStatus:n,llmUsage:l,onFinish:t,errorMessage:K}}const ao=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function bt(){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),u=s.useCurrentAIContext(),{setCurrentAIContext:h}=s.useAIActions(),p=s.useDashboardStore(P=>P.dashboard.aiContext),f=s.useEditorStore(P=>P.card.dataSource),j=s.useEditorStore(P=>P.actions.setCardSql),x=s.useEditorStore(P=>P.actions.setRunSql),y=s.useEditorStore(P=>P.showAIDialog),g=s.useDashboardStore(P=>P.handleOpenAssistantProfile),{setShowAIDialog:C,setCardPython:E}=s.useEditorActions(),{setDataSource:R}=s.useEditorActions(),{assistantProfile:S}=s.useAssistantProfile(),{messages:N,setMessages:b,reload:T,append:k,input:L,setInput:w,isLoading:B,handleInputChange:D,handleSubmit:I,stop:v,chatStatus:M,llmUsage:F,errorMessage:O}=no();s.useAssistantScroll({scrollContainerRef:t,inputRef:a,messages:N}),A.useEffect(()=>{var P;y&&((P=a.current)==null||P.focus(),h({selectedEntities:(f==null?void 0:f.selectedEntities)||[]}))},[y,f,h]);function V(P,G){G==="sql"?(j(P),x(!0)):G==="python"&&(E(P),x(!0))}function _(){var P;(P=p==null?void 0:p.selectedEntities)==null||P[0],m(!0)}function W(){u.selectedEntities.length===0&&h({selectedEntities:(p==null?void 0:p.selectedEntities)||[]})}function Q(P){W();const G={role:"user",content:P.title+" "+P.subtitle};k(G)}function U(P){W(),k({role:"user",content:P})}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 Y(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const $=(L==null?void 0:L.length)===0&&(N==null?void 0:N.filter(P=>P.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:[Y(),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:_,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([]),T()},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:()=>{C(!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:N,showTools:l,handleRun:V,showSystemMessage:c}),e.jsx(s.ChatStatus,{messages:N,chatStatus:M,errorMessage:O})]})}),e.jsxs("div",{className:"mb-3",children:[$&&!S&&e.jsx(s.Placeholders,{onClick:Q,placeholders:ao}),e.jsx("div",{children:$&&S&&e.jsx(s.SeedQuestions,{seedQuestions:S.seedQuestions||[],handleSeedQuestionClick:U})})]}),e.jsx(s.ChatInputWithContext,{ref:a,setInput:w,stop:v,input:L,handleInputChange:D,handleSubmit:P=>{W(),I(P)},isLoading:B,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 kn(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 ro(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(!kn(r,t.qualifiedEntityName,n))return{isValid:!1,showError:!0}}else return{isValid:!1,showError:!0};return{isValid:!0}}function As(){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 Ms(t,a){return a.some(n=>n.name===t.name&&n.qualifiedEntityName===t.qualifiedEntityName)}const et=t=>{var w;const{updateCardConfig:a,updateGroupByColumn:n,updateMetricColumn:r,updatePivotByColumn:l,updateSortByColumn:o,removeGroupByColumn:c,removeMetricColumn:i,removePivotByColumn:d,removeSortByColumn:m}=s.useEditorActions(),u=s.useEditorStore(B=>B.card.type),h=t==null?void 0:t.id,p=A.useCallback(B=>{if(!(t!=null&&t.config))return[];switch(B){case"groupBy":return(t.config.groupByColumns||[]).map(D=>({id:D.id,name:D.name,dataType:D.dataType,label:D.label!==void 0?D.label:D.name,qualifiedEntityName:D.qualifiedEntityName,entityId:D.entityId,entityName:D.entityName,entityType:D.entityType,dateFormat:D.dateFormat,customFormat:D.customFormat,granularity:D.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(D=>({id:D.id,name:D.name,dataType:D.dataType,label:D.label!==void 0?D.label:D.name,qualifiedEntityName:D.qualifiedEntityName,entityId:D.entityId,entityName:D.entityName,entityType:D.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(D=>({id:D.id,name:D.name,dataType:D.dataType,label:D.label!==void 0?D.label:D.name,qualifiedEntityName:D.qualifiedEntityName,entityId:D.entityId,entityName:D.entityName,entityType:D.entityType,direction:D.direction}));case"source":return[];default:return[]}},[t]),f=A.useCallback((B,D)=>{if(h)switch(B){case"groupBy":{a(h,{groupByColumns:D});break}case"metrics":{a(h,{metricColumns:D});break}case"pivotBy":{a(h,{pivotByColumns:D});break}case"sortBy":{a(h,{sortByColumns:D});break}}},[h,a]),j=A.useCallback((B,D,I)=>{if(!h)return;const M=p(B)[D];if(M)switch(B){case"groupBy":n(h,M.id,{label:I});break;case"metrics":r(h,M.id,{label:I});break;case"pivotBy":l(h,M.id,{label:I});break;case"sortBy":o(h,M.id,{label:I});break}},[h,p,n,r,l,o]),x=A.useCallback((B,D)=>{if(!h)return;const v=p("metrics")[B];v&&r(h,v.id,{aggregate:D,label:s.getAggregationLabel(v.name,D)})},[h,p,r]),y=A.useCallback((B,D,I)=>{if(!h)return;const M=p("groupBy")[B];if(!M)return;const F={dateFormat:D};D==="custom"&&I?F.customFormat=I:F.customFormat=void 0,n(h,M.id,F)},[h,p,n]),g=A.useCallback((B,D)=>{if(!h)return;const v=p("groupBy")[B];v&&n(h,v.id,{granularity:D})},[h,p,n]),C=A.useCallback((B,D)=>{if(!h)return;const v=p("metrics")[B];v&&r(h,v.id,{aliasTemplate:D})},[h,p,r]),E=A.useCallback((B,D)=>{if(console.log("handleValueAliasesChange",B,D),!h)return;console.log("handleValueAliasesChange",B,D);const v=p("metrics")[B];v&&(console.log("handleValueAliasesChange",D),r(h,v.id,{valueAliases:D}))},[h,p,r]),R=A.useCallback(B=>{h&&a(h,{comparisonType:B})},[h,a]),S=A.useCallback(B=>{h&&a(h,{showTrendline:B})},[h,a]),N=A.useCallback(B=>{h&&a(h,{trendlineWindow:B})},[h,a]),b=A.useCallback(B=>{h&&a(h,{trendlineGranularity:B})},[h,a]),T=A.useCallback(B=>{h&&a(h,{targetValue:B})},[h,a]),k=A.useCallback(B=>{var V;if(!h)return;const D=[...p("groupBy"),...p("pivotBy"),...p("metrics"),...p("sortBy")],I=(V=t==null?void 0:t.config)==null?void 0:V.joinPlan,v=ro(B,D,I);if(!v.isValid){v.showError&&As();return}const M=s.getSmartContainerForField(B),F=p(M);if(Ms(B,F))return;const O=s.getNewField(B,M);O&&f(M,[...F,O])},[h,(w=t==null?void 0:t.config)==null?void 0:w.joinPlan,p,f]),L=A.useCallback((B,D)=>{if(!h)return;const v=p(B)[D];if(v){if(B!=="sortBy"){const M=p("sortBy"),F=M.filter(O=>!(O.name===v.name&&O.qualifiedEntityName===v.qualifiedEntityName));F.length!==M.length&&a(h,{sortByColumns:F})}switch(B){case"groupBy":c(h,v.id);break;case"metrics":i(h,v.id);break;case"pivotBy":d(h,v.id);break;case"sortBy":m(h,v.id);break}}},[h,p,c,i,d,m,a]);return{getFieldsForContainer:p,setFieldsForContainer:f,updateLabel:j,handleAggregationChange:x,handleDateFormatChange:y,handleGranularityChange:g,handleAliasTemplateChange:C,handleValueAliasesChange:E,removeField:L,handleFieldClick:k,handleKpiComparisonTypeChange:R,handleKpiShowTrendlineChange:S,handleKpiTrendlineWindowChange:N,handleKpiTrendlineGranularityChange:b,handleKpiTargetValueChange:T,cardType:u}};function lo({field:t}){return e.jsxs("div",{className:"w-64 bg-background p-0",children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"text-sm font-medium text-foreground",children:t.label||t.name}),e.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:t.dataType})]}),t.description&&e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:t.description}),e.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:t.name})})]})}function oo({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(j=>j.card),{handleFieldClick:u}=et(m),h={transform:s.CSS.Transform.toString(l),transition:o};s.getDataType(t.dataType);const p=j=>{const x=(j||"").toLowerCase();switch(s.getDataType(x)){case"number":return Ge;case"date":return s.Calendar;case"boolean":return ns;case"json":return it;case"geo":return ct;default:return Qe}},f=j=>{const x=(j||"").toLowerCase(),y=s.getDataType(x);return y==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(Qe,{className:"h-3 w-3"})}):y==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Ge,{className:"h-3 w-3"})}):y==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):y==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(ns,{className:"h-3 w-3"})}):y==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(it,{className:"h-3 w-3"})}):y==="geo"?e.jsx("div",{className:"bg-orange -100 flex size-6 shrink-0 items-center justify-center rounded-sm text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(ct,{className:"h-3 w-3"})}):y==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Tt,{className:"h-3 w-3"})}):null};return p(t.dataType),e.jsxs("div",{ref:r,style:h,...a,...n,className:`group/container overflow-hidden rounded-lg transition-all ${c?"scale-95 opacity-50":"border border-transparent hover:bg-muted"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:()=>u(t),children:[f(t.dataType),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/80 hover:text-foreground dark:text-muted-foreground ${i?"whitespace-normal break-words":"truncate"}`,children:t.label||t.name})})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:e.jsx(lo,{field:t})})]})})]}),i&&e.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:e.jsx(s.Card,{className:"",children:e.jsxs(s.CardContent,{className:"space-y-2 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bt,{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(Ra,{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 io(){const[t,a]=A.useState(""),[n,r]=A.useState("all"),l=s.useEditorStore(E=>E.card.dataSource),{columns:o=[],columnGroups:c=[],isLoading:i,error:d}=s.useColumns(),m=o.filter(E=>E.name.toLowerCase().includes(t.toLowerCase())||E.dataType.toLowerCase().includes(t.toLowerCase())||E.qualifiedEntityName&&E.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),u=E=>{if(E.dataType==="number"||E.dataType==="integer"||E.dataType==="float"||E.dataType==="decimal"||E.dataType==="currency")return"metrics";const R=s.getDataType(E.dataType);return["date","string","boolean"].includes(R)?"dimensions":R==="number"?"metrics":"dimensions"},p=(n==="all"?m:m.filter(E=>u(E)===n)).reduce((E,R)=>{const S=R.qualifiedEntityName||"Other Fields";return E[S]||(E[S]={label:s.toLabel(R.entityName),fields:[]}),E[S].fields.push(R),E},{}),j=Object.keys(p),x=m.filter(E=>u(E)==="dimensions").length,y=m.filter(E=>u(E)==="metrics").length,g=m.filter(E=>u(E)==="calculated").length,C=m.length>0;return i?e.jsx("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):d?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:d.message||"Failed to load column data"})]}):!l||!l.selectedEntities||l.selectedEntities.length===0?e.jsx(s.ScrollArea,{className:"h-[calc(100vh-200px)] w-[290px]",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-[calc(100vh-200px)] w-full grow flex-col gap-2 px-6 pb-6",children:[e.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[o.length>0&&e.jsxs("div",{className:"relative mb-4",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:t,onChange:E=>a(E.target.value)})]}),C&&e.jsx(s.Tabs,{defaultValue:"all",value:n,onValueChange:E=>r(E),className:"mb-4",children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-4",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children: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:y})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(Tt,{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(([E,R])=>{const S=c.find(N=>N.entityName===E)||{entityName:E,label:R.label};return e.jsxs(s.AccordionItem,{value:E,className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:e.jsxs("div",{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:R.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:R.fields.map(N=>e.jsx(oo,{field:N},N.id))})})]},E)})}),Object.keys(p).length===0&&o.length===0&&e.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[e.jsx("p",{children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]}),Object.keys(p).length===0&&o.length>0&&e.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),e.jsx(s.ScrollBar,{orientation:"horizontal"}),e.jsx(s.ScrollBar,{orientation:"vertical"})]})]})}function co(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(io,{})," "]})}function uo({initialJoinPlan:t,availableDataSources:a}){const[n,r]=A.useState(t),[l,o]=A.useState(new Set),c=()=>{const N=n.joins.length>0?Math.max(...n.joins.map(T=>T.sequence))+1:1,b={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:N,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...n,joins:[...n.joins,b]}),o(new Set([...l,b.id]))},i=N=>{r({...n,joins:n.joins.filter(b=>b.id!==N)}),o(new Set([...l].filter(b=>b!==N)))},d=(N,b)=>{var w,B;const T=n.joins.find(D=>D.id===N);if(!T)return;const k={...T,...b},L=n.joins.map(D=>D.id===N?k:D);if((w=k.source)!=null&&w.name&&((B=k.target)!=null&&B.name)&&k.joinKeyGroups[0].keys.length===0){const D=a.find(F=>{var O;return F.name===((O=k.source)==null?void 0:O.name)}),I=a.find(F=>{var O;return F.name===((O=k.target)==null?void 0:O.name)}),v={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(D==null?void 0:D.name)||"",entityName:(D==null?void 0:D.name)||"",entityType:(D==null?void 0:D.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(I==null?void 0:I.name)||"",entityName:(I==null?void 0:I.name)||"",entityType:(I==null?void 0:I.type)||"table"},operator:"="},M=[...k.joinKeyGroups];M[0]={...M[0],keys:[v]},k.joinKeyGroups=M,L[L.findIndex(F=>F.id===N)]=k}r({...n,joins:L})};return{joinPlan:n,expandedJoins:l,setJoinPlan:r,addJoin:c,removeJoin:i,updateJoin:d,moveJoinUp:N=>{const b=n.joins.findIndex(T=>T.id===N);if(b>0){const T=[...n.joins],k={...T[b]},L={...T[b-1]};T[b]=L,T[b-1]=k,T.forEach((B,D)=>{B.sequence=D+1});const w={...n,joins:T};r(w)}},moveJoinDown:N=>{const b=n.joins.findIndex(T=>T.id===N);if(b<n.joins.length-1){const T=[...n.joins],k={...T[b]},L={...T[b+1]};T[b]=L,T[b+1]=k,T.forEach((B,D)=>{B.sequence=D+1});const w={...n,joins:T};r(w)}},toggleJoinExpansion:N=>{const b=new Set(l);b.has(N)?b.delete(N):b.add(N),o(b)},getAvailableSourceEntities:N=>{if(n.joins.length===0)return a;const b=n.joins.findIndex(k=>k.id===N);if(b===0)return a;const T=new Set;return n.baseEntity.name&&T.add(n.baseEntity.name),n.joins.slice(0,b).forEach(k=>{T.add(k.source.name),T.add(k.target.name)}),a.filter(k=>T.has(k.name))},getAvailableTargetEntities:N=>a.filter(b=>b.name!==N),addJoinKeyGroup:N=>{const b=n.joins.find(k=>k.id===N);if(!b)return;const T=[...b.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];d(N,{joinKeyGroups:T})},updateGroupOperator:(N,b,T)=>{const k=n.joins.find(w=>w.id===N);if(!k)return;const L=[...k.joinKeyGroups];L[b]={...L[b],operator:T},d(N,{joinKeyGroups:L})},removeJoinKeyGroup:(N,b)=>{const T=n.joins.find(L=>L.id===N);if(!T)return;const k=[...T.joinKeyGroups];k.splice(b,1),d(N,{joinKeyGroups:k})},addJoinKey:(N,b)=>{const T=n.joins.find(D=>D.id===N);if(!T)return;const k=a.find(D=>D.name===T.source.name),L=a.find(D=>D.name===T.target.name),w=[...T.joinKeyGroups],B={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(k==null?void 0:k.name)||"",entityName:(k==null?void 0:k.name)||"",entityType:(k==null?void 0:k.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:"="};w[b]={...w[b],keys:[...w[b].keys,B]},d(N,{joinKeyGroups:w})},updateJoinKey:(N,b,T,k,L)=>{const w=n.joins.find(M=>M.id===N);if(!w)return;const B=a.find(M=>M.name===w.source.name),D=a.find(M=>M.name===w.target.name),I=[...w.joinKeyGroups],v=I[b].keys[T];k==="sourceColumnName"&&B?I[b].keys[T]={...v,source:{...v.source,name:L}}:k==="targetColumnName"&&D?I[b].keys[T]={...v,target:{...v.target,name:L}}:k==="operator"&&(I[b].keys[T]={...v,operator:L}),d(N,{joinKeyGroups:I})},removeJoinKey:(N,b,T)=>{const k=n.joins.find(w=>w.id===N);if(!k)return;const L=[...k.joinKeyGroups];L[b].keys.splice(T,1),d(N,{joinKeyGroups:L})},generateSQLPreview:()=>{const N=[...n.joins].sort((k,L)=>k.sequence-L.sequence),b=n.baseEntity;if(!b.name)return"SELECT * FROM table -- Please select a base entity";let T=`SELECT *
|
|
430
|
-
FROM ${b.name}`;return N.forEach(k=>{const L=a.find(D=>D.name===k.target.name);if(!L)return;const w=k.joinKeyGroups.filter(D=>D.keys&&D.keys.length>0).map(D=>{const
|
|
443
|
+
`;C(_)}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(tl,{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 O(){return e.jsxs(s.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(s.ResizablePanel,{id:"1",order:1,defaultSize:a?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(el,{})}),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(sl,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function V(){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:I||k,onClick:()=>{T()},className:"h-8 shrink-0",size:"sm",children:[I||k?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(dn,{sql:b==null?void 0:b.sql,error:v,onDebugWithAssistant:M}),e.jsx(hs,{}),e.jsx(s.Toggle,{pressed:a,onPressedChange:_=>n(_),className:"",size:"sm",children:e.jsx(Zr,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:c,onClick:()=>{E(!0)},className:"h-9 w-full cursor-text px-3 text-left text-sm text-muted-foreground",children:c?"":"Type your question..."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gs,{}),e.jsx(Ys,{})]})]})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsxs("div",{className:"relative flex grow justify-between overflow-y-scroll",children:[O(),F()]}),V()]})}function rl({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 ll({card:t}){var C,E,R,S,N,b,I,k,L,w,B;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(D=>D.themeStyle),d={colors:((E=(C=i==null?void 0:i.chart)==null?void 0:C.dataset)==null?void 0:E.backgroundColor)||[]};(R=t.customCardPreferences)!=null&&R.inputData;const{getCard:m}=s.useCustomVisual(((S=t.customCardPreferences)==null?void 0:S.url)||""),u=((N=t.customCardPreferences)==null?void 0:N.visualType)||"single",h=s.useEditorStore(D=>D.frame),{setCustomCardPreferences:p}=s.useEditorActions(),{data:f}=s.useDashboardCardQuery(t),j=A.useCallback((D,T)=>{l(v=>({...v,[D]:T}))},[]);if(!((b=t.customCardPreferences)!=null&&b.componentName))return null;const x=m((I=t.customCardPreferences)==null?void 0:I.componentName);function y(D){n(D)}const g=Object.keys(((k=t.customCardPreferences)==null?void 0:k.dataInputCardIds)||{}).map(D=>{var M,F,O;const T=(F=(M=t.customCardPreferences)==null?void 0:M.dataInputCardIds)==null?void 0:F[D].cardId,v=(O=h==null?void 0:h.cards)==null?void 0:O.find(V=>V.id===T);return v||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&&u==="single"&&e.jsx(x,{editing:!0,params:c,theme:d,settings:(L=t.customCardPreferences)==null?void 0:L.settings,onDataChange:j,data:(f==null?void 0:f.records)||[]}),x&&u==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((w=t.customCardPreferences)==null?void 0:w.dataInputCardIds)||{}).map(D=>{var M,F,O;const T=(F=(M=t.customCardPreferences)==null?void 0:M.dataInputCardIds)==null?void 0:F[D].cardId,v=(O=h==null?void 0:h.cards)==null?void 0:O.find(V=>V.id===T);if(v)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:y,onDataChange:j,dataInputIndex:D,card:v},v.id+D)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(x,{theme:d,onDataChange:j,settings:g.map(D=>{var T;return(T=D==null?void 0:D.customCardPreferences)==null?void 0:T.settings}),data:g.map(D=>D!=null&&D.id?r==null?void 0:r[D.id]:[])})})]})]},(B=t.customCardPreferences)==null?void 0:B.componentName)})}function xn({className:t,...a}){var I;const n=s.useEditorStore(k=>k.card),r=s.isExplorerCard(n),l=((I=n.customCardPreferences)==null?void 0:I.showCardHeader)??!0,o=s.useEditorStore(k=>k.frame),c=s.useDashboardStore(k=>k.dashboard.filters),i=s.useEditorStore(k=>k.actions.setRunSql),{updateFilter:d}=s.useDashboardActions(),m=c==null?void 0:c.find(k=>k.id===o.filterId),{data:u,isLoading:h,isFetching:p,errorMessage:f,pagination:j,refetch:x}=s.useDashboardCardQuery(n),{setCard:y,updateCardInFrame:g}=s.useEditorActions(),{data:C}=s.useTopoJson(n),E=A.useMemo(()=>n.type==="pivotTable"&&(u!=null&&u.records)&&(u==null?void 0:u.records.length)>0?s.getPivotTableConfig({card:n,data:{records:(u==null?void 0:u.records)||[],columnSubtotalMeta:u==null?void 0:u.columnSubtotalMeta,subtotalColumns:u==null?void 0:u.subtotalColumns,pivotSchema:(u==null?void 0:u.pivotSchema)||[],groupByColumns:u==null?void 0:u.groupByColumns}}):null,[n,u==null?void 0:u.records,u==null?void 0:u.columnSubtotalMeta,u==null?void 0:u.subtotalColumns,u==null?void 0:u.pivotSchema,u==null?void 0:u.groupByColumns]),R=(k,L)=>{var B,D;const w={...n,paginationConfig:{page:k+1,pageSize:L}};y(w),g(w),n.sql&&((D=(B=n.preferences)==null?void 0:B.tablePrefs)!=null&&D.enableDevModePagination)&&i(!0)},S=A.useMemo(()=>!n.id||!(u!=null&&u.records)?null:s.createChartConfig({card:n,data:u==null?void 0:u.records,cardType:n.type,queryConfig:n.queryConfig,customCfg:n.customCfg,preferences:n.preferences,topoJson:C}),[n.id,u==null?void 0:u.records,n.type,n.queryConfig,n.customCfg,n.preferences,C]);function N(k){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(ll,{card:k})})}function b(){if(u!=null&&u.records&&(u==null?void 0:u.records.length)===0&&!h&&!p)return f?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.SearchX,{className:"size-8 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r?"Error fetching data. Please check your chart configuration":"Error fetching data. Please check your SQL or Python code."})]}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((h||p)&&n.type!=="table")return e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!n.id)return null;if(n.type==="custom")return N(n);if(!["table","pivotTable","aggregateTable","custom"].includes(n.type)&&S)return e.jsx(e.Fragment,{children:h||p?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:S})});if(n.type==="table")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:n,data:(u==null?void 0:u.records)||[],paginationMetadata:j,onPaginationChange:R,isLoading:h||p})});if(n.type==="pivotTable"&&E)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.PivotTableVisual,{card:n,data:E.data,options:E.options,onAggregationChange:k=>{const L=s.handleAggregationChange(k,n.config),w={...n,config:L};y(w),g(w)},onAggregationLabelChange:k=>{const L=s.handleAggregationLabelChange(k,n.config),w={...n,config:L};y(w),g(w)}})});if(n.type==="aggregateTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.AggregateTable,{card:n,data:(u==null?void 0:u.records)||[],groupByColumns:u==null?void 0:u.groupByColumns,pivotSchema:u==null?void 0:u.pivotSchema,paginationMetadata:j,onPaginationChange:R,onAggregationChange:k=>{const L=s.handleAggregationChange(k,n.config),w={...n,config:L};y(w),g(w)},isLoading:h||p})})}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:k=>y({...n,title:k}),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:k=>y({...n,description:k}),children:e.jsx(s.CardDescription,{children:n.description||"Add description"})},n.description)]}),m&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Editable,{enabled:!0,className:"my-1",text:m.title||m.column,onSave:k=>d({...m,title:k}),children:e.jsx(s.Label,{children:m.title})}),e.jsx(s.FilterComponent,{filter:m})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:b()})]})}const Ns=({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}),ol=()=>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."})]})]}),il=({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(Ns,{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(Ns,{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(Ns,{language:"javascript",value:t,onChange:l})})]}),cl=({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 dl(){const[t,a]=A.useState(!1),[n,r]=A.useState(""),[l,o]=A.useState(""),[c,i]=A.useState(""),[d,m]=A.useState(""),u=s.useEditorStore(S=>S.card),h=s.useEditorStore(S=>S.card.customCfg),p=h?JSON.stringify(h,null,2):"",{data:f}=s.useDashboardCardQuery(u),{data:j}=s.useTopoJson(u),{setCardCustomCfg:x,setCustomVisualCode:y}=s.useEditorActions(),g=S=>{var N,b;return JSON.stringify({...S,data:{...S.data,datasets:(b=(N=S.data)==null?void 0:N.datasets)==null?void 0:b.map(I=>({...I,data:[]}))}},null,2)},C=()=>{var N,b;if(!((N=f==null?void 0:f.records)!=null&&N.length))return;const S=s.createChartConfig({card:u,data:f.records,cardType:u.type,queryConfig:u.queryConfig,preferences:u.preferences,topoJson:j});if(S){r(g(S)),i(((b=u.preferences)==null?void 0:b.customVisualCode)||"");const I=s.merge(S,h);o(g(I))}},E=()=>{try{if(c&&y(c),l){const S=JSON.parse(l),N=s.getObjectDiff(JSON.parse(n),S);x(N),m("")}}catch{m("Invalid JSON configuration")}},R=Object.keys(h||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:a,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:C,className:R?"":"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(ol,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(xn,{className:"w-1/2 rounded shadow-none"})}),e.jsx(il,{customCode:c,cardCustomCfgString:p,mergedConfig:l,onConfigChange:S=>o(S??""),onCodeChange:S=>i(S??"")})]}),e.jsx(cl,{error:d,hasCardCustomConfig:!!h,onReset:()=>{o(n),x(null)},onApply:E,onClose:()=>a(!1)})]})]})}function xs(t){const[a,n]=A.useState(null);return a}function pn(){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 fn(){const{data:t,isLoading:a,isError:n}=pn(),r=s.useQueries({queries:((t==null?void 0:t.plugins)||[]).map(i=>({queryKey:["manifest",i.value],queryFn:()=>s.loadManifest(i.value),enabled:!!i.value,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:d=>Math.min(1e3*2**d,3e4)}))}),l=[];let o=a,c=n;return r.forEach((i,d)=>{var m;if(i.isLoading&&(o=!0),i.isError&&(c=!0),i.data&&((m=t==null?void 0:t.plugins)!=null&&m[d])){const u=t.plugins[d],h=i.data.visuals.map(p=>({name:p.name,pluginName:u.label,componentType:p.componentType,pluginType:u.type,icon:p.icon,chartType:p.chartType,url:u.value}));l.push(...h)}}),{data:l,isLoading:o,isError:c}}function ul({onChartTypeChange:t}){const{setCardCustomCfg:a,setCardPreferences:n,setCardType:r,setCustomCardPreferences:l}=s.useEditorActions(),{data:o,isLoading:c,isError:i}=fn(),d=A.useCallback((m,u)=>{a(null),n({}),r(m),u&&l({type:"component",visualType:"single",url:u.url,componentName:u.name,icon:u.icon}),t==null||t()},[a,n,r,l,t]);return c?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading custom visuals..."})})]}):i?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-destructive",children:"Failed to load custom visuals"})})]}):!o||o.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:o.map((m,u)=>e.jsx(ml,{text:m.name,onClick:()=>d("custom",m),icon:m.icon},`${m.url}-${m.name}-${u}`))})]})}const ml=({text:t,icon:a,onClick:n})=>{const r=xs(),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 Hs(t){return Re({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 hl(t){return Re({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 Ks(t){return Re({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 Qs(t){return Re({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 Ws(t){return Re({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 Js(t){return Re({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 gn({onChartTypeChange:t,iconClassName:a}){const{setCardType:n,setCardPreferences:r,setIsDevMode:l}=s.useEditorStore(u=>u.actions),{setCardCustomCfg:o,setCustomCardPreferences:c,setQueryConfig:i}=s.useEditorActions();function d(u,h){o(null),r({}),n(u),["custom","text","map"].includes(u)&&(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(_e,{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(ds,{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(us,{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(Ls,{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(Ws,{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(Rs,{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(Ks,{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(ms,{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(Bs,{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(Qs,{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(Ps,{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(Hs,{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(zs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Range Chart",onClick:()=>d("range"),className:"h-10 p-4",children:e.jsx(Os,{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(Js,{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(Et,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Map",onClick:()=>d("map"),className:"h-10 p-4",children:e.jsx(Fs,{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(He,{className:s.cn("size-5",a)})})]})}function xl({chartType:t,className:a,customIcon:n,componentName:r}){const l=xs();switch(t){case"bar":return e.jsx(ds,{className:a});case"line":return e.jsx(us,{className:a});case"pie":return e.jsx(ms,{className:a});case"radar":return e.jsx(Ps,{className:a});case"scatter":return e.jsx(Rs,{className:a});case"bubble":return e.jsx(Ks,{className:a});case"doughnut":return e.jsx(Bs,{className:a});case"stackedBar":return e.jsx(Ls,{className:a});case"stackedLine":return e.jsx(Ws,{className:a});case"polarArea":return e.jsx(Hs,{className:a});case"funnel":return e.jsx(Qs,{className:a});case"tornado":case"pyramid":return e.jsx(zs,{className:a});case"range":return e.jsx(Os,{className:a});case"kpi":return e.jsx(Js,{className:a});case"text":return e.jsx(Qe,{className:a});case"map":return e.jsx(Fs,{className:a});case"custom":return n&&l?e.jsx(l,{className:a}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(He,{className:a});default:return e.jsx(_e,{className:a})}}function jn({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(xl,{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(gn,{onChartTypeChange:()=>n(!1)}),e.jsx(ul,{onChartTypeChange:()=>n(!1)})]})]})}const Je="focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0";function yt(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 pl(){var M,F,O,V,_,W;const[t,a]=A.useState(!1),n=s.useEditorStore(Q=>{var $;return($=Q.card)==null?void 0:$.preferences}),r=s.useEditorStore(Q=>{var $;return($=Q.card)==null?void 0:$.type}),l=s.getNumberAxis(n,{}),[o,c]=A.useState(yt(n,r)),[i,d]=A.useState(((O=(F=(M=n==null?void 0:n.chartOptions)==null?void 0:M.scales)==null?void 0:F[l])==null?void 0:O.min)||""),[m,u]=A.useState(((W=(_=(V=n==null?void 0:n.chartOptions)==null?void 0:V.scales)==null?void 0:_[l])==null?void 0:W.max)||""),[h,p]=A.useState(i||m?"custom":"auto"),[f,j]=A.useState(""),[x,y]=A.useState(0),[g,C]=A.useState(""),[E,R]=A.useState(""),[S,N]=A.useState(""),b=s.useEditorStore(Q=>Q.actions.setCardPreferences),{updateCardInFrame:I}=s.useEditorActions(),k=s.useEditorStore(Q=>Q.card),L=["pie","doughnut","polarArea","funnel"].includes(r);A.useEffect(()=>{var Q,$,q,H,U,P,Y,G,X,se,ae,te,le,K;c(yt(n,r)),d(((q=($=(Q=n==null?void 0:n.chartOptions)==null?void 0:Q.scales)==null?void 0:$[l])==null?void 0:q.min)===0?0:""),u(((P=(U=(H=n==null?void 0:n.chartOptions)==null?void 0:H.scales)==null?void 0:U[l])==null?void 0:P.max)||""),j(((se=(X=(G=(Y=n==null?void 0:n.chartOptions)==null?void 0:Y.scales)==null?void 0:G[l])==null?void 0:X.ticks)==null?void 0:se.stepSize)||""),y(((ae=n==null?void 0:n.numberAxisFormat)==null?void 0:ae.decimalPlaces)||0),C(((te=n==null?void 0:n.numberAxisFormat)==null?void 0:te.suffix)||""),R(((le=n==null?void 0:n.numberAxisFormat)==null?void 0:le.currency)||""),N(((K=n==null?void 0:n.numberAxisFormat)==null?void 0:K.locale)||"")},[t,n,l,r]);function w(Q,$){return $===""||/^[0-9\b]+$/.test($)?Number($):Number(Q)}function B(){const Q=[...new Set(s.LOCALE_CURRENCY_PAIRS.map($=>$.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:E||"none",onValueChange:$=>R($==="none"?"":$),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"}),Q.map($=>e.jsx(s.SelectItem,{value:$,children:$},$))]})})]}),e.jsxs(s.Select,{value:S,onValueChange:$=>N($),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($=>e.jsx(s.SelectItem,{value:$.locale,children:$.locale},$.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:$=>y(Number($.target.value)),id:"format",className:`col-span-6 h-8 w-full tracking-wide ${Je}`})]})]})}function D(){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:Q=>c(Q),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:h,onValueChange:Q=>p(Q),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"})]})]})]}),h==="custom"&&o=="linear"&&T()]})}function T(){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:Q=>d($=>w($,Q.target.value)),className:`col-span-1 h-8 w-full ${Je}`}),e.jsx(s.Input,{value:m,onChange:Q=>u($=>w($,Q.target.value)),id:"max",className:`col-span-1 h-8 w-full ${Je}`})]}),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:Q=>j($=>w($,Q.target.value)),id:"step-size",className:`col-span-1 h-8 w-full ${Je}`})]})]})}function v(){var H;let Q={};h==="custom"&&(Q={min:i,max:m,ticks:{stepSize:f}});const $={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,scales:{...(H=n==null?void 0:n.chartOptions)==null?void 0:H.scales,[l]:{type:o,...o==="linear"?Q:{}}}},numberAxisFormat:{decimalPlaces:x,suffix:g,currency:E,locale:S}};console.log($),b($);const q={...k,preferences:$};I(q)}return e.jsxs(s.Popover,{onOpenChange:Q=>a(Q),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Format Number",children:e.jsx(oa,{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:[B(),D(),e.jsx(s.SelectSeparator,{}),e.jsx("div",{className:"grid grid-cols-3",children:e.jsx(s.Button,{onClick:v,variant:"secondary",className:"col-span-1 col-start-3 h-8 w-full",children:"Apply"})})]})]})})]})}function fl(){const t=s.useEditorStore(i=>{var d,m,u,h;return(h=(u=(m=(d=i.card.preferences)==null?void 0:d.chartOptions)==null?void 0:m.plugins)==null?void 0:u.legend)==null?void 0:h.position}),a=s.useEditorStore(i=>{var d,m,u,h;return(h=(u=(m=(d=i.card.preferences)==null?void 0:d.chartOptions)==null?void 0:m.plugins)==null?void 0:u.legend)==null?void 0:h.align}),n=s.useEditorStore(i=>{var d,m,u,h;return(h=(u=(m=(d=i.card.preferences)==null?void 0:d.chartOptions)==null?void 0:m.plugins)==null?void 0:u.legend)==null?void 0:h.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(Lt,{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(Kn,{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(Un,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Center",onClick:()=>c("center"),children:e.jsx(_n,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"End",onClick:()=>c("end"),children:e.jsx($n,{className:"size-4"})})]})]})]})]})]})})]})}function gl(){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(ut,{className:"size-4"}):e.jsx(dt,{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(ut,{className:"size-4"}):e.jsx(dt,{className:"size-4"})})}return e.jsx(e.Fragment,{children:a==="funnel"?l():r()})}function yn(){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(gl,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsxs(e.Fragment,{children:[e.jsx(pl,{}),e.jsx(fl,{})]}),!["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(pa,{className:"size-4"}),r==="x"&&e.jsx(na,{className:"size-4"}),r==="y"&&e.jsx(Ia,{className:"size-4"}),r==="none"&&e.jsx(Ba,{className:"size-4"})]})]}):null}function jl(){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 y=j.dataTransfer.getData("tabIndex");if(y===x.toString())return;const g=Array.from(t.cards),[C]=g.splice(parseInt(y),1);g.splice(x,0,C),n({...t,cards:g})};function m(j){const x=t.cards.filter(C=>C.id!==j),y=x[0],g={...t,cards:x,activeCardId:y.id};n(g),r(y.id),l(y)}function u(j,x){const y={...t,cards:[...t.cards,x],activeCardId:j.id};n(y),r(x.id)}function h(){const j={...a,id:s.v4(),title:`${a.title} Copy`,tabTitle:`${a.tabTitle||a.title} Copy`};u(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"};u(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 y=x.displayTab===void 0?!1:!x.displayTab;l({...x,displayTab:y}),o({...x,displayTab:y})},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(ia,{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:y=>c(y,x),onDragOver:i,onDrop:y=>d(y,x),className:"",value:j.id,children:[f(t,j),e.jsx(s.Editable,{enabled:t.activeCardId===j.id,text:j.tabTitle||j.title,onSave:y=>{l({...a,tabTitle:y}),o({...a,tabTitle:y})},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:h,children:e.jsx(ra,{className:"h-4 w-4"})})]})})}function bn(){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:u,isFetching:h}=s.useDashboardCardQuery(a);function p(x){const y=t.cards.find(g=>g.id===x);if(y!=null&&y.sql){r||i(!0),o(x);return}if(y!=null&&y.queryConfig){r&&i(!1),f(x),o(x);return}r||f(x),o(x)}function f(x){const y={...t,cards:t.cards.map(C=>C.id===a.id?a:C),activeCardId:x};l(y);const g=y.cards.find(C=>C.id===x);g.sql&&d(!0),c(g)}function j(){return a.type==="kpi"?u||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border border-border",children:e.jsx(s.KPICard,{card:a,data:m==null?void 0:m.records,isPending:u||h})})}):a.type==="text"?u||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:n,card:a,data:m==null?void 0:m.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(xn,{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(jl,{})]})}function Xe({children:t}){var R,S;s.useEditorStore(N=>N.frame);const a=s.useEditorStore(N=>N.card),n=s.useEditorStore(N=>N.isDevMode),r=s.useEditorStore(N=>N.isShowingVisual),l=s.useDashboardStore(N=>N.isVisualEditing),o=s.useEditorStore(N=>N.pythonStdOut);s.useEditorStore(N=>N.actions.setRunSql);const{setFrame:c,setCard:i,setActiveTabCardId:d,runAssistant:m,setIsDevMode:u,setCardPreferences:h}=s.useEditorActions(),{data:p,isLoading:f,isFetching:j,errorMessage:x,refetch:y}=s.useDashboardCardQuery(a);function g(){const N=JSON.stringify(p==null?void 0:p.records,null,2),b=new Blob([N],{type:"application/json"}),I=URL.createObjectURL(b),k=document.createElement("a");k.href=I,k.download=`${a.title}.json`,k.click()}function C(){const b=[Object.keys(p==null?void 0:p.records.reduce((w,B)=>({...w,...B}),{})).join(","),...((p==null?void 0:p.records)||[]).map(w=>Object.values(w).join(","))].join(`
|
|
444
|
+
`),I=new Blob([b],{type:"text/csv"}),k=URL.createObjectURL(I),L=document.createElement("a");L.href=k,L.download=`${a.title}.csv`,L.click()}function E(){const N=`Can you get the documentation for ${a.type} chart?`;m(N)}return a?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[r&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(jn,{}),l&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:E,children:e.jsx(Xn,{className:"size-4"})}),!["table","custom"].includes(a.type)&&l&&e.jsx(dl,{})]}),!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:C,children:e.jsx(hl,{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:g,children:e.jsx(da,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(p==null?void 0:p.records,null,2),className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t,e.jsx(yn,{})]}),a.type==="table"&&a.sql&&!s.hasValidCardConfig(a.config)&&e.jsxs("div",{className:"mr-2 flex items-center gap-3",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((S=(R=a.preferences)==null?void 0:R.tablePrefs)==null?void 0:S.enableDevModePagination)??!1,onCheckedChange:N=>{var b;h({...a.preferences,tablePrefs:{...(b=a.preferences)==null?void 0:b.tablePrefs,enableDevModePagination:N}}),y()}}),e.jsx(s.Label,{htmlFor:"pagination",children:"Paginate Results"})]}),n&&e.jsx(bl,{})]}),r?e.jsx(bn,{}):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(yl,{})}),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:[(p==null?void 0:p.records)&&(p==null?void 0:p.records.length)>0&&e.jsx(rl,{data:(p==null?void 0:p.records)||[]}),x&&e.jsx(on,{error:x})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function yl(){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 bl(){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 vl(){var x,y;const t=s.useEditorStore(g=>g.card.customCardPreferences),{data:a}=pn(),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 u(g,C){if(!t)return;const R={...(t==null?void 0:t.dataInputCardIds)||{},[g]:{cardId:C,hookRef:null}};c({...t,dataInputCardIds:R})}function h(g){var E,R;const C=(E=l==null?void 0:l.cards)==null?void 0:E.filter(S=>{var N;return((N=S==null?void 0:S.customCardPreferences)==null?void 0:N.visualType)!=="multiple"}).map(S=>({value:S.id,label:S.tabTitle||S.title}));return e.jsx("div",{className:"space-y-2",children:(R=g==null?void 0:g.dataInputs)==null?void 0:R.map((S,N)=>{var b,I;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(he,{className:"col-span-6 h-8 w-full justify-between",label:"",options:C||[],value:((I=(b=t==null?void 0:t.dataInputCardIds)==null?void 0:b[N])==null?void 0:I.cardId)||"",onValueChange:k=>u(N,k)})]},N+Math.random())})})}function p(g,C,E=[],R=""){var S,N;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[C])||R,onChange:b=>{c({...t,settings:{...t==null?void 0:t.settings,[C]:b.target.value}})}},C):g==="select"?e.jsx(he,{className:"h-8 w-full",label:"",options:E,value:((N=t==null?void 0:t.settings)==null?void 0:N[C])||R,onValueChange:b=>{c({...t,settings:{...t==null?void 0:t.settings,[C]:b}})}}):null:null}function f(g){const C=Object.entries((g==null?void 0:g.settings)||{});return e.jsx("div",{className:"space-y-3",children:C.map(([E,R])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:R.title}),p(R.ui,E,R.options,R.defaultValue)]},E))})}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(he,{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: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(he,{icon:e.jsx(aa,{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})}})})]})})]}),((y=r==null?void 0:r.customCardPreferences)==null?void 0:y.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:h(m)})]}),m&&m.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:f(m)})})]})]})]})}function Be(){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 u;return(u=m.card.preferences)==null?void 0:u.filterOnClickColumnIndex}),A.useEffect(()=>{o&&a(new Array(o.length).fill(!1))},[o]);function c(m,u){var h,p;u?n!=null&&n.onClickFilter&&((h=n==null?void 0:n.onClickFilter)==null?void 0:h.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,u){var p;const h=(p=n==null?void 0:n.onClickFilter)==null?void 0:p.map(f=>f.columnIndex===m?{...f,expression:u.target.value}:f);l({...n,onClickFilter:h})}function d(m){var u,h,p,f;if(t!=null&&t[m]||(h=(u=n==null?void 0:n.onClickFilter)==null?void 0:u.find(j=>j.columnIndex===m))!=null&&h.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,u)=>{var h,p;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((h=n==null?void 0:n.onClickFilter)!=null&&h.find(f=>f.columnIndex===u)),onCheckedChange:f=>c(u,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===u))&&e.jsx(s.Pencil,{onClick:()=>{a(f=>{const j=[...f];return j[u]=!f[u],j})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(u)]})},m)})]})}function Nl({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 u={display:d!=="none",align:d,anchor:d,clamp:!0};if(!o)r({...a,datasetOptions:[...n||[],{idx:m,datalabels:u}]});else{const h={...o};h.datalabels=u;const p=n==null?void 0:n.map(f=>f.idx===m?h:f);r({...a,datasetOptions:p})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(Ft,{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(ja,{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(ba,{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(ya,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function Cl(){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 Xs({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 vn(){const t=s.useEditorStore(d=>d.card),a=s.useEditorStore(d=>{var m,u,h;return(h=(u=(m=d==null?void 0:d.card)==null?void 0:m.preferences)==null?void 0:u.chartOptions)==null?void 0:h.indexAxis}),{data:n}=s.useDashboardCardQuery(t),r=a==="y"?"Metric":"Dimension",l=a==="y"?"Dimension":"Metric",{dimensionKeys:o,transformedMetricKeys:c,keys:i}=Cl();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:Nn(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(Cn,{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 Nn(t,a=30){return t.length>a?t.slice(0,a)+"...":t}function Cn({col:t,idx:a,className:n,iconClassName:r,children:l}){const o=s.useEditorStore(u=>{var h;return(h=u.card)==null?void 0:h.preferences}),c=s.useEditorStore(u=>{var h,p;return(p=(h=u.card)==null?void 0:h.preferences)==null?void 0:p.datasetOptions}),i=c==null?void 0:c.find(u=>u.idx===a),{setCardPreferences:d}=s.useEditorStore(u=>u.actions);function m(u){if(!i)d({...o,datasetOptions:[...c||[],{idx:a,type:u==="area"?"line":u,fill:u==="area"?"origin":""}]});else{const h={...i};h.type=u==="area"?"line":u,h.fill=u==="area"?"origin":"";const p=c==null?void 0:c.map(f=>f.idx===a?h: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(Xs,{className:"max-w-[100px]",title:t,children:Nn(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ds,{onClick:()=>m("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(us,{onClick:()=>m("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(It,{onClick:()=>m("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(Nl,{idx:a})]})]})}function Sn(){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:u,connectionType:h}=s.useEditorAside();function p(f,j="dashboard"){var b;const x=s.fmt(f.column_name),y=s.fmt(n||""),g=s.fmt(r||""),C=s.fmt(u);let E=s.getQualifiedTableName({schemaName:g,tableName:C,connectionType:h,databaseName:y}),R=`${E}.${x}`;const S=(b=m==null?void 0:m.find(I=>I.id===a))==null?void 0:b.name;a&&a!=="none"&&(R=`${s.DATAMODEL_NAMESPCACE}.${S}.${x}`,E=`${s.DATAMODEL_NAMESPCACE}.${S}`);const N=o==null?void 0:o.find(I=>I.column===R&&I.table===C&&(I.database===y||I.database===n));if(N)d(N.id),i(N.id);else{const I=s.v4();return u==="api"&&t?(c({location:j,id:I,column:R,title:f.column_name,dataType:f.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(f.data_type,E,x)}),I):(c({id:I,location:j,column:R,title:f.column_name,dataType:f.data_type,table:l||"",database:n||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(f.data_type,E,x)}),I)}}return{assignFilter:p}}function $e(){const t=s.useDashboardStore(i=>i.dashboard.filters),a=s.useEditorStore(i=>i.frame),{setFrame:n}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=Sn();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(Sl,{onSelect:o,columns:r}),c&&e.jsx(s.FilterHeader,{filter:c})]})}function Sl({columns:t,onSelect:a}){var c;const[n,r]=ue.useState(!1),[l,o]=ue.useState("");return e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[l?(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 wl({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(vn,{})})]}),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(Be,{}),e.jsx($e,{})]})]})]})})}function ps(){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 u;const d={datalabels:{display:i!=="none",align:i,anchor:i,clamp:!0}},m={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(u=n==null?void 0:n.chartOptions)==null?void 0:u.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 Dl({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(ps,{})})]}),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(Be,{}),e.jsx($e,{})]})]})]})})}const kl={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},El={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function Tl(){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:Il(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(ps,{}),e.jsx(Be,{}),e.jsx($e,{})]})]})}function Il(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(kl,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(El,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 Al(){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 Cs({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 Ml=[{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"}],Ll=["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"],Ol=Ll.map(t=>({label:t,value:t}));function Rl(){var d,m,u,h,p,f,j,x,y,g,C,E,R,S,N,b,I,k;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]=A.useState(((h=(u=t==null?void 0:t.preferences)==null?void 0:u.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:o}=s.useTopoJson(t),c=Object.keys((o==null?void 0:o.objects)||{}).map(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(Cs,{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(Cs,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(he,{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(he,{className:"h-9",options:c,value:((f=(p=t.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:f.objectKey)||"",label:"Map Object",onValueChange:L=>{var w;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,objectKey:L}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(he,{className:"h-9",options:Ml,value:((x=(j=t.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:x.projection)||"",label:"Projection",onValueChange:L=>{var w;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,projection:L}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(he,{className:"h-9",options:Ol,value:((g=(y=t.preferences)==null?void 0:y.mapVisualOptions)==null?void 0:g.colorScale)||"",label:"Select Color Scale",onValueChange:L=>{var w;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,colorScale:L}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Cs,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:.1,value:((E=(C=t.preferences)==null?void 0:C.mapVisualOptions)==null?void 0:E.projectionScale)||1,onChange:L=>{var w;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.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:((N=(S=(R=t.preferences)==null?void 0:R.mapVisualOptions)==null?void 0:S.projectionOffset)==null?void 0:N[0])||0,onChange:L=>{var w,B,D,T;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,projectionOffset:[Number(L.target.value),((T=(D=(B=t.preferences)==null?void 0:B.mapVisualOptions)==null?void 0:D.projectionOffset)==null?void 0:T[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((k=(I=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:I.projectionOffset)==null?void 0:k[1])||0,onChange:L=>{var w,B,D,T;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,projectionOffset:[((T=(D=(B=t.preferences)==null?void 0:B.mapVisualOptions)==null?void 0:D.projectionOffset)==null?void 0:T[0])||0,Number(L.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Be,{})]})}function Bl(){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 Ze({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(ps,{}),t==="text"&&e.jsx(Bl,{})]})]}),!["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(Be,{}),e.jsx($e,{})]})]})]})})}function Fl(){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(he,{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(vn,{})]})]}),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(Be,{}),e.jsx($e,{})]})]})]})})}function Pl({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(Be,{}),e.jsx($e,{})]})]})}),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 zl=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."]})]}),Vl=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."]})]}),_l=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 Ul(){const t=s.useEditorStore(n=>n.card.type);function a(n){switch(n){case"stackedBar":case"stackedLine":return e.jsx(Fl,{});case"tornado":case"pyramid":return e.jsx(Ze,{docContent:zl,cardType:n});case"kpi":return e.jsx(Al,{});case"line":case"bar":return e.jsx(wl,{cardType:n});case"range":return e.jsx(Ze,{docContent:Vl,cardType:n});case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return e.jsx(Ze,{cardType:n});case"bubble":case"scatter":return e.jsx(Dl,{cardType:n});case"table":return e.jsx(Pl,{cardType:n});case"text":return e.jsx(Ze,{docContent:_l,cardType:n,suffix:"Visual"});case"map":return e.jsx(Rl,{});case"custom":return e.jsx(vl,{});default:return e.jsx(Tl,{})}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[a(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function wn({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(he,{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 $l=[{label:"Sum",value:"SUM",logo:e.jsx(Bt,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(Ge,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(ma,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(Gn,{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 ql({column:t}){const{updateMetricColumnOld:a}=s.useEditorActions();let n=$l;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:We(t.name,l)};a(t.id,o)}return e.jsx(wn,{column:t,functions:n,onFunctionChange:l=>r(l),label:"Aggregation"})}const Yl=[{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 Gl({column:t}){const{updateGroupByColumnOld:a}=s.useEditorActions();function n(r){const l={...t,granularity:r,label:Ue(t.name,r)};a(t.id,l)}return e.jsx(wn,{column:t,functions:Yl,onFunctionChange:r=>n(r),label:"Granularity"})}function Hl({col:t,onChange:a,droppableId:n}){const{columns:r}=s.useDataColumns(),l=A.useMemo(()=>{let i=[];(n===Ae||n===Me||n===Le)&&(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 u;return m.column_name===((u=i[0])==null?void 0:u.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 Dn({column:t}){const a=s.useEditorStore(d=>d.card.type),n=s.useEditorStore(d=>{var m,u;return(u=(m=d.card)==null?void 0:m.config)==null?void 0:u.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(Cn,{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(ps,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&c(),["pie","doughnut"].includes(a)&&i()]})}function Kl({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:u,setNodeRef:h,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,y=s.isTextDataType(t.type);function g(N){const b=s.isNumberDataType(N.data_type),I=s.isTextDataType(N.data_type),k=s.isDateDataType(N.data_type),L=b?"number":I?"string":k?"date":"string";if(r===Ae){if(I){const w={id:t.id,name:N.column_name,type:L,role:"groupby"};c(t.id,w)}if(k){const w={id:t.id,name:N.column_name,type:L,role:"groupby",label:Ue(N.column_name,"month"),granularity:"month"};c(t.id,w)}}if(r===Le){if(I){const w={id:t.id,name:N.column_name,type:L,role:"groupby"};d(t.id,w)}if(k){const w={id:t.id,name:N.column_name,type:L,label:Ue(N.column_name,"month"),granularity:"month",role:"groupby"};d(t.id,w)}}if(r===Me){const w={id:t.id,name:N.column_name,type:L,role:"metric",label:We(N.column_name,"SUM"),aggregate:b?"SUM":"COUNT"};i(t.id,w)}}function C(){if(r===Me)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(Dn,{column:t})})}function E(){const N=s.isDateDataType(t.type);if(r===Me)return e.jsx(ql,{column:t});if((r===Ae||r===Le)&&N)return e.jsx(Gl,{column:t})}function R(){return e.jsx("div",{className:s.cn("grow",{"pl-3":(r===Ae||r===Le)&&y}),children:e.jsx(Hl,{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(La,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(Mt,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...u,...m,ref:h,style:x,children:e.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex h-8 grow items-center justify-between rounded-md bg-muted",children:[S(),E(),R()]}),l&&C()]}),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 Ss({id:t,label:a,columns:n,previewColumns:r,sortableType:l,onRemoveColumn:o}){var x,y;const{setNodeRef:c,isOver:i,over:d}=s.useDroppable({id:t}),m=s.useDndStore(g=>g.activeId),u=s.useEditorStore(g=>{var C;return(C=g.card)==null?void 0:C.type}),h=i||((y=(x=d==null?void 0:d.data)==null?void 0:x.current)==null?void 0:y.type)===l,p=m?r:n,f=l===ls?"Rows":l===os?"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",h&&"border border-muted-foreground/20"),ref:c,children:[e.jsxs("div",{className:"flex items-center justify-between pr-5",children:[e.jsx(s.Label,{className:"text-sm",children:a}),u!=="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===rn.id?e.jsx(Ql,{},g.id):e.jsx(Kl,{droppableId:t,type:l,column:g,onRemoveColumn:o},g.id))})]})})}function Ql(){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 kn({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 Wl(){const t=s.useEditorStore(g=>{var C;return(C=g.card.queryConfig)==null?void 0:C.orderBy})||[],a=s.useEditorStore(g=>{var C;return(C=g.card.queryConfig)==null?void 0:C.groupByColumns})||[],n=s.useEditorStore(g=>{var C;return(C=g.card.queryConfig)==null?void 0:C.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(Wn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx(Yn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=e.jsx(Qn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=e.jsx(qn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=c==null?void 0:c.filter(g=>!t.some(C=>C.columnId===g.id)).map(g=>({id:g.id,value:g.label||g.name}));function p(g,C){const E=f(g);return E?E.role==="metric"?C==="asc"?m:u:C==="asc"?i:d:null}function f(g){return c.find(C=>C.id===g)}function j(g){const C=t.find(E=>E.columnId===g);if(C){const E={...C,direction:C.direction==="asc"?"desc":"asc"};o(E)}}const x=g=>{r({columnId:g.id,direction:"asc"})};function y(g){const C=t.find(E=>E.columnId===g);C&&l(C)}return e.jsx(s.SortableContext,{items:t.map(g=>Ye(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"}),h.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(s.ComboBox2,{multiple:!1,options:h,selectedOptions:[],onChange:g=>x(g[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),t.map(g=>{var C,E;return e.jsx(kn,{id:Ye(g.columnId),type:qs,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(Mt,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(Xs,{className:"w-[175px] text-sm",children:((C=f(g.columnId))==null?void 0:C.label)||((E=f(g.columnId))==null?void 0:E.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:()=>y(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)},Ye(g.columnId))})]})})}function Jl(){const t=s.useEditorStore(y=>{var g;return((g=y.card.queryConfig)==null?void 0:g.groupByColumns)||[]}),a=s.useEditorStore(y=>y.card.type),n=s.useDndStore(y=>y.previewGroupByColumns),r=s.useEditorStore(y=>{var g;return((g=y.card.queryConfig)==null?void 0:g.metricColumns)||[]}),l=s.useDndStore(y=>y.previewMetricColumns),o=s.useEditorStore(y=>{var g;return((g=y.card.queryConfig)==null?void 0:g.pivotColumns)||[]}),c=s.useDndStore(y=>y.previewPivotColumns),{removeColumnFromGroupBy:i,removeColumnFromMetricColumns:d,removeColumnFromPivotBy:m}=s.useEditorActions();function u(y){i(y)}function h(y){d(y)}function p(y){m(y)}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(gn,{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(Ss,{onRemoveColumn:u,sortableType:ls,id:Ae,label:f,columns:t,previewColumns:n}),e.jsx(Ss,{onRemoveColumn:p,sortableType:os,id:Le,label:x,columns:o,previewColumns:c}),e.jsx(Ss,{onRemoveColumn:h,sortableType:Es,id:Me,label:j,columns:r,previewColumns:l}),e.jsx(Wl,{})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Zs({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(h=>{var p,f;return(f=(p=h.card.queryConfig)==null?void 0:p.filters)==null?void 0:f.some(j=>j.filterColumnName===a.name)});function u(h){i(h)}return e.jsx(kn,{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:()=>u(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 Xl({column:t,sortableType:a}){const n=s.useDashboardStore(E=>E.themeStyle),r=s.useEditorStore(E=>{var R,S;return(S=(R=E.card)==null?void 0:R.queryConfig)==null?void 0:S.filters}),l=s.useEditorStore(E=>{var R,S;return(S=(R=E.card.queryConfig)==null?void 0:R.filterColumns)==null?void 0:S.find(N=>N.name===t.name)}),{selectedConnectionId:o,selectedDatabaseName:c,selectedTableName:i}=s.useEditorAside(),d=A.useMemo(()=>{var E;return(E=r==null?void 0:r.find(R=>R.filterColumnName===t.name))==null?void 0:E.filterValue},[r,t.name]),m=A.useMemo(()=>Array.isArray(d)?d.map(E=>({id:E,value:E})):[],[d]),{updateEditorFilterValue:u}=s.useEditorActions(),h={column:t.name,sql:t.sql,id:t.name,connectionId:o,dataType:t.type},{data:p,isLoading:f,isFetching:j,isError:x}=s.useFilterQuery(h),y=A.useMemo(()=>{var R;return h.column?(R=p==null?void 0:p.records)==null?void 0:R.map(S=>{let N=h.column.split(".").slice(-1)[0].replace(/"/g,"");return S[N]===void 0&&(N=N.toLowerCase()),{id:S[N],value:S[N]}}):[]},[p,h.column]);function g(E){const R=E.map(S=>S.id);u(t.name,R)}function C(){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(Zl,{columnName:t.name}),showNegativeIndicator:(l==null?void 0:l.mode)==="exclude",options:y,onChange:g,selectedOptions:m,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(Zs,{className:"w-60",id:t.id,sortableType:a,column:t,children:C()})}function Zl({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 eo({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:u,data:h}=s.useFilterQuery(i),p=h==null?void 0:h.records,{dateRange:f,setDateRange:j,initialDateRange:x}=s.useDateRangeFromRecords(p),{updateEditorFilterValue:y}=s.useEditorActions();function g(R){var N,b;const S={gte:(N=R==null?void 0:R.from)==null?void 0:N.toISOString(),lte:(b=R==null?void 0:R.to)==null?void 0:b.toISOString()};y(t.name,S)}function C(){y(t.name,null,!0),j(x)}function E(){return d||m?e.jsx("div",{children:e.jsx(s.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):u?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:C}):e.jsx(s.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(Zs,{className:"w-72",id:t.id,sortableType:a,column:t,children:E()})}function so({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(y=>y.activeId),m={},u=c||((x=(j=i==null?void 0:i.data)==null?void 0:j.current)==null?void 0:x.type)===l;function h(){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(y){const g=s.isDateDataType(y.type);return y.id===rn.id?e.jsx(Zs,{id:y.id,sortableType:l,column:y,children:e.jsx(to,{})},y.id):g?e.jsx(eo,{droppableId:t,sortableType:l,column:y},y.id):e.jsx(Xl,{droppableId:t,sortableType:l,column:y},y.id)}const f=d?r:n;return e.jsx(s.SortableContext,{items:n==null?void 0:n.map(y=>y.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",u&&"border border-muted-foreground/20"),ref:o,style:m,children:[e.jsx(s.Label,{className:"text-sm",children:a}),h(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:f==null?void 0:f.map(y=>p(y))})]})})}function to(){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 no(){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(so,{onRemoveColumn:r,sortableType:Is,id:Ts,label:"Filters",columns:t,previewColumns:a})})}function ao(){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(hs,{}),!a&&e.jsxs(s.Button,{onClick:()=>n(!0),variant:"secondary",size:"sm",children:[e.jsx(wa,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(dn,{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(Gs,{}),e.jsx(Ys,{variant:"default"})]})]})}function ro(){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,u;r?((i=t.current)==null||i.resize(0),(d=a.current)==null||d.resize(0)):((m=t.current)==null||m.resize(25),(u=a.current)==null||u.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(al,{})}),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(Ul,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(Xe,{})})]}):e.jsx(Xe,{})})]})}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(Jl,{})})}),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(ao,{}),e.jsx(no,{})]}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(Xe,{})})]})})]}):e.jsx(Xe,{})})})}return e.jsx(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:l?o():c()})}function lo(t){const a=s.useAIInteractionStore(z=>z.currentAIContext),[n,r]=A.useState(""),[l,o]=A.useState(null),{authToken:c}=s.useSemaphorContext(),i=s.useEditorStore(z=>{var Z;return(Z=z==null?void 0:z.card)==null?void 0:Z.sql}),d=s.useEditorStore(z=>z.isDevMode),m=s.useEditorStore(z=>{var Z;return(Z=z==null?void 0:z.card)==null?void 0:Z.python}),{setCardPython:u,setCardSql:h,setRunSql:p,switchCardType:f,setQueryConfig:j}=s.useEditorActions(),x=s.useEditorStore(z=>z.currentAssitantScope)||[],y=s.useEditorStore(z=>z.userInputForAI),g=s.useEditorStore(z=>z.triggerAIRun),C=s.useEditorStore(z=>z.card),E=s.useEditorStore(z=>z.selectedDatabaseName),R=s.useEditorStore(z=>z.selectedTableName),S=s.useEditorStore(z=>z.selectedConnectionId),N=s.useEditorStore(z=>z.selectedSchemaName),b=s.useDashboardStore(z=>z.dashboard.aiScopeTables),{errorMessage:I,refetch:k,data:L}=s.useDashboardCardQuery(C),{setTriggerAIRun:w,setCurrentAssitantScope:B,setCardConfig:D}=s.useEditorActions(),{selectedDatamodelName:T,connectionType:v,selectedDatamodelId:M}=s.useEditorAside(),{messages:F,setMessages:O,reload:V,error:_,append:W,input:Q,setInput:$,status:q,handleInputChange:H,handleSubmit:U,stop:P}=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:z=>{console.log("on error",z)},onToolCall:Y,onFinish(z,Z){G(Z.usage),r(""),Z.finishReason==="stop"&&r("")}});A.useEffect(()=>{g&&y&&(W({role:"user",content:y}),w(!1))},[g,y,W,w]);async function Y({toolCall:z}){var Z,oe,Ce,Te;if(["createChartFromSql","createForecast"].includes(z.toolName)){const ne=z.args.sql,ie=z.args.python,ce=z.args.chartType;return f(ce),h(ne),u(ie),p(!0),{status:"success",message:"Let the user know that chart is created"}}else if(z.toolName==="getTableColumns")r("Getting table columns...");else{if(z.toolName==="getUserSql")return i?{status:"success",sql:i,python:m||""}:{status:"error",message:"No SQL found"};if(z.toolName==="getCurrentTableScope")return r("Getting table scope..."),te(),{status:"success",tables:x};if(z.toolName==="generateQueryConfig"){r("Generating query config...");const ne=z.args.chartType,ie=z.args.queryConfig;z.args.cardConfig,f(ne),D(ie),h(void 0),u(void 0);const ce=await k();return(Z=ce==null?void 0:ce.data)!=null&&Z.error?{status:"error",queryConfig:ie,message:(oe=ce==null?void 0:ce.data)==null?void 0:oe.error.message}:(Ce=ce==null?void 0:ce.data)!=null&&Ce.records?{status:"success",queryConfig:ie,message:"The data has been visualized"}:{status:"success",queryConfig:ie,message:"The data has been visualized",records:(Te=ce==null?void 0:ce.data)==null?void 0:Te.records}}else r("Analyzing...")}}function G(z){o(Z=>Z?{promptTokens:Z.promptTokens+z.promptTokens,completionTokens:Z.completionTokens+z.completionTokens,totalTokens:Z.totalTokens+z.totalTokens}:z)}function X(z){const Z=s.removeFromScopeArray(x,z);se(Z)}function se(z){const Z=s.sanitizeAIScope(z);B(Z),O(oe=>[...oe,{id:crypto.randomUUID(),role:"system",content:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(Z)}`}])}function ae(){const z={databaseName:E||"",schemaName:N||"",tableName:R||"",datamodelId:M||"",datamodelName:s.resolveDatamodelName(T),connectionId:S||"",connectionType:v||""},Z=s.dedup([...x,z]);se(Z)}function te(){const z={databaseName:E||"",schemaName:N||"",tableName:R||"",datamodelName:s.resolveDatamodelName(T),connectionId:S||"",connectionType:v||"",datamodelId:M||""};if(!s.isInAiScopeArray([...b||[],...x],z)||x.length===0){const oe=s.dedup([...b||[],...x,z]).filter(Ce=>Ce.connectionId===z.connectionId);se(oe)}}const le=!["ready","error"].includes(q),K=s.getErrorMessage(_);return{messages:F,setMessages:O,reload:V,append:W,input:Q,setInput:$,isLoading:le,handleSetAIScope:te,handleAddCurrentTableToScope:ae,removeFromCurrentSelections:X,currentAssitantScope:x,setCurrentAssitantScope:B,handleInputChange:H,handleSubmit:U,stop:P,chatStatus:q,toolStatus:n,llmUsage:l,onFinish:t,errorMessage:K}}const oo=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function bt(){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),u=s.useCurrentAIContext(),{setCurrentAIContext:h}=s.useAIActions(),p=s.useDashboardStore(P=>P.dashboard.aiContext),f=s.useEditorStore(P=>P.card.dataSource),j=s.useEditorStore(P=>P.actions.setCardSql),x=s.useEditorStore(P=>P.actions.setRunSql),y=s.useEditorStore(P=>P.showAIDialog),g=s.useDashboardStore(P=>P.handleOpenAssistantProfile),{setShowAIDialog:C,setCardPython:E}=s.useEditorActions(),{setDataSource:R}=s.useEditorActions(),{assistantProfile:S}=s.useAssistantProfile(),{messages:N,setMessages:b,reload:I,append:k,input:L,setInput:w,isLoading:B,handleInputChange:D,handleSubmit:T,stop:v,chatStatus:M,llmUsage:F,errorMessage:O}=lo();s.useAssistantScroll({scrollContainerRef:t,inputRef:a,messages:N}),A.useEffect(()=>{var P;y&&((P=a.current)==null||P.focus(),h({selectedEntities:(f==null?void 0:f.selectedEntities)||[]}))},[y,f,h]);function V(P,Y){Y==="sql"?(j(P),x(!0)):Y==="python"&&(E(P),x(!0))}function _(){var P;(P=p==null?void 0:p.selectedEntities)==null||P[0],m(!0)}function W(){u.selectedEntities.length===0&&h({selectedEntities:(p==null?void 0:p.selectedEntities)||[]})}function Q(P){W();const Y={role:"user",content:P.title+" "+P.subtitle};k(Y)}function $(P){W(),k({role:"user",content:P})}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 H(){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&&(N==null?void 0:N.filter(P=>P.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:[H(),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:_,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([]),I()},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:()=>{C(!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:N,showTools:l,handleRun:V,showSystemMessage:c}),e.jsx(s.ChatStatus,{messages:N,chatStatus:M,errorMessage:O})]})}),e.jsxs("div",{className:"mb-3",children:[U&&!S&&e.jsx(s.Placeholders,{onClick:Q,placeholders:oo}),e.jsx("div",{children:U&&S&&e.jsx(s.SeedQuestions,{seedQuestions:S.seedQuestions||[],handleSeedQuestionClick:$})})]}),e.jsx(s.ChatInputWithContext,{ref:a,setInput:w,stop:v,input:L,handleInputChange:D,handleSubmit:P=>{W(),T(P)},isLoading:B,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 En(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 io(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(!En(r,t.qualifiedEntityName,n))return{isValid:!1,showError:!0}}else return{isValid:!1,showError:!0};return{isValid:!0}}function As(){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 Ms(t,a){return a.some(n=>n.name===t.name&&n.qualifiedEntityName===t.qualifiedEntityName)}const et=t=>{var w;const{updateCardConfig:a,updateGroupByColumn:n,updateMetricColumn:r,updatePivotByColumn:l,updateSortByColumn:o,removeGroupByColumn:c,removeMetricColumn:i,removePivotByColumn:d,removeSortByColumn:m}=s.useEditorActions(),u=s.useEditorStore(B=>B.card.type),h=t==null?void 0:t.id,p=A.useCallback(B=>{if(!(t!=null&&t.config))return[];switch(B){case"groupBy":return(t.config.groupByColumns||[]).map(D=>({id:D.id,name:D.name,dataType:D.dataType,label:D.label!==void 0?D.label:D.name,qualifiedEntityName:D.qualifiedEntityName,entityId:D.entityId,entityName:D.entityName,entityType:D.entityType,dateFormat:D.dateFormat,customFormat:D.customFormat,granularity:D.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(D=>({id:D.id,name:D.name,dataType:D.dataType,label:D.label!==void 0?D.label:D.name,qualifiedEntityName:D.qualifiedEntityName,entityId:D.entityId,entityName:D.entityName,entityType:D.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(D=>({id:D.id,name:D.name,dataType:D.dataType,label:D.label!==void 0?D.label:D.name,qualifiedEntityName:D.qualifiedEntityName,entityId:D.entityId,entityName:D.entityName,entityType:D.entityType,direction:D.direction}));case"source":return[];default:return[]}},[t]),f=A.useCallback((B,D)=>{if(h)switch(B){case"groupBy":{a(h,{groupByColumns:D});break}case"metrics":{a(h,{metricColumns:D});break}case"pivotBy":{a(h,{pivotByColumns:D});break}case"sortBy":{a(h,{sortByColumns:D});break}}},[h,a]),j=A.useCallback((B,D,T)=>{if(!h)return;const M=p(B)[D];if(M)switch(B){case"groupBy":n(h,M.id,{label:T});break;case"metrics":r(h,M.id,{label:T});break;case"pivotBy":l(h,M.id,{label:T});break;case"sortBy":o(h,M.id,{label:T});break}},[h,p,n,r,l,o]),x=A.useCallback((B,D)=>{if(!h)return;const v=p("metrics")[B];v&&r(h,v.id,{aggregate:D,label:s.getAggregationLabel(v.name,D)})},[h,p,r]),y=A.useCallback((B,D,T)=>{if(!h)return;const M=p("groupBy")[B];if(!M)return;const F={dateFormat:D};D==="custom"&&T?F.customFormat=T:F.customFormat=void 0,n(h,M.id,F)},[h,p,n]),g=A.useCallback((B,D)=>{if(!h)return;const v=p("groupBy")[B];v&&n(h,v.id,{granularity:D})},[h,p,n]),C=A.useCallback((B,D)=>{if(!h)return;const v=p("metrics")[B];v&&r(h,v.id,{aliasTemplate:D})},[h,p,r]),E=A.useCallback((B,D)=>{if(console.log("handleValueAliasesChange",B,D),!h)return;console.log("handleValueAliasesChange",B,D);const v=p("metrics")[B];v&&(console.log("handleValueAliasesChange",D),r(h,v.id,{valueAliases:D}))},[h,p,r]),R=A.useCallback(B=>{h&&a(h,{comparisonType:B})},[h,a]),S=A.useCallback(B=>{h&&a(h,{showTrendline:B})},[h,a]),N=A.useCallback(B=>{h&&a(h,{trendlineWindow:B})},[h,a]),b=A.useCallback(B=>{h&&a(h,{trendlineGranularity:B})},[h,a]),I=A.useCallback(B=>{h&&a(h,{targetValue:B})},[h,a]),k=A.useCallback(B=>{var V;if(!h)return;const D=[...p("groupBy"),...p("pivotBy"),...p("metrics"),...p("sortBy")],T=(V=t==null?void 0:t.config)==null?void 0:V.joinPlan,v=io(B,D,T);if(!v.isValid){v.showError&&As();return}const M=s.getSmartContainerForField(B),F=p(M);if(Ms(B,F))return;const O=s.getNewField(B,M);O&&f(M,[...F,O])},[h,(w=t==null?void 0:t.config)==null?void 0:w.joinPlan,p,f]),L=A.useCallback((B,D)=>{if(!h)return;const v=p(B)[D];if(v){if(B!=="sortBy"){const M=p("sortBy"),F=M.filter(O=>!(O.name===v.name&&O.qualifiedEntityName===v.qualifiedEntityName));F.length!==M.length&&a(h,{sortByColumns:F})}switch(B){case"groupBy":c(h,v.id);break;case"metrics":i(h,v.id);break;case"pivotBy":d(h,v.id);break;case"sortBy":m(h,v.id);break}}},[h,p,c,i,d,m,a]);return{getFieldsForContainer:p,setFieldsForContainer:f,updateLabel:j,handleAggregationChange:x,handleDateFormatChange:y,handleGranularityChange:g,handleAliasTemplateChange:C,handleValueAliasesChange:E,removeField:L,handleFieldClick:k,handleKpiComparisonTypeChange:R,handleKpiShowTrendlineChange:S,handleKpiTrendlineWindowChange:N,handleKpiTrendlineGranularityChange:b,handleKpiTargetValueChange:I,cardType:u}};function co({field:t}){return e.jsxs("div",{className:"w-64 bg-background p-0",children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"text-sm font-medium text-foreground",children:t.label||t.name}),e.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:t.dataType})]}),t.description&&e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:t.description}),e.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:t.name})})]})}function uo({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(j=>j.card),{handleFieldClick:u}=et(m),h={transform:s.CSS.Transform.toString(l),transition:o};s.getDataType(t.dataType);const p=j=>{const x=(j||"").toLowerCase();switch(s.getDataType(x)){case"number":return Ge;case"date":return s.Calendar;case"boolean":return ns;case"json":return it;case"geo":return ct;default:return Qe}},f=j=>{const x=(j||"").toLowerCase(),y=s.getDataType(x);return y==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(Qe,{className:"h-3 w-3"})}):y==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Ge,{className:"h-3 w-3"})}):y==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):y==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(ns,{className:"h-3 w-3"})}):y==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(it,{className:"h-3 w-3"})}):y==="geo"?e.jsx("div",{className:"bg-orange -100 flex size-6 shrink-0 items-center justify-center rounded-sm text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(ct,{className:"h-3 w-3"})}):y==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Tt,{className:"h-3 w-3"})}):null};return p(t.dataType),e.jsxs("div",{ref:r,style:h,...a,...n,className:`group/container overflow-hidden rounded-lg transition-all ${c?"scale-95 opacity-50":"border border-transparent hover:bg-muted"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:()=>u(t),children:[f(t.dataType),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/80 hover:text-foreground dark:text-muted-foreground ${i?"whitespace-normal break-words":"truncate"}`,children:t.label||t.name})})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:e.jsx(co,{field:t})})]})})]}),i&&e.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:e.jsx(s.Card,{className:"",children:e.jsxs(s.CardContent,{className:"space-y-2 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ft,{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(Fa,{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 mo(){const[t,a]=A.useState(""),[n,r]=A.useState("all"),l=s.useEditorStore(E=>E.card.dataSource),{columns:o=[],columnGroups:c=[],isLoading:i,error:d}=s.useColumns(),m=o.filter(E=>E.name.toLowerCase().includes(t.toLowerCase())||E.dataType.toLowerCase().includes(t.toLowerCase())||E.qualifiedEntityName&&E.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),u=E=>{if(E.dataType==="number"||E.dataType==="integer"||E.dataType==="float"||E.dataType==="decimal"||E.dataType==="currency")return"metrics";const R=s.getDataType(E.dataType);return["date","string","boolean"].includes(R)?"dimensions":R==="number"?"metrics":"dimensions"},p=(n==="all"?m:m.filter(E=>u(E)===n)).reduce((E,R)=>{const S=R.qualifiedEntityName||"Other Fields";return E[S]||(E[S]={label:s.toLabel(R.entityName),fields:[]}),E[S].fields.push(R),E},{}),j=Object.keys(p),x=m.filter(E=>u(E)==="dimensions").length,y=m.filter(E=>u(E)==="metrics").length,g=m.filter(E=>u(E)==="calculated").length,C=m.length>0;return i?e.jsx("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):d?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:d.message||"Failed to load column data"})]}):!l||!l.selectedEntities||l.selectedEntities.length===0?e.jsx(s.ScrollArea,{className:"h-[calc(100vh-200px)] w-[290px]",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-[calc(100vh-200px)] w-full grow flex-col gap-2 px-6 pb-6",children:[e.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[o.length>0&&e.jsxs("div",{className:"relative mb-4",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:t,onChange:E=>a(E.target.value)})]}),C&&e.jsx(s.Tabs,{defaultValue:"all",value:n,onValueChange:E=>r(E),className:"mb-4",children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-4",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children: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:y})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(Tt,{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(([E,R])=>{const S=c.find(N=>N.entityName===E)||{entityName:E,label:R.label};return e.jsxs(s.AccordionItem,{value:E,className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:e.jsxs("div",{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:R.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:R.fields.map(N=>e.jsx(uo,{field:N},N.id))})})]},E)})}),Object.keys(p).length===0&&o.length===0&&e.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[e.jsx("p",{children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]}),Object.keys(p).length===0&&o.length>0&&e.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),e.jsx(s.ScrollBar,{orientation:"horizontal"}),e.jsx(s.ScrollBar,{orientation:"vertical"})]})]})}function ho(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(mo,{})," "]})}function xo({initialJoinPlan:t,availableDataSources:a}){const[n,r]=A.useState(t),[l,o]=A.useState(new Set),c=()=>{const N=n.joins.length>0?Math.max(...n.joins.map(I=>I.sequence))+1:1,b={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:N,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...n,joins:[...n.joins,b]}),o(new Set([...l,b.id]))},i=N=>{r({...n,joins:n.joins.filter(b=>b.id!==N)}),o(new Set([...l].filter(b=>b!==N)))},d=(N,b)=>{var w,B;const I=n.joins.find(D=>D.id===N);if(!I)return;const k={...I,...b},L=n.joins.map(D=>D.id===N?k:D);if((w=k.source)!=null&&w.name&&((B=k.target)!=null&&B.name)&&k.joinKeyGroups[0].keys.length===0){const D=a.find(F=>{var O;return F.name===((O=k.source)==null?void 0:O.name)}),T=a.find(F=>{var O;return F.name===((O=k.target)==null?void 0:O.name)}),v={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(D==null?void 0:D.name)||"",entityName:(D==null?void 0:D.name)||"",entityType:(D==null?void 0:D.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(T==null?void 0:T.name)||"",entityName:(T==null?void 0:T.name)||"",entityType:(T==null?void 0:T.type)||"table"},operator:"="},M=[...k.joinKeyGroups];M[0]={...M[0],keys:[v]},k.joinKeyGroups=M,L[L.findIndex(F=>F.id===N)]=k}r({...n,joins:L})};return{joinPlan:n,expandedJoins:l,setJoinPlan:r,addJoin:c,removeJoin:i,updateJoin:d,moveJoinUp:N=>{const b=n.joins.findIndex(I=>I.id===N);if(b>0){const I=[...n.joins],k={...I[b]},L={...I[b-1]};I[b]=L,I[b-1]=k,I.forEach((B,D)=>{B.sequence=D+1});const w={...n,joins:I};r(w)}},moveJoinDown:N=>{const b=n.joins.findIndex(I=>I.id===N);if(b<n.joins.length-1){const I=[...n.joins],k={...I[b]},L={...I[b+1]};I[b]=L,I[b+1]=k,I.forEach((B,D)=>{B.sequence=D+1});const w={...n,joins:I};r(w)}},toggleJoinExpansion:N=>{const b=new Set(l);b.has(N)?b.delete(N):b.add(N),o(b)},getAvailableSourceEntities:N=>{if(n.joins.length===0)return a;const b=n.joins.findIndex(k=>k.id===N);if(b===0)return a;const I=new Set;return n.baseEntity.name&&I.add(n.baseEntity.name),n.joins.slice(0,b).forEach(k=>{I.add(k.source.name),I.add(k.target.name)}),a.filter(k=>I.has(k.name))},getAvailableTargetEntities:N=>a.filter(b=>b.name!==N),addJoinKeyGroup:N=>{const b=n.joins.find(k=>k.id===N);if(!b)return;const I=[...b.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];d(N,{joinKeyGroups:I})},updateGroupOperator:(N,b,I)=>{const k=n.joins.find(w=>w.id===N);if(!k)return;const L=[...k.joinKeyGroups];L[b]={...L[b],operator:I},d(N,{joinKeyGroups:L})},removeJoinKeyGroup:(N,b)=>{const I=n.joins.find(L=>L.id===N);if(!I)return;const k=[...I.joinKeyGroups];k.splice(b,1),d(N,{joinKeyGroups:k})},addJoinKey:(N,b)=>{const I=n.joins.find(D=>D.id===N);if(!I)return;const k=a.find(D=>D.name===I.source.name),L=a.find(D=>D.name===I.target.name),w=[...I.joinKeyGroups],B={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(k==null?void 0:k.name)||"",entityName:(k==null?void 0:k.name)||"",entityType:(k==null?void 0:k.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:"="};w[b]={...w[b],keys:[...w[b].keys,B]},d(N,{joinKeyGroups:w})},updateJoinKey:(N,b,I,k,L)=>{const w=n.joins.find(M=>M.id===N);if(!w)return;const B=a.find(M=>M.name===w.source.name),D=a.find(M=>M.name===w.target.name),T=[...w.joinKeyGroups],v=T[b].keys[I];k==="sourceColumnName"&&B?T[b].keys[I]={...v,source:{...v.source,name:L}}:k==="targetColumnName"&&D?T[b].keys[I]={...v,target:{...v.target,name:L}}:k==="operator"&&(T[b].keys[I]={...v,operator:L}),d(N,{joinKeyGroups:T})},removeJoinKey:(N,b,I)=>{const k=n.joins.find(w=>w.id===N);if(!k)return;const L=[...k.joinKeyGroups];L[b].keys.splice(I,1),d(N,{joinKeyGroups:L})},generateSQLPreview:()=>{const N=[...n.joins].sort((k,L)=>k.sequence-L.sequence),b=n.baseEntity;if(!b.name)return"SELECT * FROM table -- Please select a base entity";let I=`SELECT *
|
|
445
|
+
FROM ${b.name}`;return N.forEach(k=>{const L=a.find(D=>D.name===k.target.name);if(!L)return;const w=k.joinKeyGroups.filter(D=>D.keys&&D.keys.length>0).map(D=>{const T=D.keys.filter(v=>{var M,F,O,V;return((M=v.source)==null?void 0:M.name)&&((F=v.target)==null?void 0:F.name)&&((O=v.source)==null?void 0:O.entityName)&&((V=v.target)==null?void 0:V.entityName)}).map(v=>`${v.source.entityName}.${v.source.name} ${v.operator} ${v.target.entityName}.${v.target.name}`);return T.length>1?`(${T.join(` ${D.operator} `)})`:T[0]}).filter(Boolean),B=w.length>1?w.join(" OR "):w[0]||"condition_here";I+=`
|
|
431
446
|
${k.joinType} JOIN ${L.name}
|
|
432
|
-
ON ${B}`}),T},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(k=>!k.source.name||!k.target.name)||n.joins.some(k=>k.joinKeyGroups.some(L=>L.keys.length===0))||n.joins.some(k=>k.joinKeyGroups.some(L=>L.keys.some(w=>!w.source.name||!w.target.name||!w.operator))))}}function mo({joinPlan:t,availableDataSources:a,onSave:n,onRemove:r,onCancel:l}){const{setCardConfig:o}=s.useEditorActions();s.useEditorStore(w=>w.card.config);const{columnGroups:c}=s.useColumns(),{joinPlan:i,expandedJoins:d,setJoinPlan:m,addJoin:u,removeJoin:h,updateJoin:p,moveJoinUp:f,moveJoinDown:j,toggleJoinExpansion:x,getAvailableSourceEntities:y,getAvailableTargetEntities:g,addJoinKeyGroup:C,updateGroupOperator:E,removeJoinKeyGroup:R,addJoinKey:S,updateJoinKey:N,removeJoinKey:b,generateSQLPreview:T,isValidConfiguration:k}=uo({initialJoinPlan:t,availableDataSources:a}),L=w=>{const B=c.find(D=>D.entityName===w);return(B==null?void 0:B.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:i.baseEntity.name,onValueChange:w=>{const B=a.find(D=>D.name===w);m({...i,baseEntity:{connectionId:(B==null?void 0:B.connectionId)||"",connectionType:(B==null?void 0:B.connectionType)||"none",type:(B==null?void 0:B.type)||"table",name:w,database:B==null?void 0:B.database,schema:B==null?void 0:B.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:a.map(w=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:w.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:w.type}),w.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},w.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:T()})]}),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:u,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(w=>{const B=a.find(v=>v.name===w.source.name),D=a.find(v=>v.name===w.target.name),I=d.has(w.id);return e.jsxs(s.Card,{className:"border",children:[e.jsx(s.CardHeader,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{children:w.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",w.sequence,B&&D&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",B.name," → ",D.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>f(w.id),disabled:w.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>j(w.id),disabled:w.sequence===i.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>x(w.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:()=>h(w.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:w.source.name,onValueChange:v=>{const M=a.find(F=>F.name===v);p(w.id,{source:{connectionId:(M==null?void 0:M.connectionId)||"",connectionType:(M==null?void 0:M.connectionType)||"none",type:(M==null?void 0:M.type)||"table",name:v,database:M==null?void 0:M.database,schema:M==null?void 0:M.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:y(w.id).map(v=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:v.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:v.type}),v.name]})},v.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:w.joinType,onValueChange:v=>p(w.id,{joinType:v}),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Target"}),e.jsxs(s.Select,{value:w.target.name,onValueChange:v=>{const M=a.find(F=>F.name===v);p(w.id,{target:{connectionId:(M==null?void 0:M.connectionId)||"",connectionType:(M==null?void 0:M.connectionType)||"none",type:(M==null?void 0:M.type)||"table",name:v,database:M==null?void 0:M.database,schema:M==null?void 0:M.schema}})},disabled:!w.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:w.source.name?g(w.source.name).map(v=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:v.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:v.type}),v.name,v.name===w.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},v.name)):[]})]})]})]}),w.source.name&&w.target.name&&B&&D&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>C(w.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),w.joinKeyGroups.length===0?e.jsx("div",{className:"rounded-md border p-3 text-center text-sm text-gray-500",children:"No join conditions defined. Add condition groups to specify how data sources should be joined."}):e.jsx("div",{className:"space-y-4",children:w.joinKeyGroups.map((v,M)=>e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{children:["Group ",M+1]}),M>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(s.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Select,{value:v.operator,onValueChange:F=>E(w.id,M,F),children:[e.jsx(s.SelectTrigger,{className:"w-[100px]",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>R(w.id,M),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[v.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:v.keys.map((F,O)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[O>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:v.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:V=>N(w.id,M,O,"sourceColumnName",V),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:L(w.source.name).map(V=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:V.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:V.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:V.dataType})]})},V.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:F.operator,onValueChange:V=>N(w.id,M,O,"operator",V),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:V=>N(w.id,M,O,"targetColumnName",V),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:L(w.target.name).map(V=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:V.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:V.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:V.dataType})]})},V.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>b(w.id,M,O),children:e.jsx(s.X,{className:"size-3.5"})})]},F.id||O))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>S(w.id,M),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},v.id))})]})]})]},w.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),l()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:l,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>n(i),disabled:!k(),children:"Save"})]})]})}function vt({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(mo,{joinPlan:r,availableDataSources:l,onSave:c,onCancel:i,onRemove:o})]}),t]})}function ho({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 xo(){var u,h;const t=s.useEditorStore(p=>p.card),a=s.useEditorStore(p=>p.actions.updateCardConfig),n=((u=t==null?void 0:t.config)==null?void 0:u.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[r,l]=A.useState(!1),o=((h=t==null?void 0:t.dataSource)==null?void 0:h.selectedEntities)||[],c=p=>{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,y)=>x.sequence-y.sequence),f=n.baseEntity;if(!f.name)return"SELECT * FROM table -- Please select a base entity";let j=`SELECT *
|
|
433
|
-
FROM ${f.name}`;return p.forEach(x=>{const y=o.find(E=>E.name===x.target.name);if(!y)return;const g=x.joinKeyGroups.filter(E=>E.keys&&E.keys.length>0).map(E=>{const R=E.keys.filter(S=>{var N,b,
|
|
447
|
+
ON ${B}`}),I},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(k=>!k.source.name||!k.target.name)||n.joins.some(k=>k.joinKeyGroups.some(L=>L.keys.length===0))||n.joins.some(k=>k.joinKeyGroups.some(L=>L.keys.some(w=>!w.source.name||!w.target.name||!w.operator))))}}function po({joinPlan:t,availableDataSources:a,onSave:n,onRemove:r,onCancel:l}){const{setCardConfig:o}=s.useEditorActions();s.useEditorStore(w=>w.card.config);const{columnGroups:c}=s.useColumns(),{joinPlan:i,expandedJoins:d,setJoinPlan:m,addJoin:u,removeJoin:h,updateJoin:p,moveJoinUp:f,moveJoinDown:j,toggleJoinExpansion:x,getAvailableSourceEntities:y,getAvailableTargetEntities:g,addJoinKeyGroup:C,updateGroupOperator:E,removeJoinKeyGroup:R,addJoinKey:S,updateJoinKey:N,removeJoinKey:b,generateSQLPreview:I,isValidConfiguration:k}=xo({initialJoinPlan:t,availableDataSources:a}),L=w=>{const B=c.find(D=>D.entityName===w);return(B==null?void 0:B.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:i.baseEntity.name,onValueChange:w=>{const B=a.find(D=>D.name===w);m({...i,baseEntity:{connectionId:(B==null?void 0:B.connectionId)||"",connectionType:(B==null?void 0:B.connectionType)||"none",type:(B==null?void 0:B.type)||"table",name:w,database:B==null?void 0:B.database,schema:B==null?void 0:B.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:a.map(w=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:w.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:w.type}),w.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},w.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:I()})]}),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:u,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(w=>{const B=a.find(v=>v.name===w.source.name),D=a.find(v=>v.name===w.target.name),T=d.has(w.id);return e.jsxs(s.Card,{className:"border",children:[e.jsx(s.CardHeader,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{children:w.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",w.sequence,B&&D&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",B.name," → ",D.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>f(w.id),disabled:w.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>j(w.id),disabled:w.sequence===i.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>x(w.id),children:T?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>h(w.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),T&&e.jsxs(s.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Source"}),e.jsxs(s.Select,{value:w.source.name,onValueChange:v=>{const M=a.find(F=>F.name===v);p(w.id,{source:{connectionId:(M==null?void 0:M.connectionId)||"",connectionType:(M==null?void 0:M.connectionType)||"none",type:(M==null?void 0:M.type)||"table",name:v,database:M==null?void 0:M.database,schema:M==null?void 0:M.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:y(w.id).map(v=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:v.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:v.type}),v.name]})},v.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:w.joinType,onValueChange:v=>p(w.id,{joinType:v}),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Target"}),e.jsxs(s.Select,{value:w.target.name,onValueChange:v=>{const M=a.find(F=>F.name===v);p(w.id,{target:{connectionId:(M==null?void 0:M.connectionId)||"",connectionType:(M==null?void 0:M.connectionType)||"none",type:(M==null?void 0:M.type)||"table",name:v,database:M==null?void 0:M.database,schema:M==null?void 0:M.schema}})},disabled:!w.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:w.source.name?g(w.source.name).map(v=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:v.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:v.type}),v.name,v.name===w.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},v.name)):[]})]})]})]}),w.source.name&&w.target.name&&B&&D&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>C(w.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),w.joinKeyGroups.length===0?e.jsx("div",{className:"rounded-md border p-3 text-center text-sm text-gray-500",children:"No join conditions defined. Add condition groups to specify how data sources should be joined."}):e.jsx("div",{className:"space-y-4",children:w.joinKeyGroups.map((v,M)=>e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{children:["Group ",M+1]}),M>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(s.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Select,{value:v.operator,onValueChange:F=>E(w.id,M,F),children:[e.jsx(s.SelectTrigger,{className:"w-[100px]",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>R(w.id,M),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[v.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:v.keys.map((F,O)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[O>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:v.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:V=>N(w.id,M,O,"sourceColumnName",V),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:L(w.source.name).map(V=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:V.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:V.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:V.dataType})]})},V.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:F.operator,onValueChange:V=>N(w.id,M,O,"operator",V),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:V=>N(w.id,M,O,"targetColumnName",V),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:L(w.target.name).map(V=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:V.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:V.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:V.dataType})]})},V.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>b(w.id,M,O),children:e.jsx(s.X,{className:"size-3.5"})})]},F.id||O))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>S(w.id,M),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},v.id))})]})]})]},w.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),l()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:l,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>n(i),disabled:!k(),children:"Save"})]})]})}function vt({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(po,{joinPlan:r,availableDataSources:l,onSave:c,onCancel:i,onRemove:o})]}),t]})}function fo({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 go(){var u,h;const t=s.useEditorStore(p=>p.card),a=s.useEditorStore(p=>p.actions.updateCardConfig),n=((u=t==null?void 0:t.config)==null?void 0:u.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[r,l]=A.useState(!1),o=((h=t==null?void 0:t.dataSource)==null?void 0:h.selectedEntities)||[],c=p=>{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,y)=>x.sequence-y.sequence),f=n.baseEntity;if(!f.name)return"SELECT * FROM table -- Please select a base entity";let j=`SELECT *
|
|
448
|
+
FROM ${f.name}`;return p.forEach(x=>{const y=o.find(E=>E.name===x.target.name);if(!y)return;const g=x.joinKeyGroups.filter(E=>E.keys&&E.keys.length>0).map(E=>{const R=E.keys.filter(S=>{var N,b,I,k;return((N=S.source)==null?void 0:N.name)&&((b=S.target)==null?void 0:b.name)&&((I=S.source)==null?void 0:I.entityName)&&((k=S.target)==null?void 0:k.entityName)}).map(S=>`${S.source.entityName}.${S.source.name} ${S.operator} ${S.target.entityName}.${S.target.name}`);return R.length>1?`(${R.join(` ${E.operator} `)})`:R[0]}).filter(Boolean),C=g.length>1?g.join(" OR "):g[0]||"condition_here";j+=`
|
|
434
449
|
${x.joinType} JOIN ${y.name}
|
|
435
|
-
ON ${C}`}),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(ho,{joins:n.joins,baseEntityId:n.baseEntity.name,availableDataSources:o,generateSQLPreview:m})})]})}),e.jsx(vt,{open:r,onOpenChange:l,joinPlan:n,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsx("div",{})})]}),n.joins.length===0&&e.jsx(vt,{open:r,onOpenChange:l,joinPlan:n,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsxs(s.Button,{onClick:()=>l(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function po({open:t,onOpenChange:a}){const[n,r]=A.useState([]),{updateDataSource:l}=s.useEditorActions(),o=s.useDashboardStore(x=>x.dashboard.aiContext),c=(o==null?void 0:o.selectedEntities)||[];A.useEffect(()=>{t&&r([])},[t]);const i=x=>{r(y=>y.some(C=>C.name===x.name&&C.type===x.type)?y.filter(C=>!(C.name===x.name&&C.type===x.type)):[...y,x])},d=()=>{r([...c])},m=()=>{r([])},u=()=>{if(n.length===0)return;const x=n[0],y=x.connectionId||"",g=x.connectionType||"",E=n.some(S=>S.type==="dataset")?"semanticDomain":"database";l({connectionId:y,connectionType:g,mode:E,selectedEntities:n}),a(!1)},h=x=>{switch(x.type){case"table":return e.jsx(s.Table,{className:"h-4 w-4"});case"view":return e.jsx(Oa,{className:"h-4 w-4"});case"model":return e.jsx(ra,{className:"h-4 w-4"});case"dataset":return e.jsx(s.Database,{className:"h-4 w-4"});case"file":case"url":case"upload":return e.jsx(s.FileText,{className:"h-4 w-4"});default:return e.jsx(s.Database,{className:"h-4 w-4"})}},p=x=>"label"in x&&x.label?x.label:x.name,f=x=>{if("description"in x&&x.description)return x.description;const y=[];return x.database&&y.push(x.database),x.schema&&y.push(x.schema),x.name&&y.push(x.name),y.join(".")},j=x=>n.some(y=>y.name===x.name&&y.type===x.type);return c.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"max-w-md",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"No Data Available"}),e.jsx(s.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{onClick:()=>a(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(s.DialogDescription,{children:"Choose entities from the dashboard's context"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"outline",size:"sm",onClick:d,disabled:n.length===c.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:m,disabled:n.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[n.length," of ",c.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:c.map((x,y)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",j(x)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:j(x),onCheckedChange:()=>i(x)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:h(x)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:p(x)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:f(x)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:x.type})]},`${x.type}-${x.name}-${y}`))})})]}),e.jsx(s.DialogFooter,{children:e.jsx("div",{className:"flex w-full justify-between",children:e.jsxs("div",{className:"flex grow justify-end gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:u,disabled:n.length===0,children:["Select"," ",n.length>0?`(${n.length})`:""]})]})})})]})})}function fo({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 go({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 jo({isVisible:t,onToggleVisibility:a}){const[n,r]=A.useState(!1),[l,o]=A.useState(!1),[c,i]=A.useState(!0),d=s.useEditorStore(p=>p.card.dataSource);Ne();const{updateDataSource:m}=s.useEditorActions(),u={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},h={...u,...d,selectedEntities:(d==null?void 0:d.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[e.jsxs("div",{children:[e.jsx("div",{className:s.cn("p-4 px-6",{"pb-0":!c}),children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex cursor-pointer items-center gap-2",children:[e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Data Source"}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>i(!c),className:"h-6 w-6 p-0",children:c?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronRight,{className:"h-4 w-4"})})]}),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 ${c?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[h.selectedEntities.length>0&&e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[h.selectedEntities.slice(0,3).map((p,f)=>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(p),e.jsx("button",{onClick:j=>{j.stopPropagation();const x=h.selectedEntities.filter(y=>!(y.name===p.name&&y.type===p.type));m({...u,...d,selectedEntities:x})},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(fo,{entity:p})]},`${p.type}-${p.name}-${f}`)),h.selectedEntities.length>3&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:["+",h.selectedEntities.length-3," more"]})}),e.jsx(go,{entities:h.selectedEntities.slice(3)})]})]})}),e.jsx(xo,{})]})]}),e.jsx(co,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(d==null?void 0:d.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:r,dataSource:h,fallbackDataSource:u}),e.jsx(po,{open:l,onOpenChange:o})]})}const ts=[{id:"table",icon:_e,label:"Table"},{id:"pivotTable",icon:_e,label:"Pivot Table"},{id:"aggregateTable",icon:_e,label:"Aggregate Table"},{id:"bar",icon:ds,label:"Bar Chart"},{id:"line",icon:us,label:"Line Chart"},{id:"area",icon:It,label:"Area Chart"},{id:"stackedBar",icon:Ls,label:"Stacked Bar Chart"},{id:"combo",icon:ea,label:"Combo Chart"},{id:"stackedLine",icon:Ws,label:"Stacked Line Chart"},{id:"scatter",icon:Os,label:"Scatter Chart"},{id:"bubble",icon:Ks,label:"Bubble Chart"},{id:"pie",icon:ms,label:"Pie Chart"},{id:"doughnut",icon:Bs,label:"Doughnut Chart"},{id:"funnel",icon:Qs,label:"Funnel Chart"},{id:"radar",icon:Ps,label:"Radar Chart"},{id:"polarArea",icon:Hs,label:"Polar Area Chart"},{id:"tornado",icon:zs,label:"Tornado Chart"},{id:"range",icon:Rs,label:"Range Chart"},{id:"kpi",icon:Js,label:"KPI"},{id:"text",icon:Et,label:"Text"},{id:"map",icon:Fs,label:"Map"}],st=t=>{const a=t.toLowerCase();for(const n of ts)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},yo="chart-selector-standard-first";function bo(){const[t,a]=s.useLocalStorageState(yo,!0);return{standardFirst:t,updatePreference:a}}const Nt=({pluginVisual:t,index:a,onSelect:n})=>{const r=xs(t.icon||""),l=t.name.charAt(0).toUpperCase(),o=st(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}`)},Ct=["default","standardPlugin","customPlugin"];function vo({selectedChart:t,onChartChange:a}){var R;const[n,r]=A.useState(!1),{data:l}=pn();bo();const c=((R=s.useEditorStore(S=>S.card).customCardPreferences)==null?void 0:R.url)||"";_s(c);const{setCardType:i,setCardPreferences:d,setIsDevMode:m}=s.useEditorStore(S=>S.actions),{setCardCustomCfg:u,setCustomCardPreferences:h,setQueryConfig:p}=s.useEditorActions(),[f,j]=s.useLocalStorageState("chart-section-active",null),x=A.useMemo(()=>f?[f,...Ct.filter(S=>S!==f)]:Ct,[f]);function y(S){u(null),d({}),i(S),["custom","text","map"].includes(S)&&(m(!0),p(void 0)),a(S),r(!1)}function g(S){u(null),d({}),i("custom"),h({type:"component",visualType:"single",url:S.url,componentName:S.name,icon:S.icon,pluginChartType:S.chartType}),p(void 0),a("custom"),r(!1)}const C=()=>{var N;if(t==="custom"){const b=s.useEditorStore.getState().card;return((N=b==null?void 0:b.customCardPreferences)==null?void 0:N.componentName)||"Custom Visual"}const S=ts.find(b=>b.id===t);return(S==null?void 0:S.label)||"Select chart type"},E=()=>{var N,b;if(t==="custom"){const T=s.useEditorStore.getState().card,k=(N=T==null?void 0:T.customCardPreferences)==null?void 0:N.icon,L=(b=T==null?void 0:T.customCardPreferences)==null?void 0:b.componentName;if(k&&L)return e.jsx(No,{icon:k,componentName:L});if(L){const w=st(L);if(w)return w}return e.jsx(He,{className:"h-4 w-4"})}const S=ts.find(T=>T.id===t);if(S){const T=S.icon;return e.jsx(T,{className:"h-4 w-4"})}return e.jsx(He,{className:"h-4 w-4"})};return e.jsx("div",{className:"mb-6",children:e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[E(),e.jsx("span",{children:C()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search chart types..."}),e.jsxs(s.CommandList,{className:"mb-2 max-h-[300px]",children:[e.jsx(s.CommandEmpty,{children:"No chart type found."}),x.map(S=>{if(S==="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:f==="default",onCheckedChange:N=>j(N?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:ts.map(N=>{const b=N.icon;return e.jsx(s.CommandItem,{value:`${N.label} ${N.id} chart graph visualization`,onSelect:()=>y(N.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(b,{className:"h-4 w-4"}),e.jsx("span",{children:N.label})]})},N.id)})},"default");if(S==="standardPlugin"){const N=l.filter(b=>b.pluginType==="standard");return N.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsx("p",{children:"Standard Visuals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:f==="standardPlugin",onCheckedChange:b=>j(b?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:N.filter(b=>b.componentType==="chart").map((b,T)=>e.jsx(Nt,{pluginVisual:b,index:T,onSelect:()=>g(b)},`${b.url}-${b.name}-${T}`))},"standardPlugin"):null}if(S==="customPlugin"){const N=l.filter(b=>b.pluginType==="custom");return N.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-2",children:["Custom Visuals",e.jsx(s.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),e.jsx(s.TooltipContent,{side:"right",children:"External visuals that are specific to your project"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:f==="customPlugin",onCheckedChange:b=>j(b?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:N.map((b,T)=>e.jsx(Nt,{pluginVisual:b,index:T,onSelect:()=>g(b)},`${b.url}-${b.name}-${T}`))},"customPlugin"):null}return null})]})]})})]})})}const No=({icon:t,componentName:a})=>{const n=xs(),r=st(a);return n?e.jsx(n,{className:"h-4 w-4"}):r||e.jsx(He,{className:"h-4 w-4"})},En=({dataType:t})=>{const a=s.getDataType(t);return a==="string"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(Qe,{className:"h-3 w-3"})}):a==="number"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Ge,{className:"h-3 w-3"})}):a==="date"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):a==="boolean"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(ns,{className:"h-3 w-3"})}):e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Qe,{className:"h-3 w-3"})})};function Co({aliasTemplate:t,onAliasTemplateChange:a}){var d;const[n,r]=A.useState(t),[l,o]=A.useState(!1),c=(d=s.useEditorStore(m=>{var u;return(u=m.card.config)==null?void 0:u.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 So({valueAliases:t,onValueAliasesChange:a}){const[n,r]=A.useState(null),[l,o]=A.useState(""),[c,i]=A.useState(""),d=()=>{a({...t,"":""})},m=h=>{const p={...t};delete p[h],a(p)},u=h=>{const p={...t};delete p[h],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(([h,p],f)=>e.jsx("div",{className:"flex items-center gap-2",children:n===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:l,onChange:j=>o(j.target.value),className:"h-8 w-24 text-xs",onPointerDown:j=>j.stopPropagation(),onKeyDown:j=>{j.key==="Enter"?u(h):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"?u(h):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:()=>u(h),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(p)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:p,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(p)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>m(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+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 je({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)},u=()=>{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:h=>{c(h.target.value),d(!0)},onFocus:()=>d(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&i&&o!==t?m():h.key==="Escape"&&u()},"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:u,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function wo({field:t,zone:a,index:n,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:o=!1,cardType:c}){var at;const{attributes:i,listeners:d,setNodeRef:m,transform:u,transition:h,isDragging:p}=s.useSortable({id:t.id}),f=s.useEditorStore(J=>J.card),{updateLabel:j,handleAggregationChange:x,handleDateFormatChange:y,handleGranularityChange:g,handleAliasTemplateChange:C,handleValueAliasesChange:E,removeField:R,handleKpiComparisonTypeChange:S,handleKpiShowTrendlineChange:N,handleKpiTrendlineWindowChange:b,handleKpiTrendlineGranularityChange:T,handleKpiTargetValueChange:k}=et(f),[L,w]=A.useState(!1),[B,D]=A.useState(t.dateFormat||"YYYY-MM-DD"),[I,v]=A.useState(t.customFormat||""),[M,F]=A.useState(!!t.customFormat),[O,V]=A.useState(t.granularity||"day"),[_,W]=A.useState(t.aliasTemplate||""),[Q,U]=A.useState(t.valueAliases||{}),q=J=>{J==="custom"?F(!0):(F(!1),D(J),a==="groupBy"&&y(n,J,""))},Y=J=>{v(J),a==="groupBy"&&y(n,"custom",J)},$=J=>{var qe;V(J);const xe=(qe=K(J)[0])==null?void 0:qe.value;xe&&!M&&(D(xe),a==="groupBy"&&y(n,xe,"")),a==="groupBy"&&g(n,J)},P=J=>{W(J),a==="metrics"&&C(n,J)},G=J=>{U(J),a==="metrics"&&E(n,J)},H=J=>{j(a,n,J)},Z=()=>{R(a,n)},se={transform:s.CSS.Transform.toString(u),transition:h},ae=s.getDataType(t.dataType),te=ae==="date",le=c==="kpi",K=J=>{switch(J){case"day":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"custom",label:"Custom Format..."}];case"week":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"Week of MMM DD, YYYY",label:"Week of Jan 15, 2024"},{value:"Week of MMMM DD, YYYY",label:"Week of January 15, 2024"},{value:"YYYY-WW",label:"2024-W03 (YYYY-WW)"},{value:"custom",label:"Custom Format..."}];case"month":return[{value:"MMM YYYY",label:"Jan 2024 (MMM YYYY)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MM/YYYY",label:"01/2024 (MM/YYYY)"},{value:"YYYY MMM",label:"2024 Jan (YYYY MMM)"},{value:"custom",label:"Custom Format..."}];case"quarter":return[{value:"Q1 YYYY",label:"Q1 2024 (Q1 YYYY)"},{value:"YYYY Q1",label:"2024 Q1 (YYYY Q1)"},{value:"1st Quarter YYYY",label:"1st Quarter 2024"},{value:"YYYY-Q1",label:"2024-Q1 (YYYY-Q1)"},{value:"Quarter 1, YYYY",label:"Quarter 1, 2024"},{value:"custom",label:"Custom Format..."}];case"year":return[{value:"YYYY",label:"2024 (YYYY)"},{value:"YY",label:"24 (YY)"},{value:"custom",label:"Custom Format..."}];default:return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"custom",label:"Custom Format..."}]}},z=K(O),X=!le&&a!=="pivotBy",oe=te&&a==="groupBy",Ce=!le&&te&&a==="groupBy",Te=le&&te&&a==="groupBy",ne=le&&a==="metrics"&&((at=f.config)==null?void 0:at.comparisonType)==="target",ie=a==="metrics",ce=()=>e.jsx("div",{onPointerDown:J=>{J.stopPropagation()},className:"cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),An=()=>X?e.jsx(je,{value:t.label??"",onSave:H,placeholder:"Display label...",type:"text"}):null,nt=()=>oe?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:O,onValueChange:$,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsx(s.SelectContent,{children:["day","week","month","quarter","year"].map(J=>e.jsx(s.SelectItem,{className:"text-xs",value:J,children:s.toTitleCase(J)},J))})]})]}):null,Mn=()=>Ce?e.jsxs(e.Fragment,{children:[nt(),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:M?"custom":B,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:z.map(J=>e.jsx(s.SelectItem,{className:"text-xs",value:J.value,children:J.label},J.value))})]}),M&&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:J=>{J.stopPropagation(),Y(J.target.value)},onClick:J=>J.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,Ln=()=>{var J,ge,xe,qe,rt;return 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:"Comparison Type"}),e.jsxs(s.Select,{value:((J=f.config)==null?void 0:J.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:((ge=f.config)==null?void 0:ge.showTrendline)||!1,onCheckedChange:N})]})}),((xe=f.config)==null?void 0:xe.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:((qe=f.config)==null?void 0:qe.trendlineWindow)||30,onChange:Bn=>{const Fn=parseInt(Bn.target.value)||30;b(Fn)},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:((rt=f.config)==null?void 0:rt.trendlineGranularity)||"day",onValueChange:T,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},Rn=()=>{var J,ge;return ne?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(je,{value:((J=f.config)==null?void 0:J.targetValue)!==void 0&&((ge=f.config)==null?void 0:ge.targetValue)!==null?String(f.config.targetValue):"",onSave:xe=>{!isNaN(Number(xe))&&xe!==null?k(Number(xe)):k(0)},placeholder:"Enter target value...",type:"text"})]}):null},On=()=>ie?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:J=>{x(n,J)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsx(wn,{column:t}),o&&e.jsxs(e.Fragment,{children:[e.jsx(Co,{aliasTemplate:_,onAliasTemplateChange:P}),e.jsx(So,{valueAliases:Q,onValueAliasesChange:G})]})]}):null;return e.jsxs("div",{ref:m,style:se,...i,...d,className:`group mx-auto flex w-full flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${p?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(En,{dataType:ae}),e.jsx(Xs,{className:"w-[140px] 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:J=>{J.stopPropagation(),w(!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:J=>{J.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const ge=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",ge),l(ge)},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:J=>{J.stopPropagation(),Z()},children:e.jsx(s.X,{className:"h-3 w-3"})})]}),L&&e.jsxs("div",{className:"space-y-3",children:[ce(),An(),c==="kpi"&&nt(),Mn(),Ln(),Rn(),On()]})]})}function Do({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 es({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),u=s.useEditorStore(j=>j.card.type),h=a.length>0,p=(j,x)=>{var g;!((g=m.config)!=null&&g.sortByColumns)||m.config.sortByColumns.findIndex(C=>C.id===j)===-1||d(m.id,j,{direction:x})};if(t==="sortBy"&&l===!1)return null;const f=t!=="sortBy"&&u!=="kpi";return e.jsxs("div",{className:"mb-4 w-full",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:n}),f&&e.jsx(Do,{concept:t})]}),e.jsx("div",{ref:i,className:`min-h-[60px] rounded-lg border-2 border-dashed p-2 transition-all ${c?"border-blue-500 bg-blue-50 dark:bg-blue-950":h?"border-blue-200 bg-blue-50/30 dark:border-blue-800 dark:bg-blue-950/30":"border-muted-foreground/20 bg-background"}`,children:a.length===0?e.jsx("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:r}):e.jsx(s.SortableContext,{items:a.map(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(wo,{field:j,zone:t,index:x,sortDirection:g,onSortDirectionChange:C=>p(j.id,C),hasPivotColumns:o,cardType:u})})},j.id)})})})})]})}function ko({color:t,onColorChange:a,onClose:n}){const[r,l]=A.useState(0),[o,c]=A.useState(100),[i,d]=A.useState(50),[m,u]=A.useState(t);A.useEffect(()=>{const y=St(t);if(y){const g=wt(y.r,y.g,y.b);l(g.h),c(g.s),d(g.l),u(t)}},[t]);const h=y=>{l(y),f(y,o,i)},p=y=>{const g=y.currentTarget.getBoundingClientRect(),C=Math.max(0,Math.min(1,(y.clientX-g.left)/g.width)),E=Math.max(0,Math.min(1,(y.clientY-g.top)/g.height)),R=C*100,S=(1-E)*100;c(R),d(S),f(r,R,S)},f=(y,g,C)=>{const E=To(y,g,C),R=Eo(E.r,E.g,E.b);u(R)},j=y=>{if(u(y),/^#[0-9A-Fa-f]{6}$/.test(y)){const g=St(y);if(g){const C=wt(g.r,g.g,g.b);l(C.h),c(C.s),d(C.l)}}},x=()=>{/^#[0-9A-Fa-f]{6}$/.test(m)&&(a(m),n())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:p,onMouseMove:y=>{y.buttons===1&&p(y)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${o}%`,top:`${100-i}%`,backgroundColor:m}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:y=>h(Number(y.target.value)),className:"w-full h-4 rounded-lg appearance-none cursor-pointer",style:{background:"linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"}})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"HEX"}),e.jsx(s.Input,{value:m,onChange:y=>j(y.target.value),placeholder:"#000000",className:"font-mono"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:t}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:m}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(s.Button,{variant:"outline",onClick:n,children:"Cancel"}),e.jsx(s.Button,{onClick:x,children:"OK"})]})]})}function St(t){const a=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return a?{r:parseInt(a[1],16),g:parseInt(a[2],16),b:parseInt(a[3],16)}:null}function Eo(t,a,n){return"#"+((1<<24)+(t<<16)+(a<<8)+n).toString(16).slice(1)}function wt(t,a,n){t/=255,a/=255,n/=255;const r=Math.max(t,a,n),l=Math.min(t,a,n);let o=0,c=0;const i=(r+l)/2;if(r!==l){const d=r-l;switch(c=i>.5?d/(2-r-l):d/(r+l),r){case t:o=((a-n)/d+(a<n?6:0))/6;break;case a:o=((n-t)/d+2)/6;break;case n:o=((t-a)/d+4)/6;break}}return{h:Math.round(o*360),s:Math.round(c*100),l:Math.round(i*100)}}function To(t,a,n){t/=360,a/=100,n/=100;let r,l,o;if(a===0)r=l=o=n;else{const c=(m,u,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?m+(u-m)*6*h:h<.5?u:h<.6666666666666666?m+(u-m)*(.6666666666666666-h)*6:m),i=n<.5?n*(1+a):n+a-n*a,d=2*n-i;r=c(d,i,t+1/3),l=c(d,i,t),o=c(d,i,t-1/3)}return{r:Math.round(r*255),g:Math.round(l*255),b:Math.round(o*255)}}const Io=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function Ao(){var E,R,S,N,b,T,k,L,w,B;const t=s.useEditorStore(D=>D.card),a=s.useEditorStore(D=>{var I;return(I=D.card)==null?void 0:I.preferences}),{setCardPreferences:n,updateCardInFrame:r}=s.useEditorActions(),{data:l}=s.useDashboardCardQuery(t),[o,c]=A.useState({}),[i,d]=A.useState(null),[m,u]=A.useState(null),h=A.useMemo(()=>{var v,M,F,O,V;if(!(l!=null&&l.records)||l.records.length===0)return[];const D=(t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine",I=((v=t==null?void 0:t.config)==null?void 0:v.pivotByColumns)&&t.config.pivotByColumns.length>0;if(D&&I){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const _=new Set;return l.pivotSchema.forEach(W=>{W.alias&&_.add(W.alias)}),Array.from(_)}if(l.records.length>0){const _=l.records[0],W=Object.keys(_),Q=new Set;(M=t==null?void 0:t.config)!=null&&M.groupByColumns&&t.config.groupByColumns.forEach(Y=>{Q.add(Y.label||Y.name),Q.add(Y.alias||Y.name)});const U=new Set;return(F=t==null?void 0:t.config)!=null&&F.metricColumns&&t.config.metricColumns.forEach(Y=>{const $=Y.alias||Y.name;U.add($),U.add(`${$}_count`),U.add(`${$}_sum`),U.add(`${$}_avg`),U.add(`${$}_min`),U.add(`${$}_max`);const P=Y.entityName||Y.qualifiedEntityName;P&&(U.add(`${P}_${$}`),U.add(`${P}_${$}_count`))}),W.filter(Y=>!Q.has(Y)&&!U.has(Y))}}if((V=(O=t==null?void 0:t.config)==null?void 0:O.groupByColumns)!=null&&V.length){const _=t.config.groupByColumns[0],W=_.label||_.name,Q=new Set;return l.records.forEach(U=>{const q=U[W];q!=null&&Q.add(String(q))}),Array.from(Q)}return[]},[l,(E=t==null?void 0:t.config)==null?void 0:E.groupByColumns,(R=t==null?void 0:t.config)==null?void 0:R.pivotByColumns,(S=t==null?void 0:t.config)==null?void 0:S.metricColumns,t==null?void 0:t.type]),p=A.useMemo(()=>s.getDefaultChartColors(),[]);A.useEffect(()=>{const D={};h.forEach((I,v)=>{D[I]=s.getColorForValue(I,v,a==null?void 0:a.colorConfig)}),c(D)},[h,a==null?void 0:a.colorConfig,p]);const f=(D,I)=>{const v={...o,[D]:I};c(v);const M={...a||{},colorConfig:{segments:v}};n(M);const F={...t,preferences:M};r(F)},j=(D,I)=>{var _;const v=p[I%p.length],{[D]:M,...F}=((_=a==null?void 0:a.colorConfig)==null?void 0:_.segments)||{},O={...a||{},colorConfig:{segments:F}};n(O);const V={...t,preferences:O};r(V),c(W=>({...W,[D]:v}))};if(!h.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((b=(N=t==null?void 0:t.config)==null?void 0:N.groupByColumns)==null?void 0:b.length)||((k=(T=t==null?void 0:t.config)==null?void 0:T.pivotByColumns)==null?void 0:k.length):(w=(L=t==null?void 0:t.config)==null?void 0:L.groupByColumns)==null?void 0:w.length)||["table","kpi","text","custom"].includes(t.type))return null;const g=()=>{const D={...a||{},colorConfig:{segments:{}}};n(D);const I={...t,preferences:D};r(I);const v={};h.forEach((M,F)=>{v[M]=s.getColorForValue(M,F,void 0)}),c(v)},C=Object.keys(((B=a==null?void 0:a.colorConfig)==null?void 0:B.segments)||{}).length>0;return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-sm font-medium",children:"Colors"}),C&&e.jsxs("button",{className:"flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:g,children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset All"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Assign colors to chart segments"})]}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:h.map((D,I)=>{const v=s.isDefaultColor(o[D],I);return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:i===D,onOpenChange:M=>d(M?D:null),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"h-5 w-5 shrink-0 rounded border border-input shadow-sm transition-colors hover:border-gray-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",style:{backgroundColor:o[D]}})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-3",children:e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Theme Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:p.slice(0,10).map((M,F)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",o[D]===M?"border-gray-900":"border-transparent"),style:{backgroundColor:M},onClick:()=>{f(D,M),d(null)},children:[F===I%p.length&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-white/90 px-0.5 text-[8px] font-bold text-gray-900 shadow-sm",children:"D"})}),e.jsx("span",{className:"sr-only",children:M})]},`default-${F}`))})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Popular Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:Io.map((M,F)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",o[D]===M?"border-2 border-gray-900":M==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:M},onClick:()=>{f(D,M),d(null)},children:e.jsx("span",{className:"sr-only",children:M})},`preset-${F}`))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsx("button",{className:"text-sm font-medium text-blue-600 hover:text-blue-700",onClick:()=>{u({value:D,color:o[D]}),d(null)},children:"Custom color"}),!v&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{j(D,I),d(null)},children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:D}),v&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(default)"})]},D)})}),m&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>u(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(ko,{color:m.color,onColorChange:D=>{f(m.value,D),u(null)},onClose:()=>u(null)})})]})]})}function Dt({axis:t,label:a,type:n,config:r,onChange:l}){var y,g,C,E,R,S,N,b,T,k,L,w,B,D,I,v,M,F;const o=(O,V)=>{l({...r,[O]:V})},c=(O,V)=>{var _,W;l({...r,name:{enabled:O==="enabled"?V:((_=r==null?void 0:r.name)==null?void 0:_.enabled)??!1,text:O==="text"?V:(W=r==null?void 0:r.name)==null?void 0:W.text}})},i=(O,V)=>{var _,W;l({...r,labels:{enabled:O==="enabled"?V:((_=r==null?void 0:r.labels)==null?void 0:_.enabled)??!0,rotation:O==="rotation"?V:(W=r==null?void 0:r.labels)==null?void 0:W.rotation}})},d=(O,V)=>{l({...r,scale:{...r==null?void 0:r.scale,[O]:V===""?"auto":Number(V)}})},m=O=>{l({...r,format:O,formatOptions:void 0})},u=(O,V)=>{l({...r,formatOptions:{...r==null?void 0:r.formatOptions,[O]:V}})},h=t==="x"?["auto","top","bottom"]:["auto","left","right"],p=["auto","0","45","90","-45","-90"],f=["auto","number","currency","percent"],j=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"GBP",label:"GBP - British Pound"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"INR",label:"INR - Indian Rupee"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"},{value:"CHF",label:"CHF - Swiss Franc"},{value:"SEK",label:"SEK - Swedish Krona"},{value:"NZD",label:"NZD - New Zealand Dollar"},{value:"MXN",label:"MXN - Mexican Peso"},{value:"SGD",label:"SGD - Singapore Dollar"},{value:"HKD",label:"HKD - Hong Kong Dollar"},{value:"NOK",label:"NOK - Norwegian Krone"},{value:"KRW",label:"KRW - South Korean Won"}],x=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"en-IN",label:"English (India)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"},{value:"ja-JP",label:"Japanese"},{value:"ko-KR",label:"Korean"},{value:"ru-RU",label:"Russian"},{value:"ar-SA",label:"Arabic"},{value:"hi-IN",label:"Hindi"},{value:"nl-NL",label:"Dutch"},{value:"sv-SE",label:"Swedish"}];return e.jsxs(s.AccordionItem,{value:`${t}-axis`,className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full flex-row-reverse items-center justify-between gap-3 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex grow items-center justify-between gap-2",children:[e.jsx("span",{children:a}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:O=>o("enabled",O),onClick:O=>O.stopPropagation()})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"NAME"}),e.jsx(s.SmallSwitch,{checked:((y=r==null?void 0:r.name)==null?void 0:y.enabled)??!1,onCheckedChange:O=>c("enabled",O)})]}),((g=r==null?void 0:r.name)==null?void 0:g.enabled)&&e.jsx(je,{placeholder:`${a} title`,value:((C=r==null?void 0:r.name)==null?void 0:C.text)||"",onSave:O=>c("text",O),className:""})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(s.Select,{value:(r==null?void 0:r.position)||"auto",onValueChange:O=>o("position",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-sm",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:h.map(O=>e.jsx(s.SelectItem,{value:O,children:O==="auto"?"Auto (Default)":s.titleCase(O)},O))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(s.SmallSwitch,{checked:((E=r==null?void 0:r.labels)==null?void 0:E.enabled)!==!1,onCheckedChange:O=>i("enabled",O)})]}),((R=r==null?void 0:r.labels)==null?void 0:R.enabled)!==!1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Rotation"}),e.jsxs(s.Select,{value:String(((S=r==null?void 0:r.labels)==null?void 0:S.rotation)||"auto"),onValueChange:O=>i("rotation",O==="auto"?"auto":Number(O)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-sm",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:p.map(O=>e.jsx(s.SelectItem,{value:O,children:O==="auto"?"Auto (Default)":`${O}°`},O))})]})]})]}),n==="value"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"FORMAT"}),e.jsxs(s.Select,{value:(r==null?void 0:r.format)||"auto",onValueChange:m,children:[e.jsx(s.SelectTrigger,{className:"h-8 text-sm",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:f.map(O=>e.jsx(s.SelectItem,{value:O,children:O==="auto"?"Auto (Default)":s.titleCase(O)},O))})]})]}),(r==null?void 0:r.format)&&r.format!=="auto"&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(r.format)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(je,{type:"number",placeholder:"0",value:String(((N=r==null?void 0:r.formatOptions)==null?void 0:N.decimalPlaces)??(r.format==="currency"?2:r.format==="percent"?1:0)),onSave:O=>u("decimalPlaces",Number(O)),className:""})})]}),r.format==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Currency"}),e.jsxs(s.Select,{value:((b=r==null?void 0:r.formatOptions)==null?void 0:b.currency)||"USD",onValueChange:O=>u("currency",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-sm flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:j.map(O=>e.jsx(s.SelectItem,{value:O.value,children:O.label},O.value))})]})]}),["number","currency"].includes(r.format)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((T=r==null?void 0:r.formatOptions)==null?void 0:T.useSuffix)??!1,onCheckedChange:O=>u("useSuffix",O)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Locale"}),e.jsxs(s.Select,{value:((k=r==null?void 0:r.formatOptions)==null?void 0:k.locale)||"en-US",onValueChange:O=>u("locale",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-sm flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:x.map(O=>e.jsx(s.SelectItem,{value:O.value,children:O.label},O.value))})]})]}),r.format==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(je,{placeholder:"e.g., $",value:((L=r==null?void 0:r.formatOptions)==null?void 0:L.prefix)||"",onSave:O=>u("prefix",O),className:""})})]}),r.format==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(je,{placeholder:"e.g., units",value:((w=r==null?void 0:r.formatOptions)==null?void 0:w.suffix)||"",onSave:O=>u("suffix",O),className:""})})]})]})]}),n==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"SCALE"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(je,{type:"number",placeholder:"auto",value:((B=r==null?void 0:r.scale)==null?void 0:B.min)==="auto"||((D=r==null?void 0:r.scale)==null?void 0:D.min)===void 0?"":String(r.scale.min),onSave:O=>d("min",O),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Max"}),e.jsx("div",{className:"flex-1",children:e.jsx(je,{type:"number",placeholder:"auto",value:((I=r==null?void 0:r.scale)==null?void 0:I.max)==="auto"||((v=r==null?void 0:r.scale)==null?void 0:v.max)===void 0?"":String(r.scale.max),onSave:O=>d("max",O),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Step"}),e.jsx("div",{className:"flex-1",children:e.jsx(je,{type:"number",placeholder:"auto",value:((M=r==null?void 0:r.scale)==null?void 0:M.stepSize)==="auto"||((F=r==null?void 0:r.scale)==null?void 0:F.stepSize)===void 0?"":String(r.scale.stepSize),onSave:O=>d("stepSize",O),className:""})})]})]})]})]})]})}function Mo(){const t=s.useEditorStore(c=>c.card),a=s.useEditorStore(c=>{var i;return(i=c.card)==null?void 0:i.preferences}),{setCardPreferences:n,updateCardInFrame:r}=s.useEditorActions();if(!t)return null;const l=s.AxisConfigurator.getAxisInfo(t.type,a);if(!l.hasXAxis&&!l.hasYAxis)return l.message?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:l.message}):null;const o=(c,i)=>{const m={...a||{},[c==="x"?"xAxisConfig":"yAxisConfig"]:i};n(m);const u={...t,preferences:m};r(u)};return e.jsx("div",{className:"space-y-3",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[l.hasXAxis&&e.jsx(Dt,{axis:"x",label:"X-Axis",type:l.xAxisType,config:a==null?void 0:a.xAxisConfig,onChange:c=>o("x",c)}),l.hasYAxis&&e.jsx(Dt,{axis:"y",label:"Y-Axis",type:l.yAxisType,config:a==null?void 0:a.yAxisConfig,onChange:c=>o("y",c)})]})})}function Lo({groupByFields:t,pivotByFields:a,metricsFields:n,sortByFields:r}){const l=s.useEditorStore(h=>h.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"},u=()=>o==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs(s.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"mt-4 w-full",children:[e.jsxs(s.AccordionItem,{value:"fields",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.ChartColumn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsx(es,{zone:"groupBy",fields:t,label:m().label,placeholder:m().placeholder}),i&&e.jsx(es,{zone:"pivotBy",fields:a,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(es,{zone:"metrics",fields:n,label:u().label,placeholder:u().placeholder,hasPivotColumns:a.length>0}),d&&e.jsx(es,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})]}),e.jsxs(s.AccordionItem,{value:"configuration",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Settings,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"CONFIGURATION"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsx(Ao,{}),e.jsx(Mo,{})]})]})]})}function Ro({selectedChart:t,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:o}){const c=s.useEditorStore(h=>h.showAIDialog),i=n.length>0||r.length>0||l.length>0,{setShowAIDialog:d}=s.useEditorActions(),m=s.useEditorStore(h=>h.card),{data:u}=s.useDashboardCardQuery(m);return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col",children:[e.jsxs("div",{className:"space-y-4 px-6 pt-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h2",{className:"font-semibold",children:"Chart Configuration"})}),e.jsx(vo,{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||u}),children:e.jsx(hs,{})}),!c&&e.jsxs(s.Button,{onClick:()=>d(!c),variant:"outline",className:"h-8",size:"sm",children:[e.jsx(Ma,{className:"mr-2 size-4"}),"AI"]})]}),e.jsxs(s.ScrollArea,{className:"w-full flex-1 basis-0 px-6",children:[e.jsx(Lo,{groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:o}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Oo({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 N=b=>{if(b.id===S){const T=i[0]||d;return{...b,conditions:[...b.conditions,{id:`condition-${Date.now()}`,field:T,operator:"=",value:""}]}}return{...b,groups:b.groups.map(N)}};r(N(n))},u=S=>{const N=b=>{if(b.id===S){const T=i[0]||d;return{...b,groups:[...b.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:T,operator:"=",value:""}],groups:[]}]}}return{...b,groups:b.groups.map(N)}};r(N(n))},h=(S,N)=>{const b=T=>T.id===S?{...T,conditions:T.conditions.filter(k=>k.id!==N)}:{...T,groups:T.groups.map(b)};r(b(n))},p=(S,N)=>{const b=T=>T.id===S?{...T,groups:T.groups.filter(k=>k.id!==N)}:{...T,groups:T.groups.map(b)};r(b(n))},f=(S,N,b,T)=>{if(b==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const k=L=>L.id===S?{...L,conditions:L.conditions.map(w=>w.id===N?{...w,[b]:T}:w)}:{...L,groups:L.groups.map(k)};r(k(n))},j=(S,N,b)=>{const T=k=>k.id===S?{...k,conditions:k.conditions.map(L=>L.id===N?{...L,...b}:L)}:{...k,groups:k.groups.map(T)};r(T(n))},x=(S,N)=>{const b=T=>T.id===S?{...T,logicalOperator:N}:{...T,groups:T.groups.map(b)};r(b(n))},y=(S,N)=>{const b=T=>T.id===S?{...T,negate:N}:{...T,groups:T.groups.map(b)};r(b(n))},g=(S,N,b)=>{const T=k=>k.id===S?{...k,conditions:s.arrayMove(k.conditions,N,b)}:{...k,groups:k.groups.map(T)};r(T(n))},C=(S,N,b)=>{const T=k=>k.id===S?{...k,groups:s.arrayMove(k.groups,N,b)}:{...k,groups:k.groups.map(T)};r(T(n))},E=S=>{if(!S||S.conditions.length===0&&S.groups.length===0)return"-- No filters defined";const N=T=>{let k="";typeof T.field=="object"?k=T.field.entityName?`${T.field.entityName}.${T.field.name}`:T.field.name:k=String(T.field);const L=T.operator;let w=T.value;if(T.field.dataType==="string"&&!["in","not in"].includes(T.operator))typeof w=="string"?w=`'${w}'`:Array.isArray(w)&&(w=`'${w.join(", ")}'`);else if(T.field.dataType==="date")(typeof w=="string"||w instanceof Date)&&(w=`DATE('${w}')`);else if(["in","not in"].includes(T.operator)){let B=[];Array.isArray(w)?B=w.map(D=>typeof D=="string"?`'${D}'`:String(D)):typeof w=="string"?B=w.split(",").map(D=>{const I=D.trim();return T.field.dataType==="string"?`'${I}'`:I}):typeof w=="number"&&(B=[String(w)]),w=`(${B.join(", ")})`}switch(L){case"contains":return typeof w=="string"?`${k} LIKE '%${w.replace(/'/g,"")}'`:`${k} LIKE '%${String(w)}'`;case"startsWith":return typeof w=="string"?`${k} LIKE '${w.replace(/'/g,"")}%'`:`${k} LIKE '${String(w)}%'`;case"endsWith":return typeof w=="string"?`${k} LIKE '%${w.replace(/'/g,"")}'`:`${k} LIKE '%${String(w)}'`;default:return`${k} ${L} ${w}`}},b=T=>{const k=T.conditions.map(N),L=T.groups.map(I=>b(I)),w=[...k,...L].filter(Boolean);if(w.length===0)return"";const B=w.join(` ${T.logicalOperator} `),D=w.length>1?`(${B})`:B;return T.negate?`NOT ${D}`:D};return b(S)},R=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:i,isLoading:o,addCondition:m,addGroup:u,removeCondition:h,removeGroup:p,updateCondition:f,updateConditionFields:j,updateGroupOperator:x,updateGroupNegate:y,reorderConditions:g,reorderGroups:C,generateSQLPreview:E,hasAnyFilters:R}}function Bo({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 Fo=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(da,{className:"h-3 w-3"});default:return e.jsx(s.Table,{className:"h-3 w-3"})}},Po=t=>{if(t.qualifiedEntityName){const a=t.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function zo({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 u=Po(m);d[u]||(d[u]={}),d[u][m.entityId]||(d[u][m.entityId]=[]),d[u][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(Bo,{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(([u,h])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[Fo(h[0].entityType),e.jsx("span",{children:h[0].entityName})]}),h.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}-${u}`))},d))})]})})]})}function tt(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:u,isPending:h,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:((u==null?void 0:u.records)||[]).map(x=>({label:x[t.name]||"BLANK",value:x[t.name]||"BLANK",count:(x==null?void 0:x.count)||0})),isPending:h,error:p}}function Vo({field:t,selected:a,onChange:n,placeholder:r="Select items...",className:l}){const[o,c]=ue.useState(!1),{filterValues:i}=tt(t),d=u=>{n(a.filter(h=>h!==u))},m=u=>{a.includes(u)?n(a.filter(h=>h!==u)):n([...a,u])};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(u=>{const h=i.find(p=>p.value===u);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[h==null?void 0:h.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:p=>{p.key==="Enter"&&d(u)},onMouseDown:p=>{p.preventDefault(),p.stopPropagation()},onClick:p=>{p.stopPropagation(),d(u)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},u)}):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((u,h)=>e.jsxs(s.CommandItem,{onSelect:()=>m(u.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",a.includes(u.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.count})]})]},u.value+h))})]})]})})]})})}const Tn=t=>{if(!t)return 0;let a=t.conditions.length;return t.groups.forEach(n=>{a+=Tn(n)}),a};function _o({field:t,value:a,onChange:n,placeholder:r="Select value...",className:l}){const{filterValues:o,isPending:c,error:i}=tt(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 Uo=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in"],$o=["=","!=","contains","startsWith","endsWith","in","not in"],qo=["=","!=",">",">=","<","<=","in","not in"],Yo=["=","!="],Go=["=","!=",">",">=","<","<=","in","not in"];function Ho(t){switch(t){case"string":return $o;case"number":return qo;case"boolean":return Yo;case"date":return Go;default:return Uo}}function In({condition:t,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:o,onUpdateGroupOperator:c,availableFields:i,updateConditionFields:d}){const{attributes:m,listeners:u,setNodeRef:h,transform:p,transition:f,isDragging:j}=s.useSortable({id:t.id}),{isPending:x,error:y}=tt(t.field),g={transform:s.CSS.Transform.toString(p),transition:f};return e.jsxs("div",{ref:h,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,...u,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:C=>c(n,C),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(zo,{value:t.field,onValueChange:C=>{d(n,t.id,{field:C,value:""})},availableFields:i,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:C=>{C==="in"||C==="not in"?d(n,t.id,{operator:C,value:[]}):d(n,t.id,{operator:C,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-28",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Ho(s.getDataType(t.field.dataType)).map(C=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:C,children:C},C))})]}),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..."]}):y?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(Vo,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(C=>typeof C=="string")?t.value:[],onChange:C=>d(n,t.id,{value:C}),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:C=>d(n,t.id,{value:C.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(_o,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:C=>d(n,t.id,{value:C}),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:C=>d(n,t.id,{value:C==="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:C=>l(n,t.id,"value",C.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 Ko({group:t,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:o,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onReorderConditions:m,onReorderGroups:u,onAddCondition:h,onAddGroup:p,availableFields:f,renderFilterGroup:j,updateConditionFields:x}){const{attributes:y,listeners:g,setNodeRef:C,transform:E,transition:R,isDragging:S}=s.useSortable({id:t.id}),N={transform:s.CSS.Transform.toString(E),transition:R},b=k=>{const{active:L,over:w}=k;if(w&&L.id!==w.id){const B=t.conditions.findIndex(I=>I.id===L.id),D=t.conditions.findIndex(I=>I.id===w.id);B!==-1&&D!==-1&&m(t.id,B,D)}},T=k=>{const{active:L,over:w}=k;if(w&&L.id!==w.id&&n){const B=t.groups.findIndex(I=>I.id===L.id),D=t.groups.findIndex(I=>I.id===w.id);B!==-1&&D!==-1&&u(n,B,D)}};return e.jsxs("div",{ref:C,style:N,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",{...y,...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:k=>r(t.id,k),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(k=>k.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((k,L)=>e.jsx(In,{condition:k,index:L,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:f,updateConditionFields:x},k.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:T,children:e.jsx(s.SortableContext,{items:t.groups.map(k=>k.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(k=>j(k,a+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>p(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Qo({filters:t,availableFields:a,onSave:n,onClearAll:r,onCancel:l}){const{currentFilters:o,availableFields:c,isLoading:i,addCondition:d,addGroup:m,removeCondition:u,removeGroup:h,updateCondition:p,updateConditionFields:f,updateGroupOperator:j,updateGroupNegate:x,reorderConditions:y,reorderGroups:g,generateSQLPreview:C,hasAnyFilters:E,setCurrentFilters:R}=Oo({initialFilters:t,availableFields:a}),S=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[N,b]=A.useState(!1),T=(w,B,D)=>{const I=v=>v.id===w?{...v,conditions:v.conditions.map(M=>M.id===B?{...M,field:D,dataType:D.dataType}:M)}:{...v,groups:v.groups.map(I)};R(I(o))},k=(w,B=0,D)=>B===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:I=>{const{active:v,over:M}=I;if(M&&v.id!==M.id){const F=w.conditions.findIndex(V=>V.id===v.id),O=w.conditions.findIndex(V=>V.id===M.id);F!==-1&&O!==-1&&y(w.id,F,O)}},children:e.jsx(s.SortableContext,{items:w.conditions.map(I=>I.id),strategy:s.verticalListSortingStrategy,children:w.conditions.map((I,v)=>e.jsx(In,{condition:I,index:v,groupId:w.id,groupLogicalOperator:w.logicalOperator,onUpdateCondition:p,onUpdateField:T,onRemoveCondition:u,onUpdateGroupOperator:j,availableFields:c,updateConditionFields:f},I.id))})}),e.jsx(s.DndContext,{sensors:S,collisionDetection:s.closestCenter,onDragEnd:I=>{const{active:v,over:M}=I;if(M&&v.id!==M.id){const F=w.groups.findIndex(V=>V.id===v.id),O=w.groups.findIndex(V=>V.id===M.id);F!==-1&&O!==-1&&g(w.id,F,O)}},children:e.jsx(s.SortableContext,{items:w.groups.map(I=>I.id),strategy:s.verticalListSortingStrategy,children:w.groups.map(I=>k(I,B+1,w.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>d(w.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),N&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>m(w.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},w.id):e.jsx(Ko,{group:w,depth:B,parentGroupId:D,onUpdateGroupOperator:j,onUpdateGroupNegate:x,onRemoveGroup:h,onUpdateCondition:p,onUpdateField:T,onRemoveCondition:u,onReorderConditions:y,onReorderGroups:g,onAddCondition:d,onAddGroup:m,availableFields:c,renderFilterGroup:k,updateConditionFields:f},w.id),L=Tn(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..."})]}):k(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:N,onCheckedChange:w=>b(!!w)}),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)"})]})}),E&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:C(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(E?o:null),children:"Apply Filters"})]})]})}function Wo({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(Qo,{filters:a,availableFields:l,onSave:i,onCancel:()=>c(!1),onClearAll:d})]})]})}function Jo({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]),u=A.useCallback(j=>{o(j.active.id)},[]),h=A.useCallback(j=>{const{active:x,over:y}=j;if(!y||!t){o(null);return}const g=x.id,C=y.id,E=m(g),R=m(C)||C;if(E==="source"&&R==="sortBy"){o(null);return}if(E==="source"&&R!=="source"&&R!=="sortBy"){const S=[...a].find(k=>k.id===g);if(!S){o(null);return}const N=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(N.length>0){const k=N[0].qualifiedEntityName;if(!k){o(null);return}if(k!==S.qualifiedEntityName&&S.qualifiedEntityName)if(i){if(!kn(k,S.qualifiedEntityName,i)){As(),o(null);return}}else{As(),o(null);return}}const b=n(R);if(Ms(S,b)){o(null);return}const T=s.getNewField(S,R);o(null),r(R,[...b,T]);return}if(E&&R&&E!=="source"&&R!=="source"&&E!==R){const S=n(E),N=n(R),b=S.find(L=>L.id===g);if(!b){o(null);return}const T=s.getNewField(b,R);if(o(null),R==="sortBy"){if(E==="pivotBy"){o(null);return}Ms(b,N)||r(R,[...N,T]);return}const k=S.filter(L=>L.id!==g);r(E,k),r(R,[...N,T]);return}if(E&&R&&E===R&&E!=="source"){const S=n(E),N=S.findIndex(T=>T.id===g),b=S.findIndex(T=>T.id===C);if(N!==b){const T=s.arrayMove(S,N,b);r(E,T)}}o(null)},[t,a,n,r,m,i]),p=l?d.find(j=>j.id===l):null;return{activeId:l,activeField:p,handleDragStart:u,handleDragEnd:h}}function Xo({onAdvancedToggle:t,onDebugToggle:a,onAccept:n}){const{currentUser:r}=Ne();r==null||r.role;const[l,o]=A.useState(!1),c=s.useEditorStore(g=>g.isDevMode),i=s.useEditorStore(g=>g.card),d=s.useEditorStore(g=>g.card.dataSource);s.isExplorerCard(i);const{config:m}=A.useContext(s.SemaphorContext).tokenProps,u=(m==null?void 0:m.showAdvancedMode)!==!1,{setIsDevMode:h}=s.useEditorActions(),p=s.useEditorStore(g=>g.showAIDialog),f=s.useEditorStore(g=>g.frame),j=s.useManagementStore(g=>g.selectedVisual),x=(j==null?void 0:j.id)===(f==null?void 0:f.id),{setShowAIDialog:y}=s.useEditorActions();return e.jsxs("div",{className:s.cn("flex items-center justify-between px-6 py-3",p&&"justify-end",!u&&"justify-end"),children:[u&&t&&!p&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{className:s.cn("",{}),checked:c,onCheckedChange:()=>h(!c),id:"advanced-mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium",children:"Advanced Mode"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[(r==null?void 0:r.type)!=="tenant"&&e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 p-0",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsx(s.DropdownMenuContent,{align:"end",children:e.jsxs(s.DropdownMenuItem,{onClick:()=>{o(!0)},children:[e.jsx(s.Database,{className:"mr-2 h-4 w-4"}),"Set Data Context"]})})]}),e.jsx(Gs,{}),n&&!x&&e.jsx(Ys,{variant:"default"}),x&&e.jsx(el,{}),a&&s.isDevEnv]}),l&&e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(d==null?void 0:d.selectedEntities)||[],open:l,onOpenChange:o,dataSource:d||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function Zo({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 ei=[{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 si(){var d,m;const t=s.useEditorStore(u=>u.card),{updateRowLimit:a}=s.useEditorActions(),[n,r]=A.useState(!1),[l,o]=A.useState(""),c=u=>{if(u==="custom"){r(!0);return}r(!1),a(t.id,parseInt(u))},i=u=>{const h=u.target.value;o(h),h&&!isNaN(parseInt(h))&&a(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(s.Input,{type:"number",value:l,onChange: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:ei.map(u=>e.jsx(s.SelectItem,{value:u.value,children:u.label},u.value))})]})})}function ti({isOpen:t,onClose:a}){const n=Kt(a,{enabled:t}),r=s.useEditorStore(u=>{var h;return((h=u.card.customCardPreferences)==null?void 0:h.url)||""}),l=s.useEditorStore(u=>u.card),o=s.useEditorStore(u=>{var h;return((h=u.card.customCardPreferences)==null?void 0:h.pluginChartType)||""}),c=s.useEditorStore(u=>{var h;return((h=u.card.customCardPreferences)==null?void 0:h.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 ni({activeView:t,onViewChange:a,showDebug:n,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:d,activeCard:m,columns:u,columnsLoading:h,columnsError:p}){var M;const f=s.useEditorStore(F=>F.card);s.useEditorStore(F=>F.frame);const j=s.useDashboardStore(F=>F.filterValues),{updateCardConfig:x,setCard:y,updateCardInFrame:g}=s.useEditorActions(),C=s.useEditorStore(F=>F.showAIDialog),[E,R]=A.useState(!1),S=s.useEditorStore(F=>{var O;return((O=F.card.customCardPreferences)==null?void 0:O.url)&&F.card.type==="custom"}),{data:N,errorMessage:b,isPending:T,isLoading:k,isFetching:L,pagination:w}=s.useDashboardCardQuery(m),B=(F,O)=>{const V={...m,paginationConfig:{page:F+1,pageSize:O}};y(V),g(V)};function D(){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 (",u.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:h?"Loading...":p?"Error loading columns":JSON.stringify(u.slice(0,5),null,2)})]})]})})}const I=F=>{if(!f.config)return;if(!F.length){x(f.id,{...f.config,sortByColumns:[]});return}const O=f.config,V=F.map(({id:_,desc:W})=>{var Y,$;const Q=(Y=O.metricColumns)==null?void 0:Y.find(P=>P.label===_),U=($=O.groupByColumns)==null?void 0:$.find(P=>P.label===_),q=Q||U;return q?{id:s.getFieldId("sortBy",q),name:q.name,dataType:q.dataType,label:q.label,qualifiedEntityName:q.qualifiedEntityName,entityId:q.entityId,entityName:q.entityName,entityType:q.entityType,role:"sortby",direction:W?"desc":"asc"}:null}).filter(_=>_!==null);x(f.id,{...O,sortByColumns:V})},v=A.useMemo(()=>{var F,O;return(O=(F=f.config)==null?void 0:F.sortByColumns)==null?void 0:O.map(V=>({id:V.label,desc:V.direction==="desc"}))},[(M=f.config)==null?void 0:M.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[e.jsx(Xo,{showDebug:n,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:d}),n&&D(),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"&&C&&e.jsx(gn,{variant:"outline"}),e.jsx(Zo,{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(si,{})}),C&&e.jsx(hs,{})]}),e.jsx("div",{className:s.cn("flex grow items-center justify-end"),children:t==="chart"&&e.jsx(jn,{})})]}),!E&&S&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>R(!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(Ta,{className:"size-4"})}),e.jsxs("div",{className:"mt-3 flex grow flex-col",children:[t==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:e.jsx(yn,{})}),t==="table"&&(N==null?void 0:N.records)&&e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:e.jsx(s.TableVisual,{card:m,data:(N==null?void 0:N.records)||[],paginationMetadata:w,onPaginationChange:B,isLoading:k||L,onSortChange:I,sortState:v})}),t==="sql"&&e.jsx("div",{className:"p-6",children:e.jsxs("div",{className:"rounded-md bg-background",children:[(N==null?void 0:N.sql)&&e.jsx("h3",{className:"mb-3 text-sm font-medium",children:"Generated SQL Query"}),e.jsx(on,{sql:N==null?void 0:N.sql,error:b})]})})]}),e.jsx(ti,{isOpen:E,onClose:()=>R(!1)})]})]})}function ai({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(En,{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 ri=()=>{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 li(){var U,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(Y=>Y.showAIDialog),m=s.useDashboardStore(Y=>Y.isVisualEditing),{setCardType:u}=s.useEditorActions(),h=s.useEditorStore(Y=>Y.card.type);A.useEffect(()=>ri(),[]);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)},y=Y=>{u(Y)},g=s.useEditorStore(Y=>Y.frame),C=s.useEditorStore(Y=>Y.card);s.useEditorStore(Y=>Y.activeTabCardId),s.useEditorStore(Y=>Y.actions.getAvailableFields);const{addCard:E,removeCard:R,updateCard:S,setActiveCard:N,updateFilters:b}=s.useEditorActions(),{columns:T=[],isLoading:k,error:L}=s.useColumns(),w=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),B=C,{getFieldsForContainer:D,setFieldsForContainer:I}=et(B),{activeField:v,handleDragStart:M,handleDragEnd:F}=Jo({activeCardId:g.activeCardId,sourceFields:T,getFieldsForContainer:D,setFieldsForContainer:I}),O=(Y,$)=>{$&&b(Y,$)},V=Y=>{var $;S(Y,{config:{...($=g.cards.find(P=>P.id===Y))==null?void 0:$.config,filters:void 0}})},_=T,W=Y=>{if(!Y)return 0;let $=Y.conditions.length;return Y.groups.forEach(P=>{$+=W(P)}),$},Q=W(((U=B==null?void 0:B.config)==null?void 0:U.filters)||null);return e.jsxs(s.DndContext,{sensors:w,collisionDetection:s.closestCenter,onDragStart:M,onDragEnd:F,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(jo,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(Ro,{selectedChart:h,onChartChange:y,groupByFields:D("groupBy"),pivotByFields:D("pivotBy"),metricsFields:D("metrics"),sortByFields:D("sortBy")}),e.jsx(ni,{selectedChart:h,activeView:t,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onAccept:p,onClear:f,onAdvancedToggle:j,onFiltersClick:x,filterCount:Q,activeCard:B,dataSourceState:C.dataSource||s.EMPTY_DATA_SOURCE,columns:T,columnsLoading:k,columnsError:L,getFieldsForContainer:D,cards:g.cards,activeCardId:g.activeCardId,addCard:E,setActiveCard:N})]}),!c&&m&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>i(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),B&&e.jsx(Wo,{cardId:B.id,filters:((q=B.config)==null?void 0:q.filters)||null,onFiltersChange:O,onClearFilters:V,availableFields:_,isOpen:l,onOpenChange:o}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(ai,{activeField:v||null})})]})}function oi({authToken:t,onSave:a,onClose:n}){const r=A.useRef(null),l=s.useEditorStore(C=>C.showAIDialog),o=s.useEditorStore(C=>C.isDevMode),{setAuthToken:c}=s.useDashboardActions(),{setShowAIDialog:i,setOnSave:d,setOnClose:m}=s.useEditorActions(),{handleDragOver:u,handleDragEnd:h,handleDragStart:p,handleDragCancel:f,sensors:j}=_r();A.useEffect(()=>{a&&d(a),n&&m(n)},[a,d,n,m]),A.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),A.useEffect(()=>{var C,E;l?((C=r.current)==null||C.resize(40),i(!0)):(i(!1),(E=r.current)==null||E.resize(0))},[l,i]);function x(C){C<1?i(!1):l||i(!0)}function y(){return e.jsxs(e.Fragment,{children:[e.jsx(rn,{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(to,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(bt,{})})]})]})}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(li,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(bt,{})})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:o?e.jsx(s.DndContext,{sensors:j,onDragStart:p,onDragEnd:h,onDragOver:u,onDragCancel:f,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:y()})}):g()})}function ii(){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(oi,{onSave:l,onClose:o})})}function ci(){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}=Cn();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($s,{column:o}),e.jsx("span",{children:o.column_name})]})},o.column_name)})})}function di(){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(rn,{type:"filter",ColumnsComponent:()=>e.jsx(ci,{})})})]})}function ui(){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 mi(){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(ui,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(di,{})})]})}function hi(){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 xi({showControls:t=!1,showFooter:a=!0,...n}){return typeof window>"u"?null: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(hi,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx(Br,{}),e.jsxs(s.DashboardPanel,{...n,children:[e.jsx(ii,{}),e.jsx(mi,{})]})]})]})]})})}exports.DashboardPlus=xi;exports.ResourceManagementPanel=nn;exports.ScheduleDashboard=Vt;exports.SelectComponent=Ve;exports.cleanCard=Ft;exports.downloadPdf=zt;exports.getDashbaordStateWithoutData=as;
|
|
450
|
+
ON ${C}`}),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(fo,{joins:n.joins,baseEntityId:n.baseEntity.name,availableDataSources:o,generateSQLPreview:m})})]})}),e.jsx(vt,{open:r,onOpenChange:l,joinPlan:n,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsx("div",{})})]}),n.joins.length===0&&e.jsx(vt,{open:r,onOpenChange:l,joinPlan:n,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsxs(s.Button,{onClick:()=>l(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function jo({open:t,onOpenChange:a}){const[n,r]=A.useState([]),{updateDataSource:l}=s.useEditorActions(),o=s.useDashboardStore(x=>x.dashboard.aiContext),c=(o==null?void 0:o.selectedEntities)||[];A.useEffect(()=>{t&&r([])},[t]);const i=x=>{r(y=>y.some(C=>C.name===x.name&&C.type===x.type)?y.filter(C=>!(C.name===x.name&&C.type===x.type)):[...y,x])},d=()=>{r([...c])},m=()=>{r([])},u=()=>{if(n.length===0)return;const x=n[0],y=x.connectionId||"",g=x.connectionType||"",E=n.some(S=>S.type==="dataset")?"semanticDomain":"database";l({connectionId:y,connectionType:g,mode:E,selectedEntities:n}),a(!1)},h=x=>{switch(x.type){case"table":return e.jsx(s.Table,{className:"h-4 w-4"});case"view":return e.jsx(Pa,{className:"h-4 w-4"});case"model":return e.jsx(la,{className:"h-4 w-4"});case"dataset":return e.jsx(s.Database,{className:"h-4 w-4"});case"file":case"url":case"upload":return e.jsx(s.FileText,{className:"h-4 w-4"});default:return e.jsx(s.Database,{className:"h-4 w-4"})}},p=x=>"label"in x&&x.label?x.label:x.name,f=x=>{if("description"in x&&x.description)return x.description;const y=[];return x.database&&y.push(x.database),x.schema&&y.push(x.schema),x.name&&y.push(x.name),y.join(".")},j=x=>n.some(y=>y.name===x.name&&y.type===x.type);return c.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"max-w-md",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"No Data Available"}),e.jsx(s.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{onClick:()=>a(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(s.DialogDescription,{children:"Choose entities from the dashboard's context"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"outline",size:"sm",onClick:d,disabled:n.length===c.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:m,disabled:n.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[n.length," of ",c.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:c.map((x,y)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",j(x)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:j(x),onCheckedChange:()=>i(x)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:h(x)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:p(x)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:f(x)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:x.type})]},`${x.type}-${x.name}-${y}`))})})]}),e.jsx(s.DialogFooter,{children:e.jsx("div",{className:"flex w-full justify-between",children:e.jsxs("div",{className:"flex grow justify-end gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:u,disabled:n.length===0,children:["Select"," ",n.length>0?`(${n.length})`:""]})]})})})]})})}function yo({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 bo({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 vo({isVisible:t,onToggleVisibility:a}){const[n,r]=A.useState(!1),[l,o]=A.useState(!1),[c,i]=A.useState(!0),d=s.useEditorStore(p=>p.card.dataSource);Ne();const{updateDataSource:m}=s.useEditorActions(),u={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},h={...u,...d,selectedEntities:(d==null?void 0:d.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[e.jsxs("div",{children:[e.jsx("div",{className:s.cn("p-4 px-6",{"pb-0":!c}),children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex cursor-pointer items-center gap-2",children:[e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Data Source"}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>i(!c),className:"h-6 w-6 p-0",children:c?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronRight,{className:"h-4 w-4"})})]}),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 ${c?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[h.selectedEntities.length>0&&e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[h.selectedEntities.slice(0,3).map((p,f)=>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(p),e.jsx("button",{onClick:j=>{j.stopPropagation();const x=h.selectedEntities.filter(y=>!(y.name===p.name&&y.type===p.type));m({...u,...d,selectedEntities:x})},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(yo,{entity:p})]},`${p.type}-${p.name}-${f}`)),h.selectedEntities.length>3&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:["+",h.selectedEntities.length-3," more"]})}),e.jsx(bo,{entities:h.selectedEntities.slice(3)})]})]})}),e.jsx(go,{})]})]}),e.jsx(ho,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(d==null?void 0:d.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:r,dataSource:h,fallbackDataSource:u}),e.jsx(jo,{open:l,onOpenChange:o})]})}const ts=[{id:"table",icon:_e,label:"Table"},{id:"pivotTable",icon:_e,label:"Pivot Table"},{id:"aggregateTable",icon:_e,label:"Aggregate Table"},{id:"bar",icon:ds,label:"Bar Chart"},{id:"line",icon:us,label:"Line Chart"},{id:"area",icon:It,label:"Area Chart"},{id:"stackedBar",icon:Ls,label:"Stacked Bar Chart"},{id:"combo",icon:sa,label:"Combo Chart"},{id:"stackedLine",icon:Ws,label:"Stacked Line Chart"},{id:"scatter",icon:Rs,label:"Scatter Chart"},{id:"bubble",icon:Ks,label:"Bubble Chart"},{id:"pie",icon:ms,label:"Pie Chart"},{id:"doughnut",icon:Bs,label:"Doughnut Chart"},{id:"funnel",icon:Qs,label:"Funnel Chart"},{id:"radar",icon:Ps,label:"Radar Chart"},{id:"polarArea",icon:Hs,label:"Polar Area Chart"},{id:"tornado",icon:zs,label:"Tornado Chart"},{id:"range",icon:Os,label:"Range Chart"},{id:"kpi",icon:Js,label:"KPI"},{id:"text",icon:Et,label:"Text"},{id:"map",icon:Fs,label:"Map"}],st=t=>{const a=t.toLowerCase();for(const n of ts)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},No="chart-selector-standard-first";function Co(){const[t,a]=s.useLocalStorageState(No,!0);return{standardFirst:t,updatePreference:a}}const Nt=({pluginVisual:t,index:a,onSelect:n})=>{const r=xs(t.icon||""),l=t.name.charAt(0).toUpperCase(),o=st(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}`)},Ct=["default","standardPlugin","customPlugin"];function So({selectedChart:t,onChartChange:a}){var R;const[n,r]=A.useState(!1),{data:l}=fn();Co();const c=((R=s.useEditorStore(S=>S.card).customCardPreferences)==null?void 0:R.url)||"";_s(c);const{setCardType:i,setCardPreferences:d,setIsDevMode:m}=s.useEditorStore(S=>S.actions),{setCardCustomCfg:u,setCustomCardPreferences:h,setQueryConfig:p}=s.useEditorActions(),[f,j]=s.useLocalStorageState("chart-section-active",null),x=A.useMemo(()=>f?[f,...Ct.filter(S=>S!==f)]:Ct,[f]);function y(S){u(null),d({}),i(S),["custom","text","map"].includes(S)&&(m(!0),p(void 0)),a(S),r(!1)}function g(S){u(null),d({}),i("custom"),h({type:"component",visualType:"single",url:S.url,componentName:S.name,icon:S.icon,pluginChartType:S.chartType}),p(void 0),a("custom"),r(!1)}const C=()=>{var N;if(t==="custom"){const b=s.useEditorStore.getState().card;return((N=b==null?void 0:b.customCardPreferences)==null?void 0:N.componentName)||"Custom Visual"}const S=ts.find(b=>b.id===t);return(S==null?void 0:S.label)||"Select chart type"},E=()=>{var N,b;if(t==="custom"){const I=s.useEditorStore.getState().card,k=(N=I==null?void 0:I.customCardPreferences)==null?void 0:N.icon,L=(b=I==null?void 0:I.customCardPreferences)==null?void 0:b.componentName;if(k&&L)return e.jsx(wo,{icon:k,componentName:L});if(L){const w=st(L);if(w)return w}return e.jsx(He,{className:"h-4 w-4"})}const S=ts.find(I=>I.id===t);if(S){const I=S.icon;return e.jsx(I,{className:"h-4 w-4"})}return e.jsx(He,{className:"h-4 w-4"})};return e.jsx("div",{className:"mb-6",children:e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[E(),e.jsx("span",{children:C()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search chart types..."}),e.jsxs(s.CommandList,{className:"mb-2 max-h-[300px]",children:[e.jsx(s.CommandEmpty,{children:"No chart type found."}),x.map(S=>{if(S==="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:f==="default",onCheckedChange:N=>j(N?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:ts.map(N=>{const b=N.icon;return e.jsx(s.CommandItem,{value:`${N.label} ${N.id} chart graph visualization`,onSelect:()=>y(N.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(b,{className:"h-4 w-4"}),e.jsx("span",{children:N.label})]})},N.id)})},"default");if(S==="standardPlugin"){const N=l.filter(b=>b.pluginType==="standard");return N.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsx("p",{children:"Standard Visuals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:f==="standardPlugin",onCheckedChange:b=>j(b?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:N.filter(b=>b.componentType==="chart").map((b,I)=>e.jsx(Nt,{pluginVisual:b,index:I,onSelect:()=>g(b)},`${b.url}-${b.name}-${I}`))},"standardPlugin"):null}if(S==="customPlugin"){const N=l.filter(b=>b.pluginType==="custom");return N.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-2",children:["Custom Visuals",e.jsx(s.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),e.jsx(s.TooltipContent,{side:"right",children:"External visuals that are specific to your project"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:f==="customPlugin",onCheckedChange:b=>j(b?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:N.map((b,I)=>e.jsx(Nt,{pluginVisual:b,index:I,onSelect:()=>g(b)},`${b.url}-${b.name}-${I}`))},"customPlugin"):null}return null})]})]})})]})})}const wo=({icon:t,componentName:a})=>{const n=xs(),r=st(a);return n?e.jsx(n,{className:"h-4 w-4"}):r||e.jsx(He,{className:"h-4 w-4"})},Tn=({dataType:t})=>{const a=s.getDataType(t);return a==="string"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(Qe,{className:"h-3 w-3"})}):a==="number"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Ge,{className:"h-3 w-3"})}):a==="date"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):a==="boolean"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(ns,{className:"h-3 w-3"})}):e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Qe,{className:"h-3 w-3"})})};function Do({aliasTemplate:t,onAliasTemplateChange:a}){var d;const[n,r]=A.useState(t),[l,o]=A.useState(!1),c=(d=s.useEditorStore(m=>{var u;return(u=m.card.config)==null?void 0:u.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 ko({valueAliases:t,onValueAliasesChange:a}){const[n,r]=A.useState(null),[l,o]=A.useState(""),[c,i]=A.useState(""),d=()=>{a({...t,"":""})},m=h=>{const p={...t};delete p[h],a(p)},u=h=>{const p={...t};delete p[h],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(([h,p],f)=>e.jsx("div",{className:"flex items-center gap-2",children:n===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:l,onChange:j=>o(j.target.value),className:"h-8 w-24 text-xs",onPointerDown:j=>j.stopPropagation(),onKeyDown:j=>{j.key==="Enter"?u(h):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"?u(h):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:()=>u(h),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(p)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:p,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(p)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>m(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+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 je({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)},u=()=>{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:h=>{c(h.target.value),d(!0)},onFocus:()=>d(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&i&&o!==t?m():h.key==="Escape"&&u()},"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:u,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function Eo({field:t,zone:a,index:n,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:o=!1,cardType:c}){var at;const{attributes:i,listeners:d,setNodeRef:m,transform:u,transition:h,isDragging:p}=s.useSortable({id:t.id}),f=s.useEditorStore(J=>J.card),{updateLabel:j,handleAggregationChange:x,handleDateFormatChange:y,handleGranularityChange:g,handleAliasTemplateChange:C,handleValueAliasesChange:E,removeField:R,handleKpiComparisonTypeChange:S,handleKpiShowTrendlineChange:N,handleKpiTrendlineWindowChange:b,handleKpiTrendlineGranularityChange:I,handleKpiTargetValueChange:k}=et(f),[L,w]=A.useState(!1),[B,D]=A.useState(t.dateFormat||"YYYY-MM-DD"),[T,v]=A.useState(t.customFormat||""),[M,F]=A.useState(!!t.customFormat),[O,V]=A.useState(t.granularity||"day"),[_,W]=A.useState(t.aliasTemplate||""),[Q,$]=A.useState(t.valueAliases||{}),q=J=>{J==="custom"?F(!0):(F(!1),D(J),a==="groupBy"&&y(n,J,""))},H=J=>{v(J),a==="groupBy"&&y(n,"custom",J)},U=J=>{var qe;V(J);const xe=(qe=K(J)[0])==null?void 0:qe.value;xe&&!M&&(D(xe),a==="groupBy"&&y(n,xe,"")),a==="groupBy"&&g(n,J)},P=J=>{W(J),a==="metrics"&&C(n,J)},Y=J=>{$(J),a==="metrics"&&E(n,J)},G=J=>{j(a,n,J)},X=()=>{R(a,n)},se={transform:s.CSS.Transform.toString(u),transition:h},ae=s.getDataType(t.dataType),te=ae==="date",le=c==="kpi",K=J=>{switch(J){case"day":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"custom",label:"Custom Format..."}];case"week":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"Week of MMM DD, YYYY",label:"Week of Jan 15, 2024"},{value:"Week of MMMM DD, YYYY",label:"Week of January 15, 2024"},{value:"YYYY-WW",label:"2024-W03 (YYYY-WW)"},{value:"custom",label:"Custom Format..."}];case"month":return[{value:"MMM YYYY",label:"Jan 2024 (MMM YYYY)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MM/YYYY",label:"01/2024 (MM/YYYY)"},{value:"YYYY MMM",label:"2024 Jan (YYYY MMM)"},{value:"custom",label:"Custom Format..."}];case"quarter":return[{value:"Q1 YYYY",label:"Q1 2024 (Q1 YYYY)"},{value:"YYYY Q1",label:"2024 Q1 (YYYY Q1)"},{value:"1st Quarter YYYY",label:"1st Quarter 2024"},{value:"YYYY-Q1",label:"2024-Q1 (YYYY-Q1)"},{value:"Quarter 1, YYYY",label:"Quarter 1, 2024"},{value:"custom",label:"Custom Format..."}];case"year":return[{value:"YYYY",label:"2024 (YYYY)"},{value:"YY",label:"24 (YY)"},{value:"custom",label:"Custom Format..."}];default:return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"custom",label:"Custom Format..."}]}},z=K(O),Z=!le&&a!=="pivotBy",oe=te&&a==="groupBy",Ce=!le&&te&&a==="groupBy",Te=le&&te&&a==="groupBy",ne=le&&a==="metrics"&&((at=f.config)==null?void 0:at.comparisonType)==="target",ie=a==="metrics",ce=()=>e.jsx("div",{onPointerDown:J=>{J.stopPropagation()},className:"cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),Mn=()=>Z?e.jsx(je,{value:t.label??"",onSave:G,placeholder:"Display label...",type:"text"}):null,nt=()=>oe?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:O,onValueChange:U,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsx(s.SelectContent,{children:["day","week","month","quarter","year"].map(J=>e.jsx(s.SelectItem,{className:"text-xs",value:J,children:s.toTitleCase(J)},J))})]})]}):null,Ln=()=>Ce?e.jsxs(e.Fragment,{children:[nt(),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:M?"custom":B,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:z.map(J=>e.jsx(s.SelectItem,{className:"text-xs",value:J.value,children:J.label},J.value))})]}),M&&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:T,onChange:J=>{J.stopPropagation(),H(J.target.value)},onClick:J=>J.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,On=()=>{var J,ge,xe,qe,rt;return 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:"Comparison Type"}),e.jsxs(s.Select,{value:((J=f.config)==null?void 0:J.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:((ge=f.config)==null?void 0:ge.showTrendline)||!1,onCheckedChange:N})]})}),((xe=f.config)==null?void 0:xe.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:((qe=f.config)==null?void 0:qe.trendlineWindow)||30,onChange:Fn=>{const Pn=parseInt(Fn.target.value)||30;b(Pn)},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:((rt=f.config)==null?void 0:rt.trendlineGranularity)||"day",onValueChange:I,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},Rn=()=>{var J,ge;return ne?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(je,{value:((J=f.config)==null?void 0:J.targetValue)!==void 0&&((ge=f.config)==null?void 0:ge.targetValue)!==null?String(f.config.targetValue):"",onSave:xe=>{!isNaN(Number(xe))&&xe!==null?k(Number(xe)):k(0)},placeholder:"Enter target value...",type:"text"})]}):null},Bn=()=>ie?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:J=>{x(n,J)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsx(Dn,{column:t}),o&&e.jsxs(e.Fragment,{children:[e.jsx(Do,{aliasTemplate:_,onAliasTemplateChange:P}),e.jsx(ko,{valueAliases:Q,onValueAliasesChange:Y})]})]}):null;return e.jsxs("div",{ref:m,style:se,...i,...d,className:`group mx-auto flex w-full flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${p?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(Tn,{dataType:ae}),e.jsx(Xs,{className:"w-[140px] 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:J=>{J.stopPropagation(),w(!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:J=>{J.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const ge=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",ge),l(ge)},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:J=>{J.stopPropagation(),X()},children:e.jsx(s.X,{className:"h-3 w-3"})})]}),L&&e.jsxs("div",{className:"space-y-3",children:[ce(),Mn(),c==="kpi"&&nt(),Ln(),On(),Rn(),Bn()]})]})}function To({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 es({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),u=s.useEditorStore(j=>j.card.type),h=a.length>0,p=(j,x)=>{var g;!((g=m.config)!=null&&g.sortByColumns)||m.config.sortByColumns.findIndex(C=>C.id===j)===-1||d(m.id,j,{direction:x})};if(t==="sortBy"&&l===!1)return null;const f=t!=="sortBy"&&u!=="kpi";return e.jsxs("div",{className:"mb-4 w-full",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:n}),f&&e.jsx(To,{concept:t})]}),e.jsx("div",{ref:i,className:`min-h-[60px] rounded-lg border-2 border-dashed p-2 transition-all ${c?"border-blue-500 bg-blue-50 dark:bg-blue-950":h?"border-blue-200 bg-blue-50/30 dark:border-blue-800 dark:bg-blue-950/30":"border-muted-foreground/20 bg-background"}`,children:a.length===0?e.jsx("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:r}):e.jsx(s.SortableContext,{items:a.map(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(Eo,{field:j,zone:t,index:x,sortDirection:g,onSortDirectionChange:C=>p(j.id,C),hasPivotColumns:o,cardType:u})})},j.id)})})})})]})}function Io({color:t,onColorChange:a,onClose:n}){const[r,l]=A.useState(0),[o,c]=A.useState(100),[i,d]=A.useState(50),[m,u]=A.useState(t);A.useEffect(()=>{const y=St(t);if(y){const g=wt(y.r,y.g,y.b);l(g.h),c(g.s),d(g.l),u(t)}},[t]);const h=y=>{l(y),f(y,o,i)},p=y=>{const g=y.currentTarget.getBoundingClientRect(),C=Math.max(0,Math.min(1,(y.clientX-g.left)/g.width)),E=Math.max(0,Math.min(1,(y.clientY-g.top)/g.height)),R=C*100,S=(1-E)*100;c(R),d(S),f(r,R,S)},f=(y,g,C)=>{const E=Mo(y,g,C),R=Ao(E.r,E.g,E.b);u(R)},j=y=>{if(u(y),/^#[0-9A-Fa-f]{6}$/.test(y)){const g=St(y);if(g){const C=wt(g.r,g.g,g.b);l(C.h),c(C.s),d(C.l)}}},x=()=>{/^#[0-9A-Fa-f]{6}$/.test(m)&&(a(m),n())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:p,onMouseMove:y=>{y.buttons===1&&p(y)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${o}%`,top:`${100-i}%`,backgroundColor:m}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:y=>h(Number(y.target.value)),className:"w-full h-4 rounded-lg appearance-none cursor-pointer",style:{background:"linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"}})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"HEX"}),e.jsx(s.Input,{value:m,onChange:y=>j(y.target.value),placeholder:"#000000",className:"font-mono"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:t}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:m}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(s.Button,{variant:"outline",onClick:n,children:"Cancel"}),e.jsx(s.Button,{onClick:x,children:"OK"})]})]})}function St(t){const a=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return a?{r:parseInt(a[1],16),g:parseInt(a[2],16),b:parseInt(a[3],16)}:null}function Ao(t,a,n){return"#"+((1<<24)+(t<<16)+(a<<8)+n).toString(16).slice(1)}function wt(t,a,n){t/=255,a/=255,n/=255;const r=Math.max(t,a,n),l=Math.min(t,a,n);let o=0,c=0;const i=(r+l)/2;if(r!==l){const d=r-l;switch(c=i>.5?d/(2-r-l):d/(r+l),r){case t:o=((a-n)/d+(a<n?6:0))/6;break;case a:o=((n-t)/d+2)/6;break;case n:o=((t-a)/d+4)/6;break}}return{h:Math.round(o*360),s:Math.round(c*100),l:Math.round(i*100)}}function Mo(t,a,n){t/=360,a/=100,n/=100;let r,l,o;if(a===0)r=l=o=n;else{const c=(m,u,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?m+(u-m)*6*h:h<.5?u:h<.6666666666666666?m+(u-m)*(.6666666666666666-h)*6:m),i=n<.5?n*(1+a):n+a-n*a,d=2*n-i;r=c(d,i,t+1/3),l=c(d,i,t),o=c(d,i,t-1/3)}return{r:Math.round(r*255),g:Math.round(l*255),b:Math.round(o*255)}}const Lo=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function Oo(){var E,R,S,N,b,I,k,L,w,B;const t=s.useEditorStore(D=>D.card),a=s.useEditorStore(D=>{var T;return(T=D.card)==null?void 0:T.preferences}),{setCardPreferences:n,updateCardInFrame:r}=s.useEditorActions(),{data:l}=s.useDashboardCardQuery(t),[o,c]=A.useState({}),[i,d]=A.useState(null),[m,u]=A.useState(null),h=A.useMemo(()=>{var M,F,O,V,_,W,Q;if(!(l!=null&&l.records)||l.records.length===0)return[];const D=(t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine",T=(t==null?void 0:t.type)==="bar"||(t==null?void 0:t.type)==="line",v=((M=t==null?void 0:t.config)==null?void 0:M.pivotByColumns)&&t.config.pivotByColumns.length>0;if((D||T)&&v){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const $=new Set;return l.pivotSchema.forEach(q=>{q.alias&&$.add(q.alias)}),Array.from($)}if(l.records.length>0){const $=l.records[0],q=Object.keys($),H=new Set;(F=t==null?void 0:t.config)!=null&&F.groupByColumns&&t.config.groupByColumns.forEach(Y=>{H.add(Y.label||Y.name),H.add(Y.alias||Y.name)});const U=new Set;return(O=t==null?void 0:t.config)!=null&&O.metricColumns&&t.config.metricColumns.forEach(Y=>{const G=Y.alias||Y.name;U.add(G),U.add(`${G}_count`),U.add(`${G}_sum`),U.add(`${G}_avg`),U.add(`${G}_min`),U.add(`${G}_max`);const X=Y.entityName||Y.qualifiedEntityName;X&&(U.add(`${X}_${G}`),U.add(`${X}_${G}_count`))}),q.filter(Y=>!H.has(Y)&&!U.has(Y))}}if((T||D)&&!v&&((_=(V=t==null?void 0:t.config)==null?void 0:V.metricColumns)!=null&&_.length))return t.config.metricColumns.map($=>$.alias||$.label||$.name);if((Q=(W=t==null?void 0:t.config)==null?void 0:W.groupByColumns)!=null&&Q.length){const $=t.config.groupByColumns[0],q=$.label||$.name,H=new Set;return l.records.forEach(U=>{const P=U[q];P!=null&&H.add(String(P))}),Array.from(H)}return[]},[l,(E=t==null?void 0:t.config)==null?void 0:E.groupByColumns,(R=t==null?void 0:t.config)==null?void 0:R.pivotByColumns,(S=t==null?void 0:t.config)==null?void 0:S.metricColumns,t==null?void 0:t.type]),p=A.useMemo(()=>s.getDefaultChartColors(),[]);A.useEffect(()=>{const D={};h.forEach((T,v)=>{D[T]=s.getColorForValue(T,v,a==null?void 0:a.colorConfig)}),c(D)},[h,a==null?void 0:a.colorConfig,p]);const f=(D,T)=>{const v={...o,[D]:T};c(v);const M={...a||{},colorConfig:{segments:v}};n(M);const F={...t,preferences:M};r(F)},j=(D,T)=>{var _;const v=p[T%p.length],{[D]:M,...F}=((_=a==null?void 0:a.colorConfig)==null?void 0:_.segments)||{},O={...a||{},colorConfig:{segments:F}};n(O);const V={...t,preferences:O};r(V),c(W=>({...W,[D]:v}))};if(!h.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((b=(N=t==null?void 0:t.config)==null?void 0:N.groupByColumns)==null?void 0:b.length)||((k=(I=t==null?void 0:t.config)==null?void 0:I.pivotByColumns)==null?void 0:k.length):(w=(L=t==null?void 0:t.config)==null?void 0:L.groupByColumns)==null?void 0:w.length)||["table","kpi","text","custom"].includes(t.type))return null;const g=()=>{const D={...a||{},colorConfig:{segments:{}}};n(D);const T={...t,preferences:D};r(T);const v={};h.forEach((M,F)=>{v[M]=s.getColorForValue(M,F,void 0)}),c(v)},C=Object.keys(((B=a==null?void 0:a.colorConfig)==null?void 0:B.segments)||{}).length>0;return e.jsxs(s.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ka,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Colors"})]})}),e.jsx(s.AccordionContent,{className:"",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("div",{className:"flex items-center justify-between",children:C&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:g,children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:h.map((D,T)=>{const v=s.isDefaultColor(o[D],T),M=!v;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:i===D,onOpenChange:F=>d(F?D:null),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"h-5 w-5 shrink-0 rounded border border-input shadow-sm transition-colors hover:border-gray-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",style:{backgroundColor:o[D]}})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-3",children:e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Theme Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:p.slice(0,10).map((F,O)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",o[D]===F?"border-gray-900":"border-transparent"),style:{backgroundColor:F},onClick:()=>{f(D,F),d(null)},children:[O===T%p.length&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-white/90 px-0.5 text-[8px] font-bold text-gray-900 shadow-sm",children:"D"})}),e.jsx("span",{className:"sr-only",children:F})]},`default-${O}`))})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Popular Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:Lo.map((F,O)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",o[D]===F?"border-2 border-gray-900":F==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:F},onClick:()=>{f(D,F),d(null)},children:e.jsx("span",{className:"sr-only",children:F})},`preset-${O}`))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsx("button",{className:"text-sm font-medium text-blue-600 hover:text-blue-700",onClick:()=>{u({value:D,color:o[D]}),d(null)},children:"Custom color"}),!v&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{j(D,T),d(null)},children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:D}),M&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},D)})}),m&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>u(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Io,{color:m.color,onColorChange:D=>{f(m.value,D),u(null)},onClose:()=>u(null)})})]})]})})]})}function Dt({axis:t,label:a,type:n,config:r,onChange:l}){var y,g,C,E,R,S,N,b,I,k,L,w,B,D,T,v,M,F;const o=(O,V)=>{l({...r,[O]:V})},c=(O,V)=>{var _,W;l({...r,name:{enabled:O==="enabled"?V:((_=r==null?void 0:r.name)==null?void 0:_.enabled)??!1,text:O==="text"?V:(W=r==null?void 0:r.name)==null?void 0:W.text}})},i=(O,V)=>{var _,W;l({...r,labels:{enabled:O==="enabled"?V:((_=r==null?void 0:r.labels)==null?void 0:_.enabled)??!0,rotation:O==="rotation"?V:(W=r==null?void 0:r.labels)==null?void 0:W.rotation}})},d=(O,V)=>{l({...r,scale:{...r==null?void 0:r.scale,[O]:V===""?"auto":Number(V)}})},m=O=>{l({...r,format:O,formatOptions:void 0})},u=(O,V)=>{l({...r,formatOptions:{...r==null?void 0:r.formatOptions,[O]:V}})},h=t==="x"?["auto","top","bottom"]:["auto","left","right"],p=["auto","0","45","90","-45","-90"],f=["auto","number","currency","percent"],j=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"GBP",label:"GBP - British Pound"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"INR",label:"INR - Indian Rupee"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"},{value:"CHF",label:"CHF - Swiss Franc"},{value:"SEK",label:"SEK - Swedish Krona"},{value:"NZD",label:"NZD - New Zealand Dollar"},{value:"MXN",label:"MXN - Mexican Peso"},{value:"SGD",label:"SGD - Singapore Dollar"},{value:"HKD",label:"HKD - Hong Kong Dollar"},{value:"NOK",label:"NOK - Norwegian Krone"},{value:"KRW",label:"KRW - South Korean Won"}],x=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"en-IN",label:"English (India)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"},{value:"ja-JP",label:"Japanese"},{value:"ko-KR",label:"Korean"},{value:"ru-RU",label:"Russian"},{value:"ar-SA",label:"Arabic"},{value:"hi-IN",label:"Hindi"},{value:"nl-NL",label:"Dutch"},{value:"sv-SE",label:"Swedish"}];return e.jsxs(s.AccordionItem,{value:`${t}-axis`,className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full flex-row-reverse items-center justify-between gap-3 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex grow items-center justify-between gap-2",children:[e.jsx("span",{children:a}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:O=>o("enabled",O),onClick:O=>O.stopPropagation()})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TITLE"}),e.jsx(s.SmallSwitch,{checked:((y=r==null?void 0:r.name)==null?void 0:y.enabled)??!1,onCheckedChange:O=>c("enabled",O)})]}),((g=r==null?void 0:r.name)==null?void 0:g.enabled)&&e.jsx(je,{placeholder:`${a} title`,value:((C=r==null?void 0:r.name)==null?void 0:C.text)||"",onSave:O=>c("text",O),className:""})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(s.Select,{value:(r==null?void 0:r.position)||"auto",onValueChange:O=>o("position",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-sm",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:h.map(O=>e.jsx(s.SelectItem,{value:O,children:O==="auto"?"Auto (Default)":s.titleCase(O)},O))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(s.SmallSwitch,{checked:((E=r==null?void 0:r.labels)==null?void 0:E.enabled)!==!1,onCheckedChange:O=>i("enabled",O)})]}),((R=r==null?void 0:r.labels)==null?void 0:R.enabled)!==!1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Rotation"}),e.jsxs(s.Select,{value:String(((S=r==null?void 0:r.labels)==null?void 0:S.rotation)||"auto"),onValueChange:O=>i("rotation",O==="auto"?"auto":Number(O)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-sm",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:p.map(O=>e.jsx(s.SelectItem,{value:O,children:O==="auto"?"Auto (Default)":`${O}°`},O))})]})]})]}),n==="value"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"NUMBER FORMAT"}),e.jsxs(s.Select,{value:(r==null?void 0:r.format)||"auto",onValueChange:m,children:[e.jsx(s.SelectTrigger,{className:"h-8 text-sm",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:f.map(O=>e.jsx(s.SelectItem,{value:O,children:O==="auto"?"Auto (Default)":s.titleCase(O)},O))})]})]}),(r==null?void 0:r.format)&&r.format!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent"].includes(r.format)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(je,{type:"number",placeholder:"0",value:String(((N=r==null?void 0:r.formatOptions)==null?void 0:N.decimalPlaces)??(r.format==="currency"?2:r.format==="percent"?1:0)),onSave:O=>u("decimalPlaces",Number(O)),className:""})})]}),r.format==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(s.Select,{value:((b=r==null?void 0:r.formatOptions)==null?void 0:b.currency)||"USD",onValueChange:O=>u("currency",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-sm",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:j.map(O=>e.jsx(s.SelectItem,{value:O.value,children:O.label},O.value))})]})]}),["number","currency"].includes(r.format)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((I=r==null?void 0:r.formatOptions)==null?void 0:I.useSuffix)??!1,onCheckedChange:O=>u("useSuffix",O)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(s.Select,{value:((k=r==null?void 0:r.formatOptions)==null?void 0:k.locale)||"en-US",onValueChange:O=>u("locale",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-sm",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:x.map(O=>e.jsx(s.SelectItem,{value:O.value,children:O.label},O.value))})]})]}),r.format==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(je,{placeholder:"e.g., $",value:((L=r==null?void 0:r.formatOptions)==null?void 0:L.prefix)||"",onSave:O=>u("prefix",O),className:""})})]}),r.format==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(je,{placeholder:"e.g., units",value:((w=r==null?void 0:r.formatOptions)==null?void 0:w.suffix)||"",onSave:O=>u("suffix",O),className:""})})]})]})]}),n==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"SCALE"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(je,{type:"number",placeholder:"auto",value:((B=r==null?void 0:r.scale)==null?void 0:B.min)==="auto"||((D=r==null?void 0:r.scale)==null?void 0:D.min)===void 0?"":String(r.scale.min),onSave:O=>d("min",O),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Max"}),e.jsx("div",{className:"flex-1",children:e.jsx(je,{type:"number",placeholder:"auto",value:((T=r==null?void 0:r.scale)==null?void 0:T.max)==="auto"||((v=r==null?void 0:r.scale)==null?void 0:v.max)===void 0?"":String(r.scale.max),onSave:O=>d("max",O),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Step"}),e.jsx("div",{className:"flex-1",children:e.jsx(je,{type:"number",placeholder:"auto",value:((M=r==null?void 0:r.scale)==null?void 0:M.stepSize)==="auto"||((F=r==null?void 0:r.scale)==null?void 0:F.stepSize)===void 0?"":String(r.scale.stepSize),onSave:O=>d("stepSize",O),className:""})})]})]})]})]})]})}function Ro(){const t=s.useEditorStore(c=>c.card),a=s.useEditorStore(c=>{var i;return(i=c.card)==null?void 0:i.preferences}),{setCardPreferences:n,updateCardInFrame:r}=s.useEditorActions();if(!t)return null;const l=s.AxisConfigurator.getAxisInfo(t.type,a);if(!l.hasXAxis&&!l.hasYAxis)return null;const o=(c,i)=>{const m={...a||{},[c==="x"?"xAxisConfig":"yAxisConfig"]:i};n(m);const u={...t,preferences:m};r(u)};return e.jsxs(s.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Axes"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[l.hasXAxis&&e.jsx(Dt,{axis:"x",label:"X-Axis",type:l.xAxisType,config:a==null?void 0:a.xAxisConfig,onChange:c=>o("x",c)}),l.hasYAxis&&e.jsx(Dt,{axis:"y",label:"Y-Axis",type:l.yAxisType,config:a==null?void 0:a.yAxisConfig,onChange:c=>o("y",c)})]})})]})}function Bo(){const t=s.useEditorStore(m=>m.card),a=s.useEditorStore(m=>{var u,h,p,f;return(f=(p=(h=(u=m.card)==null?void 0:u.preferences)==null?void 0:h.chartOptions)==null?void 0:p.plugins)==null?void 0:f.legend}),{setLegendOptions:n}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r="bottom",l="center",o=!(t.type==="stackedBar"||t.type==="stackedLine"),c=(m,u)=>{const h={...a,[m]:u};n(h)},i=["top","bottom","left","right"],d=["start","center","end"];return e.jsxs(s.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Lt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:(a==null?void 0:a.display)??o,onCheckedChange:m=>c("display",m)})]}),((a==null?void 0:a.display)??o)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(a==null?void 0:a.position)||r,onValueChange:m=>c("position",m),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-sm",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:i.map(m=>e.jsx(s.SelectItem,{value:m,children:s.titleCase(m)},m))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(s.Select,{value:(a==null?void 0:a.align)||l,onValueChange:m=>c("align",m),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-sm",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:d.map(m=>e.jsx(s.SelectItem,{value:m,children:s.titleCase(m)},m))})]})]})]})]})})]})}function Fo({groupByFields:t,pivotByFields:a,metricsFields:n,sortByFields:r}){const l=s.useEditorStore(p=>{var f;return((f=p.card.customCardPreferences)==null?void 0:f.url)&&p.card.type==="custom"}),o=s.useEditorStore(p=>p.card),c=o==null?void 0:o.type,i=t.length>0||n.length>0,d=c!=="kpi",m=c!=="kpi"&&i,u=()=>c==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},h=()=>c==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs(s.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"mt-4 w-full",children:[e.jsxs(s.AccordionItem,{value:"fields",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(va,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsx(es,{zone:"groupBy",fields:t,label:u().label,placeholder:u().placeholder}),d&&e.jsx(es,{zone:"pivotBy",fields:a,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(es,{zone:"metrics",fields:n,label:h().label,placeholder:h().placeholder,hasPivotColumns:a.length>0}),m&&e.jsx(es,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})]}),!l&&e.jsxs(s.AccordionItem,{value:"configuration",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Settings,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"CONFIGURATION"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md bg-muted/50 px-3 pt-2",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[e.jsx(Oo,{}),e.jsx(Ro,{}),e.jsx(Bo,{})]})})]})]})}function Po({selectedChart:t,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:o}){const c=s.useEditorStore(h=>h.showAIDialog),i=n.length>0||r.length>0||l.length>0,{setShowAIDialog:d}=s.useEditorActions(),m=s.useEditorStore(h=>h.card),{data:u}=s.useDashboardCardQuery(m);return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col",children:[e.jsxs("div",{className:"space-y-4 px-6 pt-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h2",{className:"font-semibold",children:"Chart Configuration"})}),e.jsx(So,{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||u}),children:e.jsx(hs,{})}),!c&&e.jsxs(s.Button,{onClick:()=>d(!c),variant:"outline",className:"h-8",size:"sm",children:[e.jsx(Ra,{className:"mr-2 size-4"}),"AI"]})]}),e.jsxs(s.ScrollArea,{className:"w-full flex-1 basis-0 px-6",children:[e.jsx(Fo,{groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:o}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function zo({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 N=b=>{if(b.id===S){const I=i[0]||d;return{...b,conditions:[...b.conditions,{id:`condition-${Date.now()}`,field:I,operator:"=",value:""}]}}return{...b,groups:b.groups.map(N)}};r(N(n))},u=S=>{const N=b=>{if(b.id===S){const I=i[0]||d;return{...b,groups:[...b.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:I,operator:"=",value:""}],groups:[]}]}}return{...b,groups:b.groups.map(N)}};r(N(n))},h=(S,N)=>{const b=I=>I.id===S?{...I,conditions:I.conditions.filter(k=>k.id!==N)}:{...I,groups:I.groups.map(b)};r(b(n))},p=(S,N)=>{const b=I=>I.id===S?{...I,groups:I.groups.filter(k=>k.id!==N)}:{...I,groups:I.groups.map(b)};r(b(n))},f=(S,N,b,I)=>{if(b==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const k=L=>L.id===S?{...L,conditions:L.conditions.map(w=>w.id===N?{...w,[b]:I}:w)}:{...L,groups:L.groups.map(k)};r(k(n))},j=(S,N,b)=>{const I=k=>k.id===S?{...k,conditions:k.conditions.map(L=>L.id===N?{...L,...b}:L)}:{...k,groups:k.groups.map(I)};r(I(n))},x=(S,N)=>{const b=I=>I.id===S?{...I,logicalOperator:N}:{...I,groups:I.groups.map(b)};r(b(n))},y=(S,N)=>{const b=I=>I.id===S?{...I,negate:N}:{...I,groups:I.groups.map(b)};r(b(n))},g=(S,N,b)=>{const I=k=>k.id===S?{...k,conditions:s.arrayMove(k.conditions,N,b)}:{...k,groups:k.groups.map(I)};r(I(n))},C=(S,N,b)=>{const I=k=>k.id===S?{...k,groups:s.arrayMove(k.groups,N,b)}:{...k,groups:k.groups.map(I)};r(I(n))},E=S=>{if(!S||S.conditions.length===0&&S.groups.length===0)return"-- No filters defined";const N=I=>{let k="";typeof I.field=="object"?k=I.field.entityName?`${I.field.entityName}.${I.field.name}`:I.field.name:k=String(I.field);const L=I.operator;let w=I.value;if(I.field.dataType==="string"&&!["in","not in"].includes(I.operator))typeof w=="string"?w=`'${w}'`:Array.isArray(w)&&(w=`'${w.join(", ")}'`);else if(I.field.dataType==="date")(typeof w=="string"||w instanceof Date)&&(w=`DATE('${w}')`);else if(["in","not in"].includes(I.operator)){let B=[];Array.isArray(w)?B=w.map(D=>typeof D=="string"?`'${D}'`:String(D)):typeof w=="string"?B=w.split(",").map(D=>{const T=D.trim();return I.field.dataType==="string"?`'${T}'`:T}):typeof w=="number"&&(B=[String(w)]),w=`(${B.join(", ")})`}switch(L){case"contains":return typeof w=="string"?`${k} LIKE '%${w.replace(/'/g,"")}'`:`${k} LIKE '%${String(w)}'`;case"startsWith":return typeof w=="string"?`${k} LIKE '${w.replace(/'/g,"")}%'`:`${k} LIKE '${String(w)}%'`;case"endsWith":return typeof w=="string"?`${k} LIKE '%${w.replace(/'/g,"")}'`:`${k} LIKE '%${String(w)}'`;default:return`${k} ${L} ${w}`}},b=I=>{const k=I.conditions.map(N),L=I.groups.map(T=>b(T)),w=[...k,...L].filter(Boolean);if(w.length===0)return"";const B=w.join(` ${I.logicalOperator} `),D=w.length>1?`(${B})`:B;return I.negate?`NOT ${D}`:D};return b(S)},R=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:i,isLoading:o,addCondition:m,addGroup:u,removeCondition:h,removeGroup:p,updateCondition:f,updateConditionFields:j,updateGroupOperator:x,updateGroupNegate:y,reorderConditions:g,reorderGroups:C,generateSQLPreview:E,hasAnyFilters:R}}function Vo({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 _o=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(ua,{className:"h-3 w-3"});default:return e.jsx(s.Table,{className:"h-3 w-3"})}},Uo=t=>{if(t.qualifiedEntityName){const a=t.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function $o({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 u=Uo(m);d[u]||(d[u]={}),d[u][m.entityId]||(d[u][m.entityId]=[]),d[u][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(Vo,{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(([u,h])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[_o(h[0].entityType),e.jsx("span",{children:h[0].entityName})]}),h.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}-${u}`))},d))})]})})]})}function tt(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:u,isPending:h,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:((u==null?void 0:u.records)||[]).map(x=>({label:x[t.name]||"BLANK",value:x[t.name]||"BLANK",count:(x==null?void 0:x.count)||0})),isPending:h,error:p}}function qo({field:t,selected:a,onChange:n,placeholder:r="Select items...",className:l}){const[o,c]=ue.useState(!1),{filterValues:i}=tt(t),d=u=>{n(a.filter(h=>h!==u))},m=u=>{a.includes(u)?n(a.filter(h=>h!==u)):n([...a,u])};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(u=>{const h=i.find(p=>p.value===u);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[h==null?void 0:h.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:p=>{p.key==="Enter"&&d(u)},onMouseDown:p=>{p.preventDefault(),p.stopPropagation()},onClick:p=>{p.stopPropagation(),d(u)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},u)}):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((u,h)=>e.jsxs(s.CommandItem,{onSelect:()=>m(u.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",a.includes(u.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.count})]})]},u.value+h))})]})]})})]})})}const In=t=>{if(!t)return 0;let a=t.conditions.length;return t.groups.forEach(n=>{a+=In(n)}),a};function Yo({field:t,value:a,onChange:n,placeholder:r="Select value...",className:l}){const{filterValues:o,isPending:c,error:i}=tt(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 Go=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in"],Ho=["=","!=","contains","startsWith","endsWith","in","not in"],Ko=["=","!=",">",">=","<","<=","in","not in"],Qo=["=","!="],Wo=["=","!=",">",">=","<","<=","in","not in"];function Jo(t){switch(t){case"string":return Ho;case"number":return Ko;case"boolean":return Qo;case"date":return Wo;default:return Go}}function An({condition:t,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:o,onUpdateGroupOperator:c,availableFields:i,updateConditionFields:d}){const{attributes:m,listeners:u,setNodeRef:h,transform:p,transition:f,isDragging:j}=s.useSortable({id:t.id}),{isPending:x,error:y}=tt(t.field),g={transform:s.CSS.Transform.toString(p),transition:f};return e.jsxs("div",{ref:h,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,...u,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:C=>c(n,C),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($o,{value:t.field,onValueChange:C=>{d(n,t.id,{field:C,value:""})},availableFields:i,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:C=>{C==="in"||C==="not in"?d(n,t.id,{operator:C,value:[]}):d(n,t.id,{operator:C,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-28",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Jo(s.getDataType(t.field.dataType)).map(C=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:C,children:C},C))})]}),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..."]}):y?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(qo,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(C=>typeof C=="string")?t.value:[],onChange:C=>d(n,t.id,{value:C}),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:C=>d(n,t.id,{value:C.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(Yo,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:C=>d(n,t.id,{value:C}),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:C=>d(n,t.id,{value:C==="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:C=>l(n,t.id,"value",C.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 Xo({group:t,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:o,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onReorderConditions:m,onReorderGroups:u,onAddCondition:h,onAddGroup:p,availableFields:f,renderFilterGroup:j,updateConditionFields:x}){const{attributes:y,listeners:g,setNodeRef:C,transform:E,transition:R,isDragging:S}=s.useSortable({id:t.id}),N={transform:s.CSS.Transform.toString(E),transition:R},b=k=>{const{active:L,over:w}=k;if(w&&L.id!==w.id){const B=t.conditions.findIndex(T=>T.id===L.id),D=t.conditions.findIndex(T=>T.id===w.id);B!==-1&&D!==-1&&m(t.id,B,D)}},I=k=>{const{active:L,over:w}=k;if(w&&L.id!==w.id&&n){const B=t.groups.findIndex(T=>T.id===L.id),D=t.groups.findIndex(T=>T.id===w.id);B!==-1&&D!==-1&&u(n,B,D)}};return e.jsxs("div",{ref:C,style:N,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",{...y,...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:k=>r(t.id,k),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(k=>k.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((k,L)=>e.jsx(An,{condition:k,index:L,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:f,updateConditionFields:x},k.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:I,children:e.jsx(s.SortableContext,{items:t.groups.map(k=>k.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(k=>j(k,a+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>p(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Zo({filters:t,availableFields:a,onSave:n,onClearAll:r,onCancel:l}){const{currentFilters:o,availableFields:c,isLoading:i,addCondition:d,addGroup:m,removeCondition:u,removeGroup:h,updateCondition:p,updateConditionFields:f,updateGroupOperator:j,updateGroupNegate:x,reorderConditions:y,reorderGroups:g,generateSQLPreview:C,hasAnyFilters:E,setCurrentFilters:R}=zo({initialFilters:t,availableFields:a}),S=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[N,b]=A.useState(!1),I=(w,B,D)=>{const T=v=>v.id===w?{...v,conditions:v.conditions.map(M=>M.id===B?{...M,field:D,dataType:D.dataType}:M)}:{...v,groups:v.groups.map(T)};R(T(o))},k=(w,B=0,D)=>B===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:T=>{const{active:v,over:M}=T;if(M&&v.id!==M.id){const F=w.conditions.findIndex(V=>V.id===v.id),O=w.conditions.findIndex(V=>V.id===M.id);F!==-1&&O!==-1&&y(w.id,F,O)}},children:e.jsx(s.SortableContext,{items:w.conditions.map(T=>T.id),strategy:s.verticalListSortingStrategy,children:w.conditions.map((T,v)=>e.jsx(An,{condition:T,index:v,groupId:w.id,groupLogicalOperator:w.logicalOperator,onUpdateCondition:p,onUpdateField:I,onRemoveCondition:u,onUpdateGroupOperator:j,availableFields:c,updateConditionFields:f},T.id))})}),e.jsx(s.DndContext,{sensors:S,collisionDetection:s.closestCenter,onDragEnd:T=>{const{active:v,over:M}=T;if(M&&v.id!==M.id){const F=w.groups.findIndex(V=>V.id===v.id),O=w.groups.findIndex(V=>V.id===M.id);F!==-1&&O!==-1&&g(w.id,F,O)}},children:e.jsx(s.SortableContext,{items:w.groups.map(T=>T.id),strategy:s.verticalListSortingStrategy,children:w.groups.map(T=>k(T,B+1,w.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>d(w.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),N&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>m(w.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},w.id):e.jsx(Xo,{group:w,depth:B,parentGroupId:D,onUpdateGroupOperator:j,onUpdateGroupNegate:x,onRemoveGroup:h,onUpdateCondition:p,onUpdateField:I,onRemoveCondition:u,onReorderConditions:y,onReorderGroups:g,onAddCondition:d,onAddGroup:m,availableFields:c,renderFilterGroup:k,updateConditionFields:f},w.id),L=In(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..."})]}):k(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:N,onCheckedChange:w=>b(!!w)}),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)"})]})}),E&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:C(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(E?o:null),children:"Apply Filters"})]})]})}function ei({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(Zo,{filters:a,availableFields:l,onSave:i,onCancel:()=>c(!1),onClearAll:d})]})]})}function si({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]),u=A.useCallback(j=>{o(j.active.id)},[]),h=A.useCallback(j=>{const{active:x,over:y}=j;if(!y||!t){o(null);return}const g=x.id,C=y.id,E=m(g),R=m(C)||C;if(E==="source"&&R==="sortBy"){o(null);return}if(E==="source"&&R!=="source"&&R!=="sortBy"){const S=[...a].find(k=>k.id===g);if(!S){o(null);return}const N=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(N.length>0){const k=N[0].qualifiedEntityName;if(!k){o(null);return}if(k!==S.qualifiedEntityName&&S.qualifiedEntityName)if(i){if(!En(k,S.qualifiedEntityName,i)){As(),o(null);return}}else{As(),o(null);return}}const b=n(R);if(Ms(S,b)){o(null);return}const I=s.getNewField(S,R);o(null),r(R,[...b,I]);return}if(E&&R&&E!=="source"&&R!=="source"&&E!==R){const S=n(E),N=n(R),b=S.find(L=>L.id===g);if(!b){o(null);return}const I=s.getNewField(b,R);if(o(null),R==="sortBy"){if(E==="pivotBy"){o(null);return}Ms(b,N)||r(R,[...N,I]);return}const k=S.filter(L=>L.id!==g);r(E,k),r(R,[...N,I]);return}if(E&&R&&E===R&&E!=="source"){const S=n(E),N=S.findIndex(I=>I.id===g),b=S.findIndex(I=>I.id===C);if(N!==b){const I=s.arrayMove(S,N,b);r(E,I)}}o(null)},[t,a,n,r,m,i]),p=l?d.find(j=>j.id===l):null;return{activeId:l,activeField:p,handleDragStart:u,handleDragEnd:h}}function ti({onAdvancedToggle:t,onDebugToggle:a,onAccept:n}){const{currentUser:r}=Ne();r==null||r.role;const[l,o]=A.useState(!1),c=s.useEditorStore(g=>g.isDevMode),i=s.useEditorStore(g=>g.card),d=s.useEditorStore(g=>g.card.dataSource);s.isExplorerCard(i);const{config:m}=A.useContext(s.SemaphorContext).tokenProps,u=(m==null?void 0:m.showAdvancedMode)!==!1,{setIsDevMode:h}=s.useEditorActions(),p=s.useEditorStore(g=>g.showAIDialog),f=s.useEditorStore(g=>g.frame),j=s.useManagementStore(g=>g.selectedVisual),x=(j==null?void 0:j.id)===(f==null?void 0:f.id),{setShowAIDialog:y}=s.useEditorActions();return e.jsxs("div",{className:s.cn("flex items-center justify-between px-6 py-3",p&&"justify-end",!u&&"justify-end"),children:[u&&t&&!p&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{className:s.cn("",{}),checked:c,onCheckedChange:()=>h(!c),id:"advanced-mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium",children:"Advanced Mode"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[(r==null?void 0:r.type)!=="tenant"&&e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 p-0",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsx(s.DropdownMenuContent,{align:"end",children:e.jsxs(s.DropdownMenuItem,{onClick:()=>{o(!0)},children:[e.jsx(s.Database,{className:"mr-2 h-4 w-4"}),"Set Data Context"]})})]}),e.jsx(Gs,{}),n&&!x&&e.jsx(Ys,{variant:"default"}),x&&e.jsx(nl,{}),a&&s.isDevEnv]}),l&&e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(d==null?void 0:d.selectedEntities)||[],open:l,onOpenChange:o,dataSource:d||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function ni({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 ai=[{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 ri(){var d,m;const t=s.useEditorStore(u=>u.card),{updateRowLimit:a}=s.useEditorActions(),[n,r]=A.useState(!1),[l,o]=A.useState(""),c=u=>{if(u==="custom"){r(!0);return}r(!1),a(t.id,parseInt(u))},i=u=>{const h=u.target.value;o(h),h&&!isNaN(parseInt(h))&&a(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(s.Input,{type:"number",value:l,onChange: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:ai.map(u=>e.jsx(s.SelectItem,{value:u.value,children:u.label},u.value))})]})})}function li({isOpen:t,onClose:a}){const n=Qt(a,{enabled:t}),r=s.useEditorStore(u=>{var h;return((h=u.card.customCardPreferences)==null?void 0:h.url)||""}),l=s.useEditorStore(u=>u.card),o=s.useEditorStore(u=>{var h;return((h=u.card.customCardPreferences)==null?void 0:h.pluginChartType)||""}),c=s.useEditorStore(u=>{var h;return((h=u.card.customCardPreferences)==null?void 0:h.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 oi({activeView:t,onViewChange:a,showDebug:n,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:d,activeCard:m,columns:u,columnsLoading:h,columnsError:p}){var M;const f=s.useEditorStore(F=>F.card);s.useEditorStore(F=>F.frame);const j=s.useDashboardStore(F=>F.filterValues),{updateCardConfig:x,setCard:y,updateCardInFrame:g}=s.useEditorActions(),C=s.useEditorStore(F=>F.showAIDialog),[E,R]=A.useState(!1),S=s.useEditorStore(F=>{var O;return((O=F.card.customCardPreferences)==null?void 0:O.url)&&F.card.type==="custom"}),{data:N,errorMessage:b,isPending:I,isLoading:k,isFetching:L,pagination:w}=s.useDashboardCardQuery(m),B=(F,O)=>{const V={...m,paginationConfig:{page:F+1,pageSize:O}};y(V),g(V)};function D(){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 (",u.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:h?"Loading...":p?"Error loading columns":JSON.stringify(u.slice(0,5),null,2)})]})]})})}const T=F=>{if(!f.config)return;if(!F.length){x(f.id,{...f.config,sortByColumns:[]});return}const O=f.config,V=F.map(({id:_,desc:W})=>{var H,U;const Q=(H=O.metricColumns)==null?void 0:H.find(P=>P.label===_),$=(U=O.groupByColumns)==null?void 0:U.find(P=>P.label===_),q=Q||$;return q?{id:s.getFieldId("sortBy",q),name:q.name,dataType:q.dataType,label:q.label,qualifiedEntityName:q.qualifiedEntityName,entityId:q.entityId,entityName:q.entityName,entityType:q.entityType,role:"sortby",direction:W?"desc":"asc"}:null}).filter(_=>_!==null);x(f.id,{...O,sortByColumns:V})},v=A.useMemo(()=>{var F,O;return(O=(F=f.config)==null?void 0:F.sortByColumns)==null?void 0:O.map(V=>({id:V.label,desc:V.direction==="desc"}))},[(M=f.config)==null?void 0:M.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[e.jsx(ti,{showDebug:n,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:d}),n&&D(),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"&&C&&e.jsx(jn,{variant:"outline"}),e.jsx(ni,{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(ri,{})}),C&&e.jsx(hs,{})]}),e.jsx("div",{className:s.cn("flex grow items-center justify-end"),children:t==="chart"&&e.jsx(yn,{})})]}),!E&&S&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>R(!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(Aa,{className:"size-4"})}),e.jsxs("div",{className:"mt-3 flex grow flex-col",children:[t==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:e.jsx(bn,{})}),t==="table"&&(N==null?void 0:N.records)&&e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:e.jsx(s.TableVisual,{card:m,data:(N==null?void 0:N.records)||[],paginationMetadata:w,onPaginationChange:B,isLoading:k||L,onSortChange:T,sortState:v})}),t==="sql"&&e.jsx("div",{className:"p-6",children:e.jsxs("div",{className:"rounded-md bg-background",children:[(N==null?void 0:N.sql)&&e.jsx("h3",{className:"mb-3 text-sm font-medium",children:"Generated SQL Query"}),e.jsx(cn,{sql:N==null?void 0:N.sql,error:b})]})})]}),e.jsx(li,{isOpen:E,onClose:()=>R(!1)})]})]})}function ii({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(Tn,{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 ci=()=>{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 di(){var $,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(H=>H.showAIDialog),m=s.useDashboardStore(H=>H.isVisualEditing),{setCardType:u}=s.useEditorActions(),h=s.useEditorStore(H=>H.card.type);A.useEffect(()=>ci(),[]);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)},y=H=>{u(H)},g=s.useEditorStore(H=>H.frame),C=s.useEditorStore(H=>H.card);s.useEditorStore(H=>H.activeTabCardId),s.useEditorStore(H=>H.actions.getAvailableFields);const{addCard:E,removeCard:R,updateCard:S,setActiveCard:N,updateFilters:b}=s.useEditorActions(),{columns:I=[],isLoading:k,error:L}=s.useColumns(),w=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),B=C,{getFieldsForContainer:D,setFieldsForContainer:T}=et(B),{activeField:v,handleDragStart:M,handleDragEnd:F}=si({activeCardId:g.activeCardId,sourceFields:I,getFieldsForContainer:D,setFieldsForContainer:T}),O=(H,U)=>{U&&b(H,U)},V=H=>{var U;S(H,{config:{...(U=g.cards.find(P=>P.id===H))==null?void 0:U.config,filters:void 0}})},_=I,W=H=>{if(!H)return 0;let U=H.conditions.length;return H.groups.forEach(P=>{U+=W(P)}),U},Q=W((($=B==null?void 0:B.config)==null?void 0:$.filters)||null);return e.jsxs(s.DndContext,{sensors:w,collisionDetection:s.closestCenter,onDragStart:M,onDragEnd:F,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(vo,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(Po,{selectedChart:h,onChartChange:y,groupByFields:D("groupBy"),pivotByFields:D("pivotBy"),metricsFields:D("metrics"),sortByFields:D("sortBy")}),e.jsx(oi,{selectedChart:h,activeView:t,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onAccept:p,onClear:f,onAdvancedToggle:j,onFiltersClick:x,filterCount:Q,activeCard:B,dataSourceState:C.dataSource||s.EMPTY_DATA_SOURCE,columns:I,columnsLoading:k,columnsError:L,getFieldsForContainer:D,cards:g.cards,activeCardId:g.activeCardId,addCard:E,setActiveCard:N})]}),!c&&m&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>i(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),B&&e.jsx(ei,{cardId:B.id,filters:((q=B.config)==null?void 0:q.filters)||null,onFiltersChange:O,onClearFilters:V,availableFields:_,isOpen:l,onOpenChange:o}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(ii,{activeField:v||null})})]})}function ui({authToken:t,onSave:a,onClose:n}){const r=A.useRef(null),l=s.useEditorStore(C=>C.showAIDialog),o=s.useEditorStore(C=>C.isDevMode),{setAuthToken:c}=s.useDashboardActions(),{setShowAIDialog:i,setOnSave:d,setOnClose:m}=s.useEditorActions(),{handleDragOver:u,handleDragEnd:h,handleDragStart:p,handleDragCancel:f,sensors:j}=qr();A.useEffect(()=>{a&&d(a),n&&m(n)},[a,d,n,m]),A.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),A.useEffect(()=>{var C,E;l?((C=r.current)==null||C.resize(40),i(!0)):(i(!1),(E=r.current)==null||E.resize(0))},[l,i]);function x(C){C<1?i(!1):l||i(!0)}function y(){return e.jsxs(e.Fragment,{children:[e.jsx(ln,{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(ro,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(bt,{})})]})]})}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(di,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(bt,{})})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:o?e.jsx(s.DndContext,{sensors:j,onDragStart:p,onDragEnd:h,onDragOver:u,onDragCancel:f,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:y()})}):g()})}function mi(){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(ui,{onSave:l,onClose:o})})}function hi(){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}=Sn();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($s,{column:o}),e.jsx("span",{children:o.column_name})]})},o.column_name)})})}function xi(){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(ln,{type:"filter",ColumnsComponent:()=>e.jsx(hi,{})})})]})}function pi(){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 fi(){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(pi,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(xi,{})})]})}function gi(){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 ji({showControls:t=!1,showFooter:a=!0,...n}){return typeof window>"u"?null: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(gi,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx(zr,{}),e.jsxs(s.DashboardPanel,{...n,children:[e.jsx(mi,{}),e.jsx(fi,{})]})]})]})]})})}exports.DashboardPlus=ji;exports.ResourceManagementPanel=an;exports.ScheduleDashboard=_t;exports.SelectComponent=Ve;exports.cleanCard=Pt;exports.downloadPdf=Vt;exports.getDashbaordStateWithoutData=as;
|