react-semaphor 0.1.8 → 0.1.11
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-DMGEOoiW.js +280 -0
- package/dist/chunks/{dashboard-plus-B2xi3W9Q.js → dashboard-plus-D_xcZ7mX.js} +6180 -5835
- package/dist/chunks/{index-C8kbVn8_.js → index-BlOXjv--.js} +16999 -16731
- package/dist/chunks/{index-D9GAKDSP.js → index-DOujqHIH.js} +210 -205
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +3 -3
- package/dist/style.css +1 -1
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +1 -1
- package/dist/types/dashboard.d.ts +1 -1
- package/dist/types/main.d.ts +16 -1
- package/dist/types/surfboard.d.ts +1 -1
- package/dist/types/types.d.ts +1 -1
- package/package.json +1 -1
- package/dist/chunks/dashboard-plus-BM0LqZoZ.js +0 -270
|
@@ -1,270 +0,0 @@
|
|
|
1
|
-
"use strict";const e=require("react/jsx-runtime"),s=require("./index-D9GAKDSP.js"),k=require("react"),Ft=require("react-dom");function Ot(t){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const a in t)if(a!=="default"){const r=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:()=>t[a]})}}return n.default=t,Object.freeze(n)}const ss=Ot(k);/**
|
|
2
|
-
* @license lucide-react v0.453.0 - ISC
|
|
3
|
-
*
|
|
4
|
-
* This source code is licensed under the ISC license.
|
|
5
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
6
|
-
*/const Pt=s.createLucideIcon("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]);/**
|
|
7
|
-
* @license lucide-react v0.453.0 - ISC
|
|
8
|
-
*
|
|
9
|
-
* This source code is licensed under the ISC license.
|
|
10
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
11
|
-
*/const Bt=s.createLucideIcon("BookOpenText",[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M16 12h2",key:"7q9ll5"}],["path",{d:"M16 8h2",key:"msurwy"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}],["path",{d:"M6 12h2",key:"32wvfc"}],["path",{d:"M6 8h2",key:"30oboj"}]]);/**
|
|
12
|
-
* @license lucide-react v0.453.0 - ISC
|
|
13
|
-
*
|
|
14
|
-
* This source code is licensed under the ISC license.
|
|
15
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
16
|
-
*/const gs=s.createLucideIcon("Building",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",ry:"2",key:"76otgf"}],["path",{d:"M9 22v-4h6v4",key:"r93iot"}],["path",{d:"M8 6h.01",key:"1dz90k"}],["path",{d:"M16 6h.01",key:"1x0f13"}],["path",{d:"M12 6h.01",key:"1vi96p"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M8 14h.01",key:"6423bh"}]]);/**
|
|
17
|
-
* @license lucide-react v0.453.0 - ISC
|
|
18
|
-
*
|
|
19
|
-
* This source code is licensed under the ISC license.
|
|
20
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
21
|
-
*/const Os=s.createLucideIcon("Calculator",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["line",{x1:"8",x2:"16",y1:"6",y2:"6",key:"x4nwl0"}],["line",{x1:"16",x2:"16",y1:"14",y2:"18",key:"wjye3r"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M8 18h.01",key:"lrp35t"}]]);/**
|
|
22
|
-
* @license lucide-react v0.453.0 - ISC
|
|
23
|
-
*
|
|
24
|
-
* This source code is licensed under the ISC license.
|
|
25
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
26
|
-
*/const Vt=s.createLucideIcon("CirclePlus",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]]);/**
|
|
27
|
-
* @license lucide-react v0.453.0 - ISC
|
|
28
|
-
*
|
|
29
|
-
* This source code is licensed under the ISC license.
|
|
30
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
31
|
-
*/const zt=s.createLucideIcon("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/**
|
|
32
|
-
* @license lucide-react v0.453.0 - ISC
|
|
33
|
-
*
|
|
34
|
-
* This source code is licensed under the ISC license.
|
|
35
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
36
|
-
*/const Ps=s.createLucideIcon("Code",[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]]);/**
|
|
37
|
-
* @license lucide-react v0.453.0 - ISC
|
|
38
|
-
*
|
|
39
|
-
* This source code is licensed under the ISC license.
|
|
40
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
41
|
-
*/const Ut=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"}]]);/**
|
|
42
|
-
* @license lucide-react v0.453.0 - ISC
|
|
43
|
-
*
|
|
44
|
-
* This source code is licensed under the ISC license.
|
|
45
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
46
|
-
*/const Gt=s.createLucideIcon("Component",[["path",{d:"M15.536 11.293a1 1 0 0 0 0 1.414l2.376 2.377a1 1 0 0 0 1.414 0l2.377-2.377a1 1 0 0 0 0-1.414l-2.377-2.377a1 1 0 0 0-1.414 0z",key:"1uwlt4"}],["path",{d:"M2.297 11.293a1 1 0 0 0 0 1.414l2.377 2.377a1 1 0 0 0 1.414 0l2.377-2.377a1 1 0 0 0 0-1.414L6.088 8.916a1 1 0 0 0-1.414 0z",key:"10291m"}],["path",{d:"M8.916 17.912a1 1 0 0 0 0 1.415l2.377 2.376a1 1 0 0 0 1.414 0l2.377-2.376a1 1 0 0 0 0-1.415l-2.377-2.376a1 1 0 0 0-1.414 0z",key:"1tqoq1"}],["path",{d:"M8.916 4.674a1 1 0 0 0 0 1.414l2.377 2.376a1 1 0 0 0 1.414 0l2.377-2.376a1 1 0 0 0 0-1.414l-2.377-2.377a1 1 0 0 0-1.414 0z",key:"1x6lto"}]]);/**
|
|
47
|
-
* @license lucide-react v0.453.0 - ISC
|
|
48
|
-
*
|
|
49
|
-
* This source code is licensed under the ISC license.
|
|
50
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
51
|
-
*/const _t=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"}]]);/**
|
|
52
|
-
* @license lucide-react v0.453.0 - ISC
|
|
53
|
-
*
|
|
54
|
-
* This source code is licensed under the ISC license.
|
|
55
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
56
|
-
*/const Yt=s.createLucideIcon("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"}]]);/**
|
|
57
|
-
* @license lucide-react v0.453.0 - ISC
|
|
58
|
-
*
|
|
59
|
-
* This source code is licensed under the ISC license.
|
|
60
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
61
|
-
*/const $t=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"}]]);/**
|
|
62
|
-
* @license lucide-react v0.453.0 - ISC
|
|
63
|
-
*
|
|
64
|
-
* This source code is licensed under the ISC license.
|
|
65
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
66
|
-
*/const qt=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"}]]);/**
|
|
67
|
-
* @license lucide-react v0.453.0 - ISC
|
|
68
|
-
*
|
|
69
|
-
* This source code is licensed under the ISC license.
|
|
70
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
71
|
-
*/const Kt=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"}]]);/**
|
|
72
|
-
* @license lucide-react v0.453.0 - ISC
|
|
73
|
-
*
|
|
74
|
-
* This source code is licensed under the ISC license.
|
|
75
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
76
|
-
*/const Ht=s.createLucideIcon("GitCompareArrows",[["circle",{cx:"5",cy:"6",r:"3",key:"1qnov2"}],["path",{d:"M12 6h5a2 2 0 0 1 2 2v7",key:"1yj91y"}],["path",{d:"m15 9-3-3 3-3",key:"1lwv8l"}],["circle",{cx:"19",cy:"18",r:"3",key:"1qljk2"}],["path",{d:"M12 18H7a2 2 0 0 1-2-2V9",key:"16sdep"}],["path",{d:"m9 15 3 3-3 3",key:"1m3kbl"}]]);/**
|
|
77
|
-
* @license lucide-react v0.453.0 - ISC
|
|
78
|
-
*
|
|
79
|
-
* This source code is licensed under the ISC license.
|
|
80
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
81
|
-
*/const Wt=s.createLucideIcon("Glasses",[["circle",{cx:"6",cy:"15",r:"4",key:"vux9w4"}],["circle",{cx:"18",cy:"15",r:"4",key:"18o8ve"}],["path",{d:"M14 15a2 2 0 0 0-2-2 2 2 0 0 0-2 2",key:"1ag4bs"}],["path",{d:"M2.5 13 5 7c.7-1.3 1.4-2 3-2",key:"1hm1gs"}],["path",{d:"M21.5 13 19 7c-.7-1.3-1.5-2-3-2",key:"1r31ai"}]]);/**
|
|
82
|
-
* @license lucide-react v0.453.0 - ISC
|
|
83
|
-
*
|
|
84
|
-
* This source code is licensed under the ISC license.
|
|
85
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
86
|
-
*/const We=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"}]]);/**
|
|
87
|
-
* @license lucide-react v0.453.0 - ISC
|
|
88
|
-
*
|
|
89
|
-
* This source code is licensed under the ISC license.
|
|
90
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
91
|
-
*/const Qt=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"}]]);/**
|
|
92
|
-
* @license lucide-react v0.453.0 - ISC
|
|
93
|
-
*
|
|
94
|
-
* This source code is licensed under the ISC license.
|
|
95
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
96
|
-
*/const as=s.createLucideIcon("Hash",[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]]);/**
|
|
97
|
-
* @license lucide-react v0.453.0 - ISC
|
|
98
|
-
*
|
|
99
|
-
* This source code is licensed under the ISC license.
|
|
100
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
101
|
-
*/const Jt=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"}]]);/**
|
|
102
|
-
* @license lucide-react v0.453.0 - ISC
|
|
103
|
-
*
|
|
104
|
-
* This source code is licensed under the ISC license.
|
|
105
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
106
|
-
*/const Xt=s.createLucideIcon("ListEnd",[["path",{d:"M16 12H3",key:"1a2rj7"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M10 18H3",key:"13769t"}],["path",{d:"M21 6v10a2 2 0 0 1-2 2h-5",key:"ilrcs8"}],["path",{d:"m16 16-2 2 2 2",key:"kkc6pm"}]]);/**
|
|
107
|
-
* @license lucide-react v0.453.0 - ISC
|
|
108
|
-
*
|
|
109
|
-
* This source code is licensed under the ISC license.
|
|
110
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
111
|
-
*/const Zt=s.createLucideIcon("ListStart",[["path",{d:"M16 12H3",key:"1a2rj7"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"M10 6H3",key:"lf8lx7"}],["path",{d:"M21 18V8a2 2 0 0 0-2-2h-5",key:"1hghli"}],["path",{d:"m16 8-2-2 2-2",key:"160uvd"}]]);/**
|
|
112
|
-
* @license lucide-react v0.453.0 - ISC
|
|
113
|
-
*
|
|
114
|
-
* This source code is licensed under the ISC license.
|
|
115
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
116
|
-
*/const ea=s.createLucideIcon("ListX",[["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"m19 10-4 4",key:"1tz659"}],["path",{d:"m15 10 4 4",key:"1n7nei"}]]);/**
|
|
117
|
-
* @license lucide-react v0.453.0 - ISC
|
|
118
|
-
*
|
|
119
|
-
* This source code is licensed under the ISC license.
|
|
120
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
121
|
-
*/const sa=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"}]]);/**
|
|
122
|
-
* @license lucide-react v0.453.0 - ISC
|
|
123
|
-
*
|
|
124
|
-
* This source code is licensed under the ISC license.
|
|
125
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
126
|
-
*/const ta=s.createLucideIcon("MapPin",[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}]]);/**
|
|
127
|
-
* @license lucide-react v0.453.0 - ISC
|
|
128
|
-
*
|
|
129
|
-
* This source code is licensed under the ISC license.
|
|
130
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
131
|
-
*/const aa=s.createLucideIcon("Menu",[["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}],["line",{x1:"4",x2:"20",y1:"6",y2:"6",key:"1owob3"}],["line",{x1:"4",x2:"20",y1:"18",y2:"18",key:"yk5zj1"}]]);/**
|
|
132
|
-
* @license lucide-react v0.453.0 - ISC
|
|
133
|
-
*
|
|
134
|
-
* This source code is licensed under the ISC license.
|
|
135
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
136
|
-
*/const na=s.createLucideIcon("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]);/**
|
|
137
|
-
* @license lucide-react v0.453.0 - ISC
|
|
138
|
-
*
|
|
139
|
-
* This source code is licensed under the ISC license.
|
|
140
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
141
|
-
*/const js=s.createLucideIcon("MoveHorizontal",[["path",{d:"m18 8 4 4-4 4",key:"1ak13k"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}]]);/**
|
|
142
|
-
* @license lucide-react v0.453.0 - ISC
|
|
143
|
-
*
|
|
144
|
-
* This source code is licensed under the ISC license.
|
|
145
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
146
|
-
*/const vs=s.createLucideIcon("MoveVertical",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m8 18 4 4 4-4",key:"bh5tu3"}],["path",{d:"m8 6 4-4 4 4",key:"ybng9g"}]]);/**
|
|
147
|
-
* @license lucide-react v0.453.0 - ISC
|
|
148
|
-
*
|
|
149
|
-
* This source code is licensed under the ISC license.
|
|
150
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
151
|
-
*/const ra=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"}]]);/**
|
|
152
|
-
* @license lucide-react v0.453.0 - ISC
|
|
153
|
-
*
|
|
154
|
-
* This source code is licensed under the ISC license.
|
|
155
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
156
|
-
*/const la=s.createLucideIcon("PanelLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]);/**
|
|
157
|
-
* @license lucide-react v0.453.0 - ISC
|
|
158
|
-
*
|
|
159
|
-
* This source code is licensed under the ISC license.
|
|
160
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
161
|
-
*/const $e=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"}]]);/**
|
|
162
|
-
* @license lucide-react v0.453.0 - ISC
|
|
163
|
-
*
|
|
164
|
-
* This source code is licensed under the ISC license.
|
|
165
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
166
|
-
*/const bs=s.createLucideIcon("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/**
|
|
167
|
-
* @license lucide-react v0.453.0 - ISC
|
|
168
|
-
*
|
|
169
|
-
* This source code is licensed under the ISC license.
|
|
170
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
171
|
-
*/const oa=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"}]]);/**
|
|
172
|
-
* @license lucide-react v0.453.0 - ISC
|
|
173
|
-
*
|
|
174
|
-
* This source code is licensed under the ISC license.
|
|
175
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
176
|
-
*/const Fe=s.createLucideIcon("Save",[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]);/**
|
|
177
|
-
* @license lucide-react v0.453.0 - ISC
|
|
178
|
-
*
|
|
179
|
-
* This source code is licensed under the ISC license.
|
|
180
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
181
|
-
*/const Ve=s.createLucideIcon("Shapes",[["path",{d:"M8.3 10a.7.7 0 0 1-.626-1.079L11.4 3a.7.7 0 0 1 1.198-.043L16.3 8.9a.7.7 0 0 1-.572 1.1Z",key:"1bo67w"}],["rect",{x:"3",y:"14",width:"7",height:"7",rx:"1",key:"1bkyp8"}],["circle",{cx:"17.5",cy:"17.5",r:"3.5",key:"w3z12y"}]]);/**
|
|
182
|
-
* @license lucide-react v0.453.0 - ISC
|
|
183
|
-
*
|
|
184
|
-
* This source code is licensed under the ISC license.
|
|
185
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
186
|
-
*/const Ee=s.createLucideIcon("Share2",[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]]);/**
|
|
187
|
-
* @license lucide-react v0.453.0 - ISC
|
|
188
|
-
*
|
|
189
|
-
* This source code is licensed under the ISC license.
|
|
190
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
191
|
-
*/const ia=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"}]]);/**
|
|
192
|
-
* @license lucide-react v0.453.0 - ISC
|
|
193
|
-
*
|
|
194
|
-
* This source code is licensed under the ISC license.
|
|
195
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
196
|
-
*/const ca=s.createLucideIcon("ShieldX",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m14.5 9.5-5 5",key:"17q4r4"}],["path",{d:"m9.5 9.5 5 5",key:"18nt4w"}]]);/**
|
|
197
|
-
* @license lucide-react v0.453.0 - ISC
|
|
198
|
-
*
|
|
199
|
-
* This source code is licensed under the ISC license.
|
|
200
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
201
|
-
*/const da=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"}]]);/**
|
|
202
|
-
* @license lucide-react v0.453.0 - ISC
|
|
203
|
-
*
|
|
204
|
-
* This source code is licensed under the ISC license.
|
|
205
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
206
|
-
*/const Bs=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"}]]);/**
|
|
207
|
-
* @license lucide-react v0.453.0 - ISC
|
|
208
|
-
*
|
|
209
|
-
* This source code is licensed under the ISC license.
|
|
210
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
211
|
-
*/const ua=s.createLucideIcon("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/**
|
|
212
|
-
* @license lucide-react v0.453.0 - ISC
|
|
213
|
-
*
|
|
214
|
-
* This source code is licensed under the ISC license.
|
|
215
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
216
|
-
*/const ma=s.createLucideIcon("Sun",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]]);/**
|
|
217
|
-
* @license lucide-react v0.453.0 - ISC
|
|
218
|
-
*
|
|
219
|
-
* This source code is licensed under the ISC license.
|
|
220
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
221
|
-
*/const Vs=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"}]]);/**
|
|
222
|
-
* @license lucide-react v0.453.0 - ISC
|
|
223
|
-
*
|
|
224
|
-
* This source code is licensed under the ISC license.
|
|
225
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
226
|
-
*/const ha=s.createLucideIcon("Tags",[["path",{d:"m15 5 6.3 6.3a2.4 2.4 0 0 1 0 3.4L17 19",key:"1cbfv1"}],["path",{d:"M9.586 5.586A2 2 0 0 0 8.172 5H3a1 1 0 0 0-1 1v5.172a2 2 0 0 0 .586 1.414L8.29 18.29a2.426 2.426 0 0 0 3.42 0l3.58-3.58a2.426 2.426 0 0 0 0-3.42z",key:"135mg7"}],["circle",{cx:"6.5",cy:"9.5",r:".5",fill:"currentColor",key:"5pm5xn"}]]);/**
|
|
227
|
-
* @license lucide-react v0.453.0 - ISC
|
|
228
|
-
*
|
|
229
|
-
* This source code is licensed under the ISC license.
|
|
230
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
231
|
-
*/const xa=s.createLucideIcon("Terminal",[["polyline",{points:"4 17 10 11 4 5",key:"akl6gq"}],["line",{x1:"12",x2:"20",y1:"19",y2:"19",key:"q2wloq"}]]);/**
|
|
232
|
-
* @license lucide-react v0.453.0 - ISC
|
|
233
|
-
*
|
|
234
|
-
* This source code is licensed under the ISC license.
|
|
235
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
236
|
-
*/const zs=s.createLucideIcon("ToggleLeft",[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"6",ry:"6",key:"f2vt7d"}],["circle",{cx:"8",cy:"12",r:"2",key:"1nvbw3"}]]);/**
|
|
237
|
-
* @license lucide-react v0.453.0 - ISC
|
|
238
|
-
*
|
|
239
|
-
* This source code is licensed under the ISC license.
|
|
240
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
241
|
-
*/const qe=s.createLucideIcon("Type",[["polyline",{points:"4 7 4 4 20 4 20 7",key:"1nosan"}],["line",{x1:"9",x2:"15",y1:"20",y2:"20",key:"swin9y"}],["line",{x1:"12",x2:"12",y1:"4",y2:"20",key:"1tx1rr"}]]);/**
|
|
242
|
-
* @license lucide-react v0.453.0 - ISC
|
|
243
|
-
*
|
|
244
|
-
* This source code is licensed under the ISC license.
|
|
245
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
246
|
-
*/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 fa(){const{setTheme:t}=s.useTheme(),n=s.useDashboardStore(a=>a.actions.setDashboardTheme);return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsxs(s.Button,{className:"h-7 p-2",variant:"ghost",size:"sm",children:[e.jsx(ma,{strokeWidth:1.5,className:"h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(na,{strokeWidth:1.5,className:"absolute h-4 w-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),e.jsx("span",{className:"sr-only",children:"Toggle theme"})]})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuItem,{onClick:()=>{t("light"),n("light")},children:"Light"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("dark"),n("dark")},children:"Dark"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("system"),n("system")},children:"System"})]})]})}function Ke(t){var n;return{...t,sheets:(n=t==null?void 0:t.sheets)==null?void 0:n.map(a=>{var r;return{...a,frames:(r=a.frames)==null?void 0:r.map(l=>{var o;return{...l,cards:(o=l.cards)==null?void 0:o.map(c=>Us(c))}})}})}}function Us(t){return{...t,customCfg:ga(t.customCfg),data:[]}}function ga(t){var n,a;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(a=(n=t==null?void 0:t.data)==null?void 0:n.datasets)==null?void 0:a.map(r=>({...r,data:[]}))}}:null}async function ja(t,n,a,r,l){if(!l)return null;const o=JSON.stringify(a),c=`${t}/v1/lens`;return await s.postRequest(c,l,{name:n,template:o,filterValues:r,operation:"create"})}async function ts(t,n,a){if(!a)return null;const{id:r,template:l,filterValues:o,isDefault:c,shared:i}=n,d=`${t}/v1/lens`;return await s.postRequest(d,a,{lensId:r,template:l,filterValues:o,isDefault:c,shared:i,operation:"update"})}async function va(t,n,a){if(!a)return null;const r=`${t}/v1/lens`;return await s.postRequest(r,a,{operation:"delete",lensId:n})}function ba(){const[t,n]=k.useState(""),[a,r]=k.useState(!1),l=s.useDashboardStore(y=>y.lenses),{setLenses:o,setSelectedLensId:c}=s.useDashboardActions(),[i,d]=k.useState(!1),[u,m]=k.useState(!1),h=s.useDashboardStore(y=>y.dashboard),x=s.useDashboardStore(y=>y.filterValues),{authToken:g,tokenProps:v}=s.useSemaphorContext();async function p(){d(!0);const y=Ke(h),b=await ja(v.apiServiceUrl,t,y,x,g==null?void 0:g.accessToken);b&&(o([...l||[],b]),c(b.id),m(!1)),d(!1)}return e.jsxs(s.Dialog,{open:u,onOpenChange:m,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create Lens"}),e.jsx(s.DialogDescription,{children:"Lenses are private by default and are only visible to you."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid grid-cols-8 items-center gap-4",children:[e.jsx(s.Label,{className:"text-right",children:"Name"}),e.jsx(s.Input,{value:t,onChange:y=>{n(y.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),a&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{size:"sm",variant:"outline",type:"submit",onClick:p,disabled:i,children:i?"Creating...":"Add"})})]})]})}function ya(){const[t,n]=k.useState(!1),a=s.useDashboardStore(h=>h.lenses),r=s.useDashboardStore(h=>h.selectedLensId),{setLenses:l,setSelectedLensId:o}=s.useDashboardActions(),{authToken:c,tokenProps:i}=s.useSemaphorContext();async function d(h){o(h)}async function u(h){if(await va(i.apiServiceUrl,h,c==null?void 0:c.accessToken)){const g=a==null?void 0:a.filter(v=>v.id!==h);l(g||[]),o("original")}}async function m(h){const x=a==null?void 0:a.map(p=>p.id===h.id?{...p,isDefault:!h.isDefault}:{...p,isDefault:!1});l(x||[]);const g={...h,isDefault:!h.isDefault};await ts(i.apiServiceUrl,g,c==null?void 0:c.accessToken);const v=a==null?void 0:a.find(p=>p.isDefault);if(v&&v.id!==h.id){const p={...v,isDefault:!1};await ts(i.apiServiceUrl,p,c==null?void 0:c.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:n,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(Wt,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(s.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuRadioGroup,{value:r,onValueChange:d,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),a==null?void 0:a.map(h=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:h.id,children:[e.jsx("p",{children:h.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:x=>{x.preventDefault(),m(h)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!h.isDefault,"text-green-500":h.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:x=>{x.preventDefault(),u(h.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},h.id))]})]})]})}function Na({iconClassName:t}){const[n,a]=k.useState(!1),[r,l]=k.useState(""),[o,c]=k.useState(!1),i=s.useDashboardStore(h=>h.isDownloadingPdf),{tokenProps:d}=s.useSemaphorContext();async function u(){const h=s.ue.loading("Generating PDF... may take up to 60 seconds");try{await s.downloadPdf(d.apiServiceUrl),s.ue.dismiss(h),s.ue.success("PDF downloaded successfully!",{duration:2e3})}catch(x){s.ue.dismiss(h),s.ue.error("Failed to download PDF",{description:"Please try again or contact support.",richColors:!0}),console.error("PDF download error:",x)}}async function m(){if(!r)return;a(!1),l(""),c(!1);const h=s.ue.loading("Generating protected PDF... may take up to 60 seconds");try{await s.downloadPdf(d.apiServiceUrl,r),s.ue.dismiss(h),s.ue.success("Protected PDF downloaded successfully!",{duration:2e3,position:"top-right"})}catch(x){s.ue.dismiss(h),s.ue.error("Failed to download protected PDF. Please try again."),console.error("Protected PDF download error:",x)}}return e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled:i,children:e.jsx(s.Download,{className:s.cn("size-4",t)})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsxs(s.DropdownMenuItem,{onClick:u,children:[e.jsx(s.File,{className:"mr-2 h-4 w-4"}),"Download PDF"]}),e.jsxs(s.DropdownMenuItem,{onClick:()=>a(!0),children:[e.jsx(s.Lock,{className:"mr-2 h-4 w-4"}),"Download Protected PDF"]})]})]}),e.jsx(s.Dialog,{open:n,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Download Protected PDF"}),e.jsx(s.DialogDescription,{children:"Enter a password to protect your PDF. The PDF will be encrypted and require this password to open."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Input,{id:"password",type:o?"text":"password",value:r,onChange:h=>l(h.target.value),placeholder:"Enter password",className:"pr-10",onKeyDown:h=>{h.key==="Enter"&&r&&m()}}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent",onClick:()=>c(!o),children:o?e.jsx(s.EyeOff,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(s.Eye,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:m,disabled:!r,children:"Download"})]})]})})]})}function Gs({triggerButtonClassName:t}){const[n,a]=k.useState(!1),r=s.useDashboardStore(i=>{var d;return(d=i.dashboard)==null?void 0:d.id}),l=s.useDashboardStore(i=>{var d;return(d=i.dashboard)==null?void 0:d.title}),o=s.useDashboardStore(i=>{var d;return(d=i.dashboard)==null?void 0:d.sheets}),c=s.useDashboardStore(i=>i.selectedSheetId);return o==null||o.find(i=>i.id===c),r?e.jsxs(e.Fragment,{children:[e.jsx(s.IconButton,{tooltip:"Schedule Dashboard",className:s.cn("h-7 p-2",t),onClick:()=>a(!0),children:e.jsx(s.Clock,{className:"size-4"})}),e.jsx(s.EmailScheduleDialog,{open:n,onOpenChange:a,dashboardId:r,dashboardName:l})]}):null}function He({value:t,onChange:n,placeholder:a="Search users by name, email, or department..."}){return e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:a,value:t,onChange:r=>n(r.target.value),className:"pl-9"})]})}function Ie({currentRole:t,onRoleChange:n,roleOptions:a,disabled:r=!1,className:l="",allowDropdown:o=!0}){var d;const c=((d=a.find(u=>u.value===t))==null?void 0:d.label)||t,i=a.filter(u=>u.value!==t);return o?e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:`cursor-pointer hover:bg-muted ${r?"cursor-not-allowed opacity-50":""} ${l}`,children:c})}),e.jsx(s.DropdownMenuContent,{className:"z-[51]",children:i.map(u=>e.jsx(s.DropdownMenuItem,{onClick:()=>n(u.value),disabled:r,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.description})]})},u.value))})]}):e.jsx(s.Badge,{variant:"outline",className:`text-xs ${l}`,children:c})}function _s({selectedUsers:t,selectedUserObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:l}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["Selected Users (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(o=>a(o.id)),className:"h-7 text-xs",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:n.map(o=>{const c=t.find(d=>d.id===o.id),i=l(o.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[o.name,e.jsx(Ie,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:d=>r(o.id,d),roleOptions:i}),e.jsx("button",{onClick:()=>a(o.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},o.id)})}),e.jsx(s.Separator,{})]})}function Ys({usersToRemove:t,allUsers:n,onRemove:a}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium text-destructive",children:["Users to Remove Access (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(r=>a(r)),className:"h-auto p-1 text-xs text-destructive hover:text-destructive",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:n.filter(r=>t.includes(r.id)).map(r=>e.jsxs(s.Badge,{variant:"destructive",className:"gap-1",children:[r.name,e.jsx("button",{onClick:()=>a(r.id),className:"ml-1 rounded-full p-0.5 hover:bg-destructive-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},r.id))}),e.jsx(s.Separator,{})]})}function $s({usersToUpdate:t,allUsers:n,onRemove:a,getRoleOptions:r}){if(t.length===0)return null;const l=r("tenant"),o=i=>{const d=n.find(u=>u.id===i);return(d==null?void 0:d.name)||"Unknown User"},c=i=>{const d=l.find(u=>u.value===i);return(d==null?void 0:d.label)||i};return e.jsxs("div",{className:"rounded-lg border border-orange-200 bg-orange-50 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-4 w-4 text-orange-600"}),e.jsxs("span",{className:"text-sm font-medium text-orange-800",children:["Updating Access (",t.length,")"]})]}),e.jsx("div",{className:"space-y-2",children:t.map(i=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:o(i.id)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c(i.currentRole)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsx(s.Badge,{variant:"default",className:"text-xs",children:c(i.newRole)})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",onClick:()=>a(i.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},i.id))})]})}function qs(t,n={}){const{enabled:a=!0,eventType:r="mousedown"}=n,l=k.useRef(null);return k.useEffect(()=>{const o=c=>{const i=c.target;l.current&&l.current.contains(i)||i instanceof Element&&(i.closest("[data-radix-popper-content-wrapper]")||i.closest("[data-radix-select-content]")||i.closest("[data-radix-popover-content]")||i.closest("[data-radix-dropdown-menu-content]")||i.closest("[data-radix-tooltip-content]")||i.closest('[role="listbox"]')||i.closest('[role="option"]')||i.closest('[role="combobox"]'))||i instanceof Element&&i.hasAttribute("data-radix-")||t()};return a&&document.addEventListener(r,o),()=>{document.removeEventListener(r,o)}},[t,a,r]),l}function Ne(t,n){var a;return((a=n.find(r=>r.value===t))==null?void 0:a.label)||t}function Ca(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function Ks(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function Sa(t,n,a){const r=Ks(t),l=(a==null?void 0:a.type)||"organization";if(!(!n||!n.shares))if(l==="organization")if(r==="organization"){if("specificOrgUsers"in n.shares)return(n.shares.specificOrgUsers||[]).find(i=>i.orgUserId===t.id)}else return(n.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id);else return(n.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id)}function wa({user:t}){return Ks(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 Da({user:t,userShare:n,usersToUpdate:a,currentUser:r,getRoleOptions:l,handleUpdateAccess:o}){if(!(n!=null&&n.role))return null;const c=Ca((r==null?void 0:r.type)||""),i=a.some(h=>h.id===t.id),d=a.find(h=>h.id===t.id),u=d?d.newRole:n==null?void 0:n.role,m=l(t.type);return n?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(Ie,{currentRole:u,onRoleChange:h=>{o(t.id,n.role,h)},roleOptions:m,disabled:!c,allowDropdown:c,className:i?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:Ne(u,m)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function Ta({hasAccess:t,isUserRemoving:n,isSelected:a,hasAccessFromAPI:r}){return e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[t&&!n&&e.jsxs(s.Badge,{variant:"outline",className:"border-green-200 bg-green-50 text-xs text-green-700",children:[e.jsx(s.Eye,{className:"mr-1 h-3 w-3"}),"Has Access"]}),n&&e.jsxs(s.Badge,{variant:"outline",className:"border-red-200 bg-red-50 text-xs text-red-700",children:[e.jsx(s.X,{className:"mr-1 h-3 w-3"}),"Remove Access"]}),a&&!r&&e.jsxs(s.Badge,{variant:"outline",className:"border-blue-200 bg-blue-50 text-xs text-blue-700",children:[e.jsx(Ee,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function ka({isUserRemoving:t,isRemoving:n}){return e.jsx(e.Fragment,{children:t&&e.jsx("span",{className:"text-xs font-medium text-red-600",children:n?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"})})}function Ea({existingShares:t,allUsers:n,getRoleOptions:a,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in t.shares){const c=t.shares,i=c.specificOrgUsers||[],d=c.specificTenantUsers||[],u=c.orgWide||[],m=c.orgUsersOnly||[],h=c.allTenantsOnly||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Org Users (",i.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[i.slice(0,3).map((x,g)=>{var b,S;const v=((b=n.find(A=>A.id===x.orgUserId))==null?void 0:b.name)||"Unknown User",p=((S=n.find(A=>A.id===x.orgUserId))==null?void 0:S.type)||"",y=Ne(x.role,a(p));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:v}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:y})]},g)}),i.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",i.length-3," more users"]})]})]}),d.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-green-600",children:["Specific Tenant Users (",d.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[d.slice(0,3).map((x,g)=>{var b,S;const v=((b=n.find(A=>A.id===x.tenantUserId))==null?void 0:b.name)||"Unknown User",p=((S=n.find(A=>A.id===x.tenantUserId))==null?void 0:S.type)||"",y=Ne(x.role,a(p));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:v}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:y})]},g)}),d.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",d.length-3," more users"]})]})]}),u.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-purple-600",children:"All Org Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:u.map((x,g)=>{const v=Ne(x.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Organization Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:v})]},g)})})]}),m.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-orange-600",children:"Org Users Only"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:m.map((x,g)=>{const v=Ne(x.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Org Users Only"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:v})]},g)})})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-indigo-600",children:"All Tenants"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:h.map((x,g)=>{const v=Ne(x.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenants"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:v})]},g)})})]}),!i.length&&!d.length&&!u.length&&!m.length&&!h.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const c=t.shares.specificTenantUsers||[],i=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",c.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[c.slice(0,3).map((d,u)=>{var g,v;const m=((g=n.find(p=>p.id===d.tenantUserId))==null?void 0:g.name)||"Unknown User",h=((v=n.find(p=>p.id===d.tenantUserId))==null?void 0:v.type)||"",x=Ne(d.role,a(h));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:m}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:x})]},u)}),c.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",c.length-3," more users"]})]})]}),i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:i.map((d,u)=>{const m=Ne(d.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:m})]},u)})})]}),!c.length&&!i.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const o=t.shares.specificTenantUsers||[],c=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[o.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",o.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[o.slice(0,3).map((i,d)=>{var x,g;const u=((x=n.find(v=>v.id===i.tenantUserId))==null?void 0:x.name)||"Unknown User",m=((g=n.find(v=>v.id===i.tenantUserId))==null?void 0:g.type)||"",h=Ne(i.role,a(m));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:u}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},d)}),o.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",o.length-3," more users"]})]})]}),c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:c.map((i,d)=>{const u=Ne(i.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:u})]},d)})})]}),!o.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function Ia({isInitialLoading:t,searchQuery:n,availableUsers:a}){return t?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(s.LoaderCircle,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading users..."})]})}):a.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:n?"No users found matching your search.":"No users available to share with."}):null}function Aa({user:t,userShare:n,isUserRemoving:a,hasAccess:r,hasAccessFromAPI:l,isSelected:o,selectedUser:c,roleOptions:i,currentUser:d,usersToUpdate:u,handleUserToggle:m,handleRemoveAccess:h,handleUpdateAccess:x,handleUserRoleChange:g}){return e.jsxs("div",{className:s.cn("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!a?"border border-green-200 bg-green-50":a?"border border-red-200 bg-red-50":o?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:l?!a:o,onCheckedChange:()=>{l?a?m(t.id):h(t.id):m(t.id)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:t.name}),e.jsx(wa,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!a?e.jsx(Ie,{currentRole:n==null?void 0:n.role,onRoleChange:v=>x(t.id,n.role,v),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(Da,{user:t,userShare:n,usersToUpdate:u,currentUser:d,getRoleOptions:()=>i,handleUpdateAccess:x}),o&&!l&&e.jsx("div",{onClick:v=>v.stopPropagation(),children:e.jsx(Ie,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:v=>g(t.id,v),roleOptions:i,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(Ta,{hasAccess:r,isUserRemoving:a,isSelected:o,hasAccessFromAPI:l}),e.jsx(ka,{isUserRemoving:a,isSelected:o,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function Hs({existingShares:t,isInitialLoading:n,isSearching:a,getRoleOptions:r,allUsers:l=[],currentUser:o,handleUserToggle:c,handleUserRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),x=s.useShareUsersToUpdate(),g=s.useShareSearchQuery(),v=s.useShareManagementActions(),p=c||(C=>{const D=m.some(N=>N.id===C),f=h.includes(C);D?v.removeSelectedUser(C):f?v.removeUserFromRemove(C):v.addSelectedUser({id:C,role:"VIEWER"})}),y=i||v.updateSelectedUserRole,b=d||v.addUserToRemove,S=u||((C,D,f)=>{v.addUserToUpdate({id:C,currentRole:D,newRole:f})}),A=l.filter(C=>C.id!==(o==null?void 0:o.id)),E=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 (",(A??[]).length,")"]}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",children:e.jsx(s.Info,{className:"h-4 w-4"})})}),e.jsx(s.TooltipContent,{className:"w-48 max-w-sm",children:e.jsx(Ea,{existingShares:t,allUsers:l,getRoleOptions:r,currentUser:o})})]})})]}),(A==null?void 0:A.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{m.length===A.length?v.setSelectedUsers([]):v.setSelectedUsers(A.map(C=>({id:C.id,role:"VIEWER"})))},className:"h-7 text-xs",children:m.length===A.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(Ia,{isInitialLoading:n,isSearching:a,searchQuery:g,availableUsers:A||[]}),!n&&!a&&(A==null?void 0:A.length)>0&&A.map(C=>{const D=t?Sa(C,t,o):void 0,f=E.includes(C.id),N=!!D,j=N&&!f,R=m.some(w=>w.id===C.id),T=m.find(w=>w.id===C.id),F=r(C.type);return e.jsx(Aa,{user:C,userShare:D,isUserRemoving:f,hasAccess:j,hasAccessFromAPI:N,isSelected:R,selectedUser:T,roleOptions:F,currentUser:o,usersToUpdate:x,handleUserToggle:p,handleRemoveAccess:b,handleUpdateAccess:S,handleUserRoleChange:y},C.id)})]})]})}function ns({shareType:t,onShareTypeChange:n,currentUser:a,options:r}){const l=(a==null?void 0:a.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(a.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:n,className:`grid grid-cols-${r.length} gap-4`,children:r.map(o=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:o.value,id:o.value,className:"peer sr-only",disabled:o.disabled}),e.jsxs(s.Label,{htmlFor:o.value,className:`flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5 [&:has([data-state=checked])]:border-primary [&:has([data-state=checked])]:bg-primary/5 ${o.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[o.icon||e.jsx(s.User,{className:"mb-3 h-6 w-6"}),e.jsxs("div",{className:"space-y-1 text-center",children:[e.jsx("p",{className:"text-sm font-medium leading-none",children:o.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o.description})]})]})]},o.value))}),!l&&r.some(o=>o.value==="all_users")&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only admins, authors, power users, and super admins can share with all users."})]})}const ye=()=>[{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 Ma({currentUser:t,currentShare:n,isSharing:a,onUpdateAccess:r,allUsersToUpdate:l=null,allUsersToRemove:o=!1,isUpdating:c=!1,isRemoving:i=!1}){const d=s.useShareCurrentMode(),u=ye().filter(S=>S.value==="VIEWER"||S.value==="EDITOR"||S.value==="CONTRIBUTOR"),m=n.role!=="NONE"?n.role:"NONE",h=l?l.newRole:m,x=n.role!=="NONE"&&!o&&(!l||l.newRole===m),g=l!==null&&l.newRole!==m,v=o,p=m==="NONE"||!m,y=S=>{switch(S){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"})}},b=S=>{r(m,S)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",g&&!v&&!p?"border-orange-300 bg-orange-50":x?"border-green-300 bg-green-50":v||p?"border-destructive bg-destructive/10":""),children:[e.jsxs(s.CardHeader,{children:[e.jsxs(s.CardTitle,{className:"flex items-center gap-2 text-base",children:[e.jsx(s.Users,{className:"h-5 w-5"}),"Share with All"," ",d==="allOrgUsers"?"Organization":d==="allTenantUsers"?"Tenant":d==="specificOrgUsers"?"Org":"Tenant"," ","Users",x&&e.jsx(s.Badge,{variant:"default",className:"ml-2 border-green-400 bg-green-100 text-green-800",children:"Active"}),g&&e.jsx(s.Badge,{variant:"secondary",className:"ml-2 border-orange-400 bg-orange-100 text-orange-800",children:"Pending Update"}),(v||p)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:v||p?"No access for all users.":"This will share the dashboard with all users in your "+((t==null?void 0:t.type)==="organization"?"organization":"tenant")+". Select an access level below."})]}),e.jsx(s.CardContent,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Select Access Level:"}),e.jsxs(s.HoverCard,{children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-4 w-4 p-0 text-muted-foreground hover:text-foreground",children:e.jsx(s.Info,{className:"h-3 w-3"})})}),e.jsx(s.HoverCardContent,{className:"w-80",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Share with All Users"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["This action will share the dashboard with all users in your"," ",(t==null?void 0:t.type)==="organization"?"organization":"tenant",". Users will receive the selected access level."]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Viewer:"})," Can view the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Editor:"})," Can view and edit the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Contributor:"})," Can view, edit, and share the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"None:"})," No access for all users"]})]})]})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:u.map(S=>e.jsxs(s.Button,{variant:h===S.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>b(S.value),disabled:a||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[y(S.value),e.jsx("span",{className:"font-medium",children:S.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:S.description})]},S.value))})]})})]})})}function Ws({currentUser:t,currentShare:n,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:o,onRemoveAccess:c,allUsersToUpdate:i,allUsersToRemove:d}){const u=p=>p==="OWNER"?"CONTRIBUTOR":p,h=n?{role:u(n.role)}:{role:"NONE"},x=i?{currentRole:u(i.currentRole),newRole:u(i.newRole)}:null,g=(p,y)=>{o(p,y)},v=()=>{c()};return e.jsx(Ma,{currentUser:t,currentShare:h,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:g,onRemoveAccess:v,allUsersToUpdate:x,allUsersToRemove:d})}function Oe(t){const{debouncedSearchQuery:n,resourceId:a,resourceType:r=s.ResourceType.DASHBOARD,userType:l,tenantId:o}=t,c=k.useMemo(()=>({search:n,active:!0,...l?{type:l}:{},...l==="tenant"&&o?{tenantId:o}:{}}),[n,l,o]),{users:i,isLoading:d,isError:u}=s.useUnifiedUsers(c),m=s.useResourceShares(r,a);return{allUsers:i,isLoadingUsers:d,isErrorLoadingUsers:u,existingShares:m.data,isLoadingShares:m.isLoading,isErrorLoadingShares:m.isError,isFetchingShares:m.isFetching}}function Ra({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var z,Q;const i=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:u,setSearchQuery:m,debouncedSearchQuery:h}=s.useShareSearchWithDebounce(),x=s.useShareSelectedUsers(),g=s.useShareUsersToRemove(),v=s.useShareUsersToUpdate(),p=s.useShareCurrentMode(),y=s.useShareOrgWideRole(),b=s.useShareManagementActions(),[S,A]=k.useState("specific_users"),E=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},C=()=>{if(i==="tenant"&&d)return d},{allUsers:D,existingShares:f,isLoadingUsers:N}=Oe({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:E(),tenantId:C()});k.useEffect(()=>{b.setCurrentContext("org-tab"),b.setCurrentMode(S==="all_users"?"allOrgUsers":"specificOrgUsers")},[b,S]);const j=X=>{var te,ie;const se=X;if(A(se),r==null||r(se),b.setCurrentContext("org-tab"),se==="specific_users")b.setCurrentMode("specificOrgUsers");else if(se==="all_users"){b.setCurrentMode("allOrgUsers");const K=(ie=(te=f==null?void 0:f.shares)==null?void 0:te.orgUsersOnly)==null?void 0:ie[0];K&&K.role!==void 0&&b.setOrgWideRole(K.role)}},R=D.filter(X=>X.name.toLowerCase().includes(u.toLowerCase())||X.email.toLowerCase().includes(u.toLowerCase())),T=D.filter(X=>x.some(se=>se.id===X.id)),F=X=>{var K,Y;const se=x.some(ae=>ae.id===X),te=g.includes(X),ie=(Y=(K=f==null?void 0:f.shares)==null?void 0:K.specificOrgUsers)==null?void 0:Y.some(ae=>ae.orgUserId===X);se?b.removeSelectedUser(X):te?b.removeUserFromRemove(X):ie||b.addSelectedUser({id:X,role:"VIEWER"})},w=(X,se)=>{b.updateSelectedUserRole(X,se)},I=X=>{b.addUserToRemove(X),b.removeSelectedUser(X)},M=X=>{b.removeUserFromRemove(X)},O=X=>{b.removeUserFromUpdate(X)},L=(X,se)=>{b.setOrgWideRole(se)},P=()=>{b.setOrgWideRole((B==null?void 0:B.role)||"NONE")},B=(Q=(z=f==null?void 0:f.shares)==null?void 0:z.orgUsersOnly)==null?void 0:Q[0];k.useEffect(()=>{S==="all_users"&&B&&B.role!==void 0&&b.setOrgWideRole(B.role)},[S,B,b]);const H=N,q=!1;return a?e.jsxs(e.Fragment,{children:[e.jsx(ns,{shareType:S,onShareTypeChange:j,currentUser:a,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(s.User,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(a==null?void 0:a.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(a.role??"")}]}),S==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(He,{value:u,onChange:m}),e.jsx(_s,{selectedUsers:x,selectedUserObjects:T,onRemove:F,onRoleChange:w,getRoleOptions:ye}),e.jsx(Ys,{usersToRemove:g,allUsers:R,onRemove:M}),e.jsx($s,{usersToUpdate:v,allUsers:R,onRemove:O,getRoleOptions:ye}),e.jsx(Hs,{existingShares:f,isInitialLoading:H,isSearching:q,resource:t,onShare:()=>{},getRoleOptions:ye,allUsers:R,currentUser:a,handleUserToggle:F,handleUserRoleChange:w,handleRemoveAccess:I,handleUpdateAccess:(X,se,te)=>{b.addUserToUpdate({id:X,currentRole:se,newRole:te})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(Ws,{currentUser:a,currentShare:B,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:L,onRemoveAccess:P,allUsersToUpdate:p==="allOrgUsers"&&y!==((B==null?void 0:B.role)||"NONE")?{currentRole:(B==null?void 0:B.role)||"NONE",newRole:y}:null,allUsersToRemove:p==="allOrgUsers"&&(B==null?void 0:B.role)===void 0})})]}):null}function La(t){switch(t){case"ORG_GROUP":return"Organization Group";case"TENANT_GROUP":return"Tenant Group";default:return"Group"}}function Fa(t){switch(t){case"ORG_GROUP":return"text-blue-600";case"TENANT_GROUP":return"text-green-600";default:return"text-gray-600"}}function Qs({groups:t,existingGroupShares:n,isLoading:a,resource:r,getRoleOptions:l,currentUser:o,handleGroupToggle:c,handleGroupRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:u}){const m=s.useShareSelectedGroups(),h=s.useShareGroupsToRemove(),x=s.useShareGroupsToUpdate(),g=s.useShareManagementActions(),v=l(o==null?void 0:o.type);return a?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):t.length===0?e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"No groups available to share with"}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Available Groups"}),e.jsx("div",{className:"max-h-[300px] space-y-2 overflow-y-auto rounded-md border p-3",children:t.map(p=>{const y=n==null?void 0:n.find(f=>f.groupId===p.id),b=m.some(f=>f.id===p.id),S=h.includes(p.id),A=x.find(f=>f.id===p.id),E=!!y&&!S;let D=(y==null?void 0:y.role)||"VIEWER";if(b){const f=m.find(N=>N.id===p.id);D=(f==null?void 0:f.role)||"VIEWER"}else A&&(D=A.newRole);return e.jsxs("div",{className:s.cn("flex items-center justify-between rounded-lg p-2 transition-colors",E&&!S?"border border-green-200 bg-green-50":S?"border border-red-200 bg-red-50":b?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx(s.Checkbox,{id:`group-${p.id}`,checked:E?!S:b,disabled:!1,onCheckedChange:()=>{E?S?g.removeGroupFromRemove(p.id):d==null||d(p.id):c==null||c(p.id)}}),e.jsxs("label",{htmlFor:`group-${p.id}`,className:"flex cursor-pointer flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:p.name}),p.type==="ORG_GROUP"?e.jsx(s.Building2,{className:"h-3 w-3 text-blue-600"}):e.jsx(s.Users,{className:"h-3 w-3 text-green-600"}),e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[p.memberCount," members"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:s.cn("text-xs",Fa(p.type)),children:La(p.type)}),p.type==="TENANT_GROUP"&&p.tenantName&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",p.tenantName]})]}),p.description&&e.jsx("span",{className:"text-xs text-muted-foreground",children:p.description})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[E&&!S?e.jsx(Ie,{currentRole:D,onRoleChange:f=>{y&&f!==y.role&&(u==null||u(p.id,y.role,f))},roleOptions:v,disabled:!1,allowDropdown:!0,className:A?"border-orange-300 bg-orange-100":""}):b&&!E&&e.jsx(Ie,{currentRole:D,onRoleChange:f=>i==null?void 0:i(p.id,f),roleOptions:v,disabled:!1}),E&&!S&&!A&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>d==null?void 0:d(p.id),children:e.jsx(s.X,{className:"h-4 w-4"})}),S&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g.removeGroupFromRemove(p.id),children:"Undo"}),A&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g.removeGroupFromUpdate(p.id),children:"Cancel"})]})]},p.id)})})]})}function Js({selectedGroups:t,groupObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:l}){if(t.length===0)return null;const o=l();return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:["Selected Groups (",t.length,")"]}),e.jsx("div",{className:"space-y-1",children:t.map(c=>{const i=n.find(d=>d.id===c.id);return i?e.jsxs("div",{className:"flex items-center justify-between rounded-md border bg-muted/50 p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[i.type==="ORG_GROUP"?e.jsx(s.Building2,{className:"h-4 w-4 text-blue-600"}):e.jsx(s.Users,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{className:"text-sm font-medium",children:i.name}),e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[i.memberCount," members"]}),i.type==="TENANT_GROUP"&&i.tenantName&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",i.tenantName]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ie,{currentRole:c.role,onRoleChange:d=>r(c.id,d),roleOptions:o}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>a(c.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})]},c.id):null})})]})}function ys({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var G;const{searchQuery:i,debouncedSearchQuery:d,setSearchQuery:u}=s.useShareSearchWithDebounce(),m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),x=s.useShareUsersToUpdate(),g=s.useShareSelectedGroups(),v=s.useShareGroupsToRemove(),p=s.useShareGroupsToUpdate(),y=s.useShareCurrentMode(),b=s.useShareTenantWideRole(),S=s.useShareAllTenantsRole(),A=s.useShareSelectedTenant(),E=s.useShareManagementActions(),{data:C,isLoading:D}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"}),{groups:f,isLoading:N}=s.useShareableGroups("tenant",(a==null?void 0:a.tenantId)||A),[j,R]=k.useState((a==null?void 0:a.type)==="organization"?"all_tenants":"specific_tenant_users");k.useEffect(()=>{(a==null?void 0:a.type)==="tenant"?(E.setCurrentContext("tenant-dialog"),E.setCurrentMode("specificTenantUsers")):(E.setCurrentContext("tenant-tab"),E.setCurrentMode("allTenants"))},[E,a==null?void 0:a.type]);const T=V=>{var oe,de,ne,me;R(V);let Z;if(V==="specific_tenant_users"?Z="specific_users":V==="all_tenant_users"||V==="all_tenants"?Z="all_users":V==="groups"?Z="groups":Z="specific_users",r==null||r(Z),V==="groups"?(E.setCurrentContext("group-share"),E.setCurrentMode("specificGroups")):(a==null?void 0:a.type)==="tenant"?(E.setCurrentContext("tenant-dialog"),V==="specific_tenant_users"?E.setCurrentMode("specificTenantUsers"):V==="all_tenant_users"&&(E.setCurrentMode("allTenantUsers"),a!=null&&a.tenantId&&E.setSelectedTenant(a.tenantId))):(E.setCurrentContext("tenant-tab"),V==="specific_tenant_users"?E.setCurrentMode("specificTenantUsers"):V==="all_tenant_users"?E.setCurrentMode("allTenantUsers"):V==="all_tenants"&&E.setCurrentMode("allTenants")),V==="all_tenant_users"){const pe=(de=(oe=I==null?void 0:I.shares)==null?void 0:oe.tenantWide)==null?void 0:de[0];pe&&pe.role!==void 0&&E.setTenantWideRole(pe.role)}else if(V==="all_tenants"){const pe=(me=(ne=I==null?void 0:I.shares)==null?void 0:ne.allTenantsOnly)==null?void 0:me[0];pe&&pe.role!==void 0&&E.setAllTenantsRole(pe.role)}},F=V=>{E.setSelectedTenant(V)},{allUsers:w,existingShares:I,isLoadingUsers:M,isErrorLoadingUsers:O,isLoadingShares:L,isErrorLoadingShares:P}=Oe({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant",tenantId:(a==null?void 0:a.type)==="tenant"?a.tenantId:A}),B=V=>{var ne,me;const Z=m.some(pe=>pe.id===V),oe=h.includes(V),de=(me=(ne=I==null?void 0:I.shares)==null?void 0:ne.specificTenantUsers)==null?void 0:me.some(pe=>pe.tenantUserId===V);Z?E.removeSelectedUser(V):oe?E.removeUserFromRemove(V):de||E.addSelectedUser({id:V,role:"VIEWER"})},H=(V,Z)=>{E.updateSelectedUserRole(V,Z)},q=V=>{E.addUserToRemove(V),E.removeSelectedUser(V)},z=V=>{E.removeUserFromRemove(V)},Q=V=>{E.removeUserFromUpdate(V)},X=(V,Z,oe)=>{E.addUserToUpdate({id:V,currentRole:Z,newRole:oe})},se=(V,Z)=>{j==="all_tenant_users"?E.setTenantWideRole(Z):j==="all_tenants"&&E.setAllTenantsRole(Z)},te=()=>{j==="all_tenant_users"?E.setTenantWideRole("VIEWER"):j==="all_tenants"&&E.setAllTenantsRole("VIEWER")},K=(()=>{var V,Z,oe,de;return y==="allTenants"?(Z=(V=I==null?void 0:I.shares)==null?void 0:V.allTenantsOnly)==null?void 0:Z[0]:y==="allTenantUsers"?(de=(oe=I==null?void 0:I.shares)==null?void 0:oe.tenantWide)==null?void 0:de[0]:null})();k.useEffect(()=>{var V,Z,oe,de;if(j==="all_tenant_users"){const ne=(Z=(V=I==null?void 0:I.shares)==null?void 0:V.tenantWide)==null?void 0:Z[0];ne&&ne.role!==void 0&&E.setTenantWideRole(ne.role)}else if(j==="all_tenants"){const ne=(de=(oe=I==null?void 0:I.shares)==null?void 0:oe.allTenantsOnly)==null?void 0:de[0];ne&&ne.role!==void 0&&E.setAllTenantsRole(ne.role)}},[j,I,E]);const Y=w.filter(V=>m.some(Z=>Z.id===V.id)),ae=V=>{const Z=g.some(ne=>ne.id===V),oe=v.includes(V),de=le==null?void 0:le.some(ne=>ne.groupId===V);Z?E.removeSelectedGroup(V):oe?E.removeGroupFromRemove(V):de||E.addSelectedGroup({id:V,role:"VIEWER"})},W=(V,Z)=>{E.updateSelectedGroupRole(V,Z)},re=V=>{E.addGroupToRemove(V),E.removeSelectedGroup(V)},U=(V,Z,oe)=>{E.addGroupToUpdate({id:V,currentRole:Z,newRole:oe})},ee=f.filter(V=>g.some(Z=>Z.id===V.id)),ce=k.useMemo(()=>j!=="groups"?[]:f.filter(V=>V.type!=="TENANT_GROUP"?!1:V.name.toLowerCase().includes(i.toLowerCase())||V.description&&V.description.toLowerCase().includes(i.toLowerCase())),[f,j,i]),le=k.useMemo(()=>{var Z,oe;const V=((Z=I==null?void 0:I.shares)==null?void 0:Z.specificGroups)||((oe=I==null?void 0:I.shares)==null?void 0:oe.groups)||[];return!V||V.length===0?[]:V.filter(de=>{const ne=f.find(me=>me.id===de.groupId);return(ne==null?void 0:ne.type)==="TENANT_GROUP"})},[I,f]),fe=M||L||j==="groups"&&N,ue=O||P,$=()=>(a==null?void 0:a.type)==="tenant"||j==="all_tenants"||j==="groups"?!0:A&&(j==="specific_tenant_users"||j==="all_tenant_users");return e.jsxs(e.Fragment,{children:[ue&&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"})]})}),!ue&&a&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(ns,{shareType:j,onShareTypeChange:T,currentUser:a,options:(a==null?void 0:a.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"specific_tenant_users",label:"Specific Users",description:"Share with specific tenant users",icon:e.jsx(s.User,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"groups",label:"Groups",description:"Share with tenant groups",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-green-500"})}]:[{value:"all_tenants",label:"All Tenants",description:"Share with all tenants and their users",icon:e.jsx(gs,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"all_tenant_users",label:"Specific Tenant",description:"Share with all users of a specific tenant",icon:e.jsx(s.House,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"specific_tenant_users",label:"Specific Tenant User",description:"Share with users of a specific tenant",icon:e.jsx(s.User,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(a==null?void 0:a.type)==="organization"&&(j==="specific_tenant_users"||j==="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:A||"",onValueChange:F,disabled:D,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:D?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(G=C==null?void 0:C.tenants)==null?void 0:G.map(V=>e.jsx(s.SelectItem,{value:V.id,children:V.name},V.id))})]})]}),$()?e.jsx(e.Fragment,{children:j==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(He,{value:i,onChange:u}),e.jsx(_s,{selectedUsers:m,selectedUserObjects:Y,onRemove:V=>B(V),onRoleChange:H,getRoleOptions:ye}),e.jsx(Ys,{usersToRemove:h,allUsers:w,onRemove:z}),e.jsx($s,{usersToUpdate:x,allUsers:w,onRemove:Q,getRoleOptions:ye}),e.jsx(Hs,{existingShares:I,isInitialLoading:!!fe,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:ye,allUsers:w,currentUser:a,handleUserToggle:B,handleUserRoleChange:H,handleRemoveAccess:q,handleUpdateAccess:X})]}):j==="groups"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(He,{value:i,onChange:u,placeholder:"Search groups..."}),e.jsx(Js,{selectedGroups:g,groupObjects:ee,onRemove:ae,onRoleChange:W,getRoleOptions:ye}),v.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-destructive",children:["Groups to Remove (",v.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"These groups will lose access when you save"})]}),p.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-orange-600",children:["Groups to Update (",p.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),e.jsx(Qs,{groups:ce,existingGroupShares:le,isLoading:N,resource:t,getRoleOptions:ye,currentUser:a,handleGroupToggle:ae,handleGroupRoleChange:W,handleRemoveAccess:re,handleUpdateAccess:U})]}):j==="all_tenant_users"||j==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(Ws,{currentUser:a,currentShare:K,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:se,onRemoveAccess:te,allUsersToUpdate:y==="allTenantUsers"&&((K==null?void 0:K.role)===void 0||b!==K.role)||y==="allTenants"&&((K==null?void 0:K.role)===void 0||S!==K.role)?{currentRole:(K==null?void 0:K.role)||"VIEWER",newRole:y==="allTenantUsers"?b:S}:null,allUsersToRemove:y==="allTenantUsers"&&(K==null?void 0:K.role)===void 0||y==="allTenants"&&(K==null?void 0:K.role)===void 0})}):null}):(a==null?void 0:a.type)==="organization"&&(j==="specific_tenant_users"||j==="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(gs,{className:"mx-auto mb-2 h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Please select a tenant to continue"})]})})]})]})}function Oa({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var O,L;const{searchQuery:i,setSearchQuery:d}=s.useShareSearchWithDebounce(),u=s.useShareSelectedGroups(),m=s.useShareGroupsToRemove(),h=s.useShareGroupsToUpdate(),x=s.useShareManagementActions(),[g,v]=k.useState("org_groups"),[p,y]=k.useState(""),{data:b,isLoading:S}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"&&g==="tenant_groups"}),A=Array.isArray(b)?b:(b==null?void 0:b.tenants)||[],E=()=>{if((a==null?void 0:a.type)==="organization")return"organization";if((a==null?void 0:a.type)==="tenant")return"tenant"},{groups:C,isLoading:D}=s.useShareableGroups(E(),g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"?p:a==null?void 0:a.tenantId),{existingShares:f}=Oe({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n}),N=C.filter(P=>g==="org_groups"&&P.type!=="ORG_GROUP"||g==="tenant_groups"&&P.type!=="TENANT_GROUP"||g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&(!p||P.tenantId&&P.tenantId!==p)?!1:P.name.toLowerCase().includes(i.toLowerCase())||P.description&&P.description.toLowerCase().includes(i.toLowerCase())),j=((O=f==null?void 0:f.shares)==null?void 0:O.specificGroups)||((L=f==null?void 0:f.shares)==null?void 0:L.groups)||[];k.useEffect(()=>{x.setCurrentContext("group-share"),x.setCurrentMode("specificGroups")},[x]);const R=P=>{const B=P;v(B),B==="org_groups"&&y(""),r==null||r(B==="org_groups"?"specific_groups":"all_groups"),x.setCurrentContext("group-share"),x.setCurrentMode("specificGroups")},T=C.filter(P=>u.some(B=>B.id===P.id)),F=P=>{const B=u.some(z=>z.id===P),H=m.includes(P),q=j==null?void 0:j.some(z=>z.groupId===P);B?x.removeSelectedGroup(P):H?x.removeGroupFromRemove(P):q||x.addSelectedGroup({id:P,role:"VIEWER"})},w=(P,B)=>{x.updateSelectedGroupRole(P,B)},I=P=>{x.addGroupToRemove(P),x.removeSelectedGroup(P)},M=(P,B,H)=>{x.addGroupToUpdate({id:P,currentRole:B,newRole:H})};return a?e.jsxs(e.Fragment,{children:[e.jsx(ns,{shareType:g,onShareTypeChange:R,currentUser:a,options:[{value:"org_groups",label:"Organization Groups",description:"Share with organization-level groups",icon:e.jsx(s.Building2,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"tenant_groups",label:"Tenant Groups",description:"Share with tenant-level groups",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-green-500"})}]}),g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(s.Label,{children:"Select Tenant"}),e.jsxs(s.Select,{value:p,onValueChange:y,disabled:S,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:S?"Loading tenants...":"Select a tenant to view its groups"})}),e.jsx(s.SelectContent,{className:"z-[51]",children:A.map(P=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:P.id,children:P.name},P.id))})]})]}),e.jsx("div",{className:"mt-3 space-y-2",children:g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&!p?e.jsx("div",{className:"rounded-md border border-dashed p-6 text-center",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Please select a tenant above to view and share with its groups"})}):e.jsxs(e.Fragment,{children:[e.jsx(He,{value:i,onChange:d,placeholder:"Search groups..."}),e.jsx(Js,{selectedGroups:u,groupObjects:T,onRemove:F,onRoleChange:w,getRoleOptions:ye}),m.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-destructive",children:["Groups to Remove (",m.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"These groups will lose access when you save"})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-orange-600",children:["Groups to Update (",h.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),e.jsx(Qs,{groups:N,existingGroupShares:j,isLoading:D,resource:t,getRoleOptions:ye,currentUser:a,handleGroupToggle:F,handleGroupRoleChange:w,handleRemoveAccess:I,handleUpdateAccess:M})]})})]}):null}const Xs=()=>{const t=s.useShareCurrentContext(),n=s.useShareCurrentMode(),a=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),l=s.useShareUsersToUpdate(),o=s.useShareSelectedGroups(),c=s.useShareGroupsToRemove(),i=s.useShareGroupsToUpdate(),d=s.useShareSelectedTenant(),u=s.useShareOrgWideRole(),m=s.useShareAllTenantsRole(),h=s.useShareTenantWideRole(),x=s.useShareGroupWideRole(),g=k.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedGroups:o,groupsToRemove:c,groupsToUpdate:i,selectedTenant:d,orgWideRole:u,allTenantsRole:m,tenantWideRole:h}),[t,n,a,r,l,o,c,i,d,u,m,h,x]),v=k.useMemo(()=>y=>s.validateShareData(y),[]),p=k.useMemo(()=>{if(!t||!n)return!1;switch(t){case"org-tab":return n==="specificOrgUsers"?a.length>0||r.length>0||l.length>0:!0;case"tenant-tab":if(n==="allTenantUsers"){if(!d)return!1}else if(n==="specificTenantUsers")return d?a.length>0||r.length>0||l.length>0:!1;return!0;case"tenant-dialog":return n==="specificTenantUsers"?a.length>0||r.length>0||l.length>0:!0;case"group-share":return n==="specificGroups"?o.length>0||c.length>0||i.length>0:!0}return!1},[t,n,a,r,l,o,c,i,d]);return{buildShareData:g,validateShareData:v,isCurrentStateValid:p,currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedTenant:d,orgWideRole:u,allTenantsRole:m,tenantWideRole:h}};function Ns({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllUsersShare:d,onRemoveAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),x=s.useShareUsersToUpdate(),g=s.useShareSelectedTenant(),v=s.useShareOrgWideRole(),p=s.useShareAllTenantsRole(),y=s.useShareTenantWideRole(),{buildShareData:b,validateShareData:S,isCurrentStateValid:A}=Xs(),E=a||r||l,C=()=>{var R,T,F,w;if(E)return"Updating...";if(i==="specific_users"){if(m.length===0&&h.length===0&&x.length===0)return"Select users to share with";const I=m.length+h.length+x.length;return I===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${I} user${I!==1?"s":""}`:h.length>0&&m.length===0&&x.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&x.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:x.length>0&&m.length===0&&h.length===0?`Update access for ${x.length} user${x.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 v===I?"Remove Access":"Update Access"}else if(i==="all_tenants"){const I=(T=(R=n==null?void 0:n.shares)==null?void 0:R.allTenantsOnly)==null?void 0:T[0];if(!I||I.role===void 0)return"Share with All Tenants";const M=I.role;return p===M?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const I=(w=(F=n==null?void 0:n.shares)==null?void 0:F.tenantWide)==null?void 0:w[0];if(!I||I.role===void 0)return"Share with All Tenant Users";const M=I.role;return y===M?"Remove Access":"Update Access"}else if(i==="specific_tenant_users"){if(m.length===0&&h.length===0&&x.length===0)return"Select users to share with";const I=m.length+h.length+x.length;return I===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${I} user${I!==1?"s":""}`:h.length>0&&m.length===0&&x.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&x.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:x.length>0&&m.length===0&&h.length===0?`Update access for ${x.length} user${x.length!==1?"s":""}`:`Update access for ${I} user${I!==1?"s":""}`}return"Share"},D=()=>E||!t||i==="all_tenant_users"&&!g||i==="specific_tenant_users"&&!g?!0:!A,f=()=>{const R=b();R&&S(R)&&o(R)},N=()=>{var R,T,F,w;if(i==="all_users")if(!d||d.role===void 0){const I=b();I&&S(I)&&o(I)}else{const I=d.role;if(v===I)u==null||u();else{const O=b();if(O&&S(O)){const L={...O,updateAccess:!0};o(L)}}}else if(i==="all_tenants"){const I=(T=(R=n==null?void 0:n.shares)==null?void 0:R.allTenantsOnly)==null?void 0:T[0];if(!I||I.role===void 0){const M=b();M&&S(M)&&o(M)}else{const M=I.role;if(p===M)u==null||u();else{const L=b();if(L&&S(L)){const P={...L,updateAccess:!0};o(P)}}}}else if(i==="all_tenant_users"){const I=(w=(F=n==null?void 0:n.shares)==null?void 0:F.tenantWide)==null?void 0:w[0];if(!I||I.role===void 0){const M=b();M&&S(M)&&o(M)}else{const M=I.role;if(y===M)u==null||u();else{const L=b();if(L&&S(L)){const P={...L,updateAccess:!0};o(P)}}}}},j=()=>{var R,T,F,w;if(i==="all_users"){if(!d||d.role===void 0)return"default";const I=d.role;return v===I?"destructive":"default"}else if(i==="all_tenants"){const I=(T=(R=n==null?void 0:n.shares)==null?void 0:R.allTenantsOnly)==null?void 0:T[0];if(!I||I.role===void 0)return"default";const M=I.role;return p===M?"destructive":"default"}else if(i==="all_tenant_users"){const I=(w=(F=n==null?void 0:n.shares)==null?void 0:F.tenantWide)==null?void 0:w[0];if(!I||I.role===void 0)return"default";const M=I.role;return y===M?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsxs(s.Button,{variant:"outline",onClick:c,disabled:E,children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),(i==="specific_users"||i==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(m.length>0||h.length>0||x.length>0)&&e.jsxs(s.Button,{onClick:f,disabled:!t||E,variant:"default",children:[E?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ee,{className:"mr-2 h-4 w-4"}),!E&&C()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:N,disabled:D(),variant:j(),children:[E?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(s.Users,{className:"mr-2 h-4 w-4"}),!E&&C()]})]})}function Pa({resource:t,isSharing:n,isRemoving:a,isUpdating:r,onShare:l,onClose:o,shareTabType:c,currentAllUsersShare:i}){const d=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),m=s.useShareUsersToUpdate(),h=s.useShareSelectedGroups(),x=s.useShareGroupsToRemove(),g=s.useShareGroupsToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const v=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:p,validateShareData:y,isCurrentStateValid:b}=Xs(),S=n||a||r,A=()=>{if(S)return"Updating...";if(c==="specific_users"){if(d.length===0&&u.length===0&&m.length===0)return"Select users to share with";const j=d.length+u.length+m.length;return j===0?"Select users to share with":d.length>0&&u.length>0?`Update access for ${j} user${j!==1?"s":""}`:u.length>0&&d.length===0&&m.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:d.length>0&&u.length===0&&m.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:m.length>0&&d.length===0&&u.length===0?`Update access for ${m.length} user${m.length!==1?"s":""}`:`Update access for ${j} user${j!==1?"s":""}`}else if(c==="groups"){if(h.length===0&&x.length===0&&g.length===0)return"Select groups to share with";const j=h.length+x.length+g.length;return j===0?"Select groups to share with":h.length>0&&x.length>0?`Update access for ${j} group${j!==1?"s":""}`:x.length>0&&h.length===0&&g.length===0?`Remove access for ${x.length} group${x.length!==1?"s":""}`:h.length>0&&x.length===0&&g.length===0?`Share with ${h.length} group${h.length!==1?"s":""}`:g.length>0&&h.length===0&&x.length===0?`Update access for ${g.length} group${g.length!==1?"s":""}`:`Update access for ${j} group${j!==1?"s":""}`}else if(c==="all_users"){if(!i||i.role==="NONE")return"Share with All Users";const j=i.role;return v===j?"Remove Access":"Update Access"}return"Share"},E=()=>S||!t?!0:!b,C=()=>{const j=p();j&&y(j)&&l(j)},D=()=>{const j=p();j&&y(j)&&l(j)},f=()=>{if(!i||i.role==="NONE"){const j=p();j&&y(j)&&l(j)}else{const j=i.role;if(v===j){const T=p();if(T&&y(T)){const F={...T,removeAccess:!0};l(F)}}else{const T=p();if(T&&y(T)){const F={...T,updateAccess:!0};l(F)}}}},N=()=>!i||i.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsxs(s.Button,{variant:"outline",onClick:o,disabled:S,children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),c==="specific_users"&&e.jsx(e.Fragment,{children:(d.length>0||u.length>0||m.length>0)&&e.jsxs(s.Button,{onClick:C,disabled:!t||S,variant:"default",children:[S?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ee,{className:"mr-2 h-4 w-4"}),!S&&A()]})}),c==="groups"&&e.jsx(e.Fragment,{children:(h.length>0||x.length>0||g.length>0)&&e.jsxs(s.Button,{onClick:D,disabled:!t||S,variant:"default",children:[S?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ee,{className:"mr-2 h-4 w-4"}),!S&&A()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:f,disabled:E(),variant:N(),children:[S?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ee,{className:"mr-2 h-4 w-4"}),!S&&A()]})]})}function Ba({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllGroupsShare:d,onRemoveAccess:u}){const m=s.useShareSelectedGroups(),h=s.useShareGroupsToRemove(),x=s.useShareGroupsToUpdate();s.useShareGroupWideRole(),s.useShareCurrentMode();const g=()=>{o({context:"group-share",mode:"specificGroups",selectedGroups:m,groupsToRemove:h,groupsToUpdate:x})},v=()=>m.length>0||h.length>0||x.length>0,p=()=>h.length>0&&m.length===0&&x.length===0?"Remove Access":x.length>0&&m.length===0&&h.length===0?"Update Access":"Share with Groups",y=a||r||l;return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[m.length>0&&e.jsxs("span",{children:[m.length," groups selected"]}),h.length>0&&e.jsxs("span",{className:"ml-2 text-destructive",children:["• ",h.length," to remove"]}),x.length>0&&e.jsxs("span",{className:"ml-2 text-orange-600",children:["• ",x.length," to update"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:y,children:"Cancel"}),e.jsxs(s.Button,{onClick:g,disabled:!v()||y,children:[y&&e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),p()]})]})]})}function ve(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function Ce(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function Va(t,n,a){const{resourceType:r,resourceId:l,shareMutation:o,removeMutation:c,existingShares:i,resetUserSelections:d}=n;if(l)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const u=ve(r,l,[{scope:"org_users_only",role:t.orgWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h}=t;if(u&&u.length>0){const x=ve(r,l,u.map(g=>({scope:"specific_org_user",orgUserId:g.id,role:g.role})));o(x,{onSuccess:()=>{d()}})}if(m&&m.length>0){const x=Ce(r,l,m.map(g=>{var p,y;const v=(y=(p=i==null?void 0:i.shares)==null?void 0:p.specificOrgUsers)==null?void 0:y.find(b=>b.orgUserId===g);return{scope:"specific_org_user",orgUserId:g,role:(v==null?void 0:v.role)||"VIEWER"}}));c(x,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(x=>{const g=ve(r,l,[{scope:"specific_org_user",orgUserId:x.id,role:x.newRole}]);o(g,{onSuccess:()=>{d()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const u=ve(r,l,[{scope:"all_tenants_only",role:t.allTenantsRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="allTenantUsers"){const u=ve(r,l,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h,tenantId:x}=t;if(m&&m.length>0){const g=Ce(r,l,m.map(v=>{var y,b;const p=(b=(y=i==null?void 0:i.shares)==null?void 0:y.specificTenantUsers)==null?void 0:b.find(S=>S.tenantUserId===v);return{scope:"specific_tenant_user",tenantUserId:v,tenantId:x,role:(p==null?void 0:p.role)||"VIEWER"}}));c(g,{onSuccess:()=>{d()}})}if(h&&h.length>0&&h.forEach(g=>{const v=ve(r,l,[{scope:"specific_tenant_user",tenantUserId:g.id,tenantId:x,role:g.newRole}]);o(v,{onSuccess:()=>{d()}})}),u&&u.length>0){const g=ve(r,l,u.map(v=>({scope:"specific_tenant_user",tenantUserId:v.id,tenantId:x,role:v.role})));o(g,{onSuccess:()=>{d()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const u=Ce(r,l,[{scope:"all_tenant_users",role:"VIEWER"}]);c(u,{onSuccess:()=>{d()}})}else if(t.updateAccess){const u=ve(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else{const u=ve(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h}=t;if(u&&u.length>0){const x=ve(r,l,u.map(g=>({scope:"specific_tenant_user",tenantUserId:g.id,role:g.role})));o(x,{onSuccess:()=>{d()}})}if(m&&m.length>0){const x=Ce(r,l,m.map(g=>{var p,y;const v=(y=(p=i==null?void 0:i.shares)==null?void 0:p.specificTenantUsers)==null?void 0:y.find(b=>b.tenantUserId===g);return{scope:"specific_tenant_user",tenantUserId:g,role:(v==null?void 0:v.role)||"VIEWER"}}));c(x,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(x=>{const g=ve(r,l,[{scope:"specific_tenant_user",tenantUserId:x.id,role:x.newRole}]);o(g,{onSuccess:()=>{d()}})})}break;case"group-share":if(t.mode==="specificGroups"){const{selectedGroups:u,groupsToRemove:m,groupsToUpdate:h}=t;if(u&&u.length>0){const x=ve(r,l,u.map(g=>({scope:"group",groupId:g.id,role:g.role})));o(x,{onSuccess:()=>{var g;d(),(g=n.resetGroupSelections)==null||g.call(n),s.ue.success(`Shared with ${u.length} group${u.length!==1?"s":""}`)}})}if(m&&m.length>0){const x=Ce(r,l,m.map(g=>({scope:"group",groupId:g,role:"VIEWER"})));c(x,{onSuccess:()=>{var g;d(),(g=n.resetGroupSelections)==null||g.call(n),s.ue.success(`Removed access from ${m.length} group${m.length!==1?"s":""}`)}})}h&&h.length>0&&h.forEach(x=>{const g=ve(r,l,[{scope:"group",groupId:x.id,role:x.newRole}]);o(g,{onSuccess:()=>{var v;d(),(v=n.resetGroupSelections)==null||v.call(n),s.ue.success("Updated access for group")}})})}break}}function za(t,n,a,r){var u,m,h,x,g,v;const{resourceType:l,resourceId:o,removeMutation:c,existingShares:i,resetUserSelections:d}=r;if(o)if(t.length>0){const p=Ce(l,o,t.map(y=>{var S,A;const b=(A=(S=i==null?void 0:i.shares)==null?void 0:S.specificTenantUsers)==null?void 0:A.find(E=>E.tenantUserId===y);return{scope:"specific_tenant_user",tenantUserId:y,role:(b==null?void 0:b.role)||"VIEWER"}}));c(p,{onSuccess:()=>{d()},onError:y=>{console.error("Remove access failed:",y)}})}else{const p=n==="tenant"&&a==="allTenants",y=n==="tenant"&&a==="allTenantUsers";if(p){const b=(m=(u=i==null?void 0:i.shares)==null?void 0:u.allTenantsOnly)==null?void 0:m[0];if(b){const S=Ce(l,o,[{scope:"all_tenants_only",role:b.role}]);c(S,{onSuccess:()=>{d()},onError:A=>{console.error("Remove all-tenants access failed:",A)}})}}else if(y){const b=(x=(h=i==null?void 0:i.shares)==null?void 0:h.tenantWide)==null?void 0:x[0];if(b){const S=Ce(l,o,[{scope:"all_tenant_users",role:b.role}]);c(S,{onSuccess:()=>{d()},onError:A=>{console.error("Remove all-tenant-users access failed:",A)}})}}else{const b=(v=(g=i==null?void 0:i.shares)==null?void 0:g.orgUsersOnly)==null?void 0:v[0];if(b){const S=Ce(l,o,[{scope:"org_users_only",role:b.role}]);c(S,{onSuccess:()=>{d()},onError:A=>{console.error("Remove org-wide access failed:",A)}})}}}}function Ua(t,n,a){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),o=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{currentUser:i}=s.useCurrentUserInfo(),{existingShares:d}=Oe({debouncedSearchQuery:"",resourceId:t||"",resourceType:s.ResourceType.DASHBOARD,userType:"tenant"}),u=k.useCallback(()=>{r.resetUserSelections()},[r]),m=k.useCallback(()=>{r.resetGroupSelections()},[r]),h=k.useCallback(g=>{if(!t)return;const v={resourceType:s.ResourceType.DASHBOARD,resourceId:t,shareMutation:n,removeMutation:a,existingShares:d,resetUserSelections:u,resetGroupSelections:m};Va(g,v,i)},[t,n,a,d,u,m,i]),x=k.useCallback(()=>{if(!t)return;const g={resourceType:s.ResourceType.DASHBOARD,resourceId:t,removeMutation:a,existingShares:d,resetUserSelections:u};za(l,o||"",c||"",g)},[t,n,a,d,u,m,l,o,c]);return{handleShareSubmit:h,handleRemoveAccess:x}}function Qe({resource:t,resourceType:n,onClose:a,onShareSuccess:r,onRemoveSuccess:l}){var w,I,M,O,L,P,B,H;const{currentUser:o}=s.useCurrentUserInfo(),[c,i]=k.useState("specific_users"),[d,u]=k.useState("specific_users"),[m,h]=k.useState("specific_groups"),x=s.useShareManagementActions(),g=s.useShareSelectedTab(),v=s.useShareCurrentMode(),p=s.useShareResource(),y=s.useRemoveResourceShares(),{handleShareSubmit:b,handleRemoveAccess:S}=Ua(t.id,(q,z)=>{p.mutate(q,{...z,onSuccess:()=>{var Q;(Q=z==null?void 0:z.onSuccess)==null||Q.call(z),r==null||r()}})},(q,z)=>{y.mutate(q,{...z,onSuccess:()=>{var Q;(Q=z==null?void 0:z.onSuccess)==null||Q.call(z),l==null||l()}})}),A=p.isPending,E=y.isPending,C=p.isPending,{existingShares:D}=Oe({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant"}),{existingShares:f}=Oe({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"organization"}),N=(I=(w=D==null?void 0:D.shares)==null?void 0:w.tenantWide)==null?void 0:I[0],j=(O=(M=f==null?void 0:f.shares)==null?void 0:M.orgUsersOnly)==null?void 0:O[0],R=()=>{if(g==="org")return d;switch(v){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},T=k.useCallback(()=>{x.resetShareState(),a()},[x,a]),F=(o==null?void 0:o.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:T,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(Ee,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:F?"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."})]}),F?e.jsxs(s.Tabs,{value:g,onValueChange:q=>{const z=q;x.setSelectedTab(z),x.resetUserSelections(),x.resetGroupSelections()},className:"mb-4 min-h-0 flex-1",children:[e.jsxs(s.TabsList,{className:"mb-2 grid w-full grid-cols-3",children:[e.jsx(s.TabsTrigger,{value:"org",children:"Org Users"}),e.jsx(s.TabsTrigger,{value:"tenant",children:"Tenant Users"}),e.jsx(s.TabsTrigger,{value:"groups",children:"Groups"})]}),e.jsx(s.TabsContent,{value:"org",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(Ra,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:u,isSharing:A,isUpdating:C,isRemoving:E})})}),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(ys,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:q=>i(q),isSharing:A,isUpdating:C,isRemoving:E})})}),e.jsx(s.TabsContent,{value:"groups",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(Oa,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:h,isSharing:A,isUpdating:C,isRemoving:E})})})]}):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(ys,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:q=>i(q),isSharing:A,isUpdating:C,isRemoving:E})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:F?g==="org"?e.jsx(Ns,{resource:t,existingShares:f,isSharing:A,isRemoving:E,isUpdating:C,onShare:b,onClose:a,shareTabType:d,currentAllUsersShare:j,onRemoveAccess:S}):g==="tenant"?e.jsx(Ns,{resource:t,existingShares:D,isSharing:A,isRemoving:E,isUpdating:C,onShare:b,onClose:a,shareTabType:R(),currentAllUsersShare:N,onRemoveAccess:S}):e.jsx(Ba,{resource:t,existingShares:f,isSharing:A,isRemoving:E,isUpdating:C,onShare:b,onClose:a,shareTabType:m,currentAllGroupsShare:(o==null?void 0:o.type)==="organization"?(P=(L=f==null?void 0:f.shares)==null?void 0:L.allOrgGroups)==null?void 0:P[0]:(H=(B=D==null?void 0:D.shares)==null?void 0:B.allTenantGroups)==null?void 0:H[0],onRemoveAccess:S}):e.jsx(Pa,{resource:t,isSharing:A,isRemoving:E,isUpdating:C,onShare:b,onClose:a,shareTabType:c,currentAllUsersShare:N,onRemoveAccess:S})})]})})}function Zs({type:t,isLinked:n,className:a}){const r=s.useDashboardStore(u=>u.selectedFrameId),l=s.useManagementStore(u=>u.selectedVisual),o=s.useEditorStore(u=>u.frame);let c;if(t)c=t;else if(n!==void 0)c=n?"linked":"library";else if(!!!(o!=null&&o.visualId||l!=null&&l.id)&&r)c="local";else if(l&&!r)c="library";else if(o!=null&&o.visualId&&r)c="linked";else if(l!=null&&l.id&&r)c="library";else return null;const i={local:"bg-gray-100 text-gray-700",linked:"bg-purple-100 text-purple-700",library:"bg-blue-100 text-blue-700"},d={local:"Local Visual",linked:"Linked Visual",library:"Library Visual"};return e.jsx("span",{className:s.cn("rounded-full px-2.5 py-0.5 text-xs font-medium",i[c],a),children:d[c]})}const Ga=async(t,n,a)=>{const r=`${t}/management/v1/groups`;return await s.postRequestRegular(r,n,a)},_a=async(t,n,a)=>{const r=`${t}/management/v1/groups/${a}`,l=await fetch(r,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});if(!l.ok){const o=await l.text();throw new Error(o||"Failed to delete group")}},Ya=async(t,n,a,r)=>{const l=`${t}/management/v1/groups/${a}/members`;return await s.postRequestRegular(l,n,r)},$a=async(t,n,a,r)=>{const l=`${t}/management/v1/groups/${a}/members`,o=await fetch(l,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(r)});if(!o.ok){const c=await o.text();throw new Error(c||"Failed to remove group members")}};function qa(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>Ga(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r),onSuccess:()=>{a.invalidateQueries({queryKey:["groups"]}),s.ue.success("Group created successfully")},onError:r=>{console.error("Failed to create group:",r),s.ue.error("Failed to create group",{description:r.message})}})}function Ka(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>_a(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r),onSuccess:(r,l)=>{a.invalidateQueries({queryKey:["groups"]}),a.removeQueries({queryKey:["group",l]}),s.ue.success("Group deleted successfully")},onError:r=>{console.error("Failed to delete group:",r),s.ue.error("Failed to delete group",{description:r.message})}})}function Ha(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>Ya(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r,l),onSuccess:(r,l)=>{a.invalidateQueries({queryKey:["group",l.groupId]}),a.invalidateQueries({queryKey:["group-members",l.groupId]}),a.invalidateQueries({queryKey:["groups"]}),s.ue.success("Members added successfully")},onError:r=>{console.error("Failed to add group members:",r),s.ue.error("Failed to add members",{description:r.message})}})}function Wa(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>$a(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r,l),onSuccess:(r,l)=>{a.invalidateQueries({queryKey:["group",l.groupId]}),a.invalidateQueries({queryKey:["group-members",l.groupId]}),a.invalidateQueries({queryKey:["groups"]}),s.ue.success("Members removed successfully")},onError:r=>{console.error("Failed to remove group members:",r),s.ue.error("Failed to remove members",{description:r.message})}})}function Qa({onSuccess:t,tenantId:n,isTenantUser:a}){const[r,l]=k.useState(""),[o,c]=k.useState(""),[i,d]=k.useState({}),u=qa(),m=()=>{const x={};return r.trim()?r.length<3?x.name="Group name must be at least 3 characters":r.length>50&&(x.name="Group name must be less than 50 characters"):x.name="Group name is required",o&&o.length>200&&(x.description="Description must be less than 200 characters"),d(x),Object.keys(x).length===0},h=async x=>{if(x.preventDefault(),!m())return;const g={name:r.trim(),description:o.trim()||void 0,type:a?"TENANT_GROUP":"ORG_GROUP",...a&&n?{tenantId:n}:{}};try{await u.mutateAsync(g),l(""),c(""),d({}),t()}catch(v){console.error("Failed to create group:",v)}};return e.jsxs("form",{onSubmit:h,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"group-name",children:["Group Name ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(s.Input,{id:"group-name",placeholder:"e.g., Marketing Team, Engineering Squad",value:r,onChange:x=>{l(x.target.value),i.name&&d(g=>({...g,name:""}))},className:i.name?"border-destructive":"",disabled:u.isPending}),i.name&&e.jsx("p",{className:"text-sm text-destructive",children:i.name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"group-description",children:["Description",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:"(optional)"})]}),e.jsx(s.Textarea,{id:"group-description",placeholder:"Describe the purpose of this group...",value:o,onChange:x=>{c(x.target.value),i.description&&d(g=>({...g,description:""}))},className:i.description?"border-destructive":"",disabled:u.isPending,rows:3}),i.description&&e.jsx("p",{className:"text-sm text-destructive",children:i.description}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[o.length,"/200 characters"]})]}),e.jsx("div",{className:"rounded-lg border bg-muted/50 p-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(s.CircleAlert,{className:"h-4 w-4 mt-0.5 text-muted-foreground"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"This group will be accessible to users in your workspace. You can add members after creating the group."})]})})]}),e.jsxs("div",{className:"flex justify-end gap-3",children:[e.jsx(s.Button,{type:"button",variant:"outline",onClick:()=>{l(""),c(""),d({})},disabled:u.isPending,children:"Clear"}),e.jsx(s.Button,{type:"submit",disabled:u.isPending||!r.trim(),children:u.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Users,{className:"mr-2 h-4 w-4"}),"Create Group"]})})]})]})}function Ja({open:t,onOpenChange:n,group:a,onUpdate:r}){const[l,o]=k.useState("members"),[c,i]=k.useState(""),[d,u]=k.useState([]),[m,h]=k.useState([]),{data:x,isLoading:g,refetch:v}=s.useGroupMembers(a.id),p=a.type==="TENANT_GROUP"?"tenant":"organization",{users:y,isLoading:b}=s.useUnifiedUsers({type:p,tenantId:a.tenantId||void 0,active:!0,limit:100}),S=Ha(),A=Wa(),E=(x==null?void 0:x.members)||[],C=k.useMemo(()=>new Set(E.map(w=>w.userId)),[E]),D=k.useMemo(()=>y.filter(w=>!C.has(w.id)),[y,C]),f=k.useMemo(()=>{if(!c)return D;const w=c.toLowerCase();return D.filter(I=>{var M,O;return((M=I.name)==null?void 0:M.toLowerCase().includes(w))||((O=I.email)==null?void 0:O.toLowerCase().includes(w))})},[D,c]),N=k.useMemo(()=>{if(!c)return E;const w=c.toLowerCase();return E.filter(I=>{var M,O,L,P;return((O=(M=I.user)==null?void 0:M.name)==null?void 0:O.toLowerCase().includes(w))||((P=(L=I.user)==null?void 0:L.email)==null?void 0:P.toLowerCase().includes(w))})},[E,c]),j=async()=>{if(d.length!==0)try{await S.mutateAsync({groupId:a.id,data:{userIds:d,userType:p==="tenant"?"tenant":"org"}}),u([]),o("members"),v(),r==null||r()}catch(w){console.error("Failed to add members:",w)}},R=async()=>{if(m.length!==0)try{await A.mutateAsync({groupId:a.id,data:{userIds:m}}),h([]),v(),r==null||r()}catch(w){console.error("Failed to remove members:",w)}},T=w=>{u(I=>I.includes(w)?I.filter(M=>M!==w):[...I,w])},F=w=>{h(I=>I.includes(w)?I.filter(M=>M!==w):[...I,w])};return e.jsx(e.Fragment,{children:e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-3xl max-h-[80vh]","aria-describedby":"group-members-description",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:a.name}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[E.length," ",E.length===1?"member":"members"]})}),e.jsxs("p",{id:"group-members-description",className:"sr-only",children:["Add or remove members from the ",a.name," group"]})]}),e.jsxs(s.Tabs,{value:l,onValueChange:w=>{o(w),i(""),h([])},className:"mt-4",children:[e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"members",children:"Current Members"}),e.jsx(s.TabsTrigger,{value:"add",children:"Add Members"})]}),e.jsxs(s.TabsContent,{value:"members",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search members...",value:c,onChange:w=>i(w.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:m.length>0?"h-[300px]":"h-[350px]",children:g?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(w=>e.jsx(s.Skeleton,{className:"h-16 w-full"},w))}):N.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(s.Users,{className:"h-12 w-12 mb-3 opacity-50"}),e.jsx("p",{className:"text-sm font-medium",children:c?"No members found":"No members yet"}),e.jsx("p",{className:"text-xs mt-1",children:c?"Try a different search":'Switch to the "Add Members" tab to add people to this group'})]}):e.jsx("div",{className:"space-y-2",children:N.map(w=>e.jsx(Xa,{member:w,selected:m.includes(w.userId),onToggle:()=>F(w.userId)},w.id))})}),m.length>0&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[m.length," member",m.length!==1?"s":""," selected"]}),e.jsx(s.Button,{variant:"destructive",size:"sm",onClick:R,disabled:A.isPending,children:A.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Removing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Trash2,{className:"mr-2 h-4 w-4"}),"Remove Selected"]})})]})]}),e.jsxs(s.TabsContent,{value:"add",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search users to add...",value:c,onChange:w=>i(w.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[300px]",children:b?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(w=>e.jsx(s.Skeleton,{className:"h-16 w-full"},w))}):f.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(s.UserPlus,{className:"h-12 w-12 mb-3 opacity-50"}),e.jsx("p",{className:"text-sm font-medium",children:"No available users"}),e.jsx("p",{className:"text-xs mt-1",children:c?"Try a different search":"All eligible users are already members"})]}):e.jsx("div",{className:"space-y-2",children:f.map(w=>e.jsx(Za,{user:w,selected:d.includes(w.id),onToggle:()=>T(w.id)},w.id))})}),d.length>0&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[d.length," user",d.length!==1?"s":""," selected"]}),e.jsx(s.Button,{onClick:j,disabled:S.isPending,children:S.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Adding..."]}):e.jsxs(e.Fragment,{children:[e.jsx(s.UserPlus,{className:"mr-2 h-4 w-4"}),"Add Members"]})})]})]})]})]})})})}function Xa({member:t,selected:n,onToggle:a}){var l,o,c,i;const r=((o=(l=t.user)==null?void 0:l.name)==null?void 0:o.split(" ").map(d=>d[0]).join("").toUpperCase())||"?";return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-card hover:bg-muted/50 cursor-pointer",onClick:a,children:[e.jsx(s.Checkbox,{checked:n}),e.jsx(s.Avatar,{className:"h-8 w-8",children:e.jsx(s.AvatarFallback,{className:"text-xs",children:r})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:((c=t.user)==null?void 0:c.name)||"Unknown User"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(i=t.user)==null?void 0:i.email})]})]})}function Za({user:t,selected:n,onToggle:a}){var l;const r=((l=t.name)==null?void 0:l.split(" ").map(o=>o[0]).join("").toUpperCase())||"?";return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-card hover:bg-muted/50 cursor-pointer",onClick:a,children:[e.jsx(s.Checkbox,{checked:n}),e.jsx(s.Avatar,{className:"h-8 w-8",children:e.jsx(s.AvatarFallback,{className:"text-xs",children:r})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:t.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t.email})]})]})}function en({open:t,onOpenChange:n}){const[a,r]=k.useState("groups"),[l,o]=k.useState(""),[c,i]=k.useState(null),[d,u]=k.useState(!1),[m,h]=k.useState(null),{tokenProps:x}=s.useSemaphorContext(),{currentUser:g}=s.useCurrentUserInfo(),v=Ka(),p=(g==null?void 0:g.type)==="tenant",y=x==null?void 0:x.tenantId,{groups:b,isLoading:S,refetch:A}=s.useGroups({type:p?"TENANT_GROUP":"all",tenantId:p?y:void 0,includeMembers:!1}),E=b.filter(N=>{var j;return N.name.toLowerCase().includes(l.toLowerCase())||((j=N.description)==null?void 0:j.toLowerCase().includes(l.toLowerCase()))}),C=async()=>{if(m)try{await v.mutateAsync(m.id),h(null),A()}catch(N){console.error("Failed to delete group:",N)}},D=N=>{i(N),u(!0)},f=()=>{r("groups"),A()};return e.jsxs(e.Fragment,{children:[e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-4xl max-h-[80vh]",children:[e.jsxs(s.DialogHeader,{children:[e.jsxs(s.DialogTitle,{className:"flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-5 w-5"}),"Group Management"]}),e.jsx(s.DialogDescription,{children:"Manage your groups, create new groups, and control group membership"})]}),e.jsxs(s.Tabs,{value:a,onValueChange:r,className:"mt-4",children:[e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsxs(s.TabsTrigger,{value:"groups",className:"flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-4 w-4"}),"Groups"]}),e.jsxs(s.TabsTrigger,{value:"create",className:"flex items-center gap-2",children:[e.jsx(s.Plus,{className:"h-4 w-4"}),"Create Group"]})]}),e.jsx(s.TabsContent,{value:"groups",className:"mt-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search groups...",value:l,onChange:N=>o(N.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[400px]",children:S?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(N=>e.jsx(s.Skeleton,{className:"h-24 w-full"},N))}):E.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(s.Users,{className:"h-12 w-12 mb-3 opacity-50"}),e.jsx("p",{className:"text-sm font-medium",children:"No groups found"}),e.jsx("p",{className:"text-xs mt-1",children:l?"Try a different search":"Create your first group to get started"})]}):e.jsx("div",{className:"space-y-3",children:E.map(N=>e.jsx(sn,{group:N,onManageMembers:()=>D(N),onDelete:()=>h(N),currentUserId:g==null?void 0:g.id},N.id))})})]})}),e.jsx(s.TabsContent,{value:"create",className:"mt-4",children:e.jsx(Qa,{onSuccess:f,tenantId:y,isTenantUser:p})})]})]})}),c&&e.jsx(Ja,{open:d,onOpenChange:u,group:c,onUpdate:()=>A()}),e.jsx(s.AlertDialog,{open:!!m,onOpenChange:()=>h(null),children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Group"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',m==null?void 0:m.name,'"? This action cannot be undone and will remove all members from the group.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:C,disabled:v.isPending,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:v.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Deleting..."]}):"Delete Group"})]})]})})]})}function sn({group:t,onManageMembers:n,onDelete:a,currentUserId:r}){const l=t.createdBy===r;return e.jsx("div",{className:"rounded-lg border bg-card p-4 transition-colors hover:bg-muted/50",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium",children:t.name}),t.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:t.description})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(s.Users,{className:"h-3 w-3"}),t.memberCount," ",t.memberCount===1?"member":"members"]}),e.jsxs("span",{children:["Created ",s.format(new Date(t.createdAt),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:n,title:"Manage members",children:e.jsx(s.UserPlus,{className:"h-4 w-4"})}),l&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:a,title:"Delete group",className:"text-destructive hover:text-destructive",children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]})})}function rs(t){const[n,a]=k.useState(null),[r,l]=k.useState(null);return k.useEffect(()=>{if(!t||t.trim()===""){a(null),l(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const i=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(i,{method:"HEAD"})).ok)throw new Error(`Module not found at ${i}`)}catch{}const d=await import(i);if(typeof d.useChartStore!="function")throw new Error("useChartStore is not a function");a(()=>d.useChartStore),l(null)}catch(c){const i=c instanceof Error?c.message:"Unknown error";console.error("Failed to load remote chart store:",i),l(i),a(null)}})()},[t]),n}function tn(t){const n=t.toUpperCase().indexOf("WHERE"),a=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),l=t.toUpperCase().indexOf("ORDER BY");let o=t.length;if(l!==-1&&(o=l),r!==-1&&r<o&&(o=r),n!==-1){const c=t.substring(0,n),i=t.substring(n);return`${c} {{ filters | where }} AND ${i.substring(6)}`}else if(a!==-1){const c=t.substring(0,a),i=t.substring(a);return`${c} {{ filters | where }} ${i}`}else{const c=t.substring(0,o),i=t.substring(o);return console.log("beforeClause",c),console.log("afterClause",i),i?`${c} {{ filters | where }} ${i}`:`${c.replace(/;$/,"")} {{ filters | where }}`}}function an(t,n){if(t.length===0)return"";if(n){const a=t.find(r=>r.id===n);if(a){const r=a.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const o=r.split("__")[0],c=t.find(i=>i.tabTitle===o);return c?c.id:t[0].id}return n}}return t[0].id}async function Cs(t,n,a,r){if(!n||!a)throw new Error("Missing auth token or visual ID");const l=["resource-by-id","visual",a],o=r.getQueryData(l);if(o)return console.log("Using cached visual data for:",a),{data:o,fromCache:!0};console.log("Fetching visual data from network for:",a);const c=s.ue.loading("Loading visual...",{position:"top-center"});try{const i=await fetch(`${t}/management/v1/visuals/${a}`,{headers:{Authorization:`Bearer ${n}`}});if(!i.ok)throw new Error("Failed to load visual");const d=await i.json();return r.setQueryData(l,d),s.ue.dismiss(c),{data:d,fromCache:!1}}catch(i){throw s.ue.dismiss(c),i}}function et(t){if(typeof t=="string")return JSON.parse(t);if(typeof t=="object")return t;throw new Error("Invalid frame object format")}function nn(t,n){var o,c;const a=(t==null?void 0:t.frameObject)??((o=t==null?void 0:t.visual)==null?void 0:o.frameObject);if(!a)return!1;const r=et(a);if(!(r!=null&&r.cards)||r.cards.length===0)return!1;const l=(c=r.cards)==null?void 0:c.find(i=>i.id===r.activeCardId);return l?(s.setupEditorWithCard({...n,frame:r,card:l,visualId:(t==null?void 0:t.id)||r.visualId}),!0):!1}function rn(){var x;const{setCardSql:t}=s.useEditorActions(),n=s.useEditorStore(g=>g.frame),a=s.useEditorStore(g=>g.card),r=rs(((x=a.customCardPreferences)==null?void 0:x.url)||""),l=s.useEditorStore(g=>g.selectedSchemaName),o=s.useEditorStore(g=>g.selectedDatamodelId),c=s.useEditorStore(g=>g.selectedDatabaseName),i=s.useEditorStore(g=>g.selectedTableName),d=s.useEditorStore(g=>g.selectedConnectionId),u=s.useEditorStore(g=>g.isShowingVisual),m=a.sql;return{getUpdatedFrame:k.useCallback(()=>{var b;let g=m;m&&!m.includes("{{")&&(g=tn(m),t(g));const v=(b=r==null?void 0:r.getState())==null?void 0:b.settings,p={...a,dataSource:a.dataSource||{mode:"directSource"},lastSelectedSchema:l,lastSelectedDatamodelId:o,lastSelectedDatabase:c,lastSelectedTable:i,connectionId:d,sql:g,customCfg:u?a.customCfg:null,preferences:a.preferences,...v&&{customCardPreferences:{...a.customCardPreferences,settings:v}}},y=n.cards.map(S=>S.id===a.id?p:S);return{...n,cards:y,activeCardId:an(y,n.activeCardId)}},[a,n,u,l,o,c,i,d,t,r,m])}}function Ae(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient(),r=s.useSelectedVisual(),{selectVisual:l}=s.useManagementActions(),{setFrame:o,setCard:c,setIsDevMode:i,setActiveTabCardId:d,updateDataSource:u,setQueryResultColumns:m,setSelectedConnectionId:h,setSelectedDatabaseName:x,setSelectedSchemaName:g,setSelectedTableName:v,setSelectedDatamodelId:p,setFilterValues:y,setApplyFilters:b}=s.useEditorActions(),{setIsDashboardEditing:S,setIsVisualEditing:A,setSelectedFrameId:E,clearSelectedFrameId:C,addFrame:D,setIsDashboardPanelOpen:f}=s.useDashboardActions(),N=s.useDashboardStore(M=>M.selectedSheetId),j=s.useDashboardStore(M=>M.selectedFrameId),R=s.useDashboardStore(M=>M.dashboard),T=s.useDashboardStore(M=>M.filterValues),F=s.useVisualById((r==null?void 0:r.id)||"",{enabled:!!(r!=null&&r.id)&&!!(t!=null&&t.accessToken)}),w=k.useCallback(async M=>{try{l(M),C();const{data:O,fromCache:L}=await Cs(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",M.id,a);if(!nn(O,{setFrame:o,setCard:c,setIsDevMode:i,setActiveTabCardId:d,updateDataSource:u,setQueryResultColumns:m,setSelectedConnectionId:h,setSelectedDatabaseName:x,setSelectedSchemaName:g,setSelectedTableName:v,setSelectedDatamodelId:p,setFilterValues:y,setApplyFilters:b,setIsDashboardEditing:S,setIsVisualEditing:A,dashboard:R,selectedSheetId:N,selectedFrameId:j,filterValues:T}))throw new Error("Failed to setup editor with visual data");return{success:!0,fromCache:L}}catch(O){return console.error("Error editing visual:",O),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,n.apiServiceUrl,a,l,o,c,S,A,i,d,u,m,h,x,g,v,p,y,b,C,R,N,j,T]),I=k.useCallback(async M=>{var O;try{if(l(M),!N)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:L,fromCache:P}=await Cs(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",M.id,a),B=(L==null?void 0:L.frameObject)??((O=L==null?void 0:L.visual)==null?void 0:O.frameObject);if(!B)return{success:!1,error:"Visual has no frame data"};const H=et(B);if(!(H!=null&&H.cards)||H.cards.length===0)return{success:!1,error:"Visual frame is malformed"};const q={...H,id:s.v4(),visualId:M.id};return D(N,q,"end"),S(!0),E(q.id),f(!1),{success:!0,fromCache:P}}catch(L){return console.error("Error adding visual:",L),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,n.apiServiceUrl,a,l,N,D,S,E,f]);return{visual:F.data,isLoading:F.isLoading,isError:F.isError,error:F.error,handleEditLibraryVisual:w,handleAddLibraryVisual:I,getUpdatedFrame:rn().getUpdatedFrame,refetch:F.refetch}}function ln({open:t,onOpenChange:n,isLibraryVisual:a,currentVisualName:r,isSaving:l=!1,onConfirm:o}){const[c,i]=k.useState(a&&r?`Copy of ${r}`:r||""),[d,u]=k.useState(""),[m,h]=k.useState(!a),[x,g]=k.useState(!0);k.useEffect(()=>{t&&(i(a&&r?`Copy of ${r}`:r||""),u(""),h(!a),g(!0))},[t,a,r]);const v=()=>{c.trim()&&(!m&&!x||o({name:c.trim(),description:d.trim()||void 0,saveToLibrary:m,saveToCurrentDashboard:x}))},p=c.trim()&&(m||x);return e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Save Visual As"}),e.jsx(s.DialogDescription,{children:a?"Create a copy of this visual with a new name":"Save this visual to make it reusable"})]}),e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"name",children:"Name"}),e.jsx(s.Input$1,{id:"name",value:c,onChange:y=>i(y.target.value),placeholder:"Enter visual name",disabled:l})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"description",children:"Description (optional)"}),e.jsx(s.Textarea,{id:"description",value:d,onChange:y=>u(y.target.value),placeholder:"Enter visual description",rows:3,disabled:l})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Label,{children:"Save to:"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"save-to-dashboard",checked:x,onCheckedChange:y=>g(!!y),disabled:l}),e.jsxs("label",{htmlFor:"save-to-dashboard",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:["Current Dashboard",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:a?"(add copy to this dashboard)":"(keep as local visual)"})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"save-to-library",checked:m,onCheckedChange:y=>h(!!y),disabled:l}),e.jsxs("label",{htmlFor:"save-to-library",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:["Visual Library",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:a?"(save as new reusable visual)":"(make available to all dashboards)"})]})]})]}),!m&&!x&&e.jsx("p",{className:"text-sm text-destructive",children:"Please select at least one destination"})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),disabled:l,children:"Cancel"}),e.jsxs(s.Button,{onClick:v,disabled:!p||l,children:[l&&e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),l?"Saving...":"Save"]})]})]})})}function on({className:t,variant:n="outline"}){var i;const{setCardSql:a}=s.useEditorActions();s.useEditorStore(d=>d.frame);const r=s.useEditorStore(d=>d.card);rs(((i=r.customCardPreferences)==null?void 0:i.url)||""),s.useEditorStore(d=>d.selectedSchemaName),s.useEditorStore(d=>d.selectedDatamodelId),s.useEditorStore(d=>d.selectedDatabaseName),s.useEditorStore(d=>d.selectedTableName),s.useEditorStore(d=>d.selectedConnectionId),s.useEditorStore(d=>d.isShowingVisual),r.sql;const l=s.useEditorStore(d=>d.onSave),{getUpdatedFrame:o}=Ae();function c(){const d=o();l==null||l(d)}return e.jsxs(s.Button,{onClick:c,className:s.cn("h-8",t),size:"sm",variant:n,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function cn({className:t,variant:n="default"}){const a=s.useQueryClient(),[r,l]=k.useState(!1),o=s.useDashboardStore(x=>x.actions.setIsDashboardPanelOpen),{setIsVisualEditing:c}=s.useDashboardActions(),{getUpdatedFrame:i}=Ae(),d=s.useSelectedVisual(),u=s.useEditorStore(x=>x.frame),m=s.useUpdateVisualMutation(),h=()=>{const x=i(),g=(u==null?void 0:u.visualId)||(d==null?void 0:d.id);if(!g){s.ue.error("No visual to save");return}l(!0),m.mutate({visualId:g,data:{frameObject:x}},{onSuccess:()=>{l(!1),o(!0),s.ue.success("Visual updated successfully"),a.invalidateQueries({queryKey:["resource-by-id","visual",g],exact:!0})},onError:()=>{l(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:h,className:s.cn("h-8",t),size:"sm",variant:n,children:[r&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!r&&e.jsxs(e.Fragment,{children:[e.jsx(Fe,{className:"mr-2 size-4 font-bold"}),"Save to Library"]})]})}function dn({className:t}){const n=s.useQueryClient(),[a,r]=k.useState(!1),l=s.useSelectedVisual(),o=s.useEditorStore(x=>x.frame),c=s.useDashboardStore(x=>x.selectedSheetId),{updateFrame:i,setIsVisualEditing:d}=s.useDashboardActions(),{getUpdatedFrame:u}=Ae(),m=s.useUpdateVisualMutation(),h=async()=>{if(!c){s.ue.error("No sheet selected");return}const x=(o==null?void 0:o.visualId)||(l==null?void 0:l.id);if(!x){s.ue.error("No visual to update");return}r(!0);try{const g=u();await m.mutateAsync({visualId:x,data:{frameObject:g}});const v={...g,visualId:x};i(c,v),n.invalidateQueries({queryKey:["visuals"]}),n.invalidateQueries({queryKey:["visual",x]}),s.ue.success("Saved to library and applied locally"),setTimeout(()=>{d(!1)},300)}catch(g){console.error("Failed to save and apply:",g),s.ue.error("Failed to save and apply changes")}finally{r(!1)}};return e.jsx(s.Button,{onClick:h,className:s.cn("h-8",t),size:"sm",variant:"default",disabled:a,children:a?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Fe,{className:"mr-2 size-4 font-bold"}),"Save & Apply"]})})}function un({className:t}){const{getUpdatedFrame:n}=Ae();s.useEditorStore(d=>d.frame);const a=s.useDashboardStore(d=>d.selectedSheetId),{updateFrame:r,setIsVisualEditing:l}=s.useDashboardActions(),[o,c]=k.useState(!1),i=()=>{if(!a){s.ue.error("No sheet selected");return}c(!0);const u={...n(),visualId:void 0};r(a,u),setTimeout(()=>{c(!1),s.ue.success("Changes applied. Visual is now local to this dashboard"),l(!1)},300)};return e.jsxs(s.Button,{onClick:i,className:s.cn("h-8",t),size:"sm",variant:"outline",children:[o&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Applying"]}),!o&&e.jsxs(e.Fragment,{children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Apply Locally"]})]})}function mn({className:t}){const{setTempQueryData:n,setSqlGen:a}=s.useEditorActions(),r=s.useQueryClient(),l=s.useEditorStore(u=>u.tempQueryData),o=s.useEditorStore(u=>u.onClose),c=s.useEditorStore(u=>u.card),{queryKey:i}=s.useDashboardCardQuery(c);function d(){if(l){const{queryKey:u,queryData:m}=l;u&&m&&r.setQueryData(u,m)}a({}),o==null||o()}return e.jsxs(s.Button,{onClick:d,className:s.cn("h-8",t),size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function ls(){const{setTempQueryData:t}=s.useEditorActions(),n=s.useQueryClient();s.useEditorStore(p=>p.isDevMode);const a=s.useEditorStore(p=>p.tempQueryData),r=s.useEditorStore(p=>p.card),{queryKey:l}=s.useDashboardCardQuery(r),{setCardSql:o,setSqlGen:c,setCardPython:i,setCardCustomCfg:d,setCardPreferences:u,updateDataSource:m,clearQueryConfig:h,setCardConfig:x,setCardType:g}=s.useEditorActions();function v(){const p=n.getQueryData(l);a!=null&&a.queryData||t({queryKey:l,queryData:p}),n.setQueryData(l,null),n.removeQueries({queryKey:l,exact:!0}),o(""),c({}),h(),x(void 0),i(""),d(""),u({}),g("bar")}return e.jsxs(s.Button,{onClick:v,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(s.SquarePen,{className:"mr-2 size-4"}),"Clear"]})}function hn(){const[t,n]=k.useState(!1),[a,r]=k.useState(!1),[l,o]=k.useState(null),c=s.useEditorStore(E=>E.frame),i=s.useEditorStore(E=>E.card),d=s.useSelectedVisual(),u=s.useDashboardStore(E=>E.selectedSheetId),m=s.useDashboardStore(E=>E.actions.setIsDashboardPanelOpen),{getUpdatedFrame:h}=Ae(),{selectVisual:x}=s.useManagementActions(),{addFrame:g,setSelectedFrameId:v,setIsVisualEditing:p}=s.useDashboardActions(),y=!!(c!=null&&c.visualId),b=(d==null?void 0:d.title)||(i==null?void 0:i.title)||"Untitled Visual",S=s.useCreateVisualWithFrame(E=>{if(E!=null&&E.id){if(x(E),a&&l&&u){const C={...l,id:s.v4(),visualId:E.id};g(u,C,"end"),v(C.id),r(!1),o(null),p(!1)}m(!0),n(!1)}});return{saveAsDialogOpen:t,setSaveAsDialogOpen:n,handleSaveAs:async E=>{if(!u){s.ue.error("No sheet selected");return}const C=h();if(E.saveToLibrary){r(E.saveToCurrentDashboard),o(C);const D={title:E.name,description:E.description,frameObject:C,isPrivate:!1};S.mutate(D)}else if(E.saveToCurrentDashboard){const D={...C,id:s.v4(),visualId:void 0,cards:C.cards.map(f=>({...f,title:f.id===i.id?E.name:f.title}))};g(u,D,"end"),v(D.id),s.ue.success("Visual saved to dashboard"),n(!1),p(!1)}},isLibraryVisual:y,currentVisualName:b,isSaving:S.isPending}}function st({className:t}){const n=s.useEditorStore(S=>S.frame),a=s.useEditorStore(S=>S.card),r=s.useManagementStore(S=>S.selectedVisual),l=s.useDashboardStore(S=>S.selectedFrameId),o=s.useDashboardStore(S=>S.selectedSheetId),{setIsVisualEditing:c}=s.useDashboardActions(),i=!!(n!=null&&n.visualId||r!=null&&r.id),d=!!(n!=null&&n.visualId&&l),u=i&&!d,{saveAsDialogOpen:m,setSaveAsDialogOpen:h,handleSaveAs:x,isLibraryVisual:g,currentVisualName:v,isSaving:p}=hn(),{handleAddLibraryVisual:y}=Ae(),b=async()=>{if(!o){s.ue.error("No dashboard sheet selected");return}if(!r){s.ue.error("No visual selected");return}const S=await y(r);S.success?(s.ue.success("Visual added to dashboard"),c(!1)):s.ue.error(S.error||"Failed to add visual to dashboard")};return e.jsxs(e.Fragment,{children:[!i&&e.jsx(on,{className:t,variant:"default"}),i&&e.jsxs(e.Fragment,{children:[d&&e.jsx(un,{className:t}),u&&o&&a&&(a.sql||s.hasValidCardConfig(a.config))&&e.jsxs(s.Button,{onClick:b,className:s.cn(t),size:"sm",variant:"outline",children:[e.jsx(Vt,{className:"mr-2 size-4 font-bold"}),"Add to Dashboard"]}),u&&e.jsx(cn,{className:t,variant:"default"}),d&&e.jsx(dn,{className:t}),e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:s.cn(t,"w-8 p-0"),children:e.jsx(s.EllipsisVertical,{className:"h-4 w-4"})})}),e.jsx(s.DropdownMenuContent,{align:"end",children:e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),h(!0)},children:[e.jsx(Fe,{className:"mr-2 h-4 w-4"}),"Save As..."]})})]})]}),!i&&e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:s.cn(t,"w-8 p-0"),children:e.jsx(s.EllipsisVertical,{className:"h-4 w-4"})})}),e.jsx(s.DropdownMenuContent,{align:"end",children:e.jsxs(s.DropdownMenuItem,{onClick:()=>h(!0),children:[e.jsx(Fe,{className:"mr-2 h-4 w-4"}),"Save As..."]})})]}),e.jsx(mn,{className:t}),e.jsx(ln,{open:m,onOpenChange:S=>{p||h(S)},isLibraryVisual:g,currentVisualName:v,isSaving:p,onConfirm:x})]})}function tt({className:t,labelClassName:n,switchClassName:a}){const r=s.useEditorStore(d=>d.isDevMode),l=s.useDashboardStore(d=>d.isVisualEditing),{setIsDevMode:o}=s.useEditorActions(),{config:c}=k.useContext(s.SemaphorContext).tokenProps,i=(c==null?void 0:c.showAdvancedMode)!==!1;return!l||!i?null:e.jsxs("div",{className:s.cn("flex items-center space-x-2",t),children:[e.jsx(s.Switch,{className:s.cn("",a),checked:r,onCheckedChange:()=>o(!r),id:"advanced-mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:s.cn("text-sm font-medium",n),children:"Advanced Mode"})]})}function xn(){var fe,ue,$;const{authToken:t,tokenProps:n,id:a}=s.useSemaphorContext(),{isLocalDev:r,isConsoleMode:l}=s.useDashboardPreferences(),{permissions:o}=s.useRoleAwareDisplayPreferences(),c=s.useHasDashboardId();s.useDashboardStore(G=>G.theme);const i=s.useDashboardStore(G=>G.lenses),d=s.useDashboardStore(G=>G.selectedLensId),u=i==null?void 0:i.find(G=>G.id===d),m=s.useDashboardStore(G=>G.dashboard);s.useDashboardStore(G=>G.selectedSheetId);const h=s.useDashboardStore(G=>G.isDashboardEditing),[x,g]=k.useState(!1),[v,p]=k.useState(!1),[y,b]=k.useState(!1),S=s.useDashboardStore(G=>G.isDashboardPanelOpen),A=s.useDashboardStore(G=>G.actions.setIsDashboardPanelOpen),E=s.useDashboardStore(G=>G.filterValues),C=s.useDashboardStore(G=>G.isVisualEditing),D=s.useEditorStore(G=>G.card),f=s.useManagementStore(G=>G.selectedDashboard),N=s.useManagementStore(G=>G.initialDashboard),j=s.useManagementStore(G=>G.selectedVisual);s.useDashboardStore(G=>G.selectedFrameId),s.useEditorStore(G=>G.frame);const R=f?(ue=f==null?void 0:f.permissions)==null?void 0:ue.canEdit:(fe=N==null?void 0:N.permissions)==null?void 0:fe.canEdit,T=s.useDashboardStore(G=>G.showFilters),F=s.useDashboardStore(G=>G.showDashboardJSON),w=s.useDashboardStore(G=>G.onSaveFunction),I=s.useDashboardStore(G=>G.actions.setShowFilters),{setIsDashboardEditing:M,setShowDashboardJSON:O}=s.useDashboardStore(G=>G.actions),{setInitialDashboard:L,clearSelectedDashboard:P}=s.useManagementStore(G=>G.actions),{resources:B}=s.useResourceManagement(s.ResourceType.DASHBOARD),{currentUser:H}=s.useCurrentUserInfo(),q=s.canUserManageGroups(H),z=f||N,Q=z?{id:z.id,title:(m==null?void 0:m.title)||z.title||"Dashboard"}:null,{handleAddNewFrame:X}=s.useAddNewFrame(),[se,te]=k.useState(!1),ie=s.useUpdateResource(s.ResourceType.DASHBOARD);k.useEffect(()=>{if(B&&B.length>0){const G=m==null?void 0:m.id;if(G){const V=B.find(Z=>Z.id===G);V&&L(V)}}},[B,m==null?void 0:m.id,L]);const K=n.orgUserId||n.tenantId,Y=h&&!C&&K&&R,ae=()=>{M(!0)};async function W(){const G=Ke(m);te(!0);const V={template:G};ie.mutate({resourceId:G.id,data:V},{onSuccess:()=>{te(!1),s.ue.success("Dashboard saved!")},onError:()=>{te(!1),s.ue.error("Failed to save dashboard")}})}async function re(){if(g(!0),!d||!u)return;const G=Ke(m),V=JSON.stringify(G),Z={...u,template:V,filterValues:E};await ts(n.apiServiceUrl,Z,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),w==null||w(G),g(!1)}const U=(u==null?void 0:u.name)||m.title,ce=B&&B.length>0&&(n.orgUserId||n.tenantId&&n.endUserId&&n.endUserEmail),le=f&&!(n!=null&&n.dashboard_id)&&!a;return e.jsxs("div",{className:"flex h-11 items-center justify-between gap-2 border-b px-4 py-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[ce&&e.jsxs(e.Fragment,{children:[e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:"Manage Dashboards",onClick:()=>{A(!S)},className:"h-7 p-2",children:e.jsx(aa,{className:"h-4 w-4"})}),le&&!C&&e.jsx(s.IconButton,{"aria-label":"Dashboard Hub",tooltip:"Dashboard Hub",onClick:()=>P(),className:"h-7 p-2",children:e.jsx(s.House,{className:"h-4 w-4"})})]}),!C&&c&&e.jsx(s.Label,{children:U}),C&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-sm font-medium",children:(j==null?void 0:j.title)||(D==null?void 0:D.title)||"Untitled Visual"}),e.jsx(Zs,{})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[C&&e.jsxs(e.Fragment,{children:[e.jsx(tt,{className:"mr-2"}),e.jsx(st,{className:"h-7"})]}),r&&!C&&e.jsx(s.IconButton,{tooltip:"Invalidate Token",onClick:()=>s.invalidateToken(n.apiServiceUrl),className:"h-7 p-2",children:e.jsx(ca,{className:"h-4 w-4"})}),!C&&c&&e.jsx(Na,{}),!C&&c&&e.jsx(Gs,{}),!C&&c&&q&&e.jsx(s.IconButton,{tooltip:"Manage Groups",onClick:()=>b(!0),className:"h-7 p-2",children:e.jsx(s.Users,{className:"h-4 w-4"})}),!C&&c&&(($=z==null?void 0:z.permissions)==null?void 0:$.canShare)&&e.jsx(s.IconButton,{tooltip:"Share Dashboard",onClick:()=>p(!0),className:"h-7 p-2",children:e.jsx(Ee,{className:"h-4 w-4"})}),!T&&!C&&h&&o.canUseFilters&&c&&e.jsx(s.Button,{className:"h-7 p-2",variant:"outline",onClick:()=>I(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),h&&!C&&K&&r&&c&&e.jsx(ba,{}),!C&&K&&r&&c&&e.jsx(ya,{}),h&&!C&&K&&u&&r&&c&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:x,onClick:re,size:"sm",children:[e.jsx(Fe,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),h&&!C&&c&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",size:"sm",disabled:!h,onClick:()=>X(),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Visual"]}),!C&&!h&&o.canEdit&&c&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:ae,size:"sm",children:[e.jsx(s.Pencil,{className:"mr-2 h-4 w-4"}),"Edit"]}),Y&&c&&e.jsxs(s.Button,{className:"h-7 p-2",disabled:se,onClick:W,size:"sm",children:[se?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Fe,{className:"mr-2 h-4 w-4"}),se?"Saving...":"Save"]}),!C&&h&&r&&c&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(s.Button,{className:"h-7 p-2",onClick:()=>O(!F),size:"sm",variant:"ghost",children:e.jsx(Ps,{className:"h-4 w-4"})})}),!C&&r&&e.jsx(fa,{}),h&&!C&&c&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:()=>{M(!1),O(!1)},children:[e.jsx(s.Cross2Icon,{className:"mr-2 h-4 w-4"}),"Close"]}),v&&Q&&e.jsx(Qe,{resource:Q,resourceType:s.ResourceType.DASHBOARD,onClose:()=>p(!1)}),e.jsx(en,{open:y,onOpenChange:b})]})]})}const os=t=>{var T;const{updateCardConfig:n,updateGroupByColumn:a,updateMetricColumn:r,updatePivotByColumn:l,updateSortByColumn:o,removeGroupByColumn:c,removeMetricColumn:i,removePivotByColumn:d,removeSortByColumn:u}=s.useEditorActions(),m=s.useEditorStore(F=>F.card.type),h=t==null?void 0:t.id,x=k.useCallback(F=>{if(!(t!=null&&t.config))return[];switch(F){case"groupBy":return(t.config.groupByColumns||[]).map(w=>({id:w.id,name:w.name,dataType:w.dataType,label:w.label!==void 0?w.label:w.name,qualifiedEntityName:w.qualifiedEntityName,entityId:w.entityId,entityName:w.entityName,entityType:w.entityType,dateFormat:w.dateFormat,customFormat:w.customFormat,granularity:w.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(w=>({id:w.id,name:w.name,dataType:w.dataType,label:w.label!==void 0?w.label:w.name,qualifiedEntityName:w.qualifiedEntityName,entityId:w.entityId,entityName:w.entityName,entityType:w.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(w=>({id:w.id,name:w.name,dataType:w.dataType,label:w.label!==void 0?w.label:w.name,qualifiedEntityName:w.qualifiedEntityName,entityId:w.entityId,entityName:w.entityName,entityType:w.entityType,direction:w.direction}));case"source":return[];default:return[]}},[t]),g=k.useCallback((F,w)=>{if(h)switch(F){case"groupBy":{n(h,{groupByColumns:w});break}case"metrics":{n(h,{metricColumns:w});break}case"pivotBy":{n(h,{pivotByColumns:w});break}case"sortBy":{n(h,{sortByColumns:w});break}}},[h,n]),v=k.useCallback((F,w,I)=>{if(!h)return;const O=x(F)[w];if(O)switch(F){case"groupBy":a(h,O.id,{label:I});break;case"metrics":r(h,O.id,{label:I});break;case"pivotBy":l(h,O.id,{label:I});break;case"sortBy":o(h,O.id,{label:I});break}},[h,x,a,r,l,o]),p=k.useCallback((F,w)=>{if(!h)return;const M=x("metrics")[F];M&&r(h,M.id,{aggregate:w,label:s.getAggregationLabel(M.name,w)})},[h,x,r]),y=k.useCallback((F,w,I)=>{if(!h)return;const O=x("groupBy")[F];if(!O)return;const L={dateFormat:w};w==="custom"&&I?L.customFormat=I:L.customFormat=void 0,a(h,O.id,L)},[h,x,a]),b=k.useCallback((F,w)=>{if(!h)return;const M=x("groupBy")[F];M&&a(h,M.id,{granularity:w})},[h,x,a]),S=k.useCallback((F,w)=>{if(!h)return;const M=x("metrics")[F];M&&r(h,M.id,{aliasTemplate:w})},[h,x,r]),A=k.useCallback((F,w)=>{if(console.log("handleValueAliasesChange",F,w),!h)return;console.log("handleValueAliasesChange",F,w);const M=x("metrics")[F];M&&(console.log("handleValueAliasesChange",w),r(h,M.id,{valueAliases:w}))},[h,x,r]),E=k.useCallback(F=>{h&&n(h,{comparisonType:F})},[h,n]),C=k.useCallback(F=>{h&&n(h,{showTrendline:F})},[h,n]),D=k.useCallback(F=>{h&&n(h,{trendlineWindow:F})},[h,n]),f=k.useCallback(F=>{h&&n(h,{trendlineGranularity:F})},[h,n]),N=k.useCallback(F=>{h&&n(h,{targetValue:F})},[h,n]),j=k.useCallback(F=>{var B;if(!h)return;const w=[...x("groupBy"),...x("pivotBy"),...x("metrics"),...x("sortBy")],I=(B=t==null?void 0:t.config)==null?void 0:B.joinPlan,M=s.validateEntityConsistency(F,w,I);if(!M.isValid){M.showError&&s.showJoinRequiredNotification();return}const O=s.getSmartContainerForField(F,w),L=x(O);if(s.fieldAlreadyExists(F,L))return;const P=s.getNewField(F,O,L);P&&g(O,[...L,P])},[h,(T=t==null?void 0:t.config)==null?void 0:T.joinPlan,x,g]),R=k.useCallback((F,w)=>{if(!h)return;const M=x(F)[w];if(M){if(F!=="sortBy"){const O=x("sortBy"),L=O.filter(P=>!(P.name===M.name&&P.qualifiedEntityName===M.qualifiedEntityName));L.length!==O.length&&n(h,{sortByColumns:L})}switch(F){case"groupBy":c(h,M.id);break;case"metrics":i(h,M.id);break;case"pivotBy":d(h,M.id);break;case"sortBy":u(h,M.id);break}}},[h,x,c,i,d,u,n]);return{getFieldsForContainer:x,setFieldsForContainer:g,updateLabel:v,handleAggregationChange:p,handleDateFormatChange:y,handleGranularityChange:b,handleAliasTemplateChange:S,handleValueAliasesChange:A,removeField:R,handleFieldClick:j,handleKpiComparisonTypeChange:E,handleKpiShowTrendlineChange:C,handleKpiTrendlineWindowChange:D,handleKpiTrendlineGranularityChange:f,handleKpiTargetValueChange:N,cardType:m}};function Ue(t){return`${t}-${s.v4()}`}function Ss(t,n){const a=s.toTitleCase(t.replace(/_/g," "));switch(n){case"SUM":return`Sum of ${a}`;case"COUNT":return`Count of ${a}`;case"DISTINCT":return`Unique ${a}`;case"AVG":return`Average of ${a}`;case"MIN":return`Min of ${a}`;case"MAX":return`Max of ${a}`;default:return a}}function pn(t,n){const a=s.toTitleCase(t.replace(/_/g," "));switch(n){case"day":return`Date of ${a}`;case"week":return`Week of ${a}`;case"month":return`Month of ${a}`;case"year":return`Year of ${a}`;default:return a}}function is(t){if(!t||!t.selectedEntities||t.selectedEntities.length===0)return{tableName:void 0,schemaName:void 0,databaseName:void 0,connectionId:t==null?void 0:t.connectionId,connectionType:t==null?void 0:t.connectionType};const n=t.selectedEntities[0];return{tableName:n==null?void 0:n.name,schemaName:n==null?void 0:n.schema,databaseName:n==null?void 0:n.database,connectionId:t.connectionId,connectionType:t.connectionType}}function at(t){if(!t||!t.selectedEntities||t.selectedEntities.length===0)return!1;const n=t.selectedEntities[0];return!!(n!=null&&n.name)}function nt(){const t=s.useEditorStore(D=>D.sqlGen),n=s.useEditorStore(D=>D.isDevMode),a=s.useEditorStore(D=>D.card.dataSource),r=s.useEditorStore(D=>{var f,N;return(N=(f=D.card)==null?void 0:f.queryConfig)==null?void 0:N.metricColumns}),{tableName:l,schemaName:o,databaseName:c}=is(a),i=at(a),d=s.useEditorStore(D=>D.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:m,setCardSql:h,setRunSql:x,setSqlGen:g,setIsShowingVisual:v}=s.useEditorActions(),{connectionType:p,modelItems:y,selectedDatamodelName:b}=s.useEditorAside(),S=D=>({column_name:D.name,data_type:D.dataType,label:D.label,description:D.description});return{handleDevModeFieldClick:D=>{var N;if(!n)return;const f=S(D);if(n&&i&&l){const j=s.createSqlGenConfig(f,t);g(j);const R=(N=y==null?void 0:y.find(F=>F.id===d))==null?void 0:N.name,T=s.getSql(j,s.fmt(o||""),s.fmt(l),R||"",p,c||"");T&&(h(T),x(!0))}else if(!n){if(s.isTextDataType(f.data_type))if(r&&r.length>0){const j={...f,role:"groupby",id:Ue(f.column_name),name:f.column_name,type:f.data_type};m(j)}else{const j={...f,role:"metric",id:Ue(f.column_name),name:f.column_name,label:Ss(f.column_name,"COUNT"),type:f.data_type,aggregate:"COUNT"};u(j)}if(s.isDateDataType(f.data_type)){const j={...f,role:"groupby",id:Ue(f.column_name),name:f.column_name,type:f.data_type,label:pn(f.column_name,"month"),granularity:"month"};m(j)}if(s.isNumberDataType(f.data_type)){const j={...f,role:"metric",id:Ue(f.column_name),name:f.column_name,label:Ss(f.column_name,"SUM"),type:f.data_type,aggregate:"SUM"};u(j)}}},handleShowSample:()=>{if(!i||!l){console.warn("Cannot generate SQL: missing table metadata");return}const D=s.getFormattedTableNameForQuery({schemaName:o||"",tableName:l,modelName:b,connectionType:p,databaseName:c||""});v(!1);const f=p==="MSSQL"?`SELECT top 10 * FROM ${D}`:`SELECT * FROM ${D} LIMIT 10`;h(f),x(!0)},handleShowCount:()=>{if(!i||!l){console.warn("Cannot generate SQL: missing table metadata");return}const D=s.getFormattedTableNameForQuery({schemaName:o||"",tableName:l,modelName:b,connectionType:p,databaseName:c||""});h(`SELECT COUNT(*) as count FROM ${D}`),x(!0)},isNumberField:D=>s.isNumberDataType(D.dataType)}}function rt(){const t=s.useEditorStore(g=>g.selectedConnectionId),n=s.useEditorStore(g=>g.selectedDatamodelId),a=s.useEditorStore(g=>g.selectedDatabaseName),r=s.useEditorStore(g=>g.selectedSchemaName),l=s.useEditorStore(g=>g.selectedTableName),o=s.useDashboardStore(g=>g.dashboard.filters)||[],c=s.useDashboardStore(g=>g.actions.addFilter),i=s.useDashboardStore(g=>g.actions.removeFilter),{removeFilterValues:d}=s.useDashboardActions(),{modelItems:u,tableName:m,connectionType:h}=s.useEditorAside();function x(g,v="dashboard",p){var N;const y=s.fmt(g.column_name),b=s.fmt(a||""),S=s.fmt(r||""),A=s.fmt(m);let E=s.getQualifiedTableName({schemaName:S,tableName:A,connectionType:h,databaseName:b}),C=`${E}.${y}`;const D=(N=u==null?void 0:u.find(j=>j.id===n))==null?void 0:N.name;n&&n!=="none"&&(C=`${s.DATAMODEL_NAMESPCACE}.${D}.${y}`,E=`${s.DATAMODEL_NAMESPCACE}.${D}`),p!=null&&p.qualifiedFieldName&&(C=p.qualifiedFieldName),p!=null&&p.entityName&&(E=p.entityName);const f=o==null?void 0:o.find(j=>j.column===C&&j.table===A&&(j.database===b||j.database===a));if(f)d(f.id),i(f.id);else{const j=s.v4();return m==="api"&&t?(c({location:v,id:j,column:C,title:g.column_name,dataType:g.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(g.data_type,E,y)}),j):(c({id:j,location:v,column:C,title:g.column_name,dataType:g.data_type,table:l||"",database:a||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(g.data_type,E,y)}),j)}}return{assignFilter:x}}function fn({column:t}){const[n,a]=k.useState(!1),r=s.useEditorStore(b=>b.card.dataSource),{tableName:l,schemaName:o,databaseName:c}=is(r),i=s.useEditorStore(b=>b.selectedDatamodelId),d=s.useEditorStore(b=>b.sqlGen),{modelItems:u,connectionType:m}=s.useEditorAside(),h=s.useEditorStore(b=>b.actions.setSqlGen),x=s.useEditorStore(b=>b.actions.setCardSql),g=s.useEditorStore(b=>b.actions.setRunSql),v=at(r);function p(b,S){var D;if(!v||!l){console.warn("Cannot generate SQL: missing table metadata");return}const A=s.createSqlGenConfig(b,d,S),E=(D=u==null?void 0:u.find(f=>f.id===i))==null?void 0:D.name;h(A);const C=s.getSql(A,s.fmt(o||""),s.fmt(l),E||"",m,c||"");C&&(x(C),g(!0)),a(!1)}function y(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>p(t,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>p(t,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>p(t,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>p(t,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>p(t,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return v?e.jsxs(s.HoverCard,{openDelay:0,open:n,onOpenChange:a,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:y()})]}):null}function gn({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 jn({field:t,context:n="editor"}){const a=s.useEditorStore(f=>f.isDevMode),r=n==="filter",l=s.useDashboardStore(f=>f.dashboard.filters),{assignFilter:o}=rt(),c=r&&(l==null?void 0:l.some(f=>{var N;return f.title===t.name||((N=f.column)==null?void 0:N.includes(t.name))})),{attributes:i,listeners:d,setNodeRef:u,transform:m,transition:h,isDragging:x}=s.useSortable({id:t.id,disabled:a||r}),[g,v]=k.useState(!1),p=s.useEditorStore(f=>f.card),{handleFieldClick:y}=os(p),{handleDevModeFieldClick:b,isNumberField:S}=nt(),A=()=>{if(r){const f={column_name:t.name,data_type:t.dataType,label:t.label,description:t.description};o(f,"dashboard",t)}else a?b(t):y(t)},E={column_name:t.name,data_type:t.dataType,label:t.label,description:t.description},C={transform:s.CSS.Transform.toString(m),transition:h},D=f=>{const N=(f||"").toLowerCase(),j=s.getDataType(N);return j==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(qe,{className:"h-3 w-3"})}):j==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(as,{className:"h-3 w-3"})}):j==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):j==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(zs,{className:"h-3 w-3"})}):j==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Ps,{className:"h-3 w-3"})}):j==="geo"?e.jsx("div",{className:"bg-orange -100 flex size-6 shrink-0 items-center justify-center rounded-sm text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(ta,{className:"h-3 w-3"})}):j==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Os,{className:"h-3 w-3"})}):null};return e.jsxs("div",{ref:u,style:C,...a||r?{}:i,...a||r?{}:d,className:s.cn("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",x&&"scale-95 opacity-50",!x&&"border border-transparent hover:bg-muted",c&&"bg-accent border-accent-foreground/20",{"cursor-pointer":a||r,"cursor-grab active:cursor-grabbing":!a&&!r}),children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:A,children:[D(t.dataType),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:e.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${g?"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(gn,{field:t})})]})}),a&&!r&&S(t)&&e.jsx("div",{onClick:f=>f.stopPropagation(),children:e.jsx(fn,{column:E})})]}),g&&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(Vs,{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(xa,{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 vn({context:t="editor"}={}){const[n,a]=k.useState(""),[r,l]=k.useState("all"),o=s.useEditorStore(f=>f.isDevMode),c=s.useEditorStore(f=>f.card.dataSource),{columns:i=[],columnGroups:d=[],isLoading:u,error:m}=s.useColumns(),{handleShowSample:h,handleShowCount:x}=nt(),g=i.filter(f=>f.name.toLowerCase().includes(n.toLowerCase())||f.dataType.toLowerCase().includes(n.toLowerCase())||f.label&&f.label.toLowerCase().includes(n.toLowerCase())||f.qualifiedEntityName&&f.qualifiedEntityName.toLowerCase().includes(n.toLowerCase())),v=f=>{if(f.dataType==="number"||f.dataType==="integer"||f.dataType==="float"||f.dataType==="decimal"||f.dataType==="currency")return"metrics";const N=s.getDataType(f.dataType);return["date","string","boolean"].includes(N)?"dimensions":N==="number"?"metrics":"dimensions"},y=(r==="all"?g:g.filter(f=>v(f)===r)).reduce((f,N)=>{const j=N.qualifiedEntityName||"Other Fields";return f[j]||(f[j]={label:s.toLabel(N.entityName),fields:[]}),f[j].fields.push(N),f},{}),S=Object.keys(y),A=g.filter(f=>v(f)==="dimensions").length,E=g.filter(f=>v(f)==="metrics").length,C=g.filter(f=>v(f)==="calculated").length,D=g.length>0;return u?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"})}):m?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:m.message||"Failed to load column data"})]}):!c||!c.selectedEntities||c.selectedEntities.length===0?e.jsx(s.ScrollArea,{className:"h-[calc(100vh-200px)] w-[290px]",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:t==="filter"?"Configure a data source for this card to see available fields":"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-[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&&t!=="filter"&&i.length>0&&e.jsxs("div",{className:"flex grow gap-2",children:[e.jsxs(s.Button,{disabled:u,onClick:h,size:"sm",variant:"secondary",className:"grow",children:[u?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(sa,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:u,onClick:x,size:"sm",variant:"secondary",className:"grow",children:[u?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(da,{className:"mr-2 size-4"}),"Count"]})]}),i.length>0&&e.jsxs("div",{className:"relative mb-4",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:n,onChange:f=>a(f.target.value)}),n&&e.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>a(""),type:"button",children:e.jsx(s.X,{className:"size-3.5"})})]}),D&&e.jsx(s.Tabs,{defaultValue:"all",value:r,onValueChange:f=>l(f),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:g.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:A})]}),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:E})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(Os,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:C})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:S,className:"space-y-2",children:Object.entries(y).map(([f,N])=>{const j=d.find(R=>R.entityName===f)||{entityName:f,label:N.label};return e.jsxs(s.AccordionItem,{value:f,className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:e.jsxs("div",{title:j.label||j.entityName,className:"flex items-center gap-2",children:[e.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:j.label||j.entityName}),e.jsx(s.Badge,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:N.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:N.fields.map(R=>e.jsx(jn,{field:R,context:t},R.id))})})]},f)})}),Object.keys(y).length===0&&i.length===0&&e.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[e.jsx("p",{children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:t==="filter"?"The selected data source has no available fields":"Try selecting different data sources"})]}),Object.keys(y).length===0&&i.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 lt({context:t="editor"}={}){return e.jsxs("div",{className:"flex h-full grow flex-col items-center",children:[" ",e.jsx(vn,{context:t})," "]})}function bn({initialJoinPlan:t,availableDataSources:n}){const[a,r]=k.useState(t),[l,o]=k.useState(new Set),c=()=>{const D=a.joins.length>0?Math.max(...a.joins.map(N=>N.sequence))+1:1,f={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:D,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...a,joins:[...a.joins,f]}),o(new Set([...l,f.id]))},i=D=>{r({...a,joins:a.joins.filter(f=>f.id!==D)}),o(new Set([...l].filter(f=>f!==D)))},d=(D,f)=>{var T,F;const N=a.joins.find(w=>w.id===D);if(!N)return;const j={...N,...f},R=a.joins.map(w=>w.id===D?j:w);if((T=j.source)!=null&&T.name&&((F=j.target)!=null&&F.name)&&j.joinKeyGroups[0].keys.length===0){const w=n.find(L=>{var P;return L.name===((P=j.source)==null?void 0:P.name)}),I=n.find(L=>{var P;return L.name===((P=j.target)==null?void 0:P.name)}),M={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(w==null?void 0:w.name)||"",entityName:(w==null?void 0:w.name)||"",entityType:(w==null?void 0:w.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(I==null?void 0:I.name)||"",entityName:(I==null?void 0:I.name)||"",entityType:(I==null?void 0:I.type)||"table"},operator:"="},O=[...j.joinKeyGroups];O[0]={...O[0],keys:[M]},j.joinKeyGroups=O,R[R.findIndex(L=>L.id===D)]=j}r({...a,joins:R})};return{joinPlan:a,expandedJoins:l,setJoinPlan:r,addJoin:c,removeJoin:i,updateJoin:d,moveJoinUp:D=>{const f=a.joins.findIndex(N=>N.id===D);if(f>0){const N=[...a.joins],j={...N[f]},R={...N[f-1]};N[f]=R,N[f-1]=j,N.forEach((F,w)=>{F.sequence=w+1});const T={...a,joins:N};r(T)}},moveJoinDown:D=>{const f=a.joins.findIndex(N=>N.id===D);if(f<a.joins.length-1){const N=[...a.joins],j={...N[f]},R={...N[f+1]};N[f]=R,N[f+1]=j,N.forEach((F,w)=>{F.sequence=w+1});const T={...a,joins:N};r(T)}},toggleJoinExpansion:D=>{const f=new Set(l);f.has(D)?f.delete(D):f.add(D),o(f)},getAvailableSourceEntities:D=>{if(a.joins.length===0)return n;const f=a.joins.findIndex(j=>j.id===D);if(f===0)return n;const N=new Set;return a.baseEntity.name&&N.add(a.baseEntity.name),a.joins.slice(0,f).forEach(j=>{N.add(j.source.name),N.add(j.target.name)}),n.filter(j=>N.has(j.name))},getAvailableTargetEntities:D=>n.filter(f=>f.name!==D),addJoinKeyGroup:D=>{const f=a.joins.find(j=>j.id===D);if(!f)return;const N=[...f.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];d(D,{joinKeyGroups:N})},updateGroupOperator:(D,f,N)=>{const j=a.joins.find(T=>T.id===D);if(!j)return;const R=[...j.joinKeyGroups];R[f]={...R[f],operator:N},d(D,{joinKeyGroups:R})},removeJoinKeyGroup:(D,f)=>{const N=a.joins.find(R=>R.id===D);if(!N)return;const j=[...N.joinKeyGroups];j.splice(f,1),d(D,{joinKeyGroups:j})},addJoinKey:(D,f)=>{const N=a.joins.find(w=>w.id===D);if(!N)return;const j=n.find(w=>w.name===N.source.name),R=n.find(w=>w.name===N.target.name),T=[...N.joinKeyGroups],F={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(j==null?void 0:j.name)||"",entityName:(j==null?void 0:j.name)||"",entityType:(j==null?void 0:j.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(R==null?void 0:R.name)||"",entityName:(R==null?void 0:R.name)||"",entityType:(R==null?void 0:R.type)||"table"},operator:"="};T[f]={...T[f],keys:[...T[f].keys,F]},d(D,{joinKeyGroups:T})},updateJoinKey:(D,f,N,j,R)=>{const T=a.joins.find(O=>O.id===D);if(!T)return;const F=n.find(O=>O.name===T.source.name),w=n.find(O=>O.name===T.target.name),I=[...T.joinKeyGroups],M=I[f].keys[N];j==="sourceColumnName"&&F?I[f].keys[N]={...M,source:{...M.source,name:R}}:j==="targetColumnName"&&w?I[f].keys[N]={...M,target:{...M.target,name:R}}:j==="operator"&&(I[f].keys[N]={...M,operator:R}),d(D,{joinKeyGroups:I})},removeJoinKey:(D,f,N)=>{const j=a.joins.find(T=>T.id===D);if(!j)return;const R=[...j.joinKeyGroups];R[f].keys.splice(N,1),d(D,{joinKeyGroups:R})},generateSQLPreview:()=>{const D=[...a.joins].sort((j,R)=>j.sequence-R.sequence),f=a.baseEntity;if(!f.name)return"SELECT * FROM table -- Please select a base entity";let N=`SELECT *
|
|
247
|
-
FROM ${f.name}`;return D.forEach(j=>{const R=n.find(w=>w.name===j.target.name);if(!R)return;const T=j.joinKeyGroups.filter(w=>w.keys&&w.keys.length>0).map(w=>{const I=w.keys.filter(M=>{var O,L,P,B;return((O=M.source)==null?void 0:O.name)&&((L=M.target)==null?void 0:L.name)&&((P=M.source)==null?void 0:P.entityName)&&((B=M.target)==null?void 0:B.entityName)}).map(M=>`${M.source.entityName}.${M.source.name} ${M.operator} ${M.target.entityName}.${M.target.name}`);return I.length>1?`(${I.join(` ${w.operator} `)})`:I[0]}).filter(Boolean),F=T.length>1?T.join(" OR "):T[0]||"condition_here";N+=`
|
|
248
|
-
${j.joinType} JOIN ${R.name}
|
|
249
|
-
ON ${F}`}),N},isValidConfiguration:()=>!(!a.baseEntity.name||a.joins.some(j=>!j.source.name||!j.target.name)||a.joins.some(j=>j.joinKeyGroups.some(R=>R.keys.length===0))||a.joins.some(j=>j.joinKeyGroups.some(R=>R.keys.some(T=>!T.source.name||!T.target.name||!T.operator))))}}function yn({joinPlan:t,availableDataSources:n,onSave:a,onRemove:r,onCancel:l}){const{setCardConfig:o}=s.useEditorActions();s.useEditorStore(T=>T.card.config);const{columnGroups:c}=s.useColumns(),{joinPlan:i,expandedJoins:d,setJoinPlan:u,addJoin:m,removeJoin:h,updateJoin:x,moveJoinUp:g,moveJoinDown:v,toggleJoinExpansion:p,getAvailableSourceEntities:y,getAvailableTargetEntities:b,addJoinKeyGroup:S,updateGroupOperator:A,removeJoinKeyGroup:E,addJoinKey:C,updateJoinKey:D,removeJoinKey:f,generateSQLPreview:N,isValidConfiguration:j}=bn({initialJoinPlan:t,availableDataSources:n}),R=T=>{const F=c.find(w=>w.entityName===T);return(F==null?void 0:F.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:i.baseEntity.name,onValueChange:T=>{const F=n.find(w=>w.name===T);u({...i,baseEntity:{connectionId:(F==null?void 0:F.connectionId)||"",connectionType:(F==null?void 0:F.connectionType)||"none",type:(F==null?void 0:F.type)||"table",name:T,database:F==null?void 0:F.database,schema:F==null?void 0:F.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:n.map(T=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:T.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:T.type}),T.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},T.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:N()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{children:["Joins Configuration (",i.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:m,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),i.joins.length===0?e.jsx("div",{className:"rounded-lg border border-dashed py-8 text-center text-muted-foreground",children:e.jsx("p",{children:"No joins configured. Add a join to connect multiple data sources."})}):e.jsx("div",{className:"max-h-[300px] space-y-4 overflow-y-auto",children:i.joins.map(T=>{const F=n.find(M=>M.name===T.source.name),w=n.find(M=>M.name===T.target.name),I=d.has(T.id);return e.jsxs(s.Card,{className:"border",children:[e.jsx(s.CardHeader,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{children:T.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",T.sequence,F&&w&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",F.name," → ",w.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g(T.id),disabled:T.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>v(T.id),disabled:T.sequence===i.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>p(T.id),children:I?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>h(T.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),I&&e.jsxs(s.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Source"}),e.jsxs(s.Select,{value:T.source.name,onValueChange:M=>{const O=n.find(L=>L.name===M);x(T.id,{source:{connectionId:(O==null?void 0:O.connectionId)||"",connectionType:(O==null?void 0:O.connectionType)||"none",type:(O==null?void 0:O.type)||"table",name:M,database:O==null?void 0:O.database,schema:O==null?void 0:O.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:y(T.id).map(M=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:M.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:M.type}),M.name]})},M.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:T.joinType,onValueChange:M=>x(T.id,{joinType:M}),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Target"}),e.jsxs(s.Select,{value:T.target.name,onValueChange:M=>{const O=n.find(L=>L.name===M);x(T.id,{target:{connectionId:(O==null?void 0:O.connectionId)||"",connectionType:(O==null?void 0:O.connectionType)||"none",type:(O==null?void 0:O.type)||"table",name:M,database:O==null?void 0:O.database,schema:O==null?void 0:O.schema}})},disabled:!T.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:T.source.name?b(T.source.name).map(M=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:M.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:M.type}),M.name,M.name===T.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},M.name)):[]})]})]})]}),T.source.name&&T.target.name&&F&&w&&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:()=>S(T.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),T.joinKeyGroups.length===0?e.jsx("div",{className:"rounded-md border p-3 text-center text-sm text-gray-500",children:"No join conditions defined. Add condition groups to specify how data sources should be joined."}):e.jsx("div",{className:"space-y-4",children:T.joinKeyGroups.map((M,O)=>e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{children:["Group ",O+1]}),O>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(s.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Select,{value:M.operator,onValueChange:L=>A(T.id,O,L),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:()=>E(T.id,O),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[M.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:M.keys.map((L,P)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[P>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:M.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:L.source.name,onValueChange:B=>D(T.id,O,P,"sourceColumnName",B),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:R(T.source.name).map(B=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:B.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:B.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:B.dataType})]})},B.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:L.operator,onValueChange:B=>D(T.id,O,P,"operator",B),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:L.target.name,onValueChange:B=>D(T.id,O,P,"targetColumnName",B),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:R(T.target.name).map(B=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:B.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:B.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:B.dataType})]})},B.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>f(T.id,O,P),children:e.jsx(s.X,{className:"size-3.5"})})]},L.id||P))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>C(T.id,O),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},M.id))})]})]})]},T.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),l()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:l,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>a(i),disabled:!j(),children:"Save"})]})]})}function ws({children:t,open:n,onOpenChange:a,joinPlan:r,availableDataSources:l,onRemove:o,onSave:c,onCancel:i}){return e.jsxs(s.Dialog,{open:n,onOpenChange:a,children:[e.jsxs(s.DialogContent,{className:"max-w-4xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Join Configuration"}),e.jsx(s.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(yn,{joinPlan:r,availableDataSources:l,onSave:c,onCancel:i,onRemove:o})]}),t]})}function Nn({joins:t,baseEntityId:n,availableDataSources:a,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[t.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const l=[...t].sort((c,i)=>c.sequence-i.sequence),o=a.find(c=>c.name===n);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:o==null?void 0:o.type}),e.jsx("span",{className:"text-xs font-medium",children:o==null?void 0:o.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),l.map(c=>{const i=a.find(d=>d.name===c.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name})]})]},c.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",t.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...t].sort((l,o)=>l.sequence-o.sequence).map((l,o)=>{const c=a.find(d=>d.name===l.source.name),i=a.find(d=>d.name===l.target.name);return e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted p-2 text-left",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:o+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:l.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[c==null?void 0:c.name," → ",i==null?void 0:i.name]}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto text-xs",children:[l.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)," ","condition",l.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)>1?"s":""]})]},l.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function Cn(){var m,h;const t=s.useEditorStore(x=>x.card),n=s.useEditorStore(x=>x.actions.updateCardConfig),a=((m=t==null?void 0:t.config)==null?void 0:m.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[r,l]=k.useState(!1),o=((h=t==null?void 0:t.dataSource)==null?void 0:h.selectedEntities)||[],c=x=>{n(t.id,{...t==null?void 0:t.config,joinPlan:x}),l(!1)},i=()=>{n(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},d=()=>{l(!1)},u=()=>{const x=[...a.joins].sort((p,y)=>p.sequence-y.sequence),g=a.baseEntity;if(!g.name)return"SELECT * FROM table -- Please select a base entity";let v=`SELECT *
|
|
250
|
-
FROM ${g.name}`;return x.forEach(p=>{const y=o.find(A=>A.name===p.target.name);if(!y)return;const b=p.joinKeyGroups.filter(A=>A.keys&&A.keys.length>0).map(A=>{const E=A.keys.filter(C=>{var D,f,N,j;return((D=C.source)==null?void 0:D.name)&&((f=C.target)==null?void 0:f.name)&&((N=C.source)==null?void 0:N.entityName)&&((j=C.target)==null?void 0:j.entityName)}).map(C=>`${C.source.entityName}.${C.source.name} ${C.operator} ${C.target.entityName}.${C.target.name}`);return E.length>1?`(${E.join(` ${A.operator} `)})`:E[0]}).filter(Boolean),S=b.length>1?b.join(" OR "):b[0]||"condition_here";v+=`
|
|
251
|
-
${p.joinType} JOIN ${y.name}
|
|
252
|
-
ON ${S}`}),v};return o.length<2?null:e.jsx(e.Fragment,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[a.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-6 text-xs font-semibold",onClick:()=>l(!0),children:[e.jsx(s.Link,{className:s.cn("mr-1 h-3 w-3",{"text-blue-500":a.joins.length>0,"text-gray-500":a.joins.length===0})}),"Join",a.joins.length>1?"s":""," (",a.joins.length,")"]})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(Nn,{joins:a.joins,baseEntityId:a.baseEntity.name,availableDataSources:o,generateSQLPreview:u})})]})}),e.jsx(ws,{open:r,onOpenChange:l,joinPlan:a,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsx("div",{})})]}),a.joins.length===0&&e.jsx(ws,{open:r,onOpenChange:l,joinPlan:a,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsxs(s.Button,{onClick:()=>l(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function Sn({open:t,onOpenChange:n}){const[a,r]=k.useState([]),{updateDataSource:l}=s.useEditorActions(),o=s.useDashboardStore(p=>p.dashboard.aiContext),c=(o==null?void 0:o.selectedEntities)||[];k.useEffect(()=>{t&&r([])},[t]);const i=p=>{r(y=>y.some(S=>S.name===p.name&&S.type===p.type)?y.filter(S=>!(S.name===p.name&&S.type===p.type)):[...y,p])},d=()=>{r([...c])},u=()=>{r([])},m=()=>{if(a.length===0)return;const p=a[0],y=p.connectionId||"",b=p.connectionType||"",A=a.some(C=>C.type==="dataset")?"semanticDomain":"database";l({connectionId:y,connectionType:b,mode:A,selectedEntities:a}),n(!1)},h=p=>{switch(p.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(_t,{className:"h-4 w-4"});case"dataset":return e.jsx(s.Database,{className:"h-4 w-4"});case"file":case"url":case"upload":return e.jsx(s.FileText,{className:"h-4 w-4"});default:return e.jsx(s.Database,{className:"h-4 w-4"})}},x=p=>"label"in p&&p.label?p.label:p.name,g=p=>{if("description"in p&&p.description)return p.description;const y=[];return p.database&&y.push(p.database),p.schema&&y.push(p.schema),p.name&&y.push(p.name),y.join(".")},v=p=>a.some(y=>y.name===p.name&&y.type===p.type);return c.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-md",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"No Data Available"}),e.jsx(s.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{onClick:()=>n(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(s.DialogDescription,{children:"Choose entities from the dashboard's context"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"outline",size:"sm",onClick:d,disabled:a.length===c.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:u,disabled:a.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[a.length," of ",c.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:c.map((p,y)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",v(p)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:v(p),onCheckedChange:()=>i(p)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:h(p)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:x(p)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:g(p)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:p.type})]},`${p.type}-${p.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:()=>n(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:m,disabled:a.length===0,children:["Select"," ",a.length>0?`(${a.length})`:""]})]})})})]})})}function wn({entity:t,title:n,maxDetails:a=10}){const l=s.getEntityDetails(t).slice(0,a),o=l.find(i=>i.label==="Description"),c=l.filter(i=>i.label==="Description"?!1:!["Connection","Database","Schema"].includes(i.label));return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:n||s.getDisplayName(t)}),o&&e.jsxs("div",{className:"border-t border-border pt-2",children:[e.jsx("div",{className:"mb-1 text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:o.value})]}),c.length>0&&e.jsx("div",{className:"space-y-0.5",children:c.map((i,d)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[i.label,":"]}),e.jsx("span",{className:"font-mono",children:i.value})]},d))})]})})}function Dn({entities:t}){return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:[t.length," more entities"]}),e.jsx("div",{className:"space-y-1",children:t.map((n,a)=>{const r=s.getEntityDetails(n),l=r.find(c=>c.label==="Description"),o=r.filter(c=>c.label==="Description"?!1:!["Connection","Database","Schema"].includes(c.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(n)}),l&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:l.value})]}),o.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:o.map((c,i)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[c.label,":"]}),e.jsx("span",{className:"font-mono",children:c.value})]},i))})]},`remaining-${n.type}-${n.name}-${a}`)})})]})})}function ot(){const t=s.useEditorStore(c=>c.card.dataSource),{setSelectedConnectionId:n,setSelectedDatabaseName:a,setSelectedSchemaName:r,setSelectedTableName:l,setSelectedDatamodelId:o}=s.useEditorActions();k.useEffect(()=>{var g;if(!t)return;const{tableName:c,schemaName:i,databaseName:d,connectionId:u}=is(t),m=(g=t.selectedEntities)==null?void 0:g[0],x=(m==null?void 0:m.type)==="model"&&"id"in m?m.id:"";n(u||""),a(d||""),r(i||""),l(c||""),o(x)},[t,n,a,r,l,o])}function it({isVisible:t}){const n=s.useEditorStore(x=>x.isDevMode);ot();const[a,r]=k.useState(!1),[l,o]=k.useState(!1),[c,i]=k.useState(!0),d=s.useEditorStore(x=>x.card.dataSource);s.useCurrentUserInfo();const{updateDataSource:u}=s.useEditorActions(),m={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},h={...m,...d,selectedEntities:(d==null?void 0:d.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[e.jsxs("div",{children:[e.jsx("div",{className:"p-4 px-6 pb-2",children:e.jsxs(s.Button,{className:"w-full bg-muted/50",variant:"outline",onClick:()=>r(!0),children:[e.jsx(s.Database,{className:"mr-2 h-3.5 w-3.5"}),"Choose Dataset"]})}),e.jsxs("div",{className:"relative px-6",children:[e.jsx("div",{className:"absolute inset-0 flex items-center px-6",children:e.jsx("div",{className:"w-full border-t border-border"})}),e.jsx("div",{className:"relative flex justify-center",children:e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>i(!c),className:"size-6 bg-background p-1 py-1 hover:bg-accent",children:c?e.jsx(s.ChevronUp,{className:"h-3.5 w-3.5"}):e.jsx(s.ChevronDown,{className:"h-3.5 w-3.5"})})})]}),e.jsxs("div",{className:`overflow-hidden px-6 ${c?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[h.selectedEntities.length>0&&e.jsx(s.TooltipProvider,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[h.selectedEntities.slice(0,3).map((x,g)=>e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[s.getDisplayName(x),e.jsx("button",{onClick:v=>{v.stopPropagation();const p=h.selectedEntities.filter(y=>!(y.name===x.name&&y.type===x.type));u({...m,...d,selectedEntities:p})},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(wn,{entity:x})]},`${x.type}-${x.name}-${g}`)),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(Dn,{entities:h.selectedEntities.slice(3)})]})]})}),!n&&e.jsx(Cn,{})]})]}),e.jsx(lt,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(d==null?void 0:d.selectedEntities)||[],dialogMode:"dataSource",open:a,onOpenChange:r,dataSource:h}),e.jsx(Sn,{open:l,onOpenChange:o})]})}function ct({error:t,errorSql:n,onSendFeedback:a,className:r,showFeedbackButton:l=!0}){const[o,c]=k.useState(!1);return e.jsx("div",{className:s.cn("rounded-lg border border-destructive/30 bg-destructive/5 p-4",r),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(s.CircleAlert,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-destructive"}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-destructive",children:"Query Error"}),e.jsxs("div",{className:"relative rounded-md bg-background/60 p-3",children:[e.jsx(s.CopyButton,{text:t,className:"absolute right-2 top-2 h-6 w-6 z-10"}),e.jsx("div",{className:"max-h-40 overflow-auto pr-10",children:e.jsx("p",{className:"font-mono text-xs text-foreground/80 break-all",children:t})})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n&&e.jsx(s.Collapsible,{open:o,onOpenChange:c,children:e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",children:o?e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronUp,{className:"mr-1.5 h-3.5 w-3.5"}),"Hide Details"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronDown,{className:"mr-1.5 h-3.5 w-3.5"}),"Show Details"]})})})}),l&&a&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:a,children:[e.jsx(s.MessageSquareWarning,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]})]}),n&&e.jsx(s.Collapsible,{open:o,onOpenChange:c,children:e.jsx(s.CollapsibleContent,{className:"space-y-2",children:e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Error SQL Query"}),e.jsx(s.CopyButton,{text:n,className:"h-6 w-6"})]}),e.jsx("div",{className:"rounded-md bg-background/60 p-2 max-h-80 overflow-auto",children:e.jsx(s.CodeHighlighter,{code:n,language:"sql"})})]})})})]})]})})}function dt({sql:t,error:n,errorSql:a,onDebugWithAssistant:r}){const l=s.useEditorStore(u=>u.isDevMode),{setIsDevMode:o,setCardSql:c,setRunSql:i}=s.useEditorActions();function d(){o(!l),c(t),setTimeout(()=>{i(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-3",children:[e.jsxs(s.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[n&&e.jsx(ct,{error:n,errorSql:a,showFeedbackButton:!1}),!n&&t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"",children:e.jsx(s.CodeHighlighter,{code:t,language:"sql"})})})]}),!l&&t&&!n&&e.jsxs(s.Button,{onClick:d,variant:"secondary",size:"sm",children:[e.jsx($t,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),n&&r&&e.jsxs(s.Button,{onClick:r,size:"sm",variant:"outline",children:[e.jsx(Qt,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function Tn({sql:t,error:n,errorSql:a,onDebugWithAssistant:r}){return e.jsxs(s.HoverCard,{openDelay:n?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:n?e.jsx(zt,{className:"h-4 w-4 text-red-500"}):e.jsx(s.Info,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(s.HoverCardContent,{align:"start",className:"flex w-[700px]",children:e.jsx(dt,{errorSql:a,sql:t,error:n,onDebugWithAssistant:r})})]})}function kn(t){return s.GenIcon({attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M439.8 200.5c-7.7-30.9-22.3-54.2-53.4-54.2h-40.1v47.4c0 36.8-31.2 67.8-66.8 67.8H172.7c-29.2 0-53.4 25-53.4 54.3v101.8c0 29 25.2 46 53.4 54.3 33.8 9.9 66.3 11.7 106.8 0 26.9-7.8 53.4-23.5 53.4-54.3v-40.7H226.2v-13.6h160.2c31.1 0 42.6-21.7 53.4-54.2 11.2-33.5 10.7-65.7 0-108.6zM286.2 404c11.1 0 20.1 9.1 20.1 20.3 0 11.3-9 20.4-20.1 20.4-11 0-20.1-9.2-20.1-20.4.1-11.3 9.1-20.3 20.1-20.3zM167.8 248.1h106.8c29.7 0 53.4-24.5 53.4-54.3V91.9c0-29-24.4-50.7-53.4-55.6-35.8-5.9-74.7-5.6-106.8.1-45.2 8-53.4 24.7-53.4 55.6v40.7h106.9v13.6h-147c-31.1 0-58.3 18.7-66.8 54.2-9.8 40.7-10.2 66.1 0 108.6 7.6 31.6 25.7 54.2 56.8 54.2H101v-48.8c0-35.3 30.5-66.4 66.8-66.4zm-6.7-142.6c-11.1 0-20.1-9.1-20.1-20.3.1-11.3 9-20.4 20.1-20.4 11 0 20.1 9.2 20.1 20.4s-9 20.3-20.1 20.3z"},child:[]}]})(t)}function ut(t){const{theme:n}=s.useTheme(),a=s.useDashboardStore(p=>p.theme),r=s.useEditorStore(p=>p.frame),l=s.useEditorStore(p=>p.card),o=s.useEditorStore(p=>p.activeTabCardId),c=s.Le(),{refetch:i}=s.useDashboardCardQuery(l),{updateCardTab:d,setRunSql:u}=s.useEditorActions(),m=k.useRef(),h=k.useRef({}),x=r.cards.find(p=>p.id===o),g=k.useCallback(()=>{let p="";return t==="python"&&(p=(x==null?void 0:x.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(p=(x==null?void 0:x.sql)||""),p},[t,x]);k.useEffect(()=>{if(o&&l.id&&l.id!==o){if(m.current&&c){const p=m.current.getModel();p&&(h.current[l.id]=p);let y=h.current[o];if(!y){const b=g();y=c.editor.createModel(b,t),h.current[o]=y}m.current.setModel(y)}d(o,l),u(!0)}},[o,l,d,c,u,t,g]),k.useEffect(()=>{if(!c)return;const p=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",y=a==="system"?p:a;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")},[n,a,c]),k.useEffect(()=>{const p=m.current;p&&c&&l&&p.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return i(),!1})},[c,i,l]);function v(p,y){if(m.current=p,!h.current[l.id]){const b=p.getModel(),S=g();h.current[l.id]=b||(y==null?void 0:y.editor.createModel(S,t))||p.getModel()}p.setModel(h.current[l.id])}return{handleEditorDidMount:v}}function En(){const t=s.useEditorStore(c=>c.card.sql),n=s.useEditorStore(c=>c.sqlGen),{setCardSql:a,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=ut("sql");function o(c){a(c),s.isObjectEmpty(n)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:o,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function In(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:n}=s.useEditorActions(),{handleEditorDidMount:a}=ut("python");function r(l){n(l)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:a})}function An({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 Mn(){const t=s.useQueryClient(),{isConsoleMode:n}=s.useDashboardPreferences(),[a,r]=k.useState(!1),[l,o]=k.useState(!1);s.useEditorStore(z=>z.frame);const c=s.useEditorStore(z=>z.card);s.useEditorStore(z=>z.isShowingVisual),s.useEditorStore(z=>z.selectedConnectionId),s.useEditorStore(z=>z.tempQueryData),s.useEditorStore(z=>z.selectedDatabaseName),s.useEditorStore(z=>z.selectedDatamodelId),s.useEditorStore(z=>z.selectedSchemaName);const i=s.useEditorStore(z=>z.showAIDialog);s.useEditorStore(z=>z.selectedTableName);const d=s.useEditorStore(z=>{var Q;return(Q=z==null?void 0:z.card)==null?void 0:Q.sql}),u=s.useEditorStore(z=>{var Q;return(Q=z==null?void 0:z.card)==null?void 0:Q.python}),{cardFilterValues:m}=s.useCardFilterValues((c==null?void 0:c.id)??""),{setCardCustomCfg:h,setQueryResultColumns:x,setCardSql:g,setTempQueryData:v,setPythonStdOut:p,setCardPreferences:y,setCardType:b,setCardPython:S,runAssistant:A,setShowAIDialog:E}=s.useEditorActions();s.useEditorStore(z=>z.onSave),s.useEditorStore(z=>z.onClose),s.useEditorStore(z=>z.actions.setSqlGen);const C=s.useEditorStore(z=>z.runSql),D=s.useEditorStore(z=>z.actions.setRunSql),f=s.useEditorStore(z=>z.actions.setIsSqlRunning),{data:N,isLoading:j,isFetching:R,isSuccess:T,isError:F,error:w,errorSql:I,queryKey:M,refetch:O,errorMessage:L}=s.useDashboardCardQuery(c);k.useEffect(()=>{if(N&&(N.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),p((N==null?void 0:N.output)||""),N.records.length>0)){const{dimensionKeys:z}=s.getKeys(N.records);x(z)}},[N,x,p]),k.useEffect(()=>{(j||R)&&f(!0),(F||T)&&f(!1),F&&(x([]),p(""))},[j,R,N,p,F,T,f,x,w]),k.useEffect(()=>{C&&(t.getQueryData(M)||O(),D(!1))},[C,O,D,M,t]);async function P(){const z=`Can you help me debug this query?
|
|
253
|
-
|
|
254
|
-
Error:
|
|
255
|
-
|
|
256
|
-
${L}
|
|
257
|
-
|
|
258
|
-
Error SQL:
|
|
259
|
-
|
|
260
|
-
${I}
|
|
261
|
-
|
|
262
|
-
Query:
|
|
263
|
-
|
|
264
|
-
${d}
|
|
265
|
-
|
|
266
|
-
${u?`Python:
|
|
267
|
-
${u}`:""}
|
|
268
|
-
`;A(z)}function B(){return e.jsxs(e.Fragment,{children:[l&&e.jsx("div",{className:"relative flex w-1/3 min-w-0 grow overflow-hidden text-xs",role:"editor-filter-container",children:e.jsx("div",{className:"mt-2 w-[99%]",children:e.jsx(An,{jsonString:JSON.stringify(m,null,2)})})}),m&&m.length>0&&e.jsx(s.Button,{variant:"ghost",onClick:()=>o(!l),className:"absolute bottom-0 right-6 size-7 p-1",children:l?e.jsx(s.X,{className:"size-3.5 text-muted-foreground"}):e.jsx(s.Filter,{className:"size-3.5 text-muted-foreground"})})]})}function H(){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(En,{})}),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(In,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function q(){return e.jsx("div",{role:"editor-controls",className:"item-center flex flex-wrap justify-between gap-2 px-6 py-4",children:e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsxs(s.Button,{title:"Shift + Enter",disabled:j||R,onClick:()=>{O()},className:"h-8 shrink-0",size:"sm",children:[j||R?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(Tn,{errorSql:I,sql:N==null?void 0:N.sql,error:L,onDebugWithAssistant:P}),e.jsx(ls,{}),e.jsx(s.Toggle,{pressed:a,onPressedChange:z=>r(z),className:"h-8",size:"sm",variant:"outline",children:e.jsx(kn,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:i,onClick:()=>{E(!0)},className:"h-9 w-full cursor-text px-3 text-left text-sm text-muted-foreground",children:i?"":"Type your question..."})]})})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsxs("div",{className:"relative flex grow justify-between overflow-y-scroll",children:[H(),B()]}),q()]})}const Rn=[{value:"table",label:"Table",icon:s.Table2},{value:"aggregateTable",label:"Aggregate",icon:s.Layers},{value:"pivotTable",label:"Pivot",icon:We}];function Ln({className:t}){const n=s.useEditorStore(d=>d.card),{setCardType:a,setCard:r,updateCardInFrame:l}=s.useEditorActions(),o=["table","aggregateTable","pivotTable"].includes(n.type),c=s.hasValidCardConfig(n.config);if(!o||!c)return null;const i=d=>{var m;const u=d;if(u==="aggregateTable"&&((m=n.config)!=null&&m.pivotByColumns)&&n.config.pivotByColumns.length>0){const h={...n,type:u,config:{...n.config,pivotByColumns:[]}};r(h),l(h)}else{a(u);const h={...n,type:u};l(h)}};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsx(s.RadioGroup,{value:n.type,onValueChange:i,className:"flex flex-row items-center justify-between gap-1 rounded-lg border p-1",children:Rn.map(d=>{const u=d.icon,m=n.type===d.value;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(s.RadioGroupItem,{value:d.value,id:`table-type-${d.value}`,className:"peer sr-only"}),e.jsxs(s.Label,{htmlFor:`table-type-${d.value}`,className:s.cn("flex cursor-pointer items-center gap-1.5 rounded-md px-3 py-1 text-sm font-medium transition-all",m?"bg-muted text-foreground shadow-sm":"text-muted-foreground hover:bg-muted/50"),children:[e.jsx(u,{className:"h-3.5 w-3.5"}),d.label]})]},d.value)})})})}function Fn({card:t}){var A,E,C,D,f,N,j,R,T,F,w;const[n,a]=k.useState(!1),[r,l]=k.useState([]),{authToken:o}=s.useSemaphorContext(),{theme:c}=s.useTheme(),i=s.getTokenParams(o==null?void 0:o.accessToken),d=s.useDashboardStore(I=>I.themeStyle),u={mode:c||"system",colors:((E=(A=d==null?void 0:d.chart)==null?void 0:A.dataset)==null?void 0:E.backgroundColor)||[]};(C=t.customCardPreferences)!=null&&C.inputData;const{getCard:m}=s.useCustomVisual(((D=t.customCardPreferences)==null?void 0:D.url)||""),h=((f=t.customCardPreferences)==null?void 0:f.visualType)||"single",x=s.useEditorStore(I=>I.frame),{setCustomCardPreferences:g}=s.useEditorActions(),{data:v}=s.useDashboardCardQuery(t),p=k.useCallback((I,M)=>{l(O=>({...O,[I]:M}))},[]);if(!((N=t.customCardPreferences)!=null&&N.componentName))return null;const y=m((j=t.customCardPreferences)==null?void 0:j.componentName);function b(I){a(I)}const S=Object.keys(((R=t.customCardPreferences)==null?void 0:R.dataInputCardIds)||{}).map(I=>{var L,P,B;const M=(P=(L=t.customCardPreferences)==null?void 0:L.dataInputCardIds)==null?void 0:P[I].cardId,O=(B=x==null?void 0:x.cards)==null?void 0:B.find(H=>H.id===M);return O||null});return e.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:e.jsxs(k.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[y&&h==="single"&&e.jsx(y,{editing:!0,params:i,theme:u,settings:(T=t.customCardPreferences)==null?void 0:T.settings,onDataChange:p,data:(v==null?void 0:v.records)||[]}),y&&h==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((F=t.customCardPreferences)==null?void 0:F.dataInputCardIds)||{}).map(I=>{var L,P,B;const M=(P=(L=t.customCardPreferences)==null?void 0:L.dataInputCardIds)==null?void 0:P[I].cardId,O=(B=x==null?void 0:x.cards)==null?void 0:B.find(H=>H.id===M);if(O)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:b,onDataChange:p,dataInputIndex:I,card:O},O.id+I)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(y,{theme:u,onDataChange:p,settings:S.map(I=>{var M;return(M=I==null?void 0:I.customCardPreferences)==null?void 0:M.settings}),data:S.map(I=>I!=null&&I.id?r==null?void 0:r[I.id]:[])})})]})]},(w=t.customCardPreferences)==null?void 0:w.componentName)})}function mt({className:t,...n}){var N;const a=s.useEditorStore(j=>j.card),r=s.isExplorerCard(a),l=((N=a.customCardPreferences)==null?void 0:N.showCardHeader)??!0,o=s.useEditorStore(j=>j.frame),c=s.useDashboardStore(j=>j.dashboard.filters),i=s.useEditorStore(j=>j.actions.setRunSql),{updateFilter:d}=s.useDashboardActions(),u=c==null?void 0:c.find(j=>j.id===o.filterId),{data:m,isLoading:h,isFetching:x,errorMessage:g,pagination:v}=s.useDashboardCardQuery(a),{setCard:p,updateCardInFrame:y}=s.useEditorActions(),{data:b}=s.useTopoJson(a),S=k.useMemo(()=>{var j;return a.type!=="pivotTable"||!((j=m==null?void 0:m.records)!=null&&j.length)?null:{records:m.records,columnSubtotalMeta:m.columnSubtotalMeta,subtotalColumns:m.subtotalColumns||[],pivotSchema:m.pivotSchema||[],groupByColumns:m.groupByColumns}},[a.type,m==null?void 0:m.records,m==null?void 0:m.columnSubtotalMeta,m==null?void 0:m.subtotalColumns,m==null?void 0:m.pivotSchema,m==null?void 0:m.groupByColumns]),A=s.usePivotTableConfig(a,S),E=(j,R)=>{var F,w;const T={...a,paginationConfig:{page:j+1,pageSize:R}};p(T),y(T),a.sql&&((w=(F=a.preferences)==null?void 0:F.tablePrefs)!=null&&w.enableDevModePagination)&&i(!0)},C=k.useMemo(()=>!a.id||!(m!=null&&m.records)?null:s.createChartConfig({card:a,data:m==null?void 0:m.records,cardType:a.type,queryConfig:a.queryConfig,customCfg:a.customCfg,preferences:a.preferences,topoJson:b}),[a.id,m==null?void 0:m.records,a.type,a.queryConfig,a.customCfg,a.preferences,b]);function D(j){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Fn,{card:j})})}function f(){if(m!=null&&m.records&&(m==null?void 0:m.records.length)===0&&!h&&!x)return g?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.SearchX,{className:"size-8 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r?"Error fetching data. Please check your chart configuration":"Error fetching data. Please check your SQL or Python code."})]}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((h||x)&&a.type!=="table")return e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!a.id)return null;if(a.type==="custom")return D(a);if(!["table","pivotTable","aggregateTable","custom"].includes(a.type)&&C)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:h||x?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:C})});if(a.type==="table")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:a,data:(m==null?void 0:m.records)||[],paginationMetadata:v,onPaginationChange:E,isLoading:h||x})});if(a.type==="pivotTable"&&A)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.PivotTableTanstack,{card:a,data:A.data,options:A.options,onAggregationChange:j=>{const R=s.handleAggregationChange(j,a.config),T={...a,config:R};p(T),y(T)},onAggregationLabelChange:j=>{const R=s.handleAggregationLabelChange(j,a.config),T={...a,config:R};p(T),y(T)}})});if(a.type==="aggregateTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.AggregateTable,{card:a,data:(m==null?void 0:m.records)||[],groupByColumns:m==null?void 0:m.groupByColumns,pivotSchema:m==null?void 0:m.pivotSchema,paginationMetadata:v,onPaginationChange:E,onAggregationChange:j=>{const R=s.handleAggregationChange(j,a.config),T={...a,config:R};p(T),y(T)},isLoading:h||x})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...n,children:[l&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-5",children:[e.jsx(s.CardTitle,{className:"text-base",children:e.jsx(s.EditableText,{value:a.title,onSave:j=>p({...a,title:j}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(Ln,{})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:a.description||"",onSave:j=>p({...a,description:j}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),u&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:u.title||u.column,onSave:j=>d({...u,title:j}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:u})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:f()})]})}const Xe=({language:t,value:n,onChange:a,readonly:r})=>e.jsx(s.Ft,{className:"h-full w-full overflow-hidden text-xs",theme:"default",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,lineHeight:16,renderLineHighlight:"none",readOnly:r},defaultLanguage:t,value:n,onChange:a}),On=()=>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."})]})]}),Pn=({customCode:t,cardCustomCfgString:n,mergedConfig:a,onConfigChange:r,onCodeChange:l})=>e.jsxs(s.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(s.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(s.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(s.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(s.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(s.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Xe,{language:"json",value:a,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Xe,{readonly:!0,language:"json",value:n,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Xe,{language:"javascript",value:t,onChange:l})})]}),Bn=({error:t,hasCardCustomConfig:n,onReset:a,onApply:r,onClose:l})=>e.jsxs(s.DialogFooter,{className:"flex items-center",children:[e.jsx(s.Label,{className:"mr-2 text-red-500",children:t}),e.jsx(s.Button,{disabled:!n,onClick:a,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:l,variant:"outline",children:"Close"})]});function Vn(){const[t,n]=k.useState(!1),[a,r]=k.useState(""),[l,o]=k.useState(""),[c,i]=k.useState(""),[d,u]=k.useState(""),m=s.useEditorStore(C=>C.card),h=s.useEditorStore(C=>C.card.customCfg),x=h?JSON.stringify(h,null,2):"",{data:g}=s.useDashboardCardQuery(m),{data:v}=s.useTopoJson(m),{setCardCustomCfg:p,setCustomVisualCode:y}=s.useEditorActions(),b=C=>{var D,f;return JSON.stringify({...C,data:{...C.data,datasets:(f=(D=C.data)==null?void 0:D.datasets)==null?void 0:f.map(N=>({...N,data:[]}))}},null,2)},S=()=>{var D,f;if(!((D=g==null?void 0:g.records)!=null&&D.length))return;const C=s.createChartConfig({card:m,data:g.records,cardType:m.type,queryConfig:m.queryConfig,preferences:m.preferences,topoJson:v});if(C){r(b(C)),i(((f=m.preferences)==null?void 0:f.customVisualCode)||"");const N=s.merge(C,h);o(b(N))}},A=()=>{try{if(c&&y(c),l){const C=JSON.parse(l),D=s.getObjectDiff(JSON.parse(a),C);p(D),u("")}}catch{u("Invalid JSON configuration")}},E=Object.keys(h||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:n,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:S,className:E?"":"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(On,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(mt,{className:"w-1/2 rounded shadow-none"})}),e.jsx(Pn,{customCode:c,cardCustomCfgString:x,mergedConfig:l,onConfigChange:C=>o(C??""),onCodeChange:C=>i(C??"")})]}),e.jsx(Bn,{error:d,hasCardCustomConfig:!!h,onReset:()=>{o(a),p(null)},onApply:A,onClose:()=>n(!1)})]})]})}function Je(t){const[n,a]=k.useState(null);return n}function ht(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),{data:a,isLoading:r,isFetching:l,isError:o}=s.useQuery({queryKey:["plugins",t==null?void 0:t.accessToken],queryFn:()=>s.getPlugins(n.apiServiceUrl,t==null?void 0:t.accessToken)});return{data:a,isLoading:r,isFetching:l,isError:o}}function xt(){const{data:t,isLoading:n,isError:a}=ht(),r=s.useQueries({queries:((t==null?void 0:t.plugins)||[]).map(i=>({queryKey:["manifest",i.value],queryFn:()=>s.loadManifest(i.value),enabled:!!i.value,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:d=>Math.min(1e3*2**d,3e4)}))}),l=[];let o=n,c=a;return r.forEach((i,d)=>{var u;if(i.isLoading&&(o=!0),i.isError&&(c=!0),i.data&&((u=t==null?void 0:t.plugins)!=null&&u[d])){const m=t.plugins[d],h=i.data.visuals.map(x=>({name:x.name,pluginName:m.label,componentType:x.componentType,pluginType:m.type,icon:x.icon,chartType:x.chartType,url:m.value}));l.push(...h)}}),{data:l,isLoading:o,isError:c}}function zn({onChartTypeChange:t}){const{setCardCustomCfg:n,setCardPreferences:a,setCardType:r,setCustomCardPreferences:l}=s.useEditorActions(),{data:o,isLoading:c,isError:i}=xt(),d=k.useCallback((u,m)=>{n(null),a({}),r(u),m&&l({type:"component",visualType:"single",url:m.url,componentName:m.name,icon:m.icon}),t==null||t()},[n,a,r,l,t]);return c?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading custom visuals..."})})]}):i?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-destructive",children:"Failed to load custom visuals"})})]}):!o||o.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:o.map((u,m)=>e.jsx(Un,{text:u.name,onClick:()=>d("custom",u),icon:u.icon},`${u.url}-${u.name}-${m}`))})]})}const Un=({text:t,icon:n,onClick:a})=>{const r=Je(),l=t.charAt(0).toUpperCase();return e.jsx(s.IconButton,{onClick:a,tooltip:t,children:r?e.jsx(r,{className:"h-4 w-4"}):l})};function Gn({onChartTypeChange:t,iconClassName:n}){const{setCardType:a,setCardPreferences:r,setIsDevMode:l}=s.useEditorStore(m=>m.actions),{setCardCustomCfg:o,setCustomCardPreferences:c,setQueryConfig:i}=s.useEditorActions();function d(m,h){o(null),r({}),a(m),["custom","text","map"].includes(m)&&(l(!0),i(void 0)),t==null||t()}const u=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(s.IconButton,{openDelay:u,tooltip:"Table",onClick:()=>d("table"),className:"h-10 p-4",children:e.jsx(s.Table2,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bar Chart",onClick:()=>d("bar"),className:"h-10 p-4",children:e.jsx(s.ChartColumnIncreasing,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Line Chart",onClick:()=>d("line"),className:"h-10 p-4",children:e.jsx(s.ChartLine,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Bar Chart",onClick:()=>d("stackedBar"),className:"h-10 p-4",children:e.jsx(s.ChartColumnStacked,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Line Chart",onClick:()=>d("stackedLine"),className:"h-10 p-4",children:e.jsx(s.MdStackedLineChart,{className:s.cn("size-5",n),strokeWidth:0})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Scatter Chart",onClick:()=>d("scatter"),className:"h-10 p-4",children:e.jsx(s.ChartScatter,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bubble Chart",onClick:()=>d("bubble"),className:"h-10 p-4",children:e.jsx(s.TbChartBubble,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Pie Chart",onClick:()=>d("pie"),className:"h-10 p-4",children:e.jsx(s.ChartPie,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Doughnut Chart",onClick:()=>d("doughnut"),className:"h-10 p-4",children:e.jsx(s.Donut,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Funnel Chart",onClick:()=>d("funnel"),className:"h-10 p-4",children:e.jsx(s.TbChartFunnel,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Radar Chart",onClick:()=>d("radar"),className:"h-10 p-4",children:e.jsx(s.Radar,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Polar Area Chart",onClick:()=>d("polarArea"),className:"h-10 p-4",children:e.jsx(s.PiChartPolar,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Tornado Chart",onClick:()=>d("tornado"),className:"h-10 p-4",children:e.jsx(s.Tornado,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{tooltip:"Range Chart",onClick:()=>d("range"),className:"h-10 p-4",children:e.jsx(s.ChartNoAxesGantt,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"KPI",onClick:()=>d("kpi"),className:"h-10 p-4",children:e.jsx(s.TiSortNumerically,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Text",onClick:()=>d("text"),className:"h-10 p-4",children:e.jsx(s.BookType,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{tooltip:"Map",onClick:()=>d("map"),className:"h-10 p-4",children:e.jsx(s.Map,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Custom",onClick:()=>d("custom"),className:"h-10 p-4",children:e.jsx(Ve,{className:s.cn("size-5",n)})})]})}function _n({chartType:t,className:n,customIcon:a,componentName:r}){const l=Je();switch(t){case"bar":return e.jsx(s.ChartColumnIncreasing,{className:n});case"line":return e.jsx(s.ChartLine,{className:n});case"pie":return e.jsx(s.ChartPie,{className:n});case"radar":return e.jsx(s.Radar,{className:n});case"scatter":return e.jsx(s.ChartScatter,{className:n});case"bubble":return e.jsx(s.TbChartBubble,{className:n});case"doughnut":return e.jsx(s.Donut,{className:n});case"stackedBar":return e.jsx(s.ChartColumnStacked,{className:n});case"stackedLine":return e.jsx(s.MdStackedLineChart,{className:n});case"polarArea":return e.jsx(s.PiChartPolar,{className:n});case"funnel":return e.jsx(s.TbChartFunnel,{className:n});case"tornado":case"pyramid":return e.jsx(s.Tornado,{className:n});case"range":return e.jsx(s.ChartNoAxesGantt,{className:n});case"kpi":return e.jsx(s.TiSortNumerically,{className:n});case"text":return e.jsx(qe,{className:n});case"map":return e.jsx(s.Map,{className:n});case"custom":return a&&l?e.jsx(l,{className:n}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(Ve,{className:n});default:return e.jsx(s.Table2,{className:n})}}function pt({variant:t="ghost"}){var o,c;const[n,a]=k.useState(!1),r=s.useEditorStore(i=>i.card),l=r.type;return s.useDashboardStore(i=>i.isVisualEditing),e.jsxs(s.Popover,{open:n,onOpenChange:a,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(_n,{className:"size-4",chartType:l,customIcon:(o=r.customCardPreferences)==null?void 0:o.icon,componentName:(c=r.customCardPreferences)==null?void 0:c.componentName})})}),e.jsxs(s.PopoverContentCustom,{onOpenAutoFocus:i=>i.preventDefault(),className:"z-[51] w-72 p-1",children:[e.jsx(Gn,{onChartTypeChange:()=>a(!1)}),e.jsx(zn,{onChartTypeChange:()=>a(!1)})]})]})}function Yn({error:t,className:n="",textClassName:a="",copyButtonClassName:r=""}){const[l,o]=k.useState(!1),c=k.useRef(null),i=k.useRef(!1);function d(){t&&!i.current&&navigator.clipboard.writeText(t)}function u(x){(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),d())}function m(){const x=window.getSelection();if(x&&x.toString().trim()!==""){const g=x.toString();navigator.clipboard.writeText(g),o(!0),i.current=!0,setTimeout(()=>{o(!1),i.current=!1},1e3)}else i.current=!1}function h(){o(!1),i.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${n}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:c,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${a}`,onClick:d,onKeyDown:u,onMouseUp:m,onMouseDown:h,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),l&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function $n(){const t=s.useEditorStore(o=>{var c,i;return(i=(c=o.card.preferences)==null?void 0:c.chartOptions)==null?void 0:i.indexAxis}),n=s.useEditorStore(o=>o.card.type),{setChartOrientation:a}=s.useEditorStore(o=>o.actions);function r(){return e.jsx(s.IconButton,{onClick:()=>{a(t==="x"||t===void 0?"y":"x")},tooltip:"Chart Orientation",children:t==="x"||t===void 0?e.jsx(vs,{className:"size-4"}):e.jsx(js,{className:"size-4"})})}function l(){return e.jsx(s.IconButton,{onClick:()=>{a(t==="y"||t===void 0?"x":"y")},tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(vs,{className:"size-4"}):e.jsx(js,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?l():r()})}function qn({className:t}){var x,g,v,p,y,b,S,A;const n=s.useEditorStore(E=>E.card),{setCardPreferences:a,updateCardInFrame:r,setCard:l}=s.useEditorActions(),[o,c]=k.useState(!1),i=((g=(x=n.preferences)==null?void 0:x.displayOptions)==null?void 0:g.showFilterInfo)??!0,d=((p=(v=n.preferences)==null?void 0:v.displayOptions)==null?void 0:p.showCardToolbar)??!0,u=((b=(y=n.preferences)==null?void 0:y.displayOptions)==null?void 0:b.showChrome)??!0,m=((A=(S=n.preferences)==null?void 0:S.displayOptions)==null?void 0:A.allowScroll)??!0,h=(E,C)=>{var N;const D={...n.preferences,displayOptions:{...(N=n.preferences)==null?void 0:N.displayOptions,[E]:C}};a(D);const f={...n,preferences:D};l(f),r(f)};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsxs(s.DropdownMenu,{modal:!1,open:o,onOpenChange:c,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{className:"h-8 w-8 p-0",tooltip:"Display Options",children:e.jsx(Bs,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(s.DropdownMenuLabel,{children:"Display Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx("div",{className:"px-2 py-1.5",children:e.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"Changes apply to dashboard view only"})}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:i,onCheckedChange:E=>{h("showFilterInfo",E)},onSelect:E=>E.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Filter Info"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Badge"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:d,onCheckedChange:E=>{h("showCardToolbar",E)},onSelect:E=>E.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Toolbar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Hover actions"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:u,onCheckedChange:E=>{h("showChrome",E)},onSelect:E=>E.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Chrome"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Frame & padding"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:m,onCheckedChange:E=>{h("allowScroll",E)},onSelect:E=>E.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Allow Scroll"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card content scroll"})]})]})]})})}function ft(){const t=s.useEditorStore(o=>o.card),n=s.useEditorStore(o=>{var c,i;return(i=(c=o.card)==null?void 0:c.preferences)==null?void 0:i.chartOptions}),a=s.getChartGridStyle(n),{setChartGrid:r}=s.useEditorActions();function l(){const o=["xy","none","x","y"],i=(o.indexOf(a)+1)%o.length;r(o[i])}return e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx($n,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsx(e.Fragment,{}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(t.type)&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:l,children:[(a==="xy"||!a)&&e.jsx(We,{className:"size-4"}),a==="x"&&e.jsx(Ut,{className:"size-4"}),a==="y"&&e.jsx(oa,{className:"size-4"}),a==="none"&&e.jsx(ua,{className:"size-4"})]}),e.jsx(qn,{})]})}function Kn(){const t=s.useEditorStore(v=>v.frame),n=s.useEditorStore(v=>v.card),{setFrame:a,setActiveTabCardId:r,setCard:l,updateCardInFrame:o}=s.useEditorActions(),c=(v,p)=>{v.dataTransfer.setData("tabIndex",p.toString())},i=v=>{v.preventDefault()},d=(v,p)=>{const y=v.dataTransfer.getData("tabIndex");if(y===p.toString())return;const b=Array.from(t.cards),[S]=b.splice(parseInt(y),1);b.splice(p,0,S),a({...t,cards:b})};function u(v){const p=t.cards.filter(S=>S.id!==v),y=p[0],b={...t,cards:p,activeCardId:y.id};a(b),r(y.id),l(y)}function m(v,p){const y={...t,cards:[...t.cards,p],activeCardId:v.id};a(y),r(p.id)}function h(){const v={...n,id:s.v4(),title:`${n.title} Copy`,tabTitle:`${n.tabTitle||n.title} Copy`};m(n,v)}function x(v){const p={dataSource:v.dataSource,connectionId:v.connectionId,lastSelectedDatabase:v.lastSelectedDatabase,lastSelectedSchema:v.lastSelectedSchema,lastSelectedTable:v.lastSelectedTable,lastSelectedDatamodelId:v.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};m(v,p)}function g(v,p){return v.cards.length===1&&(p.displayTab===!0||p.displayTab===void 0)||v.activeCardId!==p.id&&(p.displayTab===!0||p.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const y=p.displayTab===void 0?!1:!p.displayTab;l({...p,displayTab:y}),o({...p,displayTab:y})},children:p.displayTab===!0||p.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(Yt,{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((v,p)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:y=>c(y,p),onDragOver:i,onDrop:y=>d(y,p),className:"",value:v.id,children:[g(t,v),e.jsx(s.Editable,{enabled:t.activeCardId===v.id,text:v.tabTitle||v.title,onSave:y=>{l({...n,tabTitle:y}),o({...n,tabTitle:y})},children:v.tabTitle||v.title},v.id),t.activeCardId===v.id&&e.jsx(s.CopyPlus,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:y=>{y.stopPropagation(),h()}}),t.activeCardId===v.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>u(v.id)})]},v.id)),e.jsx(s.IconButton,{tooltip:"Add Card",className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",onClick:()=>x(n),children:e.jsx(s.Plus,{className:"h-4 w-4"})})]})})}function gt(){const t=s.useEditorStore(p=>p.frame),n=s.useEditorStore(p=>p.card),a=s.useEditorStore(p=>p.isSqlRunning),r=s.useEditorStore(p=>p.isDevMode),{setFrame:l,setActiveTabCardId:o,setCard:c,setIsDevMode:i,setRunSql:d}=s.useEditorActions(),{data:u,isLoading:m,isFetching:h}=s.useDashboardCardQuery(n);function x(p){const y=t.cards.find(b=>b.id===p);if(y!=null&&y.sql){r||i(!0),o(p);return}if(y!=null&&y.queryConfig){r&&i(!1),g(p),o(p);return}r||g(p),o(p)}function g(p){const y={...t,cards:t.cards.map(S=>S.id===n.id?n:S),activeCardId:p};l(y);const b=y.cards.find(S=>S.id===p);b.sql&&d(!0),c(b)}function v(){return n.type==="kpi"?m||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border border-border",children:e.jsx(s.KPICard,{card:n,data:u==null?void 0:u.records,isPending:m||h})})}):n.type==="text"?m||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:a,card:n,data:u==null?void 0:u.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(mt,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:x,value:t.activeCardId,className:"flex grow flex-col",children:[t.cards.map(p=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:p.id,children:v()},p.id)),e.jsx(Kn,{})]})}function Ds({children:t}){var D,f;s.useEditorStore(N=>N.frame);const n=s.useEditorStore(N=>N.card),a=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:u,setIsDevMode:m,setCardPreferences:h}=s.useEditorActions(),{data:x,isLoading:g,isFetching:v,errorMessage:p,refetch:y}=s.useDashboardCardQuery(n),[b,S]=k.useState(!1);k.useEffect(()=>{v||S(!1)},[v]);function A(){const N=JSON.stringify(x==null?void 0:x.records,null,2),j=new Blob([N],{type:"application/json"}),R=URL.createObjectURL(j),T=document.createElement("a");T.href=R,T.download=`${n.title}.json`,T.click()}function E(){const j=[Object.keys(x==null?void 0:x.records.reduce((w,I)=>({...w,...I}),{})).join(","),...((x==null?void 0:x.records)||[]).map(w=>Object.values(w).join(","))].join(`
|
|
269
|
-
`),R=new Blob([j],{type:"text/csv"}),T=URL.createObjectURL(R),F=document.createElement("a");F.href=T,F.download=`${n.title}.csv`,F.click()}function C(){const N=`Can you get the documentation for ${n.type} chart?`;u(N)}return n?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[r&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(pt,{}),l&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:C,children:e.jsx(Bt,{className:"size-4"})}),!["table","custom"].includes(n.type)&&l&&e.jsx(Vn,{})]}),!r&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:E,children:e.jsx(s.PiFileCsv,{className:"size-4"})}),e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:A,children:e.jsx(qt,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(x==null?void 0:x.records,null,2),className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t,e.jsx(s.IconButton,{tooltip:"Refresh",disabled:g||v,onClick:()=>{S(!0),y()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":b})})}),e.jsx(ft,{})]}),n.type==="table"&&n.sql&&!s.hasValidCardConfig(n.config)&&e.jsxs("div",{className:"mr-2 flex items-center gap-3",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((f=(D=n.preferences)==null?void 0:D.tablePrefs)==null?void 0:f.enableDevModePagination)??!1,onCheckedChange:N=>{var j;h({...n.preferences,tablePrefs:{...(j=n.preferences)==null?void 0:j.tablePrefs,enableDevModePagination:N}}),y()}}),e.jsx(s.Label,{htmlFor:"pagination",children:"Paginate Results"})]}),a&&e.jsx(Wn,{})]}),r?e.jsx(gt,{}):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(Hn,{})}),e.jsx(s.ResizableHandle,{})]}),e.jsxs(s.ResizablePanel,{id:"2",order:2,minSize:10,className:s.cn("relative flex h-full min-h-0 w-full flex-1 basis-0",{"px-6":o}),children:[(x==null?void 0:x.records)&&(x==null?void 0:x.records.length)>0&&e.jsx(s.TableVisual,{card:n,data:(x==null?void 0:x.records)||[]}),p&&e.jsx(Yn,{error:p})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function Hn(){const t=s.useEditorStore(a=>a.pythonStdOut);if(!t)return null;const n=t.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(s.ScrollArea,{className:"overflow-y-auto pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:n}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Wn(){const t=s.useEditorStore(a=>a.isShowingVisual),n=s.useEditorStore(a=>a.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(s.SmallSwitch,{checked:t,onCheckedChange:()=>n(!t),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function Se({defaultValue:t,label:n,options:a,value:r,onValueChange:l,className:o,icon:c,showPlaceholderLabel:i=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:l,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",o),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),i&&e.jsx(s.SelectValue,{placeholder:n})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:n}),a.map(d=>e.jsx(s.SelectItem,{value:d.value,children:d.label},d.value))]})})]})}function Qn(){var p,y;const t=s.useEditorStore(b=>b.card.customCardPreferences),{data:n}=ht(),a=(n==null?void 0:n.plugins)||[],r=s.useEditorStore(b=>b.card),l=s.useEditorStore(b=>b.frame),o=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:c}=s.useEditorActions(),{components:i,manifest:d}=s.useCustomVisual((t==null?void 0:t.url)||""),u=(p=d==null?void 0:d.visuals)==null?void 0:p.find(b=>b.name===(t==null?void 0:t.componentName));function m(b,S){if(!t)return;const E={...(t==null?void 0:t.dataInputCardIds)||{},[b]:{cardId:S,hookRef:null}};c({...t,dataInputCardIds:E})}function h(b){var A,E;const S=(A=l==null?void 0:l.cards)==null?void 0:A.filter(C=>{var D;return((D=C==null?void 0:C.customCardPreferences)==null?void 0:D.visualType)!=="multiple"}).map(C=>({value:C.id,label:C.tabTitle||C.title}));return e.jsx("div",{className:"space-y-2",children:(E=b==null?void 0:b.dataInputs)==null?void 0:E.map((C,D)=>{var f,N;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:C}),e.jsx(Se,{className:"col-span-6 h-8 w-full justify-between",label:"",options:S||[],value:((N=(f=t==null?void 0:t.dataInputCardIds)==null?void 0:f[D])==null?void 0:N.cardId)||"",onValueChange:j=>m(D,j)})]},D+Math.random())})})}function x(b,S,A=[],E=""){var C,D;return t?b==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((C=t==null?void 0:t.settings)==null?void 0:C[S])||E,onChange:f=>{c({...t,settings:{...t==null?void 0:t.settings,[S]:f.target.value}})}},S):b==="select"?e.jsx(Se,{className:"h-8 w-full",label:"",options:A,value:((D=t==null?void 0:t.settings)==null?void 0:D[S])||E,onValueChange:f=>{c({...t,settings:{...t==null?void 0:t.settings,[S]:f}})}}):null:null}function g(b){const S=Object.entries((b==null?void 0:b.settings)||{});return e.jsx("div",{className:"space-y-3",children:S.map(([A,E])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:E.title}),x(E.ui,A,E.options,E.defaultValue)]},A))})}function v(b){t&&c({...t,visualType:b,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(Se,{icon:e.jsx(Pt,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:a,value:(t==null?void 0:t.url)||"",onValueChange:b=>c({...t||{url:"",componentName:""},url:b})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:o,onValueChange:v,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(Se,{icon:e.jsx(Gt,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(i==null?void 0:i.filter(b=>b.type===o).map(b=>({value:b.name,label:b.name})))||[],value:t.componentName,onValueChange:b=>{console.log("changing value",b),c({...t,componentName:b})}})})]})})]}),((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:[u&&u.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:h(u)})]}),u&&u.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:g(u)})})]})]})]})}function Me(){const[t,n]=k.useState([]),a=s.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:l}=s.useEditorStore(u=>u.actions),o=s.useEditorStore(u=>u.queryResultColumns);s.useEditorStore(u=>{var m;return(m=u.card.preferences)==null?void 0:m.filterOnClickColumnIndex}),k.useEffect(()=>{o&&n(new Array(o.length).fill(!1))},[o]);function c(u,m){var h,x;m?a!=null&&a.onClickFilter&&((h=a==null?void 0:a.onClickFilter)==null?void 0:h.length)>0?l({...a,onClickFilter:[...a.onClickFilter,{columnIndex:u,expression:""}]}):l({...a,onClickFilter:[{columnIndex:u,expression:""}]}):(l({...a,onClickFilter:(x=a==null?void 0:a.onClickFilter)==null?void 0:x.filter(g=>g.columnIndex!==u)}),n(g=>{const v=[...g];return v[u]=!1,v}))}function i(u,m){var x;const h=(x=a==null?void 0:a.onClickFilter)==null?void 0:x.map(g=>g.columnIndex===u?{...g,expression:m.target.value}:g);l({...a,onClickFilter:h})}function d(u){var m,h,x,g;if(t!=null&&t[u]||(h=(m=a==null?void 0:a.onClickFilter)==null?void 0:m.find(v=>v.columnIndex===u))!=null&&h.expression)return e.jsx(s.Input,{value:(g=(x=a==null?void 0:a.onClickFilter)==null?void 0:x.find(v=>v.columnIndex===u))==null?void 0:g.expression,onChange:v=>i(u,v),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsx("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:o==null?void 0:o.map((u,m)=>{var h,x;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((h=a==null?void 0:a.onClickFilter)!=null&&h.find(g=>g.columnIndex===m)),onCheckedChange:g=>c(m,g)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:u}),e.jsx("div",{className:"flex items-center gap-2",children:((x=a==null?void 0:a.onClickFilter)==null?void 0:x.find(g=>g.columnIndex===m))&&e.jsx(s.Pencil,{onClick:()=>{n(g=>{const v=[...g];return v[m]=!g[m],v})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(m)]})},u)})})}function Jn({idx:t}){var i;const n=s.useEditorStore(d=>{var u;return(u=d.card)==null?void 0:u.preferences}),a=s.useEditorStore(d=>{var u;return(u=d.card.preferences)==null?void 0:u.datasetOptions}),r=s.useEditorStore(d=>d.actions.setCardPreferences),l=(i=n==null?void 0:n.chartOptions)==null?void 0:i.indexAxis,o=a==null?void 0:a.find(d=>d.idx===t);function c(d,u){(d==="end"||d==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const m={display:d!=="none",align:d,anchor:d,clamp:!0};if(!o)r({...n,datasetOptions:[...a||[],{idx:u,datalabels:m}]});else{const h={...o};h.datalabels=m;const x=a==null?void 0:a.map(g=>g.idx===u?h:g);r({...n,datasetOptions:x})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(Vs,{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(Xt,{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(ea,{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(Zt,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function Xn(){const t=s.useEditorStore(o=>o.card),{data:n}=s.useDashboardCardQuery(t),{keys:a}=s.getKeys((n==null?void 0:n.records)||[]),r=a.slice(1).filter(o=>!s.METADATA_KEYS.includes(o));let l=r;if(["stackedBar","stackedLine"].includes(t.type)){const o=s.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:c}=s.getKeys(o);l=c.slice(1)}return{transformedMetricKeys:l,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}function cs({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",n),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function jt(){const t=s.useEditorStore(d=>d.card),n=s.useEditorStore(d=>{var u,m,h;return(h=(m=(u=d==null?void 0:d.card)==null?void 0:u.preferences)==null?void 0:m.chartOptions)==null?void 0:h.indexAxis}),{data:a}=s.useDashboardCardQuery(t),r=n==="y"?"Metric":"Dimension",l=n==="y"?"Dimension":"Metric",{dimensionKeys:o,transformedMetricKeys:c,keys:i}=Xn();return i.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:o.map(d=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:d,children:vt(d)},d))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:l}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:c.map((d,u)=>e.jsx(bt,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:d,idx:u},d))})]})]})}function vt(t,n=30){return t.length>n?t.slice(0,n)+"...":t}function bt({col:t,idx:n,className:a,iconClassName:r,children:l}){const o=s.useEditorStore(m=>{var h;return(h=m.card)==null?void 0:h.preferences}),c=s.useEditorStore(m=>{var h,x;return(x=(h=m.card)==null?void 0:h.preferences)==null?void 0:x.datasetOptions}),i=c==null?void 0:c.find(m=>m.idx===n),{setCardPreferences:d}=s.useEditorStore(m=>m.actions);function u(m){if(!i)d({...o,datasetOptions:[...c||[],{idx:n,type:m==="area"?"line":m,fill:m==="area"?"origin":""}]});else{const h={...i};h.type=m==="area"?"line":m,h.fill=m==="area"?"origin":"";const x=c==null?void 0:c.map(g=>g.idx===n?h:g);d({...o,datasetOptions:x})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[l||e.jsx(cs,{className:"max-w-[100px]",title:t,children:vt(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.ChartColumnIncreasing,{onClick:()=>u("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartLine,{onClick:()=>u("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartArea,{onClick:()=>u("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(Jn,{idx:n})]})]})}function Pe(){const t=s.useDashboardStore(i=>i.dashboard.filters),n=s.useEditorStore(i=>i.frame),{setFrame:a}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=rt();function o(i){const d=l(i,"frame");a({...n,filterId:d})}const c=t==null?void 0:t.find(i=>i.id===n.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(Zn,{onSelect:o,columns:r}),c&&e.jsx(s.FilterHeader,{filter:c})]})}function Zn({columns:t,onSelect:n}){var c;const[a,r]=ss.useState(!1),[l,o]=ss.useState("");return e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between font-normal",children:[l?(c=t.find(i=>i.column_name===l))==null?void 0:c.column_name:"Select Column...",e.jsx(s.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No framework found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(i=>e.jsxs(s.CommandItem,{value:i.column_name,onSelect:d=>{const u=d===l?"":d;o(u),r(!1),u&&n(i)},children:[i.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",l===i.column_name?"opacity-100":"opacity-0")})]},i.column_name))})]})]})})]})}function er({cardType:t}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, y-axis-1, y-axis-2,... FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"y-axis1 - number"}),e.jsx("li",{children:"y-axis2 - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:n=>n.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(jt,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Me,{}),e.jsx(Pe,{})]})]})]})})}function sr({cardType:t}){function n(a){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:a==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),a==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:o=>o.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsx(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:n(t)})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Me,{}),e.jsx(Pe,{})]})]})]})})}function yt(){const t=s.useEditorStore(i=>i.card.type),n=s.useEditorStore(i=>i.isDevMode),a=s.useEditorStore(i=>i.card.preferences),{setCardPreferences:r}=s.useEditorStore(i=>i.actions);function l(i){var m;const d={datalabels:{display:i!=="none",align:i,anchor:i,clamp:!0}},u={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(m=a==null?void 0:a.chartOptions)==null?void 0:m.plugins,...d}}};r(u)}function o(){var i,d,u;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((u=(d=(i=a==null?void 0:a.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Data Labels"}),e.jsx(s.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"start",children:"Start"}),e.jsx(s.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"end",children:"End"})]})})]})]})}function c(){var i,d,u;return e.jsx("div",{children:e.jsxs(s.Select,{value:((u=(d=(i=a==null?void 0:a.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(s.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:n?o():c()})}const tr={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},ar={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function nr(){const t=s.useEditorStore(n=>n.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:rr(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(yt,{}),e.jsx(Me,{}),e.jsx(Pe,{})]})]})}function rr(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(tr,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(ar,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 lr({colorRanges:t,setColorRanges:n}){const a={start:-1/0,end:100,color:""};function r(c,i,d){const u=[...t];u[c]={...u[c],[i]:d},n(u)}function l(c){const i=[...t];i.splice(c,1),n(i)}function o(){n([...t,a])}return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:"Color Range"}),e.jsx(s.Button,{onClick:o,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((c,i)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input,{onChange:d=>r(i,"start",d.target.value),value:c.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input,{value:c.end,onChange:d=>r(i,"end",d.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input,{onChange:d=>r(i,"color",d.target.value),value:c.color,className:s.cn(`h-7 min-w-14 p-0 ${s.removeRing}`),type:"color",list:"presetColors"}),e.jsxs("datalist",{id:"presetColors",children:[e.jsx("option",{children:s.colors.green[600]}),e.jsx("option",{children:s.colors.red[500]}),e.jsx("option",{children:s.colors.yellow[400]}),e.jsx("option",{children:s.colors.orange[500]})]}),e.jsx(s.Button,{onClick:()=>l(i),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},i))]})}function or(){var m,h,x,g,v;const t=s.useEditorStore(p=>p.card.preferences),n=s.useEditorStore(p=>p.actions.setCardPreferences),a=s.useEditorStore(p=>p.card),r=s.isExplorerCard(a),l=s.useEditorStore(p=>p.actions.setNumberFormat);s.useEditorStore(p=>{var y,b;return(b=(y=p.card.preferences)==null?void 0:y.formatNumber)==null?void 0:b.decimalPlaces});const o=s.useEditorStore(p=>{var y,b;return(b=(y=p.card.preferences)==null?void 0:y.formatNumber)==null?void 0:b.locale}),c=s.useEditorStore(p=>{var y,b;return(b=(y=p.card.preferences)==null?void 0:y.formatNumber)==null?void 0:b.currency});s.useEditorStore(p=>p.actions.setFilterOnClickField);const i=s.useEditorStore(p=>{var y,b;return(b=(y=p.card.preferences)==null?void 0:y.formatNumber)==null?void 0:b.colorRanges})||[],d=s.useEditorStore(p=>p.actions.setColorRanges),u=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(p=>p.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(s.Checkbox,{checked:!!((m=t==null?void 0:t.formatNumber)!=null&&m.enabled),onCheckedChange:p=>{n({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:p}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((h=t==null?void 0:t.formatNumber)==null?void 0:h.enabled)===!0||r)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Locale"}),e.jsxs(s.Select,{value:o||"none",onValueChange:p=>{var y,b,S;return l(((y=t==null?void 0:t.formatNumber)==null?void 0:y.decimalPlaces)||0,((b=t==null?void 0:t.formatNumber)==null?void 0:b.currency)||"",p,((S=t==null?void 0:t.formatNumber)==null?void 0:S.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Format"}),e.jsx(s.SelectItem,{value:"none",children:"Auto"},"none"),s.LOCALE_CURRENCY_PAIRS.map(p=>e.jsx(s.SelectItem,{value:p.locale,children:p.locale},p.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:c||"none",onValueChange:p=>{var y,b,S;console.log("currency",p),l(((y=t==null?void 0:t.formatNumber)==null?void 0:y.decimalPlaces)||0,p==="none"?"":p,((b=t==null?void 0:t.formatNumber)==null?void 0:b.locale)||"",((S=t==null?void 0:t.formatNumber)==null?void 0:S.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Currency"}),e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),u.map(p=>e.jsx(s.SelectItem,{value:p,children:p},p))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Decimals"}),e.jsxs(s.Select,{value:((g=(x=t==null?void 0:t.formatNumber)==null?void 0:x.decimalPlaces)==null?void 0:g.toString())||"0",onValueChange:p=>{var y,b,S;return l(Number(p),((y=t==null?void 0:t.formatNumber)==null?void 0:y.currency)||"",((b=t==null?void 0:t.formatNumber)==null?void 0:b.locale)||"",((S=t==null?void 0:t.formatNumber)==null?void 0:S.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-3 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["0","1","2","3","4"].map(p=>e.jsx(s.SelectItem,{value:p,children:p},p))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Suffix"}),e.jsx(s.Input,{value:((v=t==null?void 0:t.formatNumber)==null?void 0:v.suffix)||"",className:"h-8 font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"K, M, B, %",onChange:p=>{var y,b,S;return l(((y=t==null?void 0:t.formatNumber)==null?void 0:y.decimalPlaces)||0,((b=t==null?void 0:t.formatNumber)==null?void 0:b.currency)||"",((S=t==null?void 0:t.formatNumber)==null?void 0:S.locale)||"",p.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(lr,{colorRanges:i,setColorRanges:d})]})]})}function ir(){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(or,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function Ze({children:t,summary:n,open:a,className:r}){return e.jsxs("details",{open:a,className:s.cn("space-y-4 [&_summary>svg]:open:-rotate-180",r),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(s.Label,{children:n}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const cr=[{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"}],dr=["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"],ur=dr.map(t=>({label:t,value:t}));function mr(){var d,u,m,h,x,g,v,p,y,b,S,A,E,C,D,f,N,j;const t=s.useEditorStore(R=>R.card),n=(u=(d=t==null?void 0:t.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:u.topoJsonUrl,[a,r]=k.useState(((h=(m=t==null?void 0:t.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:o}=s.useTopoJson(t),c=Object.keys((o==null?void 0:o.objects)||{}).map(R=>({label:R,value:R}))||[],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(Ze,{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(Ze,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(Se,{className:"h-9",options:i,onValueChange:R=>{console.log("value",R),l({...t.preferences,mapVisualOptions:{topoJsonUrl:R}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(s.Input,{onChange:R=>{r(R.target.value)},onBlur:()=>{var R;console.log("onBlur",a),l({...t.preferences,mapVisualOptions:{...(R=t.preferences)==null?void 0:R.mapVisualOptions,customTopoJsonUrl:a}})},value:a,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),o&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(Se,{className:"h-9",options:c,value:((g=(x=t.preferences)==null?void 0:x.mapVisualOptions)==null?void 0:g.objectKey)||"",label:"Map Object",onValueChange:R=>{var T;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,objectKey:R}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(Se,{className:"h-9",options:cr,value:((p=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:p.projection)||"",label:"Projection",onValueChange:R=>{var T;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,projection:R}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(Se,{className:"h-9",options:ur,value:((b=(y=t.preferences)==null?void 0:y.mapVisualOptions)==null?void 0:b.colorScale)||"",label:"Select Color Scale",onValueChange:R=>{var T;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,colorScale:R}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Ze,{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:((A=(S=t.preferences)==null?void 0:S.mapVisualOptions)==null?void 0:A.projectionScale)||1,onChange:R=>{var T;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,projectionScale:Number(R.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((D=(C=(E=t.preferences)==null?void 0:E.mapVisualOptions)==null?void 0:C.projectionOffset)==null?void 0:D[0])||0,onChange:R=>{var T,F,w,I;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,projectionOffset:[Number(R.target.value),((I=(w=(F=t.preferences)==null?void 0:F.mapVisualOptions)==null?void 0:w.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:((j=(N=(f=t.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:N.projectionOffset)==null?void 0:j[1])||0,onChange:R=>{var T,F,w,I;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,projectionOffset:[((I=(w=(F=t.preferences)==null?void 0:F.mapVisualOptions)==null?void 0:w.projectionOffset)==null?void 0:I[0])||0,Number(R.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Me,{})]})}function hr(){var r;const t=s.useEditorStore(l=>l.card.preferences),{setCardPreferences:n}=s.useEditorStore(l=>l.actions);function a(l){n({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:l==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:a,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function Ge({cardType:t,docContent:n,suffix:a="Chart"}){let r="pie-donut-polar";return t==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} ${a}`}),e.jsx(s.AccordionContent,{children:n||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:l=>l.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),t==="text"&&e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2 py-4",children:e.jsx(hr,{})})]}),!["range","text"].includes(t)&&e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Me,{}),e.jsx(Pe,{})]})]})]})})}function xr(){const t=s.useEditorStore(r=>{var l,o;return(o=(l=r==null?void 0:r.card)==null?void 0:l.preferences)==null?void 0:o.sortChart}),{setSortChart:n}=s.useEditorActions();function a(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(Se,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:t||"none",onValueChange:r=>{n(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[a(),e.jsx(jt,{})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Me,{}),e.jsx(Pe,{})]})]})]})})}function pr({cardType:t="table"}){console.log("cardType",t);const n=s.useEditorStore(l=>{var o;return(o=l.card)==null?void 0:o.preferences}),a=s.useEditorStore(l=>l.actions.setCardPreferences),r=l=>{a({...n,allowDownload:l})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Me,{}),e.jsx(Pe,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{onCheckedChange:r,id:"allow-download"}),e.jsx("label",{htmlFor:"allow-download",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Allow Download"})]})]})}function Nt({color:t,onColorChange:n,onClose:a}){const[r,l]=k.useState(0),[o,c]=k.useState(100),[i,d]=k.useState(50),[u,m]=k.useState(t);k.useEffect(()=>{const y=Ts(t);if(y){const b=ks(y.r,y.g,y.b);l(b.h),c(b.s),d(b.l),m(t)}},[t]);const h=y=>{l(y),g(y,o,i)},x=y=>{const b=y.currentTarget.getBoundingClientRect(),S=Math.max(0,Math.min(1,(y.clientX-b.left)/b.width)),A=Math.max(0,Math.min(1,(y.clientY-b.top)/b.height)),E=S*100,C=(1-A)*100;c(E),d(C),g(r,E,C)},g=(y,b,S)=>{const A=gr(y,b,S),E=fr(A.r,A.g,A.b);m(E)},v=y=>{if(m(y),/^#[0-9A-Fa-f]{6}$/.test(y)){const b=Ts(y);if(b){const S=ks(b.r,b.g,b.b);l(S.h),c(S.s),d(S.l)}}},p=()=>{/^#[0-9A-Fa-f]{6}$/.test(u)&&(n(u),a())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:x,onMouseMove:y=>{y.buttons===1&&x(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:u}})]}),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:u,onChange:y=>v(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:u}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(s.Button,{variant:"outline",onClick:a,children:"Cancel"}),e.jsx(s.Button,{onClick:p,children:"OK"})]})]})}function Ts(t){const n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return n?{r:parseInt(n[1],16),g:parseInt(n[2],16),b:parseInt(n[3],16)}:null}function fr(t,n,a){return"#"+((1<<24)+(t<<16)+(n<<8)+a).toString(16).slice(1)}function ks(t,n,a){t/=255,n/=255,a/=255;const r=Math.max(t,n,a),l=Math.min(t,n,a);let o=0,c=0;const i=(r+l)/2;if(r!==l){const d=r-l;switch(c=i>.5?d/(2-r-l):d/(r+l),r){case t:o=((n-a)/d+(n<a?6:0))/6;break;case n:o=((a-t)/d+2)/6;break;case a:o=((t-n)/d+4)/6;break}}return{h:Math.round(o*360),s:Math.round(c*100),l:Math.round(i*100)}}function gr(t,n,a){t/=360,n/=100,a/=100;let r,l,o;if(n===0)r=l=o=a;else{const c=(u,m,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?u+(m-u)*6*h:h<.5?m:h<.6666666666666666?u+(m-u)*(.6666666666666666-h)*6:u),i=a<.5?a*(1+n):a+n-a*n,d=2*a-i;r=c(d,i,t+1/3),l=c(d,i,t),o=c(d,i,t-1/3)}return{r:Math.round(r*255),g:Math.round(l*255),b:Math.round(o*255)}}const jr=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function Ct(){var A,E,C,D,f,N,j,R,T,F;const t=s.useEditorStore(w=>w.card),n=s.useEditorStore(w=>{var I;return(I=w.card)==null?void 0:I.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions(),{data:l}=s.useDashboardCardQuery(t),[o,c]=k.useState({}),[i,d]=k.useState(null),[u,m]=k.useState(null),h=k.useMemo(()=>{var O,L,P,B,H,q,z;if(!(l!=null&&l.records)||l.records.length===0)return[];const w=(t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine",I=(t==null?void 0:t.type)==="bar"||(t==null?void 0:t.type)==="line",M=((O=t==null?void 0:t.config)==null?void 0:O.pivotByColumns)&&t.config.pivotByColumns.length>0;if((w||I)&&M){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const Q=new Set;return l.pivotSchema.forEach(X=>{X.alias&&Q.add(X.alias)}),Array.from(Q)}if(l.records.length>0){const Q=l.records[0],X=Object.keys(Q),se=new Set;(L=t==null?void 0:t.config)!=null&&L.groupByColumns&&t.config.groupByColumns.forEach(K=>{se.add(K.label||K.name),se.add(K.alias||K.name)});const te=new Set;return(P=t==null?void 0:t.config)!=null&&P.metricColumns&&t.config.metricColumns.forEach(K=>{const Y=K.alias||K.name;te.add(Y),te.add(`${Y}_count`),te.add(`${Y}_sum`),te.add(`${Y}_avg`),te.add(`${Y}_min`),te.add(`${Y}_max`);const ae=K.entityName||K.qualifiedEntityName;ae&&(te.add(`${ae}_${Y}`),te.add(`${ae}_${Y}_count`))}),X.filter(K=>!se.has(K)&&!te.has(K))}}if((I||w)&&!M&&((H=(B=t==null?void 0:t.config)==null?void 0:B.metricColumns)!=null&&H.length))return t.config.metricColumns.map(Q=>Q.alias||Q.label||Q.name);if((z=(q=t==null?void 0:t.config)==null?void 0:q.groupByColumns)!=null&&z.length){const Q=t.config.groupByColumns[0],X=Q.label||Q.name,se=new Set;return l.records.forEach(te=>{const ie=te[X];ie!=null&&se.add(String(ie))}),Array.from(se)}return[]},[l,(A=t==null?void 0:t.config)==null?void 0:A.groupByColumns,(E=t==null?void 0:t.config)==null?void 0:E.pivotByColumns,(C=t==null?void 0:t.config)==null?void 0:C.metricColumns,t==null?void 0:t.type]),x=k.useMemo(()=>s.getDefaultChartColors(),[]);k.useEffect(()=>{const w={};h.forEach((I,M)=>{w[I]=s.getColorForValue(I,M,n==null?void 0:n.colorConfig)}),c(w)},[h,n==null?void 0:n.colorConfig,x]);const g=(w,I)=>{const M={...o,[w]:I};c(M);const O={...n||{},colorConfig:{segments:M}};a(O);const L={...t,preferences:O};r(L)},v=(w,I)=>{var H;const M=x[I%x.length],{[w]:O,...L}=((H=n==null?void 0:n.colorConfig)==null?void 0:H.segments)||{},P={...n||{},colorConfig:{segments:L}};a(P);const B={...t,preferences:P};r(B),c(q=>({...q,[w]:M}))};if(!h.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((f=(D=t==null?void 0:t.config)==null?void 0:D.groupByColumns)==null?void 0:f.length)||((j=(N=t==null?void 0:t.config)==null?void 0:N.pivotByColumns)==null?void 0:j.length):(T=(R=t==null?void 0:t.config)==null?void 0:R.groupByColumns)==null?void 0:T.length)||["table","kpi","text","custom"].includes(t.type))return null;const b=()=>{const w={...n||{},colorConfig:{segments:{}}};a(w);const I={...t,preferences:w};r(I);const M={};h.forEach((O,L)=>{M[O]=s.getColorForValue(O,L,void 0)}),c(M)},S=Object.keys(((F=n==null?void 0:n.colorConfig)==null?void 0:F.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(ra,{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:S&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:b,children:[e.jsx(bs,{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((w,I)=>{const M=s.isDefaultColor(o[w],I),O=!M;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:i===w,onOpenChange:L=>d(L?w: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[w]}})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-3",children:e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Theme Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:x.slice(0,10).map((L,P)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",o[w]===L?"border-gray-900":"border-transparent"),style:{backgroundColor:L},onClick:()=>{g(w,L),d(null)},children:[P===I%x.length&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-white/90 px-0.5 text-[8px] font-bold text-gray-900 shadow-sm",children:"D"})}),e.jsx("span",{className:"sr-only",children:L})]},`default-${P}`))})]}),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:jr.map((L,P)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",o[w]===L?"border-2 border-gray-900":L==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:L},onClick:()=>{g(w,L),d(null)},children:e.jsx("span",{className:"sr-only",children:L})},`preset-${P}`))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsx("button",{className:"text-sm font-medium text-blue-600 hover:text-blue-700",onClick:()=>{m({value:w,color:o[w]}),d(null)},children:"Custom color"}),!M&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{v(w,I),d(null)},children:[e.jsx(bs,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:w}),O&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},w)})}),u&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>m(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Nt,{color:u.color,onColorChange:w=>{g(u.value,w),m(null)},onClose:()=>m(null)})})]})]})})]})}function we({value:t,onSave:n,placeholder:a="",type:r="text",className:l=""}){const[o,c]=k.useState(t??""),[i,d]=k.useState(!1);k.useEffect(()=>{c(t??"")},[t]);const u=()=>{n(o),d(!1)},m=()=>{c(t??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${l}`,children:[e.jsx(s.Input$1,{placeholder:a,type:r,value:i?o:t??"",onChange:h=>{c(h.target.value),d(!0)},onFocus:()=>d(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&i&&o!==t?u():h.key==="Escape"&&m()},"aria-label":a||"Edit field"}),i&&o!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:u,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:m,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}const vr=["auto","number","currency","percent","scientific","date"],br=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"GBP",label:"GBP - British Pound"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"CHF",label:"CHF - Swiss Franc"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"},{value:"HKD",label:"HKD - Hong Kong Dollar"},{value:"SGD",label:"SGD - Singapore Dollar"},{value:"NZD",label:"NZD - New Zealand Dollar"},{value:"SEK",label:"SEK - Swedish Krona"},{value:"NOK",label:"NOK - Norwegian Krone"},{value:"DKK",label:"DKK - Danish Krone"},{value:"KRW",label:"KRW - South Korean Won"},{value:"INR",label:"INR - Indian Rupee"},{value:"RUB",label:"RUB - Russian Ruble"},{value:"BRL",label:"BRL - Brazilian Real"},{value:"MXN",label:"MXN - Mexican Peso"},{value:"TRY",label:"TRY - Turkish Lira"},{value:"ZAR",label:"ZAR - South African Rand"},{value:"SAR",label:"SAR - Saudi Riyal"},{value:"AED",label:"AED - UAE Dirham"},{value:"ARS",label:"ARS - Argentine Peso"},{value:"CLP",label:"CLP - Chilean Peso"},{value:"COP",label:"COP - Colombian Peso"},{value:"THB",label:"THB - Thai Baht"},{value:"IDR",label:"IDR - Indonesian Rupiah"},{value:"MYR",label:"MYR - Malaysian Ringgit"},{value:"PHP",label:"PHP - Philippine Peso"},{value:"PLN",label:"PLN - Polish Zloty"},{value:"NGN",label:"NGN - Nigerian Naira"},{value:"KES",label:"KES - Kenyan Shilling"},{value:"GHS",label:"GHS - Ghanaian Cedi"},{value:"ZMW",label:"ZMW - Zambian Kwacha"},{value:"ZWL",label:"ZWL - Zimbabwean Dollar"},{value:"EGP",label:"EGP - Egyptian Pound"},{value:"MAD",label:"MAD - Moroccan Dirham"},{value:"UAH",label:"UAH - Ukrainian Hryvnia"},{value:"HUF",label:"HUF - Hungarian Forint"},{value:"CZK",label:"CZK - Czech Koruna"},{value:"RON",label:"RON - Romanian Leu"},{value:"PKR",label:"PKR - Pakistani Rupee"},{value:"BDT",label:"BDT - Bangladeshi Taka"},{value:"VND",label:"VND - Vietnamese Dong"},{value:"TWD",label:"TWD - New Taiwan Dollar"},{value:"ILS",label:"ILS - Israeli New Shekel"}],yr=[{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"}],Nr=t=>t.charAt(0).toUpperCase()+t.slice(1);function ds({formatOptions:t={},onFormatOptionsChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const l=t.type||"auto",o=(i,d)=>{n({...t,[i]:d})},c=()=>l==="currency"?2:l==="percent"?1:0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[a&&e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(s.Select,{value:l,onValueChange:i=>o("type",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:vr.map(i=>e.jsx(s.SelectItem,{value:i,className:"text-xs",children:i==="auto"?"Auto (Default)":Nr(i)},i))})]})]}),l!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent"].includes(l)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",min:"0",max:"10",placeholder:"0",value:t.decimalPlaces??c(),onChange:i=>o("decimalPlaces",parseInt(i.target.value)||0),className:"h-8 text-xs"})})]}),l==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(s.Select,{value:t.currency||"USD",onValueChange:i=>o("currency",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:br.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:t.useSuffix??!1,onCheckedChange:i=>o("useSuffix",i)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(s.Select,{value:t.locale||"en-US",onValueChange:i=>o("locale",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:yr.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., $",value:t.prefix||"",onChange:i=>o("prefix",i.target.value),className:"h-8 text-xs"})})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., units",value:t.suffix||"",onChange:i=>o("suffix",i.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Negative in ()"}),e.jsx(s.SmallSwitch,{checked:t.negativeInParentheses??!1,onCheckedChange:i=>o("negativeInParentheses",i)})]}),l==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",placeholder:"100",value:t.multiplyBy??"",onChange:i=>o("multiplyBy",i.target.value?parseFloat(i.target.value):void 0),className:"h-8 text-xs"})})]}),l==="date"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Format"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"text",placeholder:"MM/DD/YYYY",value:t.dateFormat||"",onChange:i=>o("dateFormat",i.target.value),className:"h-8 text-xs"})})]})]})]})}function Es({axis:t,label:n,type:a,config:r,onChange:l}){var h,x,g,v,p,y,b,S,A,E,C,D;const o=(f,N)=>{l({...r,[f]:N})},c=(f,N)=>{var j,R;l({...r,name:{enabled:f==="enabled"?N:((j=r==null?void 0:r.name)==null?void 0:j.enabled)??!1,text:f==="text"?N:(R=r==null?void 0:r.name)==null?void 0:R.text}})},i=(f,N)=>{var j,R;l({...r,labels:{enabled:f==="enabled"?N:((j=r==null?void 0:r.labels)==null?void 0:j.enabled)??!0,rotation:f==="rotation"?N:(R=r==null?void 0:r.labels)==null?void 0:R.rotation}})},d=(f,N)=>{l({...r,scale:{...r==null?void 0:r.scale,[f]:N===""?"auto":Number(N)}})},u=t==="x"?["auto","top","bottom"]:["auto","left","right"],m=["auto","0","45","90","-45","-90"];return e.jsxs(s.AccordionItem,{value:`${t}-axis`,className:"border-b-0",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx(s.AccordionTrigger,{className:"flex grow items-center justify-between gap-3 py-2 text-sm font-medium hover:no-underline",children:e.jsx("div",{className:"flex grow items-center justify-between gap-2",children:e.jsx("span",{children:n})})}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:f=>o("enabled",f),onClick:f=>f.stopPropagation()})]}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TITLE"}),e.jsx(s.SmallSwitch,{checked:((h=r==null?void 0:r.name)==null?void 0:h.enabled)??!1,onCheckedChange:f=>c("enabled",f)})]}),((x=r==null?void 0:r.name)==null?void 0:x.enabled)&&e.jsx(we,{placeholder:`${n} title`,value:((g=r==null?void 0:r.name)==null?void 0:g.text)||"",onSave:f=>c("text",f),className:""})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(s.Select,{value:(r==null?void 0:r.position)||"auto",onValueChange:f=>o("position",f),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(f=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:f==="auto"?"Auto (Default)":s.titleCase(f)},f))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(s.SmallSwitch,{checked:((v=r==null?void 0:r.labels)==null?void 0:v.enabled)!==!1,onCheckedChange:f=>i("enabled",f)})]}),((p=r==null?void 0:r.labels)==null?void 0:p.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(((y=r==null?void 0:r.labels)==null?void 0:y.rotation)||"auto"),onValueChange:f=>i("rotation",f==="auto"?"auto":Number(f)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:m.map(f=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:f==="auto"?"Auto (Default)":`${f}°`},f))})]})]})]}),a==="value"&&e.jsx(ds,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:f=>l({...r,formatOptions:f}),showTitle:!0,title:"FORMAT"}),a==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"SCALE"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"auto",value:((b=r==null?void 0:r.scale)==null?void 0:b.min)==="auto"||((S=r==null?void 0:r.scale)==null?void 0:S.min)===void 0?"":String(r.scale.min),onSave:f=>d("min",f),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Max"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"auto",value:((A=r==null?void 0:r.scale)==null?void 0:A.max)==="auto"||((E=r==null?void 0:r.scale)==null?void 0:E.max)===void 0?"":String(r.scale.max),onSave:f=>d("max",f),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Step"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"auto",value:((C=r==null?void 0:r.scale)==null?void 0:C.stepSize)==="auto"||((D=r==null?void 0:r.scale)==null?void 0:D.stepSize)===void 0?"":String(r.scale.stepSize),onSave:f=>d("stepSize",f),className:""})})]})]})]})]})]})}function St(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>{var i;return(i=c.card)==null?void 0:i.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions();if(!t||["tornado","pyramid","kpi"].includes(t.type))return null;const l=s.AxisConfigurator.getAxisInfo(t.type,n);if(!l.hasXAxis&&!l.hasYAxis)return null;const o=(c,i)=>{const u={...n||{},[c==="x"?"xAxisConfig":"yAxisConfig"]:i};a(u);const m={...t,preferences:u};r(m)};return e.jsxs(s.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bs,{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(Es,{axis:"x",label:"X-Axis",type:l.xAxisType,config:n==null?void 0:n.xAxisConfig,onChange:c=>o("x",c)}),l.hasYAxis&&e.jsx(Es,{axis:"y",label:"Y-Axis",type:l.yAxisType,config:n==null?void 0:n.yAxisConfig,onChange:c=>o("y",c)})]})})]})}function wt(){const t=s.useEditorStore(u=>u.card),n=s.useEditorStore(u=>{var m,h,x,g;return(g=(x=(h=(m=u.card)==null?void 0:m.preferences)==null?void 0:h.chartOptions)==null?void 0:x.plugins)==null?void 0:g.legend}),{setLegendOptions:a}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r="bottom",l="center",o=!(t.type==="stackedBar"||t.type==="stackedLine"),c=(u,m)=>{const h={...n,[u]:m};a(h)},i=["top","bottom","left","right"],d=["start","center","end"];return e.jsxs(s.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Jt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:(n==null?void 0:n.display)??o,onCheckedChange:u=>c("display",u)})]}),((n==null?void 0:n.display)??o)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(n==null?void 0:n.position)||r,onValueChange:u=>c("position",u),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:i.map(u=>e.jsx(s.SelectItem,{value:u,className:"text-xs",children:s.titleCase(u)},u))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(s.Select,{value:(n==null?void 0:n.align)||l,onValueChange:u=>c("align",u),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:d.map(u=>e.jsx(s.SelectItem,{value:u,className:"text-xs",children:s.titleCase(u)},u))})]})]})]})]})})]})}function Dt(){var N,j,R,T,F,w,I,M,O;const t=s.useEditorStore(L=>L.card),n=s.useEditorStore(L=>{var P,B;return(B=(P=L.card)==null?void 0:P.preferences)==null?void 0:B.dataLabelsConfig}),a=s.useEditorStore(L=>{var P;return(P=L.card)==null?void 0:P.preferences}),{setCardPreferences:r,updateCardInFrame:l}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(t.type))return null;const o=((N=a==null?void 0:a.chartOptions)==null?void 0:N.indexAxis)==="y",c=t.type==="stackedBar"||t.type==="stackedLine",i=t.type==="pie"||t.type==="doughnut"||t.type==="polarArea"||t.type==="funnel",d=!i,u=(R=(j=a==null?void 0:a.chartOptions)==null?void 0:j.plugins)==null?void 0:R.datalabels,m=(u==null?void 0:u.display)!==!1&&((u==null?void 0:u.anchor)||(u==null?void 0:u.align)),h=(n==null?void 0:n.enabled)!==void 0?n.enabled:m,x=(L,P)=>{const B={...n,[L]:P},H={...t.preferences||{},dataLabelsConfig:B};r(H);const q={...t,preferences:H};l(q)},g=(L,P)=>{const B={...n,font:{...n==null?void 0:n.font,[L]:P}},H={...t.preferences||{},dataLabelsConfig:B};r(H);const q={...t,preferences:H};l(q)},v=(L,P)=>{const B={...n,formatOptions:{...n==null?void 0:n.formatOptions,[L]:P}},H={...t.preferences||{},dataLabelsConfig:B};r(H);const q={...t,preferences:H};l(q)},y=(()=>{const L=t.type;return L==="stackedBar"||L==="stackedLine"||L==="pie"||L==="doughnut"?"center":o?"right":"top"})();let b=[];c||i?b=["center"]:b=["auto",...(o?["center","left","right"]:["center","top","bottom"]).filter(P=>P!==y),"custom"];const S=()=>s.titleCase(y),A=["center","start","end"],E=["center","start","end","top","bottom"],C=d?["auto","number","currency","percent","none"]:["number","currency","percent","none"],D=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"GBP",label:"GBP - British Pound"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"INR",label:"INR - Indian Rupee"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"}],f=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"}];return e.jsxs(s.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ha,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:h,onCheckedChange:L=>x("enabled",L)})]}),h&&e.jsxs(e.Fragment,{children:[!c&&!i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(n==null?void 0:n.position)||"auto",onValueChange:L=>x("position",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:b.map(L=>e.jsx(s.SelectItem,{value:L,className:"text-xs",children:L==="auto"?S():L==="custom"?"Custom (Advanced)":s.titleCase(L)},L))})]})]}),c&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Show Total"}),e.jsx(s.SmallSwitch,{checked:(n==null?void 0:n.showTotal)??!1,onCheckedChange:L=>x("showTotal",L)})]}),(n==null?void 0:n.position)==="custom"&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Anchor"}),e.jsxs(s.Select,{value:(n==null?void 0:n.anchor)||"center",onValueChange:L=>x("anchor",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:A.map(L=>e.jsx(s.SelectItem,{value:L,className:"text-xs",children:s.titleCase(L)},L))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Align"}),e.jsxs(s.Select,{value:String((n==null?void 0:n.align)||"center"),onValueChange:L=>x("align",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:E.map(L=>e.jsx(s.SelectItem,{value:L,className:"text-xs",children:s.titleCase(L)},L))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(n==null?void 0:n.format)||(d?"auto":"none"),onValueChange:L=>x("format",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:C.map(L=>e.jsx(s.SelectItem,{value:L,className:"text-xs",children:L==="auto"&&d?"Auto (Use Axis)":L==="none"?"None (Raw Value)":s.titleCase(L)},L))})]})]}),(n==null?void 0:n.format)&&!["auto","none"].includes(n.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(n.format)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"0",value:String(((T=n==null?void 0:n.formatOptions)==null?void 0:T.decimalPlaces)??(n.format==="currency"?2:n.format==="percent"?1:0)),onSave:L=>v("decimalPlaces",Number(L)),className:""})})]}),n.format==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Currency"}),e.jsxs(s.Select,{value:((F=n==null?void 0:n.formatOptions)==null?void 0:F.currency)||"USD",onValueChange:L=>v("currency",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:D.map(L=>e.jsx(s.SelectItem,{value:L.value,className:"text-xs",children:L.label},L.value))})]})]}),["number","currency"].includes(n.format)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((w=n==null?void 0:n.formatOptions)==null?void 0:w.useSuffix)??!1,onCheckedChange:L=>v("useSuffix",L)})]}),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:((I=n==null?void 0:n.formatOptions)==null?void 0:I.locale)||"en-US",onValueChange:L=>v("locale",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:f.map(L=>e.jsx(s.SelectItem,{value:L.value,className:"text-xs",children:L.label},L.value))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Appearance"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Size"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"12",value:String(((M=n==null?void 0:n.font)==null?void 0:M.size)||12),onSave:L=>g("size",Number(L)),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Weight"}),e.jsxs(s.Select,{value:((O=n==null?void 0:n.font)==null?void 0:O.weight)||"normal",onValueChange:L=>g("weight",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(s.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Color"}),e.jsxs(s.Select,{value:(n==null?void 0:n.color)==="auto"||!(n!=null&&n.color)?"auto":"custom",onValueChange:L=>{L==="auto"&&x("color","auto")},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Smart Contrast)"}),e.jsx(s.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom (Coming Soon)"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Rotation"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"0",value:String((n==null?void 0:n.rotation)||0),onSave:L=>x("rotation",Number(L)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}function Cr(){return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Chart Configuration"}),e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:[e.jsx(Ct,{}),e.jsx(St,{}),e.jsx(wt,{}),e.jsx(Dt,{})]})]})}const Sr=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."]})]}),wr=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."]})]}),Dr=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 Tr(){const t=s.useEditorStore(a=>a.card.type);function n(a){const r=["kpi","table","text","map","custom"],l=o=>r.includes(a)?o:e.jsxs(e.Fragment,{children:[o,e.jsx(Cr,{})]});switch(a){case"stackedBar":case"stackedLine":return l(e.jsx(xr,{}));case"tornado":case"pyramid":return l(e.jsx(Ge,{docContent:Sr,cardType:a}));case"kpi":return e.jsx(ir,{});case"line":case"bar":return l(e.jsx(er,{cardType:a}));case"range":return l(e.jsx(Ge,{docContent:wr,cardType:a}));case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return l(e.jsx(Ge,{cardType:a}));case"bubble":case"scatter":return l(e.jsx(sr,{cardType:a}));case"table":return e.jsx(pr,{cardType:a});case"text":return e.jsx(Ge,{docContent:Dr,cardType:a,suffix:"Visual"});case"map":return e.jsx(mr,{});case"custom":return e.jsx(Qn,{});default:return l(e.jsx(nr,{}))}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[n(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function kr(){const t=k.useRef(null),n=k.useRef(null),a=s.useEditorStore(l=>l.isShowingVisual),r=s.useEditorStore(l=>l.showAIDialog);return k.useEffect(()=>{var l,o,c,i;r?((l=t.current)==null||l.resize(0),(o=n.current)==null||o.resize(0)):((c=t.current)==null||c.resize(25),(i=n.current)==null||i.resize(25))},[r]),e.jsxs(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(Mn,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:a&&!r?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:t,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(Tr,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(Ds,{})})]}):e.jsx(Ds,{})})]})}function Er(t){s.useAIInteractionStore(U=>U.currentAIContext);const[n,a]=k.useState(""),[r,l]=k.useState(null),{authToken:o,tokenProps:c}=s.useSemaphorContext(),i=s.useEditorStore(U=>{var ee;return(ee=U==null?void 0:U.card)==null?void 0:ee.sql}),d=s.useEditorStore(U=>U.isDevMode),u=s.useEditorStore(U=>{var ee;return(ee=U==null?void 0:U.card)==null?void 0:ee.python}),{setCardPython:m,setCardSql:h,setRunSql:x,switchCardType:g,setQueryConfig:v}=s.useEditorActions(),p=s.useEditorStore(U=>U.currentAssitantScope)||[],y=s.useEditorStore(U=>U.userInputForAI),b=s.useEditorStore(U=>U.triggerAIRun),S=s.useEditorStore(U=>U.card),A=s.useEditorStore(U=>U.selectedDatabaseName),E=s.useEditorStore(U=>U.selectedTableName),C=s.useEditorStore(U=>U.selectedConnectionId),D=s.useEditorStore(U=>U.selectedSchemaName),f=s.useDashboardStore(U=>U.dashboard.aiScopeTables),{errorMessage:N,refetch:j,data:R}=s.useDashboardCardQuery(S),{setTriggerAIRun:T,setCurrentAssitantScope:F,setCardConfig:w}=s.useEditorActions(),{selectedDatamodelName:I,connectionType:M,selectedDatamodelId:O}=s.useEditorAside(),{messages:L,setMessages:P,regenerate:B,error:H,sendMessage:q,status:z,addToolResult:Q,stop:X,clearError:se}=s.useChat({transport:new s.DefaultChatTransport({api:`${c.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${o==null?void 0:o.accessToken}`}),body:()=>{const U=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",isDevMode:d,aiContext:U.currentAIContext,reasoningEffort:U.reasoningEffort,showReasoning:U.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:U,body:ee})=>({body:{...ee,messages:s.cleanupIncompleteMessages(U)}})}),onError:U=>{var ee;if(U.name==="AbortError"||(ee=U.message)!=null&&ee.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)");return}console.error("[Editor Assistant] Stream error:",U)},onToolCall:te,onFinish({isAbort:U,isDisconnect:ee,isError:ce}){a(""),console.log(U?"[Editor Assistant] Stream aborted by user":ee?"[Editor Assistant] Stream disconnected (network error)":ce?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully")}});k.useEffect(()=>{b&&y&&(q({role:"user",parts:[{type:"text",text:y}]}),T(!1))},[b,y,q,T]);async function te({toolCall:U}){var ee,ce,le,fe,ue,$,G,V,Z,oe,de,ne,me,pe,Re,Le;if(["createChartFromSql","createForecast"].includes(U.toolName)){const De=((ee=U.input)==null?void 0:ee.sql)??((ce=U.args)==null?void 0:ce.sql),be=((le=U.input)==null?void 0:le.python)??((fe=U.args)==null?void 0:fe.python),J=((ue=U.input)==null?void 0:ue.chartType)??(($=U.args)==null?void 0:$.chartType);g(J),h(De),m(be),x(!0),Q({tool:U.toolName,toolCallId:U.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(U.toolName==="getUserSql"){if(!i){Q({tool:U.toolName,toolCallId:U.toolCallId,output:{status:"error",message:"No SQL found"}});return}Q({tool:U.toolName,toolCallId:U.toolCallId,output:{status:"success",sql:i,python:u||""}})}else if(U.toolName==="generateQueryConfig"){a("Generating query config...");const De=((G=U.input)==null?void 0:G.chartType)??((V=U.args)==null?void 0:V.chartType),be=((Z=U.input)==null?void 0:Z.queryConfig)??((oe=U.args)==null?void 0:oe.queryConfig);((de=U.input)==null?void 0:de.cardConfig)??((ne=U.args)==null||ne.cardConfig),g(De),w(be),h(void 0),m(void 0);const J=await j();if((me=J==null?void 0:J.data)!=null&&me.error){Q({tool:U.toolName,toolCallId:U.toolCallId,output:{status:"error",queryConfig:be,message:(pe=J==null?void 0:J.data)==null?void 0:pe.error.message}});return}if((Re=J==null?void 0:J.data)!=null&&Re.records){Q({tool:U.toolName,toolCallId:U.toolCallId,output:{status:"success",queryConfig:be,message:"The data has been visualized"}});return}Q({tool:U.toolName,toolCallId:U.toolCallId,output:{status:"success",queryConfig:be,message:"The data has been visualized",records:(Le=J==null?void 0:J.data)==null?void 0:Le.records}})}else a("Analyzing...")}function ie(U){const ee=s.removeFromScopeArray(p,U);K(ee)}function K(U){const ee=s.sanitizeAIScope(U);F(ee),P(ce=>[...ce,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(ee)}`}]}])}function Y(){const U={databaseName:A||"",schemaName:D||"",tableName:E||"",datamodelId:O||"",datamodelName:s.resolveDatamodelName(I),connectionId:C||"",connectionType:M||""},ee=s.dedup([...p,U]);K(ee)}function ae(){const U={databaseName:A||"",schemaName:D||"",tableName:E||"",datamodelName:s.resolveDatamodelName(I),connectionId:C||"",connectionType:M||"",datamodelId:O||""};if(!s.isInAiScopeArray([...f||[],...p],U)||p.length===0){const ce=s.dedup([...f||[],...p,U]).filter(le=>le.connectionId===U.connectionId);K(ce)}}const W=!["ready","error"].includes(z),re=s.getErrorMessage(H);return{messages:L,setMessages:P,sendMessage:q,regenerate:B,isLoading:W,handleSetAIScope:ae,handleAddCurrentTableToScope:Y,removeFromCurrentSelections:ie,currentAssitantScope:p,setCurrentAssitantScope:F,stop:X,status:z,toolStatus:n,llmUsage:r,onFinish:t,errorMessage:re,clearError:se}}const Ir=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Is({isFullscreen:t,onFullscreenChange:n,fullscreenContainer:a}){const r=k.useRef(null),[l,o]=k.useState(!1),[c,i]=k.useState(s.isDevEnv),[d,u]=k.useState(!1),[m,h]=k.useState(!1),[x,g]=k.useState(!1),v=t??x,p=s.useCurrentAIContext(),{setCurrentAIContext:y}=s.useAIActions(),{clearQueue:b}=s.useQueueActions(),{clearFileAttachments:S}=s.useFileActions(),A=s.useFileAttachments("editor"),E=s.useDashboardStore(J=>J.dashboard.aiContext),C=s.useEditorStore(J=>J.card.dataSource),D=s.useEditorStore(J=>J.actions.setCardSql),f=s.useEditorStore(J=>J.actions.setRunSql),N=s.useEditorStore(J=>J.showAIDialog),j=s.useDashboardStore(J=>J.handleOpenAssistantProfile),{setShowAIDialog:R,setCardPython:T}=s.useEditorActions(),{setDataSource:F}=s.useEditorActions(),{assistantProfile:w}=s.useAssistantProfile(),{messages:I,setMessages:M,sendMessage:O,isLoading:L,stop:P,status:B,llmUsage:H,errorMessage:q,clearError:z}=Er(),[Q,X]=k.useState(""),se=J=>{X(J.target.value)},te=J=>{J.preventDefault();const ge=Q.trim();if(!ge&&A.length===0)return;const Be=[];ge&&Be.push({type:"text",text:ge}),A.forEach(ke=>{ke.data&&Be.push({type:"file",mediaType:ke.type,filename:ke.name,url:`data:${ke.type};base64,${ke.data}`})}),O({role:"user",parts:Be}),X(""),S("editor"),le({force:!0})},{visibleMessages:ie,hasMoreMessages:K,totalMessageCount:Y,loadMoreMessages:ae,resetMessageWindow:W}=s.useMessageWindow(I,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:re,isAtBottom:U,hasNewMessages:ee,newMessageCount:ce,scrollToBottom:le,handleScroll:fe,resetNewMessageCount:ue}=s.useAutoScroll(ie,{threshold:50,delay:0,dependencies:[B,I.length]});k.useEffect(()=>{var J;N&&((J=r.current)==null||J.focus(),y({selectedEntities:(C==null?void 0:C.selectedEntities)||[]}))},[N,C,y]),s.useAutoSubmitQueue({assistantType:"editor",status:B,isLoading:L,sendMessage:O});const{hasActiveTools:$}=s.useActiveToolStatus(I),G=k.useCallback(J=>{n==null||n(J),t===void 0&&g(J)},[t,n]);k.useEffect(()=>{if(!v)return;function J(ge){ge.key==="Escape"&&G(!1)}return window.addEventListener("keydown",J),()=>{window.removeEventListener("keydown",J)}},[v,G]);const V=k.useCallback(J=>{O({role:"user",parts:[{type:"text",text:J}]}),le({force:!0})},[O,le]),Z=k.useCallback(async()=>{const J=JSON.stringify(I??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(J),s.ue.success("Conversation copied")}catch(ge){console.error("Failed to copy conversation",ge),s.ue.error("Unable to copy conversation")}},[I]),oe=k.useCallback(()=>{G(!v)},[v,G]);function de(J,ge){ge==="sql"?(D(J),f(!0)):ge==="python"&&(T(J),f(!0))}function ne(){p.selectedEntities.length===0&&y({selectedEntities:(E==null?void 0:E.selectedEntities)||[]})}function me(J){ne();const ge={role:"user",parts:[{type:"text",text:J.title+" "+J.subtitle}]};O(ge)}function pe(J){ne(),O({role:"user",parts:[{type:"text",text:J}]})}function Re(){return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuLabel,{children:"Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx(s.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:o,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:i,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:d,onCheckedChange:u,children:"System Message"})]})]})}function Le(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const De=(Q==null?void 0:Q.length)===0&&(I==null?void 0:I.filter(J=>J.role==="user").length)===0,be=e.jsxs("div",{"data-role":"editor-assistant",className:s.cn("flex h-full w-full flex-col justify-between px-6 py-4",v&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Le(),j&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:j,children:(w==null?void 0:w.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[Re(),c&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Z,children:"Copy Conversation"}),e.jsx(s.IconButton,{tooltip:v?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:oe,children:v?e.jsx(s.Minimize2,{className:"size-4"}):e.jsx(s.Maximize2,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{M([]),b("editor"),z(),W()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{R(!1)},children:e.jsx(s.X,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:re,className:"mt-2 flex w-full grow basis-0",onScroll:fe,children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[K&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:ae,className:"text-xs",children:["Load ",Math.min(5,Y-ie.length)," ","more messages (",Y-ie.length," ","hidden)"]})}),e.jsx(s.PrintMessages,{messages:ie,showTools:c,handleRun:de,showSystemMessage:d,onQuickReply:V,disableQuickReplies:L}),!$&&e.jsx(s.AssistantStatus,{status:B,errorMessage:q})]})}),!U&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{le({force:!0}),ue()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),ee&&ce>0&&e.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:ce>9?"9+":ce})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[De&&!w&&e.jsx(s.Placeholders,{onClick:me,placeholders:Ir}),e.jsx("div",{children:De&&w&&e.jsx(s.SeedQuestions,{seedQuestions:w.seedQuestions||[],handleSeedQuestionClick:pe})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:r,setInput:X,stop:P,input:Q,handleInputChange:se,handleSubmit:J=>{ne(),te(J),le({force:!0})},isLoading:L,status:B,assistantType:"editor",onFocus:()=>{}})]}),H&&l&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",H.inputTokens," prompt tokens, ",H.outputTokens," ","completion tokens, ",H.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(C==null?void 0:C.selectedEntities)||[],open:m,onOpenChange:h,dataSource:C||s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]});return v&&a?Ft.createPortal(e.jsx("div",{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:e.jsx("div",{className:"flex h-full w-full",children:be})}),a):be}function us(t,n){const[a,r]=k.useState(()=>{const l=localStorage.getItem(t);return l?JSON.parse(l):n});return k.useEffect(()=>{localStorage.setItem(t,JSON.stringify(a))},[a,t]),[a,r]}const Ar="chart-selector-standard-first";function Mr(){const[t,n]=us(Ar,!0);return{standardFirst:t,updatePreference:n}}const As=({pluginVisual:t,index:n,onSelect:a})=>{const r=Je(t.icon||""),l=t.name.charAt(0).toUpperCase(),o=s.getAutoDetectedChartIcon(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:a,className:"group flex items-center gap-2",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(r,{className:"h-4 w-4"}):o||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:l}),e.jsx("span",{children:t.name})]}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:"opacity-0 outline-none transition-opacity group-hover:opacity-100",children:e.jsx(s.Info,{className:"ml-1 h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"right",children:t.pluginName})]})]})},`${t.url}-${t.name}-${n}`)},Ms=["default","standardPlugin","customPlugin"];function Rr({selectedChart:t,onChartChange:n}){var E;const[a,r]=k.useState(!1),{data:l}=xt();Mr();const c=((E=s.useEditorStore(C=>C.card).customCardPreferences)==null?void 0:E.url)||"";rs(c);const{setCardType:i,setCardPreferences:d,setIsDevMode:u}=s.useEditorStore(C=>C.actions),{setCardCustomCfg:m,setCustomCardPreferences:h,setQueryConfig:x}=s.useEditorActions(),[g,v]=us("chart-section-active",null),p=k.useMemo(()=>g?[g,...Ms.filter(C=>C!==g)]:Ms,[g]);function y(C){m(null),d({}),i(C),["custom","map"].includes(C)&&(u(!0),x(void 0)),n(C),r(!1)}function b(C){m(null),d({}),i("custom"),h({type:"component",visualType:"single",url:C.url,componentName:C.name,icon:C.icon,pluginChartType:C.chartType}),x(void 0),n("custom"),r(!1)}const S=()=>{var D;if(t==="custom"){const f=s.useEditorStore.getState().card;return((D=f==null?void 0:f.customCardPreferences)==null?void 0:D.componentName)||"Custom Visual"}const C=s.chartTypes.find(f=>f.id===t);return(C==null?void 0:C.label)||"Select chart type"},A=()=>{var D,f;if(t==="custom"){const N=s.useEditorStore.getState().card,j=(D=N==null?void 0:N.customCardPreferences)==null?void 0:D.icon,R=(f=N==null?void 0:N.customCardPreferences)==null?void 0:f.componentName;if(j&&R)return e.jsx(Lr,{icon:j,componentName:R});if(R){const T=s.getAutoDetectedChartIcon(R);if(T)return T}return e.jsx(Ve,{className:"h-4 w-4"})}const C=s.chartTypes.find(N=>N.id===t);if(C){const N=C.icon;return e.jsx(N,{className:"h-4 w-4"})}return e.jsx(Ve,{className:"h-4 w-4"})};return e.jsx("div",{className:"",children:e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[A(),e.jsx("span",{children:S()})]}),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."}),p.map(C=>{if(C==="default")return e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center gap-2",children:"Default Visuals"})}),e.jsx(s.TooltipContent,{side:"right",children:"These are the standard visuals available in Semaphor"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="default",onCheckedChange:D=>v(D?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:s.chartTypes.map(D=>{const f=D.icon;return e.jsx(s.CommandItem,{value:`${D.label} ${D.id} chart graph visualization`,onSelect:()=>y(D.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(f,{className:"h-4 w-4"}),e.jsx("span",{children:D.label})]})},D.id)})},"default");if(C==="standardPlugin"){const D=l.filter(f=>f.pluginType==="standard");return D.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsx("p",{children:"Standard Visuals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="standardPlugin",onCheckedChange:f=>v(f?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:D.filter(f=>f.componentType==="chart").map((f,N)=>e.jsx(As,{pluginVisual:f,index:N,onSelect:()=>b(f)},`${f.url}-${f.name}-${N}`))},"standardPlugin"):null}if(C==="customPlugin"){const D=l.filter(f=>f.pluginType==="custom");return D.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-2",children:["Custom Visuals",e.jsx(s.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),e.jsx(s.TooltipContent,{side:"right",children:"External visuals that are specific to your project"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="customPlugin",onCheckedChange:f=>v(f?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:D.map((f,N)=>e.jsx(As,{pluginVisual:f,index:N,onSelect:()=>b(f)},`${f.url}-${f.name}-${N}`))},"customPlugin"):null}return null})]})]})})]})})}const Lr=({icon:t,componentName:n})=>{const a=Je(),r=s.getAutoDetectedChartIcon(n);return a?e.jsx(a,{className:"h-4 w-4"}):r||e.jsx(Ve,{className:"h-4 w-4"})},Fr=[{id:"table",icon:s.Table2,label:"Table"},{id:"bar",icon:s.ChartColumnIncreasing,label:"Bar Chart"},{id:"line",icon:s.ChartLine,label:"Line Chart"},{id:"stackedBar",icon:s.ChartColumnStacked,label:"Stacked Bar",requiresPivot:!0},{id:"pie",icon:s.ChartPie,label:"Pie Chart"},{id:"doughnut",icon:s.Donut,label:"Donut Chart"},{id:"kpi",icon:s.TiSortNumerically,label:"KPI"}];function Or({selectedChart:t,onChartChange:n}){var l;const a=s.useEditorStore(o=>o.card),r=((l=a==null?void 0:a.config)==null?void 0:l.pivotByColumns)&&a.config.pivotByColumns.length>0;return e.jsx("div",{className:"flex items-center justify-center gap-1",children:Fr.map(o=>{if(o.requiresPivot&&!r)return null;const c=o.icon,i=t===o.id;return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",onClick:()=>n(o.id),className:s.cn("h-8 w-8 p-0",i&&"bg-accent text-accent-foreground"),children:[e.jsx(c,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:o.label})]})}),e.jsx(s.TooltipContent,{side:"bottom",children:e.jsx("p",{children:o.label})})]},o.id)})})}const ms=({dataType:t})=>{const n=s.getDataType(t);return n==="string"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(qe,{className:"h-3 w-3"})}):n==="number"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(as,{className:"h-3 w-3"})}):n==="date"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(zs,{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 Pr({aliasTemplate:t,onAliasTemplateChange:n}){var d;const[a,r]=k.useState(t),[l,o]=k.useState(!1),c=(d=s.useEditorStore(u=>{var m;return(m=u.card.config)==null?void 0:m.pivotByColumns}))==null?void 0:d[0],i=c?`e.g. Min Sales in {{${c.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Input$1,{placeholder:i,value:l?a:t,onChange:u=>{r(u.target.value),o(!0)},onFocus:()=>o(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&l&&a!==t?(n(a),o(!1)):u.key==="Escape"&&(r(t),o(!1))},"aria-label":"Edit alias template"}),l&&a!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{n(a),o(!1)},children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(t),o(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function Br({valueAliases:t,onValueAliasesChange:n}){const[a,r]=k.useState(null),[l,o]=k.useState(""),[c,i]=k.useState(""),d=()=>{n({...t,"":""})},u=h=>{const x={...t};delete x[h],n(x)},m=h=>{const x={...t};delete x[h],x[l]=c,n(x),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(t).map(([h,x],g)=>e.jsx("div",{className:"flex items-center gap-2",children:a===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:l,onChange:v=>o(v.target.value),className:"h-8 w-24 text-xs",onPointerDown:v=>v.stopPropagation(),onKeyDown:v=>{v.key==="Enter"?m(h):v.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:v=>i(v.target.value),className:"h-8 w-24 text-xs",onPointerDown:v=>v.stopPropagation(),onKeyDown:v=>{v.key==="Enter"?m(h):v.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>m(h),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(x)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:x,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(x)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+g)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:d,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function Vr({column:t}){const n=s.useEditorStore(d=>d.card.type),a=s.useEditorStore(d=>{var u,m;return(m=(u=d.card)==null?void 0:u.config)==null?void 0:m.metricColumns}),r=(a==null?void 0:a.map(d=>d.label))||[],l=r==null?void 0:r.find(d=>d===t.label||d===t.name),o=l?r.indexOf(l):-1;function c(){return e.jsx("div",{className:"pr-1",children:l&&e.jsx(bt,{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(yt,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&c(),["pie","doughnut"].includes(n)&&i()]})}function zr({field:t,searchQuery:n="",limit:a=500}){const{authToken:r,tokenProps:l}=s.useSemaphorContext(),o=s.useEditorStore(u=>u.card),c=o==null?void 0:o.dataSource,i=["attribute-values",t.entityName,t.name,n,a],d=s.useQuery({queryKey:i,queryFn:async()=>{if(!(c!=null&&c.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const u={groupByColumns:[{...t,role:"groupby"}],metricColumns:[],filters:n?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:n}],groups:[]}:void 0,rowLimit:a},m={connection_id:c.connectionId,cardConfig:u,cardDataSource:c,cache_config:s.getCacheConfig({card:o})};console.log("requestBody",m);const h=await s.postRequestRegular(`${l.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",m);if(h!=null&&h.error)return console.error("Error fetching attribute values:",h.error),[];const x=t.name;return((h==null?void 0:h.records)||[]).map(v=>{const p=v[x]||v[t.alias||x]||v[t.label];return{id:p||"",value:p||"",label:String(p||"(empty)")}})}catch(u){return console.error("Error fetching attribute values:",u),[]}},enabled:!!t&&!!(c!=null&&c.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:d.data||[],isLoading:d.isLoading,isFetching:d.isFetching,isError:d.isError,error:d.error,refetch:d.refetch}}function Ur({open:t,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:l,onSave:o}){var A,E;const c=!!l,[i,d]=k.useState(c?"values":"fields"),[u,m]=k.useState(""),[h,x]=k.useState({id:(l==null?void 0:l.id)||s.v4(),field:(l==null?void 0:l.field)||null,selectedValues:l?Array.isArray(l.value)?l.value:[l.value]:[]}),g=a.filter(C=>{var f;return c?!1:!((f=r==null?void 0:r.conditions)==null?void 0:f.some(N=>N.field.id===C.id))&&C.label.toLowerCase().includes(u.toLowerCase())}),v=C=>{x({...h,field:C}),d("values")},p=()=>{if(h.field&&h.selectedValues.length>0){const C={id:h.id,field:h.field,operator:"in",value:h.selectedValues};let D;if(c){const f=((r==null?void 0:r.conditions)||[]).map(N=>N.id===l.id?C:N);D={...r,conditions:f}}else{const f=(r==null?void 0:r.conditions)||[];D={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...f,C],groups:[]}}o(D),n(!1)}},y=()=>{if(!c||!l)return;const C=((r==null?void 0:r.conditions)||[]).filter(D=>D.id!==l.id);if(C.length>0){const D={...r,conditions:C};o(D)}else o(void 0);n(!1)},b=C=>{x({...h,selectedValues:C})},S=()=>{c&&l?(x({id:l.id,field:l.field,selectedValues:Array.isArray(l.value)?l.value:[l.value]}),d("values")):(x({id:s.v4(),field:null,selectedValues:[]}),d("fields")),m("")};return k.useEffect(()=>{t&&S()},[t,c,l]),e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsx(s.DialogHeader,{children:e.jsx(s.DialogTitle,{children:c?`Edit Filter: ${(A=h.field)==null?void 0:A.label}`:i==="fields"?"Select Field to Filter":`Select Values for ${(E=h.field)==null?void 0:E.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!c&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&i==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Current Filters:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.conditions.map(C=>e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-muted rounded-md text-xs",children:[e.jsxs("span",{className:"font-medium",children:[C.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(C.value)?`${C.value.length} values`:String(C.value)})]},C.id))})]}),i==="fields"&&!c?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search fields...",value:u,onChange:C=>m(C.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:g.map(C=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>v(C),children:[e.jsx(ms,{dataType:s.getDataType(C.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:C.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[C.entityName,".",C.name]})]})]},C.id))}),g.length===0&&u&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',u,'"']}),g.length===0&&!u&&a.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(Gr,{field:h.field,selectedValues:h.selectedValues,onValuesChange:b,onBack:c?void 0:()=>d("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:c?e.jsx(s.Button,{variant:"destructive",onClick:y,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:S,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:p,disabled:!h.field||h.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function Gr({field:t,selectedValues:n,onValuesChange:a,onBack:r}){const[l,o]=k.useState(""),{values:c,isLoading:i,isFetching:d}=zr({field:t,searchQuery:l,limit:500}),u=l?c.filter(x=>String(x.value).toLowerCase().includes(l.toLowerCase())):c,m=x=>{const g=n.includes(x);a(g?n.filter(v=>v!==x):[...n,x])},h=()=>{n.length===u.length&&u.length>0?a([]):a(u.map(x=>x.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:r,children:"← Back"}),e.jsxs(s.Label,{className:"text-sm font-medium",children:["Select values for ",t.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search values...",value:l,onChange:x=>o(x.target.value),className:"pl-10"})]}),i||d?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx(s.Checkbox,{checked:n.length===u.length&&u.length>0,onCheckedChange:h}),e.jsxs(s.Label,{className:"text-sm",children:["Select All (",u.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:u.map(x=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>m(x.value),children:[e.jsx(s.Checkbox,{checked:n.includes(x.value),onCheckedChange:()=>m(x.value)}),e.jsx(cs,{className:"text-sm",children:x.label})]},x.id))})]})]})}function _r({field:t,zone:n,index:a,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:o=!1,cardType:c}){var xs,ps,fs;const{attributes:i,listeners:d,setNodeRef:u,transform:m,transition:h,isDragging:x}=s.useSortable({id:t.id}),g=s.useEditorStore(_=>_.card),{updateLabel:v,handleAggregationChange:p,handleDateFormatChange:y,handleGranularityChange:b,handleAliasTemplateChange:S,handleValueAliasesChange:A,removeField:E,handleKpiComparisonTypeChange:C,handleKpiShowTrendlineChange:D,handleKpiTrendlineWindowChange:f,handleKpiTrendlineGranularityChange:N,handleKpiTargetValueChange:j}=os(g),[R,T]=k.useState(!1),[F,w]=k.useState(!1),[I,M]=k.useState(null),[O,L]=k.useState(t.dateFormat||"YYYY-MM-DD"),[P,B]=k.useState(t.customFormat||""),[H,q]=k.useState(!!t.customFormat),[z,Q]=k.useState(t.granularity||"day"),[X,se]=k.useState(t.aliasTemplate||""),[te,ie]=k.useState(t.valueAliases||{}),[K,Y]=k.useState((xs=t.parameters)==null?void 0:xs.filters),ae=_=>{_==="custom"?q(!0):(q(!1),L(_),n==="groupBy"&&y(a,_,""))},W=_=>{B(_),n==="groupBy"&&y(a,"custom",_)},re=_=>{var je;Q(_);const xe=(je=Z(_)[0])==null?void 0:je.value;xe&&!H&&(L(xe),n==="groupBy"&&y(a,xe,"")),n==="groupBy"&&b(a,_)},U=_=>{se(_),n==="metrics"&&S(a,_)},ee=_=>{ie(_),n==="metrics"&&A(a,_)},ce=_=>{v(n,a,_)},le=_=>{var he;if(Y(_),n==="metrics"){const xe={...t,parameters:{...t.parameters,filters:_}},je=[...((he=g.config)==null?void 0:he.metricColumns)||[]];je[a]=xe,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:je})}w(!1)},fe=()=>{E(n,a)},ue={transform:s.CSS.Transform.toString(m),transition:h},$=s.getDataType(t.dataType),G=$==="date",V=c==="kpi",Z=_=>{switch(_){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..."}]}},oe=Z(z),de=n!=="pivotBy",ne=G&&n==="groupBy",me=!V&&G&&n==="groupBy",pe=V&&G&&n==="groupBy",Re=V&&n==="metrics"&&((ps=g.config)==null?void 0:ps.comparisonType)==="target",Le=n==="metrics",De=()=>e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:_=>{_.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),be=()=>de?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(we,{value:t.label??"",onSave:ce,placeholder:"Display label...",type:"text"})]}):null,J=()=>ne?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(s.Select,{value:z,onValueChange:re,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsx(s.SelectContent,{children:["day","week","month","quarter","year"].map(_=>e.jsx(s.SelectItem,{className:"text-xs",value:_,children:s.toTitleCase(_)},_))})]})]}):null,ge=()=>me?e.jsxs(e.Fragment,{children:[J(),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:H?"custom":O,onValueChange:ae,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:oe.map(_=>e.jsx(s.SelectItem,{className:"text-xs",value:_.value,children:_.label},_.value))})]}),H&&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:P,onChange:_=>{_.stopPropagation(),W(_.target.value)},onClick:_=>_.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,Be=()=>{var _,he,xe,je,Te;return pe?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:((_=g.config)==null?void 0:_.comparisonType)||"none",onValueChange:C,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"none",children:"No Comparison"}),e.jsx(s.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(s.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(s.SelectItem,{value:"target",children:"Target Value"})]})]})]}),e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(s.SmallSwitch,{checked:((he=g.config)==null?void 0:he.showTrendline)||!1,onCheckedChange:D})]})}),((xe=g.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:((je=g.config)==null?void 0:je.trendlineWindow)||30,onChange:ze=>{const Lt=parseInt(ze.target.value)||30;f(Lt)},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:((Te=g.config)==null?void 0:Te.trendlineGranularity)||"day",onValueChange:N,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"day",children:"Day"}),e.jsx(s.SelectItem,{value:"week",children:"Week"}),e.jsx(s.SelectItem,{value:"month",children:"Month"})]})]})]})]})]}):null},ke=()=>{var _,he;return Re?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(we,{value:((_=g.config)==null?void 0:_.targetValue)!==void 0&&((he=g.config)==null?void 0:he.targetValue)!==null?String(g.config.targetValue):"",onSave:xe=>{!isNaN(Number(xe))&&xe!==null?j(Number(xe)):j(0)},placeholder:"Enter target value...",type:"text"})]}):null},At=()=>Le?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:_=>{p(a,_)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(K==null?void 0:K.conditions)&&K.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:K.conditions.map(_=>e.jsxs("div",{className:"flex cursor-pointer items-center gap-2 rounded bg-muted/50 p-2 text-xs transition-colors hover:bg-muted/70",onClick:()=>{M(_),w(!0)},children:[e.jsxs("span",{className:"font-medium",children:[_.field.label,":"]}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"cursor-help text-muted-foreground",children:Array.isArray(_.value)?_.value.length===1?String(_.value[0]):_.value.length<=2?_.value.join(", "):`${_.value.slice(0,2).join(", ")} +${_.value.length-2}`:String(_.value)})}),Array.isArray(_.value)&&_.value.length>1&&e.jsx(s.TooltipContent,{side:"top",className:"max-w-[300px]",children:e.jsxs("div",{className:"text-xs",children:[e.jsxs("div",{className:"mb-1 font-medium",children:["Selected values (",_.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:_.value.map((he,xe)=>e.jsx("div",{children:String(he)},xe))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:he=>{var je;he.stopPropagation();const xe=K.conditions.filter(Te=>Te.id!==_.id);if(xe.length>0){const Te={...K,conditions:xe};le(Te)}else if(Y(void 0),n==="metrics"){const Te={...t,parameters:{...t.parameters,filters:void 0}},ze=[...((je=g.config)==null?void 0:je.metricColumns)||[]];ze[a]=Te,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:ze})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},_.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{M(null),w(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(Vr,{column:t}),o&&e.jsxs(e.Fragment,{children:[e.jsx(Pr,{aliasTemplate:X,onAliasTemplateChange:U}),e.jsx(Br,{valueAliases:te,onValueAliasesChange:ee})]})]}):null,{columns:Mt=[]}=s.useColumns(),Rt=(K==null?void 0:K.conditions)&&K.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:u,style:ue,...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 ${x?"z-50 scale-95 opacity-50":"border-slate-200"} ${n==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(ms,{dataType:$}),e.jsx(cs,{className:s.cn("w-[140px] flex-1 text-sm",Rt&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),n==="metrics"&&((fs=K==null?void 0:K.conditions)==null?void 0:fs.length)&&!R&&e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 text-xs",children:[e.jsx(s.Filter,{className:"h-3 w-3"}),e.jsx("span",{children:K.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:K.conditions.map(_=>e.jsxs("div",{children:[_.field.label,":"," ",Array.isArray(_.value)?`${_.value.length} values`:String(_.value)]},_.id))})})]})}),n!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:_=>{_.stopPropagation(),T(!R)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${R?"rotate-180":""}`})}),n==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:_=>{_.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const he=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",he),l(he)},children:r==="asc"?e.jsx(s.ArrowUp,{className:"h-3 w-3"}):e.jsx(s.ArrowDown,{className:"h-3 w-3"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:_=>{_.stopPropagation(),fe()},children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]}),R&&e.jsxs("div",{className:"space-y-3",children:[De(),be(),c==="kpi"&&J(),ge(),Be(),ke(),At()]})]}),F&&e.jsx(Ur,{open:F,onOpenChange:_=>{w(_),_||M(null)},availableFields:Mt,existingFilters:K,editingCondition:I,onSave:_=>{var he;if(_)le(_);else if(Y(void 0),n==="metrics"){const xe={...t,parameters:{...t.parameters,filters:void 0}},je=[...((he=g.config)==null?void 0:he.metricColumns)||[]];je[a]=xe,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:je})}M(null)}})]})}function Yr({concept:t}){const n=()=>{switch(t){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-100 text-xs font-medium dark:bg-blue-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/50 text-xs font-medium dark:bg-blue-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/30 text-xs font-medium dark:bg-blue-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/20 text-xs font-medium dark:bg-blue-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metrics = Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});default:return null}};return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(s.TooltipContent,{side:"right",align:"start",className:"p-3",children:n()})]})})}function _e({zone:t,fields:n,label:a,placeholder:r,shouldShow:l,hasPivotColumns:o=!1}){const{isOver:c,setNodeRef:i}=s.useDroppable({id:t}),{updateSortByColumn:d}=s.useEditorActions(),u=s.useEditorStore(v=>v.card),m=s.useEditorStore(v=>v.card.type),h=n.length>0,x=(v,p)=>{var b;!((b=u.config)!=null&&b.sortByColumns)||u.config.sortByColumns.findIndex(S=>S.id===v)===-1||d(u.id,v,{direction:p})};if(t==="sortBy"&&l===!1)return null;const g=t!=="sortBy"&&m!=="kpi";return e.jsxs("div",{className:"mb-4 w-full",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:a}),g&&e.jsx(Yr,{concept:t})]}),e.jsx("div",{ref:i,className:`rounded-lg border-2 border-dashed p-1 transition-all ${c?"border-blue-500 bg-blue-50 dark:bg-blue-950":h?"border-blue-200 bg-blue-50/30 dark:border-blue-800 dark:bg-blue-950/30":"min-h-[60px] border-muted-foreground/20 bg-background"}`,children:n.length===0?e.jsx("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:r}):e.jsx(s.SortableContext,{items:n.map(v=>v.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:n.map((v,p)=>{const b=v.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(_r,{field:v,zone:t,index:p,sortDirection:b,onSortDirectionChange:S=>x(v.id,S),hasPivotColumns:o,cardType:m})})},v.id)})})})})]})}const Rs=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],$r=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function es({value:t,onChange:n,label:a}){const[r,l]=k.useState(!1),[o,c]=k.useState(!1),i=()=>{const d=Rs.find(u=>u.value===t);return d?d.color:t.startsWith("#")?t:Rs[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:r,onOpenChange:l,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"size-5 rounded border-2 border-input shadow-sm transition-all hover:scale-110 hover:border-gray-400",style:{backgroundColor:i()},"aria-label":`Change color for ${a}`})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"grid grid-cols-3 items-center justify-items-center gap-1",children:$r.map(d=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",i()===d?"border-gray-900":"border-transparent"),style:{backgroundColor:d},onClick:()=>{n(d),l(!1)},children:e.jsx("span",{className:"sr-only",children:d})},d))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{c(!0),l(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a})]}),o&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>c(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Nt,{color:i(),onColorChange:d=>{n(d),c(!1)},onClose:()=>c(!1)})})]})]})}const Ye={difference:{label:"Difference",description:"Shows the exact difference between two values.",formula:"Primary - Secondary",example:"Sales increased by $5,000 compared to last year."},change:{label:"Change",description:"Shows the percentage increase or decrease between two values.",formula:"(Primary - Secondary) / Secondary × 100%",example:"Year-over-year sales change of 25%."},change_difference:{label:"Change (difference)",description:"Shows both the percentage change and the exact difference between two values.",formula:`% Change: (Primary - Secondary) / Secondary × 100%
|
|
270
|
-
Difference: Primary - Secondary`,example:"Sales grew by 25% ($5,000) compared to last year."},ratio:{label:"Ratio",description:"Shows how much of one value is covered by another — useful for quotas and benchmarks.",formula:"Primary / Secondary × 100%",example:"You've achieved 80% of your sales quota."}};function qr(){var i,d,u,m,h,x,g,v,p,y;const t=s.useEditorStore(b=>b.card),{setCardPreferences:n}=s.useEditorActions(),a=((i=t.config)==null?void 0:i.metricColumns)||[],r=((d=t.config)==null?void 0:d.groupByColumns)||[];if(!(t.type==="kpi"&&(a.length>=2&&r.length===0||a.length>=1&&r.length>0)))return null;const o=((m=(u=t.preferences)==null?void 0:u.kpiVisualOptions)==null?void 0:m.metricComparison)||{},c=b=>{var A;const S={...t.preferences,kpiVisualOptions:{...(A=t.preferences)==null?void 0:A.kpiVisualOptions,metricComparison:{...o,...b}}};n(S)};return e.jsxs(s.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ht,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(s.SmallSwitch,{id:"enable-comparison",checked:o.enabled||!1,onCheckedChange:b=>c({enabled:b,...b&&!o.calculationType?{calculationType:"difference"}:{}})})]}),o.enabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(s.Select,{value:o.calculationType||"difference",onValueChange:b=>c({calculationType:b}),children:[e.jsx(s.SelectTrigger,{id:"calculation-type",className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Object.entries(Ye).map(([b,S])=>e.jsx(s.SelectItem,{value:b,className:"text-xs",children:S.label},b))})]}),(()=>{var S,A,E;const b=o.calculationType||"difference";return e.jsxs("div",{className:"space-y-2 rounded-md bg-muted/50 p-2 text-xs",children:[e.jsx("p",{className:"text-muted-foreground",children:(S=Ye[b])==null?void 0:S.description}),e.jsxs("div",{className:"text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Formula:"})," ",e.jsx("code",{className:"rounded bg-background px-1 py-0.5 text-[10px]",children:(A=Ye[b])==null?void 0:A.formula})]}),e.jsxs("div",{className:"border-t pt-1 italic text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",(E=Ye[b])==null?void 0:E.example]})]})})()]}),e.jsx(ds,{formatOptions:o.formatOptions||{},onFormatOptionsChange:b=>c({formatOptions:b}),showTitle:!0,title:"COMPARISON FORMAT"}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:o.position||"left",onValueChange:b=>c({position:b}),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"top",className:"text-xs",children:"Top"}),e.jsx(s.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(s.SelectItem,{value:"right",className:"text-xs",children:"Right"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-arrow",checked:o.showArrow!==!1,onCheckedChange:b=>c({showArrow:b})}),e.jsx(s.Label,{htmlFor:"show-arrow",className:"cursor-pointer text-xs text-muted-foreground",children:"Arrow"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-color",checked:o.showColor!==!1,onCheckedChange:b=>c({showColor:b})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),o.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(es,{value:((h=o.colorConfig)==null?void 0:h.increase)||"green",onChange:b=>c({colorConfig:{...o.colorConfig,increase:b}}),label:"Primary > Secondary"}),e.jsx(es,{value:((x=o.colorConfig)==null?void 0:x.decrease)||"red",onChange:b=>c({colorConfig:{...o.colorConfig,decrease:b}}),label:"Primary < Secondary"}),e.jsx(es,{value:((g=o.colorConfig)==null?void 0:g.noChange)||"neutral",onChange:b=>c({colorConfig:{...o.colorConfig,noChange:b}}),label:"Primary = Secondary"})]})]}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"conditional-label",checked:o.conditionalLabel||!1,onCheckedChange:b=>c({conditionalLabel:b})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),o.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(s.Input,{id:"label-increase",type:"text",value:((v=o.conditionalLabels)==null?void 0:v.increase)??"Increase",onChange:b=>c({conditionalLabels:{...o.conditionalLabels,increase:b.target.value}}),placeholder:"Increase",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-decrease",className:"text-xs text-muted-foreground",children:["Primary ","<"," Secondary"]}),e.jsx(s.Input,{id:"label-decrease",type:"text",value:((p=o.conditionalLabels)==null?void 0:p.decrease)??"Decrease",onChange:b=>c({conditionalLabels:{...o.conditionalLabels,decrease:b.target.value}}),placeholder:"Decrease",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-no-change",className:"text-xs text-muted-foreground",children:"Primary = Secondary"}),e.jsx(s.Input,{id:"label-no-change",type:"text",value:((y=o.conditionalLabels)==null?void 0:y.noChange)??"No change",onChange:b=>c({conditionalLabels:{...o.conditionalLabels,noChange:b.target.value}}),placeholder:"No change",className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-name",className:"text-xs text-muted-foreground",children:"Name"}),e.jsx(s.Input,{id:"label-name",type:"text",value:o.labelName??"",onChange:b=>c({labelName:b.target.value}),placeholder:"e.g. Versus, Compared to",className:"h-7 text-xs"})]})]})]})]})]})}function Kr(){var l,o;const t=s.useEditorStore(c=>c.card),{setCardPreferences:n}=s.useEditorActions();if(t.type!=="kpi")return null;const a=((o=(l=t.preferences)==null?void 0:l.kpiVisualOptions)==null?void 0:o.formatOptions)||{},r=c=>{var d;const i={...t.preferences,kpiVisualOptions:{...(d=t.preferences)==null?void 0:d.kpiVisualOptions,formatOptions:c}};n(i)};return e.jsxs(s.AccordionItem,{value:"kpi-format",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(as,{className:"h-4 w-4"}),e.jsx("span",{children:"Number Format"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:e.jsx(ds,{formatOptions:a,onFormatOptionsChange:r,showTitle:!1})})]})}function Hr({groupByFields:t,pivotByFields:n,metricsFields:a,sortByFields:r}){const l=s.useEditorStore(v=>{var p;return((p=v.card.customCardPreferences)==null?void 0:p.url)&&v.card.type==="custom"}),o=s.useEditorStore(v=>v.card),c=o==null?void 0:o.type,i=t.length>0||a.length>0,d=c!=="kpi",u=c!=="kpi"&&i,m=["pie","doughnut","polar","funnel","aggregateTable"].includes(c),h=d&&!m,x=()=>c==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},g=()=>c==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs(s.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full",children:[e.jsxs(s.AccordionItem,{value:"fields",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.List,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsx(_e,{zone:"groupBy",fields:t,label:x().label,placeholder:x().placeholder}),h&&e.jsx(_e,{zone:"pivotBy",fields:n,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(_e,{zone:"metrics",fields:a,label:g().label,placeholder:g().placeholder,hasPivotColumns:n.length>0}),u&&e.jsx(_e,{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.Settings2,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"CONFIGURATION"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[e.jsx(Kr,{}),e.jsx(qr,{}),e.jsx(Ct,{}),e.jsx(St,{}),e.jsx(wt,{}),e.jsx(Dt,{})]})})]})]})}const Ls={getItem(t){if(typeof window>"u")return null;try{return localStorage.getItem(t)}catch(n){return console.warn(`Failed to read from localStorage (${t}):`,n),null}},setItem(t,n){if(!(typeof window>"u"))try{localStorage.setItem(t,n)}catch(a){console.warn(`Failed to write to localStorage (${t}):`,a)}}};function Wr({selectedChart:t,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:o}){const[c,i]=k.useState(()=>Ls.getItem("chart-selector-expanded")==="true"),d=s.useEditorStore(x=>x.card),u=a.length>0||r.length>0||l.length>0,{data:m}=s.useDashboardCardQuery(d);k.useEffect(()=>{Ls.setItem("chart-selector-expanded",String(c))},[c]);const h=()=>{i(x=>!x)};return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col border-x border-border",children:[e.jsxs("div",{className:s.cn("px-6 pt-4",{"space-y-4":c}),children:[e.jsx("div",{className:s.cn("overflow-hidden transition-all duration-300 ease-in-out",c?"max-h-[200px] opacity-100":"max-h-0 opacity-0"),children:c&&e.jsx(Rr,{selectedChart:t,onChartChange:n})}),e.jsxs("div",{"data-content":"Chart Quick Selector",className:"flex items-center justify-center gap-1",children:[e.jsx(Or,{selectedChart:t,onChartChange:n}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:h,className:"h-8 w-8 p-0","aria-label":c?"Hide all charts":"Show all charts",children:c?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})})}),e.jsx(s.TooltipContent,{side:"bottom",children:e.jsx("p",{children:c?"Hide dropdown":"Show all charts"})})]})]})]}),e.jsx("div",{className:s.cn("flex justify-end gap-2 px-6 py-6"),children:e.jsx("div",{className:s.cn("invisible flex gap-2",{visible:u||m}),children:e.jsx(ls,{})})}),e.jsxs(s.ScrollArea,{className:"w-full flex-1 basis-0 px-6 pb-6",children:[e.jsx(Hr,{groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:o}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Qr({initialFilters:t,availableFields:n}={}){const[a,r]=k.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(C=>C.card.dataSource);const{columns:l,isLoading:o}=s.useColumns(),i=n||l||[],d={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=C=>{const D=f=>{if(f.id===C){const N=i[0]||d,j=s.getDataType(N.dataType)==="date";return{...f,conditions:[...f.conditions,{id:`condition-${Date.now()}`,field:N,operator:j?"between":"=",value:j?[]:""}]}}return{...f,groups:f.groups.map(D)}};r(D(a))},m=C=>{const D=f=>{if(f.id===C){const N=i[0]||d,j=s.getDataType(N.dataType)==="date";return{...f,groups:[...f.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:N,operator:j?"between":"=",value:j?[]:""}],groups:[]}]}}return{...f,groups:f.groups.map(D)}};r(D(a))},h=(C,D)=>{const f=N=>N.id===C?{...N,conditions:N.conditions.filter(j=>j.id!==D)}:{...N,groups:N.groups.map(f)};r(f(a))},x=(C,D)=>{const f=N=>N.id===C?{...N,groups:N.groups.filter(j=>j.id!==D)}:{...N,groups:N.groups.map(f)};r(f(a))},g=(C,D,f,N)=>{if(f==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const j=R=>R.id===C?{...R,conditions:R.conditions.map(T=>T.id===D?{...T,[f]:N}:T)}:{...R,groups:R.groups.map(j)};r(j(a))},v=(C,D,f)=>{const N=j=>j.id===C?{...j,conditions:j.conditions.map(R=>R.id===D?{...R,...f}:R)}:{...j,groups:j.groups.map(N)};r(N(a))},p=(C,D)=>{const f=N=>N.id===C?{...N,logicalOperator:D}:{...N,groups:N.groups.map(f)};r(f(a))},y=(C,D)=>{const f=N=>N.id===C?{...N,negate:D}:{...N,groups:N.groups.map(f)};r(f(a))},b=(C,D,f)=>{const N=j=>j.id===C?{...j,conditions:s.arrayMove(j.conditions,D,f)}:{...j,groups:j.groups.map(N)};r(N(a))},S=(C,D,f)=>{const N=j=>j.id===C?{...j,groups:s.arrayMove(j.groups,D,f)}:{...j,groups:j.groups.map(N)};r(N(a))},A=C=>{if(!C||C.conditions.length===0&&C.groups.length===0)return"-- No filters defined";const D=N=>{let j="";typeof N.field=="object"?j=N.field.entityName?`${N.field.entityName}.${N.field.name}`:N.field.name:j=String(N.field);const R=N.operator;let T=N.value;if(N.field.dataType==="string"&&!["in","not in"].includes(N.operator))typeof T=="string"?T=`'${T}'`:Array.isArray(T)&&(T=`'${T.join(", ")}'`);else if(N.field.dataType==="date"||N.field.dataType==="datetime"||N.field.dataType==="timestamp")if(N.operator==="between"&&Array.isArray(T)&&T.length===2){const F=T[0]?`'${T[0]}'`:"NULL",w=T[1]?`'${T[1]}'`:"NULL";return`${j} BETWEEN ${F} AND ${w}`}else if((N.operator==="in"||N.operator==="not in")&&Array.isArray(T)){const F=T.map(w=>w?`'${w}'`:"NULL").join(", ");return`${j} ${R} (${F})`}else typeof T=="string"||T instanceof Date?T=`'${T}'`:Array.isArray(T)&&T.length>0&&(T=`'${T[0]}'`);else if(["in","not in"].includes(N.operator)){let F=[];Array.isArray(T)?F=T.map(w=>typeof w=="string"?`'${w}'`:String(w)):typeof T=="string"?F=T.split(",").map(w=>{const I=w.trim();return N.field.dataType==="string"?`'${I}'`:I}):typeof T=="number"&&(F=[String(T)]),T=`(${F.join(", ")})`}switch(R){case"contains":return typeof T=="string"?`${j} LIKE '%${T.replace(/'/g,"")}'`:`${j} LIKE '%${String(T)}'`;case"startsWith":return typeof T=="string"?`${j} LIKE '${T.replace(/'/g,"")}%'`:`${j} LIKE '${String(T)}%'`;case"endsWith":return typeof T=="string"?`${j} LIKE '%${T.replace(/'/g,"")}'`:`${j} LIKE '%${String(T)}'`;case"isNull":return`${j} IS NULL`;case"isNotNull":return`${j} IS NOT NULL`;default:return`${j} ${R} ${T}`}},f=N=>{const j=N.conditions.map(D),R=N.groups.map(I=>f(I)),T=[...j,...R].filter(Boolean);if(T.length===0)return"";const F=T.join(` ${N.logicalOperator} `),w=T.length>1?`(${F})`:F;return N.negate?`NOT ${w}`:w};return f(C)},E=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:i,isLoading:o,addCondition:u,addGroup:m,removeCondition:h,removeGroup:x,updateCondition:g,updateConditionFields:v,updateGroupOperator:p,updateGroupNegate:y,reorderConditions:b,reorderGroups:S,generateSQLPreview:A,hasAnyFilters:E}}function Jr({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",n),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const Xr=t=>{switch(t){case"table":return e.jsx(s.Table,{className:"h-3 w-3"});case"view":return e.jsx(s.Eye,{className:"h-3 w-3"});case"dataset":return e.jsx(s.ChartColumn,{className:"h-3 w-3"});case"file":return e.jsx(s.File,{className:"h-3 w-3"});default:return e.jsx(s.Table,{className:"h-3 w-3"})}},Zr=t=>{if(t.qualifiedEntityName){const n=t.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function el({value:t,onValueChange:n,availableFields:a,placeholder:r="Select field",className:l="w-64"}){const[o,c]=k.useState(!1),i=k.useMemo(()=>{const d={};return a.forEach(u=>{const m=Zr(u);d[m]||(d[m]={}),d[m][u.entityId]||(d[m][u.entityId]=[]),d[m][u.entityId].push(u)}),d},[a]);return e.jsxs(s.Popover,{modal:!0,open:o,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:s.cn("justify-between",!t&&"text-muted-foreground",l),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Jr,{children:[t.entityName,".",t.name]})}):r,e.jsx(s.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(s.CommandEmpty,{children:"No fields found."}),e.jsx(s.CommandList,{className:"max-h-80",children:Object.entries(i).map(([d,u])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),d]}),children:Object.entries(u).map(([m,h])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[Xr(h[0].entityType),e.jsx("span",{children:h[0].entityName})]}),h.map((x,g)=>e.jsxs(s.CommandItem,{value:x.id,onSelect:()=>{n(x),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)===x.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:x.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:x.description&&e.jsx("span",{children:x.description})})]})]},x.id+g))]},`${d}-${m}`))},d))})]})})]})}function hs(t){var p;const n=s.useEditorStore(y=>y.card),{authToken:a,tokenProps:r}=s.useSemaphorContext(),l=s.useEditorStore(y=>y.card.config),o=l==null?void 0:l.joinPlan,c={...t,alias:t.name,label:"value",role:"groupby"},i={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},d={...c,role:"sortby",direction:"asc"},u={joinPlan:o,groupByColumns:[c],metricColumns:[i],sortByColumns:[d]},m=((p=n.dataSource)==null?void 0:p.connectionId)||n.connectionId,{data:h,isPending:x,error:g}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular(`${r.apiServiceUrl}/v1/query`,(a==null?void 0:a.accessToken)||"",{connection_id:m,cardConfig:u,cardDataSource:n.dataSource})}catch(y){console.log(t),console.error("error",y)}},enabled:!!m,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((h==null?void 0:h.records)||[]).map(y=>({label:y.value||"BLANK",value:y.value||"BLANK",count:(y==null?void 0:y.count)||0})),isPending:x,error:g}}function sl({field:t,selected:n,onChange:a,placeholder:r="Select items...",className:l}){const[o,c]=ss.useState(!1),{filterValues:i}=hs(t),d=m=>{a(n.filter(h=>h!==m))},u=m=>{n.includes(m)?a(n.filter(h=>h!==m)):a([...n,m])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open:o,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:n.length>0?n.map(m=>{const h=i.find(x=>x.value===m);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[h==null?void 0:h.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:x=>{x.key==="Enter"&&d(m)},onMouseDown:x=>{x.preventDefault(),x.stopPropagation()},onClick:x=>{x.stopPropagation(),d(m)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},m)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No results found."}),e.jsx(s.CommandGroup,{children:i.map((m,h)=>e.jsxs(s.CommandItem,{onSelect:()=>u(m.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",n.includes(m.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.count})]})]},m.value+h))})]})]})})]})})}function tl({field:t,value:n,onChange:a,placeholder:r="Select value...",className:l}){const{filterValues:o,isPending:c,error:i}=hs(t);return c?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):i?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:n,onValueChange:a,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:n})}),e.jsx(s.SelectContent,{children:o.map((d,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+u))})]})}function al({value:t,operator:n,onChange:a,className:r}){var d;const{tokenProps:l}=s.useSemaphorContext(),o=(d=l==null?void 0:l.params)==null?void 0:d.timeZone,c=k.useMemo(()=>{if(t){if(n==="between"||n==="not between"){if(Array.isArray(t)&&t.length===2){const u=t[0]?new Date(t[0]):void 0,m=t[1]?new Date(t[1]):void 0;if(u&&m)return{from:u,to:m}}}else if(n==="="||n==="!="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:u}}}else if(n===">"||n===">="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:void 0}}}else if(n==="<"||n==="<="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:void 0,to:u}}}else if((n==="in"||n==="not in")&&Array.isArray(t)&&t.length>0){const u=new Date(t[0]),m=t.length>1?new Date(t[t.length-1]):u;if(!isNaN(u.getTime()))return{from:u,to:m}}}},[t,n]),i=u=>{if(!u){a(void 0);return}if(u.from&&u.to)a([u.from.toISOString(),u.to.toISOString()]);else if(u.from){const m=new Date(u.from);m.setHours(23,59,59,999),a([u.from.toISOString(),m.toISOString()])}else if(u.to){const m=new Date(u.to);m.setHours(0,0,0,0),a([m.toISOString(),u.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:c,onChange:i,timezone:o,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const nl=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],rl=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],ll=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],ol=["=","!=","isNull","isNotNull"],il=["between","isNull","isNotNull"],cl={"=":"Equals","!=":"Not Equals",">":"Greater Than",">=":"Greater Than or Equal","<":"Less Than","<=":"Less Than or Equal",contains:"Contains",startsWith:"Starts With",endsWith:"Ends With",in:"In","not in":"Not In",between:"Between",isNull:"Is Null",isNotNull:"Is Not Null"};function Fs(t){return cl[t]||s.titleCase(t)}function dl(t){switch(t){case"string":return rl;case"number":return ll;case"boolean":return ol;case"date":return il;default:return nl}}function Tt({condition:t,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:o,onUpdateGroupOperator:c,availableFields:i,updateConditionFields:d}){const{attributes:u,listeners:m,setNodeRef:h,transform:x,transition:g,isDragging:v}=s.useSortable({id:t.id}),{isPending:p,error:y}=hs(t.field),b={transform:s.CSS.Transform.toString(x),transition:g};return e.jsxs("div",{ref:h,style:b,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${v?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...m,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),n>0&&e.jsxs(s.Select,{value:r,onValueChange:S=>c(a,S),children:[e.jsx(s.SelectTrigger,{className:"w-24",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),n===0&&e.jsx("div",{className:"w-24"}),e.jsx(el,{value:t.field,onValueChange:S=>{const A=S,E=s.getDataType(A.dataType)==="date";d(a,t.id,{field:A,value:"",operator:E?"between":"="})},availableFields:i,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:S=>{S==="in"||S==="not in"?d(a,t.id,{operator:S,value:[]}):S==="isNull"||S==="isNotNull"?d(a,t.id,{operator:S,value:null}):d(a,t.id,{operator:S,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?Fs(t.operator):""})}),e.jsx(s.SelectContent,{children:dl(s.getDataType(t.field.dataType)).map(S=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:S,children:Fs(S)},S))})]}),t.operator==="isNull"||t.operator==="isNotNull"?e.jsx("div",{className:"flex-1"}):s.getDataType(t.field.dataType)==="string"?t.operator==="in"||t.operator==="not in"?p?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(sl,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(S=>typeof S=="string")?t.value:[],onChange:S=>d(a,t.id,{value:S}),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:S=>d(a,t.id,{value:S.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(tl,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:S=>d(a,t.id,{value:S}),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:S=>d(a,t.id,{value:S==="true"}),children:[e.jsx(s.SelectTrigger,{className:"flex-1",children:e.jsx(s.SelectValue,{placeholder:"Select value..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"true",children:"True"}),e.jsx(s.SelectItem,{value:"false",children:"False"})]})]}):s.getDataType(t.field.dataType)==="date"?e.jsx(al,{value:t.value,operator:t.operator,onChange:S=>d(a,t.id,{value:S}),className:"flex-1"}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:S=>l(a,t.id,"value",S.target.value),className:"flex-1",placeholder:t.operator==="in"||t.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>o(a,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function ul({group:t,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:o,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onReorderConditions:u,onReorderGroups:m,onAddCondition:h,onAddGroup:x,availableFields:g,renderFilterGroup:v,updateConditionFields:p}){const{attributes:y,listeners:b,setNodeRef:S,transform:A,transition:E,isDragging:C}=s.useSortable({id:t.id}),D={transform:s.CSS.Transform.toString(A),transition:E},f=j=>{const{active:R,over:T}=j;if(T&&R.id!==T.id){const F=t.conditions.findIndex(I=>I.id===R.id),w=t.conditions.findIndex(I=>I.id===T.id);F!==-1&&w!==-1&&u(t.id,F,w)}},N=j=>{const{active:R,over:T}=j;if(T&&R.id!==T.id&&a){const F=t.groups.findIndex(I=>I.id===R.id),w=t.groups.findIndex(I=>I.id===T.id);F!==-1&&w!==-1&&m(a,F,w)}};return e.jsxs("div",{ref:S,style:D,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${C?"z-50 opacity-50":""}`,children:[n>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...y,...b,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:j=>r(t.id,j),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>a&&o(a,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${n>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:f,children:e.jsx(s.SortableContext,{items:t.conditions.map(j=>j.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((j,R)=>e.jsx(Tt,{condition:j,index:R,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:g,updateConditionFields:p},j.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:N,children:e.jsx(s.SortableContext,{items:t.groups.map(j=>j.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(j=>v(j,n+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>x(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function ml({filters:t,availableFields:n,onSave:a,onClearAll:r,onCancel:l}){const{currentFilters:o,availableFields:c,isLoading:i,addCondition:d,addGroup:u,removeCondition:m,removeGroup:h,updateCondition:x,updateConditionFields:g,updateGroupOperator:v,updateGroupNegate:p,reorderConditions:y,reorderGroups:b,generateSQLPreview:S,hasAnyFilters:A,setCurrentFilters:E}=Qr({initialFilters:t,availableFields:n}),C=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[D,f]=k.useState(!1),N=(T,F,w)=>{const I=M=>M.id===T?{...M,conditions:M.conditions.map(O=>O.id===F?{...O,field:w,dataType:w.dataType}:O)}:{...M,groups:M.groups.map(I)};E(I(o))},j=(T,F=0,w)=>F===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:C,collisionDetection:s.closestCenter,onDragEnd:I=>{const{active:M,over:O}=I;if(O&&M.id!==O.id){const L=T.conditions.findIndex(B=>B.id===M.id),P=T.conditions.findIndex(B=>B.id===O.id);L!==-1&&P!==-1&&y(T.id,L,P)}},children:e.jsx(s.SortableContext,{items:T.conditions.map(I=>I.id),strategy:s.verticalListSortingStrategy,children:T.conditions.map((I,M)=>e.jsx(Tt,{condition:I,index:M,groupId:T.id,groupLogicalOperator:T.logicalOperator,onUpdateCondition:x,onUpdateField:N,onRemoveCondition:m,onUpdateGroupOperator:v,availableFields:c,updateConditionFields:g},I.id))})}),e.jsx(s.DndContext,{sensors:C,collisionDetection:s.closestCenter,onDragEnd:I=>{const{active:M,over:O}=I;if(O&&M.id!==O.id){const L=T.groups.findIndex(B=>B.id===M.id),P=T.groups.findIndex(B=>B.id===O.id);L!==-1&&P!==-1&&b(T.id,L,P)}},children:e.jsx(s.SortableContext,{items:T.groups.map(I=>I.id),strategy:s.verticalListSortingStrategy,children:T.groups.map(I=>j(I,F+1,T.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>d(T.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),D&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(T.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},T.id):e.jsx(ul,{group:T,depth:F,parentGroupId:w,onUpdateGroupOperator:v,onUpdateGroupNegate:p,onRemoveGroup:h,onUpdateCondition:x,onUpdateField:N,onRemoveCondition:m,onReorderConditions:y,onReorderGroups:b,onAddCondition:d,onAddGroup:u,availableFields:c,renderFilterGroup:j,updateConditionFields:g},T.id),R=s.getFilterCount(t);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Card,{children:e.jsx(s.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[i?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):j(o),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{id:"advanced-mode",checked:D,onCheckedChange:T=>f(T)}),e.jsx(s.Label,{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),A&&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:S(o)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:l,children:"Cancel"}),R>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>a(A?o:null),children:"Apply Filters"})]})]})}function hl({cardId:t,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:l,isOpen:o,onOpenChange:c}){const i=u=>{a(t,u),c(!1)},d=()=>{r(t),c(!1)};return e.jsxs(s.Dialog,{modal:!1,open:o,onOpenChange:c,children:[o&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:u=>{u.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Card Filters"}),e.jsx(s.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(ml,{filters:n,availableFields:l,onSave:i,onCancel:()=>c(!1),onClearAll:d})]})]})}function xl({activeCardId:t,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var g;const[l,o]=k.useState(null),c=s.useEditorStore(v=>v.card),i=(g=c==null?void 0:c.config)==null?void 0:g.joinPlan,d=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")],u=k.useCallback(v=>v.startsWith("card-")?null:v.startsWith("source-")||n.find(p=>p.id===v)?"source":a("groupBy").find(p=>p.id===v)?"groupBy":a("metrics").find(p=>p.id===v)?"metrics":a("pivotBy").find(p=>p.id===v)?"pivotBy":a("sortBy").find(p=>p.id===v)?"sortBy":null,[n,a]),m=k.useCallback(v=>{o(v.active.id)},[]),h=k.useCallback(v=>{const{active:p,over:y}=v;if(!y||!t){o(null);return}const b=p.id,S=y.id,A=u(b),E=u(S)||S;if(E==="sortBy"){if(A==="source"){const C=n.find(f=>f.id===b);if(!C){o(null);return}if(!(a("groupBy").some(f=>f.name===C.name&&f.qualifiedEntityName===C.qualifiedEntityName)||a("metrics").some(f=>f.name===C.name&&f.qualifiedEntityName===C.qualifiedEntityName))){o(null);return}}else if(A==="pivotBy"){o(null);return}else if(A!=="groupBy"&&A!=="metrics"&&A!=="sortBy"){o(null);return}}if(A==="source"&&E==="sortBy"){const C=[...n].find(N=>N.id===b);if(!C){o(null);return}const D=a("sortBy");if(s.fieldAlreadyExists(C,D)){o(null);return}const f=s.getNewField(C,"sortBy",D);o(null),r("sortBy",[...D,f]);return}if(A==="source"&&E!=="source"&&E!=="sortBy"){const C=[...n].find(j=>j.id===b);if(!C){o(null);return}const D=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")];if(D.length>0){const j=D[0].qualifiedEntityName;if(!j){o(null);return}if(j!==C.qualifiedEntityName&&C.qualifiedEntityName)if(i){if(!s.areEntitiesJoined(j,C.qualifiedEntityName,i)){s.showJoinRequiredNotification(),o(null);return}}else{s.showJoinRequiredNotification(),o(null);return}}const f=a(E);if(s.fieldAlreadyExists(C,f)){o(null);return}const N=s.getNewField(C,E,f);o(null),r(E,[...f,N]);return}if(A&&E&&A!=="source"&&E!=="source"&&A!==E){const C=a(A),D=a(E),f=C.find(R=>R.id===b);if(!f){o(null);return}const N=s.getNewField(f,E,D);if(o(null),E==="sortBy"){s.fieldAlreadyExists(f,D)||r(E,[...D,N]);return}const j=C.filter(R=>R.id!==b);r(A,j),r(E,[...D,N]);return}if(A&&E&&A===E&&A!=="source"){const C=a(A),D=C.findIndex(N=>N.id===b),f=C.findIndex(N=>N.id===S);if(D!==f){const N=s.arrayMove(C,D,f);r(A,N)}}o(null)},[t,n,a,r,u,i]),x=l?d.find(v=>v.id===l):null;return{activeId:l,activeField:x,handleDragStart:m,handleDragEnd:h}}function pl({activeView:t,onViewChange:n}){const a=s.useEditorStore(c=>c.card),{config:r}=k.useContext(s.SemaphorContext).tokenProps,l=(r==null?void 0:r.showInfoTab)!==!1,{errorMessage:o}=s.useDashboardCardQuery(a);return e.jsx(s.Tabs,{value:t,onValueChange:c=>n(c),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-1 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),a.type!=="kpi"&&l&&e.jsx(s.TabsTrigger,{value:"info",className:s.cn("rounded-md transition data-[state=active]:bg-muted",o&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:o?"Error":"Info"})]})})}const fl=[{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 gl(){var d,u;const t=s.useEditorStore(m=>m.card),{updateRowLimit:n}=s.useEditorActions(),[a,r]=k.useState(!1),[l,o]=k.useState(""),c=m=>{if(m==="custom"){r(!0);return}r(!1),n(t.id,parseInt(m))},i=m=>{const h=m.target.value;o(h),h&&!isNaN(parseInt(h))&&n(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:a?e.jsx(s.Input,{type:"number",value:l,onChange:i,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(d=t.config)==null?void 0:d.rowLimit)==null?void 0:u.toString())||"100",onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(s.SelectValue,{placeholder:"Select limit"})}),e.jsx(s.SelectContent,{children:fl.map(m=>e.jsx(s.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function jl({isOpen:t,onClose:n}){const a=qs(n,{enabled:t}),r=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.url)||""}),l=s.useEditorStore(m=>m.card),o=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.pluginChartType)||""}),c=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.settings)||{}}),{data:i}=s.useDashboardCardQuery(l),{getCard:d}=s.useCustomVisual(r),u=k.useMemo(()=>!r||r.trim()===""?null:d("Chart Settings"),[d,r]);return e.jsx("div",{ref:a,className:s.cn("absolute right-0 top-0 z-40 h-full w-[350px] border-l bg-background shadow-lg transition-transform duration-300",t?"translate-x-0":"translate-x-full"),style:{willChange:"transform"},tabIndex:t?0:-1,"aria-hidden":!t,children:e.jsxs("div",{className:"flex h-full flex-col p-4 px-5 pr-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Chart Settings"}),e.jsx(s.IconButton,{"aria-label":"Hide Chart Settings",tooltip:"Hide",onClick:n,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:u&&e.jsx(k.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(i==null?void 0:i.records)||[],chartType:o,settings:c})})})]})})}function vl({activeView:t,onViewChange:n,showDebug:a,onDebugToggle:r,onFiltersClick:l,activeCard:o,columns:c,columnsLoading:i,columnsError:d}){var K,Y,ae;const u=s.useEditorStore(W=>W.card),m=s.useDashboardStore(W=>W.filterValues);m!=null&&m.length;const{updateCardConfig:h,setCard:x,updateCardInFrame:g,setCardId:v,setShowAIDialog:p}=s.useEditorActions(),{updateCardId:y}=s.useDashboardActions(),[b,S]=k.useState(null),A=s.useEditorStore(W=>W.showAIDialog),E=s.useDashboardStore(W=>W.isVisualEditing),[C,D]=k.useState(!1),[f,N]=k.useState(!1),[j,R]=k.useState(null),{isConsoleMode:T}=s.useDashboardPreferences(),{config:F}=k.useContext(s.SemaphorContext).tokenProps,w=(F==null?void 0:F.showInfoTab)!==!1,I=s.useEditorStore(W=>{var re;return((re=W.card.customCardPreferences)==null?void 0:re.url)&&W.card.type==="custom"}),{data:M,errorMessage:O,isLoading:L,isFetching:P,errorSql:B,pagination:H,refetch:q}=s.useDashboardCardQuery(o),[z,Q]=k.useState(!1);k.useEffect(()=>{P||Q(!1)},[P]);const X=(W,re)=>{const U={...o,paginationConfig:{page:W+1,pageSize:re}};x(U),g(U)};function se(){return e.jsxs("div",{className:"relative border-b border-border bg-background p-4",children:[e.jsx("button",{onClick:r,className:"absolute right-4 top-4 rounded-md p-1 hover:bg-muted","aria-label":"Close Debug Panel",children:e.jsx(s.X,{className:"h-4 w-4"})}),e.jsxs("div",{className:"space-y-4 pr-8",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(u.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Dashboard Filters"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(m||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(o.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",c.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:i?"Loading...":d?"Error loading columns":JSON.stringify(c.slice(0,5),null,2)})]})]})]})}const te=W=>{if(!u.config)return;if(!W.length){h(u.id,{...u.config,sortByColumns:[]});return}const re=u.config,U=W.map(({id:ee,desc:ce})=>{var $,G;const le=($=re.metricColumns)==null?void 0:$.find(V=>V.label===ee),fe=(G=re.groupByColumns)==null?void 0:G.find(V=>V.label===ee),ue=le||fe;return ue?{id:s.getFieldId("sortBy",ue),name:ue.name,dataType:ue.dataType,label:ue.label,qualifiedEntityName:ue.qualifiedEntityName,entityId:ue.entityId,entityName:ue.entityName,entityType:ue.entityType,role:"sortby",direction:ce?"desc":"asc"}:null}).filter(ee=>ee!==null);h(u.id,{...re,sortByColumns:U})},ie=k.useMemo(()=>{var W,re;return(re=(W=u.config)==null?void 0:W.sortByColumns)==null?void 0:re.map(U=>({id:U.label,desc:U.direction==="desc"}))},[(K=u.config)==null?void 0:K.sortByColumns]);return e.jsxs("div",{className:s.cn("relative flex w-0 grow flex-col",{"border-l":A&&E}),children:[a&&se(),e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t==="chart"&&A&&e.jsx(pt,{variant:"outline"}),e.jsx(pl,{activeView:t,onViewChange:n}),e.jsx(s.FilterInfo,{cardId:o.id,cardFilters:(Y=o.config)==null?void 0:Y.filters,cardFilterCount:s.getFilterCount(((ae=o.config)==null?void 0:ae.filters)||null),onFiltersClick:l}),e.jsx("div",{className:"ml-2",children:e.jsx(gl,{})}),A&&e.jsx(ls,{})]}),e.jsxs("div",{className:s.cn("flex grow items-center justify-end gap-2"),children:[e.jsx(s.IconButton,{tooltip:"Refresh",disabled:L||P,onClick:()=>{Q(!0),q()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":z})})}),t==="chart"&&e.jsx(ft,{}),!A&&e.jsx(s.IconButton,{onClick:()=>p(!A),tooltip:"AI",className:"h-8","aria-label":"AI",children:e.jsx(s.Sparkles,{className:"size-4"})}),r&&s.isDevEnv]})]}),!C&&I&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>D(!0),className:"absolute right-5 top-1/2 z-40 size-10 -translate-y-1/2 rounded-full border border-border bg-background shadow-lg hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:e.jsx(s.Settings2,{className:"size-4"})}),e.jsxs("div",{className:"mt-3 flex grow flex-col",children:[t==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:e.jsx(gt,{})}),t==="table"&&(M==null?void 0:M.records)&&e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:e.jsx(s.TableVisual,{card:o,data:(M==null?void 0:M.records)||[],paginationMetadata:H,onPaginationChange:X,isLoading:L||P,onSortChange:te,sortState:ie})}),t==="info"&&w&&e.jsx("div",{className:"px-6",children:e.jsxs("div",{className:"rounded-md bg-background",children:[e.jsxs("div",{className:"mb-2",children:[T&&e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Card ID:"}),e.jsx(s.EditableText,{value:u.id,onSave:W=>{const re=s.sanitizeCardId(W);if(!re){S("Card ID cannot be empty");return}const U=y(u.id,re);if(U.success){v(re);const ee={...u,id:re};x(ee),g(ee),S(null),s.ue.success("Card ID updated successfully")}else S(U.error||"Failed to update Card ID"),s.ue.error(U.error||"Failed to update Card ID")},isEditable:!0,placeholder:"Enter card ID",displayClassName:"font-mono text-xs text-muted-foreground hover:text-foreground",inputClassName:"font-mono text-xs"}),e.jsx(s.CopyButton,{text:u.id,className:"h-5 w-5"})]}),b&&e.jsx("p",{className:"text-xs text-destructive",children:b})]}),O||B?e.jsx(ct,{error:O,errorSql:B,onSendFeedback:()=>{const W=s.prepareFeedbackData(s.FeedbackCategory.QUERY_GENERATION,{cardConfig:u.config,dataSource:o.dataSource,dashboardFilters:m,errorMessage:O,errorSql:B,generatedSql:M==null?void 0:M.sql});R(W),N(!0)}}):e.jsxs(e.Fragment,{children:[(M==null?void 0:M.sql)&&e.jsx("h3",{className:"mb-1 px-2 font-mono text-xs font-medium",children:"Generated SQL Query"}),e.jsx(dt,{sql:M==null?void 0:M.sql,error:O,errorSql:B})]})]})})]}),e.jsx(jl,{isOpen:C,onClose:()=>D(!1)}),j&&e.jsx(s.FeedbackDialog,{open:f,onOpenChange:N,feedbackData:j})]})]})}function bl({activeField:t}){const[n,a]=k.useState(!0);return k.useEffect(()=>{t&&a(!0)},[t]),t?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${n?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(s.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(ms,{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 yl=()=>{const t=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||t.apply(console,r)};const n=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},a=r=>{var l;if((l=r.reason)!=null&&l.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",n,!0),window.addEventListener("unhandledrejection",a,!0),()=>{console.error=t,window.removeEventListener("error",n,!0),window.removeEventListener("unhandledrejection",a,!0)}};function Nl(){var B,H;const[t,n]=k.useState("chart"),[a,r]=k.useState(!1),[l,o]=k.useState(!1),[c,i]=k.useState(!0),d=s.useEditorStore(q=>q.showAIDialog),u=s.useDashboardStore(q=>q.isVisualEditing),{setCardType:m}=s.useEditorActions(),h=s.useEditorStore(q=>q.card.type);k.useEffect(()=>yl(),[]);const x=q=>{m(q)},g=s.useEditorStore(q=>q.frame),v=s.useEditorStore(q=>q.card);s.useEditorStore(q=>q.activeTabCardId),s.useEditorStore(q=>q.actions.getAvailableFields);const{addCard:p,removeCard:y,updateCard:b,setActiveCard:S,updateFilters:A}=s.useEditorActions(),{columns:E=[],isLoading:C,error:D}=s.useColumns(),f=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),N=v,{getFieldsForContainer:j,setFieldsForContainer:R}=os(N),{activeField:T,handleDragStart:F,handleDragEnd:w}=xl({activeCardId:g.activeCardId,sourceFields:E,getFieldsForContainer:j,setFieldsForContainer:R}),I=(q,z)=>{z&&A(q,z)},M=q=>{var z;b(q,{config:{...(z=g.cards.find(Q=>Q.id===q))==null?void 0:z.config,filters:void 0}})},O=E,L=q=>{if(!q)return 0;let z=q.conditions.length;return q.groups.forEach(Q=>{z+=L(Q)}),z},P=L(((B=N==null?void 0:N.config)==null?void 0:B.filters)||null);return e.jsxs(s.DndContext,{sensors:f,collisionDetection:s.closestCenter,onDragStart:F,onDragEnd:w,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(it,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(Wr,{selectedChart:h,onChartChange:x,groupByFields:j("groupBy"),pivotByFields:j("pivotBy"),metricsFields:j("metrics"),sortByFields:j("sortBy")}),e.jsx(vl,{selectedChart:h,activeView:t,onViewChange:n,showDebug:a,onDebugToggle:()=>r(!a),onFiltersClick:()=>o(!0),filterCount:P,activeCard:N,dataSourceState:v.dataSource||s.EMPTY_DATA_SOURCE,columns:E,columnsLoading:C,columnsError:D,getFieldsForContainer:j,cards:g.cards,activeCardId:g.activeCardId,addCard:p,setActiveCard:S})]}),!c&&u&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>i(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),N&&e.jsx(hl,{cardId:N.id,filters:((H=N.config)==null?void 0:H.filters)||null,onFiltersChange:I,onClearFilters:M,availableFields:O,isOpen:l,onOpenChange:o}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(bl,{activeField:T||null})})]})}function Cl({authToken:t,onSave:n,onClose:a}){const r=k.useRef(null),l=s.useEditorStore(D=>D.showAIDialog),o=s.useEditorStore(D=>D.isDevMode),c=s.useAssistantLayoutStore(D=>D.setFullscreen),i=s.useAssistantLayoutStore(D=>D.setPanelOpen),d=s.useAssistantLayoutStore(D=>D.setContainer),u=s.useAssistantPanel("editor"),m=s.useFullscreenAssistant(),h=s.useAssistantContainer("editor"),x=m==="editor",g=k.useCallback(D=>{d("editor",D)},[d]),{setAuthToken:v}=s.useDashboardActions(),{setShowAIDialog:p,setOnSave:y,setOnClose:b}=s.useEditorActions(),{setActiveAssistantType:S}=s.useAIActions();k.useEffect(()=>{n&&y(n),a&&b(a)},[n,y,a,b]),k.useEffect(()=>{t&&t.accessToken&&v(t)},[t,v]),k.useEffect(()=>{var D,f;l?((D=r.current)==null||D.resize(40),i("editor",!0),S("editor")):((f=r.current)==null||f.resize(0),i("editor",!1),m==="editor"&&c(null),S(null))},[l,i,S,c,m]);function A(D){D<1?(p(!1),i("editor",!1),m==="editor"&&c(null),S(null)):(l||(p(!0),S("editor")),u.isOpen||i("editor",!0))}function E(){return e.jsxs(e.Fragment,{children:[e.jsx(it,{isVisible:!0,onToggleVisibility:()=>{}}),e.jsxs("div",{className:"relative flex grow border-l",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:s.cn("grow transition-opacity",x&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(kr,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:A,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Is,{isFullscreen:x,onFullscreenChange:D=>c(D?"editor":null),fullscreenContainer:h})})})]}),e.jsx("div",{ref:g,className:s.cn("absolute inset-0",!x&&"pointer-events-none")})]})]})}function C(){return e.jsxs("div",{className:"relative flex h-full grow",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:s.cn("flex grow transition-opacity",x&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Nl,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:A,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Is,{isFullscreen:x,onFullscreenChange:D=>c(D?"editor":null),fullscreenContainer:h})})})]}),e.jsx("div",{ref:g,className:s.cn("absolute inset-0",!x&&"pointer-events-none")})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:o?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:E()}):C()})}function Sl(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:n}=s.useDashboardStore(c=>c.actions),a=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function l(c){t&&(r(t,c),n(!1))}function o(){n(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!a}),children:e.jsx(Cl,{onSave:l,onClose:o})})}function wl(){ot();const t=s.useDashboardStore(d=>d.selectedSheetId),n=s.useDashboardStore(d=>d.selectedFrameId),a=s.useDashboardStore(d=>d.dashboard),r=s.useDashboardStore(d=>d.actions.getSelectedFrame),{setSelectedFrameId:l}=s.useDashboardActions(),{setCard:o}=s.useEditorActions(),c=s.useEditorStore(d=>d.card.dataSource);return k.useEffect(()=>{var u,m;let d=r();if(!d){const h=(u=a==null?void 0:a.sheets)==null?void 0:u.find(g=>g.id===t),x=(m=h==null?void 0:h.frames)==null?void 0:m[0];x&&(l(x.id),d=x)}if(d){const h=d.cards.find(x=>x.id===d.activeCardId);h&&o(h)}},[r,t,n,a,l,o]),{hasEntities:!!(c!=null&&c.selectedEntities&&c.selectedEntities.length>0)}}function Dl(){const t=s.useDashboardStore(a=>a.actions.setShowFilters),{hasEntities:n}=wl();return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[e.jsx(s.Label,{className:"px-2 text-base",children:"Dashboard Filters"}),e.jsx(s.Button,{onClick:()=>t(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(s.Cross2Icon,{})})]}),!n&&e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-muted-foreground/50"}),e.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"No fields configured"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Please configure a data source for this card to enable filtering"})]}),n&&e.jsx("div",{className:"flex grow",children:e.jsx(s.DndContext,{collisionDetection:s.closestCenter,children:e.jsx(s.SortableContext,{items:[],strategy:s.verticalListSortingStrategy,children:e.jsx(lt,{context:"filter"})})})})]})}function Tl(){const t=s.useDashboardStore(r=>r.dashboard.filters),n=s.useDashboardStore(r=>r.theme),a=t==null?void 0:t.filter(r=>r.hide);return a!=null&&a.length?e.jsx("div",{className:s.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":n==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":n==="dark"}),children:a==null?void 0:a.map(r=>e.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[e.jsx(s.FilterHeader,{filter:r}),e.jsx(s.FilterComponent,{filter:r})]},r.id))}):null}function kl(){const t=s.useDashboardStore(r=>r.showFilters),n=s.useDashboardStore(r=>r.isVisualEditing),a=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":n,"flex grow overflow-auto":!n}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[a&&e.jsx(Tl,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Dl,{})})]})}function El(){const t=s.useDashboardStore(l=>l.dashboard),n=s.useDashboardStore(l=>l.actions.setDashboard),a=s.useDashboardStore(l=>l.showDashboardJSON),r=s.useDashboardStore(l=>l.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!a}),children:[e.jsxs(s.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(s.de,{onChange:l=>{if(l)try{JSON.parse(l),n(JSON.parse(l))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(t,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function kt(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4",children:[e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"space-y-2",children:[...Array(4)].map((t,n)=>e.jsx("div",{className:"animate-pulse",children:e.jsxs("div",{className:"group relative flex items-start gap-3 px-4 py-3",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-muted"})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("div",{className:"h-4 w-32 rounded bg-muted"})}),e.jsx("div",{className:"shrink-0",children:e.jsx("div",{className:"h-3.5 w-3.5 rounded bg-muted"})})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-3 w-48 rounded bg-muted"})})]}),e.jsx("div",{className:"absolute right-3 top-2",children:e.jsx("div",{className:"flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:e.jsx("div",{className:"h-6 w-6 rounded bg-muted"})})})]})]})},n))})]})})}const Il=t=>{const n=s.useDashboardStore(l=>l.isVisualEditing),a=s.useDashboardStore(l=>l.selectedFrameId),r=s.useEditorStore(l=>l.frame);return!!(n&&a&&(r==null?void 0:r.visualId)===t)};function Al({visual:t,isDeleting:n,isDuplicating:a,onAddVisual:r,onOpenVisual:l,onEditDetails:o,onDeleteClick:c,onDuplicateVisual:i,onShareVisual:d,formatDate:u}){var C,D,f,N;const{selectVisual:m}=s.useManagementActions(),h=s.useIsVisualSelected(t.id),x=Il(t.id),{isConsoleMode:g}=s.useDashboardPreferences(),v=k.useRef(null),[p,y]=k.useState(!1),[b,S]=k.useState(!1);k.useEffect(()=>{a?(y(!0),S(!0)):b&&(y(!1),S(!1))},[a,b]),k.useEffect(()=>{x&&v.current&&v.current.scrollIntoView({behavior:"smooth",block:"center"})},[x]);const A=()=>e.jsx(We,{className:"h-4 w-4"}),E=()=>{m(t),l==null||l(t)};return e.jsx(s.Card,{ref:v,className:s.cn("group cursor-pointer border border-border/50 p-3 transition-colors hover:bg-accent/50",x?"border-purple-500":h&&"border-primary"),onClick:E,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 rounded bg-muted p-1.5",children:A()}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium text-foreground truncate",title:t.title||"Untitled Visual",children:t.title||"Untitled Visual"}),t.ownership.status==="shared"&&e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:[e.jsx(s.Users,{className:"mr-1 h-2.5 w-2.5"}),"Shared"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",title:t.description||"No description",children:(C=t.description)!=null&&C.trim()?t.description:"No description"})]}),e.jsxs("div",{className:s.cn("invisible ml-2 flex flex-shrink-0 items-center gap-1 transition-opacity duration-150 group-hover:visible",h&&"visible"),onClick:j=>j.stopPropagation(),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:j=>{j.stopPropagation(),r(t)},title:"Add to dashboard",children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),t.ownership.isOwner&&e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:j=>{j.stopPropagation(),o==null||o(t)},title:"Edit details",children:e.jsx($e,{className:"h-3 w-3"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:p,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",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:j=>{j.stopPropagation(),r(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:j=>{j.stopPropagation(),l==null||l(t)},children:[e.jsx(Kt,{className:"mr-2 h-3 w-3"}),"Open"]}),e.jsxs(s.DropdownMenuItem,{onClick:j=>{j.preventDefault(),j.stopPropagation(),i(t.id)},disabled:a,children:[a?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),a?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:j=>{j.stopPropagation(),o==null||o(t)},children:[e.jsx($e,{className:"mr-2 h-3 w-3"}),"Edit details"]}),e.jsxs(s.DropdownMenuItem,{onClick:j=>{j.stopPropagation(),d(t)},children:[e.jsx(s.Users,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:j=>{j.stopPropagation(),c(t)},className:"text-destructive",disabled:n,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),n?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((D=t.ownership.createdBy)==null?void 0:D.type)==="tenant"||((f=t.ownership.createdBy)==null?void 0:f.type)==="organization"&&g)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.User,{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 Et({open:t,resourceLabel:n,initialTitle:a,initialDescription:r="",onClose:l,onSave:o,isSaving:c=!1}){const[i,d]=k.useState(a),[u,m]=k.useState(r??"");k.useEffect(()=>{t&&(d(a),m(r??""))},[t,a,r]);const h=x=>{x.preventDefault();const g=i.trim();g&&o({title:g,description:u.trim()})};return e.jsx(s.Dialog,{open:t,onOpenChange:x=>x?null:l(),children:e.jsx(s.DialogContent,{className:"sm:max-w-md",children:e.jsxs("form",{onSubmit:h,className:"space-y-4",children:[e.jsxs(s.DialogHeader,{children:[e.jsxs(s.DialogTitle,{children:["Edit ",n]}),e.jsxs(s.DialogDescription,{children:["Update the title and description for this ",n.toLowerCase(),"."]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"resource-title",children:"Title"}),e.jsx(s.Input,{id:"resource-title",value:i,onChange:x=>d(x.target.value),placeholder:`Enter ${n.toLowerCase()} title`,autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"resource-description",children:"Description"}),e.jsx(s.Textarea,{id:"resource-description",value:u,onChange:x=>m(x.target.value),placeholder:`Enter ${n.toLowerCase()} description (optional)`,rows:3})]}),e.jsxs(s.DialogFooter,{className:"mt-6 flex justify-end gap-2 sm:justify-end",children:[e.jsx(s.Button,{type:"button",variant:"outline",onClick:l,disabled:c,children:"Cancel"}),e.jsx(s.Button,{type:"submit",disabled:c||!i.trim(),children:c?"Saving...":"Save changes"})]})]})})})}function Ml({open:t,onOpenChange:n,onSubmit:a,isCreating:r}){const[l,o]=k.useState(""),[c,i]=k.useState("");k.useEffect(()=>{t||(o(""),i(""))},[t]);const d=()=>{l.trim()&&a({title:l,description:c})},u=m=>{n(m)};return e.jsx(s.Dialog,{open:t,onOpenChange:u,children:e.jsxs(s.DialogContent,{children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create New Visual"}),e.jsx(s.DialogDescription,{children:"Add a new visual to your library. You can configure it after creation."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",children:"Visual Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:l,onChange:m=>o(m.target.value),disabled:r,onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),d())}})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter visual description...",value:c,onChange:m=>i(m.target.value),disabled:r})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>u(!1),disabled:r,children:"Cancel"}),e.jsx(s.Button,{onClick:d,disabled:!l.trim()||r,children:r?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Visual"})]})]})})}function Rl(){const[t,n]=k.useState(""),[a,r]=k.useState(!1),[l,o]=k.useState(!1),[c,i]=k.useState(null),[d,u]=k.useState(!1),[m,h]=k.useState(null),[x,g]=k.useState(null),[v,p]=k.useState(null),{selectVisual:y}=s.useManagementActions(),{handleEditLibraryVisual:b,handleAddLibraryVisual:S}=Ae(),{resources:A,isLoading:E,isError:C,createResource:D,updateResource:f,deleteResource:N,duplicateResource:j,isCreating:R,isDeleting:T}=s.useVisualManagement(()=>{u(!1),h(null)},Y=>{r(!1),Y&&(y(Y),b(Y))});s.useCurrentUserInfo();const F=A.filter(Y=>{var ae,W;return((ae=Y==null?void 0:Y.title)==null?void 0:ae.toLowerCase().includes(t.toLowerCase()))||((W=Y==null?void 0:Y.description)==null?void 0:W.toLowerCase().includes(t.toLowerCase()))}),w=Y=>new Date(Y).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),I=Y=>{D({title:Y.title,description:Y.description,isPrivate:!1})},M=Y=>{h(Y),u(!0)},O=()=>{m&&N(m.id)},{startUpdating:L,stopUpdating:P,isUpdating:B}=s.useResourceUpdateState(),H=(Y,ae,W)=>{var ce;const re=Object.fromEntries(Object.entries(ae).filter(([,le])=>le!==void 0));if(Object.keys(re).length===0){(ce=W==null?void 0:W.onSuccess)==null||ce.call(W);return}const U=Object.keys(re),ee=U.length===1?U[0]:void 0;L(Y,ee),f({resourceId:Y,data:re},{onSuccess:()=>{var le;P(Y,ee),(le=W==null?void 0:W.onSuccess)==null||le.call(W)},onError:()=>{var le;P(Y,ee),(le=W==null?void 0:W.onError)==null||le.call(W)}})},q=Y=>{g(Y),j(Y,{onSettled:()=>g(null)})},z=Y=>{b(Y)},Q=Y=>{S(Y)},X=Y=>{const ae=A.find(W=>W.id===Y);ae&&f({resourceId:Y,data:{isPrivate:!ae.isPrivate}})},se=Y=>{i(Y),o(!0)},te=Y=>{p(Y)},ie=()=>{p(null)},K=({title:Y,description:ae})=>{if(!v)return;const W={};Y!==v.title&&(W.title=Y),(v.description||"")!==ae&&(W.description=ae),H(v.id,W,{onSuccess:()=>{p(null)}})};return E?e.jsx(kt,{}):C?e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load visuals"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]})}):e.jsxs("div",{className:"relative flex h-full flex-1 flex-col gap-4",children:[A&&A.length>5&&e.jsx("div",{className:"space-y-2",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:t,onChange:Y=>n(Y.target.value),className:"h-9"})}),e.jsx("div",{className:"flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-3 overflow-y-auto",children:F.length===0?e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"mb-3",children:e.jsx(We,{className:"mx-auto h-12 w-12 text-muted-foreground/50"})}),e.jsx("h3",{className:"mb-1 font-medium text-foreground",children:t?"No visuals found":"No visuals yet"}),e.jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:t?"Try adjusting your search":"Create your first visual component to get started"}),!t&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>r(!0),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Create Visual"]})]}):F.map(Y=>e.jsx(Al,{visual:Y,onAddVisual:Q,onOpenVisual:z,onEditDetails:te,onDeleteClick:M,onDuplicateVisual:q,onTogglePrivacy:X,onShareVisual:se,isDeleting:T,isDuplicating:x===Y.id,formatDate:w},Y.id))})}),l&&c&&e.jsx(Qe,{resource:c,resourceType:s.ResourceType.VISUAL,onClose:()=>{o(!1),i(null)}}),v&&e.jsx(Et,{open:!!v,resourceLabel:"Visual",initialTitle:v.title||"",initialDescription:v.description||"",onClose:ie,onSave:K,isSaving:B(v.id)}),e.jsx(s.AlertDialog,{open:d,onOpenChange:Y=>{!Y&&T||(u(Y),Y||h(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Visual"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',m==null?void 0:m.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:T,children:"Cancel"}),e.jsxs(s.AlertDialogAction,{onClick:Y=>{Y.preventDefault(),Y.stopPropagation(),O()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:T,children:[T?e.jsx(s.LoaderCircle,{className:"mr-2 h-3.5 w-3.5 animate-spin"}):e.jsx(s.Trash2,{className:"mr-2 h-3.5 w-3.5"}),T?"Deleting...":"Delete"]})]})]})}),e.jsx(Ml,{open:a,onOpenChange:r,onSubmit:I,isCreating:R}),e.jsx(s.Button,{size:"icon",className:"absolute bottom-2 left-2 h-11 w-11 rounded-full shadow-lg shadow-black/15",onClick:()=>r(!0),"aria-label":"Create visual",children:e.jsx(s.Plus,{className:"h-5 w-5"})})]})}function Ll({dashboard:t,isDeleting:n,isDuplicating:a,onLoadDashboard:r,onEditDetails:l,onDeleteClick:o,onDuplicateDashboard:c,onShareDashboard:i,formatDate:d,onDashboardItemClick:u}){var N,j,R,T,F;const{selectDashboard:m}=s.useManagementActions(),h=s.useIsDashboardSelected(t.id),{isConsoleMode:x}=s.useDashboardPreferences(),{currentUser:g,isLoading:v,isError:p}=s.useCurrentUserInfo(),y=!p&&(g==null?void 0:g.type)==="tenant"&&((N=g==null?void 0:g.role)==null?void 0:N.toUpperCase())==="VIEWER",b=v||y,[S,A]=k.useState(!1),[E,C]=k.useState(!1);k.useEffect(()=>{a?(A(!0),C(!0)):E&&(A(!1),C(!1))},[a,E]);const D=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4"}),f=()=>{m(t),r(t.id),u==null||u(t.id)};return e.jsx(s.Card,{className:s.cn("group cursor-pointer border border-border/50 p-3 transition-colors hover:bg-accent/50",h&&"border-primary"),onClick:f,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 rounded bg-muted p-1.5",children:D()}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium text-foreground truncate",title:t.title||"Untitled Dashboard",children:t.title||"Untitled Dashboard"}),t.ownership.status==="shared"&&e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:[e.jsx(s.Users,{className:"mr-1 h-2.5 w-2.5"}),"Shared"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",title:t.description||"No description",children:(j=t.description)!=null&&j.trim()?t.description:"No description"})]}),e.jsxs("div",{className:"invisible ml-2 flex flex-shrink-0 items-center gap-1 transition-opacity duration-150 group-hover:visible",onClick:w=>w.stopPropagation(),children:[t.permissions.canEdit&&!b&&e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:w=>{w.stopPropagation(),l==null||l(t)},title:"Edit details",children:e.jsx($e,{className:"h-3 w-3"})}),!b&&e.jsxs(s.DropdownMenu,{modal:!1,open:S,onOpenChange:A,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:w=>{w.preventDefault(),w.stopPropagation(),c(t.id)},disabled:a,children:[a?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),a?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsxs(s.DropdownMenuItem,{onClick:w=>{w.stopPropagation(),l==null||l(t)},children:[e.jsx($e,{className:"mr-2 h-3 w-3"}),"Edit details"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:w=>{w.stopPropagation(),i(t)},children:[e.jsx(s.Users,{className:"mr-2 h-3 w-3"}),"Share"]})}),t.permissions.canDelete&&e.jsxs(e.Fragment,{children:[e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:w=>{w.stopPropagation(),o(t)},className:"text-destructive",disabled:n,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),n?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((R=t.ownership.createdBy)==null?void 0:R.type)==="tenant"||((T=t.ownership.createdBy)==null?void 0:T.type)==="organization"&&x)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.User,{className:"h-3 w-3"}),e.jsx("span",{children:((F=t.ownership.createdBy)==null?void 0:F.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:d(t.lastModified)})]})]})]})]})]})]})},t.id)}function Fl({onRetry:t}){return e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load dashboards"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:t,children:"Retry"})]})})}function Ol(t){const{onLoadDashboard:n,onEditDashboard:a,onDashboardItemClick:r}=t,[l,o]=k.useState(""),[c,i]=k.useState(!1),[d,u]=k.useState(!1),[m,h]=k.useState(null),[x,g]=k.useState(!1),[v,p]=k.useState(null),[y,b]=k.useState(null),[S,A]=k.useState(null),E=s.useManagementStore($=>$.lastSelectedDashboard),C=s.useManagementStore($=>$.selectedDashboard),D=s.useManagementStore($=>$.actions.selectDashboard),f=s.useManagementStore($=>$.actions.clearSelectedDashboard),{tokenProps:N,id:j}=s.useSemaphorContext(),{permissions:R}=s.useRoleAwareDisplayPreferences(),{onCreateSuccess:T}=s.useDashboardCreation({onDashboardSelect:r}),{resources:F,isLoading:w,isError:I,createResource:M,updateResource:O,deleteResource:L,duplicateResource:P,isCreating:B,isDeleting:H,refetch:q}=s.useDashboardManagement(()=>{g(!1);const $=v==null?void 0:v.id;p(null),(C==null?void 0:C.id)===$&&(!(N!=null&&N.dashboard_id)&&!j?f():E&&E.id!==$&&D(E))},$=>{i(!1),T($,q)}),{currentUser:z}=s.useCurrentUserInfo(),Q=F.filter($=>{var G,V;return((G=$==null?void 0:$.title)==null?void 0:G.toLowerCase().includes(l.toLowerCase()))||((V=$==null?void 0:$.description)==null?void 0:V.toLowerCase().includes(l.toLowerCase()))}),X=$=>new Date($).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),se=$=>{M({title:$.title,description:$.description,isPrivate:!1})},te=$=>{n==null||n($)},ie=$=>{p($),g(!0)},K=()=>{v&&L(v.id)},Y=$=>{b($),P($,{onSettled:()=>b(null)})},{startUpdating:ae,stopUpdating:W,isUpdating:re}=s.useResourceUpdateState(),U=($,G,V)=>{var ne;const Z=Object.fromEntries(Object.entries(G).filter(([,me])=>me!==void 0));if(Object.keys(Z).length===0){(ne=V==null?void 0:V.onSuccess)==null||ne.call(V);return}const oe=Object.keys(Z),de=oe.length===1?oe[0]:void 0;ae($,de),O({resourceId:$,data:Z},{onSuccess:()=>{var me;W($,de),(me=V==null?void 0:V.onSuccess)==null||me.call(V)},onError:()=>{var me;W($,de),(me=V==null?void 0:V.onError)==null||me.call(V)}})},ee=$=>{const G=F.find(V=>V.id===$);G&&O({resourceId:$,data:{isPrivate:!G.isPrivate}})},ce=$=>{h($),z==null||z.type,u(!0)},le=$=>{a==null||a($.id),A($)},fe=()=>{A(null)},ue=({title:$,description:G})=>{if(!S)return;const V={};$!==S.title&&(V.title=$),(S.description||"")!==G&&(V.description=G),U(S.id,V,{onSuccess:()=>{A(null)}})};return w?e.jsx(kt,{}):I?e.jsx(Fl,{onRetry:()=>window.location.reload()}):e.jsxs("div",{className:"relative flex h-full flex-1 flex-col gap-4",children:[F&&F.length>5&&e.jsx("div",{className:"space-y-2",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:l,onChange:$=>o($.target.value),className:"h-9"})}),e.jsx("div",{className:"flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-3 overflow-y-auto",children:Q.length===0?e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"mb-3",children:e.jsx(s.ChartColumn,{className:"mx-auto h-12 w-12 text-muted-foreground/50"})}),e.jsx("h3",{className:"mb-1 font-medium text-foreground",children:l?"No dashboards found":"No dashboards yet"}),e.jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:l?"Try adjusting your search":R.canCreateDashboards?"Create your first dashboard to get started":"No dashboards have been shared with you yet"}),R.canCreateDashboards&&!l&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>i(!0),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Create Dashboard"]})]}):Q.map($=>e.jsx(Ll,{dashboard:$,isDeleting:H,isDuplicating:y===$.id,onLoadDashboard:te,onEditDetails:le,onDeleteClick:ie,onDuplicateDashboard:Y,onTogglePrivacy:ee,onShareDashboard:ce,formatDate:X,onDashboardItemClick:r},$.id))})}),d&&m&&e.jsx(Qe,{resource:m,resourceType:s.ResourceType.DASHBOARD,onClose:()=>{u(!1),h(null)}}),e.jsx(s.AlertDialog,{open:x,onOpenChange:$=>{!$&&H||(g($),$||p(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 "',v==null?void 0:v.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:H,children:"Cancel"}),e.jsxs(s.AlertDialogAction,{onClick:$=>{$.preventDefault(),$.stopPropagation(),K()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:H,children:[H?e.jsx(s.LoaderCircle,{className:"mr-2 h-3.5 w-3.5 animate-spin"}):e.jsx(s.Trash2,{className:"mr-2 h-3.5 w-3.5"}),H?"Deleting...":"Delete"]})]})]})}),S&&e.jsx(Et,{open:!!S,resourceLabel:"Dashboard",initialTitle:S.title||"",initialDescription:S.description||"",onClose:fe,onSave:ue,isSaving:re(S.id)}),e.jsx(s.CreateDashboardDialog,{open:c,onOpenChange:i,onSubmit:se,isCreating:B}),R.canCreateDashboards&&e.jsx(s.Button,{size:"icon",className:"absolute bottom-2 left-2 h-11 w-11 rounded-full shadow-lg shadow-black/15",onClick:()=>i(!0),"aria-label":"Create dashboard",children:e.jsx(s.Plus,{className:"h-5 w-5"})})]})}function It({isOpen:t,onClose:n,className:a,onDashboardItemClick:r,variant:l="inline"}){s.useDashboardStore(C=>C.dashboard);const{setDashboard:o,addSheet:c}=s.useDashboardStore(C=>C.actions),{currentUser:i}=s.useCurrentUserInfo(),d=i,{permissions:u}=s.useRoleAwareDisplayPreferences(),h=s.useSelectedDashboard()&&u.canAccessVisuals,x="dashboards",[g,v]=us("resource-management-active-tab",x),p=h?g:"dashboards",y=l==="overlay",b=qs(n,{enabled:t&&y}),S=s.cn("flex h-full flex-col border-r bg-background",y?s.cn("absolute inset-y-0 left-0 z-[51] w-96 shadow-lg transition-transform duration-300 ease-in-out",t?"translate-x-0":"pointer-events-none -translate-x-full"):"w-full max-w-[28rem] min-w-[18rem] overflow-hidden shadow-sm",a),A=C=>{},E=C=>{console.log("Editing dashboard:",C)};return e.jsx(s.TooltipProvider,{children:(!y||t)&&e.jsxs("div",{ref:b,className:S,children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border p-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:d&&e.jsxs(e.Fragment,{children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"flex h-8 w-8 cursor-default items-center justify-center rounded-full bg-primary/10",children:e.jsx("span",{className:"text-sm font-medium text-primary",children:d.name.charAt(0).toUpperCase()})})}),e.jsx(s.TooltipContent,{side:"bottom",className:"ml-2 max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"font-medium",children:d.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:d.email}),d.role&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Role:"," ",s.toTitleCase(d.role.replace(/_/g," "))]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",d.id]})]})})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"text-sm font-medium text-foreground",children:d.name})})]})}),e.jsx(s.IconButton,{className:"h-8 w-8 p-0 text-muted-foreground hover:text-foreground",onClick:n,tooltip:"Close Sidebar",children:e.jsx(la,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:p,onValueChange:h?v:void 0,className:"flex h-9 grow flex-col",children:[h&&e.jsx("div",{className:"px-4 pt-4",children:e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"dashboards",className:"text-sm",children:"Dashboards"}),e.jsx(s.TabsTrigger,{value:"visuals",className:"text-sm",children:"Visuals"})]})}),e.jsx(s.TabsContent,{value:"dashboards",className:"flex-1 px-4 py-4",children:e.jsx(Ol,{onLoadDashboard:A,onEditDashboard:E,onDashboardItemClick:r})}),h&&e.jsx(s.TabsContent,{value:"visuals",className:"flex-1 px-4 py-4",children:e.jsx(Rl,{})})]})})]})})}function Pl({showControls:t=!1,showFooter:n=!0,...a}){const r=s.useDashboardStore(x=>x.isDashboardPanelOpen);s.useDashboardStore(x=>x.isVisualEditing);const l=s.useDashboardStore(x=>x.actions.setIsDashboardPanelOpen),o=20,c=20,i=30,d=r,u=k.useRef(null),m=k.useRef(null);k.useEffect(()=>{u.current&&m.current&&(r?(u.current.resize(o),m.current.resize(100-o)):(u.current.resize(0),m.current.resize(100)))},[r]);const{preferences:h}=a;return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:a,children:[e.jsx(s.$e,{}),e.jsx(s.UXProvider,{children:e.jsxs(s.DashboardPreferencesProvider,{preferences:h,children:[e.jsx(El,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx(xn,{}),e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",className:"flex grow overflow-hidden",children:[e.jsx(s.ResizablePanel,{ref:u,className:s.cn("flex h-full max-w-[26rem] overflow-hidden",{"min-w-[20rem]":d}),defaultSize:d?o:0,minSize:d?c:0,maxSize:d?i:0,children:e.jsx(It,{isOpen:r,onClose:()=>l(!1),variant:"inline"})}),e.jsx(s.ResizableHandle,{withHandle:d,className:s.cn("w-1",{"w-0":!d})}),e.jsx(s.ResizablePanel,{ref:m,className:"flex min-w-0 flex-1",defaultSize:d?100-o:100,minSize:d?40:100,children:e.jsxs(s.Container,{...a,type:"dashboard",children:[e.jsx(Sl,{}),e.jsx(kl,{})]})})]})]})]})})]})})}exports.AdvancedModeToggle=tt;exports.DashboardPlus=Pl;exports.ResourceManagementPanel=It;exports.ScheduleDashboard=Gs;exports.ShareDialog=Qe;exports.VisualBadge=Zs;exports.VisualEditingControls=st;exports.cleanCard=Us;exports.getDashbaordStateWithoutData=Ke;
|