react-semaphor 0.1.241 → 0.1.242
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/CHANGELOG.md +6 -0
- package/dist/chunks/{dashboard-controls-Bbjg39W1.js → dashboard-controls-BZJeyZlZ.js} +1 -1
- package/dist/chunks/{dashboard-controls-CydTgB8b.js → dashboard-controls-Cf72JYT4.js} +4 -4
- package/dist/chunks/{dashboard-json-Dh0BCAEU.js → dashboard-json-Bd10raU6.js} +1 -1
- package/dist/chunks/{dashboard-json-BqhlPxCk.js → dashboard-json-DlbxwVSD.js} +1 -1
- package/dist/chunks/{dashboard-summary-settings-dialog-DMGeFM9N.js → dashboard-summary-settings-dialog-CojnJ2sv.js} +1 -1
- package/dist/chunks/{dashboard-summary-settings-dialog-DXEx7VYT.js → dashboard-summary-settings-dialog-DkzmxM-i.js} +1 -1
- package/dist/chunks/{edit-dashboard-visual-DcLZThas.js → edit-dashboard-visual--he-HORJ.js} +42 -42
- package/dist/chunks/{edit-dashboard-visual-BSHC5QiP.js → edit-dashboard-visual-DOZbjM9y.js} +1590 -1590
- package/dist/chunks/{editor-action-buttons-lDMI1SQ2.js → editor-action-buttons-BVHMz1tA.js} +2 -2
- package/dist/chunks/{editor-action-buttons-C_zLw3Aj.js → editor-action-buttons-ClV0JS2e.js} +1 -1
- package/dist/chunks/{index-C1qXov_Z.js → index-BWyor40k.js} +17910 -17813
- package/dist/chunks/{index-CYQV2kbT.js → index-CVln6PdW.js} +200 -200
- package/dist/chunks/{notification-bell-CuEbhFaL.js → notification-bell-DPPmQdyG.js} +3 -3
- package/dist/chunks/{notification-bell-CfYK7Cx6.js → notification-bell-Df4gFiua.js} +1 -1
- package/dist/chunks/{resource-management-panel-G3XJbfPx.js → resource-management-panel-CcN5WvaG.js} +2 -2
- package/dist/chunks/{resource-management-panel-xwPhr6Lm.js → resource-management-panel-DO1EHHP0.js} +1 -1
- package/dist/chunks/{use-visual-utils-Du-m-SYb.js → use-visual-utils-BxXi20gi.js} +1 -1
- package/dist/chunks/{use-visual-utils-Cdm8jbGc.js → use-visual-utils-COV2QBKs.js} +1 -1
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +5 -5
- package/dist/style.css +1 -1
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +2 -2
- package/dist/types/main.d.ts +3 -2
- package/dist/types/types.d.ts +3 -2
- package/package.json +1 -1
|
@@ -1,179 +1,179 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),s=require("./index-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),s=require("./index-CVln6PdW.js"),C=require("react"),Ae=require("./editor-action-buttons-ClV0JS2e.js"),an=require("react-dom");function nn(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 at=nn(C);/**
|
|
2
2
|
* @license lucide-react v0.453.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
5
5
|
* See the LICENSE file in the root directory of this source tree.
|
|
6
|
-
*/const
|
|
6
|
+
*/const rn=s.createLucideIcon("ArrowDownAZ",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M20 8h-5",key:"1vsyxs"}],["path",{d:"M15 10V6.5a2.5 2.5 0 0 1 5 0V10",key:"ag13bf"}],["path",{d:"M15 14h5l-5 6h5",key:"ur5jdg"}]]);/**
|
|
7
7
|
* @license lucide-react v0.453.0 - ISC
|
|
8
8
|
*
|
|
9
9
|
* This source code is licensed under the ISC license.
|
|
10
10
|
* See the LICENSE file in the root directory of this source tree.
|
|
11
|
-
*/const
|
|
11
|
+
*/const ln=s.createLucideIcon("ArrowUpAZ",[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M20 8h-5",key:"1vsyxs"}],["path",{d:"M15 10V6.5a2.5 2.5 0 0 1 5 0V10",key:"ag13bf"}],["path",{d:"M15 14h5l-5 6h5",key:"ur5jdg"}]]);/**
|
|
12
12
|
* @license lucide-react v0.453.0 - ISC
|
|
13
13
|
*
|
|
14
14
|
* This source code is licensed under the ISC license.
|
|
15
15
|
* See the LICENSE file in the root directory of this source tree.
|
|
16
|
-
*/const
|
|
16
|
+
*/const ya=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"}]]);/**
|
|
17
17
|
* @license lucide-react v0.453.0 - ISC
|
|
18
18
|
*
|
|
19
19
|
* This source code is licensed under the ISC license.
|
|
20
20
|
* See the LICENSE file in the root directory of this source tree.
|
|
21
|
-
*/const
|
|
21
|
+
*/const lt=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"}]]);/**
|
|
22
22
|
* @license lucide-react v0.453.0 - ISC
|
|
23
23
|
*
|
|
24
24
|
* This source code is licensed under the ISC license.
|
|
25
25
|
* See the LICENSE file in the root directory of this source tree.
|
|
26
|
-
*/const
|
|
26
|
+
*/const on=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"}]]);/**
|
|
27
27
|
* @license lucide-react v0.453.0 - ISC
|
|
28
28
|
*
|
|
29
29
|
* This source code is licensed under the ISC license.
|
|
30
30
|
* See the LICENSE file in the root directory of this source tree.
|
|
31
|
-
*/const
|
|
31
|
+
*/const Na=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"}]]);/**
|
|
32
32
|
* @license lucide-react v0.453.0 - ISC
|
|
33
33
|
*
|
|
34
34
|
* This source code is licensed under the ISC license.
|
|
35
35
|
* See the LICENSE file in the root directory of this source tree.
|
|
36
|
-
*/const
|
|
36
|
+
*/const cn=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"}]]);/**
|
|
37
37
|
* @license lucide-react v0.453.0 - ISC
|
|
38
38
|
*
|
|
39
39
|
* This source code is licensed under the ISC license.
|
|
40
40
|
* See the LICENSE file in the root directory of this source tree.
|
|
41
|
-
*/const
|
|
41
|
+
*/const dn=s.createLucideIcon("Fullscreen",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{width:"10",height:"8",x:"7",y:"8",rx:"1",key:"vys8me"}]]);/**
|
|
42
42
|
* @license lucide-react v0.453.0 - ISC
|
|
43
43
|
*
|
|
44
44
|
* This source code is licensed under the ISC license.
|
|
45
45
|
* See the LICENSE file in the root directory of this source tree.
|
|
46
|
-
*/const
|
|
46
|
+
*/const Ca=s.createLucideIcon("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"}]]);/**
|
|
47
47
|
* @license lucide-react v0.453.0 - ISC
|
|
48
48
|
*
|
|
49
49
|
* This source code is licensed under the ISC license.
|
|
50
50
|
* See the LICENSE file in the root directory of this source tree.
|
|
51
|
-
*/const
|
|
51
|
+
*/const un=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"}]]);/**
|
|
52
52
|
* @license lucide-react v0.453.0 - ISC
|
|
53
53
|
*
|
|
54
54
|
* This source code is licensed under the ISC license.
|
|
55
55
|
* See the LICENSE file in the root directory of this source tree.
|
|
56
|
-
*/const
|
|
56
|
+
*/const mn=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"}]]);/**
|
|
57
57
|
* @license lucide-react v0.453.0 - ISC
|
|
58
58
|
*
|
|
59
59
|
* This source code is licensed under the ISC license.
|
|
60
60
|
* See the LICENSE file in the root directory of this source tree.
|
|
61
|
-
*/const
|
|
61
|
+
*/const xn=s.createLucideIcon("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"}]]);/**
|
|
62
62
|
* @license lucide-react v0.453.0 - ISC
|
|
63
63
|
*
|
|
64
64
|
* This source code is licensed under the ISC license.
|
|
65
65
|
* See the LICENSE file in the root directory of this source tree.
|
|
66
|
-
*/const
|
|
66
|
+
*/const Wt=s.createLucideIcon("ListFilter",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M7 12h10",key:"b7w52i"}],["path",{d:"M10 18h4",key:"1ulq68"}]]);/**
|
|
67
67
|
* @license lucide-react v0.453.0 - ISC
|
|
68
68
|
*
|
|
69
69
|
* This source code is licensed under the ISC license.
|
|
70
70
|
* See the LICENSE file in the root directory of this source tree.
|
|
71
|
-
*/const
|
|
71
|
+
*/const hn=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"}]]);/**
|
|
72
72
|
* @license lucide-react v0.453.0 - ISC
|
|
73
73
|
*
|
|
74
74
|
* This source code is licensed under the ISC license.
|
|
75
75
|
* See the LICENSE file in the root directory of this source tree.
|
|
76
|
-
*/const
|
|
76
|
+
*/const pn=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"}]]);/**
|
|
77
77
|
* @license lucide-react v0.453.0 - ISC
|
|
78
78
|
*
|
|
79
79
|
* This source code is licensed under the ISC license.
|
|
80
80
|
* See the LICENSE file in the root directory of this source tree.
|
|
81
|
-
*/const
|
|
81
|
+
*/const Hs=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"}]]);/**
|
|
82
82
|
* @license lucide-react v0.453.0 - ISC
|
|
83
83
|
*
|
|
84
84
|
* This source code is licensed under the ISC license.
|
|
85
85
|
* See the LICENSE file in the root directory of this source tree.
|
|
86
|
-
*/const
|
|
86
|
+
*/const Js=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"}]]);/**
|
|
87
87
|
* @license lucide-react v0.453.0 - ISC
|
|
88
88
|
*
|
|
89
89
|
* This source code is licensed under the ISC license.
|
|
90
90
|
* See the LICENSE file in the root directory of this source tree.
|
|
91
|
-
*/const
|
|
91
|
+
*/const fn=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"}]]);/**
|
|
92
92
|
* @license lucide-react v0.453.0 - ISC
|
|
93
93
|
*
|
|
94
94
|
* This source code is licensed under the ISC license.
|
|
95
95
|
* See the LICENSE file in the root directory of this source tree.
|
|
96
|
-
*/const
|
|
96
|
+
*/const gn=s.createLucideIcon("PanelRightClose",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m8 9 3 3-3 3",key:"12hl5m"}]]);/**
|
|
97
97
|
* @license lucide-react v0.453.0 - ISC
|
|
98
98
|
*
|
|
99
99
|
* This source code is licensed under the ISC license.
|
|
100
100
|
* See the LICENSE file in the root directory of this source tree.
|
|
101
|
-
*/const
|
|
101
|
+
*/const jn=s.createLucideIcon("PanelRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
|
|
102
102
|
* @license lucide-react v0.453.0 - ISC
|
|
103
103
|
*
|
|
104
104
|
* This source code is licensed under the ISC license.
|
|
105
105
|
* See the LICENSE file in the root directory of this source tree.
|
|
106
|
-
*/const
|
|
106
|
+
*/const Xt=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"}]]);/**
|
|
107
107
|
* @license lucide-react v0.453.0 - ISC
|
|
108
108
|
*
|
|
109
109
|
* This source code is licensed under the ISC license.
|
|
110
110
|
* See the LICENSE file in the root directory of this source tree.
|
|
111
|
-
*/const
|
|
111
|
+
*/const Fs=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"}]]);/**
|
|
112
112
|
* @license lucide-react v0.453.0 - ISC
|
|
113
113
|
*
|
|
114
114
|
* This source code is licensed under the ISC license.
|
|
115
115
|
* See the LICENSE file in the root directory of this source tree.
|
|
116
|
-
*/const
|
|
116
|
+
*/const bn=s.createLucideIcon("SendHorizontal",[["path",{d:"M3.714 3.048a.498.498 0 0 0-.683.627l2.843 7.627a2 2 0 0 1 0 1.396l-2.842 7.627a.498.498 0 0 0 .682.627l18-8.5a.5.5 0 0 0 0-.904z",key:"117uat"}],["path",{d:"M6 12h16",key:"s4cdu5"}]]);/**
|
|
117
117
|
* @license lucide-react v0.453.0 - ISC
|
|
118
118
|
*
|
|
119
119
|
* This source code is licensed under the ISC license.
|
|
120
120
|
* See the LICENSE file in the root directory of this source tree.
|
|
121
|
-
*/const
|
|
121
|
+
*/const vn=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"}]]);/**
|
|
122
122
|
* @license lucide-react v0.453.0 - ISC
|
|
123
123
|
*
|
|
124
124
|
* This source code is licensed under the ISC license.
|
|
125
125
|
* See the LICENSE file in the root directory of this source tree.
|
|
126
|
-
*/const
|
|
126
|
+
*/const yn=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"}]]);/**
|
|
127
127
|
* @license lucide-react v0.453.0 - ISC
|
|
128
128
|
*
|
|
129
129
|
* This source code is licensed under the ISC license.
|
|
130
130
|
* See the LICENSE file in the root directory of this source tree.
|
|
131
|
-
*/const
|
|
131
|
+
*/const nt=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"}]]);/**
|
|
132
132
|
* @license lucide-react v0.453.0 - ISC
|
|
133
133
|
*
|
|
134
134
|
* This source code is licensed under the ISC license.
|
|
135
135
|
* See the LICENSE file in the root directory of this source tree.
|
|
136
|
-
*/const
|
|
136
|
+
*/const Nn=s.createLucideIcon("Spline",[["circle",{cx:"19",cy:"5",r:"2",key:"mhkx31"}],["circle",{cx:"5",cy:"19",r:"2",key:"v8kfzx"}],["path",{d:"M5 17A12 12 0 0 1 17 5",key:"1okkup"}]]);/**
|
|
137
137
|
* @license lucide-react v0.453.0 - ISC
|
|
138
138
|
*
|
|
139
139
|
* This source code is licensed under the ISC license.
|
|
140
140
|
* See the LICENSE file in the root directory of this source tree.
|
|
141
|
-
*/const
|
|
141
|
+
*/const Cn=s.createLucideIcon("SquareFunction",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["path",{d:"M9 17c2 0 2.8-1 2.8-2.8V10c0-2 1-3.3 3.2-3",key:"m1af9g"}],["path",{d:"M9 11.2h5.7",key:"3zgcl2"}]]);/**
|
|
142
142
|
* @license lucide-react v0.453.0 - ISC
|
|
143
143
|
*
|
|
144
144
|
* This source code is licensed under the ISC license.
|
|
145
145
|
* See the LICENSE file in the root directory of this source tree.
|
|
146
|
-
*/const
|
|
146
|
+
*/const Sn=s.createLucideIcon("SquareSplitVertical",[["path",{d:"M5 8V5c0-1 1-2 2-2h10c1 0 2 1 2 2v3",key:"1pi83i"}],["path",{d:"M19 16v3c0 1-1 2-2 2H7c-1 0-2-1-2-2v-3",key:"ido5k7"}],["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}]]);/**
|
|
147
147
|
* @license lucide-react v0.453.0 - ISC
|
|
148
148
|
*
|
|
149
149
|
* This source code is licensed under the ISC license.
|
|
150
150
|
* See the LICENSE file in the root directory of this source tree.
|
|
151
|
-
*/const
|
|
151
|
+
*/const wn=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"}]]);/**
|
|
152
152
|
* @license lucide-react v0.453.0 - ISC
|
|
153
153
|
*
|
|
154
154
|
* This source code is licensed under the ISC license.
|
|
155
155
|
* See the LICENSE file in the root directory of this source tree.
|
|
156
|
-
*/const
|
|
157
|
-
FROM ${D.name}`;return v.forEach(f=>{const I=n.find(R=>R.name===f.target.name);if(!I)return;const j=f.joinKeyGroups.filter(R=>R.keys&&R.keys.length>0).map(R=>{const P=R.keys.filter(N=>{var
|
|
156
|
+
*/const Tn=s.createLucideIcon("Wand",[["path",{d:"M15 4V2",key:"z1p9b7"}],["path",{d:"M15 16v-2",key:"px0unx"}],["path",{d:"M8 9h2",key:"1g203m"}],["path",{d:"M20 9h2",key:"19tzq7"}],["path",{d:"M17.8 11.8 19 13",key:"yihg8r"}],["path",{d:"M15 9h.01",key:"x1ddxp"}],["path",{d:"M17.8 6.2 19 5",key:"fd4us0"}],["path",{d:"m3 21 9-9",key:"1jfql5"}],["path",{d:"M12.2 6.2 11 5",key:"i3da3b"}]]);function Sa({storeValue:t,defaultValue:n="",onStoreUpdate:a,delay:r=300}){const[i,d]=C.useState(t??n),o=s.useDebounce(i,r),c=C.useRef(t),l=C.useRef(!1);C.useEffect(()=>{t!==c.current&&(d(t??n),c.current=t)},[t,n]),C.useEffect(()=>{l.current&&o!==c.current&&(a(o),c.current=o)},[o,a]);const x=C.useCallback(p=>{l.current=!0,d(p??n)},[n]);return{value:i,onChange:x}}function En({initialJoinPlan:t,availableDataSources:n}){const[a,r]=C.useState(t),[i,d]=C.useState(new Set),o=()=>{const v=a.joins.length>0?Math.max(...a.joins.map(M=>M.sequence))+1:1,D={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:v,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...a,joins:[...a.joins,D]}),d(new Set([...i,D.id]))},c=v=>{r({...a,joins:a.joins.filter(D=>D.id!==v)}),d(new Set([...i].filter(D=>D!==v)))},l=(v,D)=>{var k,R,P,N,L;const M=a.joins.find(S=>S.id===v);if(!M)return;const f={...M,...D};if((k=f.source)!=null&&k.name&&((R=f.target)!=null&&R.name)&&f.source.name===f.target.name){s.ue.error("Self-joins are not yet supported",{description:`Joining ${f.source.name} to itself is not currently supported. Please select a different target table.`});return}const I=a.joins.filter(S=>{var F;return S.id!==v&&S.target.name===((F=f.target)==null?void 0:F.name)});if((P=f.target)!=null&&P.name&&I.length>0){s.ue.error("Duplicate join targets are not supported",{description:`The table ${f.target.name} is already used as a target in another join. Each table can only be joined once.`});return}const j=a.joins.map(S=>S.id===v?f:S);if((N=f.source)!=null&&N.name&&((L=f.target)!=null&&L.name)&&f.joinKeyGroups[0].keys.length===0){const S=n.find(Q=>{var B;return Q.name===((B=f.source)==null?void 0:B.name)}),F=n.find(Q=>{var B;return Q.name===((B=f.target)==null?void 0:B.name)}),O={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(S==null?void 0:S.name)||"",entityName:(S==null?void 0:S.name)||"",entityType:(S==null?void 0:S.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(F==null?void 0:F.name)||"",entityName:(F==null?void 0:F.name)||"",entityType:(F==null?void 0:F.type)||"table"},operator:"="},_=[...f.joinKeyGroups];_[0]={..._[0],keys:[O]},f.joinKeyGroups=_,j[j.findIndex(Q=>Q.id===v)]=f}r({...a,joins:j})};return{joinPlan:a,expandedJoins:i,setJoinPlan:r,addJoin:o,removeJoin:c,updateJoin:l,moveJoinUp:v=>{const D=a.joins.findIndex(M=>M.id===v);if(D>0){const M=[...a.joins],f={...M[D]},I={...M[D-1]};M[D]=I,M[D-1]=f,M.forEach((k,R)=>{k.sequence=R+1});const j={...a,joins:M};r(j)}},moveJoinDown:v=>{const D=a.joins.findIndex(M=>M.id===v);if(D<a.joins.length-1){const M=[...a.joins],f={...M[D]},I={...M[D+1]};M[D]=I,M[D+1]=f,M.forEach((k,R)=>{k.sequence=R+1});const j={...a,joins:M};r(j)}},toggleJoinExpansion:v=>{const D=new Set(i);D.has(v)?D.delete(v):D.add(v),d(D)},getAvailableSourceEntities:v=>{if(a.joins.length===0)return n;const D=a.joins.findIndex(f=>f.id===v);if(D===0)return n.filter(f=>f.name===a.baseEntity.name);const M=new Set;return a.baseEntity.name&&M.add(a.baseEntity.name),a.joins.slice(0,D).forEach(f=>{M.add(f.source.name),M.add(f.target.name)}),n.filter(f=>M.has(f.name))},getAvailableTargetEntities:v=>n.filter(D=>D.name!==v),addJoinKeyGroup:v=>{const D=a.joins.find(f=>f.id===v);if(!D)return;const M=[...D.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];l(v,{joinKeyGroups:M})},updateGroupOperator:(v,D,M)=>{const f=a.joins.find(j=>j.id===v);if(!f)return;const I=[...f.joinKeyGroups];I[D]={...I[D],operator:M},l(v,{joinKeyGroups:I})},removeJoinKeyGroup:(v,D)=>{const M=a.joins.find(I=>I.id===v);if(!M)return;const f=[...M.joinKeyGroups];f.splice(D,1),l(v,{joinKeyGroups:f})},addJoinKey:(v,D)=>{const M=a.joins.find(R=>R.id===v);if(!M)return;const f=n.find(R=>R.name===M.source.name),I=n.find(R=>R.name===M.target.name),j=[...M.joinKeyGroups],k={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(f==null?void 0:f.name)||"",entityName:(f==null?void 0:f.name)||"",entityType:(f==null?void 0:f.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(I==null?void 0:I.name)||"",entityName:(I==null?void 0:I.name)||"",entityType:(I==null?void 0:I.type)||"table"},operator:"="};j[D]={...j[D],keys:[...j[D].keys,k]},l(v,{joinKeyGroups:j})},updateJoinKey:(v,D,M,f,I)=>{const j=a.joins.find(L=>L.id===v);if(!j)return;const k=n.find(L=>L.name===j.source.name),R=n.find(L=>L.name===j.target.name),P=[...j.joinKeyGroups],N=P[D].keys[M];f==="sourceColumnName"&&k?P[D].keys[M]={...N,source:{...N.source,name:I}}:f==="targetColumnName"&&R?P[D].keys[M]={...N,target:{...N.target,name:I}}:f==="operator"&&(P[D].keys[M]={...N,operator:I}),l(v,{joinKeyGroups:P})},removeJoinKey:(v,D,M)=>{const f=a.joins.find(j=>j.id===v);if(!f)return;const I=[...f.joinKeyGroups];I[D].keys.splice(M,1),l(v,{joinKeyGroups:I})},generateSQLPreview:()=>{const v=[...a.joins].sort((f,I)=>f.sequence-I.sequence),D=a.baseEntity;if(!D.name)return"SELECT * FROM table -- Please select a base entity";let M=`SELECT *
|
|
157
|
+
FROM ${D.name}`;return v.forEach(f=>{const I=n.find(R=>R.name===f.target.name);if(!I)return;const j=f.joinKeyGroups.filter(R=>R.keys&&R.keys.length>0).map(R=>{const P=R.keys.filter(N=>{var L,S,F,O;return((L=N.source)==null?void 0:L.name)&&((S=N.target)==null?void 0:S.name)&&((F=N.source)==null?void 0:F.entityName)&&((O=N.target)==null?void 0:O.entityName)}).map(N=>`${N.source.entityName}.${N.source.name} ${N.operator} ${N.target.entityName}.${N.target.name}`);return P.length>1?`(${P.join(` ${R.operator} `)})`:P[0]}).filter(Boolean),k=j.length>1?j.join(" OR "):j[0]||"condition_here";M+=`
|
|
158
158
|
${f.joinType} JOIN ${I.name}
|
|
159
|
-
ON ${k}`}),L},isValidConfiguration:()=>!(!a.baseEntity.name||a.joins.some(f=>!f.source.name||!f.target.name)||a.joins.some(f=>f.joinKeyGroups.some(I=>I.keys.length===0))||a.joins.some(f=>f.joinKeyGroups.some(I=>I.keys.some(j=>!j.source.name||!j.target.name||!j.operator))))}}function En({joinPlan:t,availableDataSources:n,onSave:a,onRemove:r,onCancel:i}){const{setCardConfig:d}=s.useEditorActions();s.useEditorStore(k=>k.card.config);const{columnGroups:o}=s.useColumns(),c=o.filter(k=>k.entityName!==s.CALCULATED_FIELDS_GROUP_NAME),{joinPlan:l,expandedJoins:x,setJoinPlan:p,addJoin:h,removeJoin:u,updateJoin:y,moveJoinUp:b,moveJoinDown:m,toggleJoinExpansion:g,getAvailableSourceEntities:w,getAvailableTargetEntities:E,addJoinKeyGroup:V,updateGroupOperator:A,removeJoinKeyGroup:T,addJoinKey:v,updateJoinKey:D,removeJoinKey:L,generateSQLPreview:f,isValidConfiguration:I}=Tn({initialJoinPlan:t,availableDataSources:n}),j=k=>{const R=c.find(P=>P.entityName===k);return(R==null?void 0:R.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:l.baseEntity.name,onValueChange:k=>{const R=n.find(P=>P.name===k);p({...l,baseEntity:{connectionId:(R==null?void 0:R.connectionId)||"",connectionType:(R==null?void 0:R.connectionType)||"none",type:(R==null?void 0:R.type)||"table",name:k,database:R==null?void 0:R.database,schema:R==null?void 0:R.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:n.map(k=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:k.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:k.type}),k.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},k.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:f()})]}),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 (",l.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:h,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),l.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:l.joins.map(k=>{const R=n.find(M=>M.name===k.source.name),P=n.find(M=>M.name===k.target.name),N=x.has(k.id);return e.jsxs(s.Card,{className:"border",children:[e.jsx(s.CardHeader,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{children:k.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",k.sequence,R&&P&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",R.name," → ",P.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>b(k.id),disabled:k.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>m(k.id),disabled:k.sequence===l.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g(k.id),children:N?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>u(k.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),N&&e.jsxs(s.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Source"}),e.jsxs(s.Select,{value:k.source.name,onValueChange:M=>{const S=n.find(F=>F.name===M);y(k.id,{source:{connectionId:(S==null?void 0:S.connectionId)||"",connectionType:(S==null?void 0:S.connectionType)||"none",type:(S==null?void 0:S.type)||"table",name:M,database:S==null?void 0:S.database,schema:S==null?void 0:S.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:w(k.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:k.joinType,onValueChange:M=>y(k.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:k.target.name,onValueChange:M=>{const S=n.find(F=>F.name===M);y(k.id,{target:{connectionId:(S==null?void 0:S.connectionId)||"",connectionType:(S==null?void 0:S.connectionType)||"none",type:(S==null?void 0:S.type)||"table",name:M,database:S==null?void 0:S.database,schema:S==null?void 0:S.schema}})},disabled:!k.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:k.source.name?E(k.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===k.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},M.name)):[]})]})]})]}),k.source.name&&k.target.name&&R&&P&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>V(k.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),k.joinKeyGroups.length===0?e.jsx("div",{className:"rounded-md border p-3 text-center text-sm text-gray-500",children:"No join conditions defined. Add condition groups to specify how data sources should be joined."}):e.jsx("div",{className:"space-y-4",children:k.joinKeyGroups.map((M,S)=>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 ",S+1]}),S>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:F=>A(k.id,S,F),children:[e.jsx(s.SelectTrigger,{className:"w-[100px]",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>T(k.id,S),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((F,O)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[O>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:M.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:F.source.name,onValueChange:$=>D(k.id,S,O,"sourceColumnName",$),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:j(k.source.name).map($=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:$.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:$.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:$.dataType})]})},$.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:F.operator,onValueChange:$=>D(k.id,S,O,"operator",$),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:F.target.name,onValueChange:$=>D(k.id,S,O,"targetColumnName",$),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:j(k.target.name).map($=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:$.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:$.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:$.dataType})]})},$.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>L(k.id,S,O),children:e.jsx(s.X,{className:"size-3.5"})})]},F.id||O))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>v(k.id,S),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},M.id))})]})]})]},k.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),i()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:i,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>a(l),disabled:!I(),children:"Save"})]})]})}function Sa({children:t,open:n,onOpenChange:a,joinPlan:r,availableDataSources:i,onRemove:d,onSave:o,onCancel:c}){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(En,{joinPlan:r,availableDataSources:i,onSave:o,onCancel:c,onRemove:d})]}),t]})}function In({joins:t,baseEntityId:n,availableDataSources:a,generateSQLPreview:r}){return e.jsxs("div",{className:"my-2 max-h-[400px] divide-y divide-border overflow-y-auto",children:[t.length>0&&e.jsxs("div",{className:"px-4 py-2",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 i=[...t].sort((o,c)=>o.sequence-c.sequence),d=a.find(o=>o.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:d==null?void 0:d.type}),e.jsx("span",{className:"text-xs font-medium",children:d==null?void 0:d.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),i.map(o=>{const c=a.find(l=>l.name===o.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:o.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:c==null?void 0:c.type}),e.jsx("span",{className:"text-xs font-medium",children:c==null?void 0:c.name})]})]},o.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((i,d)=>i.sequence-d.sequence).map((i,d)=>{const o=a.find(x=>x.name===i.source.name),c=a.find(x=>x.name===i.target.name),l=i.joinKeyGroups.reduce((x,p)=>x+p.keys.length,0);return e.jsxs("div",{className:"rounded-md bg-muted p-2 text-left",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:d+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:i.joinType}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto shrink-0 text-xs",children:[l," condition",l>1?"s":""]})]}),e.jsxs("div",{className:"mt-1 truncate pl-1 text-xs text-muted-foreground",children:[o==null?void 0:o.name," → ",c==null?void 0:c.name]})]},i.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 Xt({open:t,onOpenChange:n,variant:a="button"}={}){var E,V;const r=s.useEditorStore(A=>A.card),{autoJoinMetadata:i}=s.useDashboardCardQuery(r),d=s.useEditorStore(A=>A.actions.updateCardConfig),o=((E=r==null?void 0:r.config)==null?void 0:E.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[c,l]=C.useState(!1),x=t!==void 0,p=x?t:c,h=x?n:l,u=((V=r==null?void 0:r.dataSource)==null?void 0:V.selectedEntities)||[],y=A=>{d(r.id,{...r==null?void 0:r.config,joinPlan:A}),h(!1)},b=()=>{d(r.id,{...r==null?void 0:r.config,joinPlan:void 0})},m=()=>{h(!1)},g=()=>{const A=[...o.joins].sort((D,L)=>D.sequence-L.sequence),T=o.baseEntity;if(!T.name)return"SELECT * FROM table -- Please select a base entity";let v=`SELECT *
|
|
160
|
-
FROM ${T.name}`;return A.forEach(D=>{const
|
|
161
|
-
${D.joinType} JOIN ${
|
|
162
|
-
ON ${I}`}),v};if(u.length<2)return null;const w=o.joins.length>0&&e.jsx(s.TooltipContent,{side:"bottom",className:"ml-4 max-w-md overflow-hidden p-0",children:e.jsx(In,{joins:o.joins,baseEntityId:o.baseEntity.name,availableDataSources:u,generateSQLPreview:g})});return e.jsxs(e.Fragment,{children:[e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:a==="badge"?e.jsxs(s.Badge,{variant:"secondary",className:"h-5 cursor-pointer gap-1 px-1.5 text-xs transition-colors hover:bg-secondary/80",onClick:A=>{A.stopPropagation(),h(!0)},children:[e.jsx(s.Link,{className:"h-3 w-3"}),o.joins.length]}):e.jsxs(s.Button,{onClick:()=>h(!0),variant:"outline",className:"w-full bg-muted/50",children:[e.jsx(s.Link,{className:"mr-2 h-3.5 w-3.5"}),o.joins.length===0?"Configure Joins":o.joins.length===1?"Join":"Joins",o.joins.length>0&&e.jsx("span",{className:"ml-2 flex h-5 min-w-5 items-center justify-center rounded-full border bg-muted-foreground px-1.5 text-xs font-medium text-background",children:o.joins.length}),(i==null?void 0:i.autoResolved)&&e.jsxs(s.Badge,{variant:"secondary",className:"ml-2 h-5 gap-1 bg-blue-50 text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:[e.jsx(s.Sparkles,{className:"h-3 w-3"}),"Auto"]})]})}),w]})}),e.jsx(Sa,{open:p,onOpenChange:h,joinPlan:o,availableDataSources:u,onSave:y,onCancel:m,onRemove:b,children:e.jsx("div",{})})]})}function kn({open:t,onOpenChange:n}){const[a,r]=C.useState([]),{updateDataSource:i}=s.useEditorActions(),d=s.useDashboardStore(b=>b.dashboard.aiContext),o=(d==null?void 0:d.selectedEntities)||[];C.useEffect(()=>{t&&r([])},[t]);const c=b=>{r(m=>m.some(w=>w.name===b.name&&w.type===b.type)?m.filter(w=>!(w.name===b.name&&w.type===b.type)):[...m,b])},l=()=>{r([...o])},x=()=>{r([])},p=()=>{if(a.length===0)return;const b=a[0],m=b.connectionId||"",g=b.connectionType||"",E=a.some(A=>A.type==="dataset")?"semanticDomain":"database";i({connectionId:m,connectionType:g,mode:E,selectedEntities:a}),n(!1)},h=b=>"label"in b&&b.label?b.label:b.name,u=b=>{if("description"in b&&b.description)return b.description;const m=[];return b.database&&m.push(b.database),b.schema&&m.push(b.schema),b.name&&m.push(b.name),m.join(".")},y=b=>a.some(m=>m.name===b.name&&m.type===b.type);return o.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:l,disabled:a.length===o.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:x,disabled:a.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[a.length," of ",o.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:o.map((b,m)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",y(b)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:y(b),onCheckedChange:()=>c(b)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:s.getEntityIcon(b.type)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:h(b)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:u(b)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:b.type})]},`${b.type}-${b.name}-${m}`))})})]}),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:p,disabled:a.length===0,children:["Select"," ",a.length>0?`(${a.length})`:""]})]})})})]})})}function Zt({entities:t,title:n}){const{isConsoleMode:a}=s.useDashboardPreferences();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??`${t.length} more entities`}),e.jsx("div",{className:"space-y-1",children:t.map((r,i)=>{const d=s.getEntityDetails(r),o=d.find(l=>l.label==="Description"&&l.value),c=d.filter(l=>l.label==="Description"?!1:a?!0:!["Connection","Database","Schema"].includes(l.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(r)}),o&&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:o.value})]}),c.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:c.map((l,x)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[l.label,":"]}),e.jsx("span",{className:"font-mono",children:l.value})]},x))})]},`remaining-${r.type}-${r.name}-${i}`)})})]})})}function wa(t,n){const[a,r]=C.useState(()=>{const i=localStorage.getItem(t);return i?JSON.parse(i):n});return C.useEffect(()=>{localStorage.setItem(t,JSON.stringify(a))},[a,t]),[a,r]}function Ta({isVisible:t}){var m,g;const n=s.useEditorStore(w=>w.isDevMode);s.useSyncLegacyEditorState();const[a,r]=C.useState(!1),[i,d]=C.useState(!1),[o,c]=wa("semaphor:data-source-collapsed",!1),l=s.useEditorStore(w=>w.card.dataSource),x=s.useEditorStore(w=>{var E,V;return(V=(E=w.card)==null?void 0:E.config)==null?void 0:V.joinPlan}),{updateDataSource:p}=s.useEditorActions(),h=((m=l==null?void 0:l.selectedEntities)==null?void 0:m.length)||0,u=((g=x==null?void 0:x.joins)==null?void 0:g.length)||0,b={...{connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},...l,selectedEntities:(l==null?void 0:l.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex shrink-0 flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"min-w-[325px]":t,"w-0":!t,"min-w-0":!t}),children:[h===0&&u===0?e.jsx("div",{className:"px-4 pt-4",children:e.jsx("div",{className:"rounded-xl border border-border/55 bg-card p-3 shadow-[0_1px_2px_rgba(15,23,42,0.05)]",children:e.jsxs(s.Button,{className:"w-full bg-background",variant:"outline",onClick:()=>r(!0),children:[e.jsx(s.Database,{className:"mr-2 h-3.5 w-3.5"}),"Choose Dataset"]})})}):e.jsx("div",{className:"px-4 pt-4",children:e.jsxs("div",{className:"rounded-xl border border-border/55 bg-card p-3 shadow-[0_1px_2px_rgba(15,23,42,0.05)]",children:[e.jsxs("div",{className:s.cn("flex cursor-pointer items-center justify-between px-1",o?"pb-0":"pb-3"),onClick:()=>c(!o),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:"Data Source"}),o&&e.jsxs("div",{className:"flex items-center gap-1.5",onClick:w=>w.stopPropagation(),children:[h>0&&e.jsx(s.TooltipProvider,{delayDuration:100,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"h-5 cursor-pointer gap-1 px-1.5 text-xs transition-colors hover:bg-secondary/80",onClick:()=>r(!0),children:[e.jsx(s.Database,{className:"h-3 w-3"}),h]})}),e.jsx(Zt,{entities:b.selectedEntities,title:`${h} selected ${h===1?"entity":"entities"}`})]})}),u>0&&!n&&e.jsx(Xt,{variant:"badge"})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:w=>{w.stopPropagation(),c(!o)},children:o?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronUp,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden transition-all duration-200 ease-in-out",o?"max-h-0 opacity-0":"max-h-96 opacity-100"),children:[e.jsx("div",{className:"px-1",children:e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{className:"w-full bg-background",variant:"outline",onClick:()=>r(!0),children:[e.jsx(s.Database,{className:"mr-2 h-3.5 w-3.5"}),h===1?"Dataset":"Datasets",e.jsx("span",{className:"ml-2 flex h-5 min-w-5 items-center justify-center rounded-full border bg-muted-foreground px-1.5 text-xs font-medium text-background",children:h})]})}),e.jsx(Zt,{entities:b.selectedEntities,title:`${h} selected ${h===1?"entity":"entities"}`})]})})}),!n&&h>1&&e.jsx("div",{className:"mt-3 px-1",children:e.jsx(Xt,{})})]})]})}),e.jsx("div",{className:"min-h-0 flex-1 px-4 pb-4 pt-2",children:e.jsx("div",{className:"h-full overflow-hidden rounded-xl border border-border/55 bg-card shadow-[0_1px_2px_rgba(15,23,42,0.05)]",children:e.jsx(s.FieldsSection,{})})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(l==null?void 0:l.selectedEntities)||[],dialogMode:"dataSource",open:a,onOpenChange:r,dataSource:b}),e.jsx(kn,{open:i,onOpenChange:d})]})}function Dn(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 Ea(t){const{theme:n}=s.useTheme(),a=s.useDashboardStore(m=>m.theme),r=s.useEditorStore(m=>m.frame),i=s.useEditorStore(m=>m.card),d=s.useEditorStore(m=>m.activeTabCardId),o=s.Le(),{refetch:c}=s.useDashboardCardQuery(i),{updateCardTab:l,setRunSql:x}=s.useEditorActions(),p=C.useRef(void 0),h=C.useRef({}),u=r.cards.find(m=>m.id===d),y=C.useCallback(()=>{let m="";return t==="python"&&(m=(u==null?void 0:u.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(m=(u==null?void 0:u.sql)||""),m},[t,u]);C.useEffect(()=>{if(d&&i.id&&i.id!==d){if(p.current&&o){const m=p.current.getModel();m&&(h.current[i.id]=m);let g=h.current[d];if(!g){const w=y();g=o.editor.createModel(w,t),h.current[d]=g}p.current.setModel(g)}l(d,i),x(!0)}},[d,i,l,o,x,t,y]),C.useEffect(()=>{if(!o)return;const m=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",g=a==="system"?m:a;o.editor.defineTheme("default",{base:g==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":g==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),o.editor.setTheme("default")},[n,a,o]),C.useEffect(()=>{const m=p.current;m&&o&&i&&m.addCommand(o.KeyMod.Shift|o.KeyCode.Enter,function(){return c(),!1})},[o,c,i]);function b(m,g){if(p.current=m,!h.current[i.id]){const w=m.getModel(),E=y();h.current[i.id]=w||(g==null?void 0:g.editor.createModel(E,t))||m.getModel()}m.setModel(h.current[i.id])}return{handleEditorDidMount:b}}const An=300;function Mn(){const t=s.useEditorStore(p=>p.card.sql),n=s.useEditorStore(p=>p.sqlGen),{setCardSql:a,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:i}=Ea("sql"),d=C.useRef(n);d.current=n;const o=C.useCallback(p=>{a(p)},[a]),{value:c,onChange:l}=Ca({storeValue:t,defaultValue:"",onStoreUpdate:o,delay:An});function x(p){l(p),s.isObjectEmpty(d.current)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!c&&e.jsx("div",{className:"pointer-events-none absolute left-[36px] 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:x,value:c,options:{minimap:{enabled:!1},glyphMargin:!1,lineNumbersMinChars:2,lineDecorationsWidth:0,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:i})]})}const Ln=300;function On(){const t=s.useEditorStore(d=>d.card.python),{setCardPython:n}=s.useEditorActions(),{handleEditorDidMount:a}=Ea("python"),{value:r,onChange:i}=Ca({storeValue:t,defaultValue:s.PYTHON_DEFAULT_CODE,onStoreUpdate:n,delay:Ln});return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:i,value:r,options:{minimap:{enabled:!1},glyphMargin:!1,lineNumbersMinChars:2,lineDecorationsWidth:0,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:a})}const Rn={async writeTextToClipboard(t){return typeof navigator>"u"||!navigator.clipboard?!1:(await navigator.clipboard.writeText(t),!0)}},Ls=50,Fn=[{target:"queryRequest",label:"Query Request"},{target:"queryResponse",label:"Query Response"},{target:"cardConfig",label:"Card Config"},{target:"dataSource",label:"Data Source"},{target:"columns",label:"Columns"},{target:"dashboardFilters",label:"Dashboard Filters"},{target:"cardMetadata",label:"Card Metadata IDs"}];function ea(t){try{return JSON.stringify(t,null,2)}catch(n){return console.error("Unable to stringify debug payload",n),null}}function ps(t){switch(t){case"queryRequest":return"Query Request";case"queryResponse":return"Query Response";case"cardConfig":return"Card Config";case"dataSource":return"Data Source";case"cardMetadata":return"Card Metadata IDs";case"columns":return"Columns";case"dashboardFilters":return"Dashboard Filters";default:return"Payload"}}function Pn(t){if(!t||typeof t!="object")return{value:t};const n=t.records;return!Array.isArray(n)||n.length<=Ls?{value:t}:{value:{...t,records:n.slice(0,Ls),previewMeta:{truncatedRecords:!0,displayedRecords:Ls,totalRecords:n.length}},truncationMessage:`Preview showing first ${Ls} records of ${n.length}. Copy actions include full payload.`}}function Ia({sql:t,showCardDetails:n=!1,debugPayloads:a,className:r}){const[i,d]=C.useState(!1),[o,c]=C.useState(null),l=s.useEditorStore(I=>I.card),x=s.useEditorStore(I=>I.frame),p=s.useEditorStore(I=>I.isDevMode),h=s.useDashboardStore(I=>I.selectedSheetId),u=s.useDashboardStore(I=>{var j;return(j=I.dashboard)==null?void 0:j.id}),{switchEditorMode:y,setRunSql:b}=s.useEditorActions(),m=C.useMemo(()=>({cardId:l.id||null,frameId:x.id||null,sheetId:h||null,dashboardId:u||null}),[l.id,x.id,h,u]),g=C.useMemo(()=>({queryRequest:a==null?void 0:a.queryRequest,queryResponse:a==null?void 0:a.queryResponse,cardConfig:l.config,dataSource:l.dataSource,columns:a==null?void 0:a.columns,dashboardFilters:a==null?void 0:a.dashboardFilters,cardMetadata:m}),[a==null?void 0:a.queryRequest,a==null?void 0:a.queryResponse,a==null?void 0:a.columns,a==null?void 0:a.dashboardFilters,l.config,l.dataSource,m]),w=n&&i&&!!a,E=C.useMemo(()=>[{label:"Card ID",value:l.id||""},{label:"Frame ID",value:x.id||""},{label:"Sheet ID",value:h||""},{label:"Dashboard ID",value:u||""}],[l.id,x.id,h,u]),V=()=>{y("dev",{sqlToLoad:t}),setTimeout(()=>{b(!0)},100)},A=I=>g[I]!==void 0,T=C.useMemo(()=>{if(!o)return null;const I=g[o];if(I===void 0)return null;const j=o==="queryResponse"?Pn(I):{value:I},k=ea(j.value);return k?{target:o,title:ps(o),json:k,truncationMessage:j.truncationMessage}:null},[o,g]),v=T?T.title:"Preview Payload",D=async I=>{const j=g[I];if(j===void 0)return s.ue.error(`No ${ps(I).toLowerCase()} available`),!1;const k=ea(j);if(!k)return s.ue.error(`Unable to serialize ${ps(I).toLowerCase()}`),!1;try{return await Rn.writeTextToClipboard(k)?(s.ue.success(`${ps(I)} copied`),!0):(s.ue.error("Clipboard is not available"),!1)}catch(R){return console.error("Failed to copy debug payload",R),s.ue.error(`Unable to copy ${ps(I).toLowerCase()}`),!1}},L=async()=>T?D(T.target):!1,f=I=>{if(g[I]===void 0){s.ue.error(`No ${ps(I).toLowerCase()} available`);return}c(I)};return e.jsxs("div",{className:s.cn("flex min-h-0 flex-1 flex-col",r),children:[!p&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsxs(s.Button,{onClick:V,variant:"secondary",size:"sm",children:[e.jsx(ya,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),n&&e.jsxs(s.Button,{onClick:()=>d(!i),variant:"outline",size:"sm",children:[e.jsx(s.Info,{className:"mr-2 h-4 w-4"}),"Card Details"]})]}),i&&n&&e.jsx("div",{className:"mb-3 rounded-lg border border-border bg-muted/30 p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Card Information"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>d(!1),children:e.jsx(Ae.CircleX,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"grid grid-cols-1 gap-2 md:grid-cols-2",children:E.map(I=>e.jsxs("div",{className:"min-w-0 rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:I.label}),e.jsx(s.CopyButton,{text:I.value,className:"h-6 w-6 shrink-0"})]}),e.jsx("code",{title:I.value||"N/A",className:"mt-1 block whitespace-normal break-all font-mono text-xs",children:I.value||"N/A"})]},I.label))}),w&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-background/70 p-3",children:[e.jsx("p",{className:"text-xs font-semibold text-muted-foreground",children:"Debug Tools"}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8","aria-label":"Preview Payload Menu",children:[e.jsx(s.Eye,{className:"mr-1.5 h-3.5 w-3.5"}),v,e.jsx(s.ChevronDown,{className:"ml-1.5 h-3.5 w-3.5"})]})}),e.jsx(s.DropdownMenuContent,{align:"start",className:"w-56",children:Fn.map(I=>e.jsx(s.DropdownMenuItem,{disabled:!A(I.target),onSelect:()=>f(I.target),className:s.cn(o===I.target&&"bg-accent"),children:I.label},`preview-${I.target}`))})]})}),T&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs font-medium text-muted-foreground",children:[T.title," Preview"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.CopyButton,{text:T.json,className:"h-6 w-6",ariaLabel:"Copy Payload",onCopy:L}),e.jsxs(s.Button,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>c(null),children:[e.jsx(Ae.CircleX,{className:"mr-1 h-3.5 w-3.5"}),"Hide"]})]})]}),T.truncationMessage&&e.jsx("p",{className:"text-xs text-muted-foreground",children:T.truncationMessage}),e.jsx("div",{className:"max-h-80 overflow-auto",children:e.jsx(s.CodeHighlighter,{code:T.json,language:"json"})})]})]})]})}),e.jsx("div",{className:"min-h-0 flex-1 overflow-auto text-xs leading-relaxed text-foreground/80",children:e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsxs("div",{className:"group relative",children:[e.jsx("div",{className:"absolute right-2 top-2 z-10 rounded-md border border-border/60 bg-background/85 p-0.5 shadow-sm backdrop-blur-sm transition-opacity duration-150",children:e.jsx(s.CopyButton,{text:t,className:"h-6 w-6 px-0 text-muted-foreground/80 hover:text-foreground"})}),e.jsx(s.CodeHighlighter,{code:t,language:"sql",wrapLongLines:!0})]})})})]})}function Vn(t){const{request:n,mode:a="draft",currentSql:r,selectedTableName:i,selectedSchemaName:d,selectedDatabaseName:o}=t,c=[o?`Database: ${o}`:"",d?`Schema: ${d}`:"",i?`Table: ${i}`:""].filter(Boolean);return["You are an expert SQL writing assistant embedded in a query editor.",`Write SQL only. You may call only read-only tools when needed: ${s.INLINE_ALLOWED_TOOL_LIST}.`,"Do not call mutation tools or chart-creation tools; those require Full Assistant.","Return exactly one SQL statement inside a single ```sql fenced block.","After the code block, optionally include one short sentence.",a==="refine"&&r?"Mode: Refine existing SQL. Keep the current query structure and only apply the requested changes unless the current query is invalid.":"Mode: Draft new SQL from the request.",c.length>0?`Context:
|
|
159
|
+
ON ${k}`}),M},isValidConfiguration:()=>!(!a.baseEntity.name||a.joins.some(f=>!f.source.name||!f.target.name)||a.joins.some(f=>f.joinKeyGroups.some(I=>I.keys.length===0))||a.joins.some(f=>f.joinKeyGroups.some(I=>I.keys.some(j=>!j.source.name||!j.target.name||!j.operator))))}}function In({joinPlan:t,availableDataSources:n,onSave:a,onRemove:r,onCancel:i}){const{setCardConfig:d}=s.useEditorActions();s.useEditorStore(k=>k.card.config);const{columnGroups:o}=s.useColumns(),c=o.filter(k=>k.entityName!==s.CALCULATED_FIELDS_GROUP_NAME),{joinPlan:l,expandedJoins:x,setJoinPlan:p,addJoin:h,removeJoin:u,updateJoin:y,moveJoinUp:b,moveJoinDown:m,toggleJoinExpansion:g,getAvailableSourceEntities:w,getAvailableTargetEntities:E,addJoinKeyGroup:V,updateGroupOperator:A,removeJoinKeyGroup:T,addJoinKey:v,updateJoinKey:D,removeJoinKey:M,generateSQLPreview:f,isValidConfiguration:I}=En({initialJoinPlan:t,availableDataSources:n}),j=k=>{const R=c.find(P=>P.entityName===k);return(R==null?void 0:R.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:l.baseEntity.name,onValueChange:k=>{const R=n.find(P=>P.name===k);p({...l,baseEntity:{connectionId:(R==null?void 0:R.connectionId)||"",connectionType:(R==null?void 0:R.connectionType)||"none",type:(R==null?void 0:R.type)||"table",name:k,database:R==null?void 0:R.database,schema:R==null?void 0:R.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:n.map(k=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:k.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:k.type}),k.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},k.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:f()})]}),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 (",l.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:h,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),l.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:l.joins.map(k=>{const R=n.find(L=>L.name===k.source.name),P=n.find(L=>L.name===k.target.name),N=x.has(k.id);return e.jsxs(s.Card,{className:"border",children:[e.jsx(s.CardHeader,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{children:k.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",k.sequence,R&&P&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",R.name," → ",P.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>b(k.id),disabled:k.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>m(k.id),disabled:k.sequence===l.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g(k.id),children:N?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>u(k.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),N&&e.jsxs(s.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Source"}),e.jsxs(s.Select,{value:k.source.name,onValueChange:L=>{const S=n.find(F=>F.name===L);y(k.id,{source:{connectionId:(S==null?void 0:S.connectionId)||"",connectionType:(S==null?void 0:S.connectionType)||"none",type:(S==null?void 0:S.type)||"table",name:L,database:S==null?void 0:S.database,schema:S==null?void 0:S.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:w(k.id).map(L=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:L.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:L.type}),L.name]})},L.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:k.joinType,onValueChange:L=>y(k.id,{joinType:L}),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Target"}),e.jsxs(s.Select,{value:k.target.name,onValueChange:L=>{const S=n.find(F=>F.name===L);y(k.id,{target:{connectionId:(S==null?void 0:S.connectionId)||"",connectionType:(S==null?void 0:S.connectionType)||"none",type:(S==null?void 0:S.type)||"table",name:L,database:S==null?void 0:S.database,schema:S==null?void 0:S.schema}})},disabled:!k.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:k.source.name?E(k.source.name).map(L=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:L.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:L.type}),L.name,L.name===k.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},L.name)):[]})]})]})]}),k.source.name&&k.target.name&&R&&P&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>V(k.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),k.joinKeyGroups.length===0?e.jsx("div",{className:"rounded-md border p-3 text-center text-sm text-gray-500",children:"No join conditions defined. Add condition groups to specify how data sources should be joined."}):e.jsx("div",{className:"space-y-4",children:k.joinKeyGroups.map((L,S)=>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 ",S+1]}),S>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(s.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Select,{value:L.operator,onValueChange:F=>A(k.id,S,F),children:[e.jsx(s.SelectTrigger,{className:"w-[100px]",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>T(k.id,S),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[L.keys.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-sm text-gray-500",children:"No conditions in this group. Add conditions to specify join criteria."}):e.jsx("div",{className:"space-y-2",children:L.keys.map((F,O)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[O>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:L.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:F.source.name,onValueChange:_=>D(k.id,S,O,"sourceColumnName",_),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:j(k.source.name).map(_=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:_.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:_.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:_.dataType})]})},_.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:F.operator,onValueChange:_=>D(k.id,S,O,"operator",_),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:F.target.name,onValueChange:_=>D(k.id,S,O,"targetColumnName",_),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:j(k.target.name).map(_=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:_.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:_.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:_.dataType})]})},_.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>M(k.id,S,O),children:e.jsx(s.X,{className:"size-3.5"})})]},F.id||O))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>v(k.id,S),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},L.id))})]})]})]},k.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),i()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:i,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>a(l),disabled:!I(),children:"Save"})]})]})}function wa({children:t,open:n,onOpenChange:a,joinPlan:r,availableDataSources:i,onRemove:d,onSave:o,onCancel:c}){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(In,{joinPlan:r,availableDataSources:i,onSave:o,onCancel:c,onRemove:d})]}),t]})}function kn({joins:t,baseEntityId:n,availableDataSources:a,generateSQLPreview:r}){return e.jsxs("div",{className:"my-2 max-h-[400px] divide-y divide-border overflow-y-auto",children:[t.length>0&&e.jsxs("div",{className:"px-4 py-2",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 i=[...t].sort((o,c)=>o.sequence-c.sequence),d=a.find(o=>o.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:d==null?void 0:d.type}),e.jsx("span",{className:"text-xs font-medium",children:d==null?void 0:d.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),i.map(o=>{const c=a.find(l=>l.name===o.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:o.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:c==null?void 0:c.type}),e.jsx("span",{className:"text-xs font-medium",children:c==null?void 0:c.name})]})]},o.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((i,d)=>i.sequence-d.sequence).map((i,d)=>{const o=a.find(x=>x.name===i.source.name),c=a.find(x=>x.name===i.target.name),l=i.joinKeyGroups.reduce((x,p)=>x+p.keys.length,0);return e.jsxs("div",{className:"rounded-md bg-muted p-2 text-left",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:d+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:i.joinType}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto shrink-0 text-xs",children:[l," condition",l>1?"s":""]})]}),e.jsxs("div",{className:"mt-1 truncate pl-1 text-xs text-muted-foreground",children:[o==null?void 0:o.name," → ",c==null?void 0:c.name]})]},i.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 Zt({open:t,onOpenChange:n,variant:a="button"}={}){var E,V;const r=s.useEditorStore(A=>A.card),{autoJoinMetadata:i}=s.useDashboardCardQuery(r),d=s.useEditorStore(A=>A.actions.updateCardConfig),o=((E=r==null?void 0:r.config)==null?void 0:E.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[c,l]=C.useState(!1),x=t!==void 0,p=x?t:c,h=x?n:l,u=((V=r==null?void 0:r.dataSource)==null?void 0:V.selectedEntities)||[],y=A=>{d(r.id,{...r==null?void 0:r.config,joinPlan:A}),h(!1)},b=()=>{d(r.id,{...r==null?void 0:r.config,joinPlan:void 0})},m=()=>{h(!1)},g=()=>{const A=[...o.joins].sort((D,M)=>D.sequence-M.sequence),T=o.baseEntity;if(!T.name)return"SELECT * FROM table -- Please select a base entity";let v=`SELECT *
|
|
160
|
+
FROM ${T.name}`;return A.forEach(D=>{const M=u.find(j=>j.name===D.target.name);if(!M)return;const f=D.joinKeyGroups.filter(j=>j.keys&&j.keys.length>0).map(j=>{const k=j.keys.filter(R=>{var P,N,L,S;return((P=R.source)==null?void 0:P.name)&&((N=R.target)==null?void 0:N.name)&&((L=R.source)==null?void 0:L.entityName)&&((S=R.target)==null?void 0:S.entityName)}).map(R=>`${R.source.entityName}.${R.source.name} ${R.operator} ${R.target.entityName}.${R.target.name}`);return k.length>1?`(${k.join(` ${j.operator} `)})`:k[0]}).filter(Boolean),I=f.length>1?f.join(" OR "):f[0]||"condition_here";v+=`
|
|
161
|
+
${D.joinType} JOIN ${M.name}
|
|
162
|
+
ON ${I}`}),v};if(u.length<2)return null;const w=o.joins.length>0&&e.jsx(s.TooltipContent,{side:"bottom",className:"ml-4 max-w-md overflow-hidden p-0",children:e.jsx(kn,{joins:o.joins,baseEntityId:o.baseEntity.name,availableDataSources:u,generateSQLPreview:g})});return e.jsxs(e.Fragment,{children:[e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:a==="badge"?e.jsxs(s.Badge,{variant:"secondary",className:"h-5 cursor-pointer gap-1 px-1.5 text-xs transition-colors hover:bg-secondary/80",onClick:A=>{A.stopPropagation(),h(!0)},children:[e.jsx(s.Link,{className:"h-3 w-3"}),o.joins.length]}):e.jsxs(s.Button,{onClick:()=>h(!0),variant:"outline",className:"w-full bg-muted/50",children:[e.jsx(s.Link,{className:"mr-2 h-3.5 w-3.5"}),o.joins.length===0?"Configure Joins":o.joins.length===1?"Join":"Joins",o.joins.length>0&&e.jsx("span",{className:"ml-2 flex h-5 min-w-5 items-center justify-center rounded-full border bg-muted-foreground px-1.5 text-xs font-medium text-background",children:o.joins.length}),(i==null?void 0:i.autoResolved)&&e.jsxs(s.Badge,{variant:"secondary",className:"ml-2 h-5 gap-1 bg-blue-50 text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:[e.jsx(s.Sparkles,{className:"h-3 w-3"}),"Auto"]})]})}),w]})}),e.jsx(wa,{open:p,onOpenChange:h,joinPlan:o,availableDataSources:u,onSave:y,onCancel:m,onRemove:b,children:e.jsx("div",{})})]})}function Dn({open:t,onOpenChange:n}){const[a,r]=C.useState([]),{updateDataSource:i}=s.useEditorActions(),d=s.useDashboardStore(b=>b.dashboard.aiContext),o=(d==null?void 0:d.selectedEntities)||[];C.useEffect(()=>{t&&r([])},[t]);const c=b=>{r(m=>m.some(w=>w.name===b.name&&w.type===b.type)?m.filter(w=>!(w.name===b.name&&w.type===b.type)):[...m,b])},l=()=>{r([...o])},x=()=>{r([])},p=()=>{if(a.length===0)return;const b=a[0],m=b.connectionId||"",g=b.connectionType||"",E=a.some(A=>A.type==="dataset")?"semanticDomain":"database";i({connectionId:m,connectionType:g,mode:E,selectedEntities:a}),n(!1)},h=b=>"label"in b&&b.label?b.label:b.name,u=b=>{if("description"in b&&b.description)return b.description;const m=[];return b.database&&m.push(b.database),b.schema&&m.push(b.schema),b.name&&m.push(b.name),m.join(".")},y=b=>a.some(m=>m.name===b.name&&m.type===b.type);return o.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:l,disabled:a.length===o.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:x,disabled:a.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[a.length," of ",o.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:o.map((b,m)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",y(b)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:y(b),onCheckedChange:()=>c(b)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:s.getEntityIcon(b.type)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:h(b)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:u(b)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:b.type})]},`${b.type}-${b.name}-${m}`))})})]}),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:p,disabled:a.length===0,children:["Select"," ",a.length>0?`(${a.length})`:""]})]})})})]})})}function ea({entities:t,title:n}){const{isConsoleMode:a}=s.useDashboardPreferences();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??`${t.length} more entities`}),e.jsx("div",{className:"space-y-1",children:t.map((r,i)=>{const d=s.getEntityDetails(r),o=d.find(l=>l.label==="Description"&&l.value),c=d.filter(l=>l.label==="Description"?!1:a?!0:!["Connection","Database","Schema"].includes(l.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(r)}),o&&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:o.value})]}),c.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:c.map((l,x)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[l.label,":"]}),e.jsx("span",{className:"font-mono",children:l.value})]},x))})]},`remaining-${r.type}-${r.name}-${i}`)})})]})})}function Ta(t,n){const[a,r]=C.useState(()=>{const i=localStorage.getItem(t);return i?JSON.parse(i):n});return C.useEffect(()=>{localStorage.setItem(t,JSON.stringify(a))},[a,t]),[a,r]}function Ea({isVisible:t}){var m,g;const n=s.useEditorStore(w=>w.isDevMode);s.useSyncLegacyEditorState();const[a,r]=C.useState(!1),[i,d]=C.useState(!1),[o,c]=Ta("semaphor:data-source-collapsed",!1),l=s.useEditorStore(w=>w.card.dataSource),x=s.useEditorStore(w=>{var E,V;return(V=(E=w.card)==null?void 0:E.config)==null?void 0:V.joinPlan}),{updateDataSource:p}=s.useEditorActions(),h=((m=l==null?void 0:l.selectedEntities)==null?void 0:m.length)||0,u=((g=x==null?void 0:x.joins)==null?void 0:g.length)||0,b={...{connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},...l,selectedEntities:(l==null?void 0:l.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex shrink-0 flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"min-w-[325px]":t,"w-0":!t,"min-w-0":!t}),children:[h===0&&u===0?e.jsx("div",{className:"px-4 pt-4",children:e.jsx("div",{className:"rounded-xl border border-border/55 bg-card p-3 shadow-[0_1px_2px_rgba(15,23,42,0.05)]",children:e.jsxs(s.Button,{className:"w-full bg-background",variant:"outline",onClick:()=>r(!0),children:[e.jsx(s.Database,{className:"mr-2 h-3.5 w-3.5"}),"Choose Dataset"]})})}):e.jsx("div",{className:"px-4 pt-4",children:e.jsxs("div",{className:"rounded-xl border border-border/55 bg-card p-3 shadow-[0_1px_2px_rgba(15,23,42,0.05)]",children:[e.jsxs("div",{className:s.cn("flex cursor-pointer items-center justify-between px-1",o?"pb-0":"pb-3"),onClick:()=>c(!o),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:"Data Source"}),o&&e.jsxs("div",{className:"flex items-center gap-1.5",onClick:w=>w.stopPropagation(),children:[h>0&&e.jsx(s.TooltipProvider,{delayDuration:100,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"h-5 cursor-pointer gap-1 px-1.5 text-xs transition-colors hover:bg-secondary/80",onClick:()=>r(!0),children:[e.jsx(s.Database,{className:"h-3 w-3"}),h]})}),e.jsx(ea,{entities:b.selectedEntities,title:`${h} selected ${h===1?"entity":"entities"}`})]})}),u>0&&!n&&e.jsx(Zt,{variant:"badge"})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:w=>{w.stopPropagation(),c(!o)},children:o?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronUp,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden transition-all duration-200 ease-in-out",o?"max-h-0 opacity-0":"max-h-96 opacity-100"),children:[e.jsx("div",{className:"px-1",children:e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{className:"w-full bg-background",variant:"outline",onClick:()=>r(!0),children:[e.jsx(s.Database,{className:"mr-2 h-3.5 w-3.5"}),h===1?"Dataset":"Datasets",e.jsx("span",{className:"ml-2 flex h-5 min-w-5 items-center justify-center rounded-full border bg-muted-foreground px-1.5 text-xs font-medium text-background",children:h})]})}),e.jsx(ea,{entities:b.selectedEntities,title:`${h} selected ${h===1?"entity":"entities"}`})]})})}),!n&&h>1&&e.jsx("div",{className:"mt-3 px-1",children:e.jsx(Zt,{})})]})]})}),e.jsx("div",{className:"min-h-0 flex-1 px-4 pb-4 pt-2",children:e.jsx("div",{className:"h-full overflow-hidden rounded-xl border border-border/55 bg-card shadow-[0_1px_2px_rgba(15,23,42,0.05)]",children:e.jsx(s.FieldsSection,{})})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(l==null?void 0:l.selectedEntities)||[],dialogMode:"dataSource",open:a,onOpenChange:r,dataSource:b}),e.jsx(Dn,{open:i,onOpenChange:d})]})}function An(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 Ia(t){const{theme:n}=s.useTheme(),a=s.useDashboardStore(m=>m.theme),r=s.useEditorStore(m=>m.frame),i=s.useEditorStore(m=>m.card),d=s.useEditorStore(m=>m.activeTabCardId),o=s.Le(),{refetch:c}=s.useDashboardCardQuery(i),{updateCardTab:l,setRunSql:x}=s.useEditorActions(),p=C.useRef(void 0),h=C.useRef({}),u=r.cards.find(m=>m.id===d),y=C.useCallback(()=>{let m="";return t==="python"&&(m=(u==null?void 0:u.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(m=(u==null?void 0:u.sql)||""),m},[t,u]);C.useEffect(()=>{if(d&&i.id&&i.id!==d){if(p.current&&o){const m=p.current.getModel();m&&(h.current[i.id]=m);let g=h.current[d];if(!g){const w=y();g=o.editor.createModel(w,t),h.current[d]=g}p.current.setModel(g)}l(d,i),x(!0)}},[d,i,l,o,x,t,y]),C.useEffect(()=>{if(!o)return;const m=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",g=a==="system"?m:a;o.editor.defineTheme("default",{base:g==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":g==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),o.editor.setTheme("default")},[n,a,o]),C.useEffect(()=>{const m=p.current;m&&o&&i&&m.addCommand(o.KeyMod.Shift|o.KeyCode.Enter,function(){return c(),!1})},[o,c,i]);function b(m,g){if(p.current=m,!h.current[i.id]){const w=m.getModel(),E=y();h.current[i.id]=w||(g==null?void 0:g.editor.createModel(E,t))||m.getModel()}m.setModel(h.current[i.id])}return{handleEditorDidMount:b}}const Ln=300;function Mn(){const t=s.useEditorStore(p=>p.card.sql),n=s.useEditorStore(p=>p.sqlGen),{setCardSql:a,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:i}=Ia("sql"),d=C.useRef(n);d.current=n;const o=C.useCallback(p=>{a(p)},[a]),{value:c,onChange:l}=Sa({storeValue:t,defaultValue:"",onStoreUpdate:o,delay:Ln});function x(p){l(p),s.isObjectEmpty(d.current)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!c&&e.jsx("div",{className:"pointer-events-none absolute left-[36px] 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:x,value:c,options:{minimap:{enabled:!1},glyphMargin:!1,lineNumbersMinChars:2,lineDecorationsWidth:0,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:i})]})}const On=300;function Rn(){const t=s.useEditorStore(d=>d.card.python),{setCardPython:n}=s.useEditorActions(),{handleEditorDidMount:a}=Ia("python"),{value:r,onChange:i}=Sa({storeValue:t,defaultValue:s.PYTHON_DEFAULT_CODE,onStoreUpdate:n,delay:On});return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:i,value:r,options:{minimap:{enabled:!1},glyphMargin:!1,lineNumbersMinChars:2,lineDecorationsWidth:0,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:a})}const Fn={async writeTextToClipboard(t){return typeof navigator>"u"||!navigator.clipboard?!1:(await navigator.clipboard.writeText(t),!0)}},Os=50,Pn=[{target:"queryRequest",label:"Query Request"},{target:"queryResponse",label:"Query Response"},{target:"cardConfig",label:"Card Config"},{target:"dataSource",label:"Data Source"},{target:"columns",label:"Columns"},{target:"dashboardFilters",label:"Dashboard Filters"},{target:"cardMetadata",label:"Card Metadata IDs"}];function sa(t){try{return JSON.stringify(t,null,2)}catch(n){return console.error("Unable to stringify debug payload",n),null}}function ps(t){switch(t){case"queryRequest":return"Query Request";case"queryResponse":return"Query Response";case"cardConfig":return"Card Config";case"dataSource":return"Data Source";case"cardMetadata":return"Card Metadata IDs";case"columns":return"Columns";case"dashboardFilters":return"Dashboard Filters";default:return"Payload"}}function Vn(t){if(!t||typeof t!="object")return{value:t};const n=t.records;return!Array.isArray(n)||n.length<=Os?{value:t}:{value:{...t,records:n.slice(0,Os),previewMeta:{truncatedRecords:!0,displayedRecords:Os,totalRecords:n.length}},truncationMessage:`Preview showing first ${Os} records of ${n.length}. Copy actions include full payload.`}}function ka({sql:t,showCardDetails:n=!1,debugPayloads:a,className:r}){const[i,d]=C.useState(!1),[o,c]=C.useState(null),l=s.useEditorStore(I=>I.card),x=s.useEditorStore(I=>I.frame),p=s.useEditorStore(I=>I.isDevMode),h=s.useDashboardStore(I=>I.selectedSheetId),u=s.useDashboardStore(I=>{var j;return(j=I.dashboard)==null?void 0:j.id}),{switchEditorMode:y,setRunSql:b}=s.useEditorActions(),m=C.useMemo(()=>({cardId:l.id||null,frameId:x.id||null,sheetId:h||null,dashboardId:u||null}),[l.id,x.id,h,u]),g=C.useMemo(()=>({queryRequest:a==null?void 0:a.queryRequest,queryResponse:a==null?void 0:a.queryResponse,cardConfig:l.config,dataSource:l.dataSource,columns:a==null?void 0:a.columns,dashboardFilters:a==null?void 0:a.dashboardFilters,cardMetadata:m}),[a==null?void 0:a.queryRequest,a==null?void 0:a.queryResponse,a==null?void 0:a.columns,a==null?void 0:a.dashboardFilters,l.config,l.dataSource,m]),w=n&&i&&!!a,E=C.useMemo(()=>[{label:"Card ID",value:l.id||""},{label:"Frame ID",value:x.id||""},{label:"Sheet ID",value:h||""},{label:"Dashboard ID",value:u||""}],[l.id,x.id,h,u]),V=()=>{y("dev",{sqlToLoad:t}),setTimeout(()=>{b(!0)},100)},A=I=>g[I]!==void 0,T=C.useMemo(()=>{if(!o)return null;const I=g[o];if(I===void 0)return null;const j=o==="queryResponse"?Vn(I):{value:I},k=sa(j.value);return k?{target:o,title:ps(o),json:k,truncationMessage:j.truncationMessage}:null},[o,g]),v=T?T.title:"Preview Payload",D=async I=>{const j=g[I];if(j===void 0)return s.ue.error(`No ${ps(I).toLowerCase()} available`),!1;const k=sa(j);if(!k)return s.ue.error(`Unable to serialize ${ps(I).toLowerCase()}`),!1;try{return await Fn.writeTextToClipboard(k)?(s.ue.success(`${ps(I)} copied`),!0):(s.ue.error("Clipboard is not available"),!1)}catch(R){return console.error("Failed to copy debug payload",R),s.ue.error(`Unable to copy ${ps(I).toLowerCase()}`),!1}},M=async()=>T?D(T.target):!1,f=I=>{if(g[I]===void 0){s.ue.error(`No ${ps(I).toLowerCase()} available`);return}c(I)};return e.jsxs("div",{className:s.cn("flex min-h-0 flex-1 flex-col",r),children:[!p&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsxs(s.Button,{onClick:V,variant:"secondary",size:"sm",children:[e.jsx(Na,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),n&&e.jsxs(s.Button,{onClick:()=>d(!i),variant:"outline",size:"sm",children:[e.jsx(s.Info,{className:"mr-2 h-4 w-4"}),"Card Details"]})]}),i&&n&&e.jsx("div",{className:"mb-3 rounded-lg border border-border bg-muted/30 p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Card Information"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>d(!1),children:e.jsx(Ae.CircleX,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"grid grid-cols-1 gap-2 md:grid-cols-2",children:E.map(I=>e.jsxs("div",{className:"min-w-0 rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:I.label}),e.jsx(s.CopyButton,{text:I.value,className:"h-6 w-6 shrink-0"})]}),e.jsx("code",{title:I.value||"N/A",className:"mt-1 block whitespace-normal break-all font-mono text-xs",children:I.value||"N/A"})]},I.label))}),w&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-background/70 p-3",children:[e.jsx("p",{className:"text-xs font-semibold text-muted-foreground",children:"Debug Tools"}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8","aria-label":"Preview Payload Menu",children:[e.jsx(s.Eye,{className:"mr-1.5 h-3.5 w-3.5"}),v,e.jsx(s.ChevronDown,{className:"ml-1.5 h-3.5 w-3.5"})]})}),e.jsx(s.DropdownMenuContent,{align:"start",className:"w-56",children:Pn.map(I=>e.jsx(s.DropdownMenuItem,{disabled:!A(I.target),onSelect:()=>f(I.target),className:s.cn(o===I.target&&"bg-accent"),children:I.label},`preview-${I.target}`))})]})}),T&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs font-medium text-muted-foreground",children:[T.title," Preview"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.CopyButton,{text:T.json,className:"h-6 w-6",ariaLabel:"Copy Payload",onCopy:M}),e.jsxs(s.Button,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>c(null),children:[e.jsx(Ae.CircleX,{className:"mr-1 h-3.5 w-3.5"}),"Hide"]})]})]}),T.truncationMessage&&e.jsx("p",{className:"text-xs text-muted-foreground",children:T.truncationMessage}),e.jsx("div",{className:"max-h-80 overflow-auto",children:e.jsx(s.CodeHighlighter,{code:T.json,language:"json"})})]})]})]})}),e.jsx("div",{className:"min-h-0 flex-1 overflow-auto text-xs leading-relaxed text-foreground/80",children:e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsxs("div",{className:"group relative",children:[e.jsx("div",{className:"absolute right-2 top-2 z-10 rounded-md border border-border/60 bg-background/85 p-0.5 shadow-sm backdrop-blur-sm transition-opacity duration-150",children:e.jsx(s.CopyButton,{text:t,className:"h-6 w-6 px-0 text-muted-foreground/80 hover:text-foreground"})}),e.jsx(s.CodeHighlighter,{code:t,language:"sql",wrapLongLines:!0})]})})})]})}function Bn(t){const{request:n,mode:a="draft",currentSql:r,selectedTableName:i,selectedSchemaName:d,selectedDatabaseName:o}=t,c=[o?`Database: ${o}`:"",d?`Schema: ${d}`:"",i?`Table: ${i}`:""].filter(Boolean);return["You are an expert SQL writing assistant embedded in a query editor.",`Write SQL only. You may call only read-only tools when needed: ${s.INLINE_ALLOWED_TOOL_LIST}.`,"Do not call mutation tools or chart-creation tools; those require Full Assistant.","Return exactly one SQL statement inside a single ```sql fenced block.","After the code block, optionally include one short sentence.",a==="refine"&&r?"Mode: Refine existing SQL. Keep the current query structure and only apply the requested changes unless the current query is invalid.":"Mode: Draft new SQL from the request.",c.length>0?`Context:
|
|
163
163
|
${c.join(`
|
|
164
164
|
`)}`:"",r?a==="refine"?`Current SQL (must refine):
|
|
165
165
|
${r}`:`Current SQL (revise if useful):
|
|
166
166
|
${r}`:"",`User request:
|
|
167
167
|
${n}`].filter(Boolean).join(`
|
|
168
168
|
|
|
169
|
-
`)}function
|
|
169
|
+
`)}function zn(t){const{request:n,failedSql:a,errorMessage:r,errorCode:i,selectedDatabaseName:d,selectedSchemaName:o,selectedTableName:c,contextEntityLabels:l}=t,x=[d?`Database: ${d}`:"",o?`Schema: ${o}`:"",c?`Table: ${c}`:"",l.length>0?`Selected context entities: ${l.join(", ")}`:""].filter(Boolean);return["You are fixing SQL after validation failed.","Return one read-only SQL statement in a single ```sql fenced block.","Do not call mutation tools.",x.length>0?`Context:
|
|
170
170
|
${x.join(`
|
|
171
171
|
`)}`:"",`Original user request:
|
|
172
172
|
${n}`,`Previous SQL draft:
|
|
173
173
|
${a}`,`Validation failure${i?` (${i})`:""}:
|
|
174
174
|
${r}`].filter(Boolean).join(`
|
|
175
175
|
|
|
176
|
-
`)}function zn(t,n){typeof window>"u"||window.dispatchEvent(new CustomEvent("semaphor:inline-query-writer",{detail:{event:t,...n,timestamp:Date.now()}}))}const Js={runId:0,phase:"idle",attempt:0,activeStep:"",timelineSteps:[],lastValidation:null,finalOutcome:"idle",hasTools:!1};function qn(t){if(typeof t=="string"&&(t==="SQL_EMPTY"||t==="SQL_PARSE_ERROR"||t==="SQL_MULTI_STATEMENT"||t==="SQL_READ_ONLY_VIOLATION"||t==="SQL_EXPLAIN_ERROR"||t==="SQL_CONNECTION_ERROR"))return t}function sa(t){let n=0;for(let a=0;a<t.length;a+=1)n=(n<<5)-n+t.charCodeAt(a),n|=0;return String(n)}function ta(t){return t==="getTableColumns"?"Discovering columns":t==="getDomainRelationships"?"Resolving relationships":t==="getChartSQLSyntax"?"Reviewing SQL syntax":t==="getUserSql"?"Inspecting current query":"Analyzing context"}function $n(t,n){return t===s.SELF_HEAL_TIMELINE_STEP&&n>0?`${s.SELF_HEAL_TIMELINE_STEP} ${n}/${s.MAX_SELF_HEAL_ATTEMPTS}`:t}function Os(t){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`${t}-${crypto.randomUUID()}`:`${t}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function aa(t){var n;for(let a=t.length-1;a>=0;a-=1){const r=t[a];if(r.role!=="user")continue;const i=(n=r.metadata)==null?void 0:n.inlineRunToken;if(typeof i=="string"&&i.length>0)return i}}function _n(t){if(!t)return"";const n=t.trim(),a=t.match(/```sql\s*([\s\S]*?)```/i);if(a!=null&&a[1])return a[1].trim();const r=t.match(/```[\w-]*\s*([\s\S]*?)```/i);return r!=null&&r[1]?r[1].trim():/^(select|with|insert|update|delete)\b/i.test(n)?n:""}function na(t){for(let n=t.length-1;n>=0;n-=1){const a=t[n];if(!(a.role!=="assistant"||!Array.isArray(a.parts)))for(let r=a.parts.length-1;r>=0;r-=1){const i=a.parts[r];if((i==null?void 0:i.type)!=="text"||typeof(i==null?void 0:i.text)!="string")continue;const d=_n(i.text);if(d)return d}}return""}function Gn({currentSql:t,currentPython:n,selectedDatabaseName:a,selectedSchemaName:r,selectedTableName:i,onApplySql:d,onOpenFullAssistant:o}){var Pe,us;const{authToken:c,tokenProps:l}=s.useSemaphorContext(),x=(Pe=s.useDashboardQuery().data)==null?void 0:Pe.assistantProfileId,p=s.useEditorStore(G=>G.isDevMode),h=s.useEditorStore(G=>G.selectedConnectionId),u=s.useEditorStore(G=>{var Y;return(Y=G.card.dataSource)==null?void 0:Y.selectedEntities}),y=s.useAIInteractionStore(G=>G.currentAIContext.selectedEntities),b=y.length,{setCurrentAIContext:m}=s.useAIActions(),[g,w]=C.useState(""),[E,V]=C.useState(""),[A,T]=C.useState(""),[v,D]=C.useState("draft"),[L,f]=C.useState("draft"),[I,j]=C.useState(""),[k,R]=C.useState(!1),[P,N]=C.useState({status:"idle"}),[M,S]=C.useState(Js),[F,O]=C.useState(!1),[$,Q]=C.useState(()=>Os("inline-query-session")),B=C.useRef(null),K=C.useRef(null),se=C.useRef(null),H=C.useRef(0),te=C.useRef(0),z=C.useRef(Os("inline-run-token")),W=C.useRef($),le=C.useRef(new Set),X=C.useRef(new Map),ne=C.useRef(0),ue=C.useRef(""),ee=C.useRef(!1),Ne=C.useRef(!1),q=C.useRef(Js),Z=C.useRef(!1),ie=C.useRef(null),je=C.useRef(()=>{}),ke=(us=l.apiServiceUrl)==null?void 0:us.replace(/\/$/,""),Oe=ke?`${ke}/v1/sql/validate`:"/v1/sql/validate",Se=C.useCallback(G=>{S(Y=>{const J=G(Y);return q.current=J,J})},[]),be=C.useCallback((G,Y)=>{Se(J=>J.runId===G?Y(J):J)},[Se]),Ce=C.useCallback(G=>te.current===G&&!le.current.has(G),[]),ae=C.useCallback((G,Y,J)=>{be(G,xe=>{const ce=xe.timelineSteps.includes(Y)?xe.timelineSteps:[...xe.timelineSteps,Y];return{...xe,phase:(J==null?void 0:J.phase)||xe.phase,attempt:typeof(J==null?void 0:J.attempt)=="number"?J.attempt:xe.attempt,activeStep:Y,timelineSteps:ce,finalOutcome:(J==null?void 0:J.finalOutcome)||xe.finalOutcome,hasTools:J!=null&&J.hasTools?!0:xe.hasTools}})},[be]),fe=C.useCallback(()=>{const G=te.current+1,Y=Os("inline-run-token"),J=Os("inline-query-session");return te.current=G,z.current=Y,W.current=J,Q(J),le.current=new Set,X.current=new Map,ne.current=0,ue.current="",Z.current=!1,Se(()=>({runId:G,phase:"drafting",attempt:0,activeStep:"Drafting SQL",timelineSteps:["Drafting SQL"],lastValidation:null,finalOutcome:"drafting",hasTools:!1})),{runId:G,runToken:Y,chatSessionId:J}},[Se]),ge=C.useCallback(()=>{if(ee.current||Ne.current||b>0)return;const G=u||[];if(G.length===0)return;const Y=s.useAIInteractionStore.getState().currentAIContext;m({...Y,selectedEntities:G}),Ne.current=!0},[b,u,m]),Ie=C.useCallback(()=>{ee.current=!0},[]),ve=C.useCallback((G,Y,J)=>{zn(G,{runId:Y,attemptCount:typeof(J==null?void 0:J.attemptCount)=="number"?J.attemptCount:ne.current,errorCode:J==null?void 0:J.errorCode,hasTools:typeof(J==null?void 0:J.hasTools)=="boolean"?J.hasTools:M.hasTools,entityCount:b,finalOutcome:(J==null?void 0:J.finalOutcome)||M.finalOutcome})},[b,M.finalOutcome,M.hasTools]),pe=C.useCallback((G,Y)=>{const J=se.current;if(!J)return;const xe={inlineRunToken:Y};J({role:"user",parts:[{type:"text",text:G}],metadata:xe},{metadata:xe})},[]);C.useEffect(()=>{const G=ie.current;!G||G.sessionId!==$||(ie.current=null,pe(G.message,G.runToken))},[$,pe]);const Re=$,Qe=C.useCallback(async({toolCall:G})=>{var Fe,Je,ms,rs,Me,xs;if(Re!==W.current)return;const Y=String(G.toolName||"").trim();if(!Y)return;const J=te.current;if(!Ce(J)){(Fe=K.current)==null||Fe.call(K,{tool:Y,toolCallId:G.toolCallId,output:{status:"error",message:"Inline run is no longer active; ignoring tool output."}});return}if(Y==="getUserSql"){ae(J,ta(Y),{hasTools:!0}),ve("inline_tool_step",J,{hasTools:!0}),(Je=K.current)==null||Je.call(K,{tool:Y,toolCallId:G.toolCallId,output:{status:"success",sql:t||"",python:n||""}});return}const xe=s.INLINE_BLOCKED_MUTATING_TOOLS.has(Y),ce=s.INLINE_ALLOWED_READ_ONLY_TOOLS.has(Y);if(xe||!ce){(ms=K.current)==null||ms.call(K,{tool:Y,toolCallId:G.toolCallId,output:{status:"error",message:"This action is unavailable in inline draft mode. Open Full Assistant for this action."}});return}const he=ta(Y);ae(J,he,{phase:M.phase==="self-healing"?"self-healing":"drafting",hasTools:!0}),ve("inline_tool_step",J,{hasTools:!0});const De=((rs=G.input)==null?void 0:rs.sql)??((Me=G.args)==null?void 0:Me.sql);typeof De=="string"&&De.trim().length>0&&(Z.current=!1,T(De.trim())),(xs=K.current)==null||xs.call(K,{tool:Y,toolCallId:G.toolCallId,output:{status:"success",message:"Read-only tool result received."}})},[n,t,ve,M.phase,Ce,Re,ae]),Ke=C.useCallback(({message:G,messages:Y})=>{if(Re!==W.current)return;const J=aa(Y);if(!J||J!==z.current)return;const xe=te.current;if(!Ce(xe))return;const ce=na([G])||na(Y);if(ce){Z.current=!1,T(ce.trim());return}Z.current&&q.current.phase==="self-healing"&&je.current(xe)},[Ce,Re]),oe=C.useCallback(G=>{if(Re!==W.current)return;const Y=te.current;Ce(Y)&&Z.current&&q.current.phase==="self-healing"&&je.current(Y)},[Ce,Re]),{setMessages:me,sendMessage:ts,addToolResult:Ye,status:Cs,stop:os,error:fs,clearError:ze}=s.useChat({id:$,transport:new s.DefaultChatTransport({api:`${l.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${c==null?void 0:c.accessToken}`}),body:()=>{const G=s.useAIInteractionStore.getState();return{assistantId:"editor-assistant",assistantProfileId:x,isDevMode:p,aiContext:G.currentAIContext,reasoningEffort:G.reasoningEffort,showReasoning:!1}},credentials:"omit",prepareSendMessagesRequest:({messages:G,body:Y,requestMetadata:J})=>{const xe=J==null?void 0:J.inlineRunToken,ce=aa(G);return{body:{...Y,inlineRunToken:xe||ce,messages:s.cleanupIncompleteMessages(G)}}}}),onToolCall:Qe,onFinish:Ke,onError:oe,sendAutomaticallyWhen:s.lastAssistantMessageIsCompleteWithToolCalls});K.current=Ye,se.current=ts;const we=!["ready","error"].includes(Cs),Ss=(fs==null?void 0:fs.message)||"Unable to generate a SQL draft right now. Try again.",Ue=C.useCallback(G=>{const Y=te.current,J=q.current.phase;if(!(J==="drafting"||J==="self-healing"||J==="validating")){G==="stopped"&&we&&os();return}le.current.add(Y),Z.current=!1,H.current+=1,ue.current="",N({status:"idle"}),T(""),ze(),me([]),be(Y,ce=>({...ce,phase:"idle",activeStep:"",finalOutcome:"cancelled"})),ve("inline_self_heal_stopped",Y,{finalOutcome:"cancelled"}),(we||G==="stopped")&&os()},[ze,ve,we,me,os,be]),ws=C.useCallback(async(G,Y)=>{var xe;if(!Ce(Y))return null;const J=H.current+1;H.current=J,ae(Y,"Validating SQL",{phase:"validating"}),N({status:"validating"});try{const ce=await s.postRequestRegular(Oe,(c==null?void 0:c.accessToken)||"",{sql:G,connectionId:h||void 0});if(H.current!==J||!Ce(Y))return null;if((ce==null?void 0:ce.valid)===!0)return N({status:"valid",message:"SQL validation passed."}),be(Y,Fe=>({...Fe,phase:"ready",finalOutcome:"validated",lastValidation:{valid:!0}})),ve("inline_draft_validated",Y,{finalOutcome:"validated"}),{status:"valid"};const he=qn(ce==null?void 0:ce.errorCode)||"UNKNOWN",De=typeof(ce==null?void 0:ce.error)=="string"&&ce.error||typeof((xe=ce==null?void 0:ce.details)==null?void 0:xe.error)=="string"&&ce.details.error||"SQL validation failed. Please revise the query draft.";return N({status:"invalid",message:De,errorCode:he}),be(Y,Fe=>({...Fe,lastValidation:{valid:!1,error:De,errorCode:he}})),ve("inline_validation_failed",Y,{errorCode:he,finalOutcome:"validation_failed"}),{status:"invalid",error:De,errorCode:he}}catch(ce){if(H.current!==J||!Ce(Y))return null;const he=typeof(ce==null?void 0:ce.error)=="string"&&ce.error||typeof(ce==null?void 0:ce.detail)=="string"&&ce.detail||"Validation service unavailable. You can still replace and run.";return N({status:"error",message:he,errorCode:"SQL_CONNECTION_ERROR"}),be(Y,De=>({...De,phase:"error",finalOutcome:"error",lastValidation:{valid:!1,error:he,errorCode:"SQL_CONNECTION_ERROR"}})),{status:"error",error:he,errorCode:"SQL_CONNECTION_ERROR"}}},[c==null?void 0:c.accessToken,ve,Ce,h,Oe,be,ae]),as=C.useCallback((G,Y,J,xe)=>{let ce=J,he="validation_failed",De="Validating SQL";Y==="attempt_limit"?(ce=`Couldn't auto-fix after ${s.MAX_SELF_HEAL_ATTEMPTS} attempts. ${J}`,he="self_heal_exhausted",De=`Auto-fix stopped (${s.MAX_SELF_HEAL_ATTEMPTS} attempts)`):Y==="duplicate"&&(ce=`Auto-fix stopped (repeated validation failure). ${J}`,he="self_heal_duplicate_stopped",De="Auto-fix stopped (repeated failure)"),N({status:"invalid",message:ce,errorCode:xe}),ae(G,De,{phase:"error",finalOutcome:he}),be(G,Fe=>({...Fe,phase:"error",finalOutcome:he,lastValidation:{valid:!1,error:ce,errorCode:xe}})),Y!=="terminal"&&ve("inline_self_heal_stopped",G,{errorCode:xe,finalOutcome:he}),Z.current=!1},[ve,be,ae]),zs=C.useCallback(G=>{const Y="Auto-fix stopped (no SQL returned). Open Full Assistant to continue.",J="self_heal_no_draft";N({status:"invalid",message:Y,errorCode:"UNKNOWN"}),ae(G,"Auto-fix stopped (no SQL returned)",{phase:"error",finalOutcome:J}),be(G,xe=>({...xe,phase:"error",finalOutcome:J,lastValidation:{valid:!1,error:Y,errorCode:"UNKNOWN"}})),ve("inline_self_heal_stopped",G,{errorCode:"UNKNOWN",finalOutcome:J}),Z.current=!1},[ve,be,ae]);je.current=zs,C.useEffect(()=>{const G=A.trim(),Y=te.current;if(!G){if(H.current+=1,ue.current="",q.current.phase==="error")return;N({status:"idle"});return}if(!Ce(Y)||we)return;const J=`${Y}:${ne.current}:${sa(G)}`;if(ue.current===J)return;ue.current=J;let xe=!1;return(async()=>{const he=await ws(G,Y);if(!he||xe||!Ce(Y)||he.status!=="invalid")return;if(!s.RECOVERABLE_SQL_ERROR_CODES.has(he.errorCode)){as(Y,"terminal",he.error,he.errorCode);return}const De=`${sa(G)}::${he.errorCode}`,Fe=(X.current.get(De)||0)+1;if(X.current.set(De,Fe),Fe>=2){as(Y,"duplicate",he.error,he.errorCode);return}if(ne.current>=s.MAX_SELF_HEAL_ATTEMPTS){as(Y,"attempt_limit",he.error,he.errorCode);return}const Je=ne.current+1;ne.current=Je,ae(Y,s.SELF_HEAL_TIMELINE_STEP,{phase:"self-healing",attempt:Je}),ve("inline_self_heal_attempt",Y,{attemptCount:Je,errorCode:he.errorCode}),Z.current=!0,ze(),me([]),T("");const ms=y.map(Me=>{const xs=Me!=null&&Me.database?`${Me.database}.`:"",Gs=Me!=null&&Me.schema?`${Me.schema}.`:"",As=(Me==null?void 0:Me.name)||"unknown";return`${xs}${Gs}${As}`}),rs=Bn({request:E,failedSql:G,errorMessage:he.error,errorCode:he.errorCode,selectedDatabaseName:a||"",selectedSchemaName:r||"",selectedTableName:i||"",contextEntityLabels:ms});pe(rs,z.current)})(),()=>{xe=!0}},[ze,y,ve,we,Ce,E,A,a,r,i,pe,me,as,ae,ws]);const We=(t==null?void 0:t.trim())||"",Ts=C.useCallback((G="draft")=>{if(we)return;const Y=g.trim();if(!Y)return;const J=G==="refine"&&We?"refine":"draft",xe=J==="refine"?We:"",ce=We,{runId:he,runToken:De,chatSessionId:Fe}=fe();ve("inline_draft_started",he,{attemptCount:0,hasTools:!1,finalOutcome:"drafting"}),ge(),ze(),V(Y),T(""),D(J),j(xe),R(!1),N({status:"idle"}),H.current+=1,me([]),O(!0);const Je=Vn({request:Y,mode:J,currentSql:ce,selectedTableName:i||"",selectedSchemaName:r||"",selectedDatabaseName:a||""});ie.current={sessionId:Fe,message:Je,runToken:De}},[fe,ze,We,ve,we,g,ge,a,r,i,me]),gs=C.useCallback(G=>{const Y=A.trim();Y&&(d(Y,G),G||O(!1))},[d,A]),Xe=A.trim().length>0,Es=["valid","invalid","error"].includes(P.status),ns=Xe&&Es,Is=P.status==="invalid",He=P.status==="validating",js=Xe&&E.length>0&&E===g.trim(),is=We.length>0,Ze=g.length>0,cs=js&&v==="draft",ds=js&&v==="refine"&&I===We,_e=L==="refine"&&!is?"draft":L,ks=(_e==="refine"?ds:cs)?"Open composer preview":"Generate composer SQL",qs=g.trim().length>0||E.trim().length>0||Xe||P.status!=="idle"||M.timelineSteps.length>0,qe=C.useCallback((G="draft")=>{if(we)return;if((G==="refine"?ds:cs)&&!F){ge(),O(!0);return}Ts(G)},[cs,ds,Ts,we,F,ge]),bs=C.useCallback(()=>{ge(),O(!0)},[ge]),$s=C.useCallback(G=>{Ue("cancelled"),w(G)},[Ue]),_s=C.useCallback(()=>{we||(Ue("cancelled"),Z.current=!1,H.current+=1,ue.current="",ne.current=0,w(""),V(""),T(""),D("draft"),f("draft"),j(""),R(!1),N({status:"idle"}),ze(),me([]),Se(G=>({...Js,runId:G.runId})))},[Ue,ze,we,me,Se]),Ds=C.useCallback(G=>{G||Ue("cancelled"),O(G)},[Ue]),Te=M.timelineSteps.findIndex(G=>G===M.activeStep),vs=M.phase==="self-healing"?"Fixing validation issue":M.phase==="validating"?"Validating SQL":M.activeStep||"Drafting SQL",Le=P.status==="valid"?{label:"Validation passed",className:"border-emerald-500/30 bg-emerald-500/10 text-emerald-700",detail:P.message}:P.status==="invalid"?{label:"Validation failed",className:"border-destructive/40 bg-destructive/10 text-destructive",detail:P.message}:P.status==="error"?{label:"Validation unavailable",className:"border-border/60 bg-muted/20 text-muted-foreground",detail:P.message}:null;return e.jsxs("div",{ref:B,className:"relative flex h-8 min-w-[320px] flex-1 items-center",children:[e.jsx(s.Input,{value:g,onChange:G=>$s(G.target.value),onFocus:bs,onClick:bs,onKeyDown:G=>{G.key==="Enter"&&(G.preventDefault(),qe(_e))},placeholder:"Type your question...",className:["h-8 border-transparent bg-muted/45 shadow-none focus-visible:border-border focus-visible:bg-background focus-visible:ring-0",Ze?"pr-[60px]":"pr-10"].join(" ")}),e.jsxs(s.Popover,{open:F,onOpenChange:Ds,children:[e.jsx(s.PopoverAnchor,{asChild:!0,children:e.jsx("div",{className:"pointer-events-none absolute inset-0"})}),e.jsxs("div",{className:"absolute right-1 flex items-center gap-1",children:[Ze&&e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"size-6 p-0",onClick:G=>{G.preventDefault(),Ue("cancelled"),w("")},disabled:we,"aria-label":"Clear input",title:"Clear input",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"size-6 p-0",onClick:G=>{G.preventDefault(),qe(_e)},disabled:we,"aria-label":ks,title:ks,children:e.jsx(jn,{className:"size-3.5"})})]}),e.jsx(s.PopoverContent,{align:"start",alignOffset:0,side:"bottom",sideOffset:8,className:"w-[min(92vw,var(--radix-popover-trigger-width))] max-w-[760px] p-2.5",onOpenAutoFocus:G=>{G.preventDefault()},onInteractOutside:G=>{var J;const Y=G.target;Y&&((J=B.current)!=null&&J.contains(Y))&&G.preventDefault()},children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Composer"}),E&&e.jsx("p",{className:"line-clamp-2 text-xs text-muted-foreground",children:E})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"inline-flex h-7 items-center rounded-md border border-border/60 bg-background p-0.5 shadow-sm",children:[e.jsx(s.Button,{type:"button",size:"sm",variant:_e==="draft"?"secondary":"ghost",className:["h-6 rounded-[6px] px-2 text-xs",_e!=="draft"?"text-muted-foreground hover:text-foreground":""].join(" "),onClick:()=>{f("draft"),R(!1)},children:"Draft New"}),e.jsx(s.Button,{type:"button",size:"sm",variant:_e==="refine"?"secondary":"ghost",className:["h-6 rounded-[6px] px-2 text-xs",_e!=="refine"?"text-muted-foreground hover:text-foreground":""].join(" "),onClick:()=>f("refine"),disabled:!is,children:"Refine Current"})]}),e.jsx("div",{className:"h-4 w-px bg-border/70"}),we&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>{Ue("stopped")},children:"Stop"}),!we&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:_s,disabled:!qs,children:"Clear"})]})]}),M.timelineSteps.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[M.timelineSteps.map((G,Y)=>{const J=G===M.activeStep&&["drafting","validating","self-healing"].includes(M.phase),xe=!J&&Te>=0&&Y<Te;return e.jsx("span",{className:["rounded-full border px-2 py-0.5 text-[11px]",J?"border-foreground/30 bg-foreground/10 text-foreground":xe?"border-border/60 bg-muted/20 text-muted-foreground":"border-border/50 bg-background text-muted-foreground/80"].join(" "),children:$n(G,M.attempt)},`${G}-${Y}`)}),Le&&e.jsx(s.TooltipProvider,{delayDuration:150,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:["rounded-full border px-2 py-0.5 text-[11px]",Le.className].join(" "),children:Le.label})}),e.jsx(s.TooltipContent,{side:"top",align:"start",className:"max-w-[680px] whitespace-pre-wrap break-words text-xs",children:Le.detail})]})})]}),e.jsx("div",{className:"py-0.5",children:e.jsx(s.AssistantContextEntityControls,{mode:"full",compact:!0,inlineLayout:!0,inlineTriggerFirst:!0,triggerVariant:"outline",triggerIconOnly:!1,triggerLabel:"Context",onSelectionChange:Ie})}),(we||M.phase==="self-healing"||P.status==="validating")&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border/60 bg-muted/20 px-3 py-2 text-xs text-muted-foreground",children:[e.jsx(s.LoaderCircle,{className:"size-3.5 animate-spin"}),vs]}),fs&&e.jsx("div",{className:"rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-xs text-destructive",children:Ss}),v==="refine"&&I&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-md border border-border/60 bg-muted/20 px-2.5 py-1.5 text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Refining editor SQL"}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>R(G=>!G),children:k?"Hide base SQL":"View base SQL"})]}),k&&e.jsx("div",{className:"max-h-[120px] overflow-auto rounded-md border border-border/60",children:e.jsx(s.CodeHighlighter,{code:I,language:"sql"})})]}),ns?e.jsxs("div",{className:"space-y-1",children:[v==="refine"&&e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Refined SQL"}),e.jsx("div",{className:"max-h-[200px] overflow-auto rounded-md border border-border/60",children:e.jsx(s.CodeHighlighter,{code:A,language:"sql"})})]}):Xe?e.jsx("div",{className:"rounded-md border border-dashed border-border/70 px-3 py-2 text-xs text-muted-foreground",children:"Validating SQL draft before preview."}):!we&&e.jsx("div",{className:"rounded-md border border-dashed border-border/70 px-3 py-2 text-xs text-muted-foreground",children:is?"Choose Draft New or Refine Current, then press Enter or click send.":"Describe what you want to query, then press Enter or click send to generate a SQL preview."}),e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:o,children:"Open Full Assistant"}),e.jsx(s.Button,{variant:"secondary",size:"sm",className:"h-8",disabled:we||!ns,onClick:()=>gs(!1),children:"Replace SQL"}),e.jsx(s.Button,{size:"sm",className:"h-8",disabled:we||!ns||He||Is,onClick:()=>gs(!0),children:"Replace & Run"})]})]})})]})]})}function Kn(){var ne,ue;const t=s.useQueryClient(),[n,a]=C.useState(!1),r=s.useEditorStore(ee=>ee.frame),i=s.useEditorStore(ee=>ee.card);s.useEditorStore(ee=>ee.isShowingVisual),s.useEditorStore(ee=>ee.selectedConnectionId),s.useEditorStore(ee=>ee.tempQueryData);const d=s.useEditorStore(ee=>ee.selectedDatabaseName);s.useEditorStore(ee=>ee.selectedDatamodelId);const o=s.useEditorStore(ee=>ee.selectedSchemaName);s.useEditorStore(ee=>ee.showAIDialog);const c=s.useEditorStore(ee=>ee.selectedTableName),{cardFilterValues:l}=s.useCardFilterValues((i==null?void 0:i.id)??""),x=s.useDashboardStore(ee=>ee.inlineFilterValuesMap[(i==null?void 0:i.id)??""]),p=C.useMemo(()=>s.findCustomVisualConfigCard(r,i),[r,i]),{manifest:h}=s.useCustomVisual(((ne=p==null?void 0:p.customCardPreferences)==null?void 0:ne.url)||""),u=C.useMemo(()=>{var ee;return(ee=h==null?void 0:h.visuals)==null?void 0:ee.find(Ne=>{var q;return Ne.name===((q=p==null?void 0:p.customCardPreferences)==null?void 0:q.componentName)})},[h,(ue=p==null?void 0:p.customCardPreferences)==null?void 0:ue.componentName]),y=s.resolveMultiInputType(p,u),b=C.useMemo(()=>s.getCustomVisualInputCards({frame:r,configCard:p,isMultiInputVisual:y==="multiple"}),[r,p,y]),m=C.useMemo(()=>{const ee=b.findIndex(Ne=>(Ne==null?void 0:Ne.id)===(i==null?void 0:i.id));return ee<0?-1:s.getSlotIndexForCard(i,ee)},[b,i]),g=C.useMemo(()=>!p||y!=="multiple"||m<0?i.type:s.getEffectiveCardTypeForSlot(i,m,u==null?void 0:u.slots)??i.type,[p,y,m,i,u==null?void 0:u.slots]),w=C.useMemo(()=>g!==i.type?{...i,type:g}:i,[i,g]),E=C.useRef(!0),{setCardCustomCfg:V,setQueryResultColumns:A,setCardSql:T,setTempQueryData:v,setPythonStdOut:D,setCardPreferences:L,setCardType:f,setCardPython:I,setShowAIDialog:j,setCard:k,updateCardInFrame:R}=s.useEditorActions();s.useEditorStore(ee=>ee.onSave),s.useEditorStore(ee=>ee.onClose),s.useEditorStore(ee=>ee.actions.setSqlGen);const P=s.useEditorStore(ee=>ee.runSql),N=s.useEditorStore(ee=>ee.actions.setRunSql),M=s.useEditorStore(ee=>ee.actions.setIsSqlRunning),{data:S,isLoading:F,isFetching:O,isSuccess:$,isError:Q,error:B,errorSql:K,queryKey:se,refetch:H,errorMessage:te}=s.useDashboardCardQuery(w);C.useEffect(()=>{if(S&&(S.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),D((S==null?void 0:S.output)||""),S.records.length>0)){const{dimensionKeys:ee}=s.getKeys(S.records);A(ee)}},[S,A,D]),C.useEffect(()=>{(F||O)&&M(!0),(Q||$)&&M(!1),Q&&(A([]),D(""))},[F,O,S,D,Q,$,M,A,B]),C.useEffect(()=>{P&&(t.getQueryData(se)||H(),N(!1))},[P,H,N,se,t]);const z=C.useRef(H);z.current=H,C.useEffect(()=>{if(E.current){E.current=!1;return}z.current()},[x]);function W(ee,Ne){T(ee),Ne&&N(!0)}function le(){return e.jsxs(s.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(s.ResizablePanel,{id:"1",order:1,defaultSize:n?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(Mn,{})}),n&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),n&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizableHandle,{withHandle:!0,className:"data-[panel-group-direction=vertical]:ml-2 data-[panel-group-direction=vertical]:mr-6 data-[panel-group-direction=vertical]:w-auto"}),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(On,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function X(){return e.jsx("div",{role:"editor-controls",className:"item-center flex w-full flex-wrap items-center gap-2 py-3 pl-2 pr-6",children:e.jsxs("div",{className:"flex w-full items-center gap-3",children:[e.jsxs(s.Button,{title:"Shift + Enter",disabled:F||O,onClick:()=>{H()},className:"h-8 shrink-0",size:"sm",children:[F||O?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"]}),(S==null?void 0:S.sql)&&!te&&e.jsxs(s.HoverCard,{openDelay:300,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Info,{className:"h-4 w-4 shrink-0 cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(s.HoverCardContent,{align:"start",className:"w-[500px] p-0",children:e.jsx(Ia,{sql:S.sql})})]}),e.jsx(Ae.EditorClearButton,{}),e.jsxs(s.Toggle,{pressed:n,onPressedChange:ee=>a(ee),className:"h-8",size:"sm",variant:"outline",children:[e.jsx(Dn,{className:"mr-2 size-4 text-foreground/70"}),"Python"]}),e.jsx(Gn,{currentSql:i==null?void 0:i.sql,currentPython:i==null?void 0:i.python,selectedDatabaseName:d,selectedSchemaName:o,selectedTableName:c,onApplySql:W,onOpenFullAssistant:()=>j(!0)}),e.jsx("div",{className:"ml-auto flex shrink-0 items-center gap-3",children:l&&l.length>0&&e.jsxs(s.HoverCard,{openDelay:200,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",className:"h-8 gap-2 px-2",children:[e.jsx(s.Filter,{className:"size-4"}),e.jsx(s.Badge,{className:"h-5 min-w-5 bg-purple-100 px-1.5 text-purple-700 hover:bg-purple-100 dark:bg-purple-950 dark:text-purple-300",children:l.length})]})}),e.jsx(s.HoverCardContent,{className:"mr-4 max-h-[400px] w-[500px] overflow-auto p-0",children:e.jsxs("div",{className:"p-3",children:[e.jsx("div",{className:"mb-2 text-sm font-semibold",children:"Active Dashboard Filters"}),e.jsx(s.CodeHighlighter,{code:JSON.stringify(l,null,2),language:"json"})]})})]})})]})})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsx("div",{className:"relative flex grow overflow-y-scroll",children:le()}),X()]})}const Un=[{value:"table",label:"Table",icon:s.Table2},{value:"aggregateTable",label:"Aggregate",icon:s.Layers},{value:"pivotTable",label:"Pivot",icon:s.Grid3x3},{value:"detailTable",label:"Detail",icon:s.List}];function Hn({className:t}){const n=s.useEditorStore(h=>h.card),a=s.useEditorStore(h=>h.frame),r=Ae.useEffectiveEditorCardType(),{setCard:i,updateCardInFrame:d}=s.useEditorActions(),o=["table","aggregateTable","pivotTable","detailTable"].includes(r),c=s.hasValidCardConfig(n.config),l=s.isCustomVisualConfigCard(n,a.cards);if(!o||!c||l)return null;const x=h=>{if(l)return;const u=h,y=n.config??{},b=p(r,u,y),m={...n,type:u,config:b};i(m),d(m)},p=(h,u,y)=>{var m;if(u==="detailTable"){const g=A=>A==null?void 0:A.toLowerCase().replace(/\s+/g,"").trim(),w=(A,T)=>{const v=[g(A.label),g(A.qualifiedFieldName),g(A.name)].filter(Boolean),D=[g(T.label),g(T.qualifiedFieldName),g(T.name)].filter(Boolean);return v.some(L=>D.includes(L))},E=(y.groupByColumns||[]).map(A=>({...A,role:"detail"})),V=((m=y.sortByColumns)==null?void 0:m.filter(A=>E.some(T=>w(A,T))))??[];return{...y,detailTableBackup:{groupByColumns:y.groupByColumns,metricColumns:y.metricColumns,pivotByColumns:y.pivotByColumns,sortByColumns:y.sortByColumns,rowAggregates:y.rowAggregates,columnAggregates:y.columnAggregates,comparisonType:y.comparisonType},detailColumns:E,groupByColumns:[],metricColumns:[],pivotByColumns:[],sortByColumns:V,rowAggregates:[],columnAggregates:[],comparisonType:"none"}}let b=y;if(h==="detailTable")if(y.detailTableBackup)b={...y,...y.detailTableBackup,detailColumns:[],detailTableBackup:void 0};else{const g=(y.detailColumns||[]).map(w=>({...w,role:"groupby"}));b={...y,groupByColumns:g,detailColumns:[]}}return u==="aggregateTable"?{...b,pivotByColumns:[]}:b};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsx(s.RadioGroup,{value:r,onValueChange:x,className:"flex flex-row items-center gap-1 border-b border-border/60",children:Un.map(h=>{const u=h.icon,y=r===h.value;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(s.RadioGroupItem,{value:h.value,id:`table-type-${h.value}`,className:"peer sr-only"}),e.jsxs(s.Label,{htmlFor:`table-type-${h.value}`,className:s.cn("flex h-8 cursor-pointer items-center justify-center gap-1.5 whitespace-nowrap border-b-2 border-transparent px-2 pb-1 text-xs font-medium transition-colors",y?"border-foreground text-foreground":"text-muted-foreground hover:border-foreground/30 hover:text-foreground"),children:[e.jsx(u,{className:s.cn("h-3.5 w-3.5",y?"opacity-100":"opacity-75")}),h.label]})]},h.value)})})})}function lt({error:t,errorSql:n,errorTitle:a="Unable to load data",onOpenInEditor:r,onDebugWithAssistant:i,onSendFeedback:d,showFeedbackButton:o=!0,className:c}){const[l,x]=C.useState(!1);return e.jsx("div",{className:s.cn("rounded-lg border border-border bg-muted/40 p-4",c),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-amber-500/10 dark:bg-amber-500/20",children:e.jsx(s.TriangleAlert,{className:"h-4 w-4 text-amber-600 dark:text-amber-500"})}),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-foreground",children:a}),e.jsxs("div",{className:"relative rounded-md border border-border bg-background p-3",children:[e.jsx(s.CopyButton,{text:t,className:"absolute right-2 top-2 z-10 h-6 w-6"}),e.jsx("div",{className:"max-h-40 overflow-auto pr-10",children:e.jsx("p",{className:"break-all font-mono text-xs text-muted-foreground",children:t})})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n&&e.jsx(s.Collapsible,{open:l,onOpenChange:x,children:e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",children:l?e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronUp,{className:"mr-1.5 h-3.5 w-3.5"}),"Hide Details"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronDown,{className:"mr-1.5 h-3.5 w-3.5"}),"Show Details"]})})})}),r&&n&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:r,children:[e.jsx(ya,{className:"mr-1.5 h-3.5 w-3.5"}),"Open in Editor"]}),o&&d&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:d,children:[e.jsx(s.MessageSquareWarning,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]}),i&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:i,children:[e.jsx(dn,{className:"mr-1.5 h-3.5 w-3.5"}),"Debug with Assistant"]})]}),n&&e.jsx(s.Collapsible,{open:l,onOpenChange:x,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:"Query"}),e.jsx(s.CopyButton,{text:n,className:"h-6 w-6"})]}),e.jsx("div",{className:"max-h-80 overflow-auto rounded-md border border-border bg-background p-2",children:e.jsx(s.CodeHighlighter,{code:n,language:"sql"})})]})})})]})]})})}function ka(t,n){const a=s.useEditorStore(x=>x.card),r=s.useEditorStore(x=>x.isDevMode),{switchEditorMode:i,setRunSql:d,runAssistant:o}=s.useEditorActions();return{isDevMode:r,handleOpenInEditor:r?void 0:()=>{const x=n||a.sql||a.python||"";i("dev",{sqlToLoad:x}),setTimeout(()=>{d(!0)},100)},handleDebugWithAssistant:r?()=>{const x=`Can you help me debug this query?
|
|
176
|
+
`)}function qn(t,n){typeof window>"u"||window.dispatchEvent(new CustomEvent("semaphor:inline-query-writer",{detail:{event:t,...n,timestamp:Date.now()}}))}const Qs={runId:0,phase:"idle",attempt:0,activeStep:"",timelineSteps:[],lastValidation:null,finalOutcome:"idle",hasTools:!1};function _n(t){if(typeof t=="string"&&(t==="SQL_EMPTY"||t==="SQL_PARSE_ERROR"||t==="SQL_MULTI_STATEMENT"||t==="SQL_READ_ONLY_VIOLATION"||t==="SQL_EXPLAIN_ERROR"||t==="SQL_CONNECTION_ERROR"))return t}function ta(t){let n=0;for(let a=0;a<t.length;a+=1)n=(n<<5)-n+t.charCodeAt(a),n|=0;return String(n)}function aa(t){return t==="getTableColumns"?"Discovering columns":t==="getDomainRelationships"?"Resolving relationships":t==="getChartSQLSyntax"?"Reviewing SQL syntax":t==="getUserSql"?"Inspecting current query":"Analyzing context"}function $n(t,n){return t===s.SELF_HEAL_TIMELINE_STEP&&n>0?`${s.SELF_HEAL_TIMELINE_STEP} ${n}/${s.MAX_SELF_HEAL_ATTEMPTS}`:t}function Rs(t){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`${t}-${crypto.randomUUID()}`:`${t}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function na(t){var n;for(let a=t.length-1;a>=0;a-=1){const r=t[a];if(r.role!=="user")continue;const i=(n=r.metadata)==null?void 0:n.inlineRunToken;if(typeof i=="string"&&i.length>0)return i}}function Gn(t){if(!t)return"";const n=t.trim(),a=t.match(/```sql\s*([\s\S]*?)```/i);if(a!=null&&a[1])return a[1].trim();const r=t.match(/```[\w-]*\s*([\s\S]*?)```/i);return r!=null&&r[1]?r[1].trim():/^(select|with|insert|update|delete)\b/i.test(n)?n:""}function ra(t){for(let n=t.length-1;n>=0;n-=1){const a=t[n];if(!(a.role!=="assistant"||!Array.isArray(a.parts)))for(let r=a.parts.length-1;r>=0;r-=1){const i=a.parts[r];if((i==null?void 0:i.type)!=="text"||typeof(i==null?void 0:i.text)!="string")continue;const d=Gn(i.text);if(d)return d}}return""}function Kn({currentSql:t,currentPython:n,selectedDatabaseName:a,selectedSchemaName:r,selectedTableName:i,onApplySql:d,onOpenFullAssistant:o}){var Fe,Pe;const{authToken:c,tokenProps:l}=s.useSemaphorContext(),x=(Fe=s.useDashboardQuery().data)==null?void 0:Fe.assistantProfileId,p=s.useEditorStore(G=>G.isDevMode),h=s.useEditorStore(G=>G.selectedConnectionId),u=s.useEditorStore(G=>{var J;return(J=G.card.dataSource)==null?void 0:J.selectedEntities}),y=s.useAIInteractionStore(G=>G.currentAIContext.selectedEntities),b=y.length,{setCurrentAIContext:m}=s.useAIActions(),[g,w]=C.useState(""),[E,V]=C.useState(""),[A,T]=C.useState(""),[v,D]=C.useState("draft"),[M,f]=C.useState("draft"),[I,j]=C.useState(""),[k,R]=C.useState(!1),[P,N]=C.useState({status:"idle"}),[L,S]=C.useState(Qs),[F,O]=C.useState(!1),[_,Q]=C.useState(()=>Rs("inline-query-session")),B=C.useRef(null),K=C.useRef(null),se=C.useRef(null),H=C.useRef(0),te=C.useRef(0),z=C.useRef(Rs("inline-run-token")),W=C.useRef(_),le=C.useRef(new Set),X=C.useRef(new Map),ne=C.useRef(0),me=C.useRef(""),ee=C.useRef(!1),Ne=C.useRef(!1),q=C.useRef(Qs),Z=C.useRef(!1),ie=C.useRef(null),je=C.useRef(()=>{}),ke=(Pe=l.apiServiceUrl)==null?void 0:Pe.replace(/\/$/,""),Me=ke?`${ke}/v1/sql/validate`:"/v1/sql/validate",we=C.useCallback(G=>{S(J=>{const Y=G(J);return q.current=Y,Y})},[]),be=C.useCallback((G,J)=>{we(Y=>Y.runId===G?J(Y):Y)},[we]),Ce=C.useCallback(G=>te.current===G&&!le.current.has(G),[]),ae=C.useCallback((G,J,Y)=>{be(G,ue=>{const de=ue.timelineSteps.includes(J)?ue.timelineSteps:[...ue.timelineSteps,J];return{...ue,phase:(Y==null?void 0:Y.phase)||ue.phase,attempt:typeof(Y==null?void 0:Y.attempt)=="number"?Y.attempt:ue.attempt,activeStep:J,timelineSteps:de,finalOutcome:(Y==null?void 0:Y.finalOutcome)||ue.finalOutcome,hasTools:Y!=null&&Y.hasTools?!0:ue.hasTools}})},[be]),fe=C.useCallback(()=>{const G=te.current+1,J=Rs("inline-run-token"),Y=Rs("inline-query-session");return te.current=G,z.current=J,W.current=Y,Q(Y),le.current=new Set,X.current=new Map,ne.current=0,me.current="",Z.current=!1,we(()=>({runId:G,phase:"drafting",attempt:0,activeStep:"Drafting SQL",timelineSteps:["Drafting SQL"],lastValidation:null,finalOutcome:"drafting",hasTools:!1})),{runId:G,runToken:J,chatSessionId:Y}},[we]),ge=C.useCallback(()=>{if(ee.current||Ne.current||b>0)return;const G=u||[];if(G.length===0)return;const J=s.useAIInteractionStore.getState().currentAIContext;m({...J,selectedEntities:G}),Ne.current=!0},[b,u,m]),Ie=C.useCallback(()=>{ee.current=!0},[]),ve=C.useCallback((G,J,Y)=>{qn(G,{runId:J,attemptCount:typeof(Y==null?void 0:Y.attemptCount)=="number"?Y.attemptCount:ne.current,errorCode:Y==null?void 0:Y.errorCode,hasTools:typeof(Y==null?void 0:Y.hasTools)=="boolean"?Y.hasTools:L.hasTools,entityCount:b,finalOutcome:(Y==null?void 0:Y.finalOutcome)||L.finalOutcome})},[b,L.finalOutcome,L.hasTools]),pe=C.useCallback((G,J)=>{const Y=se.current;if(!Y)return;const ue={inlineRunToken:J};Y({role:"user",parts:[{type:"text",text:G}],metadata:ue},{metadata:ue})},[]);C.useEffect(()=>{const G=ie.current;!G||G.sessionId!==_||(ie.current=null,pe(G.message,G.runToken))},[_,pe]);const Oe=_,Ye=C.useCallback(async({toolCall:G})=>{var Re,Qe,ms,xs,Le,rs;if(Oe!==W.current)return;const J=String(G.toolName||"").trim();if(!J)return;const Y=te.current;if(!Ce(Y)){(Re=K.current)==null||Re.call(K,{tool:J,toolCallId:G.toolCallId,output:{status:"error",message:"Inline run is no longer active; ignoring tool output."}});return}if(J==="getUserSql"){ae(Y,aa(J),{hasTools:!0}),ve("inline_tool_step",Y,{hasTools:!0}),(Qe=K.current)==null||Qe.call(K,{tool:J,toolCallId:G.toolCallId,output:{status:"success",sql:t||"",python:n||""}});return}const ue=s.INLINE_BLOCKED_MUTATING_TOOLS.has(J),de=s.INLINE_ALLOWED_READ_ONLY_TOOLS.has(J);if(ue||!de){(ms=K.current)==null||ms.call(K,{tool:J,toolCallId:G.toolCallId,output:{status:"error",message:"This action is unavailable in inline draft mode. Open Full Assistant for this action."}});return}const he=aa(J);ae(Y,he,{phase:L.phase==="self-healing"?"self-healing":"drafting",hasTools:!0}),ve("inline_tool_step",Y,{hasTools:!0});const Te=((xs=G.input)==null?void 0:xs.sql)??((Le=G.args)==null?void 0:Le.sql);typeof Te=="string"&&Te.trim().length>0&&(Z.current=!1,T(Te.trim())),(rs=K.current)==null||rs.call(K,{tool:J,toolCallId:G.toolCallId,output:{status:"success",message:"Read-only tool result received."}})},[n,t,ve,L.phase,Ce,Oe,ae]),Ue=C.useCallback(({message:G,messages:J})=>{if(Oe!==W.current)return;const Y=na(J);if(!Y||Y!==z.current)return;const ue=te.current;if(!Ce(ue))return;const de=ra([G])||ra(J);if(de){Z.current=!1,T(de.trim());return}Z.current&&q.current.phase==="self-healing"&&je.current(ue)},[Ce,Oe]),oe=C.useCallback(G=>{if(Oe!==W.current)return;const J=te.current;Ce(J)&&Z.current&&q.current.phase==="self-healing"&&je.current(J)},[Ce,Oe]),{setMessages:xe,sendMessage:as,addToolResult:We,status:Ns,stop:os,error:He,clearError:ze}=s.useChat({id:_,transport:new s.DefaultChatTransport({api:`${l.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${c==null?void 0:c.accessToken}`}),body:()=>{const G=s.useAIInteractionStore.getState();return{assistantId:"editor-assistant",assistantProfileId:x,isDevMode:p,aiContext:G.currentAIContext,reasoningEffort:G.reasoningEffort,showReasoning:!1}},credentials:"omit",prepareSendMessagesRequest:({messages:G,body:J,requestMetadata:Y})=>{const ue=Y==null?void 0:Y.inlineRunToken,de=na(G);return{body:{...J,inlineRunToken:ue||de,messages:s.cleanupIncompleteMessages(G)}}}}),onToolCall:Ye,onFinish:Ue,onError:oe,sendAutomaticallyWhen:s.lastAssistantMessageIsCompleteWithToolCalls});K.current=We,se.current=as;const Se=!["ready","error"].includes(Ns),Cs=(He==null?void 0:He.message)||"Unable to generate a SQL draft right now. Try again.",$e=C.useCallback(G=>{const J=te.current,Y=q.current.phase;if(!(Y==="drafting"||Y==="self-healing"||Y==="validating")){G==="stopped"&&Se&&os();return}le.current.add(J),Z.current=!1,H.current+=1,me.current="",N({status:"idle"}),T(""),ze(),xe([]),be(J,de=>({...de,phase:"idle",activeStep:"",finalOutcome:"cancelled"})),ve("inline_self_heal_stopped",J,{finalOutcome:"cancelled"}),(Se||G==="stopped")&&os()},[ze,ve,Se,xe,os,be]),Ss=C.useCallback(async(G,J)=>{var ue;if(!Ce(J))return null;const Y=H.current+1;H.current=Y,ae(J,"Validating SQL",{phase:"validating"}),N({status:"validating"});try{const de=await s.postRequestRegular(Me,(c==null?void 0:c.accessToken)||"",{sql:G,connectionId:h||void 0});if(H.current!==Y||!Ce(J))return null;if((de==null?void 0:de.valid)===!0)return N({status:"valid",message:"SQL validation passed."}),be(J,Re=>({...Re,phase:"ready",finalOutcome:"validated",lastValidation:{valid:!0}})),ve("inline_draft_validated",J,{finalOutcome:"validated"}),{status:"valid"};const he=_n(de==null?void 0:de.errorCode)||"UNKNOWN",Te=typeof(de==null?void 0:de.error)=="string"&&de.error||typeof((ue=de==null?void 0:de.details)==null?void 0:ue.error)=="string"&&de.details.error||"SQL validation failed. Please revise the query draft.";return N({status:"invalid",message:Te,errorCode:he}),be(J,Re=>({...Re,lastValidation:{valid:!1,error:Te,errorCode:he}})),ve("inline_validation_failed",J,{errorCode:he,finalOutcome:"validation_failed"}),{status:"invalid",error:Te,errorCode:he}}catch(de){if(H.current!==Y||!Ce(J))return null;const he=typeof(de==null?void 0:de.error)=="string"&&de.error||typeof(de==null?void 0:de.detail)=="string"&&de.detail||"Validation service unavailable. You can still replace and run.";return N({status:"error",message:he,errorCode:"SQL_CONNECTION_ERROR"}),be(J,Te=>({...Te,phase:"error",finalOutcome:"error",lastValidation:{valid:!1,error:he,errorCode:"SQL_CONNECTION_ERROR"}})),{status:"error",error:he,errorCode:"SQL_CONNECTION_ERROR"}}},[c==null?void 0:c.accessToken,ve,Ce,h,Me,be,ae]),is=C.useCallback((G,J,Y,ue)=>{let de=Y,he="validation_failed",Te="Validating SQL";J==="attempt_limit"?(de=`Couldn't auto-fix after ${s.MAX_SELF_HEAL_ATTEMPTS} attempts. ${Y}`,he="self_heal_exhausted",Te=`Auto-fix stopped (${s.MAX_SELF_HEAL_ATTEMPTS} attempts)`):J==="duplicate"&&(de=`Auto-fix stopped (repeated validation failure). ${Y}`,he="self_heal_duplicate_stopped",Te="Auto-fix stopped (repeated failure)"),N({status:"invalid",message:de,errorCode:ue}),ae(G,Te,{phase:"error",finalOutcome:he}),be(G,Re=>({...Re,phase:"error",finalOutcome:he,lastValidation:{valid:!1,error:de,errorCode:ue}})),J!=="terminal"&&ve("inline_self_heal_stopped",G,{errorCode:ue,finalOutcome:he}),Z.current=!1},[ve,be,ae]),ws=C.useCallback(G=>{const J="Auto-fix stopped (no SQL returned). Open Full Assistant to continue.",Y="self_heal_no_draft";N({status:"invalid",message:J,errorCode:"UNKNOWN"}),ae(G,"Auto-fix stopped (no SQL returned)",{phase:"error",finalOutcome:Y}),be(G,ue=>({...ue,phase:"error",finalOutcome:Y,lastValidation:{valid:!1,error:J,errorCode:"UNKNOWN"}})),ve("inline_self_heal_stopped",G,{errorCode:"UNKNOWN",finalOutcome:Y}),Z.current=!1},[ve,be,ae]);je.current=ws,C.useEffect(()=>{const G=A.trim(),J=te.current;if(!G){if(H.current+=1,me.current="",q.current.phase==="error")return;N({status:"idle"});return}if(!Ce(J)||Se)return;const Y=`${J}:${ne.current}:${ta(G)}`;if(me.current===Y)return;me.current=Y;let ue=!1;return(async()=>{const he=await Ss(G,J);if(!he||ue||!Ce(J)||he.status!=="invalid")return;if(!s.RECOVERABLE_SQL_ERROR_CODES.has(he.errorCode)){is(J,"terminal",he.error,he.errorCode);return}const Te=`${ta(G)}::${he.errorCode}`,Re=(X.current.get(Te)||0)+1;if(X.current.set(Te,Re),Re>=2){is(J,"duplicate",he.error,he.errorCode);return}if(ne.current>=s.MAX_SELF_HEAL_ATTEMPTS){is(J,"attempt_limit",he.error,he.errorCode);return}const Qe=ne.current+1;ne.current=Qe,ae(J,s.SELF_HEAL_TIMELINE_STEP,{phase:"self-healing",attempt:Qe}),ve("inline_self_heal_attempt",J,{attemptCount:Qe,errorCode:he.errorCode}),Z.current=!0,ze(),xe([]),T("");const ms=y.map(Le=>{const rs=Le!=null&&Le.database?`${Le.database}.`:"",Gs=Le!=null&&Le.schema?`${Le.schema}.`:"",Ks=(Le==null?void 0:Le.name)||"unknown";return`${rs}${Gs}${Ks}`}),xs=zn({request:E,failedSql:G,errorMessage:he.error,errorCode:he.errorCode,selectedDatabaseName:a||"",selectedSchemaName:r||"",selectedTableName:i||"",contextEntityLabels:ms});pe(xs,z.current)})(),()=>{ue=!0}},[ze,y,ve,Se,Ce,E,A,a,r,i,pe,xe,is,ae,Ss]);const Ze=(t==null?void 0:t.trim())||"",Ts=C.useCallback((G="draft")=>{if(Se)return;const J=g.trim();if(!J)return;const Y=G==="refine"&&Ze?"refine":"draft",ue=Y==="refine"?Ze:"",de=Ze,{runId:he,runToken:Te,chatSessionId:Re}=fe();ve("inline_draft_started",he,{attemptCount:0,hasTools:!1,finalOutcome:"drafting"}),ge(),ze(),V(J),T(""),D(Y),j(ue),R(!1),N({status:"idle"}),H.current+=1,xe([]),O(!0);const Qe=Bn({request:J,mode:Y,currentSql:de,selectedTableName:i||"",selectedSchemaName:r||"",selectedDatabaseName:a||""});ie.current={sessionId:Re,message:Qe,runToken:Te}},[fe,ze,Ze,ve,Se,g,ge,a,r,i,xe]),Es=C.useCallback(G=>{const J=A.trim();J&&(d(J,G),G||O(!1))},[d,A]),ns=A.trim().length>0,fs=["valid","invalid","error"].includes(P.status),cs=ns&&fs,gs=P.status==="invalid",Is=P.status==="validating",Ge=ns&&E.length>0&&E===g.trim(),ds=Ze.length>0,js=g.length>0,Xe=Ge&&v==="draft",us=Ge&&v==="refine"&&I===Ze,Je=M==="refine"&&!ds?"draft":M,Ds=(Je==="refine"?us:Xe)?"Open composer preview":"Generate composer SQL",qs=g.trim().length>0||E.trim().length>0||ns||P.status!=="idle"||L.timelineSteps.length>0,As=C.useCallback((G="draft")=>{if(Se)return;if((G==="refine"?us:Xe)&&!F){ge(),O(!0);return}Ts(G)},[Xe,us,Ts,Se,F,ge]),qe=C.useCallback(()=>{ge(),O(!0)},[ge]),Ls=C.useCallback(G=>{$e("cancelled"),w(G)},[$e]),_s=C.useCallback(()=>{Se||($e("cancelled"),Z.current=!1,H.current+=1,me.current="",ne.current=0,w(""),V(""),T(""),D("draft"),f("draft"),j(""),R(!1),N({status:"idle"}),ze(),xe([]),we(G=>({...Qs,runId:G.runId})))},[$e,ze,Se,xe,we]),$s=C.useCallback(G=>{G||$e("cancelled"),O(G)},[$e]),bs=L.timelineSteps.findIndex(G=>G===L.activeStep),De=L.phase==="self-healing"?"Fixing validation issue":L.phase==="validating"?"Validating SQL":L.activeStep||"Drafting SQL",es=P.status==="valid"?{label:"Validation passed",className:"border-emerald-500/30 bg-emerald-500/10 text-emerald-700",detail:P.message}:P.status==="invalid"?{label:"Validation failed",className:"border-destructive/40 bg-destructive/10 text-destructive",detail:P.message}:P.status==="error"?{label:"Validation unavailable",className:"border-border/60 bg-muted/20 text-muted-foreground",detail:P.message}:null;return e.jsxs("div",{ref:B,className:"relative flex h-8 min-w-[320px] flex-1 items-center",children:[e.jsx(s.Input,{value:g,onChange:G=>Ls(G.target.value),onFocus:qe,onClick:qe,onKeyDown:G=>{G.key==="Enter"&&(G.preventDefault(),As(Je))},placeholder:"Type your question...",className:["h-8 border-transparent bg-muted/45 shadow-none focus-visible:border-border focus-visible:bg-background focus-visible:ring-0",js?"pr-[60px]":"pr-10"].join(" ")}),e.jsxs(s.Popover,{open:F,onOpenChange:$s,children:[e.jsx(s.PopoverAnchor,{asChild:!0,children:e.jsx("div",{className:"pointer-events-none absolute inset-0"})}),e.jsxs("div",{className:"absolute right-1 flex items-center gap-1",children:[js&&e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"size-6 p-0",onClick:G=>{G.preventDefault(),$e("cancelled"),w("")},disabled:Se,"aria-label":"Clear input",title:"Clear input",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"size-6 p-0",onClick:G=>{G.preventDefault(),As(Je)},disabled:Se,"aria-label":Ds,title:Ds,children:e.jsx(bn,{className:"size-3.5"})})]}),e.jsx(s.PopoverContent,{align:"start",alignOffset:0,side:"bottom",sideOffset:8,className:"w-[min(92vw,var(--radix-popover-trigger-width))] max-w-[760px] p-2.5",onOpenAutoFocus:G=>{G.preventDefault()},onInteractOutside:G=>{var Y;const J=G.target;J&&((Y=B.current)!=null&&Y.contains(J))&&G.preventDefault()},children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Composer"}),E&&e.jsx("p",{className:"line-clamp-2 text-xs text-muted-foreground",children:E})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"inline-flex h-7 items-center rounded-md border border-border/60 bg-background p-0.5 shadow-sm",children:[e.jsx(s.Button,{type:"button",size:"sm",variant:Je==="draft"?"secondary":"ghost",className:["h-6 rounded-[6px] px-2 text-xs",Je!=="draft"?"text-muted-foreground hover:text-foreground":""].join(" "),onClick:()=>{f("draft"),R(!1)},children:"Draft New"}),e.jsx(s.Button,{type:"button",size:"sm",variant:Je==="refine"?"secondary":"ghost",className:["h-6 rounded-[6px] px-2 text-xs",Je!=="refine"?"text-muted-foreground hover:text-foreground":""].join(" "),onClick:()=>f("refine"),disabled:!ds,children:"Refine Current"})]}),e.jsx("div",{className:"h-4 w-px bg-border/70"}),Se&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>{$e("stopped")},children:"Stop"}),!Se&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:_s,disabled:!qs,children:"Clear"})]})]}),L.timelineSteps.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[L.timelineSteps.map((G,J)=>{const Y=G===L.activeStep&&["drafting","validating","self-healing"].includes(L.phase),ue=!Y&&bs>=0&&J<bs;return e.jsx("span",{className:["rounded-full border px-2 py-0.5 text-[11px]",Y?"border-foreground/30 bg-foreground/10 text-foreground":ue?"border-border/60 bg-muted/20 text-muted-foreground":"border-border/50 bg-background text-muted-foreground/80"].join(" "),children:$n(G,L.attempt)},`${G}-${J}`)}),es&&e.jsx(s.TooltipProvider,{delayDuration:150,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:["rounded-full border px-2 py-0.5 text-[11px]",es.className].join(" "),children:es.label})}),e.jsx(s.TooltipContent,{side:"top",align:"start",className:"max-w-[680px] whitespace-pre-wrap break-words text-xs",children:es.detail})]})})]}),e.jsx("div",{className:"py-0.5",children:e.jsx(s.AssistantContextEntityControls,{mode:"full",compact:!0,inlineLayout:!0,inlineTriggerFirst:!0,triggerVariant:"outline",triggerIconOnly:!1,triggerLabel:"Context",onSelectionChange:Ie})}),(Se||L.phase==="self-healing"||P.status==="validating")&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border/60 bg-muted/20 px-3 py-2 text-xs text-muted-foreground",children:[e.jsx(s.LoaderCircle,{className:"size-3.5 animate-spin"}),De]}),He&&e.jsx("div",{className:"rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-xs text-destructive",children:Cs}),v==="refine"&&I&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-md border border-border/60 bg-muted/20 px-2.5 py-1.5 text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Refining editor SQL"}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>R(G=>!G),children:k?"Hide base SQL":"View base SQL"})]}),k&&e.jsx("div",{className:"max-h-[120px] overflow-auto rounded-md border border-border/60",children:e.jsx(s.CodeHighlighter,{code:I,language:"sql"})})]}),cs?e.jsxs("div",{className:"space-y-1",children:[v==="refine"&&e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Refined SQL"}),e.jsx("div",{className:"max-h-[200px] overflow-auto rounded-md border border-border/60",children:e.jsx(s.CodeHighlighter,{code:A,language:"sql"})})]}):ns?e.jsx("div",{className:"rounded-md border border-dashed border-border/70 px-3 py-2 text-xs text-muted-foreground",children:"Validating SQL draft before preview."}):!Se&&e.jsx("div",{className:"rounded-md border border-dashed border-border/70 px-3 py-2 text-xs text-muted-foreground",children:ds?"Choose Draft New or Refine Current, then press Enter or click send.":"Describe what you want to query, then press Enter or click send to generate a SQL preview."}),e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:o,children:"Open Full Assistant"}),e.jsx(s.Button,{variant:"secondary",size:"sm",className:"h-8",disabled:Se||!cs,onClick:()=>Es(!1),children:"Replace SQL"}),e.jsx(s.Button,{size:"sm",className:"h-8",disabled:Se||!cs||Is||gs,onClick:()=>Es(!0),children:"Replace & Run"})]})]})})]})]})}function Un(){var ne,me;const t=s.useQueryClient(),[n,a]=C.useState(!1),r=s.useEditorStore(ee=>ee.frame),i=s.useEditorStore(ee=>ee.card);s.useEditorStore(ee=>ee.isShowingVisual),s.useEditorStore(ee=>ee.selectedConnectionId),s.useEditorStore(ee=>ee.tempQueryData);const d=s.useEditorStore(ee=>ee.selectedDatabaseName);s.useEditorStore(ee=>ee.selectedDatamodelId);const o=s.useEditorStore(ee=>ee.selectedSchemaName);s.useEditorStore(ee=>ee.showAIDialog);const c=s.useEditorStore(ee=>ee.selectedTableName),{cardFilterValues:l}=s.useCardFilterValues((i==null?void 0:i.id)??""),x=s.useDashboardStore(ee=>ee.inlineFilterValuesMap[(i==null?void 0:i.id)??""]),p=C.useMemo(()=>s.findCustomVisualConfigCard(r,i),[r,i]),{manifest:h}=s.useCustomVisual(((ne=p==null?void 0:p.customCardPreferences)==null?void 0:ne.url)||""),u=C.useMemo(()=>{var ee;return(ee=h==null?void 0:h.visuals)==null?void 0:ee.find(Ne=>{var q;return Ne.name===((q=p==null?void 0:p.customCardPreferences)==null?void 0:q.componentName)})},[h,(me=p==null?void 0:p.customCardPreferences)==null?void 0:me.componentName]),y=s.resolveMultiInputType(p,u),b=C.useMemo(()=>s.getCustomVisualInputCards({frame:r,configCard:p,isMultiInputVisual:y==="multiple"}),[r,p,y]),m=C.useMemo(()=>{const ee=b.findIndex(Ne=>(Ne==null?void 0:Ne.id)===(i==null?void 0:i.id));return ee<0?-1:s.getSlotIndexForCard(i,ee)},[b,i]),g=C.useMemo(()=>!p||y!=="multiple"||m<0?i.type:s.getEffectiveCardTypeForSlot(i,m,u==null?void 0:u.slots)??i.type,[p,y,m,i,u==null?void 0:u.slots]),w=C.useMemo(()=>g!==i.type?{...i,type:g}:i,[i,g]),E=C.useRef(!0),{setCardCustomCfg:V,setQueryResultColumns:A,setCardSql:T,setTempQueryData:v,setPythonStdOut:D,setCardPreferences:M,setCardType:f,setCardPython:I,setShowAIDialog:j,setCard:k,updateCardInFrame:R}=s.useEditorActions();s.useEditorStore(ee=>ee.onSave),s.useEditorStore(ee=>ee.onClose),s.useEditorStore(ee=>ee.actions.setSqlGen);const P=s.useEditorStore(ee=>ee.runSql),N=s.useEditorStore(ee=>ee.actions.setRunSql),L=s.useEditorStore(ee=>ee.actions.setIsSqlRunning),{data:S,isLoading:F,isFetching:O,isSuccess:_,isError:Q,error:B,errorSql:K,queryKey:se,refetch:H,errorMessage:te}=s.useDashboardCardQuery(w);C.useEffect(()=>{if(S&&(S.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),D((S==null?void 0:S.output)||""),S.records.length>0)){const{dimensionKeys:ee}=s.getKeys(S.records);A(ee)}},[S,A,D]),C.useEffect(()=>{(F||O)&&L(!0),(Q||_)&&L(!1),Q&&(A([]),D(""))},[F,O,S,D,Q,_,L,A,B]),C.useEffect(()=>{P&&(t.getQueryData(se)||H(),N(!1))},[P,H,N,se,t]);const z=C.useRef(H);z.current=H,C.useEffect(()=>{if(E.current){E.current=!1;return}z.current()},[x]);function W(ee,Ne){T(ee),Ne&&N(!0)}function le(){return e.jsxs(s.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(s.ResizablePanel,{id:"1",order:1,defaultSize:n?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(Mn,{})}),n&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),n&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizableHandle,{withHandle:!0,className:"data-[panel-group-direction=vertical]:ml-2 data-[panel-group-direction=vertical]:mr-6 data-[panel-group-direction=vertical]:w-auto"}),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(Rn,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function X(){return e.jsx("div",{role:"editor-controls",className:"item-center flex w-full flex-wrap items-center gap-2 py-3 pl-2 pr-6",children:e.jsxs("div",{className:"flex w-full items-center gap-3",children:[e.jsxs(s.Button,{title:"Shift + Enter",disabled:F||O,onClick:()=>{H()},className:"h-8 shrink-0",size:"sm",children:[F||O?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"]}),(S==null?void 0:S.sql)&&!te&&e.jsxs(s.HoverCard,{openDelay:300,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Info,{className:"h-4 w-4 shrink-0 cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(s.HoverCardContent,{align:"start",className:"w-[500px] p-0",children:e.jsx(ka,{sql:S.sql})})]}),e.jsx(Ae.EditorClearButton,{}),e.jsxs(s.Toggle,{pressed:n,onPressedChange:ee=>a(ee),className:"h-8",size:"sm",variant:"outline",children:[e.jsx(An,{className:"mr-2 size-4 text-foreground/70"}),"Python"]}),e.jsx(Kn,{currentSql:i==null?void 0:i.sql,currentPython:i==null?void 0:i.python,selectedDatabaseName:d,selectedSchemaName:o,selectedTableName:c,onApplySql:W,onOpenFullAssistant:()=>j(!0)}),e.jsx("div",{className:"ml-auto flex shrink-0 items-center gap-3",children:l&&l.length>0&&e.jsxs(s.HoverCard,{openDelay:200,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",className:"h-8 gap-2 px-2",children:[e.jsx(s.Filter,{className:"size-4"}),e.jsx(s.Badge,{className:"h-5 min-w-5 bg-purple-100 px-1.5 text-purple-700 hover:bg-purple-100 dark:bg-purple-950 dark:text-purple-300",children:l.length})]})}),e.jsx(s.HoverCardContent,{className:"mr-4 max-h-[400px] w-[500px] overflow-auto p-0",children:e.jsxs("div",{className:"p-3",children:[e.jsx("div",{className:"mb-2 text-sm font-semibold",children:"Active Dashboard Filters"}),e.jsx(s.CodeHighlighter,{code:JSON.stringify(l,null,2),language:"json"})]})})]})})]})})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsx("div",{className:"relative flex grow overflow-y-scroll",children:le()}),X()]})}const Hn=[{value:"table",label:"Table",icon:s.Table2},{value:"aggregateTable",label:"Aggregate",icon:s.Layers},{value:"pivotTable",label:"Pivot",icon:s.Grid3x3},{value:"detailTable",label:"Detail",icon:s.List}];function Jn({className:t}){const n=s.useEditorStore(h=>h.card),a=s.useEditorStore(h=>h.frame),r=Ae.useEffectiveEditorCardType(),{setCard:i,updateCardInFrame:d}=s.useEditorActions(),o=["table","aggregateTable","pivotTable","detailTable"].includes(r),c=s.hasValidCardConfig(n.config),l=s.isCustomVisualConfigCard(n,a.cards);if(!o||!c||l)return null;const x=h=>{if(l)return;const u=h,y=n.config??{},b=p(r,u,y),m={...n,type:u,config:b};i(m),d(m)},p=(h,u,y)=>{var m;if(u==="detailTable"){const g=A=>A==null?void 0:A.toLowerCase().replace(/\s+/g,"").trim(),w=(A,T)=>{const v=[g(A.label),g(A.qualifiedFieldName),g(A.name)].filter(Boolean),D=[g(T.label),g(T.qualifiedFieldName),g(T.name)].filter(Boolean);return v.some(M=>D.includes(M))},E=(y.groupByColumns||[]).map(A=>({...A,role:"detail"})),V=((m=y.sortByColumns)==null?void 0:m.filter(A=>E.some(T=>w(A,T))))??[];return{...y,detailTableBackup:{groupByColumns:y.groupByColumns,metricColumns:y.metricColumns,pivotByColumns:y.pivotByColumns,sortByColumns:y.sortByColumns,rowAggregates:y.rowAggregates,columnAggregates:y.columnAggregates,comparisonType:y.comparisonType},detailColumns:E,groupByColumns:[],metricColumns:[],pivotByColumns:[],sortByColumns:V,rowAggregates:[],columnAggregates:[],comparisonType:"none"}}let b=y;if(h==="detailTable")if(y.detailTableBackup)b={...y,...y.detailTableBackup,detailColumns:[],detailTableBackup:void 0};else{const g=(y.detailColumns||[]).map(w=>({...w,role:"groupby"}));b={...y,groupByColumns:g,detailColumns:[]}}return u==="aggregateTable"?{...b,pivotByColumns:[]}:b};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsx(s.RadioGroup,{value:r,onValueChange:x,className:"flex flex-row items-center gap-1 border-b border-border/60",children:Hn.map(h=>{const u=h.icon,y=r===h.value;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(s.RadioGroupItem,{value:h.value,id:`table-type-${h.value}`,className:"peer sr-only"}),e.jsxs(s.Label,{htmlFor:`table-type-${h.value}`,className:s.cn("flex h-8 cursor-pointer items-center justify-center gap-1.5 whitespace-nowrap border-b-2 border-transparent px-2 pb-1 text-xs font-medium transition-colors",y?"border-foreground text-foreground":"text-muted-foreground hover:border-foreground/30 hover:text-foreground"),children:[e.jsx(u,{className:s.cn("h-3.5 w-3.5",y?"opacity-100":"opacity-75")}),h.label]})]},h.value)})})})}function ot({error:t,errorSql:n,errorTitle:a="Unable to load data",onOpenInEditor:r,onDebugWithAssistant:i,onSendFeedback:d,showFeedbackButton:o=!0,className:c}){const[l,x]=C.useState(!1);return e.jsx("div",{className:s.cn("rounded-lg border border-border bg-muted/40 p-4",c),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-amber-500/10 dark:bg-amber-500/20",children:e.jsx(s.TriangleAlert,{className:"h-4 w-4 text-amber-600 dark:text-amber-500"})}),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-foreground",children:a}),e.jsxs("div",{className:"relative rounded-md border border-border bg-background p-3",children:[e.jsx(s.CopyButton,{text:t,className:"absolute right-2 top-2 z-10 h-6 w-6"}),e.jsx("div",{className:"max-h-40 overflow-auto pr-10",children:e.jsx("p",{className:"break-all font-mono text-xs text-muted-foreground",children:t})})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n&&e.jsx(s.Collapsible,{open:l,onOpenChange:x,children:e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",children:l?e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronUp,{className:"mr-1.5 h-3.5 w-3.5"}),"Hide Details"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronDown,{className:"mr-1.5 h-3.5 w-3.5"}),"Show Details"]})})})}),r&&n&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:r,children:[e.jsx(Na,{className:"mr-1.5 h-3.5 w-3.5"}),"Open in Editor"]}),o&&d&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:d,children:[e.jsx(s.MessageSquareWarning,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]}),i&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:i,children:[e.jsx(un,{className:"mr-1.5 h-3.5 w-3.5"}),"Debug with Assistant"]})]}),n&&e.jsx(s.Collapsible,{open:l,onOpenChange:x,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:"Query"}),e.jsx(s.CopyButton,{text:n,className:"h-6 w-6"})]}),e.jsx("div",{className:"max-h-80 overflow-auto rounded-md border border-border bg-background p-2",children:e.jsx(s.CodeHighlighter,{code:n,language:"sql"})})]})})})]})]})})}function Da(t,n){const a=s.useEditorStore(x=>x.card),r=s.useEditorStore(x=>x.isDevMode),{switchEditorMode:i,setRunSql:d,runAssistant:o}=s.useEditorActions();return{isDevMode:r,handleOpenInEditor:r?void 0:()=>{const x=n||a.sql||a.python||"";i("dev",{sqlToLoad:x}),setTimeout(()=>{d(!0)},100)},handleDebugWithAssistant:r?()=>{const x=`Can you help me debug this query?
|
|
177
177
|
|
|
178
178
|
Error:
|
|
179
179
|
|
|
@@ -183,6 +183,6 @@ ${r}`].filter(Boolean).join(`
|
|
|
183
183
|
|
|
184
184
|
${n||a.sql||a.python}
|
|
185
185
|
|
|
186
|
-
`;o(x)}:void 0}}function Da({className:t,...n}){var X,ne,ue,ee,Ne;const a=s.useEditorStore(q=>q.card);s.useEditorStore(q=>q.isDevMode);const r=((X=a.customCardPreferences)==null?void 0:X.showCardHeader)??!0,i=((ue=(ne=a.preferences)==null?void 0:ne.displayOptions)==null?void 0:ue.showInlineFilterBar)??!0,d=s.useEditorStore(q=>q.frame),o=s.useDashboardStore(q=>q.dashboard.filters),c=s.useDashboardStore(q=>q.selectedSheetId),[l,x]=C.useState(!1),{currentUser:p}=s.useCurrentUserInfo(),{tokenProps:h}=C.useContext(s.SemaphorContext),u=s.useEditorStore(q=>q.actions.setRunSql),{updateFilter:y}=s.useDashboardActions(),b=o==null?void 0:o.find(q=>q.id===d.filterId),m=C.useMemo(()=>s.findCustomVisualConfigCard(d,a),[d,a]),{manifest:g}=s.useCustomVisual(((ee=m==null?void 0:m.customCardPreferences)==null?void 0:ee.url)||""),w=C.useMemo(()=>{var q;return(q=g==null?void 0:g.visuals)==null?void 0:q.find(Z=>{var ie;return Z.name===((ie=m==null?void 0:m.customCardPreferences)==null?void 0:ie.componentName)})},[g,(Ne=m==null?void 0:m.customCardPreferences)==null?void 0:Ne.componentName]),E=s.resolveMultiInputType(m,w),V=C.useMemo(()=>s.getCustomVisualInputCards({frame:d,configCard:m,isMultiInputVisual:E==="multiple"}),[d,m,E]),A=C.useMemo(()=>{const q=V.findIndex(Z=>(Z==null?void 0:Z.id)===(a==null?void 0:a.id));return q<0?-1:s.getSlotIndexForCard(a,q)},[V,a]),T=C.useMemo(()=>!m||E!=="multiple"||A<0?a.type:s.getEffectiveCardTypeForSlot(a,A,w==null?void 0:w.slots)??a.type,[m,E,A,a,w==null?void 0:w.slots]),v=T??a.type,D=C.useMemo(()=>v===a.type?a:{...a,type:v},[a,v]),L=C.useMemo(()=>T!==a.type?{...a,type:T}:a,[a,T]),{data:f,isLoading:I,isFetching:j,errorMessage:k,errorSql:R,pagination:P}=s.useDashboardCardQuery(L),{handleOpenInEditor:N,handleDebugWithAssistant:M}=ka(k,R||a.sql||a.python),S=C.useMemo(()=>(f==null?void 0:f.records)||[],[f==null?void 0:f.records]),{setCard:F,updateCardInFrame:O}=s.useEditorActions(),{data:$}=s.useTopoJson(D),Q=C.useMemo(()=>{var q;return v!=="pivotTable"||!((q=f==null?void 0:f.records)!=null&&q.length)?null:{records:f.records,columnSubtotalMeta:f.columnSubtotalMeta,subtotalColumns:f.subtotalColumns||[],pivotSchema:f.pivotSchema||[],groupByColumns:f.groupByColumns}},[v,f==null?void 0:f.records,f==null?void 0:f.columnSubtotalMeta,f==null?void 0:f.subtotalColumns,f==null?void 0:f.pivotSchema,f==null?void 0:f.groupByColumns]),B=s.usePivotTableConfig(D,Q),K=()=>{x(!0)},se=C.useMemo(()=>{const q=typeof window<"u"?window.location.href:"",Z=typeof navigator<"u"?navigator.userAgent:"",ie=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:s.FeedbackCategory.QUERY_GENERATION,user:p,tokenContext:h,systemState:{cardConfig:a.config,dataSource:a.dataSource,dashboardFilters:o,errorMessage:k||void 0,errorSql:R||a.sql||a.python,generatedSql:R||a.sql},metadata:{url:q,userAgent:Z,timestamp:new Date().toISOString(),viewport:ie}}},[p,h,a,o,k,R]),H=(q,Z)=>{var je,ke;const ie={...a,paginationConfig:{page:q+1,pageSize:Z}};F(ie),O(ie),a.sql&&((ke=(je=a.preferences)==null?void 0:je.tablePrefs)!=null&&ke.enableDevModePagination)&&u(!0)},te=q=>{var je,ke,Oe,Se,be;const Z=s.sortStateToSortByColumns(q,(je=a.config)==null?void 0:je.metricColumns,(ke=a.config)==null?void 0:ke.groupByColumns,(Oe=a.config)==null?void 0:Oe.detailColumns),ie={...a,config:{...a.config||{},sortByColumns:Z}};F(ie),O(ie),a.sql&&((be=(Se=a.preferences)==null?void 0:Se.tablePrefs)!=null&&be.enableDevModePagination)&&u(!0)},z=C.useMemo(()=>!D.id||!(f!=null&&f.records)?null:s.createChartConfig({card:D,data:f==null?void 0:f.records,cardType:v,queryConfig:D.queryConfig,customCfg:D.customCfg,preferences:D.preferences,topoJson:$}),[D,f==null?void 0:f.records,v,$]);function W(q){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(s.EditorCustomVisual,{card:q})})}function le(){var q;if(f!=null&&f.records&&(f==null?void 0:f.records.length)===0&&!I&&!j)return k?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(lt,{error:k,errorSql:R||a.sql||a.python,onOpenInEditor:N,onDebugWithAssistant:M,onSendFeedback:K,showFeedbackButton:!0})}):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((I||j)&&(!(f!=null&&f.records)||f.records.length===0))return v==="table"||v==="detailTable"?e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableSkeleton,{})}):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(!D.id)return null;if(v==="custom")return W(a);if(!["table","pivotTable","aggregateTable","detailTable","custom"].includes(v)&&z)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:I||j?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:z})});if(v==="table"||v==="detailTable")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:D,data:S,comparisonMetadata:(q=f==null?void 0:f.metadata)==null?void 0:q.comparisonMetadata,paginationMetadata:P,onPaginationChange:H,onSortChange:te,isLoading:I||j})});if(v==="pivotTable"&&B)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:D,data:B.data,options:B.options,onAggregationChange:Z=>{const ie=s.handleAggregationChange(Z,a.config),je={...a,config:ie};F(je),O(je)},onAggregationLabelChange:Z=>{const ie=s.handleAggregationLabelChange(Z,a.config),je={...a,config:ie};F(je),O(je)}})});if(v==="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:D,data:(f==null?void 0:f.records)||[],groupByColumns:f==null?void 0:f.groupByColumns,pivotSchema:f==null?void 0:f.pivotSchema,paginationMetadata:P,onPaginationChange:H,onAggregationChange:Z=>{const ie=s.handleAggregationChange(Z,a.config),je={...a,config:ie};F(je),O(je)},isLoading:I||j})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...n,children:[(I||j)&&(f==null?void 0:f.records)&&f.records.length>0&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),r&&e.jsxs(s.CardHeader,{className:s.cn("flex flex-row items-start justify-between py-4 pr-6","pl-2"),children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.CardTitle,{className:"text-base",children:e.jsx(s.EditableText,{value:a.title,onSave:q=>F({...a,title:q}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(s.InfoHover,{card:a}),e.jsx(Ae.VisualBadge,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(Hn,{})})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:(a.description||"").trim(),onSave:q=>F({...a,description:q.trim()}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),b&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:b.title||b.column,onSave:q=>y({...b,title:q}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:b})]})]}),i&&a.inlineFilters&&a.inlineFilters.length>0&&e.jsx("div",{className:s.cn("pb-3 pr-6","pl-2"),children:e.jsx(s.InlineFilterBar,{card:a,sheetId:c||""})}),e.jsxs(s.CardContent,{className:s.cn("flex min-h-0 grow flex-col pr-6","pl-2"),children:[e.jsx("div",{className:"min-h-0 flex-1 grow basis-0",children:le()}),s.isCardSummaryVisibleOnCard(D)&&e.jsx("div",{className:"pt-3",children:e.jsx(s.CardSummary,{card:D,mode:"editor"})})]}),e.jsx(s.FeedbackDialog,{open:l,onOpenChange:x,feedbackData:se,showDebugInfo:!0})]})}const Qs=({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}),Jn=()=>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."})]})]}),Qn=({customCode:t,cardCustomCfgString:n,mergedConfig:a,onConfigChange:r,onCodeChange:i})=>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(Qs,{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(Qs,{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(Qs,{language:"javascript",value:t,onChange:i})})]}),Yn=({error:t,hasCardCustomConfig:n,onReset:a,onApply:r,onClose:i})=>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:i,variant:"outline",children:"Close"})]});function Wn({triggerVariant:t="icon",className:n,label:a="Customize Visual"}={}){const[r,i]=C.useState(!1),[d,o]=C.useState(""),[c,l]=C.useState(""),[x,p]=C.useState(""),[h,u]=C.useState(""),y=s.useEditorStore(I=>I.card),b=Ae.useEffectiveEditorCardType(),m=s.useEditorStore(I=>I.card.customCfg),g=m?JSON.stringify(m,null,2):"",w=C.useMemo(()=>b!==y.type?{...y,type:b}:y,[y,b]),{data:E}=s.useDashboardCardQuery(w),{data:V}=s.useTopoJson(y),{setCardCustomCfg:A,setCustomVisualCode:T}=s.useEditorActions(),v=I=>{var j,k;return JSON.stringify({...I,data:{...I.data,datasets:(k=(j=I.data)==null?void 0:j.datasets)==null?void 0:k.map(R=>({...R,data:[]}))}},null,2)},D=()=>{var j,k;if(!((j=E==null?void 0:E.records)!=null&&j.length))return;const I=s.createChartConfig({card:y,data:E.records,cardType:y.type,queryConfig:y.queryConfig,preferences:y.preferences,topoJson:V});if(I){o(v(I)),p(((k=y.preferences)==null?void 0:k.customVisualCode)||"");const R=s.merge(I,m);l(v(R))}},L=()=>{try{if(x&&T(x),c){const I=JSON.parse(c),j=s.getObjectDiff(JSON.parse(d),I);A(j),u("")}}catch{u("Invalid JSON configuration")}},f=Object.keys(m||{}).length===0;return e.jsxs(s.Dialog,{open:r,onOpenChange:i,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:t==="menu"?e.jsxs(s.Button,{variant:"ghost",onClick:D,className:s.cn("h-8 w-full justify-start gap-2 px-2 text-sm",f?"":"text-green-600 hover:text-green-700",n),children:[e.jsx(s.Settings,{className:"h-4 w-4"}),e.jsx("span",{children:a})]}):e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:D,className:s.cn(f?"":"text-green-600 hover:text-green-700",n),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(Jn,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Da,{className:"w-1/2 rounded shadow-none"})}),e.jsx(Qn,{customCode:x,cardCustomCfgString:g,mergedConfig:c,onConfigChange:I=>l(I??""),onCodeChange:I=>p(I??"")})]}),e.jsx(Yn,{error:h,hasCardCustomConfig:!!m,onReset:()=>{l(d),A(null)},onApply:L,onClose:()=>i(!1)})]})]})}function Xn({isStarred:t,onClick:n,className:a}){const r=i=>{i.stopPropagation(),i.preventDefault(),n(i)};return e.jsx("button",{type:"button",onClick:r,className:s.cn("flex items-center justify-center rounded-sm p-0.5 transition-all","hover:bg-muted/80",a),"aria-label":t?"Remove from favorites":"Add to favorites",children:e.jsx(s.Star,{className:s.cn("h-3.5 w-3.5 transition-colors",t?"fill-yellow-400 text-yellow-400":"text-muted-foreground hover:text-foreground")})})}function ra({chartType:t,chartName:n,isCustom:a=!1,pluginName:r,isStarred:i,showStar:d=!0,onSelect:o,onToggleStar:c}){return e.jsxs("button",{onClick:o,className:s.cn("group relative flex flex-col items-center gap-2 rounded-lg border border-border","bg-background p-3 transition-all","hover:border-primary/50 hover:bg-muted/50 hover:shadow-sm"),children:[d&&e.jsx("div",{className:s.cn("absolute left-1 top-1 transition-opacity",i?"opacity-100":"opacity-0 group-hover:opacity-100"),children:e.jsx(Xn,{isStarred:i,onClick:()=>c()})}),a&&r&&e.jsx("div",{className:"absolute right-1 top-1",children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center justify-center",children:e.jsx(s.Info,{className:"h-3 w-3 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"top",className:"text-xs",children:r})]})}),e.jsx(s.ChartIcon,{chartType:t,chartName:n,isCustom:a,className:"h-6 w-6"}),e.jsx("span",{title:n,className:"line-clamp-2 text-center text-xs font-medium text-foreground",children:n})]})}const la=[{id:"table",name:"Table"},{id:"bar",name:"Bar Chart"},{id:"line",name:"Line Chart"},{id:"area",name:"Area Chart"},{id:"combo",name:"Combo Chart"},{id:"stackedBar",name:"Stacked Bar"},{id:"stackedArea",name:"Stacked Area"},{id:"stackedLine",name:"Stacked Line"},{id:"scatter",name:"Scatter"},{id:"bubble",name:"Bubble"},{id:"pie",name:"Pie Chart"},{id:"doughnut",name:"Doughnut"},{id:"funnel",name:"Funnel"},{id:"radar",name:"Radar"},{id:"polarArea",name:"Polar Area"},{id:"tornado",name:"Tornado"},{id:"range",name:"Range"},{id:"bullet",name:"Bullet Chart"},{id:"treemap",name:"Treemap"},{id:"heatmap",name:"Heatmap"},{id:"kpi",name:"KPI"},{id:"text",name:"Text"},{id:"map",name:"Map"}];function Zn({onChartSelect:t,onClose:n}){const[a,r]=C.useState(""),{starredCharts:i,isStarred:d,toggleStar:o}=s.useStarredChartsStore(),{data:c=[],isLoading:l}=s.useCustomVisualsQuery(),{setCardType:x,setCardPreferences:p,setIsDevMode:h}=s.useEditorStore(f=>f.actions),u=s.useEditorStore(f=>f.card),{setCardCustomCfg:y,setCustomCardPreferences:b,setQueryConfig:m,replaceFrameCards:g,clearModeDrafts:w,initializeModeDrafts:E}=s.useEditorActions(),V=C.useMemo(()=>{if(!a)return la;const f=a.toLowerCase();return la.filter(I=>I.name.toLowerCase().includes(f))},[a]),A=C.useMemo(()=>{const f=c.filter(j=>j.componentType==="chart"&&j.pluginType!=="standard");if(!a)return f;const I=a.toLowerCase();return f.filter(j=>j.name.toLowerCase().includes(I))},[c,a]),T=f=>{y(null),p({}),x(f),["custom","text","map"].includes(f)&&(h(!0),m(void 0)),t==null||t(f),n==null||n()},v=f=>{y(null),p({}),m(void 0);const I=s.resolveMultiInputTypeFromVisual(f);if(I==="multiple"&&f.slots&&f.slots.length>0){w();const k=s.createCardsFromSlots(f.slots,f,u);g(k),k[0]&&E(k[0]),n==null||n();return}else x("custom"),b({type:"component",visualType:I,url:f.url,componentName:f.name,icon:f.icon,pluginChartType:f.chartType,minInputs:f.minInputs,maxInputs:f.maxInputs});t==null||t("custom",f),n==null||n()},D=f=>{const I={type:"default",id:f.id,name:f.name};o(I)},L=f=>{const I={type:"custom",id:f.name,url:f.url,icon:f.icon,name:f.name};o(I)};return e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2 rounded-sm border border-border bg-background px-3 py-2",children:[e.jsx(s.Search,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search charts...",value:a,onChange:f=>r(f.target.value),className:"h-auto border-0 p-0 text-sm focus-visible:ring-0 focus-visible:ring-offset-0"})]}),e.jsxs("div",{className:"max-h-[350px] overflow-y-auto",children:[V.length>0&&e.jsx("div",{className:"mb-3",children:e.jsx("div",{className:"grid grid-cols-3 gap-2",children:V.map(f=>e.jsx(ra,{chartType:f.id,chartName:f.name,isCustom:!1,isStarred:d("default",f.id),onSelect:()=>T(f.id),onToggleStar:()=>D(f)},f.id))})}),A.length>0&&e.jsxs(e.Fragment,{children:[V.length>0?e.jsx(s.Separator,{className:"my-3"}):null,e.jsxs("div",{children:[e.jsx("span",{className:"mb-2 block text-xs font-medium text-muted-foreground",children:"Custom Charts"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:A.map((f,I)=>e.jsx(ra,{chartName:f.name,isCustom:!0,pluginName:f.pluginName,isStarred:d("custom",f.name),onSelect:()=>v(f),onToggleStar:()=>L(f)},`${f.url}-${f.name}-${I}`))})]})]}),l&&e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-3"}),e.jsx("div",{className:"py-4 text-center text-sm text-muted-foreground",children:"Loading custom charts..."})]}),V.length===0&&A.length===0&&!l&&e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No charts found"})]})]})}function er({selectedChart:t,onChartChange:n}){var v,D,L,f;const a=s.useEditorStore(I=>I.card),r=s.useEditorStore(I=>I.frame),i=s.useEditorStore(I=>I.isDevMode),{replaceFrameCards:d,clearModeDrafts:o,initializeModeDrafts:c,setIsDevMode:l}=s.useEditorActions(),x=C.useMemo(()=>s.findCustomVisualConfigCard(r,a),[r,a]),{manifest:p}=s.useCustomVisual(((v=x==null?void 0:x.customCardPreferences)==null?void 0:v.url)||""),h=C.useMemo(()=>{var I;return(I=p==null?void 0:p.visuals)==null?void 0:I.find(j=>{var k;return j.name===((k=x==null?void 0:x.customCardPreferences)==null?void 0:k.componentName)})},[p,(D=x==null?void 0:x.customCardPreferences)==null?void 0:D.componentName]),u=s.resolveMultiInputType(x,h)==="multiple",y=Ae.useEffectiveEditorCardType(),b=u?y:t??a.type,m=(L=a==null?void 0:a.customCardPreferences)==null?void 0:L.componentName,g=(f=x==null?void 0:x.customCardPreferences)==null?void 0:f.componentName,w=u&&!!g,E=C.useMemo(()=>{const I=s.chartTypes.find(j=>j.id===b);return I?I.label:b==="custom"?m||"Custom Visual":"Select chart type"},[b,m]),V=C.useMemo(()=>{const I=s.chartTypes.find(j=>j.id===b);if(I){const j=I.icon;return e.jsx(j,{className:"h-4 w-4"})}if(b==="custom"&&m){const j=s.getAutoDetectedChartIcon(m);return j||e.jsx(s.ChartIcon,{chartName:m,isCustom:!0,className:"h-4 w-4"})}return e.jsx(bn,{className:"h-4 w-4"})},[b,m]);return{displayChartType:b,displayLabel:E,displayIcon:V,showBadge:w,badgeLabel:g,isMultiInputContext:u,handleChartSelect:I=>{n==null||n(I)},handleClearCustomVisual:I=>{I.stopPropagation();const j={...a,type:"bar",sql:"",python:"",config:void 0,queryConfig:void 0,customCfg:void 0,preferences:{},customCardPreferences:void 0,title:"Chart",tabTitle:"Chart",description:void 0,info:void 0};d([j]),o(),c(j),i&&l(!0),n==null||n("bar")}}}function ot({selectedChart:t,onChartChange:n,variant:a="ghost",className:r}){const[i,d]=C.useState(!1),{displayLabel:o,displayIcon:c,showBadge:l,badgeLabel:x,handleChartSelect:p,handleClearCustomVisual:h}=er({selectedChart:t,onChartChange:n});return e.jsxs("div",{className:s.cn("relative w-full",r),children:[e.jsxs(s.Popover,{open:i,onOpenChange:d,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:a,role:"combobox","aria-expanded":i,className:s.cn("w-full justify-between gap-2",a==="ghost"&&"border border-border/70 bg-background text-foreground/90",a==="outline"&&"border-border/70 bg-background text-foreground/90",a==="secondary"&&"text-foreground"),children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c,e.jsx("span",{className:"truncate",children:o})]}),e.jsx(s.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-70"})]})}),e.jsx(s.PopoverContent,{className:"w-[360px] p-3",align:"start",onOpenAutoFocus:u=>u.preventDefault(),children:e.jsx(Zn,{onChartSelect:u=>p(u),onClose:()=>d(!1)})})]}),l&&e.jsxs("div",{className:"absolute right-10 top-1/2 z-10 flex max-w-[140px] -translate-y-1/2 items-center gap-1 rounded-full border bg-background py-0.5 pl-2 pr-1 text-[10px] text-muted-foreground shadow-sm",title:x,children:[e.jsx(s.Layers,{className:"h-2.5 w-2.5 shrink-0"}),e.jsx("span",{className:"truncate",children:x}),e.jsx("button",{onClick:h,className:"rounded-full p-0.5 hover:bg-muted",title:"Clear custom visual",children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]})]})}function sr(){const t=s.useEditorStore(l=>{var x,p;return(p=(x=l.card.preferences)==null?void 0:x.chartOptions)==null?void 0:p.indexAxis}),n=s.useEditorStore(l=>l.card.type),{setChartOrientation:a,setCardPreferences:r}=s.useEditorStore(l=>l.actions),i=l=>{if(a(l),n!=="bullet")return;const x=l==="y"?"horizontal":"vertical",p=s.useEditorStore.getState().card.preferences,h={...p||{},bulletConfig:{...(p==null?void 0:p.bulletConfig)||{},orientation:x}};r(h)};function d(){const l=t??"x",x=()=>{i(l==="x"?"y":"x")};return e.jsx(s.IconButton,{onClick:x,tooltip:"Chart Orientation",children:l==="x"?e.jsx(Hs,{className:"size-4"}):e.jsx(Us,{className:"size-4"})})}function o(){const l=()=>{i(t==="y"||t===void 0?"x":"y")};return e.jsx(s.IconButton,{onClick:l,tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(Hs,{className:"size-4"}):e.jsx(Us,{className:"size-4"})})}function c(){const l=t??"y",x=()=>{i(l==="y"?"x":"y")};return e.jsx(s.IconButton,{onClick:x,tooltip:"Chart Orientation",children:l==="y"?e.jsx(Us,{className:"size-4"}):e.jsx(Hs,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?o():n==="bullet"?c():d()})}function it({className:t,triggerVariant:n="icon",label:a="Display Options"}){var m,g,w,E,V,A,T,v,D,L;const r=s.useEditorStore(f=>f.card),{setCardPreferences:i,updateCardInFrame:d,setCard:o}=s.useEditorActions(),[c,l]=C.useState(!1),x=((g=(m=r.preferences)==null?void 0:m.displayOptions)==null?void 0:g.showFilterInfo)??!0,p=((E=(w=r.preferences)==null?void 0:w.displayOptions)==null?void 0:E.showCardToolbar)??!0,h=((A=(V=r.preferences)==null?void 0:V.displayOptions)==null?void 0:A.showChrome)??!0,u=((v=(T=r.preferences)==null?void 0:T.displayOptions)==null?void 0:v.allowScroll)??!0,y=((L=(D=r.preferences)==null?void 0:D.displayOptions)==null?void 0:L.showInlineFilterBar)??!0,b=(f,I)=>{var R;const j={...r.preferences,displayOptions:{...(R=r.preferences)==null?void 0:R.displayOptions,[f]:I}};i(j);const k={...r,preferences:j};o(k),d(k)};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsxs(s.DropdownMenu,{modal:!1,open:c,onOpenChange:l,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:n==="menu"?e.jsxs(s.Button,{variant:"ghost",className:"h-8 w-full justify-start gap-2 px-2 text-sm",children:[e.jsx(at,{className:"h-4 w-4"}),e.jsx("span",{children:a})]}):e.jsx(s.IconButton,{className:"h-8 w-8 p-0",tooltip:"Display Options",children:e.jsx(at,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(s.DropdownMenuLabel,{children:"Display Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx("div",{className:"px-2 py-1.5",children:e.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"Changes apply to dashboard view only"})}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:x,onCheckedChange:f=>{b("showFilterInfo",f)},onSelect:f=>f.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:p,onCheckedChange:f=>{b("showCardToolbar",f)},onSelect:f=>f.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:h,onCheckedChange:f=>{b("showChrome",f)},onSelect:f=>f.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:u,onCheckedChange:f=>{b("allowScroll",f)},onSelect:f=>f.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"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:y,onCheckedChange:f=>{b("showInlineFilterBar",f)},onSelect:f=>f.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Inline Filter Bar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card filters"})]})]})]})})}function ct({className:t,triggerVariant:n="icon",label:a="Inline Filters"}){const[r,i]=C.useState(!1),d=s.useEditorStore(m=>m.card),o=s.useEditorStore(m=>m.selectedConnectionId),{setCard:c}=s.useEditorActions(),l=s.useDashboardStore(m=>m.actions.removeCardInlineFilterValue),x=(d==null?void 0:d.inlineFilters)||[];function p(m){var I,j,k,R,P;const g=((k=(j=(I=d==null?void 0:d.dataSource)==null?void 0:I.selectedEntities)==null?void 0:j[0])==null?void 0:k.database)||"",w=m.qualifiedFieldName||m.name;if(x.find(N=>N.column===w))return;const V=m.qualifiedFieldName?m.qualifiedFieldName.split(".").slice(0,-1).join("."):m.qualifiedEntityName||m.entityName,T=s.fmt(m.name),v=s.buildFilterFieldMeta(m),D=s.buildFilterSemanticContext(d==null?void 0:d.dataSource,{connectionId:o||((R=d==null?void 0:d.dataSource)==null?void 0:R.connectionId),connectionType:(P=d==null?void 0:d.dataSource)==null?void 0:P.connectionType}),L=s.isCalculatedFilterField(v),f={id:s.v4(),column:w,title:m.label||m.name,dataType:m.dataType,table:m.entityName||"",database:g,connectionId:o||"",operation:"in",sql:L?"":s.getDefaultFilterSql(m.dataType,V,T),fieldMeta:v,semanticContext:D,width:250};c({...d,inlineFilters:[...x,f]})}function h(m){const g=x.filter(w=>w.id!==m);c({...d,inlineFilters:g}),l(d.id,m)}function u(m,g){const w=x.map(E=>E.id===m?{...E,...g}:E);c({...d,inlineFilters:w})}if(!["bar","line","pie","doughnut","table","detailTable","stackedBar","stackedLine","horizontalBar","radar","polarArea","scatter","bubble","funnel","aggregateTable","custom"].includes(d==null?void 0:d.type))return null;const b=n==="menu";return e.jsx("div",{className:s.cn("flex items-center gap-1",b&&"w-full",t),children:e.jsxs(s.Popover,{open:r,onOpenChange:i,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:b?e.jsxs(s.Button,{variant:"ghost",className:s.cn("h-8 w-full justify-start gap-2 px-2 text-sm",x.length>0&&"text-primary"),children:[e.jsx(Yt,{className:"h-4 w-4"}),e.jsx("span",{children:a}),x.length>0&&e.jsx("span",{className:"ml-auto inline-flex min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[10px] font-medium text-primary-foreground",children:x.length})]}):e.jsxs(s.IconButton,{tooltip:"Add Inline Filter",className:s.cn("relative",{"text-primary":x.length>0}),children:[e.jsx(Yt,{className:"h-4 w-4"}),x.length>0&&e.jsx("span",{className:"absolute -right-1 -top-1 flex h-4 w-4 items-center justify-center rounded-full bg-primary text-[10px] font-medium text-primary-foreground",children:x.length})]})}),e.jsx(s.PopoverContent,{align:"end",className:s.cn("w-80 p-0",b&&"z-[60]"),children:e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"border-b px-4 py-3",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Inline Filters"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"On-card filters for fast, focused exploration."})]}),e.jsx("div",{className:"flex max-h-[300px] flex-col overflow-hidden",children:e.jsx(s.DndContext,{collisionDetection:s.closestCenter,children:e.jsx(s.SortableContext,{items:[],strategy:s.verticalListSortingStrategy,children:e.jsx(s.FieldsList,{context:"inline-filter",onFieldSelect:p,inlineFilters:x})})})}),x.length>0&&e.jsxs("div",{className:"border-t px-4 py-3",children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Active Filters"}),e.jsx("div",{className:"space-y-1",children:x.map(m=>e.jsx(tr,{filter:m,onUpdate:g=>u(m.id,g),onRemove:()=>h(m.id)},m.id))})]})]})})]})})}function tr({filter:t,onUpdate:n,onRemove:a}){return e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-muted px-2 py-1.5 text-sm",children:[e.jsx("span",{className:"truncate",title:t.column,children:t.title}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(s.CustomFilterPopover,{filter:t,variant:"inline",onAccept:r=>n(r),trigger:e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0",title:"Configure filter",children:e.jsx(s.Settings2,{className:"h-3 w-3"})})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0 hover:bg-destructive/10 hover:text-destructive",onClick:a,children:e.jsx(s.X,{className:"h-3 w-3"})})]})]})}function Aa({showOrientation:t=!0,showGridStyle:n=!0,showInlineFilters:a=!0,showDisplayOptions:r=!0}={}){const i=s.useEditorStore(u=>u.card),d=s.useEditorStore(u=>{var y,b;return(b=(y=u.card)==null?void 0:y.preferences)==null?void 0:b.chartOptions}),o=s.getChartGridStyle(d),{setChartGrid:c}=s.useEditorActions();function l(){const u=["xy","none","x","y"],b=(u.indexOf(o)+1)%u.length;c(u[b])}const x=t&&["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel","bullet"].includes(i.type),p=n&&!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(i.type);return x||p||a||r?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[x&&e.jsx(e.Fragment,{children:e.jsx(sr,{})}),p&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:l,children:[(o==="xy"||!o)&&e.jsx(s.Grid3x3,{className:"size-4"}),o==="x"&&e.jsx(rt,{className:"size-4"}),o==="y"&&e.jsx(Rs,{className:"size-4"}),o==="none"&&e.jsx(s.Square,{className:"size-4"})]}),a&&e.jsx(ct,{}),r&&e.jsx(it,{})]}):null}function ar({isPreviewMode:t,onPreviewToggle:n,configCard:a}){var P,N,M,S,F;const r=s.useEditorStore(O=>O.frame),i=s.useEditorStore(O=>O.card),{setFrame:d,setActiveTabCardId:o,setCard:c,updateCardInFrame:l,clearModeDrafts:x,initializeModeDrafts:p}=s.useEditorActions(),{manifest:h}=s.useCustomVisual(((P=a==null?void 0:a.customCardPreferences)==null?void 0:P.url)||""),u=(N=h==null?void 0:h.visuals)==null?void 0:N.find(O=>{var $;return O.name===(($=a==null?void 0:a.customCardPreferences)==null?void 0:$.componentName)}),b=s.resolveMultiInputType(a,u)==="multiple",m=(u==null?void 0:u.minInputs)??((M=a==null?void 0:a.customCardPreferences)==null?void 0:M.minInputs)??1,g=(u==null?void 0:u.maxInputs)??((S=a==null?void 0:a.customCardPreferences)==null?void 0:S.maxInputs),w=C.useMemo(()=>s.getCustomVisualInputCards({frame:r,configCard:a,isMultiInputVisual:b}),[r,a,b]),E=b?w.filter(Boolean).length:r.cards.length,V=g?E<g:!0,A=E>Math.max(m||1,1),T=!!((F=a==null?void 0:a.customCardPreferences)!=null&&F.dataInputCardIds),v=(O,$)=>{O.dataTransfer.setData("tabIndex",$.toString())},D=O=>{O.preventDefault()},L=(O,$)=>{const Q=O.dataTransfer.getData("tabIndex");if(Q===$.toString())return;const B=Array.from(r.cards),[K]=B.splice(parseInt(Q),1);B.splice($,0,K),d({...r,cards:B})};function f(O){const $=(a==null?void 0:a.id)===O;if(!(T&&$?r.cards.length>1:A))return;let B=r.cards.filter(te=>te.id!==O);b&&!T&&(B=s.reindexSlotCards(B));const K=B[0],se={...r,cards:B,activeCardId:K.id},H=O===i.id;H&&x(),d(se),o(K.id),c(K),H&&p(K)}function I(O,$){if(!V)return;const Q={...r,cards:[...r.cards,$],activeCardId:O.id};d(Q),o($.id)}function j(){if(b&&(a==null?void 0:a.id)===i.id){k(i);return}const O={...i,id:s.v4(),title:`${i.title} Copy`,tabTitle:`${i.tabTitle||i.title} Copy`,customCardPreferences:i.customCardPreferences?{...i.customCardPreferences,slotIndex:b?Math.max(-1,...w.map(($,Q)=>s.getSlotIndexForCard($,Q)))+1:i.customCardPreferences.slotIndex}:void 0};I(i,O)}function k(O){var H;if(!V)return;let $=b?"table":"bar",Q="Title",B="";const K=b?Math.max(-1,...w.map((te,z)=>s.getSlotIndexForCard(te,z)))+1:E;if(b&&((H=u==null?void 0:u.slots)!=null&&H.length)){const te=s.getSlotDefinitionForIndex(u.slots,K);te&&($=s.getSlotExpectedChartType(te),Q=te.label||`Tab ${K+1}`,B=te.description||"")}const se={dataSource:O.dataSource,connectionId:O.connectionId,lastSelectedDatabase:O.lastSelectedDatabase,lastSelectedSchema:O.lastSelectedSchema,lastSelectedTable:O.lastSelectedTable,lastSelectedDatamodelId:O.lastSelectedDatamodelId,id:s.v4(),title:Q,tabTitle:Q,description:B,preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:$,sql:"",data:[],mode:"explorer",...b&&{customCardPreferences:{slotIndex:K}}};I(O,se)}function R(O,$){return O.cards.length===1&&($.displayTab===!0||$.displayTab===void 0)||O.activeCardId!==$.id&&($.displayTab===!0||$.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const Q=$.displayTab===void 0?!1:!$.displayTab;c({...$,displayTab:Q}),l({...$,displayTab:Q})},children:$.displayTab===!0||$.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(s.EyeOff,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(s.TabsList,{className:"group ml-2 mr-6 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[r.cards.map((O,$)=>{var H,te;const Q=b?s.getSlotIndexForCard(O,$):-1,B=b&&((H=u==null?void 0:u.slots)!=null&&H.length)&&Q>=0?s.getSlotDefinitionForIndex(u.slots,Q):null,K=B?(Array.isArray(B.expectedType)?B.expectedType[0]:B.expectedType)||"table":O.type,se=b&&((te=u==null?void 0:u.slots)==null?void 0:te.length)&&u.slots.every(z=>typeof z.position=="number"||typeof z.position=="string"&&!z.position.includes("+"));return e.jsxs(s.TabsTrigger,{draggable:!b,onDragStart:b?void 0:z=>v(z,$),onDragOver:b?void 0:D,onDrop:b?void 0:z=>L(z,$),className:"",value:O.id,children:[b&&B?e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:s.getChartIconByType(K,"size-3.5")}),e.jsx("span",{children:B.label||`Tab ${Q+1}`})]})}),e.jsx(s.TooltipContent,{side:"bottom",className:"w-64 p-3 text-left",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium",children:B.label}),B.description&&e.jsx("p",{className:"whitespace-normal break-words text-xs text-muted-foreground",children:B.description}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[B.expectedType&&e.jsx("span",{className:"inline-flex items-center rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground",children:Array.isArray(B.expectedType)?B.expectedType.join(" / "):B.expectedType}),B.required&&e.jsx("span",{className:"inline-flex items-center rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground",children:"Required"})]})]})})]})}):e.jsxs(e.Fragment,{children:[R(r,O),e.jsx(s.Editable,{enabled:r.activeCardId===O.id,text:O.tabTitle||O.title,onSave:z=>{c({...i,tabTitle:z}),l({...i,tabTitle:z})},children:O.tabTitle||O.title},O.id)]}),r.activeCardId===O.id&&!se&&e.jsx(s.CopyPlus,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:z=>{z.stopPropagation(),j()}}),r.activeCardId===O.id&&(T&&(a==null?void 0:a.id)===O.id?r.cards.length>1:A)&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>f(O.id)})]},O.id)}),e.jsx(s.IconButton,{tooltip:"Add Card",className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",onClick:()=>k(i),disabled:!V,children:e.jsx(s.Plus,{className:"h-4 w-4"})}),b&&e.jsxs(s.Toggle,{pressed:t,onPressedChange:n,size:"sm",className:"ml-2 h-8 gap-1 px-2 data-[state=on]:bg-background data-[state=on]:text-foreground","aria-label":"Toggle preview",children:[t?e.jsx(s.EyeOff,{className:"h-4 w-4"}):e.jsx(s.Eye,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Preview"})]})]})})}function nt(){var ke,Oe,Se,be,Ce;const t=s.useEditorStore(ae=>ae.frame),n=s.useEditorStore(ae=>ae.card),[a,r]=C.useState(!1),i=C.useMemo(()=>s.findCustomVisualConfigCard(t,n),[t,n]),d=s.useEditorStore(ae=>ae.isSqlRunning);s.useEditorStore(ae=>ae.isDevMode);const{setFrame:o,setActiveTabCardId:c,setCard:l,setRunSql:x,mergeDraftsIntoCard:p,clearModeDrafts:h,initializeModeDrafts:u}=s.useEditorActions(),[y,b]=C.useState({}),[m,g]=C.useState(()=>new Set),{theme:w}=s.useTheme(),E=s.useDashboardStore(ae=>ae.themeStyle),{authToken:V}=s.useSemaphorContext(),A=s.getTokenParams(V==null?void 0:V.accessToken),T={mode:w||"system",colors:((Oe=(ke=E==null?void 0:E.chart)==null?void 0:ke.dataset)==null?void 0:Oe.backgroundColor)||[]},{getCard:v,manifest:D,isLoading:L}=s.useCustomVisual(((Se=i==null?void 0:i.customCardPreferences)==null?void 0:Se.url)||""),f=(be=i==null?void 0:i.customCardPreferences)==null?void 0:be.componentName,I=f?v(f):null,j=(Ce=D==null?void 0:D.visuals)==null?void 0:Ce.find(ae=>ae.name===f),k=s.resolveMultiInputType(i,j),R=a&&k==="multiple"&&!!i,P=C.useMemo(()=>s.getCustomVisualInputCards({frame:t,configCard:i,isMultiInputVisual:!0}).map(fe=>(fe==null?void 0:fe.id)===n.id?n:fe),[t,i,n]),N=C.useMemo(()=>s.buildSlotOrderedCards(P),[P]),M=C.useMemo(()=>{const ae=P.findIndex(fe=>(fe==null?void 0:fe.id)===n.id);return ae<0?-1:s.getSlotIndexForCard(n,ae)},[P,n]),S=C.useMemo(()=>!i||k!=="multiple"||M<0?n.type:s.getEffectiveCardTypeForSlot(n,M,j==null?void 0:j.slots)??n.type,[i,k,M,n,j==null?void 0:j.slots]),F=C.useMemo(()=>R?{...n,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:S!==n.type?{...n,type:S}:n,[n,S,R]),{data:O,isLoading:$,isFetching:Q,isError:B}=s.useDashboardCardQuery(F),K=C.useCallback((ae,fe)=>{const ge=s.normalizeMultiInputPayload(fe);b(Ie=>({...Ie,[ae]:ge}))},[]),se=C.useCallback((ae,fe)=>{g(ge=>{const Ie=new Set(ge);return fe?Ie.add(ae):Ie.delete(ae),Ie})},[]),H=m.size>0,te=s.useInteractionStore(ae=>ae.interactionStates),z=s.useDashboardStore(ae=>{var fe;return(fe=ae.dashboard)==null?void 0:fe.id}),W=s.useDashboardStore(ae=>ae.dashboard.filters),le=s.useDashboardStore(ae=>ae.filterValues),X=s.useDashboardStore(ae=>ae.selectedSheetId),ne=s.useDashboardStore(ae=>ae.inlineFilterValuesMap[(i==null?void 0:i.id)||""]),ue=C.useMemo(()=>i?s.buildInlineFilterNodes({card:i,sheetId:X||"",inlineFilterValues:ne}):[],[i,X,ne]),{cardFilters:ee,cardFilterValues:Ne}=C.useMemo(()=>i?s.calculateContextAwareFilters({card:i,interactionStates:te,currentDashboardId:z,filters:W,filterValues:le,selectedSheetId:X}):{cardFilters:[],cardFilterValues:[]},[i,te,z,W,le,X]);function q(ae){const fe=t.cards.find(ge=>ge.id===ae);fe&&(p(),Z(ae),c(ae),h(),u(fe))}function Z(ae){const fe=s.useEditorStore.getState().card,ge=s.useEditorStore.getState().frame,Ie={...ge,cards:ge.cards.map(pe=>pe.id===fe.id?fe:pe),activeCardId:ae};o(Ie);const ve=Ie.cards.find(pe=>pe.id===ae);ve.sql&&x(!0),l(ve)}function ie(){if(L)return e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading manifest"})});if(!I)return e.jsx("div",{className:"flex h-full items-center justify-center text-sm text-muted-foreground",children:"Select a component to preview the multi-input visual."});const fe=N.map((ge,Ie)=>s.getEffectiveCardTypeForSlot(ge,Ie,j==null?void 0:j.slots));return e.jsxs("div",{className:"relative flex h-full flex-col pl-2 pr-4",children:[P.map((ge,Ie)=>{if(!ge)return null;const ve=s.getSlotIndexForCard(ge,Ie),pe=s.getEffectiveCardTypeForSlot(ge,ve,j==null?void 0:j.slots);return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:se,onDataChange:K,card:ge,effectiveCardType:pe},`${ge.id}-${ve}`)}),H&&e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/50",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading preview"})}),e.jsx("div",{className:s.cn("flex h-full min-h-0 flex-1 flex-col gap-2",H&&"opacity-50"),children:e.jsx(C.Suspense,{fallback:e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted"})}),children:e.jsx(I,{editing:!0,...s.buildMultiInputCustomVisualProps({configCard:i,slotOrderedCards:N,slotTypes:fe,multiInputData:y,params:A,theme:T,filters:ee,filterValues:[...Ne||[],...ne||[]],inlineFilters:ue})})})})]})}function je(){var ae;return R?ie():n.type==="kpi"?$||Q?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.jsxs("div",{className:"w-1/2 space-y-3",children:[e.jsx("div",{className:"rounded-md border border-border",children:e.jsx(s.KPICard,{card:n,data:O==null?void 0:O.records,isPending:$||Q,isError:B,comparisonMetadata:(ae=O==null?void 0:O.metadata)==null?void 0:ae.comparisonMetadata})}),s.isCardSummaryVisibleOnCard(n)&&e.jsx(s.CardSummary,{card:n,mode:"editor"})]})}):n.type==="text"?$||Q?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:d,card:n,data:O==null?void 0:O.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Da,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:q,value:t.activeCardId,className:"flex grow flex-col gap-2",children:[R?e.jsx("div",{className:"mt-0 grow",children:je()}):t.cards.map(ae=>e.jsx(s.TabsContent,{className:"mt-0 grow focus-visible:ring-0 focus-visible:ring-offset-0",value:ae.id,children:je()},ae.id)),e.jsx(ar,{isPreviewMode:R,onPreviewToggle:r,configCard:i})]})}function oa({children:t,visualAsideControl:n}){var Q;const a=s.useEditorStore(B=>B.frame),r=s.useEditorStore(B=>B.card),i=r.type==="table"||r.type==="detailTable",d=s.useEditorStore(B=>B.isDevMode),o=s.useEditorStore(B=>B.isShowingVisual),c=s.useEditorStore(B=>B.actions.setIsShowingVisual),l=s.useDashboardStore(B=>B.isVisualEditing),{isConsoleMode:x}=s.useDashboardPreferences(),p=s.useEditorStore(B=>B.pythonStdOut),h=s.useEditorStore(B=>B.actions.setRunSql),u=Ae.useEffectiveEditorCardType(),{setFrame:y,setCard:b,setActiveTabCardId:m,setCardPreferences:g,mergeDraftsIntoCard:w,clearModeDrafts:E,initializeModeDrafts:V}=s.useEditorActions(),A=C.useMemo(()=>u!==r.type?{...r,type:u}:r,[r,u]),{data:T,isLoading:v,isFetching:D,errorMessage:L,errorSql:f,refetch:I,pagination:j}=s.useDashboardCardQuery(A),{handleDebugWithAssistant:k}=ka(L,f),R=C.useMemo(()=>(T==null?void 0:T.records)||[],[T==null?void 0:T.records]),[P,N]=C.useState(!1);C.useEffect(()=>{D||N(!1)},[D]),C.useEffect(()=>{i&&!o&&c(!0)},[i,o,c]);function M(B,K){var te,z;const se={...r,paginationConfig:{page:B+1,pageSize:K}};b(se);const H={...a,cards:a.cards.map(W=>W.id===r.id?se:W)};y(H),r.sql&&((z=(te=r.preferences)==null?void 0:te.tablePrefs)!=null&&z.enableDevModePagination)&&h(!0)}function S(B){var te,z,W,le,X;const K=s.sortStateToSortByColumns(B,(te=r.config)==null?void 0:te.metricColumns,(z=r.config)==null?void 0:z.groupByColumns,(W=r.config)==null?void 0:W.detailColumns),se={...r,config:{...r.config||{},sortByColumns:K}};b(se);const H={...a,cards:a.cards.map(ne=>ne.id===r.id?se:ne)};y(H),r.sql&&((X=(le=r.preferences)==null?void 0:le.tablePrefs)!=null&&X.enableDevModePagination)&&h(!0)}function F(){var K;const B=JSON.stringify(T==null?void 0:T.records,null,2);typeof navigator>"u"||!((K=navigator.clipboard)!=null&&K.writeText)||navigator.clipboard.writeText(B).catch(se=>{console.error("Failed to copy JSON",se)})}function O(){const B=JSON.stringify(T==null?void 0:T.records,null,2),K=new Blob([B],{type:"application/json"}),se=URL.createObjectURL(K),H=document.createElement("a");H.href=se,H.download=`${r.title}.json`,H.click()}function $(){const K=[Object.keys(T==null?void 0:T.records.reduce((z,W)=>({...z,...W}),{})).join(","),...((T==null?void 0:T.records)||[]).map(z=>Object.values(z).join(","))].join(`
|
|
187
|
-
`),se=new Blob([K],{type:"text/csv"}),H=URL.createObjectURL(se),te=document.createElement("a");te.href=H,te.download=`${r.title}.csv`,te.click()}return r?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 pl-2 pr-6",children:[o&&e.jsx("div",{className:"flex grow items-center",children:e.jsxs("div",{className:"flex items-center gap-3",children:[(n==null?void 0:n.show)&&e.jsx(s.IconButton,{tooltip:n.isOpen?"Hide Visual Aside":"Show Visual Aside",className:"h-9 w-9 px-0",buttonProps:{variant:"outline"},onClick:n.onToggle,children:n.isOpen?e.jsx(s.ChevronLeft,{className:"size-4"}):e.jsx(s.ChevronRight,{className:"size-4"})}),e.jsx("div",{className:"w-[200px]",children:e.jsx(ot,{variant:d?"secondary":"ghost"})})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[t,e.jsx(s.IconButton,{tooltip:"Refresh",disabled:v||D,onClick:()=>{N(!0),I()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":P})})}),e.jsx(Aa,{showInlineFilters:!1,showDisplayOptions:!1}),(d||x)&&e.jsxs(e.Fragment,{children:[!i&&e.jsx(lr,{}),i&&e.jsx(rr,{})]}),e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"More Options",className:"h-8 w-8 px-0","aria-label":"More options",children:e.jsx(s.EllipsisVertical,{className:"size-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(s.DropdownMenuLabel,{children:"More Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"px-1 py-1",children:[!["table","detailTable","custom"].includes(r.type)&&l&&e.jsx(Wn,{triggerVariant:"menu",className:"w-full"}),e.jsx(ct,{triggerVariant:"menu",className:"w-full"}),e.jsx(it,{triggerVariant:"menu",className:"w-full"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.Button,{variant:"ghost",className:"h-8 w-full justify-start gap-2 px-2 text-sm",onClick:$,children:[e.jsx(s.Download,{className:"h-4 w-4"}),e.jsx("span",{children:"Download CSV"})]}),e.jsxs(s.Button,{variant:"ghost",className:"h-8 w-full justify-start gap-2 px-2 text-sm",onClick:O,children:[e.jsx(on,{className:"h-4 w-4"}),e.jsx("span",{children:"Download JSON"})]}),e.jsxs(s.Button,{variant:"ghost",className:"h-8 w-full justify-start gap-2 px-2 text-sm",onClick:F,children:[e.jsx(s.Copy,{className:"h-4 w-4"}),e.jsx("span",{children:"Copy JSON"})]})]})]})]})]})]}),o?e.jsx(nt,{}):e.jsxs(s.ResizablePanelGroup,{className:"py-2 pl-2 pr-6",direction:"horizontal",children:[p&&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:p&&e.jsx(nr,{})}),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",{"py-2 pl-2 pr-6":p}),children:[(T==null?void 0:T.records)&&(T==null?void 0:T.records.length)>0&&e.jsx(s.TableVisual,{card:r,data:R,comparisonMetadata:(Q=T==null?void 0:T.metadata)==null?void 0:Q.comparisonMetadata,paginationMetadata:j,onPaginationChange:M,onSortChange:S,isLoading:v||D}),L&&e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(lt,{error:L,errorSql:f||r.sql||r.python,onDebugWithAssistant:k,showFeedbackButton:!1})})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function nr(){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 rr(){var d,o,c,l,x,p;const t=s.useEditorStore(h=>h.card),n=s.useEditorStore(h=>h.actions.setCard),a=s.useEditorStore(h=>h.actions.setRunSql),r=s.useEditorStore(h=>h.actions.setCardPreferences),i=s.useEditorStore(h=>h.actions.updateCardInFrame);return t.type!=="table"&&t.type!=="detailTable"?null:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"dev-pagination",checked:((o=(d=t.preferences)==null?void 0:d.tablePrefs)==null?void 0:o.enableDevModePagination)??!1,onCheckedChange:h=>{var u;r({...t.preferences,tablePrefs:{...(u=t.preferences)==null?void 0:u.tablePrefs,enableDevModePagination:h}})}}),e.jsx(s.Label,{htmlFor:"dev-pagination",className:"cursor-pointer text-sm",children:"Paginate"}),((l=(c=t.preferences)==null?void 0:c.tablePrefs)==null?void 0:l.enableDevModePagination)&&e.jsxs(s.Select,{value:String(((p=(x=t.preferences)==null?void 0:x.tablePrefs)==null?void 0:p.pageSize)||50),onValueChange:h=>{var b,m,g;const u=Number(h),y={...t,preferences:{...t.preferences,tablePrefs:{...(b=t.preferences)==null?void 0:b.tablePrefs,pageSize:u}},paginationConfig:{page:1,pageSize:u}};n(y),i(y),t.sql&&((g=(m=t.preferences)==null?void 0:m.tablePrefs)!=null&&g.enableDevModePagination)&&a(!0)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"10",children:"10"}),e.jsx(s.SelectItem,{value:"25",children:"25"}),e.jsx(s.SelectItem,{value:"50",children:"50"}),e.jsx(s.SelectItem,{value:"100",children:"100"}),e.jsx(s.SelectItem,{value:"500",children:"500"}),e.jsx(s.SelectItem,{value:"1000",children:"1000"})]})]})]})}function lr(){const t=s.useEditorStore(a=>a.isShowingVisual),n=s.useEditorStore(a=>a.actions.setIsShowingVisual);return e.jsxs(s.Toggle,{pressed:!t,onPressedChange:a=>{n(!a)},variant:"default",size:"sm",className:"h-8 gap-2 border border-transparent text-foreground/80 hover:bg-accent hover:text-accent-foreground data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",children:[e.jsx(s.Table2,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:"Results"})]})}function Ve({value:t,onCommit:n,type:a="text",placeholder:r,className:i}){const[d,o]=C.useState(t),c=C.useRef(!1);C.useEffect(()=>{o(t)},[t]);const l=()=>{if(c.current){c.current=!1;return}d!==t&&n(d)},x=p=>{if(p.key==="Enter"){p.currentTarget.blur();return}p.key==="Escape"&&(c.current=!0,o(t),p.currentTarget.blur())};return e.jsx(s.Input,{type:a,placeholder:r,value:d,onChange:p=>o(p.target.value),onBlur:l,onKeyDown:x,className:i})}function es({defaultValue:t,label:n,options:a,value:r,onValueChange:i,className:d,icon:o,showPlaceholderLabel:c=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:i,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",d),children:e.jsxs("div",{className:"flex items-center gap-2",children:[o&&e.jsx("span",{children:o}),c&&e.jsx(s.SelectValue,{placeholder:n})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:n}),a.map(l=>e.jsx(s.SelectItem,{value:l.value,children:l.label},l.value))]})})]})}function or(t,n){return s.getSlotDefinitionForIndex(t,n)||null}function ys(t){if(typeof t=="number")return`Tab ${t+1}`;const n=t.match(/^(\d+)-(\d+)$/);if(n){const[,r,i]=n;return`Tabs ${Number(r)+1}-${Number(i)+1}`}const a=t.match(/^(\d+)\+$/);return a?`Tabs ${Number(a[1])+1}+`:`Tab ${t}`}function ir(t){return t?Array.isArray(t)?t:[t]:[]}function Ys(t){var r,i;if(!t)return!1;if(t.type==="text")return!!((r=t.description)!=null&&r.trim());const n=!!((i=t.sql)!=null&&i.trim()),a=s.hasValidCardConfig(t.config);return n||a}function cr({slots:t,cards:n,minInputs:a}){const r=[],i=n.filter(Boolean).length;return a&&i<a&&r.push({type:"too-few-inputs",message:`This visual requires at least ${a} tab${a===1?"":"s"}.`}),!t||t.length===0||(t.forEach(d=>{if(!d.required)return;if(typeof d.position=="number"){const l=n[d.position];Ys(l)||r.push({type:"missing-required",message:`${ys(d.position)} ("${d.label}") is required but has no data configured.`});return}const o=d.position.match(/^(\d+)-(\d+)$/);if(o){const[,l,x]=o.map(Number);for(let p=l;p<=x;p+=1){const h=n[p];if(!Ys(h)){r.push({type:"missing-required",message:`${ys(p)} ("${d.label}") is required but has no data configured.`});break}}return}const c=d.position.match(/^(\d+)\+$/);if(c){const l=Number(c[1]);if(n.length<=l){r.push({type:"missing-required",message:`${ys(l)} ("${d.label}") is required but has no data configured.`});return}for(let x=l;x<n.length;x+=1){const p=n[x];if(!Ys(p)){r.push({type:"missing-required",message:`${ys(x)} ("${d.label}") is required but has no data configured.`});break}}}}),n.forEach((d,o)=>{if(!d)return;const c=or(t,o);if(!c||!c.expectedType)return;const l=ir(c.expectedType);l.length!==0&&(l.includes(d.type)||r.push({type:"wrong-type",message:`${ys(o)} ("${c.label}") expects ${l.join(", ")}, but is configured as ${d.type}.`}))})),r}const dr={table:({children:t})=>e.jsx("table",{className:"my-3 w-full border-collapse overflow-hidden rounded-md border border-border text-sm",children:t}),thead:({children:t})=>e.jsx("thead",{className:"bg-muted",children:t}),th:({children:t})=>e.jsx("th",{className:"border border-border px-3 py-2 text-left font-medium",children:t}),td:({children:t})=>e.jsx("td",{className:"border border-border px-3 py-2",children:t}),code:({children:t,className:n})=>(n==null?void 0:n.includes("language-"))?e.jsx("pre",{className:"my-3 overflow-x-auto rounded-md bg-muted p-3 text-xs",children:e.jsx("code",{children:t})}):e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-xs",children:t}),pre:({children:t})=>e.jsx(e.Fragment,{children:t})};function Ma(){var k,R,P;const t=s.useEditorStore(N=>N.card.customCardPreferences),{data:n}=s.usePluginQuery(),a=(n==null?void 0:n.plugins)||[],r=s.useEditorStore(N=>N.card),i=s.useEditorStore(N=>N.frame),{setCustomCardPreferences:d}=s.useEditorActions(),o=C.useMemo(()=>s.findCustomVisualConfigCard(i,r),[i,r]),c=o==null?void 0:o.customCardPreferences,{components:l,manifest:x}=s.useCustomVisual((c==null?void 0:c.url)||(t==null?void 0:t.url)||""),p=(k=x==null?void 0:x.visuals)==null?void 0:k.find(N=>N.name===((c==null?void 0:c.componentName)||(t==null?void 0:t.componentName))),u=s.resolveMultiInputType(o||r,p)==="multiple",y=!!o&&o.id===r.id,b=(p==null?void 0:p.minInputs)??((R=o==null?void 0:o.customCardPreferences)==null?void 0:R.minInputs),m=(p==null?void 0:p.maxInputs)??((P=o==null?void 0:o.customCardPreferences)==null?void 0:P.maxInputs),g=C.useMemo(()=>s.getCustomVisualInputCards({frame:i,configCard:o||r,isMultiInputVisual:u}),[i,o,r,u]),w=C.useMemo(()=>s.buildSlotOrderedCards(g),[g]),E=C.useMemo(()=>w.map((N,M)=>{if(!N)return null;const S=s.getSlotIndexForCard(N,M),F=s.getEffectiveCardTypeForSlot(N,S,p==null?void 0:p.slots);return{...N,type:F??N.type}}),[w,p==null?void 0:p.slots]),V=C.useMemo(()=>cr({slots:p==null?void 0:p.slots,cards:E,minInputs:b}),[p==null?void 0:p.slots,E,b]),A=C.useMemo(()=>{const N=g.findIndex(M=>(M==null?void 0:M.id)===r.id);return N<0?-1:s.getSlotIndexForCard(r,N)},[g,r]);function T(N){if(typeof N=="number")return`Tab ${N+1}`;const M=N.match(/^(\d+)-(\d+)$/);if(M){const[,F,O]=M;return`Tabs ${Number(F)+1}-${Number(O)+1}`}const S=N.match(/^(\d+)\+$/);return S?`Tabs ${Number(S[1])+1}+`:`Tab ${N}`}function v(N){return N?(Array.isArray(N)?N:[N]).join(", "):null}function D(N,M,S=[],F="",O,$,Q){const B=L({key:M,defaultValue:F,settingsValue:$,sourceCard:Q});return N==="input"?e.jsx(Ve,{className:`h-8 w-full ${s.removeRing}`,value:String(B??""),onCommit:K=>{f({key:M,value:K,settingsField:O,settingsValue:$,sourceCard:Q})}},M):N==="select"?e.jsx(es,{className:"h-8 w-full",label:"",options:S,value:String(B!==void 0?B:F??""),onValueChange:K=>{f({key:M,value:K,settingsField:O,settingsValue:$,sourceCard:Q})}}):null}function L({key:N,defaultValue:M,settingsValue:S,sourceCard:F}){const O=S==null?void 0:S[N];return O!==void 0?O:N==="title"&&(F==null?void 0:F.title)!==void 0?F.title:N==="description"&&(F==null?void 0:F.description)!==void 0?F.description:M}function f({key:N,value:M,settingsField:S,settingsValue:F,sourceCard:O}){const $={...F||{}},Q=N==="title"&&(O==null?void 0:O.title)!==void 0,B=N==="description"&&(O==null?void 0:O.description)!==void 0;Q&&M===String((O==null?void 0:O.title)??"")||B&&M===String((O==null?void 0:O.description)??"")?delete $[N]:$[N]=M,d({...t||{},[S]:$})}function I({settingsSchema:N,settingsField:M,settingsValue:S,sourceCard:F,headerLabel:O}){const $=Object.entries(N||{});return e.jsxs("div",{className:"space-y-3",children:[O&&e.jsx(s.Label,{children:O}),$.map(([Q,B])=>{var K;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:B.title}),((K=B.docs)==null?void 0:K.description)&&e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{className:"text-xs",children:B.docs.description})})]})})]}),D(B.ui,Q,B.options,B.defaultValue,M,S,F)]},Q)})]})}function j(){return e.jsxs(e.Fragment,{children:[u&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Slot Guide"}),e.jsx("div",{className:"space-y-3 rounded-md border border-border bg-muted/40 px-3 py-2 text-xs",children:p!=null&&p.slots&&p.slots.length>0?e.jsx("div",{className:"space-y-3",children:p.slots.map((N,M)=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-foreground",children:[e.jsx("span",{className:"font-medium",children:T(N.position)}),e.jsx("span",{className:"text-muted-foreground",children:"•"}),e.jsx("span",{className:"font-medium",children:N.label})]}),N.description&&e.jsx("p",{className:"text-muted-foreground",children:N.description}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-muted-foreground",children:[v(N.expectedType)&&e.jsxs("span",{children:["Expected: ",v(N.expectedType)]}),N.required&&e.jsx("span",{children:"Required"})]})]},`${N.label}-${M}`))}):e.jsxs("div",{className:"space-y-1 text-muted-foreground",children:[e.jsx("p",{children:"This visual renders all tabs in a flexible layout. Add as many tabs as needed."}),(b||m)&&e.jsxs("p",{children:[b?`Min ${b} tabs`:"",b&&m?" • ":"",m?`Max ${m} tabs`:""]})]})})]}),u&&V.length>0&&e.jsx(s.Alert,{className:"mt-3 border-yellow-500/40 bg-yellow-500/10 text-yellow-900 dark:text-yellow-100",children:e.jsx(s.AlertDescription,{children:e.jsx("ul",{className:"list-disc space-y-1 pl-4 text-xs",children:V.map((N,M)=>e.jsx("li",{children:N.message},`${N.type}-${M}`))})})}),p&&!u&&p.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:I({settingsSchema:p.settings,settingsField:"settings",settingsValue:t==null?void 0:t.settings,sourceCard:r})})}),p&&u&&(p.settings||p.slotSettings)&&e.jsxs("div",{className:"mt-4 space-y-4",children:[y&&p.settings&&e.jsx("div",{className:"px-2",children:I({settingsSchema:p.settings,settingsField:"settings",settingsValue:t==null?void 0:t.settings,sourceCard:o||r,headerLabel:"Global Settings"})}),p.slotSettings&&e.jsx("div",{className:"px-2",children:I({settingsSchema:p.slotSettings,settingsField:"slotSettings",settingsValue:t==null?void 0:t.slotSettings,sourceCard:r,headerLabel:(()=>{const N=r.tabTitle||r.title,M=A>=0?A:0,S=y?"Slot 0":`Slot ${M}`;return N?`${S}: ${N} Settings`:`${S} Settings`})()})})]})]})}return e.jsxs(s.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"",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:[(!u||y)&&e.jsx(es,{icon:e.jsx(va,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:a,value:(c==null?void 0:c.url)||"",onValueChange:N=>d({...t||{url:"",componentName:""},url:N})}),u&&!y&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Switch to the config tab to change the plugin or component."})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&(!u||y)&&e.jsx(e.Fragment,{children:l&&e.jsx(es,{icon:e.jsx(ln,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(l==null?void 0:l.map(N=>({value:N.name,label:N.name})))||[],value:t.componentName||"",onValueChange:N=>{var F;const M=(F=x==null?void 0:x.visuals)==null?void 0:F.find(O=>O.name===N),S=l==null?void 0:l.find(O=>O.name===N);d({...t,componentName:N,visualType:(M==null?void 0:M.visualType)||(S==null?void 0:S.type)||"single",minInputs:M==null?void 0:M.minInputs,maxInputs:M==null?void 0:M.maxInputs,pluginChartType:M==null?void 0:M.chartType})}})})]})})]}),((c==null?void 0:c.componentName)||(t==null?void 0:t.componentName))&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:(p==null?void 0:p.name)||"Settings"}),(p==null?void 0:p.docs)&&e.jsxs(s.HoverCard,{openDelay:0,closeDelay:100,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,onClick:N=>N.stopPropagation(),children:e.jsx(s.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground transition-colors hover:text-foreground"})}),e.jsx(s.HoverCardContent,{side:"right",align:"start",className:"max-h-[40vh] w-[500px] overflow-y-auto text-left",children:e.jsxs("div",{className:"space-y-4 text-left",children:[p.docs.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:p.docs.description}),p.docs.dataSchema&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Data Schema"}),e.jsx("div",{className:"prose prose-sm dark:prose-invert prose-pre:bg-muted prose-pre:text-xs max-w-none",children:e.jsx(s.Markdown,{remarkPlugins:[s.remarkGfm],components:dr,children:p.docs.dataSchema})})]}),(()=>{var M;const N=(M=p.docs)==null?void 0:M.useCases;return!N||N.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Use Cases"}),e.jsx("ul",{className:"space-y-1 text-sm",children:N.map((S,F)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1 text-primary",children:"•"}),e.jsx("span",{children:S})]},F))})]})})()]})})]})]})}),e.jsx(s.AccordionContent,{children:j()})]})]})}function ur({colorRanges:t,setColorRanges:n}){const a={start:-1/0,end:100,color:""};function r(o,c,l){const x=[...t];x[o]={...x[o],[c]:l},n(x)}function i(o){const c=[...t];c.splice(o,1),n(c)}function d(){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:d,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((o,c)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input,{onChange:l=>r(c,"start",l.target.value),value:o.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input,{value:o.end,onChange:l=>r(c,"end",l.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input,{onChange:l=>r(c,"color",l.target.value),value:o.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:()=>i(c),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},c))]})}function mr(){var p,h,u,y,b;const t=s.useEditorStore(m=>m.card.preferences),n=s.useEditorStore(m=>m.actions.setCardPreferences),a=s.useEditorStore(m=>m.card),r=s.hasValidCardConfig(a.config),i=s.useEditorStore(m=>m.actions.setNumberFormat);s.useEditorStore(m=>{var g,w;return(w=(g=m.card.preferences)==null?void 0:g.formatNumber)==null?void 0:w.decimalPlaces});const d=s.useEditorStore(m=>{var g,w;return(w=(g=m.card.preferences)==null?void 0:g.formatNumber)==null?void 0:w.locale}),o=s.useEditorStore(m=>{var g,w;return(w=(g=m.card.preferences)==null?void 0:g.formatNumber)==null?void 0:w.currency});s.useEditorStore(m=>m.actions.setFilterOnClickField);const c=s.useEditorStore(m=>{var g,w;return(w=(g=m.card.preferences)==null?void 0:g.formatNumber)==null?void 0:w.colorRanges})||[],l=s.useEditorStore(m=>m.actions.setColorRanges),x=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(m=>m.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(s.Checkbox,{checked:!!((p=t==null?void 0:t.formatNumber)!=null&&p.enabled),onCheckedChange:m=>{n({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:m}})}}),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:d||"none",onValueChange:m=>{var g,w,E;return i(((g=t==null?void 0:t.formatNumber)==null?void 0:g.decimalPlaces)||0,((w=t==null?void 0:t.formatNumber)==null?void 0:w.currency)||"",m,((E=t==null?void 0:t.formatNumber)==null?void 0:E.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(m=>e.jsx(s.SelectItem,{value:m.locale,children:m.locale},m.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:o||"none",onValueChange:m=>{var g,w,E;console.log("currency",m),i(((g=t==null?void 0:t.formatNumber)==null?void 0:g.decimalPlaces)||0,m==="none"?"":m,((w=t==null?void 0:t.formatNumber)==null?void 0:w.locale)||"",((E=t==null?void 0:t.formatNumber)==null?void 0:E.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"),x.map(m=>e.jsx(s.SelectItem,{value:m,children:m},m))]})})]})]})]}),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:((y=(u=t==null?void 0:t.formatNumber)==null?void 0:u.decimalPlaces)==null?void 0:y.toString())||"0",onValueChange:m=>{var g,w,E;return i(Number(m),((g=t==null?void 0:t.formatNumber)==null?void 0:g.currency)||"",((w=t==null?void 0:t.formatNumber)==null?void 0:w.locale)||"",((E=t==null?void 0:t.formatNumber)==null?void 0:E.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(m=>e.jsx(s.SelectItem,{value:m,children:m},m))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Suffix"}),e.jsx(s.Input,{value:((b=t==null?void 0:t.formatNumber)==null?void 0:b.suffix)||"",className:"h-8 font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"K, M, B, %",onChange:m=>{var g,w,E;return i(((g=t==null?void 0:t.formatNumber)==null?void 0:g.decimalPlaces)||0,((w=t==null?void 0:t.formatNumber)==null?void 0:w.currency)||"",((E=t==null?void 0:t.formatNumber)==null?void 0:E.locale)||"",m.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(ur,{colorRanges:c,setColorRanges:l})]})]})}const xr={combo:{label:"Combo Chart",query:"SELECT x-axis, metric-1, metric-2, ... FROM table",fields:[{name:"x-axis",type:"category",description:"dimension"},{name:"metric-1, metric-2",type:"number",description:"can be bar, line, or area"}],description:"Combo charts allow mixing bar and line series with optional dual Y-axis for metrics with different scales.",docsUrl:"https://docs.semaphor.cloud/docs/charts/combo"},area:{label:"Area Chart",query:"SELECT x-axis, y-axis-1, y-axis-2, ... FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., date, city"},{name:"Y-axis",type:"number",description:"e.g., sales, population"}],description:"Area charts display quantitative data with filled areas under the line.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bar-line-area"},stackedArea:{label:"Stacked Area Chart",query:"SELECT x-axis, y-axis-1, y-axis-2, ... FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., date, city"},{name:"Y-axis",type:"number",description:"e.g., sales, population"}],description:"Stacked area charts show how multiple series contribute to a total over time.",docsUrl:"https://docs.semaphor.cloud/docs/charts/stacked"},bar:{label:"Bar Chart",query:"SELECT x-axis, y-axis-1, y-axis-2, ... FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., city, product"},{name:"Y-axis",type:"number",description:"e.g., sales, count"}],description:"Bar charts compare values across categories using horizontal or vertical bars.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bar-line-area"},line:{label:"Line Chart",query:"SELECT x-axis, y-axis-1, y-axis-2, ... FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., date, month"},{name:"Y-axis",type:"number",description:"e.g., revenue, count"}],description:"Line charts show trends over time or continuous data.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bar-line-area"},stackedBar:{label:"Stacked Bar Chart",query:"SELECT x-axis, stack-by, y-axis FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., month"},{name:"Stack-by",type:"category",description:"e.g., product type"},{name:"Y-axis",type:"number",description:"e.g., sales"}],description:"Stacked bar charts show how parts contribute to a whole across categories.",docsUrl:"https://docs.semaphor.cloud/docs/charts/stacked"},stackedLine:{label:"Stacked Line Chart",query:"SELECT x-axis, stack-by, y-axis FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., date"},{name:"Stack-by",type:"category",description:"e.g., region"},{name:"Y-axis",type:"number",description:"e.g., revenue"}],description:"Stacked line charts show cumulative trends over time.",docsUrl:"https://docs.semaphor.cloud/docs/charts/stacked"},pie:{label:"Pie Chart",query:"SELECT label, measure FROM table",fields:[{name:"Label",type:"category",description:"e.g., product, region"},{name:"Measure",type:"number",description:"e.g., sales, count"}],description:"Pie charts show proportions of a whole.",docsUrl:"https://docs.semaphor.cloud/docs/charts/pie-donut-polar"},doughnut:{label:"Doughnut Chart",query:"SELECT label, measure FROM table",fields:[{name:"Label",type:"category",description:"e.g., product, region"},{name:"Measure",type:"number",description:"e.g., sales, count"}],description:"Doughnut charts show proportions with a hollow center.",docsUrl:"https://docs.semaphor.cloud/docs/charts/pie-donut-polar"},polarArea:{label:"Polar Area Chart",query:"SELECT label, measure FROM table",fields:[{name:"Label",type:"category",description:"e.g., skill, metric"},{name:"Measure",type:"number",description:"e.g., score, value"}],description:"Polar area charts compare values using sectors of equal angle but varying radius.",docsUrl:"https://docs.semaphor.cloud/docs/charts/pie-donut-polar"},radar:{label:"Radar Chart",query:"SELECT label, measure FROM table",fields:[{name:"Label",type:"category",description:"e.g., attribute, skill"},{name:"Measure",type:"number",description:"e.g., score, rating"}],description:"Radar charts display multivariate data on axes starting from the same point.",docsUrl:"https://docs.semaphor.cloud/docs/charts/pie-donut-polar"},funnel:{label:"Funnel Chart",query:"SELECT label, measure FROM table",fields:[{name:"Label",type:"category",description:"e.g., stage name"},{name:"Measure",type:"number",description:"e.g., count, value"}],description:"Funnel charts visualize progressive reduction of data through stages.",docsUrl:"https://docs.semaphor.cloud/docs/charts/funnel"},bubble:{label:"Bubble Chart",query:"SELECT label, [group], x-axis, y-axis, radius FROM table",fields:[{name:"Label",type:"category",description:"e.g., city"},{name:"Group",type:"category",description:"e.g., region",optional:!0},{name:"X-axis",type:"number",description:"e.g., population"},{name:"Y-axis",type:"number",description:"e.g., income"},{name:"Radius",type:"number",description:"e.g., area"}],description:"Bubble charts display three dimensions of data using position and size.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bubble"},scatter:{label:"Scatter Chart",query:"SELECT label, [group], x-axis, y-axis FROM table",fields:[{name:"Label",type:"category",description:"e.g., item name"},{name:"Group",type:"category",description:"e.g., type",optional:!0},{name:"X-axis",type:"number",description:"e.g., price"},{name:"Y-axis",type:"number",description:"e.g., quantity"}],description:"Scatter charts show relationships between two numeric variables.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bubble"},tornado:{label:"Tornado Chart",query:"SELECT dimension, cohort, metric FROM table",fields:[{name:"Dimension",type:"category",description:"e.g., age group"},{name:"Cohort",type:"category",description:"e.g., gender"},{name:"Metric",type:"number",description:"e.g., population"}],description:"Tornado charts compare two groups across categories using back-to-back bars.",docsUrl:"https://docs.semaphor.cloud/docs/charts/tornado"},pyramid:{label:"Pyramid Chart",query:"SELECT dimension, cohort, metric FROM table",fields:[{name:"Dimension",type:"category",description:"e.g., age group"},{name:"Cohort",type:"category",description:"e.g., gender"},{name:"Metric",type:"number",description:"e.g., population"}],description:"Population pyramids show age and gender distribution.",docsUrl:"https://docs.semaphor.cloud/docs/charts/tornado"},range:{label:"Range Chart",query:"SELECT y-axis, label, range-from, range-to, range-value FROM table",fields:[{name:"Y-axis",type:"category",description:"e.g., category"},{name:"Label",type:"category",description:"e.g., range name"},{name:"Range-from",type:"number",description:"start value"},{name:"Range-to",type:"number",description:"end value"},{name:"Range-value",type:"number",description:"e.g., midpoint"}],description:"Range charts display data ranges with start and end values.",docsUrl:"https://docs.semaphor.cloud/docs/charts/range"},heatmap:{label:"Heatmap",query:"SELECT x-axis, y-axis, value FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., day"},{name:"Y-axis",type:"category",description:"e.g., hour"},{name:"Value",type:"number",description:"e.g., count, intensity"}],description:"Heatmaps visualize data density using color intensity.",docsUrl:"https://docs.semaphor.cloud/docs/charts/heatmap"},bullet:{label:"Bullet Chart",query:"SELECT label, actual, target, [ranges] FROM table",fields:[{name:"Label",type:"category",description:"e.g., metric name"},{name:"Actual",type:"number",description:"current value"},{name:"Target",type:"number",description:"goal value"},{name:"Ranges",type:"number",description:"threshold values",optional:!0}],description:"Bullet charts compare actual performance against targets.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bullet"},text:{label:"Text Visual",query:"SELECT text FROM table LIMIT 1",fields:[{name:"Text",type:"string",description:"content to display"}],description:"Text visuals display dynamic text content from your data.",docsUrl:"https://docs.semaphor.cloud/docs/charts/text"},kpi:{label:"KPI",query:"SELECT current, previous FROM table",fields:[{name:"Current",type:"number",description:"current value"},{name:"Previous",type:"number",description:"comparison value"}],description:"KPI visuals display key performance indicators with comparison values.",docsUrl:"https://docs.semaphor.cloud/docs/charts/kpi"},map:{label:"Map Chart",query:"SELECT country, value FROM table",fields:[{name:"Country/Region",type:"category",description:"geographic identifier"},{name:"Value",type:"number",description:"e.g., population, sales"}],description:"Map charts visualize geographic data using color intensity.",docsUrl:"https://docs.semaphor.cloud/docs/charts/map"},table:{label:"Table",query:"SELECT column1, column2, ... FROM table",fields:[{name:"Columns",type:"category",description:"any data columns"}],description:"Tables display data in rows and columns.",docsUrl:"https://docs.semaphor.cloud/docs/charts/table"},detailTable:{label:"Detail Table",query:"SELECT column1, column2, ... FROM table ORDER BY column1 DESC",fields:[{name:"Columns",type:"category",description:"columns to display (no aggregation)"}],description:"Detail tables display raw records without aggregation. Ideal for event logs, transaction history, and audit trails.",docsUrl:"https://docs.semaphor.cloud/docs/charts/detail-table"}};function La(t){return xr[t]}function hr({chartType:t,showDocsLink:n=!0}){const a=La(t);return a?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Query Format"}),e.jsx("code",{className:"block rounded-md bg-muted/50 px-3 py-2 font-mono text-xs text-foreground",children:a.query})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Fields"}),e.jsx("div",{className:"rounded-md border",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/50",children:[e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Field"}),e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Type"}),e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Description"})]})}),e.jsx("tbody",{children:a.fields.map((r,i)=>e.jsxs("tr",{className:i<a.fields.length-1?"border-b":"",children:[e.jsxs("td",{className:"px-2.5 py-1.5 font-medium text-foreground",children:[r.name,r.optional&&e.jsx("span",{className:"ml-1 text-muted-foreground",children:"?"})]}),e.jsx("td",{className:"px-2.5 py-1.5 font-mono text-muted-foreground",children:r.type}),e.jsx("td",{className:"px-2.5 py-1.5 text-muted-foreground",children:r.description||"—"})]},r.name))})]})})]}),e.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:a.description}),n&&a.docsUrl&&e.jsxs("a",{href:a.docsUrl,target:"_blank",rel:"noopener noreferrer",onClick:r=>r.stopPropagation(),className:"inline-flex items-center gap-1.5 text-xs font-medium text-primary hover:underline",children:["View documentation",e.jsx(s.ExternalLink,{className:"h-3 w-3"})]})]}):null}function pr({chartType:t}){return La(t)?e.jsxs(s.HoverCard,{openDelay:200,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded bg-muted px-2 py-0.5 font-mono text-[10px] font-semibold uppercase tracking-wider text-muted-foreground transition-colors hover:bg-muted/80 hover:text-foreground",children:"SQL"})}),e.jsx(s.HoverCardContent,{className:"w-80 p-4",side:"left",align:"start",sideOffset:8,children:e.jsx(hr,{chartType:t})})]}):null}function Fs({chartType:t,suffix:n="Configuration"}){return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-medium",children:n}),e.jsx(pr,{chartType:t})]})}function fr(){return e.jsxs("div",{className:"space-y-6 px-6 py-4",children:[e.jsx(Fs,{chartType:"kpi"}),e.jsx("section",{children:e.jsx(mr,{})})]})}function ia({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})]})}function Oa(){const[t,n]=C.useState([]),a=s.useEditorStore(x=>x.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:i}=s.useEditorStore(x=>x.actions),d=s.useEditorStore(x=>x.queryResultColumns);s.useEditorStore(x=>{var p;return(p=x.card.preferences)==null?void 0:p.filterOnClickColumnIndex}),C.useEffect(()=>{d&&n(new Array(d.length).fill(!1))},[d]);function o(x,p){var h,u;p?a!=null&&a.onClickFilter&&((h=a==null?void 0:a.onClickFilter)==null?void 0:h.length)>0?i({...a,onClickFilter:[...a.onClickFilter,{columnIndex:x,expression:""}]}):i({...a,onClickFilter:[{columnIndex:x,expression:""}]}):(i({...a,onClickFilter:(u=a==null?void 0:a.onClickFilter)==null?void 0:u.filter(y=>y.columnIndex!==x)}),n(y=>{const b=[...y];return b[x]=!1,b}))}function c(x,p){var u;const h=(u=a==null?void 0:a.onClickFilter)==null?void 0:u.map(y=>y.columnIndex===x?{...y,expression:p.target.value}:y);i({...a,onClickFilter:h})}function l(x){var p,h,u,y;if(t!=null&&t[x]||(h=(p=a==null?void 0:a.onClickFilter)==null?void 0:p.find(b=>b.columnIndex===x))!=null&&h.expression)return e.jsx(s.Input,{value:(y=(u=a==null?void 0:a.onClickFilter)==null?void 0:u.find(b=>b.columnIndex===x))==null?void 0:y.expression,onChange:b=>c(x,b),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsx("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:d==null?void 0:d.map((x,p)=>{var h,u;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(y=>y.columnIndex===p)),onCheckedChange:y=>o(p,y)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:x}),e.jsx("div",{className:"flex items-center gap-2",children:((u=a==null?void 0:a.onClickFilter)==null?void 0:u.find(y=>y.columnIndex===p))&&e.jsx(s.Pencil,{onClick:()=>{n(y=>{const b=[...y];return b[p]=!y[p],b})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),l(p)]})},x)})})}const gr=[{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"}],jr=["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"],br=jr.map(t=>({label:t,value:t}));function vr(){var l,x,p,h,u,y,b,m,g,w,E,V,A,T,v,D,L,f;const t=s.useEditorStore(I=>I.card),n=(x=(l=t==null?void 0:t.preferences)==null?void 0:l.mapVisualOptions)==null?void 0:x.topoJsonUrl,[a,r]=C.useState(((h=(p=t==null?void 0:t.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:i}=s.useEditorActions(),{data:d}=s.useTopoJson(t),o=Object.keys((d==null?void 0:d.objects)||{}).map(I=>({label:I,value:I}))||[],c=[{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:"space-y-4 px-6 py-4",children:[e.jsx(Fs,{chartType:"map"}),e.jsx(ia,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(es,{className:"h-9",options:c,onValueChange:I=>{console.log("value",I),i({...t.preferences,mapVisualOptions:{topoJsonUrl:I}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(s.Input,{onChange:I=>{r(I.target.value)},onBlur:()=>{var I;console.log("onBlur",a),i({...t.preferences,mapVisualOptions:{...(I=t.preferences)==null?void 0:I.mapVisualOptions,customTopoJsonUrl:a}})},value:a,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),d&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(es,{className:"h-9",options:o,value:((y=(u=t.preferences)==null?void 0:u.mapVisualOptions)==null?void 0:y.objectKey)||"",label:"Map Object",onValueChange:I=>{var j;i({...t.preferences,mapVisualOptions:{...(j=t.preferences)==null?void 0:j.mapVisualOptions,objectKey:I}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(es,{className:"h-9",options:gr,value:((m=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:m.projection)||"",label:"Projection",onValueChange:I=>{var j;i({...t.preferences,mapVisualOptions:{...(j=t.preferences)==null?void 0:j.mapVisualOptions,projection:I}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(es,{className:"h-9",options:br,value:((w=(g=t.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:w.colorScale)||"",label:"Select Color Scale",onValueChange:I=>{var j;i({...t.preferences,mapVisualOptions:{...(j=t.preferences)==null?void 0:j.mapVisualOptions,colorScale:I}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(ia,{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:((V=(E=t.preferences)==null?void 0:E.mapVisualOptions)==null?void 0:V.projectionScale)||1,onChange:I=>{var j;i({...t.preferences,mapVisualOptions:{...(j=t.preferences)==null?void 0:j.mapVisualOptions,projectionScale:Number(I.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((v=(T=(A=t.preferences)==null?void 0:A.mapVisualOptions)==null?void 0:T.projectionOffset)==null?void 0:v[0])||0,onChange:I=>{var j,k,R,P;i({...t.preferences,mapVisualOptions:{...(j=t.preferences)==null?void 0:j.mapVisualOptions,projectionOffset:[Number(I.target.value),((P=(R=(k=t.preferences)==null?void 0:k.mapVisualOptions)==null?void 0:R.projectionOffset)==null?void 0:P[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((f=(L=(D=t.preferences)==null?void 0:D.mapVisualOptions)==null?void 0:L.projectionOffset)==null?void 0:f[1])||0,onChange:I=>{var j,k,R,P;i({...t.preferences,mapVisualOptions:{...(j=t.preferences)==null?void 0:j.mapVisualOptions,projectionOffset:[((P=(R=(k=t.preferences)==null?void 0:k.mapVisualOptions)==null?void 0:R.projectionOffset)==null?void 0:P[0])||0,Number(I.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Oa,{})]})}function Ra({color:t,onColorChange:n,onClose:a}){const[r,i]=C.useState(0),[d,o]=C.useState(100),[c,l]=C.useState(50),[x,p]=C.useState(t);C.useEffect(()=>{const g=ca(t);if(g){const w=da(g.r,g.g,g.b);i(w.h),o(w.s),l(w.l),p(t)}},[t]);const h=g=>{i(g),y(g,d,c)},u=g=>{const w=g.currentTarget.getBoundingClientRect(),E=Math.max(0,Math.min(1,(g.clientX-w.left)/w.width)),V=Math.max(0,Math.min(1,(g.clientY-w.top)/w.height)),A=E*100,T=(1-V)*100;o(A),l(T),y(r,A,T)},y=(g,w,E)=>{const V=Nr(g,w,E),A=yr(V.r,V.g,V.b);p(A)},b=g=>{if(p(g),/^#[0-9A-Fa-f]{6}$/.test(g)){const w=ca(g);if(w){const E=da(w.r,w.g,w.b);i(E.h),o(E.s),l(E.l)}}},m=()=>{/^#[0-9A-Fa-f]{6}$/.test(x)&&(n(x),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:u,onMouseMove:g=>{g.buttons===1&&u(g)},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:`${d}%`,top:`${100-c}%`,backgroundColor:x}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:g=>h(Number(g.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:x,onChange:g=>b(g.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:x}}),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:m,children:"OK"})]})]})}function ca(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 yr(t,n,a){return"#"+((1<<24)+(t<<16)+(n<<8)+a).toString(16).slice(1)}function da(t,n,a){t/=255,n/=255,a/=255;const r=Math.max(t,n,a),i=Math.min(t,n,a);let d=0,o=0;const c=(r+i)/2;if(r!==i){const l=r-i;switch(o=c>.5?l/(2-r-i):l/(r+i),r){case t:d=((n-a)/l+(n<a?6:0))/6;break;case n:d=((a-t)/l+2)/6;break;case a:d=((t-n)/l+4)/6;break}}return{h:Math.round(d*360),s:Math.round(o*100),l:Math.round(c*100)}}function Nr(t,n,a){t/=360,n/=100,a/=100;let r,i,d;if(n===0)r=i=d=a;else{const o=(x,p,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?x+(p-x)*6*h:h<.5?p:h<.6666666666666666?x+(p-x)*(.6666666666666666-h)*6:x),c=a<.5?a*(1+n):a+n-a*n,l=2*a-c;r=o(l,c,t+1/3),i=o(l,c,t),d=o(l,c,t-1/3)}return{r:Math.round(r*255),g:Math.round(i*255),b:Math.round(d*255)}}const ua=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],Cr=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function ss({value:t,onChange:n,label:a}){const[r,i]=C.useState(!1),[d,o]=C.useState(!1),c=()=>{const l=ua.find(x=>x.value===t);return l?l.color:t.startsWith("#")?t:ua[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:i,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:c()},"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:Cr.map(l=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",c()===l?"border-gray-900":"border-transparent"),style:{backgroundColor:l},onClick:()=>{n(l),i(!1)},children:e.jsx("span",{className:"sr-only",children:l})},l))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{o(!0),i(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a})]}),d&&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:()=>o(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Ra,{color:c(),onColorChange:l=>{n(l),o(!1)},onClose:()=>o(!1)})})]})]})}const Sr=["auto","number","currency","percent","scientific","date"],wr=[{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"}],Tr=[{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"}],Er=t=>t.charAt(0).toUpperCase()+t.slice(1);function Ps({formatOptions:t={},onFormatOptionsChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const i=t.type||"auto",d=(c,l)=>{n({...t,[c]:l})},o=()=>i==="currency"?2:i==="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:i,onValueChange:c=>d("type",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Sr.map(c=>e.jsx(s.SelectItem,{value:c,className:"text-xs",children:c==="auto"?"Auto (Default)":Er(c)},c))})]})]}),i!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent"].includes(i)&&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??o(),onChange:c=>d("decimalPlaces",parseInt(c.target.value)||0),className:"h-8 text-xs"})})]}),i==="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:c=>d("currency",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:wr.map(c=>e.jsx(s.SelectItem,{value:c.value,className:"text-xs",children:c.label},c.value))})]})]}),["number","currency"].includes(i)&&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:c=>d("useSuffix",c)})]}),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:c=>d("locale",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Tr.map(c=>e.jsx(s.SelectItem,{value:c.value,className:"text-xs",children:c.label},c.value))})]})]}),i==="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:c=>d("prefix",c.target.value),className:"h-8 text-xs"})})]}),i==="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:c=>d("suffix",c.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(i)&&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:c=>d("negativeInParentheses",c)})]}),i==="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:c=>d("multiplyBy",c.target.value?parseFloat(c.target.value):void 0),className:"h-8 text-xs"})})]}),i==="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:c=>d("dateFormat",c.target.value),className:"h-8 text-xs"})})]})]})]})}function Ir(){const t=s.useDashboardStore(c=>c.dashboard.filters),n=s.useEditorStore(c=>c.frame),{setFrame:a}=s.useEditorActions(),{columns:r}=s.useColumns(),{assignFilter:i}=s.useAssignFilter();function d(c){const l=i(c,"frame");a({...n,filterId:l})}const o=t==null?void 0:t.find(c=>c.id===n.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(kr,{onSelect:d,columns:r}),o&&e.jsx(s.FilterHeader,{filter:o})]})}function kr({columns:t,onSelect:n}){var o;const[a,r]=tt.useState(!1),[i,d]=tt.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:[i?((o=t.find(c=>c.name===i))==null?void 0:o.label)||i:"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 column found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(c=>e.jsxs(s.CommandItem,{value:c.name,onSelect:l=>{const x=l===i?"":l;d(x),r(!1),x&&n(c)},children:[c.label||c.name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",i===c.name?"opacity-100":"opacity-0")})]},c.id))})]})]})})]})}const Dr=[{value:"difference",label:"Difference"},{value:"change",label:"Change (%)"},{value:"change_difference",label:"Change + Difference"},{value:"ratio",label:"Ratio"}],Ar=[{value:"arrow_badge",label:"Arrow + Badge"},{value:"arrow",label:"Arrow Only"},{value:"badge",label:"Badge Only"},{value:"none",label:"None"}];function Mr({cardType:t="table"}){var p,h,u,y,b;const n=s.useEditorStore(m=>m.card),a=s.useEditorStore(m=>{var g;return(g=m.card)==null?void 0:g.preferences}),r=s.useEditorStore(m=>m.actions.setCardPreferences),d=(((p=n.config)==null?void 0:p.metricColumns)||[]).some(m=>m.comparisonType&&m.comparisonType!=="none"),o=((h=a==null?void 0:a.tableVisualOptions)==null?void 0:h.metricComparison)||{},c=m=>{r({...a,tableVisualOptions:{...a==null?void 0:a.tableVisualOptions,metricComparison:{...o,...m}}})},l={increase:((u=o.colors)==null?void 0:u.increase)||"green",decrease:((y=o.colors)==null?void 0:y.decrease)||"red",neutral:((b=o.colors)==null?void 0:b.neutral)||"neutral"},x=m=>{r({...a,allowDownload:m})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsxs(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:[d&&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(Na,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison Settings"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated As"}),e.jsxs(s.Select,{value:o.calculatedAs||"change_difference",onValueChange:m=>c({calculatedAs:m}),children:[e.jsx(s.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Dr.map(m=>e.jsx(s.SelectItem,{value:m.value,className:"text-xs",children:m.label},m.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Number Format"}),e.jsx(Ps,{formatOptions:o.formatOptions||{},onFormatOptionsChange:m=>c({formatOptions:m}),showTitle:!1})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator Style"}),e.jsxs(s.Select,{value:o.indicatorStyle||"arrow_badge",onValueChange:m=>c({indicatorStyle:m}),children:[e.jsx(s.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Ar.map(m=>e.jsx(s.SelectItem,{value:m.value,className:"text-xs",children:m.label},m.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Colors"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{value:l.increase,onChange:m=>c({colors:{...l,increase:m}}),label:"Increase"}),e.jsx(ss,{value:l.decrease,onChange:m=>c({colors:{...l,decrease:m}}),label:"Decrease"}),e.jsx(ss,{value:l.neutral,onChange:m=>c({colors:{...l,neutral:m}}),label:"No Change"})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Lower is Better"}),e.jsx(s.Checkbox,{checked:o.lowerIsBetter||!1,onCheckedChange:m=>c({lowerIsBetter:!!m})})]})]})]}),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(Oa,{}),e.jsx(Ir,{})]})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{onCheckedChange:x,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 Lr(){var r;const t=s.useEditorStore(i=>i.card.preferences),{setCardPreferences:n}=s.useEditorStore(i=>i.actions);function a(i){n({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:i==="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 Or(){return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(Fs,{chartType:"text"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Text Type"}),e.jsx(Lr,{})]})]})}const Rr=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function Fr(){var T,v,D,L,f,I,j,k,R,P;const t=s.useEditorStore(N=>N.card),n=s.useEditorStore(N=>{var M;return(M=N.card)==null?void 0:M.preferences}),a=Ae.useEffectiveEditorCardType(),{setCardPreferences:r,updateCardInFrame:i}=s.useEditorActions(),d=C.useMemo(()=>a!==t.type?{...t,type:a}:t,[t,a]),{data:o}=s.useDashboardCardQuery(d),[c,l]=C.useState({}),[x,p]=C.useState(null),[h,u]=C.useState(null),y=C.useMemo(()=>{var F,O,$,Q,B,K,se;if(!(o!=null&&o.records)||o.records.length===0)return[];const N=a==="stackedBar"||a==="stackedLine",M=a==="bar"||a==="line"||a==="horizontalBar"||a==="bullet"||a==="combo"||a==="area"||a==="stackedArea",S=((F=t==null?void 0:t.config)==null?void 0:F.pivotByColumns)&&t.config.pivotByColumns.length>0;if((N||M)&&S){if(o.pivotSchema&&Array.isArray(o.pivotSchema)){const H=new Set;return o.pivotSchema.forEach(te=>{te.alias&&H.add(te.alias)}),Array.from(H)}if(o.records.length>0){const H=o.records[0],te=Object.keys(H),z=new Set;(O=t==null?void 0:t.config)!=null&&O.groupByColumns&&t.config.groupByColumns.forEach(X=>{z.add(X.label||X.name),z.add(X.alias||X.name)});const W=new Set;return($=t==null?void 0:t.config)!=null&&$.metricColumns&&t.config.metricColumns.forEach(X=>{const ne=X.alias||X.name;W.add(ne),W.add(`${ne}_count`),W.add(`${ne}_sum`),W.add(`${ne}_avg`),W.add(`${ne}_min`),W.add(`${ne}_max`);const ue=X.entityName||X.qualifiedEntityName;ue&&(W.add(`${ue}_${ne}`),W.add(`${ue}_${ne}_count`))}),te.filter(X=>!z.has(X)&&!W.has(X))}}if((M||N)&&!S&&((B=(Q=t==null?void 0:t.config)==null?void 0:Q.metricColumns)!=null&&B.length))return t.config.metricColumns.map(H=>H.alias||H.label||H.name);if((se=(K=t==null?void 0:t.config)==null?void 0:K.groupByColumns)!=null&&se.length){const H=t.config.groupByColumns[0],te=H.label||H.name,z=new Set;return o.records.forEach(W=>{const le=W[te];le!=null&&z.add(String(le))}),Array.from(z)}return[]},[o,(T=t==null?void 0:t.config)==null?void 0:T.groupByColumns,(v=t==null?void 0:t.config)==null?void 0:v.pivotByColumns,(D=t==null?void 0:t.config)==null?void 0:D.metricColumns,t==null?void 0:t.type]),b=C.useMemo(()=>s.getDefaultChartColors(),[]);C.useEffect(()=>{const N={};y.forEach((M,S)=>{N[M]=s.getColorForValue(M,S,n==null?void 0:n.colorConfig)}),l(N)},[y,n==null?void 0:n.colorConfig,b]);const m=(N,M)=>{const S={...c,[N]:M};l(S);const F={...n||{},colorConfig:{segments:S}};r(F);const O={...t,preferences:F};i(O)},g=(N,M)=>{var B;const S=b[M%b.length],{[N]:F,...O}=((B=n==null?void 0:n.colorConfig)==null?void 0:B.segments)||{},$={...n||{},colorConfig:{segments:O}};r($);const Q={...t,preferences:$};i(Q),l(K=>({...K,[N]:S}))};if(!y.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((f=(L=t==null?void 0:t.config)==null?void 0:L.groupByColumns)==null?void 0:f.length)||((j=(I=t==null?void 0:t.config)==null?void 0:I.pivotByColumns)==null?void 0:j.length):(R=(k=t==null?void 0:t.config)==null?void 0:k.groupByColumns)==null?void 0:R.length)||["table","kpi","text","custom","heatmap"].includes(a))return null;const V=()=>{const N={...n||{},colorConfig:{segments:{}}};r(N);const M={...t,preferences:N};i(M);const S={};y.forEach((F,O)=>{S[F]=s.getColorForValue(F,O,void 0)}),l(S)},A=Object.keys(((P=n==null?void 0:n.colorConfig)==null?void 0:P.segments)||{}).length>0;return e.jsxs(s.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pn,{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:A&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:V,children:[e.jsx(Wt,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:y.map((N,M)=>{const S=s.isDefaultColor(c[N],M),F=!S;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:x===N,onOpenChange:O=>p(O?N: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:c[N]}})}),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:b.slice(0,10).map((O,$)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",c[N]===O?"border-gray-900":"border-transparent"),style:{backgroundColor:O},onClick:()=>{m(N,O),p(null)},children:[$===M%b.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:O})]},`default-${$}`))})]}),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:Rr.map((O,$)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",c[N]===O?"border-2 border-gray-900":O==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:O},onClick:()=>{m(N,O),p(null)},children:e.jsx("span",{className:"sr-only",children:O})},`preset-${$}`))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsx("button",{className:"text-sm font-medium text-blue-600 hover:text-blue-700",onClick:()=>{u({value:N,color:c[N]}),p(null)},children:"Custom color"}),!S&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{g(N,M),p(null)},children:[e.jsx(Wt,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:N}),F&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},N)})}),h&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>u(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Ra,{color:h.color,onColorChange:N=>{m(h.value,N),u(null)},onClose:()=>u(null)})})]})]})})]})}function $e({value:t,onSave:n,placeholder:a="",type:r="text",className:i=""}){const[d,o]=C.useState(t??""),[c,l]=C.useState(!1);C.useEffect(()=>{o(t??"")},[t]);const x=()=>{n(d),l(!1)},p=()=>{o(t??""),l(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${i}`,children:[e.jsx(s.Input$1,{placeholder:a,type:r,value:c?d:t??"",onChange:h=>{o(h.target.value),l(!0)},onFocus:()=>l(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&c&&d!==t?x():h.key==="Escape"&&p()},"aria-label":a||"Edit field"}),c&&d!==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:x,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:p,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function Ws({axis:t,label:n,type:a,config:r,onChange:i,defaultTitle:d,hidePosition:o}){var y,b,m,g,w,E,V,A,T,v,D,L,f,I;const c=(j,k)=>{i({...r??{},[j]:k})},l=(j,k)=>{var M,S,F,O;const R=j==="enabled"&&k===!0,P=(M=r==null?void 0:r.name)==null?void 0:M.text,N=R&&!P&&d;i({...r??{},name:{...r==null?void 0:r.name,enabled:j==="enabled"?k:((S=r==null?void 0:r.name)==null?void 0:S.enabled)??!1,text:j==="text"?k:N?d:P,fontSize:j==="fontSize"?k:(F=r==null?void 0:r.name)==null?void 0:F.fontSize,fontWeight:j==="fontWeight"?k:(O=r==null?void 0:r.name)==null?void 0:O.fontWeight}})},x=(j,k)=>{var R,P;i({...r??{},labels:{enabled:j==="enabled"?k:((R=r==null?void 0:r.labels)==null?void 0:R.enabled)??!0,rotation:j==="rotation"?k:(P=r==null?void 0:r.labels)==null?void 0:P.rotation}})},p=(j,k)=>{i({...r??{},scale:{...r==null?void 0:r.scale,[j]:k===""?"auto":Number(k)}})},h=t==="x"?["auto","top","bottom"]:["auto","left","right"],u=["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:j=>c("enabled",j),onClick:j=>j.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 gap-2",children:[e.jsx(s.Checkbox,{id:`${t}-title-enabled`,checked:((y=r==null?void 0:r.name)==null?void 0:y.enabled)??!1,onCheckedChange:j=>l("enabled",j===!0)}),e.jsx(s.Label,{htmlFor:`${t}-title-enabled`,className:"text-xs font-medium cursor-pointer",children:"TITLE"})]}),((b=r==null?void 0:r.name)==null?void 0:b.enabled)&&e.jsxs("div",{className:"space-y-2 pl-6",children:[e.jsx($e,{placeholder:`${n} title`,value:((m=r==null?void 0:r.name)==null?void 0:m.text)||"",onSave:j=>l("text",j),className:""}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Size"}),e.jsx("div",{className:"w-14",children:e.jsx($e,{type:"number",placeholder:"12",value:String(((g=r==null?void 0:r.name)==null?void 0:g.fontSize)||12),onSave:j=>l("fontSize",Number(j)||12),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Weight"}),e.jsxs(s.Select,{value:((w=r==null?void 0:r.name)==null?void 0:w.fontWeight)||"normal",onValueChange:j=>l("fontWeight",j),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:"normal",className:"text-xs",children:"Normal"}),e.jsx(s.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]})]})]})]}),!o&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(s.Select,{value:(r==null?void 0:r.position)||"auto",onValueChange:j=>c("position",j),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:h.map(j=>e.jsx(s.SelectItem,{value:j,className:"text-xs",children:j==="auto"?"Auto (Default)":s.titleCase(j)},j))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(s.SmallSwitch,{checked:((E=r==null?void 0:r.labels)==null?void 0:E.enabled)!==!1,onCheckedChange:j=>x("enabled",j)})]}),((V=r==null?void 0:r.labels)==null?void 0:V.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(((A=r==null?void 0:r.labels)==null?void 0:A.rotation)||"auto"),onValueChange:j=>x("rotation",j==="auto"?"auto":Number(j)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(j=>e.jsx(s.SelectItem,{value:j,className:"text-xs",children:j==="auto"?"Auto (Default)":`${j}°`},j))})]})]})]}),a==="value"&&e.jsx(Ps,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:j=>i({...r,formatOptions:j}),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($e,{type:"number",placeholder:"auto",value:((T=r==null?void 0:r.scale)==null?void 0:T.min)==="auto"||((v=r==null?void 0:r.scale)==null?void 0:v.min)===void 0?"":String(r.scale.min),onSave:j=>p("min",j),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($e,{type:"number",placeholder:"auto",value:((D=r==null?void 0:r.scale)==null?void 0:D.max)==="auto"||((L=r==null?void 0:r.scale)==null?void 0:L.max)===void 0?"":String(r.scale.max),onSave:j=>p("max",j),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($e,{type:"number",placeholder:"auto",value:((f=r==null?void 0:r.scale)==null?void 0:f.stepSize)==="auto"||((I=r==null?void 0:r.scale)==null?void 0:I.stepSize)===void 0?"":String(r.scale.stepSize),onSave:j=>p("stepSize",j),className:""})})]})]})]})]})]})}function Xs(t,n,a){var d,o,c;if(t==="x"){const l=(o=(d=n==null?void 0:n.config)==null?void 0:d.groupByColumns)==null?void 0:o[0];return(l==null?void 0:l.label)||(l==null?void 0:l.name)||""}const r=((c=n==null?void 0:n.config)==null?void 0:c.metricColumns)||[],i=(a==null?void 0:a.datasetOptions)||[];if(t==="y"){const l=r.filter((x,p)=>{const h=i.find(u=>u.idx===p);return!h||h.yAxisId!=="y2"});return l.length===1&&(l[0].label||l[0].name)||""}if(t==="y2"){const l=r.filter((x,p)=>{const h=i.find(u=>u.idx===p);return(h==null?void 0:h.yAxisId)==="y2"});return l.length===1&&(l[0].label||l[0].name)||""}return""}function Pr(){const t=s.useEditorStore(l=>l.card),n=s.useEditorStore(l=>{var x;return(x=l.card)==null?void 0:x.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions(),i=Ae.useEffectiveEditorCardType();if(!t||["tornado","pyramid","kpi","treemap"].includes(i))return null;const d=s.AxisConfigurator.getAxisInfo(i,n);if(!d.hasXAxis&&!d.hasYAxis)return null;const o=(l,x)=>{let p;l==="x"?p="xAxisConfig":l==="y"?p="yAxisConfig":p="secondaryYAxisConfig";const h={...n||{},[p]:x};a(h);const u={...t,preferences:h};r(u)},c=d.hasY2Axis&&i==="combo";return e.jsxs(s.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(at,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Axes"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[d.hasXAxis&&e.jsx(Ws,{axis:"x",label:"X-Axis",type:d.xAxisType,config:s.mergeAxisConfig(s.getDefaultAxisConfig(i,"x"),n==null?void 0:n.xAxisConfig),onChange:l=>o("x",l),defaultTitle:Xs("x",t,n)}),d.hasYAxis&&e.jsx(Ws,{axis:"y",label:c?"Y-Axis (Left)":"Y-Axis",type:d.yAxisType,config:s.mergeAxisConfig(s.getDefaultAxisConfig(i,"y"),n==null?void 0:n.yAxisConfig),onChange:l=>o("y",l),defaultTitle:Xs("y",t,n)}),c&&e.jsx(Ws,{axis:"y2",label:"Y2-Axis (Right)",type:"value",config:s.mergeAxisConfig({enabled:!0,position:"right"},n==null?void 0:n.secondaryYAxisConfig),onChange:l=>o("y2",l),defaultTitle:Xs("y2",t,n),hidePosition:!0})]})})]})}function Vr(){const t=s.useEditorStore(h=>h.card),n=Ae.useEffectiveEditorCardType(),a=s.useEditorStore(h=>{var u,y,b,m;return(m=(b=(y=(u=h.card)==null?void 0:u.preferences)==null?void 0:y.chartOptions)==null?void 0:b.plugins)==null?void 0:m.legend}),{setLegendOptions:r}=s.useEditorActions();if(!t||!s.chartSupportsLegend(n))return null;const i=s.getDefaultLegendConfig(n),d=(i==null?void 0:i.display)??!0,o=(i==null?void 0:i.position)??"top",c=(i==null?void 0:i.align)??"center",l=(h,u)=>{const y={...a,[h]:u};r(y)},x=["top","bottom","left","right"],p=["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(un,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:(a==null?void 0:a.display)??d,onCheckedChange:h=>l("display",h)})]}),((a==null?void 0:a.display)??d)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(a==null?void 0:a.position)||o,onValueChange:h=>l("position",h),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:x.map(h=>e.jsx(s.SelectItem,{value:h,className:"text-xs",children:s.titleCase(h)},h))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(s.Select,{value:(a==null?void 0:a.align)||c,onValueChange:h=>l("align",h),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:p.map(h=>e.jsx(s.SelectItem,{value:h,className:"text-xs",children:s.titleCase(h)},h))})]})]})]})]})})]})}function Br(){var M,S,F,O,$,Q,B,K,se,H,te;const t=s.useEditorStore(z=>z.card),n=Ae.useEffectiveEditorCardType(),a=s.useEditorStore(z=>{var W,le;return(le=(W=z.card)==null?void 0:W.preferences)==null?void 0:le.dataLabelsConfig}),r=s.useEditorStore(z=>{var W;return(W=z.card)==null?void 0:W.preferences}),{setCardPreferences:i,updateCardInFrame:d}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(n))return null;const o=n==="bullet"?((M=r==null?void 0:r.bulletConfig)==null?void 0:M.orientation)??(((S=r==null?void 0:r.chartOptions)==null?void 0:S.indexAxis)==="x"?"vertical":"horizontal"):void 0,c=o!=null?o==="horizontal":((F=r==null?void 0:r.chartOptions)==null?void 0:F.indexAxis)==="y",l=n==="stackedBar"||n==="stackedLine",x=n==="pie"||n==="doughnut"||n==="polarArea"||n==="funnel",p=!x,h=n==="bubble"||n==="scatter",u=($=(O=r==null?void 0:r.chartOptions)==null?void 0:O.plugins)==null?void 0:$.datalabels,y=(u==null?void 0:u.display)!==!1&&((u==null?void 0:u.anchor)||(u==null?void 0:u.align)),b=s.getDefaultDataLabelsConfig(n,t.preferences),m=a??b,g=(b==null?void 0:b.enabled)??y??!1,w=(a==null?void 0:a.enabled)!==void 0?a.enabled:g,E=(z,W)=>{const ne={...b??{},...a??{},[z]:W};z==="enabled"&&(ne.display=W,W&&h&&!ne.position&&(ne.position="bottom")),z==="position"&&h&&(ne.position="bottom");const ue={...t.preferences||{},dataLabelsConfig:ne};i(ue);const ee={...t,preferences:ue};d(ee)},V=(z,W)=>{const le=a??{},ne={...b??{},...le,font:{...le.font||{},[z]:W}},ue={...t.preferences||{},dataLabelsConfig:ne};i(ue);const ee={...t,preferences:ue};d(ee)},A=(z,W)=>{const le=a??{},ne={...b??{},...le,formatOptions:{...le.formatOptions||{},[z]:W}},ue={...t.preferences||{},dataLabelsConfig:ne};i(ue);const ee={...t,preferences:ue};d(ee)},T=()=>{const z=n;return z==="stackedBar"||z==="stackedLine"||z==="pie"||z==="doughnut"?"center":c?"right":"top"},v=n!=="treemap"&&n!=="heatmap",D=n!=="treemap",L=T();let f=[];if(v)if(h)f=["bottom"];else if(l||x)f=["center"];else{const z=c?["center","left","right"]:["center","top","bottom"];f=["auto",...n==="bullet"?z:z.filter(le=>le!==L),"custom"]}const I=()=>s.titleCase(L),j=["center","start","end"],k=["center","start","end","top","bottom"],R=p?["auto","number","currency","percent","none"]:["number","currency","percent","none"],P=[{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"}],N=[{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(Sn,{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:w,onCheckedChange:z=>E("enabled",z)})]}),w&&e.jsxs(e.Fragment,{children:[v&&!l&&!x&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:h?(m==null?void 0:m.position)||"bottom":(m==null?void 0:m.position)||"auto",onValueChange:z=>E("position",z),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:f.map(z=>e.jsx(s.SelectItem,{value:z,className:"text-xs",children:z==="auto"?I():z==="custom"?"Custom (Advanced)":s.titleCase(z)},z))})]})]}),l&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Show Total"}),e.jsx(s.SmallSwitch,{checked:(a==null?void 0:a.showTotal)??!1,onCheckedChange:z=>E("showTotal",z)})]}),(m==null?void 0:m.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:(m==null?void 0:m.anchor)||"center",onValueChange:z=>E("anchor",z),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:j.map(z=>e.jsx(s.SelectItem,{value:z,className:"text-xs",children:s.titleCase(z)},z))})]})]}),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((m==null?void 0:m.align)||"center"),onValueChange:z=>E("align",z),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:k.map(z=>e.jsx(s.SelectItem,{value:z,className:"text-xs",children:s.titleCase(z)},z))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(m==null?void 0:m.format)||(p?"auto":"none"),onValueChange:z=>E("format",z),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:R.map(z=>e.jsx(s.SelectItem,{value:z,className:"text-xs",children:z==="auto"&&p?"Auto (Use Axis)":z==="none"?"None (Raw Value)":s.titleCase(z)},z))})]})]}),(m==null?void 0:m.format)&&!["auto","none"].includes(m.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(m.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($e,{type:"number",placeholder:"0",value:String(((Q=m==null?void 0:m.formatOptions)==null?void 0:Q.decimalPlaces)??(m.format==="currency"?2:m.format==="percent"?1:0)),onSave:z=>A("decimalPlaces",Number(z)),className:""})})]}),m.format==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Currency"}),e.jsxs(s.Select,{value:((B=m==null?void 0:m.formatOptions)==null?void 0:B.currency)||"USD",onValueChange:z=>A("currency",z),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:P.map(z=>e.jsx(s.SelectItem,{value:z.value,className:"text-xs",children:z.label},z.value))})]})]}),["number","currency"].includes(m.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:((K=m==null?void 0:m.formatOptions)==null?void 0:K.useSuffix)??!1,onCheckedChange:z=>A("useSuffix",z)})]}),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:((se=m==null?void 0:m.formatOptions)==null?void 0:se.locale)||"en-US",onValueChange:z=>A("locale",z),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:N.map(z=>e.jsx(s.SelectItem,{value:z.value,className:"text-xs",children:z.label},z.value))})]})]})]}),D&&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($e,{type:"number",placeholder:"12",value:String(((H=m==null?void 0:m.font)==null?void 0:H.size)||12),onSave:z=>V("size",Number(z)),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:((te=m==null?void 0:m.font)==null?void 0:te.weight)||"normal",onValueChange:z=>V("weight",z),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:(m==null?void 0:m.color)==="auto"||!(m!=null&&m.color)?"auto":"custom",onValueChange:z=>{z==="auto"&&E("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($e,{type:"number",placeholder:"0",value:String((m==null?void 0:m.rotation)||0),onSave:z=>E("rotation",Number(z)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}const ma={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%
|
|
188
|
-
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 zr(){var u,y,b,m,g,w,E,V,A,T;const t=s.useEditorStore(v=>v.card),{setCardPreferences:n}=s.useEditorActions(),a=Ae.useEffectiveEditorCardType(),r=((u=t.config)==null?void 0:u.metricColumns)||[],i=((y=t.config)==null?void 0:y.groupByColumns)||[],d=r.length===2&&i.length===0,o=r.some(v=>v.comparisonType&&v.comparisonType!=="none");if(!(a==="kpi"&&(d||o)))return null;const l=((m=(b=t.preferences)==null?void 0:b.kpiVisualOptions)==null?void 0:m.metricComparison)||{},x=v=>{var L;const D={...t.preferences,kpiVisualOptions:{...(L=t.preferences)==null?void 0:L.kpiVisualOptions,metricComparison:{...l,...v}}};n(D)},p=o||l.enabled,h=r.some(v=>v.comparisonType==="previous_period"||v.comparisonType==="same_period_last_year"||v.comparisonType==="start_vs_end");return e.jsxs(s.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Na,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[d&&r.length===2&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(s.SmallSwitch,{id:"enable-comparison",checked:l.enabled||!1,onCheckedChange:v=>x({enabled:v,...v&&!l.calculationType?{calculationType:"difference"}:{}})})]}),p&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Info,{className:"h-3 w-3 cursor-help text-muted-foreground"})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-xs",children:(()=>{const v=l.calculationType||"difference",D=ma[v];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:D==null?void 0:D.label}),e.jsx("p",{children:D==null?void 0:D.description}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Formula:"})," ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-[10px]",children:D==null?void 0:D.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",D==null?void 0:D.example]})]})})()})]})]}),e.jsxs(s.Select,{value:l.calculationType||"difference",onValueChange:v=>x({calculationType:v}),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(ma).map(([v,D])=>e.jsx(s.SelectItem,{value:v,className:"text-xs",children:D.label},v))})]})]}),e.jsx(Ps,{formatOptions:l.formatOptions||{},onFormatOptionsChange:v=>x({formatOptions:v}),showTitle:!0,title:"COMPARISON FORMAT"}),(h||d)&&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"}),d&&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:l.position||"right",onValueChange:v=>x({position:v}),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"right",className:"text-xs",children:"Right"}),e.jsx(s.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(s.SelectItem,{value:"top",className:"text-xs",children:"Top"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-arrow",checked:l.showArrow!==!1,onCheckedChange:v=>x({showArrow:v})}),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:l.showColor!==!1,onCheckedChange:v=>x({showColor:v})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),l.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(ss,{value:((g=l.colorConfig)==null?void 0:g.increase)||"green",onChange:v=>x({colorConfig:{...l.colorConfig,increase:v}}),label:"Primary > Secondary"}),e.jsx(ss,{value:((w=l.colorConfig)==null?void 0:w.decrease)||"red",onChange:v=>x({colorConfig:{...l.colorConfig,decrease:v}}),label:"Primary < Secondary"}),e.jsx(ss,{value:((E=l.colorConfig)==null?void 0:E.noChange)||"neutral",onChange:v=>x({colorConfig:{...l.colorConfig,noChange:v}}),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:l.conditionalLabel||!1,onCheckedChange:v=>x({conditionalLabel:v})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),l.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=l.conditionalLabels)==null?void 0:V.increase)??"Increase",onChange:v=>x({conditionalLabels:{...l.conditionalLabels,increase:v.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:((A=l.conditionalLabels)==null?void 0:A.decrease)??"Decrease",onChange:v=>x({conditionalLabels:{...l.conditionalLabels,decrease:v.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:((T=l.conditionalLabels)==null?void 0:T.noChange)??"No change",onChange:v=>x({conditionalLabels:{...l.conditionalLabels,noChange:v.target.value}}),placeholder:"No change",className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-name",className:"text-xs text-muted-foreground",children:"Previous Label"}),e.jsx(s.Input,{id:"label-name",type:"text",value:l.labelName??"",onChange:v=>x({labelName:v.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function qr(){var d,o;const t=s.useEditorStore(c=>c.card),{setCardPreferences:n}=s.useEditorActions();if(Ae.useEffectiveEditorCardType()!=="kpi")return null;const r=((o=(d=t.preferences)==null?void 0:d.kpiVisualOptions)==null?void 0:o.formatOptions)||{},i=c=>{var x;const l={...t.preferences,kpiVisualOptions:{...(x=t.preferences)==null?void 0:x.kpiVisualOptions,formatOptions:c}};n(l)};return e.jsxs(s.AccordionItem,{value:"kpi-format",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Hash,{className:"h-4 w-4"}),e.jsx("span",{children:"Number Format"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:e.jsx(Ps,{formatOptions:r,onFormatOptionsChange:i,showTitle:!1})})]})}function $r(){var d;const t=s.useEditorStore(o=>{var c;return(c=o.card)==null?void 0:c.type}),n=s.useEditorStore(o=>{var c;return(c=o.card)==null?void 0:c.preferences}),{setCardPreferences:a}=s.useEditorActions();if(t!=="treemap")return null;const r=((d=n==null?void 0:n.chartOptions)==null?void 0:d.treemapColorMode)??"branch",i=o=>{const c={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,treemapColorMode:o}};a(c)};return e.jsxs(s.AccordionItem,{value:"treemap-color-mode",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TbChartTreemap,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Treemap Colors"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:e.jsxs(s.RadioGroup,{value:r,onValueChange:o=>i(o??"branch"),className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:"treemap-color-branch",value:"branch"}),e.jsxs(s.Label,{htmlFor:"treemap-color-branch",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Shade by value (default)"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Keeps parent hue and adjusts lightness based on the node's share within the branch."})]})]}),e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:"treemap-color-category",value:"category"}),e.jsxs(s.Label,{htmlFor:"treemap-color-category",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Single color per category"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Applies the top-level color to all descendants without lightening/darkening."})]})]})]})})]})}const _r=Object.keys(s.HEATMAP_PRESET_PALETTES);function Gr(){const t=s.useEditorStore(u=>u.card),n=s.useEditorStore(u=>{var y;return(y=u.card)==null?void 0:y.preferences}),{setCardPreferences:a}=s.useEditorActions(),r=(t==null?void 0:t.type)==="heatmap",i=(n==null?void 0:n.heatmapConfig)||{},d=i.colorPalette??"green",o=i.legendPosition??"bottom",c=C.useMemo(()=>i.colorRange&&i.colorRange[0]&&i.colorRange[1]?[i.colorRange[0],i.colorRange[1]]:[...s.DEFAULT_HEATMAP_CUSTOM_RANGE],[i.colorRange]),l=u=>{const y={...i,...u};y.colorPalette!=="custom"?delete y.colorRange:(!y.colorRange||!y.colorRange[0]||!y.colorRange[1])&&(y.colorRange=[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]),a({...n||{},heatmapConfig:y})},x=u=>{l({colorPalette:u,colorRange:u==="custom"?i.colorRange??[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},p=(u,y)=>{const b=[...c];b[u]=y,l({colorPalette:"custom",colorRange:b})},h=u=>{l({legendPosition:u})};return r?e.jsxs(s.AccordionItem,{value:"heatmap-color-config",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Grid3x3,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Heatmap Settings"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs(s.RadioGroup,{value:d,onValueChange:u=>x(u??"blue"),className:"space-y-3",children:[_r.map(u=>{const y=s.HEATMAP_PRESET_PALETTES[u];return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:`heatmap-${u}`,value:u}),e.jsxs(s.Label,{htmlFor:`heatmap-${u}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:y.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${y.start}, ${y.end})`}})]})]},u)}),e.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.RadioGroupItem,{id:"heatmap-custom",value:"custom"}),e.jsx(s.Label,{htmlFor:"heatmap-custom",className:"text-sm font-medium",children:"Custom colors"})]}),d==="custom"&&e.jsxs("div",{className:"flex flex-col gap-3 pl-6",children:[e.jsx(ss,{value:c[0],onChange:u=>p(0,u),label:"Start color"}),e.jsx(ss,{value:c[1],onChange:u=>p(1,u),label:"End color"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Color scale position"}),e.jsxs(s.Select,{value:o,onValueChange:u=>h(u??"bottom"),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["top","bottom","left","right"].map(u=>e.jsx(s.SelectItem,{value:u,className:"text-xs",children:u[0].toUpperCase()+u.slice(1)},u))})]})]})]})]}):null}const xa=["poor","satisfactory","good"];function ha(t){if(!t)return;const n={...t};return n.targetMetricKey||delete n.targetMetricKey,n.comparativeMetricKey||delete n.comparativeMetricKey,!n.targetValue&&n.targetValue!==0&&delete n.targetValue,(!n.rangeKeys||Object.keys(n.rangeKeys).length===0)&&delete n.rangeKeys,(!n.ranges||Object.keys(n.ranges).length===0)&&delete n.ranges,(!n.rangeLabels||Object.keys(n.rangeLabels).length===0)&&delete n.rangeLabels,n}function Kr(){var R,P;const t=s.useEditorStore(N=>N.card.preferences),n=s.useEditorStore(N=>N.card),a=s.useEditorStore(N=>N.isDevMode),{setCardPreferences:r,setChartOrientation:i}=s.useEditorActions(),d=C.useMemo(()=>(t==null?void 0:t.bulletConfig)||{},[t==null?void 0:t.bulletConfig]),c=s.hasValidCardConfig(n==null?void 0:n.config)&&!a,[l,x]=C.useState(d.showRanges??!1),[p,h]=C.useState(d.rangesArePercentages??!1),u=d.disableAutoComparative?!1:d.comparativeMetricKey!==void 0||!c,[y,b]=C.useState(u);C.useEffect(()=>{x(d.showRanges??!1)},[d.showRanges]),C.useEffect(()=>{h(d.rangesArePercentages??!1)},[d.rangesArePercentages]);const m=d.targetValue===void 0?"":String(d.targetValue);C.useEffect(()=>{const N=d.disableAutoComparative?!1:d.comparativeMetricKey!==void 0||!c;b(N)},[d.disableAutoComparative,d.comparativeMetricKey,c]);const g=C.useMemo(()=>{var N,M;return((M=(N=n==null?void 0:n.config)==null?void 0:N.metricColumns)==null?void 0:M.map(S=>{const F=S.label||S.name||S.alias||"";return{value:F,label:F}}))||[]},[(R=n==null?void 0:n.config)==null?void 0:R.metricColumns]);C.useEffect(()=>{var B,K;if(!t||g.length===0)return;const N={};let M=!1;const S=(B=g[1])==null?void 0:B.value;!d.targetMetricKey&&S&&(N.targetMetricKey=S,M=!0);const F=(K=g[2])==null?void 0:K.value;!d.comparativeMetricKey&&!d.disableAutoComparative&&F&&(N.comparativeMetricKey=F,M=!0);const O=g.slice(3),$={...d.rangeKeys||{}};let Q=!1;if(xa.forEach((se,H)=>{!$[se]&&O[H]&&($[se]=O[H].value,Q=!0)}),Q&&(N.rangeKeys=$,M=!0,d.showRanges===void 0&&(N.showRanges=!0)),M){const se=ha({...d,...N});r({...t,bulletConfig:se})}},[g,d,t,r]);const w=N=>{const M=ha({...d,...N});r({...t,bulletConfig:M})},E=(N,M)=>{const S={...d.rangeKeys||{},[N]:M.trim()};M.trim()||delete S[N],w({rangeKeys:Object.keys(S).length>0?S:void 0})},V=(N,M)=>{const S=M===""?void 0:Number(M),F={...d.ranges||{}};S===void 0||Number.isNaN(S)?delete F[N]:F[N]=S,w({ranges:Object.keys(F).length?F:void 0})},A=N=>{if(N===""){w({targetValue:void 0});return}const M=Number(N);w({targetValue:Number.isNaN(M)?void 0:M})},T=(N,M)=>{const S=M.trim(),F={...d.rangeLabels||{}};S?F[N]=S:delete F[N],w({rangeLabels:Object.keys(F).length>0?F:void 0})},v=N=>{x(N),w({showRanges:N})},D=N=>{h(N),w({rangesArePercentages:N})},L=d.orientation||(((P=t==null?void 0:t.chartOptions)==null?void 0:P.indexAxis)==="y"?"horizontal":"vertical"),f=N=>{w({orientation:N}),i(N==="horizontal"?"y":"x")},I=[{value:"__none",label:"None"},...g.map(N=>({value:N.value,label:N.label}))],j=I,k=N=>{if(b(N),!N){w({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!c){w({disableAutoComparative:!1});return}if(d.comparativeMetricKey)w({disableAutoComparative:!1});else{const M=g.find(S=>S.value!==d.targetMetricKey);w({comparativeMetricKey:M==null?void 0:M.value,disableAutoComparative:!1})}};return e.jsxs(s.AccordionItem,{value:"bullet-config",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.BulletChartIcon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bullet Chart"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-6 border-t border-border/50 py-4",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"ORIENTATION"}),e.jsxs(s.Select,{value:L,onValueChange:N=>f(N),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"horizontal",className:"text-xs",children:"Horizontal"}),e.jsx(s.SelectItem,{value:"vertical",className:"text-xs",children:"Vertical"})]})]})]}),c&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TARGET METRIC"}),e.jsxs(s.Select,{value:d.targetMetricKey||"__none",onValueChange:N=>w({targetMetricKey:N==="__none"?void 0:N}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select metric"})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"__none",className:"text-xs",children:"None"}),g.map(N=>e.jsx(s.SelectItem,{value:N.value,className:"text-xs",children:N.label},N.value))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"COMPARATIVE METRIC"}),c?e.jsxs(s.Select,{value:d.comparativeMetricKey||"__none",onValueChange:N=>w({comparativeMetricKey:N==="__none"?void 0:N,disableAutoComparative:N==="__none"}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select metric"})}),e.jsx(s.SelectContent,{children:I.map(N=>e.jsx(s.SelectItem,{value:N.value,className:"text-xs",children:N.label},N.value))})]}):e.jsxs("div",{className:"space-y-2 rounded-md border border-border/50 p-3 text-xs",children:[e.jsxs("div",{className:"flex items-center justify-between font-medium",children:[e.jsx("span",{children:"Show comparative"}),e.jsx(s.SmallSwitch,{checked:y,onCheckedChange:N=>k(N)})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Comparative values are auto-detected from the third metric in your results."})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TARGET VALUE (FALLBACK)"}),e.jsx(Ve,{type:"number",className:"h-8 text-xs",value:m,onCommit:A,placeholder:"Optional numeric fallback"})]})]}),e.jsxs("section",{className:"space-y-4 rounded-md border border-border/60 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"QUALITATIVE RANGES"}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:200,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"text-muted-foreground transition-colors hover:text-foreground",children:e.jsx(s.Info,{className:"h-3.5 w-3.5"})})}),e.jsx(s.TooltipContent,{side:"top",children:"Use columns or static values for Poor / Average / Good."})]})})]}),e.jsx("div",{className:"flex items-center gap-2 text-xs font-medium",children:e.jsx(s.SmallSwitch,{checked:l,onCheckedChange:v})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:p,disabled:!l,onChange:N=>D(N.target.checked),className:"h-3.5 w-3.5 accent-primary disabled:opacity-50"}),e.jsx("span",{children:"Use % of value"})]})]}),l&&e.jsx("div",{className:"space-y-3",children:xa.map(N=>{var M,S,F,O,$;return e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-muted/40 p-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[N," LABEL"]}),e.jsx(Ve,{placeholder:`Display label (${N})`,value:((M=d.rangeLabels)==null?void 0:M[N])||"",onCommit:Q=>T(N,Q),className:"h-8 text-xs"})]}),c?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[N," COLUMN"]}),e.jsxs(s.Select,{value:((S=d.rangeKeys)==null?void 0:S[N])||"__none",onValueChange:Q=>{Q==="__none"?E(N,""):E(N,Q)},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select column"})}),e.jsx(s.SelectContent,{children:j.map(Q=>e.jsx(s.SelectItem,{value:Q.value,className:"text-xs",children:Q.label},Q.value))})]})]}):e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[N," COLUMN KEY"]}),e.jsx(Ve,{placeholder:"Column key",value:((F=d.rangeKeys)==null?void 0:F[N])||"",onCommit:Q=>E(N,Q),className:"h-8 text-xs"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[N," VALUE"]}),e.jsx(Ve,{type:"number",placeholder:p?"0.80":"Static value",value:((O=d.ranges)==null?void 0:O[N])===void 0?"":String(($=d.ranges)==null?void 0:$[N]),onCommit:Q=>V(N,Q),className:"h-8 text-xs"})]})]},N)})})]})]})]})}function pa(t){if(!t)return;const n={...t};if(n.xMetricKey||delete n.xMetricKey,n.yMetricKey||delete n.yMetricKey,n.radiusMetricKey||delete n.radiusMetricKey,n.labelKey||delete n.labelKey,n.groupKey||delete n.groupKey,n.enableGrouping===void 0&&delete n.enableGrouping,n.radiusScale||delete n.radiusScale,n.fixedRadius===void 0&&delete n.fixedRadius,n.minRadius===void 0&&delete n.minRadius,n.maxRadius===void 0&&delete n.maxRadius,Object.keys(n).length!==0)return n}function Ur(){var T,v,D,L,f,I,j,k,R,P,N,M;const t=s.useEditorStore(S=>S.card.preferences),n=s.useEditorStore(S=>S.card),a=Ae.useEffectiveEditorCardType(),r=s.useEditorStore(S=>S.isDevMode),{setCardPreferences:i,updateCardInFrame:d}=s.useEditorActions(),o=a==="bubble",c=a==="scatter",l=C.useMemo(()=>(t==null?void 0:t.bubbleScatterConfig)||{},[t==null?void 0:t.bubbleScatterConfig]),p=s.hasValidCardConfig(n==null?void 0:n.config)&&!r,h=C.useMemo(()=>{var S,F;return((F=(S=n==null?void 0:n.config)==null?void 0:S.metricColumns)==null?void 0:F.map(O=>{const $=O.label||O.name||O.alias||"";return{value:$,label:$}}))||[]},[(T=n==null?void 0:n.config)==null?void 0:T.metricColumns]),u=C.useMemo(()=>{var S,F;return((F=(S=n==null?void 0:n.config)==null?void 0:S.groupByColumns)==null?void 0:F.map(O=>{const $=O.label||O.name||O.alias||"";return{value:$,label:$}}))||[]},[(v=n==null?void 0:n.config)==null?void 0:v.groupByColumns]),y=C.useMemo(()=>l.enableGrouping!==void 0?l.enableGrouping:!r&&u.length>=2,[l.enableGrouping,r,u.length]),[b,m]=C.useState(y);C.useEffect(()=>{m(y)},[y]);const g=S=>{const F={...t||{},bubbleScatterConfig:S};i(F),n&&d({...n,preferences:F})},w=S=>{i(S),n&&d({...n,preferences:S})};C.useEffect(()=>{if(!t||h.length===0)return;const S={};let F=!1;if(!l.xMetricKey&&h[0]&&(S.xMetricKey=h[0].value,F=!0),!l.yMetricKey&&h[1]&&(S.yMetricKey=h[1].value,F=!0),o&&!l.radiusMetricKey&&h[2]&&(S.radiusMetricKey=h[2].value,F=!0),!l.labelKey&&u[0]&&(S.labelKey=u[0].value,F=!0),y&&!l.groupKey&&u[1]&&(S.groupKey=u[1].value,S.enableGrouping=!0,F=!0),F){const O=pa({...l,...S});g(O)}},[h,u,l,t,i,o,y]);const E=S=>{const F=pa({...l,...S});g(F)},V=S=>{m(S),E({enableGrouping:S,groupKey:S?l.groupKey:void 0})};if(!o&&!c)return null;const A=o?s.Circle:s.ChartScatter;return e.jsxs(s.AccordionItem,{value:"bubble-scatter-config",children:[e.jsx(s.AccordionTrigger,{className:"py-2 text-sm",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(A,{className:"h-4 w-4"}),e.jsxs("span",{children:[o?"Bubble":"Scatter"," Configuration"]})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-1 pb-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-1 text-xs font-medium text-muted-foreground",children:["Dimensions",e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{children:e.jsx(s.Info,{className:"h-3 w-3"})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{children:"Label identifies each point. Group creates separate series in the legend."})})]})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Label Column"}),p?e.jsxs(s.Select,{value:l.labelKey||"",onValueChange:S=>E({labelKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select label column"})}),e.jsx(s.SelectContent,{children:u.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(Ve,{className:"h-8 text-xs",placeholder:"Column name for labels",value:l.labelKey||"",onCommit:S=>E({labelKey:S})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Group points into series"}),e.jsx(s.SmallSwitch,{checked:b,onCheckedChange:V})]}),b&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Group By"}),p?e.jsxs(s.Select,{value:l.groupKey||"",onValueChange:S=>E({groupKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select group column"})}),e.jsx(s.SelectContent,{children:u.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(Ve,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:l.groupKey||"",onCommit:S=>E({groupKey:S})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Metrics"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"X Axis"}),p?e.jsxs(s.Select,{value:l.xMetricKey||"",onValueChange:S=>E({xMetricKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select X metric"})}),e.jsx(s.SelectContent,{children:h.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(Ve,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:l.xMetricKey||"",onCommit:S=>E({xMetricKey:S})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Y Axis"}),p?e.jsxs(s.Select,{value:l.yMetricKey||"",onValueChange:S=>E({yMetricKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select Y metric"})}),e.jsx(s.SelectContent,{children:h.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(Ve,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:l.yMetricKey||"",onCommit:S=>E({yMetricKey:S})})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Radius"}),p?e.jsxs(s.Select,{value:l.radiusMetricKey||"",onValueChange:S=>E({radiusMetricKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select radius metric"})}),e.jsx(s.SelectContent,{children:h.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(Ve,{className:"h-8 text-xs",placeholder:"Column name for radius",value:l.radiusMetricKey||"",onCommit:S=>E({radiusMetricKey:S})})]})]}),o&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Radius Settings"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Scale Mode"}),e.jsxs(s.Select,{value:l.radiusScale||"sqrt",onValueChange:S=>E({radiusScale:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"sqrt",children:"Square Root (area-proportional)"}),e.jsx(s.SelectItem,{value:"linear",children:"Linear"}),e.jsx(s.SelectItem,{value:"fixed",children:"Fixed Size"})]})]})]}),l.radiusScale!=="fixed"&&e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Min Radius"}),e.jsx(Ve,{className:"h-8 text-xs",type:"number",placeholder:"5",value:((D=l.minRadius)==null?void 0:D.toString())||"",onCommit:S=>E({minRadius:S?Number(S):void 0})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Max Radius"}),e.jsx(Ve,{className:"h-8 text-xs",type:"number",placeholder:"30",value:((L=l.maxRadius)==null?void 0:L.toString())||"",onCommit:S=>E({maxRadius:S?Number(S):void 0})})]})]}),l.radiusScale==="fixed"&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs(s.Label,{className:"text-xs",children:["Fixed Radius: ",l.fixedRadius||10]}),e.jsx(s.Slider,{value:[l.fixedRadius||10],onValueChange:([S])=>E({fixedRadius:S}),min:3,max:30,step:1,className:"py-2"})]})]}),c&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Point Settings"}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(s.Label,{className:"text-xs",children:["Point Size: ",l.fixedRadius||5]}),e.jsx(s.Slider,{value:[l.fixedRadius||5],onValueChange:([S])=>E({fixedRadius:S}),min:2,max:15,step:1,className:"py-2"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Axis Titles"}),e.jsx(s.SmallSwitch,{checked:((I=(f=t==null?void 0:t.xAxisConfig)==null?void 0:f.name)==null?void 0:I.enabled)??!1,onCheckedChange:S=>{var $,Q,B,K;const F=l.xMetricKey||"X Axis",O=l.yMetricKey||"Y Axis";w({...t??{},xAxisConfig:{...t==null?void 0:t.xAxisConfig,name:{enabled:S,text:((Q=($=t==null?void 0:t.xAxisConfig)==null?void 0:$.name)==null?void 0:Q.text)||F}},yAxisConfig:{...t==null?void 0:t.yAxisConfig,name:{enabled:S,text:((K=(B=t==null?void 0:t.yAxisConfig)==null?void 0:B.name)==null?void 0:K.text)||O}}})}})]}),((k=(j=t==null?void 0:t.xAxisConfig)==null?void 0:j.name)==null?void 0:k.enabled)&&e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"X Title"}),e.jsx(Ve,{className:"h-8 text-xs",placeholder:l.xMetricKey||"X Axis",value:((P=(R=t==null?void 0:t.xAxisConfig)==null?void 0:R.name)==null?void 0:P.text)||"",onCommit:S=>{var F;w({...t??{},xAxisConfig:{...t==null?void 0:t.xAxisConfig,name:{...(F=t==null?void 0:t.xAxisConfig)==null?void 0:F.name,enabled:!0,text:S||l.xMetricKey||"X Axis"}}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Y Title"}),e.jsx(Ve,{className:"h-8 text-xs",placeholder:l.yMetricKey||"Y Axis",value:((M=(N=t==null?void 0:t.yAxisConfig)==null?void 0:N.name)==null?void 0:M.text)||"",onCommit:S=>{var F;w({...t??{},yAxisConfig:{...t==null?void 0:t.yAxisConfig,name:{...(F=t==null?void 0:t.yAxisConfig)==null?void 0:F.name,enabled:!0,text:S||l.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const Hr=[{value:"percentOfTotal",label:"% of Total",description:"Each stage shows percentage of the sum of all values"},{value:"percentOfFirst",label:"% of Stage 1",description:"First stage = 100%, others relative to first stage"}];function Jr(){const t=s.useEditorStore(u=>u.card),n=s.useEditorStore(u=>{var y;return(y=u.card)==null?void 0:y.preferences}),{setCardPreferences:a}=s.useEditorActions(),r=(t==null?void 0:t.type)==="funnel",i=(n==null?void 0:n.funnelConfig)||{},d=i.percentMode??"percentOfTotal",o=i.shrinkFraction??1,c=i.labelThreshold??0,l=u=>{const y={...i,...u};a({...n||{},funnelConfig:y})},x=u=>{l({percentMode:u})},p=u=>{l({shrinkFraction:u[0]})},h=u=>{l({labelThreshold:u[0]})};return r?e.jsxs(s.AccordionItem,{value:"funnel-config",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Filter,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Funnel Settings"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"PERCENTAGE MODE"}),e.jsx(s.RadioGroup,{value:d,onValueChange:u=>x(u),className:"space-y-2",children:Hr.map(u=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:`funnel-${u.value}`,value:u.value,className:"mt-0.5"}),e.jsxs(s.Label,{htmlFor:`funnel-${u.value}`,className:"flex flex-col gap-0.5 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.description})]})]},u.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"SEGMENT SHRINK"}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Same Width"}),e.jsx(s.Slider,{value:[o],onValueChange:p,min:0,max:1,step:.1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Full Shrink"})]}),e.jsxs("p",{className:"text-center text-xs text-muted-foreground",children:["Current: ",Math.round(o*100),"%"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"LABEL VISIBILITY THRESHOLD"}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Show All"}),e.jsx(s.Slider,{value:[c],onValueChange:h,min:0,max:25,step:1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Hide Small"})]}),e.jsx("p",{className:"text-center text-xs text-muted-foreground",children:c===0?"Showing all labels":`Hide labels below ${c}%`})]})]})]}):null}function Vs(){const t=s.useEditorStore(d=>d.card),{data:n}=s.useDashboardCardQuery(t),{keys:a}=s.getKeys((n==null?void 0:n.records)||[]),r=a.slice(1).filter(d=>!s.METADATA_KEYS.includes(d));let i=r;if(["stackedBar","stackedLine"].includes(t.type)){const d=s.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:o}=s.getKeys(d);i=o.slice(1)}return{transformedMetricKeys:i,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}const Qr=[{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"}],Yr=[{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)"}],Wr=["center","start","end"],Xr=["center","start","end","top","bottom"];function Bs({config:t,onChange:n,isHorizontal:a=!1,showAutoFormat:r=!0,positionOptions:i,showAppearance:d=!0}){var b,m,g,w,E,V;const o=i??(a?["auto","center","left","right","custom"]:["auto","center","top","bottom","custom"]),c=r?["auto","number","currency","percent","none"]:["number","currency","percent","none"],l=(A,T)=>{const v={...t,[A]:T};n(v)},x=(A,T)=>{const v={...t,font:{...(t==null?void 0:t.font)||{},[A]:T}};n(v)},p=(A,T)=>{const v={...t,formatOptions:{...(t==null?void 0:t.formatOptions)||{},[A]:T}};n(v)},h=()=>a?"Right":"Top",u=t||{},y=u.format||(r?"auto":"number");return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:u.position||"auto",onValueChange:A=>l("position",A),children:[e.jsx(s.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:o.map(A=>e.jsx(s.SelectItem,{value:A,className:"text-xs",children:A==="auto"?h():A==="custom"?"Custom (Advanced)":s.titleCase(A)},A))})]})]}),u.position==="custom"&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Anchor"}),e.jsxs(s.Select,{value:u.anchor||"center",onValueChange:A=>l("anchor",A),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Wr.map(A=>e.jsx(s.SelectItem,{value:A,className:"text-xs",children:s.titleCase(A)},A))})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Align"}),e.jsxs(s.Select,{value:String(u.align||"center"),onValueChange:A=>l("align",A),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Xr.map(A=>e.jsx(s.SelectItem,{value:A,className:"text-xs",children:s.titleCase(A)},A))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Format"}),e.jsxs(s.Select,{value:y,onValueChange:A=>l("format",A),children:[e.jsx(s.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:c.map(A=>e.jsx(s.SelectItem,{value:A,className:"text-xs",children:A==="auto"&&r?"Auto (Use Axis)":A==="none"?"None (Raw Value)":s.titleCase(A)},A))})]})]}),!["auto","none"].includes(y)&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[["number","currency","percent"].includes(y)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Decimals"}),e.jsx("div",{className:"w-16",children:e.jsx($e,{type:"number",placeholder:"0",value:String(((b=u.formatOptions)==null?void 0:b.decimalPlaces)??(y==="currency"?2:y==="percent"?1:0)),onSave:A=>p("decimalPlaces",Number(A)),className:""})})]}),y==="currency"&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Currency"}),e.jsxs(s.Select,{value:((m=u.formatOptions)==null?void 0:m.currency)||"USD",onValueChange:A=>p("currency",A),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Qr.map(A=>e.jsx(s.SelectItem,{value:A.value,className:"text-xs",children:A.label},A.value))})]})]}),["number","currency"].includes(y)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((g=u.formatOptions)==null?void 0:g.useSuffix)??!1,onCheckedChange:A=>p("useSuffix",A)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Locale"}),e.jsxs(s.Select,{value:((w=u.formatOptions)==null?void 0:w.locale)||"en-US",onValueChange:A=>p("locale",A),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Yr.map(A=>e.jsx(s.SelectItem,{value:A.value,className:"text-xs",children:A.label},A.value))})]})]})]}),d&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Appearance"}),e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Size"}),e.jsx("div",{className:"w-16",children:e.jsx($e,{type:"number",placeholder:"12",value:String(((E=u.font)==null?void 0:E.size)||12),onSave:A=>x("size",Number(A)),className:""})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Weight"}),e.jsxs(s.Select,{value:((V=u.font)==null?void 0:V.weight)||"normal",onValueChange:A=>x("weight",A),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-24 text-xs",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 justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Color"}),e.jsxs(s.Select,{value:u.color==="auto"||!u.color?"auto":"custom",onValueChange:A=>{A==="auto"&&l("color","auto")},children:[e.jsx(s.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Contrast)"}),e.jsx(s.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Rotation"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-12",children:e.jsx($e,{type:"number",placeholder:"0",value:String(u.rotation||0),onSave:A=>l("rotation",Number(A)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"°"})]})]})]})]})]})}const Zr=[{type:"bar",icon:s.ChartColumnIncreasing,label:"Bar"},{type:"line",icon:s.ChartLine,label:"Line"}],el=[0,1,2,3,4,5,6,8,10],sl=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],tl=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function al(){return s.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type})!=="combo"?null:e.jsxs(s.AccordionItem,{value:"combo-series",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.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsx(nl,{})})]})}function nl(){const{transformedMetricKeys:t}=Vs();return t.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:t.map((n,a)=>e.jsx(rl,{metricKey:n,idx:a},n))})}function rl({metricKey:t,idx:n}){var w;const[a,r]=C.useState(!1),i=s.useEditorStore(E=>{var V;return(V=E.card)==null?void 0:V.preferences}),d=s.useEditorStore(E=>{var V,A;return(A=(V=E.card)==null?void 0:V.preferences)==null?void 0:A.datasetOptions}),o=d==null?void 0:d.find(E=>E.idx===n),{setCardPreferences:c}=s.useEditorStore(E=>E.actions),l=(o==null?void 0:o.type)||"bar",x=(o==null?void 0:o.yAxisId)||"y",p=((w=o==null?void 0:o.dataLabels)==null?void 0:w.enabled)??!1,h=l==="line"?s.ChartLine:s.ChartColumnIncreasing;function u(E){const V={idx:n,type:l,yAxisId:x,dataLabels:o==null?void 0:o.dataLabels,...E};if(!o)c({...i||{},datasetOptions:[...d||[],V]});else{const A=d==null?void 0:d.map(T=>T.idx===n?{...T,...V}:T);c({...i||{},datasetOptions:A})}}function y(E){u({type:E})}function b(E){u({yAxisId:E})}function m(E){u({dataLabels:{...o==null?void 0:o.dataLabels,enabled:E}})}function g(E){u({dataLabels:E})}return e.jsx(s.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(s.ChevronRight,{className:s.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:t,children:t})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[e.jsxs("span",{className:s.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(h,{className:"h-3 w-3"}),l==="line"?"Line":"Bar"]}),e.jsx("span",{className:s.cn("rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:x==="y2"?"Y2":"Y1"})]})]})}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"flex items-end gap-4",children:[e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Chart Type"}),e.jsx("div",{className:"flex gap-2",children:Zr.map(({type:E,icon:V,label:A})=>{const T=l===E;return e.jsxs("button",{onClick:()=>y(E),className:s.cn("flex items-center gap-2 rounded-md border px-3 py-1.5 text-xs transition-colors",T?"border-primary bg-primary/10 text-primary":"border-border bg-background text-muted-foreground hover:bg-muted"),children:[e.jsx(V,{className:"h-4 w-4"}),e.jsx("span",{children:A})]},E)})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Axis"}),e.jsxs(s.Select,{value:x,onValueChange:E=>b(E),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-20 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"y",className:"text-xs",children:"Y1 (Left)"}),e.jsx(s.SelectItem,{value:"y2",className:"text-xs",children:"Y2 (Right)"})]})]})]})]}),l==="line"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(s.Select,{value:(o==null?void 0:o.lineStyle)||"solid",onValueChange:E=>u({lineStyle:E}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:tl.map(({value:E,label:V})=>e.jsx(s.SelectItem,{value:E,className:"text-xs",children:V},E))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(s.Select,{value:String((o==null?void 0:o.pointRadius)??3),onValueChange:E=>u({pointRadius:Number(E)}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:el.map(E=>e.jsx(s.SelectItem,{value:String(E),className:"text-xs",children:E===0?"None":E},E))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(s.Select,{value:(o==null?void 0:o.pointStyle)||"circle",onValueChange:E=>u({pointStyle:E}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:sl.map(({value:E,label:V})=>e.jsx(s.SelectItem,{value:E,className:"text-xs",children:V},E))})]})]})]})]}),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 text-muted-foreground",children:"Data Labels"}),e.jsx(s.SmallSwitch,{checked:p,onCheckedChange:m})]}),p&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Bs,{config:o==null?void 0:o.dataLabels,onChange:g,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Zs=[{value:"origin",label:"Origin (X-axis)",description:"Fill to the X-axis (y=0)"},{value:"start",label:"Start (Top)",description:"Fill to the top of chart area"},{value:"end",label:"End (Bottom)",description:"Fill to the bottom of chart area"},{value:"-1",label:"Previous Series",description:"Fill to the series below"},{value:"+1",label:"Next Series",description:"Fill to the series above"},{value:"false",label:"No Fill (Line)",description:"Show as line without fill"}],ll=[0,1,2,3,4,5,6,8,10],ol=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],il=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function cl(t){return t==null?"origin":t===!1?"false":t}function dl(){const t=s.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type});return t!=="area"&&t!=="stackedArea"?null:e.jsxs(s.AccordionItem,{value:"area-series",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.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsx(ul,{})})]})}function ul(){const{transformedMetricKeys:t}=Vs();return t.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:t.map((n,a)=>e.jsx(ml,{metricKey:n,idx:a},n))})}function ml({metricKey:t,idx:n}){var m;const[a,r]=C.useState(!1),i=s.useEditorStore(g=>{var w;return(w=g.card)==null?void 0:w.preferences}),d=s.useEditorStore(g=>{var w,E;return(E=(w=g.card)==null?void 0:w.preferences)==null?void 0:E.datasetOptions}),o=d==null?void 0:d.find(g=>g.idx===n),{setCardPreferences:c}=s.useEditorStore(g=>g.actions),l=cl(o==null?void 0:o.fill),x=((m=o==null?void 0:o.dataLabels)==null?void 0:m.enabled)??!1,p=Zs.find(g=>g.value===l)||Zs[0];function h(g){const w={idx:n,fill:l,dataLabels:o==null?void 0:o.dataLabels,...g};if(!o)c({...i||{},datasetOptions:[...d||[],w]});else{const E=d==null?void 0:d.map(V=>V.idx===n?{...V,...w}:V);c({...i||{},datasetOptions:E})}}function u(g){h({fill:g==="false"?!1:g})}function y(g){h({dataLabels:{...o==null?void 0:o.dataLabels,enabled:g}})}function b(g){h({dataLabels:g})}return e.jsx(s.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(s.ChevronRight,{className:s.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:t,children:t})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:e.jsxs("span",{className:s.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(s.ChartArea,{className:"h-3 w-3"}),p.label.split(" ")[0]]})})]})}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Fill Target"}),e.jsxs(s.Select,{value:l,onValueChange:g=>u(g),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Zs.map(g=>e.jsx(s.SelectItem,{value:g.value,className:"text-xs",children:e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{children:g.label})})},g.value))})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(s.Select,{value:(o==null?void 0:o.lineStyle)||"solid",onValueChange:g=>h({lineStyle:g}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:il.map(({value:g,label:w})=>e.jsx(s.SelectItem,{value:g,className:"text-xs",children:w},g))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(s.Select,{value:String((o==null?void 0:o.pointRadius)??3),onValueChange:g=>h({pointRadius:Number(g)}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:ll.map(g=>e.jsx(s.SelectItem,{value:String(g),className:"text-xs",children:g===0?"None":g},g))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(s.Select,{value:(o==null?void 0:o.pointStyle)||"circle",onValueChange:g=>h({pointStyle:g}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:ol.map(({value:g,label:w})=>e.jsx(s.SelectItem,{value:g,className:"text-xs",children:w},g))})]})]})]})]}),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 text-muted-foreground",children:"Data Labels"}),e.jsx(s.SmallSwitch,{checked:x,onCheckedChange:y})]}),x&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Bs,{config:o==null?void 0:o.dataLabels,onChange:b,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const xl=[0,1,2,3,4,5,6,8,10],hl=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],et=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function pl(){return s.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type})!=="line"?null:e.jsxs(s.AccordionItem,{value:"line-series",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.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsx(fl,{})})]})}function fl(){const{transformedMetricKeys:t}=Vs();return t.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:t.map((n,a)=>e.jsx(gl,{metricKey:n,idx:a},n))})}function gl({metricKey:t,idx:n}){var g;const[a,r]=C.useState(!1),i=s.useEditorStore(w=>{var E;return(E=w.card)==null?void 0:E.preferences}),d=s.useEditorStore(w=>{var E,V;return(V=(E=w.card)==null?void 0:E.preferences)==null?void 0:V.datasetOptions}),o=d==null?void 0:d.find(w=>w.idx===n),{setCardPreferences:c}=s.useEditorStore(w=>w.actions),l=(o==null?void 0:o.lineStyle)||"solid",x=(o==null?void 0:o.pointRadius)??3,p=(o==null?void 0:o.pointStyle)||"circle",h=((g=o==null?void 0:o.dataLabels)==null?void 0:g.enabled)??!1,u=et.find(w=>w.value===l)||et[0];function y(w){const E={idx:n,lineStyle:l,pointRadius:x,pointStyle:p,dataLabels:o==null?void 0:o.dataLabels,...w};if(!o)c({...i||{},datasetOptions:[...d||[],E]});else{const V=d==null?void 0:d.map(A=>A.idx===n?{...A,...E}:A);c({...i||{},datasetOptions:V})}}function b(w){y({dataLabels:{...o==null?void 0:o.dataLabels,enabled:w}})}function m(w){y({dataLabels:w})}return e.jsx(s.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(s.ChevronRight,{className:s.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:t,children:t})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:e.jsxs("span",{className:s.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(s.TrendingUp,{className:"h-3 w-3"}),u.label.split(" ")[0]]})})]})}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(s.Select,{value:l,onValueChange:w=>y({lineStyle:w}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:et.map(({value:w,label:E})=>e.jsx(s.SelectItem,{value:w,className:"text-xs",children:E},w))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(s.Select,{value:String(x),onValueChange:w=>y({pointRadius:Number(w)}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:xl.map(w=>e.jsx(s.SelectItem,{value:String(w),className:"text-xs",children:w===0?"None":w},w))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(s.Select,{value:p,onValueChange:w=>y({pointStyle:w}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:hl.map(({value:w,label:E})=>e.jsx(s.SelectItem,{value:w,className:"text-xs",children:E},w))})]})]})]})]}),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 text-muted-foreground",children:"Data Labels"}),e.jsx(s.SmallSwitch,{checked:h,onCheckedChange:b})]}),h&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Bs,{config:o==null?void 0:o.dataLabels,onChange:m,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const jl=[0,2,4,6,8,10,12,16,20];function bl(){const t=s.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type});return!t||!["bar","horizontalBar","stackedBar"].includes(t)?null:e.jsxs(s.AccordionItem,{value:"bar-series",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.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsx(vl,{})})]})}function vl(){const{transformedMetricKeys:t}=Vs();return t.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:t.map((n,a)=>e.jsx(yl,{metricKey:n,idx:a},n))})}function yl({metricKey:t,idx:n}){var b;const[a,r]=C.useState(!1),i=s.useEditorStore(m=>{var g;return(g=m.card)==null?void 0:g.type}),d=s.useEditorStore(m=>{var g;return(g=m.card)==null?void 0:g.preferences}),o=s.useEditorStore(m=>{var g,w;return(w=(g=m.card)==null?void 0:g.preferences)==null?void 0:w.datasetOptions}),c=o==null?void 0:o.find(m=>m.idx===n),{setCardPreferences:l}=s.useEditorStore(m=>m.actions),x=(c==null?void 0:c.borderRadius)??0,p=((b=c==null?void 0:c.dataLabels)==null?void 0:b.enabled)??!1;function h(m){const g={idx:n,borderRadius:x,dataLabels:c==null?void 0:c.dataLabels,...m};if(!c)l({...d||{},datasetOptions:[...o||[],g]});else{const w=o==null?void 0:o.map(E=>E.idx===n?{...E,...g}:E);l({...d||{},datasetOptions:w})}}function u(m){h({dataLabels:{...c==null?void 0:c.dataLabels,enabled:m}})}function y(m){h({dataLabels:m})}return e.jsx(s.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(s.ChevronRight,{className:s.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:t,children:t})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:x>0&&e.jsxs("span",{className:s.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(s.ChartColumn,{className:"h-3 w-3"}),"r:",x]})})]})}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Bar Style"}),e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Corner Radius"}),e.jsxs(s.Select,{value:String(x),onValueChange:m=>h({borderRadius:Number(m)}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:jl.map(m=>e.jsx(s.SelectItem,{value:String(m),className:"text-xs",children:m===0?"None":`${m}px`},m))})]})]})})]}),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 text-muted-foreground",children:"Data Labels"}),e.jsx(s.SmallSwitch,{checked:p,onCheckedChange:u})]}),p&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Bs,{config:c==null?void 0:c.dataLabels,onChange:y,isHorizontal:i==="horizontalBar",showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Nl=[0,1,2,3,4,5,6,8,10],Cl=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],Sl=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function wl(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>{var l;return(l=c.card)==null?void 0:l.preferences}),a=Ae.useEffectiveEditorCardType(),r=n==null?void 0:n.lineStyleConfig,{setCardPreferences:i,updateCardInFrame:d}=s.useEditorActions();if(!t||!["line","area","stackedArea"].includes(a))return null;const o=(c,l)=>{const x={...n||{},lineStyleConfig:{...r,[c]:l}};i(x),d({...t,preferences:x})};return e.jsxs(s.AccordionItem,{value:"line-style",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(yn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Line Style"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Default styles for all series. Override per-series in the Series section."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Line Pattern"}),e.jsxs(s.Select,{value:(r==null?void 0:r.lineStyle)||"solid",onValueChange:c=>o("lineStyle",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Sl.map(({value:c,label:l})=>e.jsx(s.SelectItem,{value:c,className:"text-xs",children:l},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Point Size"}),e.jsxs(s.Select,{value:String((r==null?void 0:r.pointRadius)??3),onValueChange:c=>o("pointRadius",Number(c)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Nl.map(c=>e.jsx(s.SelectItem,{value:String(c),className:"text-xs",children:c===0?"None":c},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Point Shape"}),e.jsxs(s.Select,{value:(r==null?void 0:r.pointStyle)||"circle",onValueChange:c=>o("pointStyle",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Cl.map(({value:c,label:l})=>e.jsx(s.SelectItem,{value:c,className:"text-xs",children:l},c))})]})]})]})})]})}const Tl=[0,2,4,6,8,10,12,16,20],El=[{value:"0.5",label:"50%"},{value:"0.6",label:"60%"},{value:"0.7",label:"70%"},{value:"0.8",label:"80%"},{value:"0.9",label:"90%"},{value:"1",label:"100%"}],Il=[{value:"0.5",label:"50%"},{value:"0.6",label:"60%"},{value:"0.7",label:"70%"},{value:"0.8",label:"80%"},{value:"0.9",label:"90%"},{value:"1",label:"100%"}];function kl(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>{var l;return(l=c.card)==null?void 0:l.preferences}),a=Ae.useEffectiveEditorCardType(),r=n==null?void 0:n.barStyleConfig,{setCardPreferences:i,updateCardInFrame:d}=s.useEditorActions();if(!t||!["bar","horizontalBar","stackedBar"].includes(a))return null;const o=(c,l)=>{const x={...n||{},barStyleConfig:{...r,[c]:l}};i(x),d({...t,preferences:x})};return e.jsxs(s.AccordionItem,{value:"bar-style",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.ChartColumn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bar Style"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Default styles for all bars. Override per-series in the Series section."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Corner Radius"}),e.jsxs(s.Select,{value:String((r==null?void 0:r.borderRadius)??0),onValueChange:c=>o("borderRadius",Number(c)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Tl.map(c=>e.jsx(s.SelectItem,{value:String(c),className:"text-xs",children:c===0?"None":`${c}px`},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Bar Width"}),e.jsxs(s.Select,{value:String((r==null?void 0:r.barPercentage)??.9),onValueChange:c=>o("barPercentage",Number(c)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:El.map(({value:c,label:l})=>e.jsx(s.SelectItem,{value:c,className:"text-xs",children:l},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Category Width"}),e.jsxs(s.Select,{value:String((r==null?void 0:r.categoryPercentage)??.8),onValueChange:c=>o("categoryPercentage",Number(c)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Il.map(({value:c,label:l})=>e.jsx(s.SelectItem,{value:c,className:"text-xs",children:l},c))})]})]})]})})]})}function Dl(){const t=s.useEditorStore(a=>{var r,i;return(i=(r=a==null?void 0:a.card)==null?void 0:r.preferences)==null?void 0:i.sortChart}),{setSortChart:n}=s.useEditorActions();return e.jsxs(s.AccordionItem,{value:"stacked-sort",children:[e.jsx(s.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.ArrowUpDown,{className:"h-4 w-4"}),"Sort"]})}),e.jsx(s.AccordionContent,{className:"space-y-4 px-1",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort Order"}),e.jsx(es,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"Ascending",value:"asc"},{label:"Descending",value:"desc"}],value:t||"none",onValueChange:a=>{n(a)}})]})})]})}const Al=["kpi"],fa={none:"None",previous_period:"Previous Period",same_period_last_year:"Same Period Last Year",start_vs_end:"Start vs End",target:"Target"},st=2;function ls(t){return typeof t=="string"?t.trim().toLowerCase():((t==null?void 0:t.id)||(t==null?void 0:t.qualifiedFieldName)||(t==null?void 0:t.name)||(t==null?void 0:t.label)||"").trim().toLowerCase()}function Ml(t){if(!(t!=null&&t.name)||!(t!=null&&t.dataType)||t.role==="metric")return!1;const n=s.getDataType(t.dataType);return["date","string","boolean"].includes(n)}function Ll(t){return{...t,role:"groupby"}}function Ol(){var E,V,A,T;const t=s.useEditorStore(v=>v.card),n=s.useEditorStore(v=>v.actions.updateCardConfig),a=Ae.useEffectiveEditorCardType(),{scopedFields:r}=s.useScopedFields(),i=((E=t.config)==null?void 0:E.metricColumns)||[],d=((V=t.config)==null?void 0:V.summary)||{},o=d.breakdownDimensions||[],c=Al.includes(a),l=i.length>0,x=d.enabled===!0,p=c&&l,h=((A=t.config)==null?void 0:A.comparisonType)||((T=i.find(v=>v.comparisonType&&v.comparisonType!=="none"))==null?void 0:T.comparisonType)||"none",u=fa[h]||fa.none,y=Array.from(new Map(r.filter(Ml).map(v=>[ls(v),Ll(v)])).values()),b=new Set(y.map(v=>ls(v))),m=new Set(o.map(v=>ls(v)).filter(v=>v&&b.has(v)));if(!c)return null;const g=v=>{n(t.id,{summary:{...d,...v}})},w=(v,D)=>{const L=ls(v),f=y.filter(j=>m.has(ls(j))),I=D?m.has(L)?f:[...f,v].slice(0,st):f.filter(j=>ls(j)!==L);g({breakdownDimensions:I})};return e.jsxs(s.AccordionItem,{value:"summary",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.FileText,{className:"h-4 w-4"}),e.jsx("span",{children:"Summary"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{htmlFor:"summary-enabled",className:"text-xs",children:"Enable Summary"}),!l&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Add at least one metric to enable summary."})]}),e.jsx(s.SmallSwitch,{id:"summary-enabled",checked:x,disabled:!p,onCheckedChange:v=>{if(!v){g({enabled:!1,showOnCard:!1,includeInDashboardSummary:!1});return}g({enabled:!0,showOnCard:d.showOnCard??!0,includeInDashboardSummary:d.includeInDashboardSummary??!0,anomalyEnabled:d.anomalyEnabled??!0})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Comparison"}),e.jsxs("p",{className:"rounded-md border border-border bg-muted/40 px-2 py-1.5 text-xs",children:["Using: ",u]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Comparison is configured from card/metric comparison settings."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"summary-show-on-card",className:"text-xs",children:"Show summary on card"}),e.jsx(s.SmallSwitch,{id:"summary-show-on-card",checked:d.showOnCard===!0,disabled:!x,onCheckedChange:v=>g({showOnCard:v})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"summary-include-rollup",className:"text-xs",children:"Include in dashboard summary"}),e.jsx(s.SmallSwitch,{id:"summary-include-rollup",checked:d.includeInDashboardSummary===!0,disabled:!x,onCheckedChange:v=>g({includeInDashboardSummary:v})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Breakdown Dimensions"}),e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[o.length,"/",st]})]}),y.length===0?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"No dimension fields available for breakdown."}):e.jsx("div",{className:"max-h-40 space-y-2 overflow-y-auto rounded-md border border-border p-2",children:y.map(v=>{const D=ls(v),L=m.has(D),f=m.size>=st,I=!x||!L&&f;return e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx(s.Checkbox,{id:`summary-breakdown-${D}`,checked:L,disabled:I,onCheckedChange:j=>w(v,j===!0)}),e.jsx(s.Label,{htmlFor:`summary-breakdown-${D}`,className:"cursor-pointer text-xs",children:v.label||v.name})]},D)})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"summary-anomaly",className:"text-xs",children:"Detect anomalies"}),e.jsx(s.SmallSwitch,{id:"summary-anomaly",checked:d.anomalyEnabled!==!1,disabled:!x,onCheckedChange:v=>g({anomalyEnabled:v})})]})]})]})}function Fa({mode:t}){const n=s.useEditorStore(a=>{var r;return(r=a.card)==null?void 0:r.type});return e.jsxs(e.Fragment,{children:[n==="combo"&&e.jsx(al,{}),(n==="area"||n==="stackedArea")&&e.jsx(dl,{}),n==="line"&&e.jsx(pl,{}),(n==="bar"||n==="horizontalBar"||n==="stackedBar")&&e.jsx(bl,{}),e.jsx(wl,{}),e.jsx(kl,{}),e.jsx($r,{}),t==="config"&&e.jsx(qr,{}),t==="config"&&e.jsx(zr,{}),t==="config"&&e.jsx(Ol,{}),e.jsx(Gr,{}),n==="bullet"&&e.jsx(Kr,{}),n==="funnel"&&e.jsx(Jr,{}),(n==="bubble"||n==="scatter")&&e.jsx(Ur,{}),(n==="stackedBar"||n==="stackedLine")&&e.jsx(Dl,{}),e.jsx(Fr,{}),e.jsx(Pr,{}),e.jsx(Vr,{}),e.jsx(Br,{})]})}function Rl(){const t=s.useEditorStore(a=>a.card),n=t==null?void 0:t.type;return n?e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(Fs,{chartType:n}),e.jsx(s.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:e.jsx(Fa,{mode:"dev"})})]}):null}function Fl(){const t=s.useEditorStore(a=>a.card.type);function n(){switch(t){case"kpi":return e.jsx(fr,{});case"table":return e.jsx(Mr,{});case"map":return e.jsx(vr,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(Ma,{})});case"text":return e.jsx(Or,{});default:return e.jsx(Rl,{})}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[n(),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Pl(){const t=C.useRef(null),n=C.useRef(null),a=s.useEditorStore(h=>h.isShowingVisual),r=s.useEditorStore(h=>h.isDevMode),i=s.useEditorStore(h=>h.showAIDialog),[d,o]=C.useState(!1),c=a&&!i,l=c&&(!r||d),x=r&&c,p=()=>o(h=>!h);return C.useEffect(()=>{var h,u,y,b;i?((h=t.current)==null||h.resize(0),(u=n.current)==null||u.resize(0)):((y=t.current)==null||y.resize(25),(b=n.current)==null||b.resize(25))},[i]),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(Kn,{})}),e.jsx(s.ResizableHandle,{withHandle:!0,className:"data-[panel-group-direction=vertical]:ml-2 data-[panel-group-direction=vertical]:mr-6 data-[panel-group-direction=vertical]:w-auto"}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:l?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(Fl,{})})}),!i&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(oa,{visualAsideControl:x?{show:!0,isOpen:d,onToggle:p}:void 0})})]}):e.jsx(oa,{visualAsideControl:x?{show:!0,isOpen:d,onToggle:p}:void 0})})]})}function Vl(t){var Ne;s.useAIInteractionStore(q=>q.currentAIContext);const[n,a]=C.useState(""),[r,i]=C.useState(null),{authToken:d,tokenProps:o}=s.useSemaphorContext(),c=s.useEditorStore(q=>{var Z;return(Z=q==null?void 0:q.card)==null?void 0:Z.sql}),l=s.useEditorStore(q=>q.isDevMode),x=s.useEditorStore(q=>{var Z;return(Z=q==null?void 0:q.card)==null?void 0:Z.python}),{setCardPython:p,setCardSql:h,setRunSql:u,switchCardType:y,setQueryConfig:b}=s.useEditorActions(),m=s.useEditorStore(q=>q.currentAssitantScope)||[],g=s.useEditorStore(q=>q.userInputForAI),w=s.useEditorStore(q=>q.triggerAIRun),E=s.useEditorStore(q=>q.card),V=s.useEditorStore(q=>q.selectedDatabaseName),A=s.useEditorStore(q=>q.selectedTableName),T=s.useEditorStore(q=>q.selectedConnectionId),v=s.useEditorStore(q=>q.selectedSchemaName),D=s.useDashboardStore(q=>q.dashboard.aiScopeTables),{errorMessage:L,refetch:f,data:I}=s.useDashboardCardQuery(E),{setTriggerAIRun:j,setCurrentAssitantScope:k,setCardConfig:R}=s.useEditorActions(),{selectedDatamodelName:P,connectionType:N,selectedDatamodelId:M}=s.useEditorAside(),S=(Ne=s.useDashboardQuery().data)==null?void 0:Ne.assistantProfileId,{messages:F,setMessages:O,regenerate:$,error:Q,sendMessage:B,status:K,addToolResult:se,stop:H,clearError:te}=s.useChat({transport:new s.DefaultChatTransport({api:`${o.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${d==null?void 0:d.accessToken}`}),body:()=>{const q=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:S,isDevMode:l,aiContext:q.currentAIContext,reasoningEffort:q.reasoningEffort,showReasoning:q.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:q,body:Z})=>({body:{...Z,messages:s.cleanupIncompleteMessages(q)}})}),onError:q=>{var Z;if(q.name==="AbortError"||(Z=q.message)!=null&&Z.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)");return}console.error("[Editor Assistant] Stream error:",q)},onToolCall:z,onFinish({isAbort:q,isDisconnect:Z,isError:ie}){a(""),console.log(q?"[Editor Assistant] Stream aborted by user":Z?"[Editor Assistant] Stream disconnected (network error)":ie?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully")}});C.useEffect(()=>{w&&g&&(B({role:"user",parts:[{type:"text",text:g}]}),j(!1))},[w,g,B,j]);async function z({toolCall:q}){var Z,ie,je,ke,Oe,Se,be,Ce,ae,fe,ge,Ie,ve,pe,Re,Qe;if(["createChartFromSql","createForecast"].includes(q.toolName)){const Ke=((Z=q.input)==null?void 0:Z.sql)??((ie=q.args)==null?void 0:ie.sql),oe=((je=q.input)==null?void 0:je.python)??((ke=q.args)==null?void 0:ke.python),me=((Oe=q.input)==null?void 0:Oe.chartType)??((Se=q.args)==null?void 0:Se.chartType);y(me),h(Ke),p(oe),u(!0),se({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(q.toolName==="getUserSql"){if(!c){se({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"error",message:"No SQL found"}});return}se({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",sql:c,python:x||""}})}else if(q.toolName==="generateQueryConfig"){a("Generating query config...");const Ke=((be=q.input)==null?void 0:be.chartType)??((Ce=q.args)==null?void 0:Ce.chartType),oe=((ae=q.input)==null?void 0:ae.queryConfig)??((fe=q.args)==null?void 0:fe.queryConfig);((ge=q.input)==null?void 0:ge.cardConfig)??((Ie=q.args)==null||Ie.cardConfig),y(Ke),R(oe),h(void 0),p(void 0);const me=await f();if((ve=me==null?void 0:me.data)!=null&&ve.error){se({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"error",queryConfig:oe,message:(pe=me==null?void 0:me.data)==null?void 0:pe.error.message}});return}if((Re=me==null?void 0:me.data)!=null&&Re.records){se({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",queryConfig:oe,message:"The data has been visualized"}});return}se({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",queryConfig:oe,message:"The data has been visualized",records:(Qe=me==null?void 0:me.data)==null?void 0:Qe.records}})}else a("Analyzing...")}function W(q){const Z=s.removeFromScopeArray(m,q);le(Z)}function le(q){const Z=s.sanitizeAIScope(q);k(Z),O(ie=>[...ie,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(Z)}`}]}])}function X(){const q={databaseName:V||"",schemaName:v||"",tableName:A||"",datamodelId:M||"",datamodelName:s.resolveDatamodelName(P),connectionId:T||"",connectionType:N||""},Z=s.dedup([...m,q]);le(Z)}function ne(){const q={databaseName:V||"",schemaName:v||"",tableName:A||"",datamodelName:s.resolveDatamodelName(P),connectionId:T||"",connectionType:N||"",datamodelId:M||""};if(!s.isInAiScopeArray([...D||[],...m],q)||m.length===0){const ie=s.dedup([...D||[],...m,q]).filter(je=>je.connectionId===q.connectionId);le(ie)}}const ue=!["ready","error"].includes(K),ee=s.getErrorMessage(Q);return{messages:F,setMessages:O,sendMessage:B,regenerate:$,isLoading:ue,handleSetAIScope:ne,handleAddCurrentTableToScope:X,removeFromCurrentSelections:W,currentAssitantScope:m,setCurrentAssitantScope:k,stop:H,status:K,toolStatus:n,llmUsage:r,onFinish:t,errorMessage:ee,clearError:te}}const Bl=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function ga({isFullscreen:t,onFullscreenChange:n,fullscreenContainer:a}){const r=C.useRef(null),[i,d]=C.useState(!1),[o,c]=C.useState(s.isDevEnv),[l,x]=C.useState(!1),[p,h]=C.useState(!1),[u,y]=C.useState(!1),b=t??u,m=s.useCurrentAIContext(),{setCurrentAIContext:g}=s.useAIActions(),{clearQueue:w}=s.useQueueActions(),{clearFileAttachments:E}=s.useFileActions(),V=s.useFileAttachments("editor"),A=s.useDashboardStore(oe=>oe.dashboard.aiContext),T=s.useEditorStore(oe=>oe.card.dataSource),v=s.useEditorStore(oe=>oe.actions.setCardSql),D=s.useEditorStore(oe=>oe.actions.setRunSql),L=s.useEditorStore(oe=>oe.showAIDialog),f=s.useDashboardStore(oe=>oe.handleOpenAssistantProfile),{setShowAIDialog:I,setCardPython:j}=s.useEditorActions(),{setDataSource:k}=s.useEditorActions(),{assistantProfile:R}=s.useAssistantProfile(),{messages:P,setMessages:N,sendMessage:M,isLoading:S,stop:F,status:O,llmUsage:$,errorMessage:Q,clearError:B}=Vl(),[K,se]=C.useState(""),H=oe=>{se(oe.target.value)},te=oe=>{oe.preventDefault();const me=K.trim();if(!me&&V.length===0)return;const ts=[];me&&ts.push({type:"text",text:me}),V.forEach(Ye=>{Ye.data&&ts.push({type:"file",mediaType:Ye.type,filename:Ye.name,url:`data:${Ye.type};base64,${Ye.data}`})}),M({role:"user",parts:ts}),se(""),E("editor"),ie({force:!0})},{visibleMessages:z,hasMoreMessages:W,totalMessageCount:le,loadMoreMessages:X,resetMessageWindow:ne}=s.useMessageWindow(P,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:ue,contentRef:ee,isAtBottom:Ne,hasNewMessages:q,newMessageCount:Z,scrollToBottom:ie,handleScroll:je,resetNewMessageCount:ke}=s.useAutoScroll(z,{threshold:40,behavior:"smooth",isStreaming:S});C.useEffect(()=>{var oe;L&&((oe=r.current)==null||oe.focus(),g({selectedEntities:(T==null?void 0:T.selectedEntities)||[]}))},[L,T,g]),s.useAutoSubmitQueue({assistantType:"editor",status:O,isLoading:S,sendMessage:M});const{hasActiveTools:Oe}=s.useActiveToolStatus(P),Se=C.useCallback(oe=>{n==null||n(oe),t===void 0&&y(oe)},[t,n]);C.useEffect(()=>{if(!b)return;function oe(me){me.key==="Escape"&&Se(!1)}return window.addEventListener("keydown",oe),()=>{window.removeEventListener("keydown",oe)}},[b,Se]);const be=C.useCallback(oe=>{M({role:"user",parts:[{type:"text",text:oe}]}),ie({force:!0})},[M,ie]),Ce=C.useCallback(async()=>{const oe=JSON.stringify(P??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(oe),s.ue.success("Conversation copied")}catch(me){console.error("Failed to copy conversation",me),s.ue.error("Unable to copy conversation")}},[P]),ae=C.useCallback(()=>{Se(!b)},[b,Se]);function fe(oe,me){me==="sql"?(v(oe),D(!0)):me==="python"&&(j(oe),D(!0))}function ge(){m.selectedEntities.length===0&&g({selectedEntities:(A==null?void 0:A.selectedEntities)||[]})}function Ie(oe){ge();const me={role:"user",parts:[{type:"text",text:oe.title+" "+oe.subtitle}]};M(me)}function ve(oe){ge(),M({role:"user",parts:[{type:"text",text:oe}]})}function pe(){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:i,onCheckedChange:d,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:c,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:x,children:"System Message"})]})]})}function Re(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const Qe=(K==null?void 0:K.length)===0&&(P==null?void 0:P.filter(oe=>oe.role==="user").length)===0,Ke=e.jsxs("div",{"data-role":"editor-assistant",className:s.cn("flex h-full w-full flex-col justify-between px-6 py-4",b&&"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:[Re(),f&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:f,children:(R==null?void 0:R.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[pe(),o&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Ce,children:"Copy Conversation"}),e.jsx(s.IconButton,{tooltip:b?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:ae,children:b?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:()=>{N([]),w("editor"),B(),ne()},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:()=>{I(!1)},children:e.jsx(s.X,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:ue,className:"mt-2 flex min-w-0 w-full grow basis-0",onScroll:je,children:e.jsxs("div",{ref:ee,className:"min-w-0 space-y-4 py-2 pr-3","data-role":"messages",children:[W&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:X,className:"text-xs",children:["Load ",Math.min(5,le-z.length)," ","more messages (",le-z.length," ","hidden)"]})}),e.jsx(s.PrintMessages,{messages:z,showTools:o,handleRun:fe,showSystemMessage:l,onQuickReply:be,disableQuickReplies:S}),!Oe&&e.jsx(s.AssistantStatus,{status:O,errorMessage:Q})]})}),L&&!Ne&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{ie({force:!0}),ke()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),q&&Z>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:Z>9?"9+":Z})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[Qe&&!R&&e.jsx(s.Placeholders,{onClick:Ie,placeholders:Bl}),e.jsx("div",{children:Qe&&R&&e.jsx(s.SeedQuestions,{seedQuestions:R.seedQuestions||[],handleSeedQuestionClick:ve})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:r,setInput:se,stop:F,input:K,handleInputChange:H,handleSubmit:oe=>{ge(),te(oe),ie({force:!0})},isLoading:S,status:O,assistantType:"editor",onFocus:()=>{}})]}),$&&i&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",$.inputTokens," prompt tokens, ",$.outputTokens," ","completion tokens, ",$.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(T==null?void 0:T.selectedEntities)||[],open:p,onOpenChange:h,dataSource:T||s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]});return b&&a?tn.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:Ke})}),a):Ke}function zl(t,n,a){if(!n)return!1;const r=n.qualifiedFieldName,i=n.qualifiedEntityName,d=i&&n.name?`${i}.${n.name}`:r;return t.some(o=>{if(!(s.getDataType(o.dataType||"")==="date"))return!1;const l=s.getSelectedDateFilterColumn(o,a),x=l.split("."),p=x[x.length-1]||l,h=x.length>1?x.slice(0,-1).join("."):void 0,u=o.qualifiedTableName||h,y=u?`${u}.${p}`:void 0;return r?y?y===d||y.endsWith(`.${r}`):p===n.name:y?y===d:p===n.name})}const Pa=["day","week","month","quarter","year"],ql=[...Pa,"hour","minute","second"],$l=t=>/timestamp|datetime|time/i.test(t||""),_l=t=>$l(t)?ql:Pa,dt=({dataType:t})=>s.getFieldIconComponent(t);function Gl({aliasTemplate:t,onAliasTemplateChange:n}){var l;const[a,r]=C.useState(t),[i,d]=C.useState(!1),o=(l=s.useEditorStore(x=>{var p;return(p=x.card.config)==null?void 0:p.pivotByColumns}))==null?void 0:l[0],c=o?`e.g. Min Sales in {{${o.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:c,value:i?a:t,onChange:x=>{r(x.target.value),d(!0)},onFocus:()=>d(!0),onPointerDown:x=>x.stopPropagation(),className:"h-8 text-xs",onKeyDown:x=>{x.key==="Enter"&&i&&a!==t?(n(a),d(!1)):x.key==="Escape"&&(r(t),d(!1))},"aria-label":"Edit alias template"}),i&&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),d(!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),d(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function Kl({valueAliases:t,onValueAliasesChange:n}){const[a,r]=C.useState(null),[i,d]=C.useState(""),[o,c]=C.useState(""),l=()=>{n({...t,"":""})},x=h=>{const u={...t};delete u[h],n(u)},p=h=>{const u={...t};delete u[h],u[i]=o,n(u),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,u],y)=>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:i,onChange:b=>d(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?p(h):b.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:o,onChange:b=>c(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?p(h):b.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>p(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),d(h),c(u)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:u,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),d(h),c(u)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>x(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+y)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:l,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function Ul({idx:t}){var c;const n=s.useEditorStore(l=>{var x;return(x=l.card)==null?void 0:x.preferences}),a=s.useEditorStore(l=>{var x;return(x=l.card.preferences)==null?void 0:x.datasetOptions}),r=s.useEditorStore(l=>l.actions.setCardPreferences),i=(c=n==null?void 0:n.chartOptions)==null?void 0:c.indexAxis,d=a==null?void 0:a.find(l=>l.idx===t);function o(l,x){(l==="end"||l==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const p={display:l!=="none",align:l,anchor:l,clamp:!0};if(!d)r({...n,datasetOptions:[...a||[],{idx:x,datalabels:p}]});else{const h={...d};h.datalabels=p;const u=a==null?void 0:a.map(y=>y.idx===x?h:y);r({...n,datasetOptions:u})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(s.Tag,{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:()=>o("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>o("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(mn,{className:s.cn("h-4 w-4",{"rotate-90":i==="y"})})}),e.jsx("button",{onClick:()=>o("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(hn,{className:s.cn("h-4 w-4",{"rotate-90":i==="y"})})}),e.jsx("button",{onClick:()=>o("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(xn,{className:s.cn("h-4 w-4",{"rotate-90":i==="y"})})})]})})]})}function ut({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 Hl(t,n=30){return t.length>n?t.slice(0,n)+"...":t}function Jl({col:t,idx:n,className:a,iconClassName:r,children:i}){const d=s.useEditorStore(p=>{var h;return(h=p.card)==null?void 0:h.preferences}),o=s.useEditorStore(p=>{var h,u;return(u=(h=p.card)==null?void 0:h.preferences)==null?void 0:u.datasetOptions}),c=o==null?void 0:o.find(p=>p.idx===n),{setCardPreferences:l}=s.useEditorStore(p=>p.actions);function x(p){if(!c)l({...d,datasetOptions:[...o||[],{idx:n,type:p==="area"?"line":p,fill:p==="area"?"origin":""}]});else{const h={...c};h.type=p==="area"?"line":p,h.fill=p==="area"?"origin":"";const u=o==null?void 0:o.map(y=>y.idx===n?h:y);l({...d,datasetOptions:u})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[i||e.jsx(ut,{className:"max-w-[100px]",title:t,children:Hl(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.ChartColumnIncreasing,{onClick:()=>x("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartLine,{onClick:()=>x("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartArea,{onClick:()=>x("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(Ul,{idx:n})]})]})}function Ql(){const t=s.useEditorStore(c=>c.card.type),n=s.useEditorStore(c=>c.isDevMode),a=s.useEditorStore(c=>c.card.preferences),{setCardPreferences:r}=s.useEditorStore(c=>c.actions);function i(c){var p;const l={datalabels:{display:c!=="none",align:c,anchor:c,clamp:!0}},x={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(p=a==null?void 0:a.chartOptions)==null?void 0:p.plugins,...l}}};r(x)}function d(){var c,l,x;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((x=(l=(c=a==null?void 0:a.chartOptions)==null?void 0:c.plugins)==null?void 0:l.datalabels)==null?void 0:x.anchor)||"none",onValueChange:i,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 o(){var c,l,x;return e.jsx("div",{children:e.jsxs(s.Select,{value:((x=(l=(c=a==null?void 0:a.chartOptions)==null?void 0:c.plugins)==null?void 0:l.datalabels)==null?void 0:x.anchor)||"none",onValueChange:i,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?d():o()})}function Yl({column:t}){const n=s.useEditorStore(l=>l.card.type),a=s.useEditorStore(l=>{var x,p;return(p=(x=l.card)==null?void 0:x.config)==null?void 0:p.metricColumns}),r=(a==null?void 0:a.map(l=>l.label))||[],i=r==null?void 0:r.find(l=>l===t.label||l===t.name),d=i?r.indexOf(i):-1;function o(){return e.jsx("div",{className:"pr-1",children:i&&e.jsx(Jl,{idx:d,col:i,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function c(){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(Ql,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&o(),["pie","doughnut"].includes(n)&&c()]})}function Wl({field:t,searchQuery:n="",limit:a=500}){const{authToken:r,tokenProps:i}=s.useSemaphorContext(),d=s.useEditorStore(x=>x.card),o=d==null?void 0:d.dataSource,c=["attribute-values",t.entityName,t.name,n,a],l=s.useQuery({queryKey:c,queryFn:async()=>{if(!(o!=null&&o.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const x={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},p={connection_id:o.connectionId,cardConfig:x,cardDataSource:o,cache_config:s.getCacheConfig({card:d})};console.log("requestBody",p);const h=await s.postRequestRegular(`${i.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",p);if(h!=null&&h.error)return console.error("Error fetching attribute values:",h.error),[];const u=t.name;return((h==null?void 0:h.records)||[]).map(b=>{const m=b[u]||b[t.alias||u]||b[t.label];return{id:m||"",value:m||"",label:String(m||"(empty)")}})}catch(x){return console.error("Error fetching attribute values:",x),[]}},enabled:!!t&&!!(o!=null&&o.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:l.data||[],isLoading:l.isLoading,isFetching:l.isFetching,isError:l.isError,error:l.error,refetch:l.refetch}}function Va({open:t,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:i,onSave:d}){var V,A;const o=!!i,[c,l]=C.useState(o?"values":"fields"),[x,p]=C.useState(""),[h,u]=C.useState({id:(i==null?void 0:i.id)||s.v4(),field:(i==null?void 0:i.field)||null,selectedValues:i?Array.isArray(i.value)?i.value:[i.value]:[]}),y=a.filter(T=>{var D;return o?!1:!((D=r==null?void 0:r.conditions)==null?void 0:D.some(L=>L.field.id===T.id))&&T.label.toLowerCase().includes(x.toLowerCase())}),b=T=>{u({...h,field:T}),l("values")},m=()=>{if(h.field&&h.selectedValues.length>0){const T={id:h.id,field:h.field,operator:"in",value:h.selectedValues};let v;if(o){const D=((r==null?void 0:r.conditions)||[]).map(L=>L.id===i.id?T:L);v={...r,conditions:D}}else{const D=(r==null?void 0:r.conditions)||[];v={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...D,T],groups:[]}}d(v),n(!1)}},g=()=>{if(!o||!i)return;const T=((r==null?void 0:r.conditions)||[]).filter(v=>v.id!==i.id);if(T.length>0){const v={...r,conditions:T};d(v)}else d(void 0);n(!1)},w=T=>{u({...h,selectedValues:T})},E=()=>{o&&i?(u({id:i.id,field:i.field,selectedValues:Array.isArray(i.value)?i.value:[i.value]}),l("values")):(u({id:s.v4(),field:null,selectedValues:[]}),l("fields")),p("")};return C.useEffect(()=>{t&&E()},[t,o,i]),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:o?`Edit Filter: ${(V=h.field)==null?void 0:V.label}`:c==="fields"?"Select Field to Filter":`Select Values for ${(A=h.field)==null?void 0:A.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!o&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&c==="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(T=>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:[T.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(T.value)?`${T.value.length} values`:String(T.value)})]},T.id))})]}),c==="fields"&&!o?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:x,onChange:T=>p(T.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:y.map(T=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>b(T),children:[e.jsx(dt,{dataType:s.getDataType(T.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:T.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[T.entityName,".",T.name]})]})]},T.id))}),y.length===0&&x&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',x,'"']}),y.length===0&&!x&&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(Xl,{field:h.field,selectedValues:h.selectedValues,onValuesChange:w,onBack:o?void 0:()=>l("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:o?e.jsx(s.Button,{variant:"destructive",onClick:g,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:E,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:m,disabled:!h.field||h.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function Xl({field:t,selectedValues:n,onValuesChange:a,onBack:r}){const[i,d]=C.useState(""),{values:o,isLoading:c,isFetching:l}=Wl({field:t,searchQuery:i,limit:500}),x=i?o.filter(u=>String(u.value).toLowerCase().includes(i.toLowerCase())):o,p=u=>{const y=n.includes(u);a(y?n.filter(b=>b!==u):[...n,u])},h=()=>{n.length===x.length&&x.length>0?a([]):a(x.map(u=>u.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:i,onChange:u=>d(u.target.value),className:"pl-10"})]}),c||l?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===x.length&&x.length>0,onCheckedChange:h}),e.jsxs(s.Label,{className:"text-sm",children:["Select All (",x.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:x.map(u=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>p(u.value),children:[e.jsx(s.Checkbox,{checked:n.includes(u.value),onCheckedChange:()=>p(u.value)}),e.jsx(ut,{className:"text-sm",children:u.label})]},u.id))})]})]})}function Zl({field:t,zone:n,index:a,sortDirection:r,onSortDirectionChange:i,hasPivotColumns:d=!1,cardType:o}){var ft,gt,jt,bt,vt,yt,Nt,Ct,St,wt,Tt,Et,It,kt,Dt,At,Mt,Lt,Ot,Rt,Ft,Pt,Vt,Bt,zt,qt,$t,_t,Gt,Kt,Ut,Ht,Jt,Qt;const{attributes:c,listeners:l,setNodeRef:x,transform:p,transition:h,isDragging:u}=s.useSortable({id:t.id}),y=s.useEditorStore(_=>_.card),b=s.useEditorStore(_=>_.frame),{scopedFields:m,isLoading:g}=s.useScopedFields(),{userContext:w}=s.useCurrentUserInfo(),E=(w==null?void 0:w.type)==="organization",V=(ft=y.dataSource)==null?void 0:ft.semanticDomainId,{promoteMetric:A}=s.usePromoteCalculatedMetricToDomain({domainId:V}),{updateLabel:T,handleAggregationChange:v,handleDateFormatChange:D,handleGranularityChange:L,handleAliasTemplateChange:f,handleValueAliasesChange:I,removeField:j,handleMetricComparisonChange:k,handleMetricWindowTransformChange:R,handleMetricWindowOrderByChange:P,handleMetricWindowDirectionChange:N,handleMetricWindowPartitionToggle:M,handleMetricMovingAverageWindowSizeChange:S,handleMetricMovingAverageMinPeriodsChange:F,handleMetricPreviousPeriodDeltaModeChange:O,handleMetricPercentOfTotalScopeChange:$,handleMetricPercentOfTotalOutputChange:Q,handleKpiShowTrendlineChange:B,handleKpiTrendlineWindowChange:K,handleKpiTrendlineGranularityChange:se,handleMetricTargetValueChange:H}=s.useFieldManagement(y),[te,z]=C.useState(!1),[W,le]=C.useState(()=>{var _;return!!((_=t.parameters)!=null&&_.windowTransform)}),[X,ne]=C.useState(!1),[ue,ee]=C.useState(!1),[Ne,q]=C.useState(null),Z=C.useMemo(()=>{const _=re=>re!=null&&re.startsWith("card-source-")?re.replace("card-source-",""):re,U=_(t.id),de=m.find(re=>{if(t.qualifiedFieldName&&re.qualifiedFieldName&&re.qualifiedFieldName===t.qualifiedFieldName||t.qualifiedEntityName&&re.qualifiedEntityName&&re.qualifiedEntityName===t.qualifiedEntityName&&re.name===t.name)return!0;const ye=_(re.id);return!!(U&&ye&&U===ye)});return{dataType:(de==null?void 0:de.dataType)||t.dataType,resolvedFromScopedField:!!de}},[t.dataType,t.id,t.name,t.qualifiedEntityName,t.qualifiedFieldName,m]),ie=_l(Z.dataType),[je,ke]=C.useState(t.dateFormat||"YYYY-MM-DD"),[Oe,Se]=C.useState(t.customFormat||""),[be,Ce]=C.useState(!!t.customFormat),ae=C.useRef(null),[fe,ge]=C.useState(t.aliasTemplate||""),[Ie,ve]=C.useState(t.valueAliases||{}),[pe,Re]=C.useState((gt=t.parameters)==null?void 0:gt.filters),Qe=_=>{_==="custom"?Ce(!0):(Ce(!1),ke(_),(n==="groupBy"||ns)&&D(a,_,"",n))},Ke=_=>{Se(_),(n==="groupBy"||ns)&&D(a,"custom",_,n)},oe=_=>{var re;const de=(re=s.getDateFormatOptionsForGranularity(_)[0])==null?void 0:re.value;de&&!be&&(ke(de),n==="groupBy"&&D(a,de,"",n)),n==="groupBy"&&L(a,_)},me=_=>{ge(_),n==="metrics"&&f(a,_)},ts=_=>{ve(_),n==="metrics"&&I(a,_)},Ye=_=>{T(n,a,_)},Cs=_=>_!=null&&_.startsWith("card-source-")?_.replace("card-source-",""):_,os=(_,U,de)=>{const re=Cs(_.id),ye=Cs(U.id);return re&&ye&&re===ye?!0:_.name===U.name&&_.role===U.role},ze=s.isCalculatedMetric(t)?(jt=b==null?void 0:b.calculatedFields)==null?void 0:jt.find(_=>os(_,t)):void 0,we=t.fieldScope==="dashboard"||t.fieldScope===void 0&&!!ze,Ss=t.fieldScope==="domain",Ue=Ss?"domain":we?"dashboard":"card",ws=Ss?t:we&&ze?ze:t,as=_=>{var U;if(Re(_),n==="metrics"){const de={...t,parameters:{...t.parameters,filters:_}},re=[...((U=y.config)==null?void 0:U.metricColumns)||[]];re[a]=de,s.useEditorStore.getState().actions.updateCardConfig(y.id,{metricColumns:re})}ne(!1)},zs=async _=>{await A(_),Za()},We=()=>{j(n,a)},Ts={transform:s.CSS.Transform.toString(p),transition:h},gs=s.getDataType(Z.dataType||t.dataType),Xe=gs==="date",Es=o==="kpi",ns=n==="detailColumns",Is=(bt=y.config)==null?void 0:bt.metricColumns,He=(vt=y.config)==null?void 0:vt.groupByColumns,js=s.useDashboardStore(_=>{var U;return(U=_.dashboard)==null?void 0:U.filters}),is=s.useDashboardStore(_=>_.filterValues),Ze=t.granularity||"day",cs=ie.includes(Ze)?Ze:"day",ds=n==="groupBy"&&!ie.includes(Ze),_e=s.getDateFormatOptionsForGranularity(cs),xt=be?"custom":_e.some(_=>_.value===je)?je:((yt=_e[0])==null?void 0:yt.value)??"YYYY-MM-DD";C.useEffect(()=>{var de;if(g||!ds){ae.current=null;return}const _=`${t.id}:${Ze}:${Z.dataType||t.dataType||""}:${a}`;if(ae.current===_)return;ae.current=_;const U="day";if(L(a,U),!be){const re=(de=s.getDateFormatOptionsForGranularity(U)[0])==null?void 0:de.value;re&&(ke(re),D(a,re,"",n))}},[t.dataType,t.id,D,L,ds,a,be,g,Ze,Z.dataType,n]);const ks=!!o&&s.COMPARISON_SUPPORTED_CHART_TYPES.includes(o),qs=o==="kpi"||o==="table",qe=C.useMemo(()=>He==null?void 0:He.find(_=>s.getDataType(_.dataType||"")==="date"),[He]),bs=C.useMemo(()=>(He||[]).some(_=>s.getDataType(_.dataType||"")==="date"),[He]),$s=C.useMemo(()=>{var re;if(!qe)return!1;const _=(re=y.config)==null?void 0:re.filters;if(!_)return!1;const U=ye=>{const Ee=ye.field;return Ee?qe.id&&Ee.id===qe.id||qe.qualifiedFieldName&&Ee.qualifiedFieldName===qe.qualifiedFieldName?!0:Ee.name===qe.name:!1},de=ye=>ye.conditions.some(Be=>s.getDataType(Be.field.dataType||"")==="date"&&U(Be))?!0:ye.groups.some(Be=>de(Be));return de(_)},[(Nt=y.config)==null?void 0:Nt.filters,qe]),_s=C.useMemo(()=>zl(js||[],qe,is),[js,is,qe]),Ds=$s||_s,Te=t,vs=((St=(Ct=Te.parameters)==null?void 0:Ct.windowTransform)==null?void 0:St.function)||"none",Le=s.isMetricTransformEnabled(Te),Pe=Le?vs:null,us=s.supportsMetricTransformForMetric({cardType:o||"table",cardConfig:y.config||{},metric:Te,transformMode:Pe||"running_total"}),G=!!Te.comparisonType&&Te.comparisonType!=="none",Y=s.getRunningTotalOrderByCandidates(He||[]),J=((Et=(Tt=(wt=Te.parameters)==null?void 0:wt.windowTransform)==null?void 0:Tt.orderBy)==null?void 0:Et.fieldId)||"",xe=((Dt=(kt=(It=Te.parameters)==null?void 0:It.windowTransform)==null?void 0:kt.orderBy)==null?void 0:Dt.direction)||"asc",ce=Y.find(_=>_.id===J),he=Pe==="running_total"||Pe==="moving_average"||Pe==="previous_period_delta",De=Le&&he&&!!ce&&s.getDataType(ce.dataType||"")!=="date",Fe=s.getDefaultRunningTotalPartitionByFieldIds({cardType:o||"table",cardConfig:y.config||{},orderByFieldId:J||void 0}),Je=new Set(((Mt=(At=Te.parameters)==null?void 0:At.windowTransform)==null?void 0:Mt.partitionByFieldIds)||Fe),ms=o==="pivotTable"||s.isSubtotalEnabledAggregateTable(o||"table",y.config||{}),rs=[...(He||[]).filter(_=>_.id&&(!he||_.id!==J)),...ms?(((Lt=y.config)==null?void 0:Lt.pivotByColumns)||[]).filter(_=>_.id):[]],Me=((Ft=(Rt=(Ot=Te.parameters)==null?void 0:Ot.windowTransform)==null?void 0:Rt.movingAverage)==null?void 0:Ft.windowSize)||7,xs=((Bt=(Vt=(Pt=Te.parameters)==null?void 0:Pt.windowTransform)==null?void 0:Vt.movingAverage)==null?void 0:Bt.minPeriods)||1,Gs=(($t=(qt=(zt=Te.parameters)==null?void 0:zt.windowTransform)==null?void 0:qt.previousPeriodDelta)==null?void 0:$t.mode)||"absolute",As=((Kt=(Gt=(_t=Te.parameters)==null?void 0:_t.windowTransform)==null?void 0:Gt.percentOfTotal)==null?void 0:Kt.scope)||"grand_total",za=((Jt=(Ht=(Ut=Te.parameters)==null?void 0:Ut.windowTransform)==null?void 0:Ht.percentOfTotal)==null?void 0:Jt.output)||"percent",qa=C.useMemo(()=>(Is||[]).some(_=>_.comparisonType==="start_vs_end"),[Is]);C.useEffect(()=>{Le&&le(!0)},[Le]);const $a=n!=="pivotBy",_a=Xe&&n==="groupBy"&&(!Es||qa),Ga=!Es&&Xe&&(n==="groupBy"||ns),Ka=o==="kpi"&&Xe&&n==="groupBy",Ua=n==="metrics",ht=ks&&n==="metrics",Ha=()=>{const _=t,U=n==="metrics"&&s.isCalculatedMetric(_);return e.jsxs("div",{className:"space-y-1",children:[!U&&e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:de=>{de.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-muted-foreground/80",children:`${t.entityName}.${t.name}`}),U&&_.calculatedFormula&&e.jsxs("div",{title:s.formatDisplayFormula(_.calculatedFormula),onPointerDown:de=>{de.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap rounded bg-muted/50 px-1.5 py-0.5 font-mono text-xs text-primary",children:["= ",s.formatDisplayFormula(_.calculatedFormula)]})]})},Ja=()=>$a?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx($e,{value:t.label??"",onSave:Ye,placeholder:"Display label...",type:"text"})]}):null,pt=()=>_a?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:cs,onValueChange:oe,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:ie.map(_=>e.jsx(s.SelectItem,{className:"text-xs",value:_,children:s.toTitleCase(_)},_))})]})]}):null,Qa=()=>Ga?e.jsxs(e.Fragment,{children:[pt(),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:xt,onValueChange:Qe,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:_e.map(_=>e.jsx(s.SelectItem,{className:"text-xs",value:_.value,children:_.label},_.value))})]}),be&&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:Oe,onChange:_=>{_.stopPropagation(),Ke(_.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,Ya=()=>{var U,de,re,ye;const _=Ka;return _?e.jsx(e.Fragment,{children:_&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(s.SmallSwitch,{checked:((U=y.config)==null?void 0:U.showTrendline)||!1,onCheckedChange:B})]})}),((de=y.config)==null?void 0:de.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:((re=y.config)==null?void 0:re.trendlineWindow)||30,onChange:Ee=>{const Be=parseInt(Ee.target.value)||30;K(Be)},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:((ye=y.config)==null?void 0:ye.trendlineGranularity)||"day",onValueChange:se,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},Wa=()=>{if(!Ua)return null;const _=s.isCalculatedMetric(Te);return e.jsxs(e.Fragment,{children:[_&&E&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Formula"}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>ee(!0),children:[e.jsx(s.Pencil,{className:"mr-2 h-3 w-3"}),"Edit Formula"]})]}),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:U=>{v(a,U)},disabled:_,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsx(s.Collapsible,{open:W,onOpenChange:le,children:e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-muted/20 p-2.5",children:[e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between rounded-sm px-0.5 py-0.5 text-left",children:[e.jsx("div",{className:"text-xs font-medium text-foreground",children:"Metric Transform"}),e.jsxs("div",{className:"flex items-center text-[11px] text-muted-foreground",children:[!W&&e.jsx("span",{className:"mr-2",children:Le?s.toTitleCase(vs.replace(/_/g," ")):"None"}),e.jsx(s.ChevronDown,{className:s.cn("h-3 w-3 transition-transform",W?"rotate-180":"")})]})]})}),e.jsxs(s.CollapsibleContent,{className:"space-y-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Transform"}),e.jsxs(s.Select,{value:Le?vs:"none",onValueChange:U=>R(a,U),disabled:!us.supported&&!Le,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select transform..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"none",children:"None"}),e.jsx(s.SelectItem,{value:"running_total",disabled:G,children:"Running Total"}),e.jsx(s.SelectItem,{value:"moving_average",disabled:G,children:"Moving Average"}),e.jsx(s.SelectItem,{value:"previous_period_delta",disabled:G,children:"Previous Period Delta"}),e.jsx(s.SelectItem,{value:"percent_of_total",disabled:G,children:"Percent of Total"})]})]}),!us.supported&&!Le&&e.jsx("div",{className:"text-xs text-muted-foreground",children:us.reason}),G&&!Le&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"Disable comparison to enable metric transforms."})]}),Le&&e.jsxs(e.Fragment,{children:[he&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Order By"}),e.jsxs(s.Select,{value:J,onValueChange:U=>P(a,U),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select order field..."})}),e.jsx(s.SelectContent,{children:Y.filter(U=>!!U.id).map(U=>e.jsx(s.SelectItem,{value:U.id,className:"text-xs",children:U.label||U.name},U.id))})]}),!J&&e.jsx("div",{className:"text-xs text-amber-700",children:"No date trend detected. Select an order field."}),De&&e.jsx("div",{className:"text-xs text-amber-700",children:"No date trend detected. The transform will follow the selected order field."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Direction"}),e.jsxs(s.Select,{value:xe,onValueChange:U=>N(a,U),disabled:!J,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select direction..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"asc",children:"Ascending"}),e.jsx(s.SelectItem,{className:"text-xs",value:"desc",children:"Descending"})]})]})]})]}),Pe==="moving_average"&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Window Size"}),e.jsx(s.Input$1,{type:"number",min:1,className:"h-8 text-xs",value:Me,onChange:U=>S(a,Number(U.target.value))}),e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Min Periods"}),e.jsx(s.Input$1,{type:"number",min:1,max:Me,className:"h-8 text-xs",value:xs,onChange:U=>F(a,Number(U.target.value))})]}),Pe==="previous_period_delta"&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Output"}),e.jsxs(s.Select,{value:Gs,onValueChange:U=>O(a,U),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select output..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"absolute",children:"Absolute Delta"}),e.jsx(s.SelectItem,{value:"percent",children:"Percent Delta"})]})]})]}),Pe==="percent_of_total"&&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:"Scope"}),e.jsxs(s.Select,{value:As,onValueChange:U=>$(a,U),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select scope..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"grand_total",children:"Grand Total"}),e.jsx(s.SelectItem,{value:"partition_total",children:"Partition Total"})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Output"}),e.jsxs(s.Select,{value:za,onValueChange:U=>Q(a,U),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select output..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"percent",children:"Percent"}),e.jsx(s.SelectItem,{value:"fraction",children:"Fraction"})]})]})]})]}),(Pe==="running_total"||Pe==="moving_average"||Pe==="previous_period_delta"||Pe==="percent_of_total"&&As==="partition_total")&&rs.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Reset By"}),e.jsx("div",{className:"space-y-1",children:rs.map(U=>{const de=!!U.id&&Je.has(U.id);return e.jsxs("button",{type:"button",onClick:()=>U.id&&M(a,U.id),className:s.cn("flex h-7 w-full items-center justify-between rounded border px-2 text-xs",de?"border-primary bg-primary/5 text-primary":"border-border text-muted-foreground"),children:[e.jsx("span",{children:U.label||U.name}),de?e.jsx(s.Check,{className:"h-3 w-3"}):null]},U.id)})})]})]})]})]})}),ht&&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:Te.comparisonType||"none",disabled:Le,onValueChange:U=>k(a,U),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"}),(()=>{const U=!bs||!Ds,de=bs?Ds?void 0:"Add a date filter to enable":"Add a date groupBy to enable",re=(ye,Ee)=>e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.SelectItem,{value:ye,disabled:U,title:de,children:Ee})}),U&&de&&e.jsx(s.TooltipContent,{side:"right",children:de})]})});return e.jsxs(e.Fragment,{children:[re("previous_period","Previous Period"),re("same_period_last_year","Same Period Last Year"),re("start_vs_end","Start vs End")]})})(),qs&&e.jsx(s.SelectItem,{value:"target",children:"Target"})]})]})]}),ht&&Te.comparisonType==="target"&&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(s.Input$1,{type:"number",value:Te.targetValue!==void 0&&Te.targetValue!==null?String(Te.targetValue):"",onChange:U=>{const de=U.target.value;if(de===""){H(a,void 0);return}const re=Number(de);H(a,Number.isFinite(re)?re:void 0)},className:"h-8 text-xs",placeholder:"Enter target value..."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(pe==null?void 0:pe.conditions)&&pe.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:pe.conditions.map(U=>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:()=>{q(U),ne(!0)},children:[e.jsxs("span",{className:"font-medium",children:[U.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(U.value)?U.value.length===1?String(U.value[0]):U.value.length<=2?U.value.join(", "):`${U.value.slice(0,2).join(", ")} +${U.value.length-2}`:String(U.value)})}),Array.isArray(U.value)&&U.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 (",U.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:U.value.map((de,re)=>e.jsx("div",{children:String(de)},re))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:de=>{var ye;de.stopPropagation();const re=pe.conditions.filter(Ee=>Ee.id!==U.id);if(re.length>0){const Ee={...pe,conditions:re};as(Ee)}else if(Re(void 0),n==="metrics"){const Ee={...t,parameters:{...t.parameters,filters:void 0}},Be=[...((ye=y.config)==null?void 0:ye.metricColumns)||[]];Be[a]=Ee,s.useEditorStore.getState().actions.updateCardConfig(y.id,{metricColumns:Be})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},U.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{q(null),ne(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(Yl,{column:t}),d&&e.jsxs(e.Fragment,{children:[e.jsx(Gl,{aliasTemplate:fe,onAliasTemplateChange:me}),e.jsx(Kl,{valueAliases:Ie,onValueAliasesChange:ts})]})]})},{columns:Xa=[],refetch:Za}=s.useColumns(),en=(pe==null?void 0:pe.conditions)&&pe.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:x,style:Ts,...c,...l,className:s.cn("group mx-auto flex w-full flex-col gap-2 rounded-md border border-border/55 bg-background p-2 transition-colors duration-150","hover:border-border/80 hover:bg-muted/20",te&&"border-border/80 bg-muted/20 shadow-[inset_0_1px_0_rgba(255,255,255,0.35)]",u&&"z-50 scale-95 opacity-50",n==="filters"?"cursor-default":"cursor-move"),children:[e.jsxs("div",{className:"flex min-w-0 grow items-center gap-2",children:[e.jsx(dt,{dataType:gs}),e.jsx(ut,{className:s.cn("w-[140px] min-w-0 flex-1 text-sm text-foreground/95",en&&"w-[120px] min-w-0"),children:s.getMetricDisplayLabel(t)}),n==="metrics"&&((Qt=pe==null?void 0:pe.conditions)==null?void 0:Qt.length)&&!te&&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 text-primary/90",children:[e.jsx(s.Filter,{className:"h-3 w-3"}),e.jsx("span",{children:pe.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:pe.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 text-foreground/55 hover:text-foreground",onClick:_=>{_.stopPropagation(),z(!te)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${te?"rotate-180":""}`})}),n==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-foreground/55 hover:text-foreground",onClick:_=>{_.stopPropagation(),i(r==="asc"?"desc":"asc")},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 text-foreground/55 hover:text-foreground",onClick:_=>{_.stopPropagation(),We()},children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]}),te&&e.jsxs("div",{className:"space-y-3 rounded-md bg-muted/20 p-2.5",children:[Ha(),Ja(),o==="kpi"&&pt(),Qa(),Ya(),Wa()]})]}),X&&e.jsx(Va,{open:X,onOpenChange:_=>{ne(_),_||q(null)},availableFields:Xa,existingFilters:pe,editingCondition:Ne,onSave:_=>{var U;if(_)as(_);else if(Re(void 0),n==="metrics"){const de={...t,parameters:{...t.parameters,filters:void 0}},re=[...((U=y.config)==null?void 0:U.metricColumns)||[]];re[a]=de,s.useEditorStore.getState().actions.updateCardConfig(y.id,{metricColumns:re})}q(null)}}),ue&&n==="metrics"&&e.jsx(s.CalculatedFieldEditor,{open:ue,onOpenChange:ee,availableFields:m,existingField:ws,existingFieldScope:Ue,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:_=>{var hs;if(_.role!=="metric")return;const U=[...((hs=y.config)==null?void 0:hs.metricColumns)||[]];U[a]=_;const{frame:de,actions:re}=s.useEditorStore.getState();if(re.updateCardConfig(y.id,{metricColumns:U}),!s.isCalculatedMetric(_))return;const ye=de.calculatedFields||[],Ee=ye.findIndex(Ge=>Ge.name===t.name&&Ge.role===t.role);if(Ee<0)return;const Be=ye.map((Ge,Ms)=>Ms===Ee?{..._,id:Ge.id}:Ge);re.updateFrame({calculatedFields:Be})},onSaveToDashboard:_=>{var Ms;if(_.role!=="metric")return;const{frame:U,actions:de}=s.useEditorStore.getState(),re=U.calculatedFields||[],ye=re.findIndex(Ks=>os(Ks,_)),Ee=ye>=0&&re[ye].id!==_.id?{..._,id:re[ye].id}:_,Be=ye>=0?re.map((Ks,sn)=>sn===ye?Ee:Ks):[...re,Ee];de.updateFrame({calculatedFields:Be});const hs=[...((Ms=y.config)==null?void 0:Ms.metricColumns)||[]],Ge=t;hs[a]={...Ee,id:Ge.id,aliasTemplate:Ge.aliasTemplate,valueAliases:Ge.valueAliases,parameters:Ge.parameters,customFormat:Ge.customFormat},de.updateCardConfig(y.id,{metricColumns:hs})},onPromoteMetricToDomain:V&&E?zs:void 0,domainId:V,cardId:y.id})]})}function eo({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:"Pivot Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metric Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});case"detailColumns":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields to display as columns in the detail table. No aggregation applied - shows raw values from the database."})]});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()})]})})}const so={groupBy:Rs,pivotBy:rt,metrics:vn,detailColumns:s.Table2,sortBy:s.ArrowUpDown};function Ns({zone:t,fields:n,label:a,placeholder:r,shouldShow:i,hasPivotColumns:d=!1,activeField:o=null}){const{isOver:c,setNodeRef:l}=s.useDroppable({id:t}),{updateSortByColumn:x}=s.useEditorActions(),p=s.useEditorStore(w=>w.card),h=s.useEditorStore(w=>w.card.type),u=n.length>0,y=C.useMemo(()=>!o||!c?!0:s.validateFieldForChartType(o,t,h).isValid,[o,c,t,h]),b=(w,E)=>{var A;!((A=p.config)!=null&&A.sortByColumns)||p.config.sortByColumns.findIndex(T=>T.id===w)===-1||x(p.id,w,{direction:E})};if(t==="sortBy"&&i===!1)return null;const m=t!=="sortBy"&&h!=="kpi",g=so[t]||s.Plus;return e.jsxs("div",{className:"mb-3 w-full",children:[e.jsxs("div",{className:"mb-1.5 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium text-foreground",{}),children:a}),m&&e.jsx(eo,{concept:t})]}),e.jsx("div",{ref:l,className:s.cn("rounded-lg border p-0.5 transition-colors duration-150",{"border-green-500 bg-green-50 shadow-[0_0_0_1px_rgba(34,197,94,0.18)] dark:bg-green-950":c&&y,"border-red-500 bg-red-50 shadow-[0_0_0_1px_rgba(239,68,68,0.18)] dark:bg-red-950":c&&!y,"border-solid border-border/55 bg-background":!c&&u,"min-h-[56px] border-dashed border-border/60 bg-background":!c&&!u}),children:n.length===0?e.jsxs("div",{className:"flex min-h-[56px] items-center justify-center gap-2 text-sm text-muted-foreground/85",children:[e.jsx(g,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground/80"}),e.jsx("span",{children:r})]}):e.jsx(s.SortableContext,{id:t,items:n.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map((w,E)=>{const A=w.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(Zl,{field:w,zone:t,index:E,sortDirection:A,onSortDirectionChange:T=>b(w.id,T),hasPivotColumns:d,cardType:h})})},w.id)})})})})]})}function to({groupByFields:t,pivotByFields:n,metricsFields:a,sortByFields:r,detailFields:i,activeField:d}){var se,H,te,z;const[o,c]=C.useState(!1),l=s.useEditorStore(W=>{var le;return!!((le=W.card.customCardPreferences)!=null&&le.url)}),x=s.useEditorStore(W=>W.card),p=s.useEditorStore(W=>W.frame),h=s.findCustomVisualConfigCard(p,x),{manifest:u}=s.useCustomVisual(((se=h==null?void 0:h.customCardPreferences)==null?void 0:se.url)||""),y=(H=u==null?void 0:u.visuals)==null?void 0:H.find(W=>{var le;return W.name===((le=h==null?void 0:h.customCardPreferences)==null?void 0:le.componentName)}),b=s.resolveMultiInputType(h,y)==="multiple",m=b&&!!((te=h==null?void 0:h.customCardPreferences)!=null&&te.url),g=s.getConfigSlotExpectedType(y==null?void 0:y.slots),w=s.useEditorStore(W=>W.actions.updateCardConfig),E=s.useEditorStore(W=>W.actions.updateFrame),{scopedFields:V,refetch:A}=s.useScopedFields(),{userContext:T}=s.useCurrentUserInfo(),v=b&&(h==null?void 0:h.id)===x.id&&g?g:x==null?void 0:x.type,D=v==="detailTable",L=t.length>0||a.length>0||i.length>0,f=!D&&(v!=="kpi"||a.length<=2),I=!D,j=!D&&v!=="kpi",k=v!=="kpi"&&L,R=D,P="Drop sort fields here",N=(z=x.dataSource)==null?void 0:z.semanticDomainId,{promoteMetric:M}=s.usePromoteCalculatedMetricToDomain({domainId:N}),S=(T==null?void 0:T.type)==="organization",F=W=>{const le=p.calculatedFields||[],X=le.findIndex(Z=>Z.name===W.name&&Z.role===W.role),ne=X>=0?{...W,id:le[X].id}:W,ue=X>=0?le.map((Z,ie)=>ie===X?ne:Z):[...le,ne];E({calculatedFields:ue});const ee=s.getNewField(ne,"metrics",a),Ne=a.findIndex(Z=>Z.name===ee.name&&Z.role===ee.role),q=Ne>=0?a.map((Z,ie)=>ie===Ne?{...Z,...ee,id:Z.id}:Z):[...a,ee];w(x.id,{metricColumns:q})},O=async W=>{await M(W),A()},$=["pie","doughnut","polar","funnel","aggregateTable","bubble","scatter"].includes(v),Q=j&&!$,B=()=>v==="kpi"?{label:"Trend By",placeholder:"Drop trend field here"}:{label:"Rows",placeholder:"Drop dimensions here"},K=()=>v==="kpi"?{label:"Metric",placeholder:"Drop metric here"}:{label:"Metrics",placeholder:"Drop metrics here"};return e.jsxs(e.Fragment,{children:[e.jsxs(s.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full space-y-2.5",children:[e.jsxs(s.AccordionItem,{value:"fields",className:"rounded-xl border border-border/55 border-b-0 bg-card px-3 shadow-[0_1px_2px_rgba(15,23,42,0.04)]",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2.5 text-xs font-semibold tracking-wide text-foreground/70 hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.List,{className:"h-4 w-4 text-foreground/60"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-3 pt-1.5",children:[f&&e.jsx(Ns,{zone:"groupBy",fields:t,label:B().label,placeholder:B().placeholder,activeField:d}),Q&&e.jsx(Ns,{zone:"pivotBy",fields:n,label:"Pivot Columns",placeholder:"Drop pivot fields here",activeField:d}),I&&e.jsx(Ns,{zone:"metrics",fields:a,label:K().label,placeholder:K().placeholder,hasPivotColumns:n.length>0,activeField:d}),R&&e.jsx(Ns,{zone:"detailColumns",fields:i,label:"Columns",placeholder:"Drop columns here"}),a.length>=1&&S&&e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:()=>c(!0),className:"mt-1.5 w-full justify-start border-border/60 border-dashed bg-background text-xs text-foreground/70 hover:bg-muted/40 hover:text-foreground",children:[e.jsx(s.Calculator,{className:"mr-2 h-4 w-4"}),"Create Metric"]}),k&&e.jsx(Ns,{zone:"sortBy",fields:r,label:"Sort By",placeholder:P,activeField:d})]})]}),(!l||m)&&e.jsxs(s.AccordionItem,{value:"configuration",className:"rounded-xl border border-border/55 border-b-0 bg-card px-3 shadow-[0_1px_2px_rgba(15,23,42,0.04)]",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2.5 text-xs font-semibold tracking-wide text-foreground/70 hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Settings2,{className:"h-4 w-4 text-foreground/60"}),e.jsx("span",{children:"CHART SETTINGS"})]})}),e.jsx(s.AccordionContent,{className:"mb-2 rounded-md bg-muted/20 px-3 py-0.5",children:e.jsx(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:e.jsx(Fa,{mode:"config"})})})]}),(l||m)&&e.jsxs(s.AccordionItem,{value:"plugin",className:"rounded-xl border border-border/55 border-b-0 bg-card px-3 shadow-[0_1px_2px_rgba(15,23,42,0.04)]",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2.5 text-xs font-semibold tracking-wide text-foreground/70 outline-none ring-0 hover:no-underline focus:outline-none focus-visible:outline-none focus-visible:ring-0 focus-visible:ring-offset-0",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(va,{className:"h-4 w-4 text-foreground/60"}),e.jsx("span",{children:"COMPONENT SETTINGS"})]})}),e.jsx(s.AccordionContent,{className:"mb-2 rounded-md bg-muted/20 px-3 py-0.5",children:e.jsx(Ma,{})})]})]}),e.jsx(s.CalculatedFieldEditor,{open:o,onOpenChange:c,availableFields:V,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:W=>{W.role==="metric"&&w(x.id,{metricColumns:[...a,W]})},onSaveToDashboard:W=>{W.role==="metric"&&F(W)},onPromoteMetricToDomain:N&&S?O:void 0,domainId:N,cardId:x.id})]})}function ao({onEditJoins:t}){const n=s.useEditorStore(c=>c.card),{autoJoinMetadata:a}=s.useDashboardCardQuery(n);if(!(a!=null&&a.autoResolved))return null;const{resolvedJoinPlan:r}=a,i=(r==null?void 0:r.joins)||[];if(i.length===0)return null;const d=c=>!c||c.length===0?"No conditions":c.map(l=>{var u,y,b,m;const x=`${(u=l.source)==null?void 0:u.entityName}.${(y=l.source)==null?void 0:y.name}`,p=`${(b=l.target)==null?void 0:b.entityName}.${(m=l.target)==null?void 0:m.name}`,h=l.operator||"=";return`${x} ${h} ${p}`}).join(" AND "),o=c=>!c.joinKeyGroups||c.joinKeyGroups.length===0?"No conditions defined":c.joinKeyGroups.length===1?d(c.joinKeyGroups[0].keys):c.joinKeyGroups.map((l,x)=>({id:x,operator:l.operator,condition:d(l.keys)}));return e.jsx(s.Card,{className:"border-blue-500/20 bg-blue-50/15 shadow-sm dark:bg-blue-950/10",children:e.jsxs("div",{className:"flex items-center justify-between p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wn,{className:"size-4 text-blue-600/90 dark:text-blue-400"}),e.jsx("h3",{className:"text-xs font-semibold tracking-wide text-blue-900/90 dark:text-blue-100",children:"Resolved Joins"}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"secondary",className:"cursor-help bg-blue-100/80 text-xs text-blue-700 dark:bg-blue-900/70 dark:text-blue-300",children:i.length})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"max-w-md p-3",children:e.jsx("div",{className:"space-y-2",children:i.map((c,l)=>{const x=o(c),p=Array.isArray(x);return e.jsxs("div",{className:"rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"font-medium text-foreground",children:c.source.name}),e.jsx(s.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:c.target.name})]}),e.jsx(s.Badge,{variant:"outline",className:"border-green-500/40 bg-green-50/30 text-xs text-green-700 dark:bg-green-950/30 dark:text-green-300",children:c.joinType})]}),e.jsx("div",{className:"mt-1 space-y-1",children:p?x.map(h=>e.jsxs("div",{className:"rounded bg-muted/30 px-2 py-1",children:[e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:h.condition}),h.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",h.operator,")"]})]},h.id)):e.jsx("div",{className:"rounded bg-muted/30 px-2 py-1",children:e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:x})})})]},c.id||l)})})})]})})]}),t&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:t,className:"h-7 gap-1 p-2 text-xs text-blue-700/80 hover:text-blue-900 dark:text-blue-300 dark:hover:text-blue-100",children:e.jsx(s.SquarePen,{className:"size-3.5"})})]})})}const ja={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 no({selectedChart:t,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:i,sortByFields:d,detailFields:o,activeField:c}){var f,I;const[l,x]=C.useState(()=>ja.getItem("chart-selector-expanded")==="true"),[p,h]=C.useState(!1),u=s.useEditorStore(j=>j.card),y=s.useEditorStore(j=>j.actions.updateCardConfig),b=a.length>0||r.length>0||i.length>0||o.length>0,{data:m,autoJoinMetadata:g}=s.useDashboardCardQuery(u),w=b||!!m,E=((f=u==null?void 0:u.config)==null?void 0:f.joinPlan)||(g!=null&&g.autoResolved?g.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),V=((I=u==null?void 0:u.dataSource)==null?void 0:I.selectedEntities)||[],A=j=>{y(u.id,{...u==null?void 0:u.config,joinPlan:j}),h(!1)},T=()=>{y(u.id,{...u==null?void 0:u.config,joinPlan:void 0}),h(!1)},v=()=>{h(!1)},D=()=>{h(!0)};C.useEffect(()=>{ja.setItem("chart-selector-expanded",String(l))},[l]);const L=()=>{x(j=>!j)};return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col bg-background",children:[e.jsx("div",{className:"pl-2 pr-4 pt-4",children:e.jsxs("div",{className:"rounded-xl border border-border/60 bg-card p-3 shadow-[0_1px_2px_rgba(15,23,42,0.05)]",children:[e.jsx("div",{className:s.cn("overflow-hidden transition-all duration-300 ease-in-out",l?"max-h-[210px] opacity-100":"max-h-0 opacity-0"),children:l&&e.jsx(ot,{selectedChart:t,onChartChange:n,variant:"outline"})}),e.jsx("div",{"data-content":"Chart Quick Selector",className:s.cn("flex items-center justify-center",{"mt-3":l,"mt-2":!l}),children:e.jsx(s.ChartQuickSelector,{selectedChart:t,onChartChange:n,isDropdownExpanded:l,onToggleDropdown:L})})]})}),w&&e.jsx("div",{className:"pl-2 pr-4 py-3",children:e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(Ae.EditorClearButton,{label:"Reset",variant:"secondary",className:"h-7 px-2 text-xs"})})}),e.jsx(s.ScrollArea,{className:"min-h-0 w-full flex-1 basis-0",children:e.jsxs("div",{className:s.cn("space-y-3 pl-2 pr-4 pb-6",w?"pt-1":"pt-4"),children:[e.jsx(ao,{onEditJoins:D}),e.jsx(to,{groupByFields:a,pivotByFields:r,metricsFields:i,sortByFields:d,detailFields:o,activeField:c})]})}),e.jsx(Sa,{open:p,onOpenChange:h,joinPlan:E,availableDataSources:V,onSave:A,onCancel:v,onRemove:T,children:e.jsx("div",{})})]})}function ro({initialFilters:t,availableFields:n}={}){const[a,r]=C.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(T=>T.card.dataSource);const{columns:i,isLoading:d}=s.useColumns(),c=n||i||[],l={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},x=T=>{const v=D=>{if(D.id===T){const L=c[0]||l,f=s.getDataType(L.dataType)==="date";return{...D,conditions:[...D.conditions,{id:`condition-${Date.now()}`,field:L,operator:f?"between":"=",value:f?[]:""}]}}return{...D,groups:D.groups.map(v)}};r(v(a))},p=T=>{const v=D=>{if(D.id===T){const L=c[0]||l,f=s.getDataType(L.dataType)==="date";return{...D,groups:[...D.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:L,operator:f?"between":"=",value:f?[]:""}],groups:[]}]}}return{...D,groups:D.groups.map(v)}};r(v(a))},h=(T,v)=>{const D=L=>L.id===T?{...L,conditions:L.conditions.filter(f=>f.id!==v)}:{...L,groups:L.groups.map(D)};r(D(a))},u=(T,v)=>{const D=L=>L.id===T?{...L,groups:L.groups.filter(f=>f.id!==v)}:{...L,groups:L.groups.map(D)};r(D(a))},y=(T,v,D,L)=>{if(D==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const f=I=>I.id===T?{...I,conditions:I.conditions.map(j=>j.id===v?{...j,[D]:L}:j)}:{...I,groups:I.groups.map(f)};r(f(a))},b=(T,v,D)=>{const L=f=>f.id===T?{...f,conditions:f.conditions.map(I=>I.id===v?{...I,...D}:I)}:{...f,groups:f.groups.map(L)};r(L(a))},m=(T,v)=>{const D=L=>L.id===T?{...L,logicalOperator:v}:{...L,groups:L.groups.map(D)};r(D(a))},g=(T,v)=>{const D=L=>L.id===T?{...L,negate:v}:{...L,groups:L.groups.map(D)};r(D(a))},w=(T,v,D)=>{const L=f=>f.id===T?{...f,conditions:s.arrayMove(f.conditions,v,D)}:{...f,groups:f.groups.map(L)};r(L(a))},E=(T,v,D)=>{const L=f=>f.id===T?{...f,groups:s.arrayMove(f.groups,v,D)}:{...f,groups:f.groups.map(L)};r(L(a))},V=T=>{if(!T||T.conditions.length===0&&T.groups.length===0)return"-- No filters defined";const v=L=>{let f="";typeof L.field=="object"?f=L.field.entityName?`${L.field.entityName}.${L.field.name}`:L.field.name:f=String(L.field);const I=L.operator;let j=L.value;if(L.field.dataType==="string"&&!["in","not in"].includes(L.operator))typeof j=="string"?j=`'${j}'`:Array.isArray(j)&&(j=`'${j.join(", ")}'`);else if(L.field.dataType==="date"||L.field.dataType==="datetime"||L.field.dataType==="timestamp")if(L.operator==="between"&&Array.isArray(j)&&j.length===2){const k=j[0]?`'${j[0]}'`:"NULL",R=j[1]?`'${j[1]}'`:"NULL";return`${f} BETWEEN ${k} AND ${R}`}else if((L.operator==="in"||L.operator==="not in")&&Array.isArray(j)){const k=j.map(R=>R?`'${R}'`:"NULL").join(", ");return`${f} ${I} (${k})`}else typeof j=="string"||j instanceof Date?j=`'${j}'`:Array.isArray(j)&&j.length>0&&(j=`'${j[0]}'`);else if(["in","not in"].includes(L.operator)){let k=[];Array.isArray(j)?k=j.map(R=>typeof R=="string"?`'${R}'`:String(R)):typeof j=="string"?k=j.split(",").map(R=>{const P=R.trim();return L.field.dataType==="string"?`'${P}'`:P}):typeof j=="number"&&(k=[String(j)]),j=`(${k.join(", ")})`}switch(I){case"contains":return typeof j=="string"?`${f} LIKE '%${j.replace(/'/g,"")}'`:`${f} LIKE '%${String(j)}'`;case"startsWith":return typeof j=="string"?`${f} LIKE '${j.replace(/'/g,"")}%'`:`${f} LIKE '${String(j)}%'`;case"endsWith":return typeof j=="string"?`${f} LIKE '%${j.replace(/'/g,"")}'`:`${f} LIKE '%${String(j)}'`;case"isNull":return`${f} IS NULL`;case"isNotNull":return`${f} IS NOT NULL`;default:return`${f} ${I} ${j}`}},D=L=>{const f=L.conditions.map(v),I=L.groups.map(P=>D(P)),j=[...f,...I].filter(Boolean);if(j.length===0)return"";const k=j.join(` ${L.logicalOperator} `),R=j.length>1?`(${k})`:k;return L.negate?`NOT ${R}`:R};return D(T)},A=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:c,isLoading:d,addCondition:x,addGroup:p,removeCondition:h,removeGroup:u,updateCondition:y,updateConditionFields:b,updateGroupOperator:m,updateGroupNegate:g,reorderConditions:w,reorderGroups:E,generateSQLPreview:V,hasAnyFilters:A}}function lo({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 oo=t=>{if(t.qualifiedEntityName){const n=t.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function io({value:t,onValueChange:n,availableFields:a,placeholder:r="Select field",className:i="w-64"}){const[d,o]=C.useState(!1),c=C.useMemo(()=>{const l={};return a.forEach(x=>{const p=oo(x);l[p]||(l[p]={}),l[p][x.entityId]||(l[p][x.entityId]=[]),l[p][x.entityId].push(x)}),l},[a]);return e.jsxs(s.Popover,{modal:!0,open:d,onOpenChange:o,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":d,className:s.cn("justify-between",!t&&"text-muted-foreground",i),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(lo,{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(c).map(([l,x])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),l]}),children:Object.entries(x).map(([p,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:[s.getEntityIcon(h[0].entityType,{size:"h-3 w-3"}),e.jsx("span",{children:h[0].entityName})]}),h.map((u,y)=>e.jsxs(s.CommandItem,{value:u.id,onSelect:()=>{n(u),o(!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)===u.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:u.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:u.description&&e.jsx("span",{children:u.description})})]})]},u.id+y))]},`${l}-${p}`))},l))})]})})]})}function mt(t){var m;const n=s.useEditorStore(g=>g.card),{authToken:a,tokenProps:r}=s.useSemaphorContext(),i=s.useEditorStore(g=>g.card.config),d=i==null?void 0:i.joinPlan,o={...t,alias:t.name,label:"value",role:"groupby"},c={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},l={...o,role:"sortby",direction:"asc"},x={joinPlan:d,groupByColumns:[o],metricColumns:[c],sortByColumns:[l]},p=((m=n.dataSource)==null?void 0:m.connectionId)||n.connectionId,{data:h,isPending:u,error:y}=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:p,cardConfig:x,cardDataSource:n.dataSource})}catch(g){console.log(t),console.error("error",g)}},enabled:!!p,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((h==null?void 0:h.records)||[]).map(g=>({label:g.value||"BLANK",value:g.value||"BLANK",count:(g==null?void 0:g.count)||0})),isPending:u,error:y}}function co({field:t,selected:n,onChange:a,placeholder:r="Select items...",className:i}){const[d,o]=tt.useState(!1),{filterValues:c}=mt(t),l=p=>{a(n.filter(h=>h!==p))},x=p=>{n.includes(p)?a(n.filter(h=>h!==p)):a([...n,p])};return e.jsx("div",{className:s.cn("w-full",i),children:e.jsxs(s.Popover,{open:d,onOpenChange:o,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":d,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(p=>{const h=c.find(u=>u.value===p);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:u=>{u.key==="Enter"&&l(p)},onMouseDown:u=>{u.preventDefault(),u.stopPropagation()},onClick:u=>{u.stopPropagation(),l(p)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},p)}):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:c.map((p,h)=>e.jsxs(s.CommandItem,{onSelect:()=>x(p.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",n.includes(p.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:p.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:p.count})]})]},p.value+h))})]})]})})]})})}function uo({field:t,value:n,onChange:a,placeholder:r="Select value...",className:i}){const{filterValues:d,isPending:o,error:c}=mt(t);return o?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..."]}):c?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:i||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:n})}),e.jsx(s.SelectContent,{children:d.map((l,x)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:l.value,children:l.label},l.value+x))})]})}function mo({value:t,operator:n,onChange:a,className:r}){var y,b,m;const{tokenProps:i}=s.useSemaphorContext(),d=((b=(y=i==null?void 0:i.params)==null?void 0:y.calendarContext)==null?void 0:b.tz)||((m=i==null?void 0:i.params)==null?void 0:m.timezone),o=d||Intl.DateTimeFormat().resolvedOptions().timeZone,c=n==="between"||n==="not between",l=C.useMemo(()=>{if(!(!t||!c)&&Array.isArray(t)&&t.length===2){const g=t[0]?new Date(t[0]):void 0,w=t[1]?new Date(t[1]):void 0;if(g&&w)return{from:g,to:w}}},[t,c]),x=C.useMemo(()=>{if(!t||c)return;const g=Array.isArray(t)?t[0]:t;if(!g)return;const w=new Date(g);if(!isNaN(w.getTime()))return w},[t,c]),p=g=>n==="<="||n===">"?s.endOfDayInTimezone(g,o):s.startOfDayInTimezone(g,o),h=g=>{if(!g){a([]);return}if(g.from&&g.to){a([g.from.toISOString(),g.to.toISOString()]);return}a([])},u=g=>{if(!g){a("");return}const w=p(g);a(w.toISOString())};return e.jsx(s.DateRangePicker,{value:c?l:void 0,selectionMode:c?"range":"single",singleValue:c?void 0:x,onChange:h,onSingleChange:u,timezone:d,showRelativeTab:c,className:r,placeholder:"Select date..."})}const xo=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],ho=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],po=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],fo=["=","!=","isNull","isNotNull"],go=["between","=","!=","<","<=",">",">=","isNull","isNotNull"],jo={"=":"Equals","!=":"Not Equals",">":"Greater Than",">=":"Greater Than or Equal","<":"Less Than","<=":"Less Than or Equal",contains:"Contains",startsWith:"Starts With",endsWith:"Ends With",in:"In","not in":"Not In",between:"Between",isNull:"Is Null",isNotNull:"Is Not Null","not between":"Not Between"};function ba(t){return jo[t]||s.titleCase(t)}function bo(t){switch(t){case"string":return ho;case"number":return po;case"boolean":return fo;case"date":return go;default:return xo}}function Ba({condition:t,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:i,onRemoveCondition:d,onUpdateGroupOperator:o,availableFields:c,updateConditionFields:l}){const{attributes:x,listeners:p,setNodeRef:h,transform:u,transition:y,isDragging:b}=s.useSortable({id:t.id}),{isPending:m,error:g}=mt(t.field),w={transform:s.CSS.Transform.toString(u),transition:y};return e.jsxs("div",{ref:h,style:w,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${b?"z-50 opacity-50":""}`,children:[e.jsx("div",{...x,...p,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:E=>o(a,E),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(io,{value:t.field,onValueChange:E=>{const V=E,A=s.getDataType(V.dataType)==="date";l(a,t.id,{field:V,value:"",operator:A?"between":"="})},availableFields:c,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:E=>{E==="in"||E==="not in"?l(a,t.id,{operator:E,value:[]}):E==="isNull"||E==="isNotNull"?l(a,t.id,{operator:E,value:null}):E==="between"||E==="not between"?l(a,t.id,{operator:E,value:[]}):l(a,t.id,{operator:E,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?ba(t.operator):""})}),e.jsx(s.SelectContent,{children:bo(s.getDataType(t.field.dataType)).map(E=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:E,children:ba(E)},E))})]}),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"?m?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..."]}):g?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(co,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(E=>typeof E=="string")?t.value:[],onChange:E=>l(a,t.id,{value:E}),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:E=>l(a,t.id,{value:E.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(uo,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:E=>l(a,t.id,{value:E}),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:E=>l(a,t.id,{value:E==="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(mo,{value:t.value,operator:t.operator,onChange:E=>l(a,t.id,{value:E}),className:"flex-1"}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:E=>i(a,t.id,"value",E.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:()=>d(a,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function vo({group:t,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:i,onRemoveGroup:d,onUpdateCondition:o,onUpdateField:c,onRemoveCondition:l,onReorderConditions:x,onReorderGroups:p,onAddCondition:h,onAddGroup:u,availableFields:y,renderFilterGroup:b,updateConditionFields:m}){const{attributes:g,listeners:w,setNodeRef:E,transform:V,transition:A,isDragging:T}=s.useSortable({id:t.id}),v={transform:s.CSS.Transform.toString(V),transition:A},D=f=>{const{active:I,over:j}=f;if(j&&I.id!==j.id){const k=t.conditions.findIndex(P=>P.id===I.id),R=t.conditions.findIndex(P=>P.id===j.id);k!==-1&&R!==-1&&x(t.id,k,R)}},L=f=>{const{active:I,over:j}=f;if(j&&I.id!==j.id&&a){const k=t.groups.findIndex(P=>P.id===I.id),R=t.groups.findIndex(P=>P.id===j.id);k!==-1&&R!==-1&&p(a,k,R)}};return e.jsxs("div",{ref:E,style:v,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${T?"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",{...g,...w,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:()=>i(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:f=>r(t.id,f),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&&d(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:D,children:e.jsx(s.SortableContext,{items:t.conditions.map(f=>f.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((f,I)=>e.jsx(Ba,{condition:f,index:I,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:o,onUpdateField:c,onRemoveCondition:l,onUpdateGroupOperator:r,availableFields:y,updateConditionFields:m},f.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:L,children:e.jsx(s.SortableContext,{items:t.groups.map(f=>f.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(f=>b(f,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:()=>u(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function yo({filters:t,availableFields:n,onSave:a,onClearAll:r,onCancel:i}){const{currentFilters:d,availableFields:o,isLoading:c,addCondition:l,addGroup:x,removeCondition:p,removeGroup:h,updateCondition:u,updateConditionFields:y,updateGroupOperator:b,updateGroupNegate:m,reorderConditions:g,reorderGroups:w,generateSQLPreview:E,hasAnyFilters:V,setCurrentFilters:A}=ro({initialFilters:t,availableFields:n}),T=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[v,D]=C.useState(!1),L=(j,k,R)=>{const P=N=>N.id===j?{...N,conditions:N.conditions.map(M=>M.id===k?{...M,field:R,dataType:R.dataType}:M)}:{...N,groups:N.groups.map(P)};A(P(d))},f=(j,k=0,R)=>k===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:T,collisionDetection:s.closestCenter,onDragEnd:P=>{const{active:N,over:M}=P;if(M&&N.id!==M.id){const S=j.conditions.findIndex(O=>O.id===N.id),F=j.conditions.findIndex(O=>O.id===M.id);S!==-1&&F!==-1&&g(j.id,S,F)}},children:e.jsx(s.SortableContext,{items:j.conditions.map(P=>P.id),strategy:s.verticalListSortingStrategy,children:j.conditions.map((P,N)=>e.jsx(Ba,{condition:P,index:N,groupId:j.id,groupLogicalOperator:j.logicalOperator,onUpdateCondition:u,onUpdateField:L,onRemoveCondition:p,onUpdateGroupOperator:b,availableFields:o,updateConditionFields:y},P.id))})}),e.jsx(s.DndContext,{sensors:T,collisionDetection:s.closestCenter,onDragEnd:P=>{const{active:N,over:M}=P;if(M&&N.id!==M.id){const S=j.groups.findIndex(O=>O.id===N.id),F=j.groups.findIndex(O=>O.id===M.id);S!==-1&&F!==-1&&w(j.id,S,F)}},children:e.jsx(s.SortableContext,{items:j.groups.map(P=>P.id),strategy:s.verticalListSortingStrategy,children:j.groups.map(P=>f(P,k+1,j.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:()=>l(j.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),v&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>x(j.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},j.id):e.jsx(vo,{group:j,depth:k,parentGroupId:R,onUpdateGroupOperator:b,onUpdateGroupNegate:m,onRemoveGroup:h,onUpdateCondition:u,onUpdateField:L,onRemoveCondition:p,onReorderConditions:g,onReorderGroups:w,onAddCondition:l,onAddGroup:x,availableFields:o,renderFilterGroup:f,updateConditionFields:y},j.id),I=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:[c?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..."})]}):f(d),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:v,onCheckedChange:j=>D(j)}),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)"})]})}),V&&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:E(d)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:i,children:"Cancel"}),I>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>a(V?d:null),children:"Apply Filters"})]})]})}function No({cardId:t,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:i,isOpen:d,onOpenChange:o}){const c=x=>{a(t,x),o(!1)},l=()=>{r(t),o(!1)};return e.jsxs(s.Dialog,{modal:!1,open:d,onOpenChange:o,children:[d&&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:x=>{x.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(yo,{filters:n,availableFields:i,onSave:c,onCancel:()=>o(!1),onClearAll:l})]})]})}function Co({activeCardId:t,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var E,V;const[i,d]=C.useState(null),o=s.useEditorStore(A=>A.card),c=s.useEditorStore(A=>A.actions.updateCardConfig),l=s.useEditorStore(A=>A.actions.setCardPreferences),x=(E=o==null?void 0:o.config)==null?void 0:E.joinPlan,p=C.useCallback(A=>A.entityName===s.CALCULATED_FIELD_ENTITY_MARKER||A.entityName==="calculated_fields"||A.qualifiedEntityName==="calculated_fields",[]),h=(V=o==null?void 0:o.dataSource)==null?void 0:V.semanticDomainId,{data:u}=s.useJoinabilityMap(h),y=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy"),...a("detailColumns")],b=C.useCallback(A=>A.startsWith("card-source-")?"source":A.startsWith("card-")?null:A.startsWith("source-")||n.find(T=>T.id===A)?"source":a("groupBy").find(T=>T.id===A)?"groupBy":a("metrics").find(T=>T.id===A)?"metrics":a("pivotBy").find(T=>T.id===A)?"pivotBy":a("sortBy").find(T=>T.id===A)?"sortBy":a("detailColumns").find(T=>T.id===A)?"detailColumns":null,[n,a]),m=C.useCallback(A=>{d(A.active.id)},[]),g=C.useCallback(A=>{var j;const{active:T,over:v}=A;if(!v||!t){d(null);return}const D=T.id,L=v.id,f=b(D),I=b(L)||L;if(I==="sortBy"){if(f==="source"){const k=n.find(P=>P.id===D);if(!k){d(null);return}if(!(a("groupBy").some(P=>P.name===k.name&&P.qualifiedEntityName===k.qualifiedEntityName)||a("metrics").some(P=>P.name===k.name&&P.qualifiedEntityName===k.qualifiedEntityName)||a("detailColumns").some(P=>P.name===k.name&&P.qualifiedEntityName===k.qualifiedEntityName))){d(null);return}}else if(f==="pivotBy"){d(null);return}else if(f!=="groupBy"&&f!=="metrics"&&f!=="sortBy"&&f!=="detailColumns"){d(null);return}}if(f==="source"&&I==="sortBy"){const k=[...n].find(M=>M.id===D);if(!k){d(null);return}const R=a("sortBy");if(s.fieldAlreadyExists(k,R)){d(null);return}const P=s.validateFieldForChartType(k,"sortBy",o.type);if(!P.isValid){s.ue.error("Invalid Field Type",{description:P.reason,position:"top-center",duration:3e3}),d(null);return}const N=s.getNewField(k,"sortBy",R);d(null),r("sortBy",[...R,N]);return}if(f==="source"&&I!=="source"&&I!=="sortBy"){const k=[...n].find(O=>O.id===D);if(!k){d(null);return}const R=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy"),...a("detailColumns")],P=R.filter(O=>!p(O));if(P.length>0){const O=P[0].qualifiedEntityName;if(!O){d(null);return}if(O!==k.qualifiedEntityName&&!p(k)&&k.qualifiedEntityName)if(h&&(u!=null&&u.joinabilityMap)){if(s.calculateFieldState(k,{joinabilityMap:u.joinabilityMap,selectedFields:R,baseEntityName:(j=x==null?void 0:x.baseEntity)==null?void 0:j.name}).state==="unreachable"){s.showJoinRequiredNotification(),d(null);return}}else{if(!x){s.showJoinRequiredNotification(),d(null);return}if(!s.areEntitiesJoined(O,k.qualifiedEntityName,x)){s.showJoinRequiredNotification(),d(null);return}}}const N=a(I);if(s.fieldAlreadyExists(k,N)){d(null);return}const M=s.validateFieldForChartType(k,I,o.type);if(!M.isValid){s.ue.error("Invalid Field Type",{description:M.reason,position:"top-center",duration:3e3}),d(null);return}const S=s.getNewField(k,I,N),F=[...N,S];if(d(null),r(I,F),I==="metrics"&&t){const O=s.seedSemanticMetricFormatDefaults(o,S,o.preferences);O&&l(O),s.cleanupKpiMetricComparisonMode(o.type,o.config,c,t,F)}return}if(f&&I&&f!=="source"&&I!=="source"&&f!==I){const k=a(f),R=a(I),P=k.find(O=>O.id===D);if(!P){d(null);return}const N=s.validateFieldForChartType(P,I,o.type);if(!N.isValid){s.ue.error("Invalid Field Type",{description:N.reason,position:"top-center",duration:3e3}),d(null);return}const M=s.getNewField(P,I,R);if(d(null),I==="sortBy"){s.fieldAlreadyExists(P,R)||r(I,[...R,M]);return}const S=k.filter(O=>O.id!==D),F=[...R,M];if(r(f,S),r(I,F),I==="metrics"&&t){const O=s.seedSemanticMetricFormatDefaults(o,M,o.preferences);O&&l(O),s.cleanupKpiMetricComparisonMode(o.type,o.config,c,t,F)}return}if(f&&I&&f===I&&f!=="source"){const k=a(f),R=k.findIndex(N=>N.id===D),P=k.findIndex(N=>N.id===L);if(R!==P){const N=s.arrayMove(k,R,P);r(f,N)}}d(null)},[t,n,a,r,b,x,h,u,p,o,c,l]),w=i?y.find(A=>A.id===i):null;return{activeId:i,activeField:w,handleDragStart:m,handleDragEnd:g}}function So({activeView:t,onViewChange:n,splitViewEnabled:a}){const r=s.useEditorStore(c=>c.card),{config:i}=C.useContext(s.SemaphorContext).tokenProps,d=(i==null?void 0:i.showInfoTab)!==!1,o=()=>a?!1:!["table","pivotTable","aggregateTable","detailTable"].includes(r.type);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"}),o()&&e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),r.type!=="kpi"&&d&&e.jsx(s.TabsTrigger,{value:"info",className:"rounded-md transition data-[state=active]:bg-muted",children:"Info"})]})})}const wo=[{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 To(){var l,x;const t=s.useEditorStore(p=>p.card),{updateRowLimit:n}=s.useEditorActions(),[a,r]=C.useState(!1),[i,d]=C.useState(""),o=p=>{if(p==="custom"){r(!0);return}r(!1),n(t.id,parseInt(p))},c=p=>{const h=p.target.value;d(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:i,onChange:c,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((x=(l=t.config)==null?void 0:l.rowLimit)==null?void 0:x.toString())||"100",onValueChange:o,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:wo.map(p=>e.jsx(s.SelectItem,{value:p.value,children:p.label},p.value))})]})})}function Eo({card:t,queryData:n,isLoading:a,isFetching:r,pagination:i,onPaginationChange:d,onSortChange:o,sortState:c,splitViewEnabled:l}){const x=C.useMemo(()=>(n==null?void 0:n.records)||[],[n==null?void 0:n.records]);return!l||["table","pivotTable","aggregateTable","detailTable"].includes(t.type)?e.jsx(nt,{}):e.jsxs(s.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(s.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:e.jsx(nt,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{defaultSize:40,minSize:20,role:"results-section",className:"flex flex-col",children:e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 py-4 pl-2 pr-4",children:[(a||r)&&(n==null?void 0:n.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),(n==null?void 0:n.records)&&e.jsx(s.TableVisual,{card:t,data:x,paginationMetadata:i,onPaginationChange:d,isLoading:a||r,onSortChange:o,sortState:c})]})})]})}const Io="semaphor-split-view-enabled";function ko(){return wa(Io,!0)}function Do({activeView:t,onViewChange:n,onFiltersClick:a,activeCard:r,columns:i}){var z,W,le;const d=s.useEditorStore(X=>X.card),o=s.useDashboardStore(X=>X.filterValues),c=s.useDashboardStore(X=>X.selectedSheetId),l=s.useDashboardStore(X=>X.inlineFilterValuesMap[(r==null?void 0:r.id)||""]),{updateCardConfig:x,setCard:p,updateCardInFrame:h,setShowAIDialog:u}=s.useEditorActions(),y=s.useEditorStore(X=>X.showAIDialog),b=s.useEditorStore(X=>X.isDevMode),m=s.useDashboardStore(X=>X.isVisualEditing),[g,w]=C.useState(!1),[E,V]=C.useState(!1),[A,T]=C.useState(null),{config:v}=C.useContext(s.SemaphorContext).tokenProps,D=(v==null?void 0:v.showInfoTab)!==!1,L=(v==null?void 0:v.showQueryDebugTools)!==!1,[f,I]=ko();s.useEditorStore(X=>{var ne;return!!((ne=X.card.customCardPreferences)!=null&&ne.url)});const{data:j,errorMessage:k,isLoading:R,isFetching:P,errorSql:N,pagination:M,refetch:S,comparisonMetadata:F,queryRequestPayload:O}=s.useDashboardCardQuery(r),$=C.useMemo(()=>(j==null?void 0:j.records)||[],[j==null?void 0:j.records]),[Q,B]=C.useState(!1);C.useEffect(()=>{P||B(!1)},[P]);const K=()=>{const X=!f;X&&t==="table"&&n("chart"),I(X)},se=(X,ne)=>{const ue={...r,paginationConfig:{page:X+1,pageSize:ne}};p(ue),h(ue)},H=X=>{if(!d.config)return;const ne=s.sortStateToSortByColumns(X,d.config.metricColumns,d.config.groupByColumns,d.config.detailColumns);x(d.id,{...d.config,sortByColumns:ne})},te=C.useMemo(()=>{var X;return s.sortByColumnsToSortState((X=d.config)==null?void 0:X.sortByColumns)},[(z=d.config)==null?void 0:z.sortByColumns]);return e.jsx("div",{className:s.cn("relative flex w-0 grow flex-col",{"border-l":y&&m}),children:e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-3",children:[e.jsxs("div",{className:"flex items-center gap-2 pl-2 pr-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t==="chart"&&y&&e.jsx("div",{className:"w-[200px]",children:e.jsx(ot,{variant:b?"secondary":"ghost"})}),e.jsx(So,{activeView:t,onViewChange:n,splitViewEnabled:f}),e.jsx(s.FilterInfo,{cardId:r.id,cardFilters:(W=r.config)==null?void 0:W.filters,cardFilterCount:s.getFilterCount(((le=r.config)==null?void 0:le.filters)||null),onFiltersClick:a,inlineFilters:r.inlineFilters,inlineFilterValues:l,sheetId:c||""}),F&&d.type!=="table"&&e.jsx(s.ComparisonMetadataBadge,{metadata:F,variant:"compact"}),e.jsx("div",{className:"ml-2",children:e.jsx(To,{})}),y&&e.jsx(Ae.EditorClearButton,{})]}),e.jsxs("div",{className:s.cn("flex grow items-center justify-end gap-2"),children:[e.jsx(s.IconButton,{tooltip:"Refresh",disabled:R||P,onClick:()=>{B(!0),S()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":Q})})}),t==="chart"&&e.jsx(Aa,{showInlineFilters:!1,showDisplayOptions:!1}),!y&&e.jsx(s.IconButton,{onClick:()=>u(!y),tooltip:"AI",className:"h-8","aria-label":"AI",children:e.jsx(s.Sparkles,{className:"size-4"})}),t==="chart"&&e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"More Options",className:"h-8","aria-label":"More options",children:e.jsx(s.EllipsisVertical,{className:"size-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(s.DropdownMenuLabel,{children:"More Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:K,children:[f?e.jsx(cn,{className:"mr-2 h-4 w-4"}):e.jsx(Cn,{className:"mr-2 h-4 w-4"}),f?"Hide Results Table":"Show Results Table"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"px-1 py-1",children:[e.jsx(ct,{triggerVariant:"menu",className:"w-full"}),e.jsx(it,{triggerVariant:"menu",className:"w-full"})]})]})]})]})]}),e.jsxs("div",{className:"mt-2 flex min-h-0 grow flex-col",children:[t==="chart"&&e.jsx("div",{className:s.cn("flex grow flex-col pb-4",{"pb-0":f&&!["table","pivotTable","aggregateTable","detailTable"].includes(r.type)}),children:e.jsx(Eo,{card:r,queryData:j,isLoading:R,isFetching:P,pagination:M,onPaginationChange:se,onSortChange:H,sortState:te,splitViewEnabled:f})}),t==="table"&&(j==null?void 0:j.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 py-4 pl-2 pr-4",children:[(R||P)&&(j==null?void 0:j.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),e.jsx(s.TableVisual,{card:r,data:$,comparisonMetadata:F,paginationMetadata:M,onPaginationChange:se,isLoading:R||P,onSortChange:H,sortState:te})]}),t==="info"&&D&&e.jsx("div",{className:"flex min-h-0 flex-1 flex-col pb-4",children:e.jsx("div",{className:"flex min-h-0 flex-1 flex-col rounded-md bg-background pl-2 pr-4",children:k?e.jsx(lt,{error:k,errorSql:N,onSendFeedback:()=>{const X=s.prepareFeedbackData(s.FeedbackCategory.QUERY_GENERATION,{cardConfig:d.config,dataSource:r.dataSource,dashboardFilters:o,errorMessage:k,errorSql:N,generatedSql:j==null?void 0:j.sql});T(X),V(!0)},onOpenInEditor:()=>{u(!0),setTimeout(()=>{const X=s.useEditorStore.getState().actions;X.setIsDevMode(!0),X.setCardSql(N||""),setTimeout(()=>{X.setRunSql(!0)},100)},100)}}):(j==null?void 0:j.sql)&&e.jsx(Ia,{sql:j.sql,showCardDetails:!0,debugPayloads:L?{queryRequest:O,queryResponse:j,columns:i,dashboardFilters:o}:void 0})})})]}),A&&e.jsx(s.FeedbackDialog,{open:E,onOpenChange:V,feedbackData:A})]})})}function Ao({activeField:t}){const[n,a]=C.useState(!0);return C.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(dt,{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 Mo=()=>{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 i;if((i=r.reason)!=null&&i.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 Lo({column:t,isSelected:n,onSelect:a,availableFields:r,width:i,onWidthChange:d}){var O,$,Q;const o=s.useEditorStore(B=>B.card),{updateCardConfig:c,removeGroupByColumn:l,removeMetricColumn:x,updateFilters:p}=s.useEditorActions(),[h,u]=C.useState(!1),[y,b]=C.useState(!1),m=C.useRef(null),g=C.useCallback(B=>{B.preventDefault(),B.stopPropagation(),b(!0),m.current={startX:B.clientX,startWidth:i||150};const K=H=>{if(!m.current)return;const te=H.clientX-m.current.startX,z=Math.max(80,m.current.startWidth+te);d==null||d(t.id,z)},se=()=>{b(!1),m.current=null,document.removeEventListener("mousemove",K),document.removeEventListener("mouseup",se)};document.addEventListener("mousemove",K),document.addEventListener("mouseup",se)},[i,t.id,d]),w=(O=o==null?void 0:o.config)==null?void 0:O.filters,E=($=w==null?void 0:w.conditions)==null?void 0:$.some(B=>B.field.name===t.name&&B.field.qualifiedEntityName===t.qualifiedEntityName),V=B=>{B?p(o.id,B):c(o.id,{filters:void 0})},{attributes:A,listeners:T,setNodeRef:v,transform:D,transition:L,isDragging:f}=s.useSortable({id:t.id}),I={transform:s.CSS.Transform.toString(D),transition:L},j=s.getDataType(t.dataType),k=Oo(j),R=()=>{var se;const B=((se=o==null?void 0:o.config)==null?void 0:se.sortByColumns)||[],K=B.findIndex(H=>H.name===t.name);if(K!==-1){const H=[...B];H[K]={...H[K],direction:"asc"},c(o.id,{sortByColumns:H})}else c(o.id,{sortByColumns:[...B,{...t,id:`sort-${t.id}`,role:"sortby",direction:"asc"}]})},P=()=>{var se;const B=((se=o==null?void 0:o.config)==null?void 0:se.sortByColumns)||[],K=B.findIndex(H=>H.name===t.name);if(K!==-1){const H=[...B];H[K]={...H[K],direction:"desc"},c(o.id,{sortByColumns:H})}else c(o.id,{sortByColumns:[...B,{...t,id:`sort-${t.id}`,role:"sortby",direction:"desc"}]})},N=()=>{var se;const B=((se=o==null?void 0:o.config)==null?void 0:se.groupByColumns)||[];if(!B.some(H=>H.name===t.name)){const H={...t,id:`groupby-${t.id}-${Date.now()}`,role:"groupby"};c(o.id,{groupByColumns:[...B,H]})}},M=B=>{var H;const K=((H=o==null?void 0:o.config)==null?void 0:H.metricColumns)||[];if(!K.some(te=>te.name===t.name&&te.aggregate===B)){const te={...t,id:`metric-${t.id}-${B}-${Date.now()}`,label:`${B} of ${t.label||t.name}`,role:"metric",aggregate:B};c(o.id,{metricColumns:[...K,te]})}},S=()=>{t.role==="groupby"?l(o.id,t.id):t.role==="metric"&&x(o.id,t.id)},F={...I,width:i?`${i}px`:void 0,minWidth:i?`${i}px`:"120px"};return e.jsxs("th",{ref:v,style:F,className:s.cn("group relative border-r border-border bg-background px-1 py-0",f&&"opacity-50",n&&"bg-primary/10",y&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...A,...T,className:"cursor-grab p-1 text-muted-foreground opacity-0 transition-opacity hover:text-foreground group-hover:opacity-100 active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-3 w-3"})}),e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsxs("button",{onClick:a,className:s.cn("flex flex-1 items-center justify-between gap-1 rounded px-2 py-2 text-left text-sm font-medium transition-colors hover:bg-muted/50",n&&"bg-primary/10"),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(k,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:t.label||t.name}),t.role==="metric"&&t.aggregate&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",t.aggregate,")"]}),E&&e.jsx(s.Filter,{className:"h-3 w-3 text-primary"})]}),e.jsx(s.ChevronDown,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsxs(s.DropdownMenuContent,{align:"start",className:"w-48",children:[e.jsxs(s.DropdownMenuItem,{onClick:()=>u(!0),children:[e.jsx(s.Filter,{className:s.cn("mr-2 h-4 w-4",E&&"text-primary")}),E?"Edit Filter":"Filter"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:R,children:[e.jsx(rn,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(s.DropdownMenuItem,{onClick:P,children:[e.jsx(nn,{className:"mr-2 h-4 w-4"}),"Sort Z → A"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuSub,{children:[e.jsxs(s.DropdownMenuSubTrigger,{children:[e.jsx(s.Calculator,{className:"mr-2 h-4 w-4"}),"Summarize"]}),e.jsxs(s.DropdownMenuSubContent,{children:[e.jsx(s.DropdownMenuItem,{onClick:()=>M("SUM"),children:"Sum"}),e.jsx(s.DropdownMenuItem,{onClick:()=>M("AVG"),children:"Average"}),e.jsx(s.DropdownMenuItem,{onClick:()=>M("COUNT"),children:"Count"}),e.jsx(s.DropdownMenuItem,{onClick:()=>M("DISTINCT"),children:"Count Distinct"}),e.jsx(s.DropdownMenuItem,{onClick:()=>M("MIN"),children:"Min"}),e.jsx(s.DropdownMenuItem,{onClick:()=>M("MAX"),children:"Max"})]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:N,children:[e.jsx(Rs,{className:"mr-2 h-4 w-4"}),"Group by this column"]}),e.jsxs(s.DropdownMenuItem,{disabled:!0,children:[e.jsx(rt,{className:"mr-2 h-4 w-4"}),"Pivot by this column"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{disabled:!0,children:[e.jsx(s.EyeOff,{className:"mr-2 h-4 w-4"}),"Hide column"]}),e.jsxs(s.DropdownMenuItem,{onClick:S,className:"text-destructive focus:text-destructive",children:[e.jsx(s.Trash2,{className:"mr-2 h-4 w-4"}),"Remove column"]})]})]})]}),e.jsx("div",{onMouseDown:g,className:s.cn("absolute right-0 top-0 h-full w-1 cursor-col-resize bg-transparent hover:bg-primary/50",y&&"bg-primary")}),e.jsx(Va,{open:h,onOpenChange:u,availableFields:r.length>0?r:[t],existingFilters:w,editingCondition:E?(Q=w==null?void 0:w.conditions)==null?void 0:Q.find(B=>B.field.name===t.name&&B.field.qualifiedEntityName===t.qualifiedEntityName):void 0,onSave:V})]})}function Oo(t){switch(t){case"number":return s.Hash;case"date":return s.Calendar;case"string":default:return s.Type}}function Ro({selectedColumn:t,onColumnSelect:n,isLoading:a=!1,sourceFields:r=[]}){var L,f,I,j;const i=s.useEditorStore(k=>k.card),{updateCardConfig:d}=s.useEditorActions(),[o,c]=C.useState(null),[l,x]=C.useState({}),[p,h]=C.useState(!1),u=C.useMemo(()=>{var P,N;const k=((P=i==null?void 0:i.config)==null?void 0:P.groupByColumns)||[],R=((N=i==null?void 0:i.config)==null?void 0:N.metricColumns)||[];return[...k,...R]},[(L=i==null?void 0:i.config)==null?void 0:L.groupByColumns,(f=i==null?void 0:i.config)==null?void 0:f.metricColumns]),y=C.useMemo(()=>{const k=new Set(u.map(R=>`${R.qualifiedEntityName}.${R.name}`));return r.filter(R=>!k.has(`${R.qualifiedEntityName}.${R.name}`))},[r,u]),{data:b,isLoading:m}=s.useDashboardCardQuery(i),g=(b==null?void 0:b.records)||[],w=C.useCallback((k,R)=>{x(P=>({...P,[k]:R}))},[]),E=C.useCallback(k=>{var M,S;const R=s.getDataType(k.dataType),P=((M=i==null?void 0:i.config)==null?void 0:M.groupByColumns)||[],N=((S=i==null?void 0:i.config)==null?void 0:S.metricColumns)||[];if(R==="number"){const F={...k,id:`metric-${k.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};d(i.id,{metricColumns:[...N,F]})}else{const F={...k,id:`groupby-${k.id}-${Date.now()}`,role:"groupby"};d(i.id,{groupByColumns:[...P,F]})}h(!1)},[(I=i==null?void 0:i.config)==null?void 0:I.groupByColumns,(j=i==null?void 0:i.config)==null?void 0:j.metricColumns,i.id,d]),V=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),A=k=>{c(k.active.id)},T=k=>{const{active:R,over:P}=k;if(c(null),!P||R.id===P.id)return;const N=u.findIndex(S=>S.id===R.id),M=u.findIndex(S=>S.id===P.id);if(N!==-1&&M!==-1){const S=s.arrayMove(u,N,M),F=S.filter($=>$.role==="groupby"),O=S.filter($=>$.role==="metric");d(i.id,{groupByColumns:F,metricColumns:O})}},v=o?u.find(k=>k.id===o):null,D=k=>{let R="";for(;k>=0;)R=String.fromCharCode(k%26+65)+R,k=Math.floor(k/26)-1;return R};return a?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):u.length===0?e.jsx("div",{className:"flex h-full flex-col items-center justify-center gap-4 p-8 text-center",children:e.jsxs("div",{className:"rounded-lg border-2 border-dashed border-muted-foreground/25 p-12",children:[e.jsx("h3",{className:"text-lg font-medium text-muted-foreground",children:"No columns selected"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground/75",children:"Select columns from the panel on the right to build your table"})]})}):e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsxs(s.DndContext,{sensors:V,collisionDetection:s.closestCenter,onDragStart:A,onDragEnd:T,children:[e.jsxs("table",{className:"w-full border-collapse",children:[e.jsxs("thead",{children:[e.jsxs("tr",{className:"border-b border-border bg-muted/30",children:[e.jsx("th",{className:"sticky left-0 z-20 w-12 border-r border-border bg-muted/50 px-2 py-1 text-center text-xs font-medium text-muted-foreground"}),e.jsx(s.SortableContext,{items:u.map(k=>k.id),strategy:s.horizontalListSortingStrategy,children:u.map((k,R)=>e.jsx("th",{style:{width:l[k.id]?`${l[k.id]}px`:void 0,minWidth:l[k.id]?`${l[k.id]}px`:"120px"},className:"border-r border-border bg-muted/30 px-2 py-1 text-center text-xs font-medium text-muted-foreground",children:D(R)},`letter-${k.id}`))}),e.jsx("th",{className:"w-10 border-r border-border bg-muted/30 px-2 py-1"})]}),e.jsxs("tr",{className:"border-b-2 border-border bg-background",children:[e.jsx("th",{className:"sticky left-0 z-20 w-12 border-r border-border bg-muted/50 px-2 py-2 text-center text-xs font-medium text-muted-foreground",children:"#"}),e.jsx(s.SortableContext,{items:u.map(k=>k.id),strategy:s.horizontalListSortingStrategy,children:u.map(k=>e.jsx(Lo,{column:k,isSelected:(t==null?void 0:t.id)===k.id,onSelect:()=>n(k),availableFields:r,width:l[k.id],onWidthChange:w},k.id))}),e.jsx("th",{className:"w-10 border-r border-border bg-background px-1 py-2",children:e.jsxs(s.Popover,{open:p,onOpenChange:h,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Add column",children:e.jsx(s.Plus,{className:"h-4 w-4"})})}),e.jsx(s.PopoverContent,{className:"w-[280px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search columns..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No columns available."}),e.jsx(s.CommandGroup,{heading:"Available Columns",children:y.map(k=>{const R=s.getDataType(k.dataType),P=R==="number"?s.Hash:R==="date"?s.Calendar:s.Type;return e.jsxs(s.CommandItem,{value:k.label||k.name,onSelect:()=>E(k),children:[e.jsx(P,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm",children:k.label||k.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:k.entityName})]})]},k.id)})})]})]})})]})})]})]}),e.jsx("tbody",{children:m?e.jsx("tr",{children:e.jsx("td",{colSpan:u.length+2,className:"h-32 text-center",children:e.jsx(s.LoaderCircle,{className:"mx-auto h-6 w-6 animate-spin text-muted-foreground"})})}):g.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:u.length+2,className:"h-32 text-center text-muted-foreground",children:"No data available"})}):g.slice(0,100).map((k,R)=>e.jsxs("tr",{className:s.cn("border-b border-border transition-colors hover:bg-muted/50",R%2===0?"bg-background":"bg-muted/20"),children:[e.jsx("td",{className:"sticky left-0 z-10 w-12 border-r border-border bg-muted/50 px-2 py-2 text-center text-xs font-medium text-muted-foreground",children:R+1}),u.map(P=>{const N=k[P.name]??k[P.label??""];return e.jsx("td",{style:{width:l[P.id]?`${l[P.id]}px`:void 0,minWidth:l[P.id]?`${l[P.id]}px`:"120px"},className:s.cn("border-r border-border px-3 py-2 text-sm",(t==null?void 0:t.id)===P.id&&"bg-primary/5"),children:e.jsx("span",{className:"block truncate",children:Fo(N,P)})},`${R}-${P.id}`)}),e.jsx("td",{className:"w-10 border-r border-border"})]},R))})]}),e.jsx(s.DragOverlay,{children:v&&e.jsx("div",{className:"rounded border border-primary bg-background px-3 py-2 text-sm font-medium shadow-lg",children:v.label||v.name})})]})}),e.jsxs("div",{className:"flex items-center justify-between border-t border-border bg-muted/30 px-4 py-2 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Showing ",Math.min(g.length,100)," of ",g.length," rows"]}),e.jsxs("span",{children:[u.length," columns"]})]})]})}function Fo(t,n){if(t==null)return"—";if(typeof t=="number")return n.role==="metric"?new Intl.NumberFormat("en-US",{minimumFractionDigits:0,maximumFractionDigits:2}).format(t):t.toString();if(t instanceof Date||typeof t=="string"&&!isNaN(Date.parse(t))){const a=new Date(t);if(!isNaN(a.getTime()))return a.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}return String(t)}function Po({entityGroups:t,isLoading:n=!1}){var V,A;const a=s.useEditorStore(T=>T.card),{updateCardConfig:r,removeGroupByColumn:i,removeMetricColumn:d}=s.useEditorActions(),[o,c]=C.useState(!0),[l,x]=C.useState(""),[p,h]=C.useState(new Set),u=((V=a==null?void 0:a.config)==null?void 0:V.groupByColumns)||[],y=((A=a==null?void 0:a.config)==null?void 0:A.metricColumns)||[],b=T=>{const v=new Set(p);v.has(T)?v.delete(T):v.add(T),h(v)},m=T=>u.some(v=>v.name===T.name&&v.qualifiedEntityName===T.qualifiedEntityName)||y.some(v=>v.name===T.name&&v.qualifiedEntityName===T.qualifiedEntityName),g=(T,v)=>{if(v)if(s.getDataType(T.dataType)==="number"){const L={...T,id:`metric-${T.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};r(a.id,{metricColumns:[...y,L]})}else{const L={...T,id:`groupby-${T.id}-${Date.now()}`,role:"groupby"};r(a.id,{groupByColumns:[...u,L]})}else{const D=u.findIndex(f=>f.name===T.name&&f.qualifiedEntityName===T.qualifiedEntityName),L=y.findIndex(f=>f.name===T.name&&f.qualifiedEntityName===T.qualifiedEntityName);D!==-1&&i(a.id,u[D].id),L!==-1&&d(a.id,y[L].id)}},w=T=>{if(!l)return T;const v=l.toLowerCase();return T.filter(D=>D.name.toLowerCase().includes(v)||D.label&&D.label.toLowerCase().includes(v))},E=T=>{switch(s.getDataType(T)){case"number":return s.Hash;case"date":return s.Calendar;default:return s.Type}};return o?e.jsxs("div",{className:"flex h-full w-72 flex-col border-l border-border bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border px-3 py-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Columns"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:()=>c(!1),title:"Close panel",children:e.jsx(fn,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"border-b border-border p-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search columns...",value:l,onChange:T=>x(T.target.value),className:"h-8 pl-8 text-sm"})]})}),(u.length>0||y.length>0)&&e.jsxs("div",{className:"border-b border-border",children:[u.length>0&&e.jsxs(s.Collapsible,{defaultOpen:!0,children:[e.jsxs(s.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(s.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(Rs,{className:"h-3.5 w-3.5 text-blue-500"}),e.jsx("span",{children:"Groupings"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:u.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:u.map(T=>{const v=E(T.dataType);return e.jsxs("div",{className:"group flex items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted/50",children:[e.jsx(s.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(v,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:T.label||T.name}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>i(a.id,T.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},T.id)})})})]}),y.length>0&&e.jsxs(s.Collapsible,{defaultOpen:!0,children:[e.jsxs(s.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(s.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(s.Calculator,{className:"h-3.5 w-3.5 text-green-500"}),e.jsx("span",{children:"Metrics"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:y.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:y.map(T=>{const v=E(T.dataType);return e.jsxs("div",{className:"group flex items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted/50",children:[e.jsx(s.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(v,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:T.label||T.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:T.aggregate}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>d(a.id,T.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},T.id)})})})]})]}),e.jsx(s.ScrollArea,{className:"flex-1",children:e.jsx("div",{className:"p-2",children:n?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent"})}):t.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No columns available"}):t.map(T=>{const v=w(T.columns);if(v.length===0)return null;const D=p.has(T.entityId)||l.length>0;return e.jsxs(s.Collapsible,{open:D,onOpenChange:()=>b(T.entityId),children:[e.jsxs(s.CollapsibleTrigger,{className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm font-medium hover:bg-muted/50",children:[e.jsx(s.ChevronRight,{className:s.cn("h-3.5 w-3.5 transition-transform duration-200",D&&"rotate-90")}),e.jsx(s.Table2,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate text-left",children:T.label||T.entityName}),e.jsx("span",{className:"text-xs text-muted-foreground",children:v.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:v.map(L=>{const f=E(L.dataType),I=m(L);return e.jsxs("label",{className:s.cn("flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-sm transition-colors hover:bg-muted/50",I&&"bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:I,onCheckedChange:j=>g(L,j),className:"h-3.5 w-3.5"}),e.jsx(f,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:L.label||L.name})]},L.id)})})})]},T.entityId)})})})]}):e.jsx("div",{className:"flex h-full items-start border-l border-border bg-muted/30 p-2",children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>c(!0),title:"Open panel",children:e.jsx(gn,{className:"h-4 w-4"})})})}const Vo=[{name:"SUM",description:"Sum of values",syntax:"SUM([column])"},{name:"AVG",description:"Average of values",syntax:"AVG([column])"},{name:"COUNT",description:"Count of rows",syntax:"COUNT([column])"},{name:"COUNTD",description:"Count distinct values",syntax:"COUNTD([column])"},{name:"MIN",description:"Minimum value",syntax:"MIN([column])"},{name:"MAX",description:"Maximum value",syntax:"MAX([column])"},{name:"IF",description:"Conditional logic",syntax:"IF(condition, then, else)"},{name:"CASE",description:"Multiple conditions",syntax:"CASE WHEN ... THEN ... END"},{name:"CONCAT",description:"Concatenate text",syntax:"CONCAT([col1], [col2])"},{name:"ROUND",description:"Round number",syntax:"ROUND([column], decimals)"},{name:"FLOOR",description:"Round down",syntax:"FLOOR([column])"},{name:"CEIL",description:"Round up",syntax:"CEIL([column])"},{name:"ABS",description:"Absolute value",syntax:"ABS([column])"},{name:"DATEPART",description:"Extract date part",syntax:"DATEPART(year, [date])"},{name:"DATEDIFF",description:"Difference between dates",syntax:"DATEDIFF(day, [date1], [date2])"}];function Bo({value:t,onChange:n,onSubmit:a,onCancel:r,selectedColumn:i,availableColumns:d}){const[o,c]=C.useState(!1),[l,x]=C.useState("column"),p=C.useRef(null);C.useEffect(()=>{const b=m=>{m.key==="Escape"&&t?r():m.key==="Enter"&&t&&!o&&a(t)};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[t,r,a,o]);const h=b=>{const m=`[${b.label||b.name}]`,g=p.current;if(g){const w=g.selectionStart||0,E=g.selectionEnd||0,V=t.slice(0,w)+m+t.slice(E);n(V),setTimeout(()=>{g.setSelectionRange(w+m.length,w+m.length),g.focus()},0)}else n(t+m);c(!1)},u=b=>{const m=p.current;if(m){const g=m.selectionStart||0,w=m.selectionEnd||0,E=t.slice(0,g)+b.syntax+t.slice(w);n(E),setTimeout(()=>{m.setSelectionRange(g+b.name.length+1,g+b.syntax.length-1),m.focus()},0)}else n(t+b.syntax);c(!1)},y=b=>{switch(s.getDataType(b)){case"number":return s.Hash;case"date":return s.Calendar;default:return s.Type}};return e.jsxs("div",{className:"flex items-center gap-2 border-b border-border bg-muted/30 px-3 py-1.5",children:[e.jsx("div",{className:"flex min-w-[100px] items-center justify-center rounded border border-border bg-background px-2 py-1 text-xs font-medium text-muted-foreground",children:i?e.jsx("span",{className:"truncate",children:i.label||i.name}):e.jsx("span",{children:"—"})}),e.jsxs(s.Popover,{open:o&&l==="function",onOpenChange:b=>{c(b),b&&x("function")},children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Insert function",children:e.jsx(Nn,{className:"h-4 w-4"})})}),e.jsx(s.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search functions..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No functions found."}),e.jsx(s.CommandGroup,{heading:"Functions",children:Vo.map(b=>e.jsx(s.CommandItem,{value:b.name,onSelect:()=>u(b),children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-sm font-medium",children:b.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:b.description})]}),e.jsx("span",{className:"font-mono text-xs text-muted-foreground/75",children:b.syntax})]})},b.name))})]})]})})]}),e.jsxs(s.Popover,{open:o&&l==="column",onOpenChange:b=>{c(b),b&&x("column")},children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",className:"h-7 gap-1 px-2 text-xs text-muted-foreground hover:text-foreground",title:"Insert column reference",children:[e.jsx("span",{children:"Columns"}),e.jsx(s.ChevronDown,{className:"h-3 w-3"})]})}),e.jsx(s.PopoverContent,{className:"w-[250px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search columns..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No columns found."}),e.jsx(s.CommandGroup,{heading:"Available Columns",children:d.map(b=>{const m=y(b.dataType);return e.jsxs(s.CommandItem,{value:b.label||b.name,onSelect:()=>h(b),children:[e.jsx(m,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:b.label||b.name})]},b.id)})})]})]})})]}),e.jsx("div",{className:"relative flex-1",children:e.jsx(s.Input,{ref:p,value:t,onChange:b=>n(b.target.value),placeholder:"Enter a formula or select a column...",className:"h-7 border-border bg-background font-mono text-sm"})}),t&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-destructive hover:bg-destructive/10 hover:text-destructive",onClick:r,title:"Cancel (Esc)",children:e.jsx(s.X,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-green-600 hover:bg-green-600/10 hover:text-green-600",onClick:()=>a(t),title:"Apply (Enter)",children:e.jsx(s.Check,{className:"h-4 w-4"})})]})]})}function zo({className:t}){var u,y,b,m;const n=s.useEditorStore(g=>g.card),[a,r]=C.useState(null),[i,d]=C.useState(""),{columns:o=[],columnGroups:c=[],isLoading:l}=s.useColumns();(u=n==null?void 0:n.config)!=null&&u.groupByColumns,(y=n==null?void 0:n.config)!=null&&y.metricColumns,(b=n==null?void 0:n.config)!=null&&b.groupByColumns,(m=n==null?void 0:n.config)!=null&&m.pivotByColumns;const x=g=>{r(g),d(g?`[${g.label||g.name}]`:"")},p=g=>{console.log("Formula submitted:",g),d(""),r(null)},h=()=>{d(""),r(null)};return e.jsxs("div",{className:s.cn("flex h-full w-full flex-col",t),children:[e.jsx(Bo,{value:i,onChange:d,onSubmit:p,onCancel:h,selectedColumn:a,availableColumns:o}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(Ro,{selectedColumn:a,onColumnSelect:x,isLoading:l,sourceFields:o})}),e.jsx(Po,{entityGroups:c,isLoading:l})]})]})}function qo(){var M,S;const[t,n]=C.useState("chart"),[a,r]=C.useState(!1),[i,d]=C.useState(!0),o=s.useEditorStore(F=>F.showAIDialog),c=s.useDashboardStore(F=>F.isVisualEditing),{setCardType:l}=s.useEditorActions(),x=s.useEditorStore(F=>F.card.type);C.useEffect(()=>Mo(),[]);const p=F=>{l(F)},h=s.useEditorStore(F=>F.frame),u=s.useEditorStore(F=>F.card);s.useEditorStore(F=>F.activeTabCardId),s.useEditorStore(F=>F.actions.getAvailableFields);const{addCard:y,removeCard:b,updateCard:m,setActiveCard:g,updateFilters:w}=s.useEditorActions(),{columnFields:E=[],scopedFields:V=[]}=s.useScopedFields(),A=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),T=u,{getFieldsForContainer:v,setFieldsForContainer:D}=s.useFieldManagement(T),{activeField:L,handleDragStart:f,handleDragEnd:I}=Co({activeCardId:h.activeCardId,sourceFields:V,getFieldsForContainer:v,setFieldsForContainer:D}),j=(F,O)=>{O&&w(F,O)},k=F=>{var O;m(F,{config:{...(O=h.cards.find($=>$.id===F))==null?void 0:O.config,filters:void 0}})},R=E,P=F=>{if(!F)return 0;let O=F.conditions.length;return F.groups.forEach($=>{O+=P($)}),O},N=P(((M=T==null?void 0:T.config)==null?void 0:M.filters)||null);return e.jsxs(s.DndContext,{sensors:A,collisionDetection:s.closestCenter,onDragStart:f,onDragEnd:I,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Ta,{isVisible:i,onToggleVisibility:()=>d(!i)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:x==="tableBuilder"?e.jsx(zo,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!o&&e.jsx(no,{selectedChart:x,onChartChange:p,groupByFields:v("groupBy"),pivotByFields:v("pivotBy"),metricsFields:v("metrics"),sortByFields:v("sortBy"),detailFields:v("detailColumns"),activeField:L}),e.jsx(Do,{selectedChart:x,activeView:t,onViewChange:n,onFiltersClick:()=>r(!0),filterCount:N,activeCard:T,columns:E,getFieldsForContainer:v,cards:h.cards,activeCardId:h.activeCardId,addCard:y,setActiveCard:g})]})}),!i&&c&&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:()=>d(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),T&&e.jsx(No,{cardId:T.id,filters:((S=T.config)==null?void 0:S.filters)||null,onFiltersChange:j,onClearFilters:k,availableFields:R,isOpen:a,onOpenChange:r}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Ao,{activeField:L||null})})]})}function $o({authToken:t,onSave:n,onClose:a}){const r=C.useRef(null),i=s.useEditorStore(v=>v.showAIDialog),d=s.useEditorStore(v=>v.isDevMode),o=s.useAssistantLayoutStore(v=>v.setFullscreen),c=s.useAssistantLayoutStore(v=>v.setPanelOpen),l=s.useAssistantLayoutStore(v=>v.setContainer),x=s.useAssistantPanel("editor"),p=s.useFullscreenAssistant(),h=s.useAssistantContainer("editor"),u=p==="editor",y=C.useCallback(v=>{l("editor",v)},[l]),{setAuthToken:b}=s.useDashboardActions(),{setShowAIDialog:m,setOnSave:g,setOnClose:w}=s.useEditorActions(),{setActiveAssistantType:E}=s.useAIActions();C.useEffect(()=>{n&&g(n),a&&w(a)},[n,g,a,w]),C.useEffect(()=>{t&&t.accessToken&&b(t)},[t,b]),C.useEffect(()=>{var v,D;i?((v=r.current)==null||v.resize(40),c("editor",!0),E("editor")):((D=r.current)==null||D.resize(0),c("editor",!1),p==="editor"&&o(null),E(null))},[i,c,E,o,p]);function V(v){var D;v<1?(m(!1),c("editor",!1),p==="editor"&&o(null),E(null),(D=r.current)==null||D.resize(0)):(i||(m(!0),E("editor")),x.isOpen||c("editor",!0))}function A(){return e.jsxs(e.Fragment,{children:[e.jsx(Ta,{isVisible:!0,onToggleVisibility:()=>{}}),e.jsxs("div",{className:"relative flex grow",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:s.cn("grow transition-opacity",u&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Pl,{})}),e.jsx(s.ResizableHandle,{disabled:!i}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:V,defaultSize:x.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(ga,{isFullscreen:u,onFullscreenChange:v=>o(v?"editor":null),fullscreenContainer:h})})})]}),e.jsx("div",{ref:y,className:s.cn("absolute inset-0",!u&&"pointer-events-none")})]})]})}function T(){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",u&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(qo,{})}),e.jsx(s.ResizableHandle,{disabled:!i}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:V,defaultSize:x.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(ga,{isFullscreen:u,onFullscreenChange:v=>o(v?"editor":null),fullscreenContainer:h})})})]}),e.jsx("div",{ref:y,className:s.cn("absolute inset-0",!u&&"pointer-events-none")})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:d?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:A()}):T()})}function _o(){s.useDashboardStore(l=>l.selectedCardId);const t=s.useDashboardStore(l=>l.selectedSheetId),n=s.useDashboardStore(l=>l.dashboard),{setIsVisualEditing:a,setSelectedSheetId:r}=s.useDashboardStore(l=>l.actions),i=s.useDashboardStore(l=>l.isVisualEditing),d=s.useDashboardStore(l=>l.actions.updateFrame);function o(l){var u,y,b;const x=t?(u=n==null?void 0:n.sheets)==null?void 0:u.some(m=>{var g;return m.id===t&&((g=m.frames)==null?void 0:g.some(w=>w.id===l.id))}):!1,p=(b=(y=n==null?void 0:n.sheets)==null?void 0:y.find(m=>{var g;return(g=m.frames)==null?void 0:g.some(w=>w.id===l.id)}))==null?void 0:b.id,h=x?t:p||null;h&&(d(h,l),t!==h&&r(h),a(!1))}function c(){a(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!i}),children:e.jsx($o,{onSave:o,onClose:c})})}exports.default=_o;
|
|
186
|
+
`;o(x)}:void 0}}function Aa({className:t,...n}){var X,ne,me,ee,Ne;const a=s.useEditorStore(q=>q.card);s.useEditorStore(q=>q.isDevMode);const r=((X=a.customCardPreferences)==null?void 0:X.showCardHeader)??!0,i=((me=(ne=a.preferences)==null?void 0:ne.displayOptions)==null?void 0:me.showInlineFilterBar)??!0,d=s.useEditorStore(q=>q.frame),o=s.useDashboardStore(q=>q.dashboard.filters),c=s.useDashboardStore(q=>q.selectedSheetId),[l,x]=C.useState(!1),{currentUser:p}=s.useCurrentUserInfo(),{tokenProps:h}=C.useContext(s.SemaphorContext),u=s.useEditorStore(q=>q.actions.setRunSql),{updateFilter:y}=s.useDashboardActions(),b=o==null?void 0:o.find(q=>q.id===d.filterId),m=C.useMemo(()=>s.findCustomVisualConfigCard(d,a),[d,a]),{manifest:g}=s.useCustomVisual(((ee=m==null?void 0:m.customCardPreferences)==null?void 0:ee.url)||""),w=C.useMemo(()=>{var q;return(q=g==null?void 0:g.visuals)==null?void 0:q.find(Z=>{var ie;return Z.name===((ie=m==null?void 0:m.customCardPreferences)==null?void 0:ie.componentName)})},[g,(Ne=m==null?void 0:m.customCardPreferences)==null?void 0:Ne.componentName]),E=s.resolveMultiInputType(m,w),V=C.useMemo(()=>s.getCustomVisualInputCards({frame:d,configCard:m,isMultiInputVisual:E==="multiple"}),[d,m,E]),A=C.useMemo(()=>{const q=V.findIndex(Z=>(Z==null?void 0:Z.id)===(a==null?void 0:a.id));return q<0?-1:s.getSlotIndexForCard(a,q)},[V,a]),T=C.useMemo(()=>!m||E!=="multiple"||A<0?a.type:s.getEffectiveCardTypeForSlot(a,A,w==null?void 0:w.slots)??a.type,[m,E,A,a,w==null?void 0:w.slots]),v=T??a.type,D=C.useMemo(()=>v===a.type?a:{...a,type:v},[a,v]),M=C.useMemo(()=>T!==a.type?{...a,type:T}:a,[a,T]),{data:f,isLoading:I,isFetching:j,errorMessage:k,errorSql:R,pagination:P}=s.useDashboardCardQuery(M),{handleOpenInEditor:N,handleDebugWithAssistant:L}=Da(k,R||a.sql||a.python),S=C.useMemo(()=>(f==null?void 0:f.records)||[],[f==null?void 0:f.records]),{setCard:F,updateCardInFrame:O}=s.useEditorActions(),{data:_}=s.useTopoJson(D),Q=C.useMemo(()=>{var q;return v!=="pivotTable"||!((q=f==null?void 0:f.records)!=null&&q.length)?null:{records:f.records,columnSubtotalMeta:f.columnSubtotalMeta,subtotalColumns:f.subtotalColumns||[],pivotSchema:f.pivotSchema||[],groupByColumns:f.groupByColumns}},[v,f==null?void 0:f.records,f==null?void 0:f.columnSubtotalMeta,f==null?void 0:f.subtotalColumns,f==null?void 0:f.pivotSchema,f==null?void 0:f.groupByColumns]),B=s.usePivotTableConfig(D,Q),K=()=>{x(!0)},se=C.useMemo(()=>{const q=typeof window<"u"?window.location.href:"",Z=typeof navigator<"u"?navigator.userAgent:"",ie=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:s.FeedbackCategory.QUERY_GENERATION,user:p,tokenContext:h,systemState:{cardConfig:a.config,dataSource:a.dataSource,dashboardFilters:o,errorMessage:k||void 0,errorSql:R||a.sql||a.python,generatedSql:R||a.sql},metadata:{url:q,userAgent:Z,timestamp:new Date().toISOString(),viewport:ie}}},[p,h,a,o,k,R]),H=(q,Z)=>{var je,ke;const ie={...a,paginationConfig:{page:q+1,pageSize:Z}};F(ie),O(ie),a.sql&&((ke=(je=a.preferences)==null?void 0:je.tablePrefs)!=null&&ke.enableDevModePagination)&&u(!0)},te=q=>{var je,ke,Me,we,be;const Z=s.sortStateToSortByColumns(q,(je=a.config)==null?void 0:je.metricColumns,(ke=a.config)==null?void 0:ke.groupByColumns,(Me=a.config)==null?void 0:Me.detailColumns),ie={...a,config:{...a.config||{},sortByColumns:Z}};F(ie),O(ie),a.sql&&((be=(we=a.preferences)==null?void 0:we.tablePrefs)!=null&&be.enableDevModePagination)&&u(!0)},z=C.useMemo(()=>!D.id||!(f!=null&&f.records)?null:s.createChartConfig({card:D,data:f==null?void 0:f.records,cardType:v,queryConfig:D.queryConfig,customCfg:D.customCfg,preferences:D.preferences,topoJson:_}),[D,f==null?void 0:f.records,v,_]);function W(q){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(s.EditorCustomVisual,{card:q})})}function le(){var q;if(f!=null&&f.records&&(f==null?void 0:f.records.length)===0&&!I&&!j)return k?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(ot,{error:k,errorSql:R||a.sql||a.python,onOpenInEditor:N,onDebugWithAssistant:L,onSendFeedback:K,showFeedbackButton:!0})}):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((I||j)&&(!(f!=null&&f.records)||f.records.length===0))return v==="table"||v==="detailTable"?e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableSkeleton,{})}):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(!D.id)return null;if(v==="custom")return W(a);if(!["table","pivotTable","aggregateTable","detailTable","custom"].includes(v)&&z)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:I||j?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:z})});if(v==="table"||v==="detailTable")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:D,data:S,comparisonMetadata:(q=f==null?void 0:f.metadata)==null?void 0:q.comparisonMetadata,paginationMetadata:P,onPaginationChange:H,onSortChange:te,isLoading:I||j})});if(v==="pivotTable"&&B)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:D,data:B.data,options:B.options,onAggregationChange:Z=>{const ie=s.handleAggregationChange(Z,a.config),je={...a,config:ie};F(je),O(je)},onAggregationLabelChange:Z=>{const ie=s.handleAggregationLabelChange(Z,a.config),je={...a,config:ie};F(je),O(je)}})});if(v==="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:D,data:(f==null?void 0:f.records)||[],groupByColumns:f==null?void 0:f.groupByColumns,pivotSchema:f==null?void 0:f.pivotSchema,paginationMetadata:P,onPaginationChange:H,onAggregationChange:Z=>{const ie=s.handleAggregationChange(Z,a.config),je={...a,config:ie};F(je),O(je)},isLoading:I||j})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...n,children:[(I||j)&&(f==null?void 0:f.records)&&f.records.length>0&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),r&&e.jsxs(s.CardHeader,{className:s.cn("flex flex-row items-start justify-between py-4 pr-6","pl-2"),children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.CardTitle,{className:"text-base",children:e.jsx(s.EditableText,{value:a.title,onSave:q=>F({...a,title:q}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(s.InfoHover,{card:a}),e.jsx(Ae.VisualBadge,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(Jn,{})})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:(a.description||"").trim(),onSave:q=>F({...a,description:q.trim()}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),b&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:b.title||b.column,onSave:q=>y({...b,title:q}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:b})]})]}),i&&a.inlineFilters&&a.inlineFilters.length>0&&e.jsx("div",{className:s.cn("pb-3 pr-6","pl-2"),children:e.jsx(s.InlineFilterBar,{card:a,sheetId:c||""})}),e.jsxs(s.CardContent,{className:s.cn("flex min-h-0 grow flex-col pr-6","pl-2"),children:[e.jsx("div",{className:"min-h-0 flex-1 grow basis-0",children:le()}),s.isCardSummaryVisibleOnCard(D)&&e.jsx("div",{className:"pt-3",children:e.jsx(s.CardSummary,{card:D,mode:"editor"})})]}),e.jsx(s.FeedbackDialog,{open:l,onOpenChange:x,feedbackData:se,showDebugInfo:!0})]})}const Ys=({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}),Qn=()=>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."})]})]}),Yn=({customCode:t,cardCustomCfgString:n,mergedConfig:a,onConfigChange:r,onCodeChange:i})=>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(Ys,{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(Ys,{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(Ys,{language:"javascript",value:t,onChange:i})})]}),Wn=({error:t,hasCardCustomConfig:n,onReset:a,onApply:r,onClose:i})=>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:i,variant:"outline",children:"Close"})]});function Xn({triggerVariant:t="icon",className:n,label:a="Customize Visual"}={}){const[r,i]=C.useState(!1),[d,o]=C.useState(""),[c,l]=C.useState(""),[x,p]=C.useState(""),[h,u]=C.useState(""),y=s.useEditorStore(I=>I.card),b=Ae.useEffectiveEditorCardType(),m=s.useEditorStore(I=>I.card.customCfg),g=m?JSON.stringify(m,null,2):"",w=C.useMemo(()=>b!==y.type?{...y,type:b}:y,[y,b]),{data:E}=s.useDashboardCardQuery(w),{data:V}=s.useTopoJson(y),{setCardCustomCfg:A,setCustomVisualCode:T}=s.useEditorActions(),v=I=>{var j,k;return JSON.stringify({...I,data:{...I.data,datasets:(k=(j=I.data)==null?void 0:j.datasets)==null?void 0:k.map(R=>({...R,data:[]}))}},null,2)},D=()=>{var j,k;if(!((j=E==null?void 0:E.records)!=null&&j.length))return;const I=s.createChartConfig({card:y,data:E.records,cardType:y.type,queryConfig:y.queryConfig,preferences:y.preferences,topoJson:V});if(I){o(v(I)),p(((k=y.preferences)==null?void 0:k.customVisualCode)||"");const R=s.merge(I,m);l(v(R))}},M=()=>{try{if(x&&T(x),c){const I=JSON.parse(c),j=s.getObjectDiff(JSON.parse(d),I);A(j),u("")}}catch{u("Invalid JSON configuration")}},f=Object.keys(m||{}).length===0;return e.jsxs(s.Dialog,{open:r,onOpenChange:i,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:t==="menu"?e.jsxs(s.Button,{variant:"ghost",onClick:D,className:s.cn("h-8 w-full justify-start gap-2 px-2 text-sm",f?"":"text-green-600 hover:text-green-700",n),children:[e.jsx(s.Settings,{className:"h-4 w-4"}),e.jsx("span",{children:a})]}):e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:D,className:s.cn(f?"":"text-green-600 hover:text-green-700",n),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(Qn,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Aa,{className:"w-1/2 rounded shadow-none"})}),e.jsx(Yn,{customCode:x,cardCustomCfgString:g,mergedConfig:c,onConfigChange:I=>l(I??""),onCodeChange:I=>p(I??"")})]}),e.jsx(Wn,{error:h,hasCardCustomConfig:!!m,onReset:()=>{l(d),A(null)},onApply:M,onClose:()=>i(!1)})]})]})}function Zn({isStarred:t,onClick:n,className:a}){const r=i=>{i.stopPropagation(),i.preventDefault(),n(i)};return e.jsx("button",{type:"button",onClick:r,className:s.cn("flex items-center justify-center rounded-sm p-0.5 transition-all","hover:bg-muted/80",a),"aria-label":t?"Remove from favorites":"Add to favorites",children:e.jsx(s.Star,{className:s.cn("h-3.5 w-3.5 transition-colors",t?"fill-yellow-400 text-yellow-400":"text-muted-foreground hover:text-foreground")})})}function la({chartType:t,chartName:n,isCustom:a=!1,pluginName:r,isStarred:i,showStar:d=!0,onSelect:o,onToggleStar:c}){return e.jsxs("button",{onClick:o,className:s.cn("group relative flex flex-col items-center gap-2 rounded-lg border border-border","bg-background p-3 transition-all","hover:border-primary/50 hover:bg-muted/50 hover:shadow-sm"),children:[d&&e.jsx("div",{className:s.cn("absolute left-1 top-1 transition-opacity",i?"opacity-100":"opacity-0 group-hover:opacity-100"),children:e.jsx(Zn,{isStarred:i,onClick:()=>c()})}),a&&r&&e.jsx("div",{className:"absolute right-1 top-1",children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center justify-center",children:e.jsx(s.Info,{className:"h-3 w-3 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"top",className:"text-xs",children:r})]})}),e.jsx(s.ChartIcon,{chartType:t,chartName:n,isCustom:a,className:"h-6 w-6"}),e.jsx("span",{title:n,className:"line-clamp-2 text-center text-xs font-medium text-foreground",children:n})]})}const oa=[{id:"table",name:"Table"},{id:"bar",name:"Bar Chart"},{id:"line",name:"Line Chart"},{id:"area",name:"Area Chart"},{id:"combo",name:"Combo Chart"},{id:"stackedBar",name:"Stacked Bar"},{id:"stackedArea",name:"Stacked Area"},{id:"stackedLine",name:"Stacked Line"},{id:"scatter",name:"Scatter"},{id:"bubble",name:"Bubble"},{id:"pie",name:"Pie Chart"},{id:"doughnut",name:"Doughnut"},{id:"funnel",name:"Funnel"},{id:"radar",name:"Radar"},{id:"polarArea",name:"Polar Area"},{id:"tornado",name:"Tornado"},{id:"range",name:"Range"},{id:"bullet",name:"Bullet Chart"},{id:"treemap",name:"Treemap"},{id:"heatmap",name:"Heatmap"},{id:"kpi",name:"KPI"},{id:"text",name:"Text"},{id:"map",name:"Map"}];function er({onChartSelect:t,onClose:n}){const[a,r]=C.useState(""),{starredCharts:i,isStarred:d,toggleStar:o}=s.useStarredChartsStore(),{data:c=[],isLoading:l}=s.useCustomVisualsQuery(),{setCardType:x,setCardPreferences:p,setIsDevMode:h}=s.useEditorStore(f=>f.actions),u=s.useEditorStore(f=>f.card),{setCardCustomCfg:y,setCustomCardPreferences:b,setQueryConfig:m,replaceFrameCards:g,clearModeDrafts:w,initializeModeDrafts:E}=s.useEditorActions(),V=C.useMemo(()=>{if(!a)return oa;const f=a.toLowerCase();return oa.filter(I=>I.name.toLowerCase().includes(f))},[a]),A=C.useMemo(()=>{const f=c.filter(j=>j.componentType==="chart"&&j.pluginType!=="standard");if(!a)return f;const I=a.toLowerCase();return f.filter(j=>j.name.toLowerCase().includes(I))},[c,a]),T=f=>{y(null),p({}),x(f),["custom","text","map"].includes(f)&&(h(!0),m(void 0)),t==null||t(f),n==null||n()},v=f=>{y(null),p({}),m(void 0);const I=s.resolveMultiInputTypeFromVisual(f);if(I==="multiple"&&f.slots&&f.slots.length>0){w();const k=s.createCardsFromSlots(f.slots,f,u);g(k),k[0]&&E(k[0]),n==null||n();return}else x("custom"),b({type:"component",visualType:I,url:f.url,componentName:f.name,icon:f.icon,pluginChartType:f.chartType,minInputs:f.minInputs,maxInputs:f.maxInputs});t==null||t("custom",f),n==null||n()},D=f=>{const I={type:"default",id:f.id,name:f.name};o(I)},M=f=>{const I={type:"custom",id:f.name,url:f.url,icon:f.icon,name:f.name};o(I)};return e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2 rounded-sm border border-border bg-background px-3 py-2",children:[e.jsx(s.Search,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search charts...",value:a,onChange:f=>r(f.target.value),className:"h-auto border-0 p-0 text-sm focus-visible:ring-0 focus-visible:ring-offset-0"})]}),e.jsxs("div",{className:"max-h-[350px] overflow-y-auto",children:[V.length>0&&e.jsx("div",{className:"mb-3",children:e.jsx("div",{className:"grid grid-cols-3 gap-2",children:V.map(f=>e.jsx(la,{chartType:f.id,chartName:f.name,isCustom:!1,isStarred:d("default",f.id),onSelect:()=>T(f.id),onToggleStar:()=>D(f)},f.id))})}),A.length>0&&e.jsxs(e.Fragment,{children:[V.length>0?e.jsx(s.Separator,{className:"my-3"}):null,e.jsxs("div",{children:[e.jsx("span",{className:"mb-2 block text-xs font-medium text-muted-foreground",children:"Custom Charts"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:A.map((f,I)=>e.jsx(la,{chartName:f.name,isCustom:!0,pluginName:f.pluginName,isStarred:d("custom",f.name),onSelect:()=>v(f),onToggleStar:()=>M(f)},`${f.url}-${f.name}-${I}`))})]})]}),l&&e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-3"}),e.jsx("div",{className:"py-4 text-center text-sm text-muted-foreground",children:"Loading custom charts..."})]}),V.length===0&&A.length===0&&!l&&e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No charts found"})]})]})}function sr({selectedChart:t,onChartChange:n}){var v,D,M,f;const a=s.useEditorStore(I=>I.card),r=s.useEditorStore(I=>I.frame),i=s.useEditorStore(I=>I.isDevMode),{replaceFrameCards:d,clearModeDrafts:o,initializeModeDrafts:c,setIsDevMode:l}=s.useEditorActions(),x=C.useMemo(()=>s.findCustomVisualConfigCard(r,a),[r,a]),{manifest:p}=s.useCustomVisual(((v=x==null?void 0:x.customCardPreferences)==null?void 0:v.url)||""),h=C.useMemo(()=>{var I;return(I=p==null?void 0:p.visuals)==null?void 0:I.find(j=>{var k;return j.name===((k=x==null?void 0:x.customCardPreferences)==null?void 0:k.componentName)})},[p,(D=x==null?void 0:x.customCardPreferences)==null?void 0:D.componentName]),u=s.resolveMultiInputType(x,h)==="multiple",y=Ae.useEffectiveEditorCardType(),b=u?y:t??a.type,m=(M=a==null?void 0:a.customCardPreferences)==null?void 0:M.componentName,g=(f=x==null?void 0:x.customCardPreferences)==null?void 0:f.componentName,w=u&&!!g,E=C.useMemo(()=>{const I=s.chartTypes.find(j=>j.id===b);return I?I.label:b==="custom"?m||"Custom Visual":"Select chart type"},[b,m]),V=C.useMemo(()=>{const I=s.chartTypes.find(j=>j.id===b);if(I){const j=I.icon;return e.jsx(j,{className:"h-4 w-4"})}if(b==="custom"&&m){const j=s.getAutoDetectedChartIcon(m);return j||e.jsx(s.ChartIcon,{chartName:m,isCustom:!0,className:"h-4 w-4"})}return e.jsx(vn,{className:"h-4 w-4"})},[b,m]);return{displayChartType:b,displayLabel:E,displayIcon:V,showBadge:w,badgeLabel:g,isMultiInputContext:u,handleChartSelect:I=>{n==null||n(I)},handleClearCustomVisual:I=>{I.stopPropagation();const j={...a,type:"bar",sql:"",python:"",config:void 0,queryConfig:void 0,customCfg:void 0,preferences:{},customCardPreferences:void 0,title:"Chart",tabTitle:"Chart",description:void 0,info:void 0};d([j]),o(),c(j),i&&l(!0),n==null||n("bar")}}}function it({selectedChart:t,onChartChange:n,variant:a="ghost",className:r}){const[i,d]=C.useState(!1),{displayLabel:o,displayIcon:c,showBadge:l,badgeLabel:x,handleChartSelect:p,handleClearCustomVisual:h}=sr({selectedChart:t,onChartChange:n});return e.jsxs("div",{className:s.cn("relative w-full",r),children:[e.jsxs(s.Popover,{open:i,onOpenChange:d,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:a,role:"combobox","aria-expanded":i,className:s.cn("w-full justify-between gap-2",a==="ghost"&&"border border-border/70 bg-background text-foreground/90",a==="outline"&&"border-border/70 bg-background text-foreground/90",a==="secondary"&&"text-foreground"),children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c,e.jsx("span",{className:"truncate",children:o})]}),e.jsx(s.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-70"})]})}),e.jsx(s.PopoverContent,{className:"w-[360px] p-3",align:"start",onOpenAutoFocus:u=>u.preventDefault(),children:e.jsx(er,{onChartSelect:u=>p(u),onClose:()=>d(!1)})})]}),l&&e.jsxs("div",{className:"absolute right-10 top-1/2 z-10 flex max-w-[140px] -translate-y-1/2 items-center gap-1 rounded-full border bg-background py-0.5 pl-2 pr-1 text-[10px] text-muted-foreground shadow-sm",title:x,children:[e.jsx(s.Layers,{className:"h-2.5 w-2.5 shrink-0"}),e.jsx("span",{className:"truncate",children:x}),e.jsx("button",{onClick:h,className:"rounded-full p-0.5 hover:bg-muted",title:"Clear custom visual",children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]})]})}function tr(){const t=s.useEditorStore(l=>{var x,p;return(p=(x=l.card.preferences)==null?void 0:x.chartOptions)==null?void 0:p.indexAxis}),n=s.useEditorStore(l=>l.card.type),{setChartOrientation:a,setCardPreferences:r}=s.useEditorStore(l=>l.actions),i=l=>{if(a(l),n!=="bullet")return;const x=l==="y"?"horizontal":"vertical",p=s.useEditorStore.getState().card.preferences,h={...p||{},bulletConfig:{...(p==null?void 0:p.bulletConfig)||{},orientation:x}};r(h)};function d(){const l=t??"x",x=()=>{i(l==="x"?"y":"x")};return e.jsx(s.IconButton,{onClick:x,tooltip:"Chart Orientation",children:l==="x"?e.jsx(Js,{className:"size-4"}):e.jsx(Hs,{className:"size-4"})})}function o(){const l=()=>{i(t==="y"||t===void 0?"x":"y")};return e.jsx(s.IconButton,{onClick:l,tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(Js,{className:"size-4"}):e.jsx(Hs,{className:"size-4"})})}function c(){const l=t??"y",x=()=>{i(l==="y"?"x":"y")};return e.jsx(s.IconButton,{onClick:x,tooltip:"Chart Orientation",children:l==="y"?e.jsx(Hs,{className:"size-4"}):e.jsx(Js,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?o():n==="bullet"?c():d()})}function ct({className:t,triggerVariant:n="icon",label:a="Display Options"}){var m,g,w,E,V,A,T,v,D,M;const r=s.useEditorStore(f=>f.card),{setCardPreferences:i,updateCardInFrame:d,setCard:o}=s.useEditorActions(),[c,l]=C.useState(!1),x=((g=(m=r.preferences)==null?void 0:m.displayOptions)==null?void 0:g.showFilterInfo)??!0,p=((E=(w=r.preferences)==null?void 0:w.displayOptions)==null?void 0:E.showCardToolbar)??!0,h=((A=(V=r.preferences)==null?void 0:V.displayOptions)==null?void 0:A.showChrome)??!0,u=((v=(T=r.preferences)==null?void 0:T.displayOptions)==null?void 0:v.allowScroll)??!0,y=((M=(D=r.preferences)==null?void 0:D.displayOptions)==null?void 0:M.showInlineFilterBar)??!0,b=(f,I)=>{var R;const j={...r.preferences,displayOptions:{...(R=r.preferences)==null?void 0:R.displayOptions,[f]:I}};i(j);const k={...r,preferences:j};o(k),d(k)};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsxs(s.DropdownMenu,{modal:!1,open:c,onOpenChange:l,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:n==="menu"?e.jsxs(s.Button,{variant:"ghost",className:"h-8 w-full justify-start gap-2 px-2 text-sm",children:[e.jsx(nt,{className:"h-4 w-4"}),e.jsx("span",{children:a})]}):e.jsx(s.IconButton,{className:"h-8 w-8 p-0",tooltip:"Display Options",children:e.jsx(nt,{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:x,onCheckedChange:f=>{b("showFilterInfo",f)},onSelect:f=>f.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:p,onCheckedChange:f=>{b("showCardToolbar",f)},onSelect:f=>f.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:h,onCheckedChange:f=>{b("showChrome",f)},onSelect:f=>f.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:u,onCheckedChange:f=>{b("allowScroll",f)},onSelect:f=>f.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"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:y,onCheckedChange:f=>{b("showInlineFilterBar",f)},onSelect:f=>f.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Inline Filter Bar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card filters"})]})]})]})})}function dt({className:t,triggerVariant:n="icon",label:a="Inline Filters"}){const[r,i]=C.useState(!1),d=s.useEditorStore(m=>m.card),o=s.useEditorStore(m=>m.selectedConnectionId),{setCard:c}=s.useEditorActions(),l=s.useDashboardStore(m=>m.actions.removeCardInlineFilterValue),x=(d==null?void 0:d.inlineFilters)||[];function p(m){var I,j,k,R,P;const g=((k=(j=(I=d==null?void 0:d.dataSource)==null?void 0:I.selectedEntities)==null?void 0:j[0])==null?void 0:k.database)||"",w=m.qualifiedFieldName||m.name;if(x.find(N=>N.column===w))return;const V=m.qualifiedFieldName?m.qualifiedFieldName.split(".").slice(0,-1).join("."):m.qualifiedEntityName||m.entityName,T=s.fmt(m.name),v=s.buildFilterFieldMeta(m),D=s.buildFilterSemanticContext(d==null?void 0:d.dataSource,{connectionId:o||((R=d==null?void 0:d.dataSource)==null?void 0:R.connectionId),connectionType:(P=d==null?void 0:d.dataSource)==null?void 0:P.connectionType}),M=s.isCalculatedFilterField(v),f={id:s.v4(),column:w,title:m.label||m.name,dataType:m.dataType,table:m.entityName||"",database:g,connectionId:o||"",operation:"in",sql:M?"":s.getDefaultFilterSql(m.dataType,V,T),fieldMeta:v,semanticContext:D,width:250};c({...d,inlineFilters:[...x,f]})}function h(m){const g=x.filter(w=>w.id!==m);c({...d,inlineFilters:g}),l(d.id,m)}function u(m,g){const w=x.map(E=>E.id===m?{...E,...g}:E);c({...d,inlineFilters:w})}if(!["bar","line","pie","doughnut","table","detailTable","stackedBar","stackedLine","horizontalBar","radar","polarArea","scatter","bubble","funnel","aggregateTable","custom"].includes(d==null?void 0:d.type))return null;const b=n==="menu";return e.jsx("div",{className:s.cn("flex items-center gap-1",b&&"w-full",t),children:e.jsxs(s.Popover,{open:r,onOpenChange:i,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:b?e.jsxs(s.Button,{variant:"ghost",className:s.cn("h-8 w-full justify-start gap-2 px-2 text-sm",x.length>0&&"text-primary"),children:[e.jsx(Wt,{className:"h-4 w-4"}),e.jsx("span",{children:a}),x.length>0&&e.jsx("span",{className:"ml-auto inline-flex min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[10px] font-medium text-primary-foreground",children:x.length})]}):e.jsxs(s.IconButton,{tooltip:"Add Inline Filter",className:s.cn("relative",{"text-primary":x.length>0}),children:[e.jsx(Wt,{className:"h-4 w-4"}),x.length>0&&e.jsx("span",{className:"absolute -right-1 -top-1 flex h-4 w-4 items-center justify-center rounded-full bg-primary text-[10px] font-medium text-primary-foreground",children:x.length})]})}),e.jsx(s.PopoverContent,{align:"end",className:s.cn("w-80 p-0",b&&"z-[60]"),children:e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"border-b px-4 py-3",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Inline Filters"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"On-card filters for fast, focused exploration."})]}),e.jsx("div",{className:"flex max-h-[300px] flex-col overflow-hidden",children:e.jsx(s.DndContext,{collisionDetection:s.closestCenter,children:e.jsx(s.SortableContext,{items:[],strategy:s.verticalListSortingStrategy,children:e.jsx(s.FieldsList,{context:"inline-filter",onFieldSelect:p,inlineFilters:x})})})}),x.length>0&&e.jsxs("div",{className:"border-t px-4 py-3",children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Active Filters"}),e.jsx("div",{className:"space-y-1",children:x.map(m=>e.jsx(ar,{filter:m,onUpdate:g=>u(m.id,g),onRemove:()=>h(m.id)},m.id))})]})]})})]})})}function ar({filter:t,onUpdate:n,onRemove:a}){return e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-muted px-2 py-1.5 text-sm",children:[e.jsx("span",{className:"truncate",title:t.column,children:t.title}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(s.CustomFilterPopover,{filter:t,variant:"inline",onAccept:r=>n(r),trigger:e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0",title:"Configure filter",children:e.jsx(s.Settings2,{className:"h-3 w-3"})})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0 hover:bg-destructive/10 hover:text-destructive",onClick:a,children:e.jsx(s.X,{className:"h-3 w-3"})})]})]})}function La({showOrientation:t=!0,showGridStyle:n=!0,showInlineFilters:a=!0,showDisplayOptions:r=!0}={}){const i=s.useEditorStore(u=>u.card),d=s.useEditorStore(u=>{var y,b;return(b=(y=u.card)==null?void 0:y.preferences)==null?void 0:b.chartOptions}),o=s.getChartGridStyle(d),{setChartGrid:c}=s.useEditorActions();function l(){const u=["xy","none","x","y"],b=(u.indexOf(o)+1)%u.length;c(u[b])}const x=t&&["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel","bullet"].includes(i.type),p=n&&!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(i.type);return x||p||a||r?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[x&&e.jsx(e.Fragment,{children:e.jsx(tr,{})}),p&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:l,children:[(o==="xy"||!o)&&e.jsx(s.Grid3x3,{className:"size-4"}),o==="x"&&e.jsx(lt,{className:"size-4"}),o==="y"&&e.jsx(Fs,{className:"size-4"}),o==="none"&&e.jsx(s.Square,{className:"size-4"})]}),a&&e.jsx(dt,{}),r&&e.jsx(ct,{})]}):null}function nr({isPreviewMode:t,onPreviewToggle:n,configCard:a}){var P,N,L,S,F;const r=s.useEditorStore(O=>O.frame),i=s.useEditorStore(O=>O.card),{setFrame:d,setActiveTabCardId:o,setCard:c,updateCardInFrame:l,clearModeDrafts:x,initializeModeDrafts:p}=s.useEditorActions(),{manifest:h}=s.useCustomVisual(((P=a==null?void 0:a.customCardPreferences)==null?void 0:P.url)||""),u=(N=h==null?void 0:h.visuals)==null?void 0:N.find(O=>{var _;return O.name===((_=a==null?void 0:a.customCardPreferences)==null?void 0:_.componentName)}),b=s.resolveMultiInputType(a,u)==="multiple",m=(u==null?void 0:u.minInputs)??((L=a==null?void 0:a.customCardPreferences)==null?void 0:L.minInputs)??1,g=(u==null?void 0:u.maxInputs)??((S=a==null?void 0:a.customCardPreferences)==null?void 0:S.maxInputs),w=C.useMemo(()=>s.getCustomVisualInputCards({frame:r,configCard:a,isMultiInputVisual:b}),[r,a,b]),E=b?w.filter(Boolean).length:r.cards.length,V=g?E<g:!0,A=E>Math.max(m||1,1),T=!!((F=a==null?void 0:a.customCardPreferences)!=null&&F.dataInputCardIds),v=(O,_)=>{O.dataTransfer.setData("tabIndex",_.toString())},D=O=>{O.preventDefault()},M=(O,_)=>{const Q=O.dataTransfer.getData("tabIndex");if(Q===_.toString())return;const B=Array.from(r.cards),[K]=B.splice(parseInt(Q),1);B.splice(_,0,K),d({...r,cards:B})};function f(O){const _=(a==null?void 0:a.id)===O;if(!(T&&_?r.cards.length>1:A))return;let B=r.cards.filter(te=>te.id!==O);b&&!T&&(B=s.reindexSlotCards(B));const K=B[0],se={...r,cards:B,activeCardId:K.id},H=O===i.id;H&&x(),d(se),o(K.id),c(K),H&&p(K)}function I(O,_){if(!V)return;const Q={...r,cards:[...r.cards,_],activeCardId:O.id};d(Q),o(_.id)}function j(){if(b&&(a==null?void 0:a.id)===i.id){k(i);return}const O={...i,id:s.v4(),title:`${i.title} Copy`,tabTitle:`${i.tabTitle||i.title} Copy`,customCardPreferences:i.customCardPreferences?{...i.customCardPreferences,slotIndex:b?Math.max(-1,...w.map((_,Q)=>s.getSlotIndexForCard(_,Q)))+1:i.customCardPreferences.slotIndex}:void 0};I(i,O)}function k(O){var H;if(!V)return;let _=b?"table":"bar",Q="Title",B="";const K=b?Math.max(-1,...w.map((te,z)=>s.getSlotIndexForCard(te,z)))+1:E;if(b&&((H=u==null?void 0:u.slots)!=null&&H.length)){const te=s.getSlotDefinitionForIndex(u.slots,K);te&&(_=s.getSlotExpectedChartType(te),Q=te.label||`Tab ${K+1}`,B=te.description||"")}const se={dataSource:O.dataSource,connectionId:O.connectionId,lastSelectedDatabase:O.lastSelectedDatabase,lastSelectedSchema:O.lastSelectedSchema,lastSelectedTable:O.lastSelectedTable,lastSelectedDatamodelId:O.lastSelectedDatamodelId,id:s.v4(),title:Q,tabTitle:Q,description:B,preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:_,sql:"",data:[],mode:"explorer",...b&&{customCardPreferences:{slotIndex:K}}};I(O,se)}function R(O,_){return O.cards.length===1&&(_.displayTab===!0||_.displayTab===void 0)||O.activeCardId!==_.id&&(_.displayTab===!0||_.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const Q=_.displayTab===void 0?!1:!_.displayTab;c({..._,displayTab:Q}),l({..._,displayTab:Q})},children:_.displayTab===!0||_.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(s.EyeOff,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(s.TabsList,{className:"group ml-2 mr-6 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[r.cards.map((O,_)=>{var H,te;const Q=b?s.getSlotIndexForCard(O,_):-1,B=b&&((H=u==null?void 0:u.slots)!=null&&H.length)&&Q>=0?s.getSlotDefinitionForIndex(u.slots,Q):null,K=B?(Array.isArray(B.expectedType)?B.expectedType[0]:B.expectedType)||"table":O.type,se=b&&((te=u==null?void 0:u.slots)==null?void 0:te.length)&&u.slots.every(z=>typeof z.position=="number"||typeof z.position=="string"&&!z.position.includes("+"));return e.jsxs(s.TabsTrigger,{draggable:!b,onDragStart:b?void 0:z=>v(z,_),onDragOver:b?void 0:D,onDrop:b?void 0:z=>M(z,_),className:"",value:O.id,children:[b&&B?e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:s.getChartIconByType(K,"size-3.5")}),e.jsx("span",{children:B.label||`Tab ${Q+1}`})]})}),e.jsx(s.TooltipContent,{side:"bottom",className:"w-64 p-3 text-left",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium",children:B.label}),B.description&&e.jsx("p",{className:"whitespace-normal break-words text-xs text-muted-foreground",children:B.description}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[B.expectedType&&e.jsx("span",{className:"inline-flex items-center rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground",children:Array.isArray(B.expectedType)?B.expectedType.join(" / "):B.expectedType}),B.required&&e.jsx("span",{className:"inline-flex items-center rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground",children:"Required"})]})]})})]})}):e.jsxs(e.Fragment,{children:[R(r,O),e.jsx(s.Editable,{enabled:r.activeCardId===O.id,text:O.tabTitle||O.title,onSave:z=>{c({...i,tabTitle:z}),l({...i,tabTitle:z})},children:O.tabTitle||O.title},O.id)]}),r.activeCardId===O.id&&!se&&e.jsx(s.CopyPlus,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:z=>{z.stopPropagation(),j()}}),r.activeCardId===O.id&&(T&&(a==null?void 0:a.id)===O.id?r.cards.length>1:A)&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>f(O.id)})]},O.id)}),e.jsx(s.IconButton,{tooltip:"Add Card",className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",onClick:()=>k(i),disabled:!V,children:e.jsx(s.Plus,{className:"h-4 w-4"})}),b&&e.jsxs(s.Toggle,{pressed:t,onPressedChange:n,size:"sm",className:"ml-2 h-8 gap-1 px-2 data-[state=on]:bg-background data-[state=on]:text-foreground","aria-label":"Toggle preview",children:[t?e.jsx(s.EyeOff,{className:"h-4 w-4"}):e.jsx(s.Eye,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Preview"})]})]})})}function rt(){var ke,Me,we,be,Ce;const t=s.useEditorStore(ae=>ae.frame),n=s.useEditorStore(ae=>ae.card),[a,r]=C.useState(!1),i=C.useMemo(()=>s.findCustomVisualConfigCard(t,n),[t,n]),d=s.useEditorStore(ae=>ae.isSqlRunning);s.useEditorStore(ae=>ae.isDevMode);const{setFrame:o,setActiveTabCardId:c,setCard:l,setRunSql:x,mergeDraftsIntoCard:p,clearModeDrafts:h,initializeModeDrafts:u}=s.useEditorActions(),[y,b]=C.useState({}),[m,g]=C.useState(()=>new Set),{theme:w}=s.useTheme(),E=s.useDashboardStore(ae=>ae.themeStyle),{authToken:V}=s.useSemaphorContext(),A=s.getTokenParams(V==null?void 0:V.accessToken),T={mode:w||"system",colors:((Me=(ke=E==null?void 0:E.chart)==null?void 0:ke.dataset)==null?void 0:Me.backgroundColor)||[]},{getCard:v,manifest:D,isLoading:M}=s.useCustomVisual(((we=i==null?void 0:i.customCardPreferences)==null?void 0:we.url)||""),f=(be=i==null?void 0:i.customCardPreferences)==null?void 0:be.componentName,I=f?v(f):null,j=(Ce=D==null?void 0:D.visuals)==null?void 0:Ce.find(ae=>ae.name===f),k=s.resolveMultiInputType(i,j),R=a&&k==="multiple"&&!!i,P=C.useMemo(()=>s.getCustomVisualInputCards({frame:t,configCard:i,isMultiInputVisual:!0}).map(fe=>(fe==null?void 0:fe.id)===n.id?n:fe),[t,i,n]),N=C.useMemo(()=>s.buildSlotOrderedCards(P),[P]),L=C.useMemo(()=>{const ae=P.findIndex(fe=>(fe==null?void 0:fe.id)===n.id);return ae<0?-1:s.getSlotIndexForCard(n,ae)},[P,n]),S=C.useMemo(()=>!i||k!=="multiple"||L<0?n.type:s.getEffectiveCardTypeForSlot(n,L,j==null?void 0:j.slots)??n.type,[i,k,L,n,j==null?void 0:j.slots]),F=C.useMemo(()=>R?{...n,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:S!==n.type?{...n,type:S}:n,[n,S,R]),{data:O,isLoading:_,isFetching:Q,isError:B}=s.useDashboardCardQuery(F),K=C.useCallback((ae,fe)=>{const ge=s.normalizeMultiInputPayload(fe);b(Ie=>({...Ie,[ae]:ge}))},[]),se=C.useCallback((ae,fe)=>{g(ge=>{const Ie=new Set(ge);return fe?Ie.add(ae):Ie.delete(ae),Ie})},[]),H=m.size>0,te=s.useInteractionStore(ae=>ae.interactionStates),z=s.useDashboardStore(ae=>{var fe;return(fe=ae.dashboard)==null?void 0:fe.id}),W=s.useDashboardStore(ae=>ae.dashboard.filters),le=s.useDashboardStore(ae=>ae.filterValues),X=s.useDashboardStore(ae=>ae.selectedSheetId),ne=s.useDashboardStore(ae=>ae.inlineFilterValuesMap[(i==null?void 0:i.id)||""]),me=C.useMemo(()=>i?s.buildInlineFilterNodes({card:i,sheetId:X||"",inlineFilterValues:ne}):[],[i,X,ne]),{cardFilters:ee,cardFilterValues:Ne}=C.useMemo(()=>i?s.calculateContextAwareFilters({card:i,interactionStates:te,currentDashboardId:z,filters:W,filterValues:le,selectedSheetId:X}):{cardFilters:[],cardFilterValues:[]},[i,te,z,W,le,X]);function q(ae){const fe=t.cards.find(ge=>ge.id===ae);fe&&(p(),Z(ae),c(ae),h(),u(fe))}function Z(ae){const fe=s.useEditorStore.getState().card,ge=s.useEditorStore.getState().frame,Ie={...ge,cards:ge.cards.map(pe=>pe.id===fe.id?fe:pe),activeCardId:ae};o(Ie);const ve=Ie.cards.find(pe=>pe.id===ae);ve.sql&&x(!0),l(ve)}function ie(){if(M)return e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading manifest"})});if(!I)return e.jsx("div",{className:"flex h-full items-center justify-center text-sm text-muted-foreground",children:"Select a component to preview the multi-input visual."});const fe=N.map((ge,Ie)=>s.getEffectiveCardTypeForSlot(ge,Ie,j==null?void 0:j.slots));return e.jsxs("div",{className:"relative flex h-full flex-col pl-2 pr-4",children:[P.map((ge,Ie)=>{if(!ge)return null;const ve=s.getSlotIndexForCard(ge,Ie),pe=s.getEffectiveCardTypeForSlot(ge,ve,j==null?void 0:j.slots);return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:se,onDataChange:K,card:ge,effectiveCardType:pe},`${ge.id}-${ve}`)}),H&&e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/50",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading preview"})}),e.jsx("div",{className:s.cn("flex h-full min-h-0 flex-1 flex-col gap-2",H&&"opacity-50"),children:e.jsx(C.Suspense,{fallback:e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted"})}),children:e.jsx(I,{editing:!0,...s.buildMultiInputCustomVisualProps({configCard:i,slotOrderedCards:N,slotTypes:fe,multiInputData:y,params:A,theme:T,filters:ee,filterValues:[...Ne||[],...ne||[]],inlineFilters:me})})})})]})}function je(){var ae;return R?ie():n.type==="kpi"?_||Q?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.jsxs("div",{className:"w-1/2 space-y-3",children:[e.jsx("div",{className:"rounded-md border border-border",children:e.jsx(s.KPICard,{card:n,data:O==null?void 0:O.records,isPending:_||Q,isError:B,comparisonMetadata:(ae=O==null?void 0:O.metadata)==null?void 0:ae.comparisonMetadata})}),s.isCardSummaryVisibleOnCard(n)&&e.jsx(s.CardSummary,{card:n,mode:"editor"})]})}):n.type==="text"?_||Q?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:d,card:n,data:O==null?void 0:O.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Aa,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:q,value:t.activeCardId,className:"flex grow flex-col gap-2",children:[R?e.jsx("div",{className:"mt-0 grow",children:je()}):t.cards.map(ae=>e.jsx(s.TabsContent,{className:"mt-0 grow focus-visible:ring-0 focus-visible:ring-offset-0",value:ae.id,children:je()},ae.id)),e.jsx(nr,{isPreviewMode:R,onPreviewToggle:r,configCard:i})]})}function ia({children:t,visualAsideControl:n}){var Q;const a=s.useEditorStore(B=>B.frame),r=s.useEditorStore(B=>B.card),i=r.type==="table"||r.type==="detailTable",d=s.useEditorStore(B=>B.isDevMode),o=s.useEditorStore(B=>B.isShowingVisual),c=s.useEditorStore(B=>B.actions.setIsShowingVisual),l=s.useDashboardStore(B=>B.isVisualEditing),{isConsoleMode:x}=s.useDashboardPreferences(),p=s.useEditorStore(B=>B.pythonStdOut),h=s.useEditorStore(B=>B.actions.setRunSql),u=Ae.useEffectiveEditorCardType(),{setFrame:y,setCard:b,setActiveTabCardId:m,setCardPreferences:g,mergeDraftsIntoCard:w,clearModeDrafts:E,initializeModeDrafts:V}=s.useEditorActions(),A=C.useMemo(()=>u!==r.type?{...r,type:u}:r,[r,u]),{data:T,isLoading:v,isFetching:D,errorMessage:M,errorSql:f,refetch:I,pagination:j}=s.useDashboardCardQuery(A),{handleDebugWithAssistant:k}=Da(M,f),R=C.useMemo(()=>(T==null?void 0:T.records)||[],[T==null?void 0:T.records]),[P,N]=C.useState(!1);C.useEffect(()=>{D||N(!1)},[D]),C.useEffect(()=>{i&&!o&&c(!0)},[i,o,c]);function L(B,K){var te,z;const se={...r,paginationConfig:{page:B+1,pageSize:K}};b(se);const H={...a,cards:a.cards.map(W=>W.id===r.id?se:W)};y(H),r.sql&&((z=(te=r.preferences)==null?void 0:te.tablePrefs)!=null&&z.enableDevModePagination)&&h(!0)}function S(B){var te,z,W,le,X;const K=s.sortStateToSortByColumns(B,(te=r.config)==null?void 0:te.metricColumns,(z=r.config)==null?void 0:z.groupByColumns,(W=r.config)==null?void 0:W.detailColumns),se={...r,config:{...r.config||{},sortByColumns:K}};b(se);const H={...a,cards:a.cards.map(ne=>ne.id===r.id?se:ne)};y(H),r.sql&&((X=(le=r.preferences)==null?void 0:le.tablePrefs)!=null&&X.enableDevModePagination)&&h(!0)}function F(){var K;const B=JSON.stringify(T==null?void 0:T.records,null,2);typeof navigator>"u"||!((K=navigator.clipboard)!=null&&K.writeText)||navigator.clipboard.writeText(B).catch(se=>{console.error("Failed to copy JSON",se)})}function O(){const B=JSON.stringify(T==null?void 0:T.records,null,2),K=new Blob([B],{type:"application/json"}),se=URL.createObjectURL(K),H=document.createElement("a");H.href=se,H.download=`${r.title}.json`,H.click()}function _(){const K=[Object.keys(T==null?void 0:T.records.reduce((z,W)=>({...z,...W}),{})).join(","),...((T==null?void 0:T.records)||[]).map(z=>Object.values(z).join(","))].join(`
|
|
187
|
+
`),se=new Blob([K],{type:"text/csv"}),H=URL.createObjectURL(se),te=document.createElement("a");te.href=H,te.download=`${r.title}.csv`,te.click()}return r?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 pl-2 pr-6",children:[o&&e.jsx("div",{className:"flex grow items-center",children:e.jsxs("div",{className:"flex items-center gap-3",children:[(n==null?void 0:n.show)&&e.jsx(s.IconButton,{tooltip:n.isOpen?"Hide Visual Aside":"Show Visual Aside",className:"h-9 w-9 px-0",buttonProps:{variant:"outline"},onClick:n.onToggle,children:n.isOpen?e.jsx(s.ChevronLeft,{className:"size-4"}):e.jsx(s.ChevronRight,{className:"size-4"})}),e.jsx("div",{className:"w-[200px]",children:e.jsx(it,{variant:d?"secondary":"ghost"})})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[t,e.jsx(s.IconButton,{tooltip:"Refresh",disabled:v||D,onClick:()=>{N(!0),I()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":P})})}),e.jsx(La,{showInlineFilters:!1,showDisplayOptions:!1}),(d||x)&&e.jsxs(e.Fragment,{children:[!i&&e.jsx(or,{}),i&&e.jsx(lr,{})]}),e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"More Options",className:"h-8 w-8 px-0","aria-label":"More options",children:e.jsx(s.EllipsisVertical,{className:"size-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(s.DropdownMenuLabel,{children:"More Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"px-1 py-1",children:[!["table","detailTable","custom"].includes(r.type)&&l&&e.jsx(Xn,{triggerVariant:"menu",className:"w-full"}),e.jsx(dt,{triggerVariant:"menu",className:"w-full"}),e.jsx(ct,{triggerVariant:"menu",className:"w-full"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.Button,{variant:"ghost",className:"h-8 w-full justify-start gap-2 px-2 text-sm",onClick:_,children:[e.jsx(s.Download,{className:"h-4 w-4"}),e.jsx("span",{children:"Download CSV"})]}),e.jsxs(s.Button,{variant:"ghost",className:"h-8 w-full justify-start gap-2 px-2 text-sm",onClick:O,children:[e.jsx(cn,{className:"h-4 w-4"}),e.jsx("span",{children:"Download JSON"})]}),e.jsxs(s.Button,{variant:"ghost",className:"h-8 w-full justify-start gap-2 px-2 text-sm",onClick:F,children:[e.jsx(s.Copy,{className:"h-4 w-4"}),e.jsx("span",{children:"Copy JSON"})]})]})]})]})]})]}),o?e.jsx(rt,{}):e.jsxs(s.ResizablePanelGroup,{className:"py-2 pl-2 pr-6",direction:"horizontal",children:[p&&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:p&&e.jsx(rr,{})}),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",{"py-2 pl-2 pr-6":p}),children:[(T==null?void 0:T.records)&&(T==null?void 0:T.records.length)>0&&e.jsx(s.TableVisual,{card:r,data:R,comparisonMetadata:(Q=T==null?void 0:T.metadata)==null?void 0:Q.comparisonMetadata,paginationMetadata:j,onPaginationChange:L,onSortChange:S,isLoading:v||D}),M&&e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(ot,{error:M,errorSql:f||r.sql||r.python,onDebugWithAssistant:k,showFeedbackButton:!1})})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function rr(){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 lr(){var d,o,c,l,x,p;const t=s.useEditorStore(h=>h.card),n=s.useEditorStore(h=>h.actions.setCard),a=s.useEditorStore(h=>h.actions.setRunSql),r=s.useEditorStore(h=>h.actions.setCardPreferences),i=s.useEditorStore(h=>h.actions.updateCardInFrame);return t.type!=="table"&&t.type!=="detailTable"?null:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"dev-pagination",checked:((o=(d=t.preferences)==null?void 0:d.tablePrefs)==null?void 0:o.enableDevModePagination)??!1,onCheckedChange:h=>{var u;r({...t.preferences,tablePrefs:{...(u=t.preferences)==null?void 0:u.tablePrefs,enableDevModePagination:h}})}}),e.jsx(s.Label,{htmlFor:"dev-pagination",className:"cursor-pointer text-sm",children:"Paginate"}),((l=(c=t.preferences)==null?void 0:c.tablePrefs)==null?void 0:l.enableDevModePagination)&&e.jsxs(s.Select,{value:String(((p=(x=t.preferences)==null?void 0:x.tablePrefs)==null?void 0:p.pageSize)||50),onValueChange:h=>{var b,m,g;const u=Number(h),y={...t,preferences:{...t.preferences,tablePrefs:{...(b=t.preferences)==null?void 0:b.tablePrefs,pageSize:u}},paginationConfig:{page:1,pageSize:u}};n(y),i(y),t.sql&&((g=(m=t.preferences)==null?void 0:m.tablePrefs)!=null&&g.enableDevModePagination)&&a(!0)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"10",children:"10"}),e.jsx(s.SelectItem,{value:"25",children:"25"}),e.jsx(s.SelectItem,{value:"50",children:"50"}),e.jsx(s.SelectItem,{value:"100",children:"100"}),e.jsx(s.SelectItem,{value:"500",children:"500"}),e.jsx(s.SelectItem,{value:"1000",children:"1000"})]})]})]})}function or(){const t=s.useEditorStore(a=>a.isShowingVisual),n=s.useEditorStore(a=>a.actions.setIsShowingVisual);return e.jsxs(s.Toggle,{pressed:!t,onPressedChange:a=>{n(!a)},variant:"default",size:"sm",className:"h-8 gap-2 border border-transparent text-foreground/80 hover:bg-accent hover:text-accent-foreground data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",children:[e.jsx(s.Table2,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:"Results"})]})}function Ve({value:t,onCommit:n,type:a="text",placeholder:r,className:i}){const[d,o]=C.useState(t),c=C.useRef(!1);C.useEffect(()=>{o(t)},[t]);const l=()=>{if(c.current){c.current=!1;return}d!==t&&n(d)},x=p=>{if(p.key==="Enter"){p.currentTarget.blur();return}p.key==="Escape"&&(c.current=!0,o(t),p.currentTarget.blur())};return e.jsx(s.Input,{type:a,placeholder:r,value:d,onChange:p=>o(p.target.value),onBlur:l,onKeyDown:x,className:i})}function ss({defaultValue:t,label:n,options:a,value:r,onValueChange:i,className:d,icon:o,showPlaceholderLabel:c=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:i,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",d),children:e.jsxs("div",{className:"flex items-center gap-2",children:[o&&e.jsx("span",{children:o}),c&&e.jsx(s.SelectValue,{placeholder:n})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:n}),a.map(l=>e.jsx(s.SelectItem,{value:l.value,children:l.label},l.value))]})})]})}function ir(t,n){return s.getSlotDefinitionForIndex(t,n)||null}function vs(t){if(typeof t=="number")return`Tab ${t+1}`;const n=t.match(/^(\d+)-(\d+)$/);if(n){const[,r,i]=n;return`Tabs ${Number(r)+1}-${Number(i)+1}`}const a=t.match(/^(\d+)\+$/);return a?`Tabs ${Number(a[1])+1}+`:`Tab ${t}`}function cr(t){return t?Array.isArray(t)?t:[t]:[]}function Ws(t){var r,i;if(!t)return!1;if(t.type==="text")return!!((r=t.description)!=null&&r.trim());const n=!!((i=t.sql)!=null&&i.trim()),a=s.hasValidCardConfig(t.config);return n||a}function dr({slots:t,cards:n,minInputs:a}){const r=[],i=n.filter(Boolean).length;return a&&i<a&&r.push({type:"too-few-inputs",message:`This visual requires at least ${a} tab${a===1?"":"s"}.`}),!t||t.length===0||(t.forEach(d=>{if(!d.required)return;if(typeof d.position=="number"){const l=n[d.position];Ws(l)||r.push({type:"missing-required",message:`${vs(d.position)} ("${d.label}") is required but has no data configured.`});return}const o=d.position.match(/^(\d+)-(\d+)$/);if(o){const[,l,x]=o.map(Number);for(let p=l;p<=x;p+=1){const h=n[p];if(!Ws(h)){r.push({type:"missing-required",message:`${vs(p)} ("${d.label}") is required but has no data configured.`});break}}return}const c=d.position.match(/^(\d+)\+$/);if(c){const l=Number(c[1]);if(n.length<=l){r.push({type:"missing-required",message:`${vs(l)} ("${d.label}") is required but has no data configured.`});return}for(let x=l;x<n.length;x+=1){const p=n[x];if(!Ws(p)){r.push({type:"missing-required",message:`${vs(x)} ("${d.label}") is required but has no data configured.`});break}}}}),n.forEach((d,o)=>{if(!d)return;const c=ir(t,o);if(!c||!c.expectedType)return;const l=cr(c.expectedType);l.length!==0&&(l.includes(d.type)||r.push({type:"wrong-type",message:`${vs(o)} ("${c.label}") expects ${l.join(", ")}, but is configured as ${d.type}.`}))})),r}const ur={table:({children:t})=>e.jsx("table",{className:"my-3 w-full border-collapse overflow-hidden rounded-md border border-border text-sm",children:t}),thead:({children:t})=>e.jsx("thead",{className:"bg-muted",children:t}),th:({children:t})=>e.jsx("th",{className:"border border-border px-3 py-2 text-left font-medium",children:t}),td:({children:t})=>e.jsx("td",{className:"border border-border px-3 py-2",children:t}),code:({children:t,className:n})=>(n==null?void 0:n.includes("language-"))?e.jsx("pre",{className:"my-3 overflow-x-auto rounded-md bg-muted p-3 text-xs",children:e.jsx("code",{children:t})}):e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-xs",children:t}),pre:({children:t})=>e.jsx(e.Fragment,{children:t})};function Ma(){var k,R,P;const t=s.useEditorStore(N=>N.card.customCardPreferences),{data:n}=s.usePluginQuery(),a=(n==null?void 0:n.plugins)||[],r=s.useEditorStore(N=>N.card),i=s.useEditorStore(N=>N.frame),{setCustomCardPreferences:d}=s.useEditorActions(),o=C.useMemo(()=>s.findCustomVisualConfigCard(i,r),[i,r]),c=o==null?void 0:o.customCardPreferences,{components:l,manifest:x}=s.useCustomVisual((c==null?void 0:c.url)||(t==null?void 0:t.url)||""),p=(k=x==null?void 0:x.visuals)==null?void 0:k.find(N=>N.name===((c==null?void 0:c.componentName)||(t==null?void 0:t.componentName))),u=s.resolveMultiInputType(o||r,p)==="multiple",y=!!o&&o.id===r.id,b=(p==null?void 0:p.minInputs)??((R=o==null?void 0:o.customCardPreferences)==null?void 0:R.minInputs),m=(p==null?void 0:p.maxInputs)??((P=o==null?void 0:o.customCardPreferences)==null?void 0:P.maxInputs),g=C.useMemo(()=>s.getCustomVisualInputCards({frame:i,configCard:o||r,isMultiInputVisual:u}),[i,o,r,u]),w=C.useMemo(()=>s.buildSlotOrderedCards(g),[g]),E=C.useMemo(()=>w.map((N,L)=>{if(!N)return null;const S=s.getSlotIndexForCard(N,L),F=s.getEffectiveCardTypeForSlot(N,S,p==null?void 0:p.slots);return{...N,type:F??N.type}}),[w,p==null?void 0:p.slots]),V=C.useMemo(()=>dr({slots:p==null?void 0:p.slots,cards:E,minInputs:b}),[p==null?void 0:p.slots,E,b]),A=C.useMemo(()=>{const N=g.findIndex(L=>(L==null?void 0:L.id)===r.id);return N<0?-1:s.getSlotIndexForCard(r,N)},[g,r]);function T(N){if(typeof N=="number")return`Tab ${N+1}`;const L=N.match(/^(\d+)-(\d+)$/);if(L){const[,F,O]=L;return`Tabs ${Number(F)+1}-${Number(O)+1}`}const S=N.match(/^(\d+)\+$/);return S?`Tabs ${Number(S[1])+1}+`:`Tab ${N}`}function v(N){return N?(Array.isArray(N)?N:[N]).join(", "):null}function D(N,L,S=[],F="",O,_,Q){const B=M({key:L,defaultValue:F,settingsValue:_,sourceCard:Q});return N==="input"?e.jsx(Ve,{className:`h-8 w-full ${s.removeRing}`,value:String(B??""),onCommit:K=>{f({key:L,value:K,settingsField:O,settingsValue:_,sourceCard:Q})}},L):N==="select"?e.jsx(ss,{className:"h-8 w-full",label:"",options:S,value:String(B!==void 0?B:F??""),onValueChange:K=>{f({key:L,value:K,settingsField:O,settingsValue:_,sourceCard:Q})}}):null}function M({key:N,defaultValue:L,settingsValue:S,sourceCard:F}){const O=S==null?void 0:S[N];return O!==void 0?O:N==="title"&&(F==null?void 0:F.title)!==void 0?F.title:N==="description"&&(F==null?void 0:F.description)!==void 0?F.description:L}function f({key:N,value:L,settingsField:S,settingsValue:F,sourceCard:O}){const _={...F||{}},Q=N==="title"&&(O==null?void 0:O.title)!==void 0,B=N==="description"&&(O==null?void 0:O.description)!==void 0;Q&&L===String((O==null?void 0:O.title)??"")||B&&L===String((O==null?void 0:O.description)??"")?delete _[N]:_[N]=L,d({...t||{},[S]:_})}function I({settingsSchema:N,settingsField:L,settingsValue:S,sourceCard:F,headerLabel:O}){const _=Object.entries(N||{});return e.jsxs("div",{className:"space-y-3",children:[O&&e.jsx(s.Label,{children:O}),_.map(([Q,B])=>{var K;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:B.title}),((K=B.docs)==null?void 0:K.description)&&e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{className:"text-xs",children:B.docs.description})})]})})]}),D(B.ui,Q,B.options,B.defaultValue,L,S,F)]},Q)})]})}function j(){return e.jsxs(e.Fragment,{children:[u&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Slot Guide"}),e.jsx("div",{className:"space-y-3 rounded-md border border-border bg-muted/40 px-3 py-2 text-xs",children:p!=null&&p.slots&&p.slots.length>0?e.jsx("div",{className:"space-y-3",children:p.slots.map((N,L)=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-foreground",children:[e.jsx("span",{className:"font-medium",children:T(N.position)}),e.jsx("span",{className:"text-muted-foreground",children:"•"}),e.jsx("span",{className:"font-medium",children:N.label})]}),N.description&&e.jsx("p",{className:"text-muted-foreground",children:N.description}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-muted-foreground",children:[v(N.expectedType)&&e.jsxs("span",{children:["Expected: ",v(N.expectedType)]}),N.required&&e.jsx("span",{children:"Required"})]})]},`${N.label}-${L}`))}):e.jsxs("div",{className:"space-y-1 text-muted-foreground",children:[e.jsx("p",{children:"This visual renders all tabs in a flexible layout. Add as many tabs as needed."}),(b||m)&&e.jsxs("p",{children:[b?`Min ${b} tabs`:"",b&&m?" • ":"",m?`Max ${m} tabs`:""]})]})})]}),u&&V.length>0&&e.jsx(s.Alert,{className:"mt-3 border-yellow-500/40 bg-yellow-500/10 text-yellow-900 dark:text-yellow-100",children:e.jsx(s.AlertDescription,{children:e.jsx("ul",{className:"list-disc space-y-1 pl-4 text-xs",children:V.map((N,L)=>e.jsx("li",{children:N.message},`${N.type}-${L}`))})})}),p&&!u&&p.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:I({settingsSchema:p.settings,settingsField:"settings",settingsValue:t==null?void 0:t.settings,sourceCard:r})})}),p&&u&&(p.settings||p.slotSettings)&&e.jsxs("div",{className:"mt-4 space-y-4",children:[y&&p.settings&&e.jsx("div",{className:"px-2",children:I({settingsSchema:p.settings,settingsField:"settings",settingsValue:t==null?void 0:t.settings,sourceCard:o||r,headerLabel:"Global Settings"})}),p.slotSettings&&e.jsx("div",{className:"px-2",children:I({settingsSchema:p.slotSettings,settingsField:"slotSettings",settingsValue:t==null?void 0:t.slotSettings,sourceCard:r,headerLabel:(()=>{const N=r.tabTitle||r.title,L=A>=0?A:0,S=y?"Slot 0":`Slot ${L}`;return N?`${S}: ${N} Settings`:`${S} Settings`})()})})]})]})}return e.jsxs(s.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"",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:[(!u||y)&&e.jsx(ss,{icon:e.jsx(ya,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:a,value:(c==null?void 0:c.url)||"",onValueChange:N=>d({...t||{url:"",componentName:""},url:N})}),u&&!y&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Switch to the config tab to change the plugin or component."})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&(!u||y)&&e.jsx(e.Fragment,{children:l&&e.jsx(ss,{icon:e.jsx(on,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(l==null?void 0:l.map(N=>({value:N.name,label:N.name})))||[],value:t.componentName||"",onValueChange:N=>{var F;const L=(F=x==null?void 0:x.visuals)==null?void 0:F.find(O=>O.name===N),S=l==null?void 0:l.find(O=>O.name===N);d({...t,componentName:N,visualType:(L==null?void 0:L.visualType)||(S==null?void 0:S.type)||"single",minInputs:L==null?void 0:L.minInputs,maxInputs:L==null?void 0:L.maxInputs,pluginChartType:L==null?void 0:L.chartType})}})})]})})]}),((c==null?void 0:c.componentName)||(t==null?void 0:t.componentName))&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:(p==null?void 0:p.name)||"Settings"}),(p==null?void 0:p.docs)&&e.jsxs(s.HoverCard,{openDelay:0,closeDelay:100,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,onClick:N=>N.stopPropagation(),children:e.jsx(s.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground transition-colors hover:text-foreground"})}),e.jsx(s.HoverCardContent,{side:"right",align:"start",className:"max-h-[40vh] w-[500px] overflow-y-auto text-left",children:e.jsxs("div",{className:"space-y-4 text-left",children:[p.docs.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:p.docs.description}),p.docs.dataSchema&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Data Schema"}),e.jsx("div",{className:"prose prose-sm dark:prose-invert prose-pre:bg-muted prose-pre:text-xs max-w-none",children:e.jsx(s.Markdown,{remarkPlugins:[s.remarkGfm],components:ur,children:p.docs.dataSchema})})]}),(()=>{var L;const N=(L=p.docs)==null?void 0:L.useCases;return!N||N.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Use Cases"}),e.jsx("ul",{className:"space-y-1 text-sm",children:N.map((S,F)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1 text-primary",children:"•"}),e.jsx("span",{children:S})]},F))})]})})()]})})]})]})}),e.jsx(s.AccordionContent,{children:j()})]})]})}function mr({colorRanges:t,setColorRanges:n}){const a={start:-1/0,end:100,color:""};function r(o,c,l){const x=[...t];x[o]={...x[o],[c]:l},n(x)}function i(o){const c=[...t];c.splice(o,1),n(c)}function d(){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:d,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((o,c)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input,{onChange:l=>r(c,"start",l.target.value),value:o.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input,{value:o.end,onChange:l=>r(c,"end",l.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input,{onChange:l=>r(c,"color",l.target.value),value:o.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:()=>i(c),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},c))]})}function xr(){var p,h,u,y,b;const t=s.useEditorStore(m=>m.card.preferences),n=s.useEditorStore(m=>m.actions.setCardPreferences),a=s.useEditorStore(m=>m.card),r=s.hasValidCardConfig(a.config),i=s.useEditorStore(m=>m.actions.setNumberFormat);s.useEditorStore(m=>{var g,w;return(w=(g=m.card.preferences)==null?void 0:g.formatNumber)==null?void 0:w.decimalPlaces});const d=s.useEditorStore(m=>{var g,w;return(w=(g=m.card.preferences)==null?void 0:g.formatNumber)==null?void 0:w.locale}),o=s.useEditorStore(m=>{var g,w;return(w=(g=m.card.preferences)==null?void 0:g.formatNumber)==null?void 0:w.currency});s.useEditorStore(m=>m.actions.setFilterOnClickField);const c=s.useEditorStore(m=>{var g,w;return(w=(g=m.card.preferences)==null?void 0:g.formatNumber)==null?void 0:w.colorRanges})||[],l=s.useEditorStore(m=>m.actions.setColorRanges),x=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(m=>m.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(s.Checkbox,{checked:!!((p=t==null?void 0:t.formatNumber)!=null&&p.enabled),onCheckedChange:m=>{n({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:m}})}}),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:d||"none",onValueChange:m=>{var g,w,E;return i(((g=t==null?void 0:t.formatNumber)==null?void 0:g.decimalPlaces)||0,((w=t==null?void 0:t.formatNumber)==null?void 0:w.currency)||"",m,((E=t==null?void 0:t.formatNumber)==null?void 0:E.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(m=>e.jsx(s.SelectItem,{value:m.locale,children:m.locale},m.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:o||"none",onValueChange:m=>{var g,w,E;console.log("currency",m),i(((g=t==null?void 0:t.formatNumber)==null?void 0:g.decimalPlaces)||0,m==="none"?"":m,((w=t==null?void 0:t.formatNumber)==null?void 0:w.locale)||"",((E=t==null?void 0:t.formatNumber)==null?void 0:E.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"),x.map(m=>e.jsx(s.SelectItem,{value:m,children:m},m))]})})]})]})]}),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:((y=(u=t==null?void 0:t.formatNumber)==null?void 0:u.decimalPlaces)==null?void 0:y.toString())||"0",onValueChange:m=>{var g,w,E;return i(Number(m),((g=t==null?void 0:t.formatNumber)==null?void 0:g.currency)||"",((w=t==null?void 0:t.formatNumber)==null?void 0:w.locale)||"",((E=t==null?void 0:t.formatNumber)==null?void 0:E.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(m=>e.jsx(s.SelectItem,{value:m,children:m},m))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Suffix"}),e.jsx(s.Input,{value:((b=t==null?void 0:t.formatNumber)==null?void 0:b.suffix)||"",className:"h-8 font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"K, M, B, %",onChange:m=>{var g,w,E;return i(((g=t==null?void 0:t.formatNumber)==null?void 0:g.decimalPlaces)||0,((w=t==null?void 0:t.formatNumber)==null?void 0:w.currency)||"",((E=t==null?void 0:t.formatNumber)==null?void 0:E.locale)||"",m.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(mr,{colorRanges:c,setColorRanges:l})]})]})}const hr={combo:{label:"Combo Chart",query:"SELECT x-axis, metric-1, metric-2, ... FROM table",fields:[{name:"x-axis",type:"category",description:"dimension"},{name:"metric-1, metric-2",type:"number",description:"can be bar, line, or area"}],description:"Combo charts allow mixing bar and line series with optional dual Y-axis for metrics with different scales.",docsUrl:"https://docs.semaphor.cloud/docs/charts/combo"},area:{label:"Area Chart",query:"SELECT x-axis, y-axis-1, y-axis-2, ... FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., date, city"},{name:"Y-axis",type:"number",description:"e.g., sales, population"}],description:"Area charts display quantitative data with filled areas under the line.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bar-line-area"},stackedArea:{label:"Stacked Area Chart",query:"SELECT x-axis, y-axis-1, y-axis-2, ... FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., date, city"},{name:"Y-axis",type:"number",description:"e.g., sales, population"}],description:"Stacked area charts show how multiple series contribute to a total over time.",docsUrl:"https://docs.semaphor.cloud/docs/charts/stacked"},bar:{label:"Bar Chart",query:"SELECT x-axis, y-axis-1, y-axis-2, ... FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., city, product"},{name:"Y-axis",type:"number",description:"e.g., sales, count"}],description:"Bar charts compare values across categories using horizontal or vertical bars.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bar-line-area"},line:{label:"Line Chart",query:"SELECT x-axis, y-axis-1, y-axis-2, ... FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., date, month"},{name:"Y-axis",type:"number",description:"e.g., revenue, count"}],description:"Line charts show trends over time or continuous data.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bar-line-area"},stackedBar:{label:"Stacked Bar Chart",query:"SELECT x-axis, stack-by, y-axis FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., month"},{name:"Stack-by",type:"category",description:"e.g., product type"},{name:"Y-axis",type:"number",description:"e.g., sales"}],description:"Stacked bar charts show how parts contribute to a whole across categories.",docsUrl:"https://docs.semaphor.cloud/docs/charts/stacked"},stackedLine:{label:"Stacked Line Chart",query:"SELECT x-axis, stack-by, y-axis FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., date"},{name:"Stack-by",type:"category",description:"e.g., region"},{name:"Y-axis",type:"number",description:"e.g., revenue"}],description:"Stacked line charts show cumulative trends over time.",docsUrl:"https://docs.semaphor.cloud/docs/charts/stacked"},pie:{label:"Pie Chart",query:"SELECT label, measure FROM table",fields:[{name:"Label",type:"category",description:"e.g., product, region"},{name:"Measure",type:"number",description:"e.g., sales, count"}],description:"Pie charts show proportions of a whole.",docsUrl:"https://docs.semaphor.cloud/docs/charts/pie-donut-polar"},doughnut:{label:"Doughnut Chart",query:"SELECT label, measure FROM table",fields:[{name:"Label",type:"category",description:"e.g., product, region"},{name:"Measure",type:"number",description:"e.g., sales, count"}],description:"Doughnut charts show proportions with a hollow center.",docsUrl:"https://docs.semaphor.cloud/docs/charts/pie-donut-polar"},polarArea:{label:"Polar Area Chart",query:"SELECT label, measure FROM table",fields:[{name:"Label",type:"category",description:"e.g., skill, metric"},{name:"Measure",type:"number",description:"e.g., score, value"}],description:"Polar area charts compare values using sectors of equal angle but varying radius.",docsUrl:"https://docs.semaphor.cloud/docs/charts/pie-donut-polar"},radar:{label:"Radar Chart",query:"SELECT label, measure FROM table",fields:[{name:"Label",type:"category",description:"e.g., attribute, skill"},{name:"Measure",type:"number",description:"e.g., score, rating"}],description:"Radar charts display multivariate data on axes starting from the same point.",docsUrl:"https://docs.semaphor.cloud/docs/charts/pie-donut-polar"},funnel:{label:"Funnel Chart",query:"SELECT label, measure FROM table",fields:[{name:"Label",type:"category",description:"e.g., stage name"},{name:"Measure",type:"number",description:"e.g., count, value"}],description:"Funnel charts visualize progressive reduction of data through stages.",docsUrl:"https://docs.semaphor.cloud/docs/charts/funnel"},bubble:{label:"Bubble Chart",query:"SELECT label, [group], x-axis, y-axis, radius FROM table",fields:[{name:"Label",type:"category",description:"e.g., city"},{name:"Group",type:"category",description:"e.g., region",optional:!0},{name:"X-axis",type:"number",description:"e.g., population"},{name:"Y-axis",type:"number",description:"e.g., income"},{name:"Radius",type:"number",description:"e.g., area"}],description:"Bubble charts display three dimensions of data using position and size.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bubble"},scatter:{label:"Scatter Chart",query:"SELECT label, [group], x-axis, y-axis FROM table",fields:[{name:"Label",type:"category",description:"e.g., item name"},{name:"Group",type:"category",description:"e.g., type",optional:!0},{name:"X-axis",type:"number",description:"e.g., price"},{name:"Y-axis",type:"number",description:"e.g., quantity"}],description:"Scatter charts show relationships between two numeric variables.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bubble"},tornado:{label:"Tornado Chart",query:"SELECT dimension, cohort, metric FROM table",fields:[{name:"Dimension",type:"category",description:"e.g., age group"},{name:"Cohort",type:"category",description:"e.g., gender"},{name:"Metric",type:"number",description:"e.g., population"}],description:"Tornado charts compare two groups across categories using back-to-back bars.",docsUrl:"https://docs.semaphor.cloud/docs/charts/tornado"},pyramid:{label:"Pyramid Chart",query:"SELECT dimension, cohort, metric FROM table",fields:[{name:"Dimension",type:"category",description:"e.g., age group"},{name:"Cohort",type:"category",description:"e.g., gender"},{name:"Metric",type:"number",description:"e.g., population"}],description:"Population pyramids show age and gender distribution.",docsUrl:"https://docs.semaphor.cloud/docs/charts/tornado"},range:{label:"Range Chart",query:"SELECT y-axis, label, range-from, range-to, range-value FROM table",fields:[{name:"Y-axis",type:"category",description:"e.g., category"},{name:"Label",type:"category",description:"e.g., range name"},{name:"Range-from",type:"number",description:"start value"},{name:"Range-to",type:"number",description:"end value"},{name:"Range-value",type:"number",description:"e.g., midpoint"}],description:"Range charts display data ranges with start and end values.",docsUrl:"https://docs.semaphor.cloud/docs/charts/range"},heatmap:{label:"Heatmap",query:"SELECT x-axis, y-axis, value FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., day"},{name:"Y-axis",type:"category",description:"e.g., hour"},{name:"Value",type:"number",description:"e.g., count, intensity"}],description:"Heatmaps visualize data density using color intensity.",docsUrl:"https://docs.semaphor.cloud/docs/charts/heatmap"},bullet:{label:"Bullet Chart",query:"SELECT label, actual, target, [ranges] FROM table",fields:[{name:"Label",type:"category",description:"e.g., metric name"},{name:"Actual",type:"number",description:"current value"},{name:"Target",type:"number",description:"goal value"},{name:"Ranges",type:"number",description:"threshold values",optional:!0}],description:"Bullet charts compare actual performance against targets.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bullet"},text:{label:"Text Visual",query:"SELECT text FROM table LIMIT 1",fields:[{name:"Text",type:"string",description:"content to display"}],description:"Text visuals display dynamic text content from your data.",docsUrl:"https://docs.semaphor.cloud/docs/charts/text"},kpi:{label:"KPI",query:"SELECT current, previous FROM table",fields:[{name:"Current",type:"number",description:"current value"},{name:"Previous",type:"number",description:"comparison value"}],description:"KPI visuals display key performance indicators with comparison values.",docsUrl:"https://docs.semaphor.cloud/docs/charts/kpi"},map:{label:"Map Chart",query:"SELECT country, value FROM table",fields:[{name:"Country/Region",type:"category",description:"geographic identifier"},{name:"Value",type:"number",description:"e.g., population, sales"}],description:"Map charts visualize geographic data using color intensity.",docsUrl:"https://docs.semaphor.cloud/docs/charts/map"},table:{label:"Table",query:"SELECT column1, column2, ... FROM table",fields:[{name:"Columns",type:"category",description:"any data columns"}],description:"Tables display data in rows and columns.",docsUrl:"https://docs.semaphor.cloud/docs/charts/table"},detailTable:{label:"Detail Table",query:"SELECT column1, column2, ... FROM table ORDER BY column1 DESC",fields:[{name:"Columns",type:"category",description:"columns to display (no aggregation)"}],description:"Detail tables display raw records without aggregation. Ideal for event logs, transaction history, and audit trails.",docsUrl:"https://docs.semaphor.cloud/docs/charts/detail-table"}};function Oa(t){return hr[t]}function pr({chartType:t,showDocsLink:n=!0}){const a=Oa(t);return a?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Query Format"}),e.jsx("code",{className:"block rounded-md bg-muted/50 px-3 py-2 font-mono text-xs text-foreground",children:a.query})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Fields"}),e.jsx("div",{className:"rounded-md border",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/50",children:[e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Field"}),e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Type"}),e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Description"})]})}),e.jsx("tbody",{children:a.fields.map((r,i)=>e.jsxs("tr",{className:i<a.fields.length-1?"border-b":"",children:[e.jsxs("td",{className:"px-2.5 py-1.5 font-medium text-foreground",children:[r.name,r.optional&&e.jsx("span",{className:"ml-1 text-muted-foreground",children:"?"})]}),e.jsx("td",{className:"px-2.5 py-1.5 font-mono text-muted-foreground",children:r.type}),e.jsx("td",{className:"px-2.5 py-1.5 text-muted-foreground",children:r.description||"—"})]},r.name))})]})})]}),e.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:a.description}),n&&a.docsUrl&&e.jsxs("a",{href:a.docsUrl,target:"_blank",rel:"noopener noreferrer",onClick:r=>r.stopPropagation(),className:"inline-flex items-center gap-1.5 text-xs font-medium text-primary hover:underline",children:["View documentation",e.jsx(s.ExternalLink,{className:"h-3 w-3"})]})]}):null}function fr({chartType:t}){return Oa(t)?e.jsxs(s.HoverCard,{openDelay:200,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded bg-muted px-2 py-0.5 font-mono text-[10px] font-semibold uppercase tracking-wider text-muted-foreground transition-colors hover:bg-muted/80 hover:text-foreground",children:"SQL"})}),e.jsx(s.HoverCardContent,{className:"w-80 p-4",side:"left",align:"start",sideOffset:8,children:e.jsx(pr,{chartType:t})})]}):null}function Ps({chartType:t,suffix:n="Configuration"}){return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-medium",children:n}),e.jsx(fr,{chartType:t})]})}function gr(){return e.jsxs("div",{className:"space-y-6 px-6 py-4",children:[e.jsx(Ps,{chartType:"kpi"}),e.jsx("section",{children:e.jsx(xr,{})})]})}function ca({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})]})}function Ra(){const[t,n]=C.useState([]),a=s.useEditorStore(x=>x.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:i}=s.useEditorStore(x=>x.actions),d=s.useEditorStore(x=>x.queryResultColumns);s.useEditorStore(x=>{var p;return(p=x.card.preferences)==null?void 0:p.filterOnClickColumnIndex}),C.useEffect(()=>{d&&n(new Array(d.length).fill(!1))},[d]);function o(x,p){var h,u;p?a!=null&&a.onClickFilter&&((h=a==null?void 0:a.onClickFilter)==null?void 0:h.length)>0?i({...a,onClickFilter:[...a.onClickFilter,{columnIndex:x,expression:""}]}):i({...a,onClickFilter:[{columnIndex:x,expression:""}]}):(i({...a,onClickFilter:(u=a==null?void 0:a.onClickFilter)==null?void 0:u.filter(y=>y.columnIndex!==x)}),n(y=>{const b=[...y];return b[x]=!1,b}))}function c(x,p){var u;const h=(u=a==null?void 0:a.onClickFilter)==null?void 0:u.map(y=>y.columnIndex===x?{...y,expression:p.target.value}:y);i({...a,onClickFilter:h})}function l(x){var p,h,u,y;if(t!=null&&t[x]||(h=(p=a==null?void 0:a.onClickFilter)==null?void 0:p.find(b=>b.columnIndex===x))!=null&&h.expression)return e.jsx(s.Input,{value:(y=(u=a==null?void 0:a.onClickFilter)==null?void 0:u.find(b=>b.columnIndex===x))==null?void 0:y.expression,onChange:b=>c(x,b),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsx("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:d==null?void 0:d.map((x,p)=>{var h,u;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(y=>y.columnIndex===p)),onCheckedChange:y=>o(p,y)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:x}),e.jsx("div",{className:"flex items-center gap-2",children:((u=a==null?void 0:a.onClickFilter)==null?void 0:u.find(y=>y.columnIndex===p))&&e.jsx(s.Pencil,{onClick:()=>{n(y=>{const b=[...y];return b[p]=!y[p],b})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),l(p)]})},x)})})}const jr=[{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"}],br=["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"],vr=br.map(t=>({label:t,value:t}));function yr(){var l,x,p,h,u,y,b,m,g,w,E,V,A,T,v,D,M,f;const t=s.useEditorStore(I=>I.card),n=(x=(l=t==null?void 0:t.preferences)==null?void 0:l.mapVisualOptions)==null?void 0:x.topoJsonUrl,[a,r]=C.useState(((h=(p=t==null?void 0:t.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:i}=s.useEditorActions(),{data:d}=s.useTopoJson(t),o=Object.keys((d==null?void 0:d.objects)||{}).map(I=>({label:I,value:I}))||[],c=[{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:"space-y-4 px-6 py-4",children:[e.jsx(Ps,{chartType:"map"}),e.jsx(ca,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(ss,{className:"h-9",options:c,onValueChange:I=>{console.log("value",I),i({...t.preferences,mapVisualOptions:{topoJsonUrl:I}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(s.Input,{onChange:I=>{r(I.target.value)},onBlur:()=>{var I;console.log("onBlur",a),i({...t.preferences,mapVisualOptions:{...(I=t.preferences)==null?void 0:I.mapVisualOptions,customTopoJsonUrl:a}})},value:a,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),d&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(ss,{className:"h-9",options:o,value:((y=(u=t.preferences)==null?void 0:u.mapVisualOptions)==null?void 0:y.objectKey)||"",label:"Map Object",onValueChange:I=>{var j;i({...t.preferences,mapVisualOptions:{...(j=t.preferences)==null?void 0:j.mapVisualOptions,objectKey:I}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(ss,{className:"h-9",options:jr,value:((m=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:m.projection)||"",label:"Projection",onValueChange:I=>{var j;i({...t.preferences,mapVisualOptions:{...(j=t.preferences)==null?void 0:j.mapVisualOptions,projection:I}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(ss,{className:"h-9",options:vr,value:((w=(g=t.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:w.colorScale)||"",label:"Select Color Scale",onValueChange:I=>{var j;i({...t.preferences,mapVisualOptions:{...(j=t.preferences)==null?void 0:j.mapVisualOptions,colorScale:I}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(ca,{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:((V=(E=t.preferences)==null?void 0:E.mapVisualOptions)==null?void 0:V.projectionScale)||1,onChange:I=>{var j;i({...t.preferences,mapVisualOptions:{...(j=t.preferences)==null?void 0:j.mapVisualOptions,projectionScale:Number(I.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((v=(T=(A=t.preferences)==null?void 0:A.mapVisualOptions)==null?void 0:T.projectionOffset)==null?void 0:v[0])||0,onChange:I=>{var j,k,R,P;i({...t.preferences,mapVisualOptions:{...(j=t.preferences)==null?void 0:j.mapVisualOptions,projectionOffset:[Number(I.target.value),((P=(R=(k=t.preferences)==null?void 0:k.mapVisualOptions)==null?void 0:R.projectionOffset)==null?void 0:P[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((f=(M=(D=t.preferences)==null?void 0:D.mapVisualOptions)==null?void 0:M.projectionOffset)==null?void 0:f[1])||0,onChange:I=>{var j,k,R,P;i({...t.preferences,mapVisualOptions:{...(j=t.preferences)==null?void 0:j.mapVisualOptions,projectionOffset:[((P=(R=(k=t.preferences)==null?void 0:k.mapVisualOptions)==null?void 0:R.projectionOffset)==null?void 0:P[0])||0,Number(I.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Ra,{})]})}function Fa({color:t,onColorChange:n,onClose:a}){const[r,i]=C.useState(0),[d,o]=C.useState(100),[c,l]=C.useState(50),[x,p]=C.useState(t);C.useEffect(()=>{const g=da(t);if(g){const w=ua(g.r,g.g,g.b);i(w.h),o(w.s),l(w.l),p(t)}},[t]);const h=g=>{i(g),y(g,d,c)},u=g=>{const w=g.currentTarget.getBoundingClientRect(),E=Math.max(0,Math.min(1,(g.clientX-w.left)/w.width)),V=Math.max(0,Math.min(1,(g.clientY-w.top)/w.height)),A=E*100,T=(1-V)*100;o(A),l(T),y(r,A,T)},y=(g,w,E)=>{const V=Cr(g,w,E),A=Nr(V.r,V.g,V.b);p(A)},b=g=>{if(p(g),/^#[0-9A-Fa-f]{6}$/.test(g)){const w=da(g);if(w){const E=ua(w.r,w.g,w.b);i(E.h),o(E.s),l(E.l)}}},m=()=>{/^#[0-9A-Fa-f]{6}$/.test(x)&&(n(x),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:u,onMouseMove:g=>{g.buttons===1&&u(g)},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:`${d}%`,top:`${100-c}%`,backgroundColor:x}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:g=>h(Number(g.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:x,onChange:g=>b(g.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:x}}),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:m,children:"OK"})]})]})}function da(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 Nr(t,n,a){return"#"+((1<<24)+(t<<16)+(n<<8)+a).toString(16).slice(1)}function ua(t,n,a){t/=255,n/=255,a/=255;const r=Math.max(t,n,a),i=Math.min(t,n,a);let d=0,o=0;const c=(r+i)/2;if(r!==i){const l=r-i;switch(o=c>.5?l/(2-r-i):l/(r+i),r){case t:d=((n-a)/l+(n<a?6:0))/6;break;case n:d=((a-t)/l+2)/6;break;case a:d=((t-n)/l+4)/6;break}}return{h:Math.round(d*360),s:Math.round(o*100),l:Math.round(c*100)}}function Cr(t,n,a){t/=360,n/=100,a/=100;let r,i,d;if(n===0)r=i=d=a;else{const o=(x,p,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?x+(p-x)*6*h:h<.5?p:h<.6666666666666666?x+(p-x)*(.6666666666666666-h)*6:x),c=a<.5?a*(1+n):a+n-a*n,l=2*a-c;r=o(l,c,t+1/3),i=o(l,c,t),d=o(l,c,t-1/3)}return{r:Math.round(r*255),g:Math.round(i*255),b:Math.round(d*255)}}const ma=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],Sr=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function ts({value:t,onChange:n,label:a}){const[r,i]=C.useState(!1),[d,o]=C.useState(!1),c=()=>{const l=ma.find(x=>x.value===t);return l?l.color:t.startsWith("#")?t:ma[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:i,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:c()},"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:Sr.map(l=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",c()===l?"border-gray-900":"border-transparent"),style:{backgroundColor:l},onClick:()=>{n(l),i(!1)},children:e.jsx("span",{className:"sr-only",children:l})},l))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{o(!0),i(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a})]}),d&&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:()=>o(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Fa,{color:c(),onColorChange:l=>{n(l),o(!1)},onClose:()=>o(!1)})})]})]})}const wr=["auto","number","currency","percent","scientific","date"],Tr=[{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"}],Er=[{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"}],Ir=t=>t.charAt(0).toUpperCase()+t.slice(1);function Vs({formatOptions:t={},onFormatOptionsChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const i=t.type||"auto",d=(c,l)=>{n({...t,[c]:l})},o=()=>i==="currency"?2:i==="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:i,onValueChange:c=>d("type",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:wr.map(c=>e.jsx(s.SelectItem,{value:c,className:"text-xs",children:c==="auto"?"Auto (Default)":Ir(c)},c))})]})]}),i!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent"].includes(i)&&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??o(),onChange:c=>d("decimalPlaces",parseInt(c.target.value)||0),className:"h-8 text-xs"})})]}),i==="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:c=>d("currency",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Tr.map(c=>e.jsx(s.SelectItem,{value:c.value,className:"text-xs",children:c.label},c.value))})]})]}),["number","currency"].includes(i)&&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:c=>d("useSuffix",c)})]}),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:c=>d("locale",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Er.map(c=>e.jsx(s.SelectItem,{value:c.value,className:"text-xs",children:c.label},c.value))})]})]}),i==="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:c=>d("prefix",c.target.value),className:"h-8 text-xs"})})]}),i==="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:c=>d("suffix",c.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(i)&&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:c=>d("negativeInParentheses",c)})]}),i==="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:c=>d("multiplyBy",c.target.value?parseFloat(c.target.value):void 0),className:"h-8 text-xs"})})]}),i==="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:c=>d("dateFormat",c.target.value),className:"h-8 text-xs"})})]})]})]})}function kr(){const t=s.useDashboardStore(c=>c.dashboard.filters),n=s.useEditorStore(c=>c.frame),{setFrame:a}=s.useEditorActions(),{columns:r}=s.useColumns(),{assignFilter:i}=s.useAssignFilter();function d(c){const l=i(c,"frame");a({...n,filterId:l})}const o=t==null?void 0:t.find(c=>c.id===n.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(Dr,{onSelect:d,columns:r}),o&&e.jsx(s.FilterHeader,{filter:o})]})}function Dr({columns:t,onSelect:n}){var o;const[a,r]=at.useState(!1),[i,d]=at.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:[i?((o=t.find(c=>c.name===i))==null?void 0:o.label)||i:"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 column found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(c=>e.jsxs(s.CommandItem,{value:c.name,onSelect:l=>{const x=l===i?"":l;d(x),r(!1),x&&n(c)},children:[c.label||c.name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",i===c.name?"opacity-100":"opacity-0")})]},c.id))})]})]})})]})}const Ar=[{value:"difference",label:"Difference"},{value:"change",label:"Change (%)"},{value:"change_difference",label:"Change + Difference"},{value:"ratio",label:"Ratio"}],Lr=[{value:"arrow_badge",label:"Arrow + Badge"},{value:"arrow",label:"Arrow Only"},{value:"badge",label:"Badge Only"},{value:"none",label:"None"}];function Mr({cardType:t="table"}){var p,h,u,y,b;const n=s.useEditorStore(m=>m.card),a=s.useEditorStore(m=>{var g;return(g=m.card)==null?void 0:g.preferences}),r=s.useEditorStore(m=>m.actions.setCardPreferences),d=(((p=n.config)==null?void 0:p.metricColumns)||[]).some(m=>m.comparisonType&&m.comparisonType!=="none"),o=((h=a==null?void 0:a.tableVisualOptions)==null?void 0:h.metricComparison)||{},c=m=>{r({...a,tableVisualOptions:{...a==null?void 0:a.tableVisualOptions,metricComparison:{...o,...m}}})},l={increase:((u=o.colors)==null?void 0:u.increase)||"green",decrease:((y=o.colors)==null?void 0:y.decrease)||"red",neutral:((b=o.colors)==null?void 0:b.neutral)||"neutral"},x=m=>{r({...a,allowDownload:m})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsxs(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:[d&&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(Ca,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison Settings"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated As"}),e.jsxs(s.Select,{value:o.calculatedAs||"change_difference",onValueChange:m=>c({calculatedAs:m}),children:[e.jsx(s.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Ar.map(m=>e.jsx(s.SelectItem,{value:m.value,className:"text-xs",children:m.label},m.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Number Format"}),e.jsx(Vs,{formatOptions:o.formatOptions||{},onFormatOptionsChange:m=>c({formatOptions:m}),showTitle:!1})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator Style"}),e.jsxs(s.Select,{value:o.indicatorStyle||"arrow_badge",onValueChange:m=>c({indicatorStyle:m}),children:[e.jsx(s.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Lr.map(m=>e.jsx(s.SelectItem,{value:m.value,className:"text-xs",children:m.label},m.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Colors"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ts,{value:l.increase,onChange:m=>c({colors:{...l,increase:m}}),label:"Increase"}),e.jsx(ts,{value:l.decrease,onChange:m=>c({colors:{...l,decrease:m}}),label:"Decrease"}),e.jsx(ts,{value:l.neutral,onChange:m=>c({colors:{...l,neutral:m}}),label:"No Change"})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Lower is Better"}),e.jsx(s.Checkbox,{checked:o.lowerIsBetter||!1,onCheckedChange:m=>c({lowerIsBetter:!!m})})]})]})]}),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(Ra,{}),e.jsx(kr,{})]})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{onCheckedChange:x,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 Or(){var r;const t=s.useEditorStore(i=>i.card.preferences),{setCardPreferences:n}=s.useEditorStore(i=>i.actions);function a(i){n({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:i==="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 Rr(){return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(Ps,{chartType:"text"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Text Type"}),e.jsx(Or,{})]})]})}const Fr=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function Pr(){var T,v,D,M,f,I,j,k,R,P;const t=s.useEditorStore(N=>N.card),n=s.useEditorStore(N=>{var L;return(L=N.card)==null?void 0:L.preferences}),a=Ae.useEffectiveEditorCardType(),{setCardPreferences:r,updateCardInFrame:i}=s.useEditorActions(),d=C.useMemo(()=>a!==t.type?{...t,type:a}:t,[t,a]),{data:o}=s.useDashboardCardQuery(d),[c,l]=C.useState({}),[x,p]=C.useState(null),[h,u]=C.useState(null),y=C.useMemo(()=>{var F,O,_,Q,B,K,se;if(!(o!=null&&o.records)||o.records.length===0)return[];const N=a==="stackedBar"||a==="stackedLine",L=a==="bar"||a==="line"||a==="horizontalBar"||a==="bullet"||a==="combo"||a==="area"||a==="stackedArea",S=((F=t==null?void 0:t.config)==null?void 0:F.pivotByColumns)&&t.config.pivotByColumns.length>0;if((N||L)&&S){if(o.pivotSchema&&Array.isArray(o.pivotSchema)){const H=new Set;return o.pivotSchema.forEach(te=>{te.alias&&H.add(te.alias)}),Array.from(H)}if(o.records.length>0){const H=o.records[0],te=Object.keys(H),z=new Set;(O=t==null?void 0:t.config)!=null&&O.groupByColumns&&t.config.groupByColumns.forEach(X=>{z.add(X.label||X.name),z.add(X.alias||X.name)});const W=new Set;return(_=t==null?void 0:t.config)!=null&&_.metricColumns&&t.config.metricColumns.forEach(X=>{const ne=X.alias||X.name;W.add(ne),W.add(`${ne}_count`),W.add(`${ne}_sum`),W.add(`${ne}_avg`),W.add(`${ne}_min`),W.add(`${ne}_max`);const me=X.entityName||X.qualifiedEntityName;me&&(W.add(`${me}_${ne}`),W.add(`${me}_${ne}_count`))}),te.filter(X=>!z.has(X)&&!W.has(X))}}if((L||N)&&!S&&((B=(Q=t==null?void 0:t.config)==null?void 0:Q.metricColumns)!=null&&B.length))return t.config.metricColumns.map(H=>H.alias||H.label||H.name);if((se=(K=t==null?void 0:t.config)==null?void 0:K.groupByColumns)!=null&&se.length){const H=t.config.groupByColumns[0],te=H.label||H.name,z=new Set;return o.records.forEach(W=>{const le=W[te];le!=null&&z.add(String(le))}),Array.from(z)}return[]},[o,(T=t==null?void 0:t.config)==null?void 0:T.groupByColumns,(v=t==null?void 0:t.config)==null?void 0:v.pivotByColumns,(D=t==null?void 0:t.config)==null?void 0:D.metricColumns,t==null?void 0:t.type]),b=C.useMemo(()=>s.getDefaultChartColors(),[]);C.useEffect(()=>{const N={};y.forEach((L,S)=>{N[L]=s.getColorForValue(L,S,n==null?void 0:n.colorConfig)}),l(N)},[y,n==null?void 0:n.colorConfig,b]);const m=(N,L)=>{const S={...c,[N]:L};l(S);const F={...n||{},colorConfig:{segments:S}};r(F);const O={...t,preferences:F};i(O)},g=(N,L)=>{var B;const S=b[L%b.length],{[N]:F,...O}=((B=n==null?void 0:n.colorConfig)==null?void 0:B.segments)||{},_={...n||{},colorConfig:{segments:O}};r(_);const Q={...t,preferences:_};i(Q),l(K=>({...K,[N]:S}))};if(!y.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((f=(M=t==null?void 0:t.config)==null?void 0:M.groupByColumns)==null?void 0:f.length)||((j=(I=t==null?void 0:t.config)==null?void 0:I.pivotByColumns)==null?void 0:j.length):(R=(k=t==null?void 0:t.config)==null?void 0:k.groupByColumns)==null?void 0:R.length)||["table","kpi","text","custom","heatmap"].includes(a))return null;const V=()=>{const N={...n||{},colorConfig:{segments:{}}};r(N);const L={...t,preferences:N};i(L);const S={};y.forEach((F,O)=>{S[F]=s.getColorForValue(F,O,void 0)}),l(S)},A=Object.keys(((P=n==null?void 0:n.colorConfig)==null?void 0:P.segments)||{}).length>0;return e.jsxs(s.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fn,{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:A&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:V,children:[e.jsx(Xt,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:y.map((N,L)=>{const S=s.isDefaultColor(c[N],L),F=!S;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:x===N,onOpenChange:O=>p(O?N: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:c[N]}})}),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:b.slice(0,10).map((O,_)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",c[N]===O?"border-gray-900":"border-transparent"),style:{backgroundColor:O},onClick:()=>{m(N,O),p(null)},children:[_===L%b.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:O})]},`default-${_}`))})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Popular Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:Fr.map((O,_)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",c[N]===O?"border-2 border-gray-900":O==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:O},onClick:()=>{m(N,O),p(null)},children:e.jsx("span",{className:"sr-only",children:O})},`preset-${_}`))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsx("button",{className:"text-sm font-medium text-blue-600 hover:text-blue-700",onClick:()=>{u({value:N,color:c[N]}),p(null)},children:"Custom color"}),!S&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{g(N,L),p(null)},children:[e.jsx(Xt,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:N}),F&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},N)})}),h&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>u(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Fa,{color:h.color,onColorChange:N=>{m(h.value,N),u(null)},onClose:()=>u(null)})})]})]})})]})}function _e({value:t,onSave:n,placeholder:a="",type:r="text",className:i=""}){const[d,o]=C.useState(t??""),[c,l]=C.useState(!1);C.useEffect(()=>{o(t??"")},[t]);const x=()=>{n(d),l(!1)},p=()=>{o(t??""),l(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${i}`,children:[e.jsx(s.Input$1,{placeholder:a,type:r,value:c?d:t??"",onChange:h=>{o(h.target.value),l(!0)},onFocus:()=>l(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&c&&d!==t?x():h.key==="Escape"&&p()},"aria-label":a||"Edit field"}),c&&d!==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:x,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:p,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function Xs({axis:t,label:n,type:a,config:r,onChange:i,defaultTitle:d,hidePosition:o}){var y,b,m,g,w,E,V,A,T,v,D,M,f,I;const c=(j,k)=>{i({...r??{},[j]:k})},l=(j,k)=>{var L,S,F,O;const R=j==="enabled"&&k===!0,P=(L=r==null?void 0:r.name)==null?void 0:L.text,N=R&&!P&&d;i({...r??{},name:{...r==null?void 0:r.name,enabled:j==="enabled"?k:((S=r==null?void 0:r.name)==null?void 0:S.enabled)??!1,text:j==="text"?k:N?d:P,fontSize:j==="fontSize"?k:(F=r==null?void 0:r.name)==null?void 0:F.fontSize,fontWeight:j==="fontWeight"?k:(O=r==null?void 0:r.name)==null?void 0:O.fontWeight}})},x=(j,k)=>{var R,P;i({...r??{},labels:{enabled:j==="enabled"?k:((R=r==null?void 0:r.labels)==null?void 0:R.enabled)??!0,rotation:j==="rotation"?k:(P=r==null?void 0:r.labels)==null?void 0:P.rotation}})},p=(j,k)=>{i({...r??{},scale:{...r==null?void 0:r.scale,[j]:k===""?"auto":Number(k)}})},h=t==="x"?["auto","top","bottom"]:["auto","left","right"],u=["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:j=>c("enabled",j),onClick:j=>j.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 gap-2",children:[e.jsx(s.Checkbox,{id:`${t}-title-enabled`,checked:((y=r==null?void 0:r.name)==null?void 0:y.enabled)??!1,onCheckedChange:j=>l("enabled",j===!0)}),e.jsx(s.Label,{htmlFor:`${t}-title-enabled`,className:"text-xs font-medium cursor-pointer",children:"TITLE"})]}),((b=r==null?void 0:r.name)==null?void 0:b.enabled)&&e.jsxs("div",{className:"space-y-2 pl-6",children:[e.jsx(_e,{placeholder:`${n} title`,value:((m=r==null?void 0:r.name)==null?void 0:m.text)||"",onSave:j=>l("text",j),className:""}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Size"}),e.jsx("div",{className:"w-14",children:e.jsx(_e,{type:"number",placeholder:"12",value:String(((g=r==null?void 0:r.name)==null?void 0:g.fontSize)||12),onSave:j=>l("fontSize",Number(j)||12),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Weight"}),e.jsxs(s.Select,{value:((w=r==null?void 0:r.name)==null?void 0:w.fontWeight)||"normal",onValueChange:j=>l("fontWeight",j),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:"normal",className:"text-xs",children:"Normal"}),e.jsx(s.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]})]})]})]}),!o&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(s.Select,{value:(r==null?void 0:r.position)||"auto",onValueChange:j=>c("position",j),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:h.map(j=>e.jsx(s.SelectItem,{value:j,className:"text-xs",children:j==="auto"?"Auto (Default)":s.titleCase(j)},j))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(s.SmallSwitch,{checked:((E=r==null?void 0:r.labels)==null?void 0:E.enabled)!==!1,onCheckedChange:j=>x("enabled",j)})]}),((V=r==null?void 0:r.labels)==null?void 0:V.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(((A=r==null?void 0:r.labels)==null?void 0:A.rotation)||"auto"),onValueChange:j=>x("rotation",j==="auto"?"auto":Number(j)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(j=>e.jsx(s.SelectItem,{value:j,className:"text-xs",children:j==="auto"?"Auto (Default)":`${j}°`},j))})]})]})]}),a==="value"&&e.jsx(Vs,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:j=>i({...r,formatOptions:j}),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(_e,{type:"number",placeholder:"auto",value:((T=r==null?void 0:r.scale)==null?void 0:T.min)==="auto"||((v=r==null?void 0:r.scale)==null?void 0:v.min)===void 0?"":String(r.scale.min),onSave:j=>p("min",j),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(_e,{type:"number",placeholder:"auto",value:((D=r==null?void 0:r.scale)==null?void 0:D.max)==="auto"||((M=r==null?void 0:r.scale)==null?void 0:M.max)===void 0?"":String(r.scale.max),onSave:j=>p("max",j),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(_e,{type:"number",placeholder:"auto",value:((f=r==null?void 0:r.scale)==null?void 0:f.stepSize)==="auto"||((I=r==null?void 0:r.scale)==null?void 0:I.stepSize)===void 0?"":String(r.scale.stepSize),onSave:j=>p("stepSize",j),className:""})})]})]})]})]})]})}function Zs(t,n,a){var d,o,c;if(t==="x"){const l=(o=(d=n==null?void 0:n.config)==null?void 0:d.groupByColumns)==null?void 0:o[0];return(l==null?void 0:l.label)||(l==null?void 0:l.name)||""}const r=((c=n==null?void 0:n.config)==null?void 0:c.metricColumns)||[],i=(a==null?void 0:a.datasetOptions)||[];if(t==="y"){const l=r.filter((x,p)=>{const h=i.find(u=>u.idx===p);return!h||h.yAxisId!=="y2"});return l.length===1&&(l[0].label||l[0].name)||""}if(t==="y2"){const l=r.filter((x,p)=>{const h=i.find(u=>u.idx===p);return(h==null?void 0:h.yAxisId)==="y2"});return l.length===1&&(l[0].label||l[0].name)||""}return""}function Vr(){const t=s.useEditorStore(l=>l.card),n=s.useEditorStore(l=>{var x;return(x=l.card)==null?void 0:x.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions(),i=Ae.useEffectiveEditorCardType();if(!t||["tornado","pyramid","kpi","treemap"].includes(i))return null;const d=s.AxisConfigurator.getAxisInfo(i,n);if(!d.hasXAxis&&!d.hasYAxis)return null;const o=(l,x)=>{let p;l==="x"?p="xAxisConfig":l==="y"?p="yAxisConfig":p="secondaryYAxisConfig";const h={...n||{},[p]:x};a(h);const u={...t,preferences:h};r(u)},c=d.hasY2Axis&&i==="combo";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(nt,{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:[d.hasXAxis&&e.jsx(Xs,{axis:"x",label:"X-Axis",type:d.xAxisType,config:s.mergeAxisConfig(s.getDefaultAxisConfig(i,"x"),n==null?void 0:n.xAxisConfig),onChange:l=>o("x",l),defaultTitle:Zs("x",t,n)}),d.hasYAxis&&e.jsx(Xs,{axis:"y",label:c?"Y-Axis (Left)":"Y-Axis",type:d.yAxisType,config:s.mergeAxisConfig(s.getDefaultAxisConfig(i,"y"),n==null?void 0:n.yAxisConfig),onChange:l=>o("y",l),defaultTitle:Zs("y",t,n)}),c&&e.jsx(Xs,{axis:"y2",label:"Y2-Axis (Right)",type:"value",config:s.mergeAxisConfig({enabled:!0,position:"right"},n==null?void 0:n.secondaryYAxisConfig),onChange:l=>o("y2",l),defaultTitle:Zs("y2",t,n),hidePosition:!0})]})})]})}function Br(){const t=s.useEditorStore(h=>h.card),n=Ae.useEffectiveEditorCardType(),a=s.useEditorStore(h=>{var u,y,b,m;return(m=(b=(y=(u=h.card)==null?void 0:u.preferences)==null?void 0:y.chartOptions)==null?void 0:b.plugins)==null?void 0:m.legend}),{setLegendOptions:r}=s.useEditorActions();if(!t||!s.chartSupportsLegend(n))return null;const i=s.getDefaultLegendConfig(n),d=(i==null?void 0:i.display)??!0,o=(i==null?void 0:i.position)??"top",c=(i==null?void 0:i.align)??"center",l=(h,u)=>{const y={...a,[h]:u};r(y)},x=["top","bottom","left","right"],p=["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(mn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:(a==null?void 0:a.display)??d,onCheckedChange:h=>l("display",h)})]}),((a==null?void 0:a.display)??d)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(a==null?void 0:a.position)||o,onValueChange:h=>l("position",h),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:x.map(h=>e.jsx(s.SelectItem,{value:h,className:"text-xs",children:s.titleCase(h)},h))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(s.Select,{value:(a==null?void 0:a.align)||c,onValueChange:h=>l("align",h),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:p.map(h=>e.jsx(s.SelectItem,{value:h,className:"text-xs",children:s.titleCase(h)},h))})]})]})]})]})})]})}function zr(){var L,S,F,O,_,Q,B,K,se,H,te;const t=s.useEditorStore(z=>z.card),n=Ae.useEffectiveEditorCardType(),a=s.useEditorStore(z=>{var W,le;return(le=(W=z.card)==null?void 0:W.preferences)==null?void 0:le.dataLabelsConfig}),r=s.useEditorStore(z=>{var W;return(W=z.card)==null?void 0:W.preferences}),{setCardPreferences:i,updateCardInFrame:d}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(n))return null;const o=n==="bullet"?((L=r==null?void 0:r.bulletConfig)==null?void 0:L.orientation)??(((S=r==null?void 0:r.chartOptions)==null?void 0:S.indexAxis)==="x"?"vertical":"horizontal"):void 0,c=o!=null?o==="horizontal":((F=r==null?void 0:r.chartOptions)==null?void 0:F.indexAxis)==="y",l=n==="stackedBar"||n==="stackedLine",x=n==="pie"||n==="doughnut"||n==="polarArea"||n==="funnel",p=!x,h=n==="bubble"||n==="scatter",u=(_=(O=r==null?void 0:r.chartOptions)==null?void 0:O.plugins)==null?void 0:_.datalabels,y=(u==null?void 0:u.display)!==!1&&((u==null?void 0:u.anchor)||(u==null?void 0:u.align)),b=s.getDefaultDataLabelsConfig(n,t.preferences),m=a??b,g=(b==null?void 0:b.enabled)??y??!1,w=(a==null?void 0:a.enabled)!==void 0?a.enabled:g,E=(z,W)=>{const ne={...b??{},...a??{},[z]:W};z==="enabled"&&(ne.display=W,W&&h&&!ne.position&&(ne.position="bottom")),z==="position"&&h&&(ne.position="bottom");const me={...t.preferences||{},dataLabelsConfig:ne};i(me);const ee={...t,preferences:me};d(ee)},V=(z,W)=>{const le=a??{},ne={...b??{},...le,font:{...le.font||{},[z]:W}},me={...t.preferences||{},dataLabelsConfig:ne};i(me);const ee={...t,preferences:me};d(ee)},A=(z,W)=>{const le=a??{},ne={...b??{},...le,formatOptions:{...le.formatOptions||{},[z]:W}},me={...t.preferences||{},dataLabelsConfig:ne};i(me);const ee={...t,preferences:me};d(ee)},T=()=>{const z=n;return z==="stackedBar"||z==="stackedLine"||z==="pie"||z==="doughnut"?"center":c?"right":"top"},v=n!=="treemap"&&n!=="heatmap",D=n!=="treemap",M=T();let f=[];if(v)if(h)f=["bottom"];else if(l||x)f=["center"];else{const z=c?["center","left","right"]:["center","top","bottom"];f=["auto",...n==="bullet"?z:z.filter(le=>le!==M),"custom"]}const I=()=>s.titleCase(M),j=["center","start","end"],k=["center","start","end","top","bottom"],R=p?["auto","number","currency","percent","none"]:["number","currency","percent","none"],P=[{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"}],N=[{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(wn,{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:w,onCheckedChange:z=>E("enabled",z)})]}),w&&e.jsxs(e.Fragment,{children:[v&&!l&&!x&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:h?(m==null?void 0:m.position)||"bottom":(m==null?void 0:m.position)||"auto",onValueChange:z=>E("position",z),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:f.map(z=>e.jsx(s.SelectItem,{value:z,className:"text-xs",children:z==="auto"?I():z==="custom"?"Custom (Advanced)":s.titleCase(z)},z))})]})]}),l&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Show Total"}),e.jsx(s.SmallSwitch,{checked:(a==null?void 0:a.showTotal)??!1,onCheckedChange:z=>E("showTotal",z)})]}),(m==null?void 0:m.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:(m==null?void 0:m.anchor)||"center",onValueChange:z=>E("anchor",z),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:j.map(z=>e.jsx(s.SelectItem,{value:z,className:"text-xs",children:s.titleCase(z)},z))})]})]}),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((m==null?void 0:m.align)||"center"),onValueChange:z=>E("align",z),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:k.map(z=>e.jsx(s.SelectItem,{value:z,className:"text-xs",children:s.titleCase(z)},z))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(m==null?void 0:m.format)||(p?"auto":"none"),onValueChange:z=>E("format",z),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:R.map(z=>e.jsx(s.SelectItem,{value:z,className:"text-xs",children:z==="auto"&&p?"Auto (Use Axis)":z==="none"?"None (Raw Value)":s.titleCase(z)},z))})]})]}),(m==null?void 0:m.format)&&!["auto","none"].includes(m.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(m.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(_e,{type:"number",placeholder:"0",value:String(((Q=m==null?void 0:m.formatOptions)==null?void 0:Q.decimalPlaces)??(m.format==="currency"?2:m.format==="percent"?1:0)),onSave:z=>A("decimalPlaces",Number(z)),className:""})})]}),m.format==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Currency"}),e.jsxs(s.Select,{value:((B=m==null?void 0:m.formatOptions)==null?void 0:B.currency)||"USD",onValueChange:z=>A("currency",z),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:P.map(z=>e.jsx(s.SelectItem,{value:z.value,className:"text-xs",children:z.label},z.value))})]})]}),["number","currency"].includes(m.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:((K=m==null?void 0:m.formatOptions)==null?void 0:K.useSuffix)??!1,onCheckedChange:z=>A("useSuffix",z)})]}),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:((se=m==null?void 0:m.formatOptions)==null?void 0:se.locale)||"en-US",onValueChange:z=>A("locale",z),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:N.map(z=>e.jsx(s.SelectItem,{value:z.value,className:"text-xs",children:z.label},z.value))})]})]})]}),D&&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(_e,{type:"number",placeholder:"12",value:String(((H=m==null?void 0:m.font)==null?void 0:H.size)||12),onSave:z=>V("size",Number(z)),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:((te=m==null?void 0:m.font)==null?void 0:te.weight)||"normal",onValueChange:z=>V("weight",z),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:(m==null?void 0:m.color)==="auto"||!(m!=null&&m.color)?"auto":"custom",onValueChange:z=>{z==="auto"&&E("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(_e,{type:"number",placeholder:"0",value:String((m==null?void 0:m.rotation)||0),onSave:z=>E("rotation",Number(z)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}const xa={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%
|
|
188
|
+
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 u,y,b,m,g,w,E,V,A,T;const t=s.useEditorStore(v=>v.card),{setCardPreferences:n}=s.useEditorActions(),a=Ae.useEffectiveEditorCardType(),r=((u=t.config)==null?void 0:u.metricColumns)||[],i=((y=t.config)==null?void 0:y.groupByColumns)||[],d=r.length===2&&i.length===0,o=r.some(v=>v.comparisonType&&v.comparisonType!=="none");if(!(a==="kpi"&&(d||o)))return null;const l=((m=(b=t.preferences)==null?void 0:b.kpiVisualOptions)==null?void 0:m.metricComparison)||{},x=v=>{var M;const D={...t.preferences,kpiVisualOptions:{...(M=t.preferences)==null?void 0:M.kpiVisualOptions,metricComparison:{...l,...v}}};n(D)},p=o||l.enabled,h=r.some(v=>v.comparisonType==="previous_period"||v.comparisonType==="same_period_last_year"||v.comparisonType==="start_vs_end");return e.jsxs(s.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ca,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[d&&r.length===2&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(s.SmallSwitch,{id:"enable-comparison",checked:l.enabled||!1,onCheckedChange:v=>x({enabled:v,...v&&!l.calculationType?{calculationType:"difference"}:{}})})]}),p&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Info,{className:"h-3 w-3 cursor-help text-muted-foreground"})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-xs",children:(()=>{const v=l.calculationType||"difference",D=xa[v];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:D==null?void 0:D.label}),e.jsx("p",{children:D==null?void 0:D.description}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Formula:"})," ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-[10px]",children:D==null?void 0:D.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",D==null?void 0:D.example]})]})})()})]})]}),e.jsxs(s.Select,{value:l.calculationType||"difference",onValueChange:v=>x({calculationType:v}),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(xa).map(([v,D])=>e.jsx(s.SelectItem,{value:v,className:"text-xs",children:D.label},v))})]})]}),e.jsx(Vs,{formatOptions:l.formatOptions||{},onFormatOptionsChange:v=>x({formatOptions:v}),showTitle:!0,title:"COMPARISON FORMAT"}),(h||d)&&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"}),d&&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:l.position||"right",onValueChange:v=>x({position:v}),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"right",className:"text-xs",children:"Right"}),e.jsx(s.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(s.SelectItem,{value:"top",className:"text-xs",children:"Top"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-arrow",checked:l.showArrow!==!1,onCheckedChange:v=>x({showArrow:v})}),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:l.showColor!==!1,onCheckedChange:v=>x({showColor:v})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),l.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(ts,{value:((g=l.colorConfig)==null?void 0:g.increase)||"green",onChange:v=>x({colorConfig:{...l.colorConfig,increase:v}}),label:"Primary > Secondary"}),e.jsx(ts,{value:((w=l.colorConfig)==null?void 0:w.decrease)||"red",onChange:v=>x({colorConfig:{...l.colorConfig,decrease:v}}),label:"Primary < Secondary"}),e.jsx(ts,{value:((E=l.colorConfig)==null?void 0:E.noChange)||"neutral",onChange:v=>x({colorConfig:{...l.colorConfig,noChange:v}}),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:l.conditionalLabel||!1,onCheckedChange:v=>x({conditionalLabel:v})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),l.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=l.conditionalLabels)==null?void 0:V.increase)??"Increase",onChange:v=>x({conditionalLabels:{...l.conditionalLabels,increase:v.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:((A=l.conditionalLabels)==null?void 0:A.decrease)??"Decrease",onChange:v=>x({conditionalLabels:{...l.conditionalLabels,decrease:v.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:((T=l.conditionalLabels)==null?void 0:T.noChange)??"No change",onChange:v=>x({conditionalLabels:{...l.conditionalLabels,noChange:v.target.value}}),placeholder:"No change",className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-name",className:"text-xs text-muted-foreground",children:"Previous Label"}),e.jsx(s.Input,{id:"label-name",type:"text",value:l.labelName??"",onChange:v=>x({labelName:v.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function _r(){var d,o;const t=s.useEditorStore(c=>c.card),{setCardPreferences:n}=s.useEditorActions();if(Ae.useEffectiveEditorCardType()!=="kpi")return null;const r=((o=(d=t.preferences)==null?void 0:d.kpiVisualOptions)==null?void 0:o.formatOptions)||{},i=c=>{var x;const l={...t.preferences,kpiVisualOptions:{...(x=t.preferences)==null?void 0:x.kpiVisualOptions,formatOptions:c}};n(l)};return e.jsxs(s.AccordionItem,{value:"kpi-format",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Hash,{className:"h-4 w-4"}),e.jsx("span",{children:"Number Format"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:e.jsx(Vs,{formatOptions:r,onFormatOptionsChange:i,showTitle:!1})})]})}function $r(){var d;const t=s.useEditorStore(o=>{var c;return(c=o.card)==null?void 0:c.type}),n=s.useEditorStore(o=>{var c;return(c=o.card)==null?void 0:c.preferences}),{setCardPreferences:a}=s.useEditorActions();if(t!=="treemap")return null;const r=((d=n==null?void 0:n.chartOptions)==null?void 0:d.treemapColorMode)??"branch",i=o=>{const c={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,treemapColorMode:o}};a(c)};return e.jsxs(s.AccordionItem,{value:"treemap-color-mode",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TbChartTreemap,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Treemap Colors"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:e.jsxs(s.RadioGroup,{value:r,onValueChange:o=>i(o??"branch"),className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:"treemap-color-branch",value:"branch"}),e.jsxs(s.Label,{htmlFor:"treemap-color-branch",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Shade by value (default)"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Keeps parent hue and adjusts lightness based on the node's share within the branch."})]})]}),e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:"treemap-color-category",value:"category"}),e.jsxs(s.Label,{htmlFor:"treemap-color-category",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Single color per category"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Applies the top-level color to all descendants without lightening/darkening."})]})]})]})})]})}const Gr=Object.keys(s.HEATMAP_PRESET_PALETTES);function Kr(){const t=s.useEditorStore(u=>u.card),n=s.useEditorStore(u=>{var y;return(y=u.card)==null?void 0:y.preferences}),{setCardPreferences:a}=s.useEditorActions(),r=(t==null?void 0:t.type)==="heatmap",i=(n==null?void 0:n.heatmapConfig)||{},d=i.colorPalette??"green",o=i.legendPosition??"bottom",c=C.useMemo(()=>i.colorRange&&i.colorRange[0]&&i.colorRange[1]?[i.colorRange[0],i.colorRange[1]]:[...s.DEFAULT_HEATMAP_CUSTOM_RANGE],[i.colorRange]),l=u=>{const y={...i,...u};y.colorPalette!=="custom"?delete y.colorRange:(!y.colorRange||!y.colorRange[0]||!y.colorRange[1])&&(y.colorRange=[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]),a({...n||{},heatmapConfig:y})},x=u=>{l({colorPalette:u,colorRange:u==="custom"?i.colorRange??[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},p=(u,y)=>{const b=[...c];b[u]=y,l({colorPalette:"custom",colorRange:b})},h=u=>{l({legendPosition:u})};return r?e.jsxs(s.AccordionItem,{value:"heatmap-color-config",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Grid3x3,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Heatmap Settings"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs(s.RadioGroup,{value:d,onValueChange:u=>x(u??"blue"),className:"space-y-3",children:[Gr.map(u=>{const y=s.HEATMAP_PRESET_PALETTES[u];return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:`heatmap-${u}`,value:u}),e.jsxs(s.Label,{htmlFor:`heatmap-${u}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:y.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${y.start}, ${y.end})`}})]})]},u)}),e.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.RadioGroupItem,{id:"heatmap-custom",value:"custom"}),e.jsx(s.Label,{htmlFor:"heatmap-custom",className:"text-sm font-medium",children:"Custom colors"})]}),d==="custom"&&e.jsxs("div",{className:"flex flex-col gap-3 pl-6",children:[e.jsx(ts,{value:c[0],onChange:u=>p(0,u),label:"Start color"}),e.jsx(ts,{value:c[1],onChange:u=>p(1,u),label:"End color"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Color scale position"}),e.jsxs(s.Select,{value:o,onValueChange:u=>h(u??"bottom"),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["top","bottom","left","right"].map(u=>e.jsx(s.SelectItem,{value:u,className:"text-xs",children:u[0].toUpperCase()+u.slice(1)},u))})]})]})]})]}):null}const ha=["poor","satisfactory","good"];function pa(t){if(!t)return;const n={...t};return n.targetMetricKey||delete n.targetMetricKey,n.comparativeMetricKey||delete n.comparativeMetricKey,!n.targetValue&&n.targetValue!==0&&delete n.targetValue,(!n.rangeKeys||Object.keys(n.rangeKeys).length===0)&&delete n.rangeKeys,(!n.ranges||Object.keys(n.ranges).length===0)&&delete n.ranges,(!n.rangeLabels||Object.keys(n.rangeLabels).length===0)&&delete n.rangeLabels,n}function Ur(){var R,P;const t=s.useEditorStore(N=>N.card.preferences),n=s.useEditorStore(N=>N.card),a=s.useEditorStore(N=>N.isDevMode),{setCardPreferences:r,setChartOrientation:i}=s.useEditorActions(),d=C.useMemo(()=>(t==null?void 0:t.bulletConfig)||{},[t==null?void 0:t.bulletConfig]),c=s.hasValidCardConfig(n==null?void 0:n.config)&&!a,[l,x]=C.useState(d.showRanges??!1),[p,h]=C.useState(d.rangesArePercentages??!1),u=d.disableAutoComparative?!1:d.comparativeMetricKey!==void 0||!c,[y,b]=C.useState(u);C.useEffect(()=>{x(d.showRanges??!1)},[d.showRanges]),C.useEffect(()=>{h(d.rangesArePercentages??!1)},[d.rangesArePercentages]);const m=d.targetValue===void 0?"":String(d.targetValue);C.useEffect(()=>{const N=d.disableAutoComparative?!1:d.comparativeMetricKey!==void 0||!c;b(N)},[d.disableAutoComparative,d.comparativeMetricKey,c]);const g=C.useMemo(()=>{var N,L;return((L=(N=n==null?void 0:n.config)==null?void 0:N.metricColumns)==null?void 0:L.map(S=>{const F=S.label||S.name||S.alias||"";return{value:F,label:F}}))||[]},[(R=n==null?void 0:n.config)==null?void 0:R.metricColumns]);C.useEffect(()=>{var B,K;if(!t||g.length===0)return;const N={};let L=!1;const S=(B=g[1])==null?void 0:B.value;!d.targetMetricKey&&S&&(N.targetMetricKey=S,L=!0);const F=(K=g[2])==null?void 0:K.value;!d.comparativeMetricKey&&!d.disableAutoComparative&&F&&(N.comparativeMetricKey=F,L=!0);const O=g.slice(3),_={...d.rangeKeys||{}};let Q=!1;if(ha.forEach((se,H)=>{!_[se]&&O[H]&&(_[se]=O[H].value,Q=!0)}),Q&&(N.rangeKeys=_,L=!0,d.showRanges===void 0&&(N.showRanges=!0)),L){const se=pa({...d,...N});r({...t,bulletConfig:se})}},[g,d,t,r]);const w=N=>{const L=pa({...d,...N});r({...t,bulletConfig:L})},E=(N,L)=>{const S={...d.rangeKeys||{},[N]:L.trim()};L.trim()||delete S[N],w({rangeKeys:Object.keys(S).length>0?S:void 0})},V=(N,L)=>{const S=L===""?void 0:Number(L),F={...d.ranges||{}};S===void 0||Number.isNaN(S)?delete F[N]:F[N]=S,w({ranges:Object.keys(F).length?F:void 0})},A=N=>{if(N===""){w({targetValue:void 0});return}const L=Number(N);w({targetValue:Number.isNaN(L)?void 0:L})},T=(N,L)=>{const S=L.trim(),F={...d.rangeLabels||{}};S?F[N]=S:delete F[N],w({rangeLabels:Object.keys(F).length>0?F:void 0})},v=N=>{x(N),w({showRanges:N})},D=N=>{h(N),w({rangesArePercentages:N})},M=d.orientation||(((P=t==null?void 0:t.chartOptions)==null?void 0:P.indexAxis)==="y"?"horizontal":"vertical"),f=N=>{w({orientation:N}),i(N==="horizontal"?"y":"x")},I=[{value:"__none",label:"None"},...g.map(N=>({value:N.value,label:N.label}))],j=I,k=N=>{if(b(N),!N){w({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!c){w({disableAutoComparative:!1});return}if(d.comparativeMetricKey)w({disableAutoComparative:!1});else{const L=g.find(S=>S.value!==d.targetMetricKey);w({comparativeMetricKey:L==null?void 0:L.value,disableAutoComparative:!1})}};return e.jsxs(s.AccordionItem,{value:"bullet-config",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.BulletChartIcon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bullet Chart"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-6 border-t border-border/50 py-4",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"ORIENTATION"}),e.jsxs(s.Select,{value:M,onValueChange:N=>f(N),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"horizontal",className:"text-xs",children:"Horizontal"}),e.jsx(s.SelectItem,{value:"vertical",className:"text-xs",children:"Vertical"})]})]})]}),c&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TARGET METRIC"}),e.jsxs(s.Select,{value:d.targetMetricKey||"__none",onValueChange:N=>w({targetMetricKey:N==="__none"?void 0:N}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select metric"})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"__none",className:"text-xs",children:"None"}),g.map(N=>e.jsx(s.SelectItem,{value:N.value,className:"text-xs",children:N.label},N.value))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"COMPARATIVE METRIC"}),c?e.jsxs(s.Select,{value:d.comparativeMetricKey||"__none",onValueChange:N=>w({comparativeMetricKey:N==="__none"?void 0:N,disableAutoComparative:N==="__none"}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select metric"})}),e.jsx(s.SelectContent,{children:I.map(N=>e.jsx(s.SelectItem,{value:N.value,className:"text-xs",children:N.label},N.value))})]}):e.jsxs("div",{className:"space-y-2 rounded-md border border-border/50 p-3 text-xs",children:[e.jsxs("div",{className:"flex items-center justify-between font-medium",children:[e.jsx("span",{children:"Show comparative"}),e.jsx(s.SmallSwitch,{checked:y,onCheckedChange:N=>k(N)})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Comparative values are auto-detected from the third metric in your results."})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TARGET VALUE (FALLBACK)"}),e.jsx(Ve,{type:"number",className:"h-8 text-xs",value:m,onCommit:A,placeholder:"Optional numeric fallback"})]})]}),e.jsxs("section",{className:"space-y-4 rounded-md border border-border/60 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"QUALITATIVE RANGES"}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:200,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"text-muted-foreground transition-colors hover:text-foreground",children:e.jsx(s.Info,{className:"h-3.5 w-3.5"})})}),e.jsx(s.TooltipContent,{side:"top",children:"Use columns or static values for Poor / Average / Good."})]})})]}),e.jsx("div",{className:"flex items-center gap-2 text-xs font-medium",children:e.jsx(s.SmallSwitch,{checked:l,onCheckedChange:v})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:p,disabled:!l,onChange:N=>D(N.target.checked),className:"h-3.5 w-3.5 accent-primary disabled:opacity-50"}),e.jsx("span",{children:"Use % of value"})]})]}),l&&e.jsx("div",{className:"space-y-3",children:ha.map(N=>{var L,S,F,O,_;return e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-muted/40 p-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[N," LABEL"]}),e.jsx(Ve,{placeholder:`Display label (${N})`,value:((L=d.rangeLabels)==null?void 0:L[N])||"",onCommit:Q=>T(N,Q),className:"h-8 text-xs"})]}),c?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[N," COLUMN"]}),e.jsxs(s.Select,{value:((S=d.rangeKeys)==null?void 0:S[N])||"__none",onValueChange:Q=>{Q==="__none"?E(N,""):E(N,Q)},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select column"})}),e.jsx(s.SelectContent,{children:j.map(Q=>e.jsx(s.SelectItem,{value:Q.value,className:"text-xs",children:Q.label},Q.value))})]})]}):e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[N," COLUMN KEY"]}),e.jsx(Ve,{placeholder:"Column key",value:((F=d.rangeKeys)==null?void 0:F[N])||"",onCommit:Q=>E(N,Q),className:"h-8 text-xs"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[N," VALUE"]}),e.jsx(Ve,{type:"number",placeholder:p?"0.80":"Static value",value:((O=d.ranges)==null?void 0:O[N])===void 0?"":String((_=d.ranges)==null?void 0:_[N]),onCommit:Q=>V(N,Q),className:"h-8 text-xs"})]})]},N)})})]})]})]})}function fa(t){if(!t)return;const n={...t};if(n.xMetricKey||delete n.xMetricKey,n.yMetricKey||delete n.yMetricKey,n.radiusMetricKey||delete n.radiusMetricKey,n.labelKey||delete n.labelKey,n.groupKey||delete n.groupKey,n.enableGrouping===void 0&&delete n.enableGrouping,n.radiusScale||delete n.radiusScale,n.fixedRadius===void 0&&delete n.fixedRadius,n.minRadius===void 0&&delete n.minRadius,n.maxRadius===void 0&&delete n.maxRadius,Object.keys(n).length!==0)return n}function Hr(){var T,v,D,M,f,I,j,k,R,P,N,L;const t=s.useEditorStore(S=>S.card.preferences),n=s.useEditorStore(S=>S.card),a=Ae.useEffectiveEditorCardType(),r=s.useEditorStore(S=>S.isDevMode),{setCardPreferences:i,updateCardInFrame:d}=s.useEditorActions(),o=a==="bubble",c=a==="scatter",l=C.useMemo(()=>(t==null?void 0:t.bubbleScatterConfig)||{},[t==null?void 0:t.bubbleScatterConfig]),p=s.hasValidCardConfig(n==null?void 0:n.config)&&!r,h=C.useMemo(()=>{var S,F;return((F=(S=n==null?void 0:n.config)==null?void 0:S.metricColumns)==null?void 0:F.map(O=>{const _=O.label||O.name||O.alias||"";return{value:_,label:_}}))||[]},[(T=n==null?void 0:n.config)==null?void 0:T.metricColumns]),u=C.useMemo(()=>{var S,F;return((F=(S=n==null?void 0:n.config)==null?void 0:S.groupByColumns)==null?void 0:F.map(O=>{const _=O.label||O.name||O.alias||"";return{value:_,label:_}}))||[]},[(v=n==null?void 0:n.config)==null?void 0:v.groupByColumns]),y=C.useMemo(()=>l.enableGrouping!==void 0?l.enableGrouping:!r&&u.length>=2,[l.enableGrouping,r,u.length]),[b,m]=C.useState(y);C.useEffect(()=>{m(y)},[y]);const g=S=>{const F={...t||{},bubbleScatterConfig:S};i(F),n&&d({...n,preferences:F})},w=S=>{i(S),n&&d({...n,preferences:S})};C.useEffect(()=>{if(!t||h.length===0)return;const S={};let F=!1;if(!l.xMetricKey&&h[0]&&(S.xMetricKey=h[0].value,F=!0),!l.yMetricKey&&h[1]&&(S.yMetricKey=h[1].value,F=!0),o&&!l.radiusMetricKey&&h[2]&&(S.radiusMetricKey=h[2].value,F=!0),!l.labelKey&&u[0]&&(S.labelKey=u[0].value,F=!0),y&&!l.groupKey&&u[1]&&(S.groupKey=u[1].value,S.enableGrouping=!0,F=!0),F){const O=fa({...l,...S});g(O)}},[h,u,l,t,i,o,y]);const E=S=>{const F=fa({...l,...S});g(F)},V=S=>{m(S),E({enableGrouping:S,groupKey:S?l.groupKey:void 0})};if(!o&&!c)return null;const A=o?s.Circle:s.ChartScatter;return e.jsxs(s.AccordionItem,{value:"bubble-scatter-config",children:[e.jsx(s.AccordionTrigger,{className:"py-2 text-sm",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(A,{className:"h-4 w-4"}),e.jsxs("span",{children:[o?"Bubble":"Scatter"," Configuration"]})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-1 pb-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-1 text-xs font-medium text-muted-foreground",children:["Dimensions",e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{children:e.jsx(s.Info,{className:"h-3 w-3"})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{children:"Label identifies each point. Group creates separate series in the legend."})})]})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Label Column"}),p?e.jsxs(s.Select,{value:l.labelKey||"",onValueChange:S=>E({labelKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select label column"})}),e.jsx(s.SelectContent,{children:u.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(Ve,{className:"h-8 text-xs",placeholder:"Column name for labels",value:l.labelKey||"",onCommit:S=>E({labelKey:S})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Group points into series"}),e.jsx(s.SmallSwitch,{checked:b,onCheckedChange:V})]}),b&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Group By"}),p?e.jsxs(s.Select,{value:l.groupKey||"",onValueChange:S=>E({groupKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select group column"})}),e.jsx(s.SelectContent,{children:u.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(Ve,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:l.groupKey||"",onCommit:S=>E({groupKey:S})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Metrics"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"X Axis"}),p?e.jsxs(s.Select,{value:l.xMetricKey||"",onValueChange:S=>E({xMetricKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select X metric"})}),e.jsx(s.SelectContent,{children:h.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(Ve,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:l.xMetricKey||"",onCommit:S=>E({xMetricKey:S})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Y Axis"}),p?e.jsxs(s.Select,{value:l.yMetricKey||"",onValueChange:S=>E({yMetricKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select Y metric"})}),e.jsx(s.SelectContent,{children:h.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(Ve,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:l.yMetricKey||"",onCommit:S=>E({yMetricKey:S})})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Radius"}),p?e.jsxs(s.Select,{value:l.radiusMetricKey||"",onValueChange:S=>E({radiusMetricKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select radius metric"})}),e.jsx(s.SelectContent,{children:h.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(Ve,{className:"h-8 text-xs",placeholder:"Column name for radius",value:l.radiusMetricKey||"",onCommit:S=>E({radiusMetricKey:S})})]})]}),o&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Radius Settings"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Scale Mode"}),e.jsxs(s.Select,{value:l.radiusScale||"sqrt",onValueChange:S=>E({radiusScale:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"sqrt",children:"Square Root (area-proportional)"}),e.jsx(s.SelectItem,{value:"linear",children:"Linear"}),e.jsx(s.SelectItem,{value:"fixed",children:"Fixed Size"})]})]})]}),l.radiusScale!=="fixed"&&e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Min Radius"}),e.jsx(Ve,{className:"h-8 text-xs",type:"number",placeholder:"5",value:((D=l.minRadius)==null?void 0:D.toString())||"",onCommit:S=>E({minRadius:S?Number(S):void 0})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Max Radius"}),e.jsx(Ve,{className:"h-8 text-xs",type:"number",placeholder:"30",value:((M=l.maxRadius)==null?void 0:M.toString())||"",onCommit:S=>E({maxRadius:S?Number(S):void 0})})]})]}),l.radiusScale==="fixed"&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs(s.Label,{className:"text-xs",children:["Fixed Radius: ",l.fixedRadius||10]}),e.jsx(s.Slider,{value:[l.fixedRadius||10],onValueChange:([S])=>E({fixedRadius:S}),min:3,max:30,step:1,className:"py-2"})]})]}),c&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Point Settings"}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(s.Label,{className:"text-xs",children:["Point Size: ",l.fixedRadius||5]}),e.jsx(s.Slider,{value:[l.fixedRadius||5],onValueChange:([S])=>E({fixedRadius:S}),min:2,max:15,step:1,className:"py-2"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Axis Titles"}),e.jsx(s.SmallSwitch,{checked:((I=(f=t==null?void 0:t.xAxisConfig)==null?void 0:f.name)==null?void 0:I.enabled)??!1,onCheckedChange:S=>{var _,Q,B,K;const F=l.xMetricKey||"X Axis",O=l.yMetricKey||"Y Axis";w({...t??{},xAxisConfig:{...t==null?void 0:t.xAxisConfig,name:{enabled:S,text:((Q=(_=t==null?void 0:t.xAxisConfig)==null?void 0:_.name)==null?void 0:Q.text)||F}},yAxisConfig:{...t==null?void 0:t.yAxisConfig,name:{enabled:S,text:((K=(B=t==null?void 0:t.yAxisConfig)==null?void 0:B.name)==null?void 0:K.text)||O}}})}})]}),((k=(j=t==null?void 0:t.xAxisConfig)==null?void 0:j.name)==null?void 0:k.enabled)&&e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"X Title"}),e.jsx(Ve,{className:"h-8 text-xs",placeholder:l.xMetricKey||"X Axis",value:((P=(R=t==null?void 0:t.xAxisConfig)==null?void 0:R.name)==null?void 0:P.text)||"",onCommit:S=>{var F;w({...t??{},xAxisConfig:{...t==null?void 0:t.xAxisConfig,name:{...(F=t==null?void 0:t.xAxisConfig)==null?void 0:F.name,enabled:!0,text:S||l.xMetricKey||"X Axis"}}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Y Title"}),e.jsx(Ve,{className:"h-8 text-xs",placeholder:l.yMetricKey||"Y Axis",value:((L=(N=t==null?void 0:t.yAxisConfig)==null?void 0:N.name)==null?void 0:L.text)||"",onCommit:S=>{var F;w({...t??{},yAxisConfig:{...t==null?void 0:t.yAxisConfig,name:{...(F=t==null?void 0:t.yAxisConfig)==null?void 0:F.name,enabled:!0,text:S||l.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const Jr=[{value:"percentOfTotal",label:"% of Total",description:"Each stage shows percentage of the sum of all values"},{value:"percentOfFirst",label:"% of Stage 1",description:"First stage = 100%, others relative to first stage"}];function Qr(){const t=s.useEditorStore(u=>u.card),n=s.useEditorStore(u=>{var y;return(y=u.card)==null?void 0:y.preferences}),{setCardPreferences:a}=s.useEditorActions(),r=(t==null?void 0:t.type)==="funnel",i=(n==null?void 0:n.funnelConfig)||{},d=i.percentMode??"percentOfTotal",o=i.shrinkFraction??1,c=i.labelThreshold??0,l=u=>{const y={...i,...u};a({...n||{},funnelConfig:y})},x=u=>{l({percentMode:u})},p=u=>{l({shrinkFraction:u[0]})},h=u=>{l({labelThreshold:u[0]})};return r?e.jsxs(s.AccordionItem,{value:"funnel-config",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Filter,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Funnel Settings"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"PERCENTAGE MODE"}),e.jsx(s.RadioGroup,{value:d,onValueChange:u=>x(u),className:"space-y-2",children:Jr.map(u=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:`funnel-${u.value}`,value:u.value,className:"mt-0.5"}),e.jsxs(s.Label,{htmlFor:`funnel-${u.value}`,className:"flex flex-col gap-0.5 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.description})]})]},u.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"SEGMENT SHRINK"}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Same Width"}),e.jsx(s.Slider,{value:[o],onValueChange:p,min:0,max:1,step:.1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Full Shrink"})]}),e.jsxs("p",{className:"text-center text-xs text-muted-foreground",children:["Current: ",Math.round(o*100),"%"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"LABEL VISIBILITY THRESHOLD"}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Show All"}),e.jsx(s.Slider,{value:[c],onValueChange:h,min:0,max:25,step:1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Hide Small"})]}),e.jsx("p",{className:"text-center text-xs text-muted-foreground",children:c===0?"Showing all labels":`Hide labels below ${c}%`})]})]})]}):null}function Bs(){const t=s.useEditorStore(d=>d.card),{data:n}=s.useDashboardCardQuery(t),{keys:a}=s.getKeys((n==null?void 0:n.records)||[]),r=a.slice(1).filter(d=>!s.METADATA_KEYS.includes(d));let i=r;if(["stackedBar","stackedLine"].includes(t.type)){const d=s.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:o}=s.getKeys(d);i=o.slice(1)}return{transformedMetricKeys:i,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}const Yr=[{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"}],Wr=[{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)"}],Xr=["center","start","end"],Zr=["center","start","end","top","bottom"];function zs({config:t,onChange:n,isHorizontal:a=!1,showAutoFormat:r=!0,positionOptions:i,showAppearance:d=!0}){var b,m,g,w,E,V;const o=i??(a?["auto","center","left","right","custom"]:["auto","center","top","bottom","custom"]),c=r?["auto","number","currency","percent","none"]:["number","currency","percent","none"],l=(A,T)=>{const v={...t,[A]:T};n(v)},x=(A,T)=>{const v={...t,font:{...(t==null?void 0:t.font)||{},[A]:T}};n(v)},p=(A,T)=>{const v={...t,formatOptions:{...(t==null?void 0:t.formatOptions)||{},[A]:T}};n(v)},h=()=>a?"Right":"Top",u=t||{},y=u.format||(r?"auto":"number");return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:u.position||"auto",onValueChange:A=>l("position",A),children:[e.jsx(s.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:o.map(A=>e.jsx(s.SelectItem,{value:A,className:"text-xs",children:A==="auto"?h():A==="custom"?"Custom (Advanced)":s.titleCase(A)},A))})]})]}),u.position==="custom"&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Anchor"}),e.jsxs(s.Select,{value:u.anchor||"center",onValueChange:A=>l("anchor",A),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Xr.map(A=>e.jsx(s.SelectItem,{value:A,className:"text-xs",children:s.titleCase(A)},A))})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Align"}),e.jsxs(s.Select,{value:String(u.align||"center"),onValueChange:A=>l("align",A),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Zr.map(A=>e.jsx(s.SelectItem,{value:A,className:"text-xs",children:s.titleCase(A)},A))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Format"}),e.jsxs(s.Select,{value:y,onValueChange:A=>l("format",A),children:[e.jsx(s.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:c.map(A=>e.jsx(s.SelectItem,{value:A,className:"text-xs",children:A==="auto"&&r?"Auto (Use Axis)":A==="none"?"None (Raw Value)":s.titleCase(A)},A))})]})]}),!["auto","none"].includes(y)&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[["number","currency","percent"].includes(y)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Decimals"}),e.jsx("div",{className:"w-16",children:e.jsx(_e,{type:"number",placeholder:"0",value:String(((b=u.formatOptions)==null?void 0:b.decimalPlaces)??(y==="currency"?2:y==="percent"?1:0)),onSave:A=>p("decimalPlaces",Number(A)),className:""})})]}),y==="currency"&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Currency"}),e.jsxs(s.Select,{value:((m=u.formatOptions)==null?void 0:m.currency)||"USD",onValueChange:A=>p("currency",A),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Yr.map(A=>e.jsx(s.SelectItem,{value:A.value,className:"text-xs",children:A.label},A.value))})]})]}),["number","currency"].includes(y)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((g=u.formatOptions)==null?void 0:g.useSuffix)??!1,onCheckedChange:A=>p("useSuffix",A)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Locale"}),e.jsxs(s.Select,{value:((w=u.formatOptions)==null?void 0:w.locale)||"en-US",onValueChange:A=>p("locale",A),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Wr.map(A=>e.jsx(s.SelectItem,{value:A.value,className:"text-xs",children:A.label},A.value))})]})]})]}),d&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Appearance"}),e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Size"}),e.jsx("div",{className:"w-16",children:e.jsx(_e,{type:"number",placeholder:"12",value:String(((E=u.font)==null?void 0:E.size)||12),onSave:A=>x("size",Number(A)),className:""})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Weight"}),e.jsxs(s.Select,{value:((V=u.font)==null?void 0:V.weight)||"normal",onValueChange:A=>x("weight",A),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-24 text-xs",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 justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Color"}),e.jsxs(s.Select,{value:u.color==="auto"||!u.color?"auto":"custom",onValueChange:A=>{A==="auto"&&l("color","auto")},children:[e.jsx(s.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Contrast)"}),e.jsx(s.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Rotation"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-12",children:e.jsx(_e,{type:"number",placeholder:"0",value:String(u.rotation||0),onSave:A=>l("rotation",Number(A)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"°"})]})]})]})]})]})}const el=[{type:"bar",icon:s.ChartColumnIncreasing,label:"Bar"},{type:"line",icon:s.ChartLine,label:"Line"}],sl=[0,1,2,3,4,5,6,8,10],tl=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],al=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function nl(){return s.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type})!=="combo"?null:e.jsxs(s.AccordionItem,{value:"combo-series",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.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsx(rl,{})})]})}function rl(){const{transformedMetricKeys:t}=Bs();return t.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:t.map((n,a)=>e.jsx(ll,{metricKey:n,idx:a},n))})}function ll({metricKey:t,idx:n}){var w;const[a,r]=C.useState(!1),i=s.useEditorStore(E=>{var V;return(V=E.card)==null?void 0:V.preferences}),d=s.useEditorStore(E=>{var V,A;return(A=(V=E.card)==null?void 0:V.preferences)==null?void 0:A.datasetOptions}),o=d==null?void 0:d.find(E=>E.idx===n),{setCardPreferences:c}=s.useEditorStore(E=>E.actions),l=(o==null?void 0:o.type)||"bar",x=(o==null?void 0:o.yAxisId)||"y",p=((w=o==null?void 0:o.dataLabels)==null?void 0:w.enabled)??!1,h=l==="line"?s.ChartLine:s.ChartColumnIncreasing;function u(E){const V={idx:n,type:l,yAxisId:x,dataLabels:o==null?void 0:o.dataLabels,...E};if(!o)c({...i||{},datasetOptions:[...d||[],V]});else{const A=d==null?void 0:d.map(T=>T.idx===n?{...T,...V}:T);c({...i||{},datasetOptions:A})}}function y(E){u({type:E})}function b(E){u({yAxisId:E})}function m(E){u({dataLabels:{...o==null?void 0:o.dataLabels,enabled:E}})}function g(E){u({dataLabels:E})}return e.jsx(s.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(s.ChevronRight,{className:s.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:t,children:t})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[e.jsxs("span",{className:s.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(h,{className:"h-3 w-3"}),l==="line"?"Line":"Bar"]}),e.jsx("span",{className:s.cn("rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:x==="y2"?"Y2":"Y1"})]})]})}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"flex items-end gap-4",children:[e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Chart Type"}),e.jsx("div",{className:"flex gap-2",children:el.map(({type:E,icon:V,label:A})=>{const T=l===E;return e.jsxs("button",{onClick:()=>y(E),className:s.cn("flex items-center gap-2 rounded-md border px-3 py-1.5 text-xs transition-colors",T?"border-primary bg-primary/10 text-primary":"border-border bg-background text-muted-foreground hover:bg-muted"),children:[e.jsx(V,{className:"h-4 w-4"}),e.jsx("span",{children:A})]},E)})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Axis"}),e.jsxs(s.Select,{value:x,onValueChange:E=>b(E),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-20 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"y",className:"text-xs",children:"Y1 (Left)"}),e.jsx(s.SelectItem,{value:"y2",className:"text-xs",children:"Y2 (Right)"})]})]})]})]}),l==="line"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(s.Select,{value:(o==null?void 0:o.lineStyle)||"solid",onValueChange:E=>u({lineStyle:E}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:al.map(({value:E,label:V})=>e.jsx(s.SelectItem,{value:E,className:"text-xs",children:V},E))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(s.Select,{value:String((o==null?void 0:o.pointRadius)??3),onValueChange:E=>u({pointRadius:Number(E)}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:sl.map(E=>e.jsx(s.SelectItem,{value:String(E),className:"text-xs",children:E===0?"None":E},E))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(s.Select,{value:(o==null?void 0:o.pointStyle)||"circle",onValueChange:E=>u({pointStyle:E}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:tl.map(({value:E,label:V})=>e.jsx(s.SelectItem,{value:E,className:"text-xs",children:V},E))})]})]})]})]}),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 text-muted-foreground",children:"Data Labels"}),e.jsx(s.SmallSwitch,{checked:p,onCheckedChange:m})]}),p&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(zs,{config:o==null?void 0:o.dataLabels,onChange:g,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const et=[{value:"origin",label:"Origin (X-axis)",description:"Fill to the X-axis (y=0)"},{value:"start",label:"Start (Top)",description:"Fill to the top of chart area"},{value:"end",label:"End (Bottom)",description:"Fill to the bottom of chart area"},{value:"-1",label:"Previous Series",description:"Fill to the series below"},{value:"+1",label:"Next Series",description:"Fill to the series above"},{value:"false",label:"No Fill (Line)",description:"Show as line without fill"}],ol=[0,1,2,3,4,5,6,8,10],il=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],cl=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function dl(t){return t==null?"origin":t===!1?"false":t}function ul(){const t=s.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type});return t!=="area"&&t!=="stackedArea"?null:e.jsxs(s.AccordionItem,{value:"area-series",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.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsx(ml,{})})]})}function ml(){const{transformedMetricKeys:t}=Bs();return t.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:t.map((n,a)=>e.jsx(xl,{metricKey:n,idx:a},n))})}function xl({metricKey:t,idx:n}){var m;const[a,r]=C.useState(!1),i=s.useEditorStore(g=>{var w;return(w=g.card)==null?void 0:w.preferences}),d=s.useEditorStore(g=>{var w,E;return(E=(w=g.card)==null?void 0:w.preferences)==null?void 0:E.datasetOptions}),o=d==null?void 0:d.find(g=>g.idx===n),{setCardPreferences:c}=s.useEditorStore(g=>g.actions),l=dl(o==null?void 0:o.fill),x=((m=o==null?void 0:o.dataLabels)==null?void 0:m.enabled)??!1,p=et.find(g=>g.value===l)||et[0];function h(g){const w={idx:n,fill:l,dataLabels:o==null?void 0:o.dataLabels,...g};if(!o)c({...i||{},datasetOptions:[...d||[],w]});else{const E=d==null?void 0:d.map(V=>V.idx===n?{...V,...w}:V);c({...i||{},datasetOptions:E})}}function u(g){h({fill:g==="false"?!1:g})}function y(g){h({dataLabels:{...o==null?void 0:o.dataLabels,enabled:g}})}function b(g){h({dataLabels:g})}return e.jsx(s.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(s.ChevronRight,{className:s.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:t,children:t})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:e.jsxs("span",{className:s.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(s.ChartArea,{className:"h-3 w-3"}),p.label.split(" ")[0]]})})]})}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Fill Target"}),e.jsxs(s.Select,{value:l,onValueChange:g=>u(g),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:et.map(g=>e.jsx(s.SelectItem,{value:g.value,className:"text-xs",children:e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{children:g.label})})},g.value))})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(s.Select,{value:(o==null?void 0:o.lineStyle)||"solid",onValueChange:g=>h({lineStyle:g}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:cl.map(({value:g,label:w})=>e.jsx(s.SelectItem,{value:g,className:"text-xs",children:w},g))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(s.Select,{value:String((o==null?void 0:o.pointRadius)??3),onValueChange:g=>h({pointRadius:Number(g)}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:ol.map(g=>e.jsx(s.SelectItem,{value:String(g),className:"text-xs",children:g===0?"None":g},g))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(s.Select,{value:(o==null?void 0:o.pointStyle)||"circle",onValueChange:g=>h({pointStyle:g}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:il.map(({value:g,label:w})=>e.jsx(s.SelectItem,{value:g,className:"text-xs",children:w},g))})]})]})]})]}),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 text-muted-foreground",children:"Data Labels"}),e.jsx(s.SmallSwitch,{checked:x,onCheckedChange:y})]}),x&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(zs,{config:o==null?void 0:o.dataLabels,onChange:b,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const hl=[0,1,2,3,4,5,6,8,10],pl=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],st=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function fl(){return s.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type})!=="line"?null:e.jsxs(s.AccordionItem,{value:"line-series",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.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsx(gl,{})})]})}function gl(){const{transformedMetricKeys:t}=Bs();return t.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:t.map((n,a)=>e.jsx(jl,{metricKey:n,idx:a},n))})}function jl({metricKey:t,idx:n}){var g;const[a,r]=C.useState(!1),i=s.useEditorStore(w=>{var E;return(E=w.card)==null?void 0:E.preferences}),d=s.useEditorStore(w=>{var E,V;return(V=(E=w.card)==null?void 0:E.preferences)==null?void 0:V.datasetOptions}),o=d==null?void 0:d.find(w=>w.idx===n),{setCardPreferences:c}=s.useEditorStore(w=>w.actions),l=(o==null?void 0:o.lineStyle)||"solid",x=(o==null?void 0:o.pointRadius)??3,p=(o==null?void 0:o.pointStyle)||"circle",h=((g=o==null?void 0:o.dataLabels)==null?void 0:g.enabled)??!1,u=st.find(w=>w.value===l)||st[0];function y(w){const E={idx:n,lineStyle:l,pointRadius:x,pointStyle:p,dataLabels:o==null?void 0:o.dataLabels,...w};if(!o)c({...i||{},datasetOptions:[...d||[],E]});else{const V=d==null?void 0:d.map(A=>A.idx===n?{...A,...E}:A);c({...i||{},datasetOptions:V})}}function b(w){y({dataLabels:{...o==null?void 0:o.dataLabels,enabled:w}})}function m(w){y({dataLabels:w})}return e.jsx(s.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(s.ChevronRight,{className:s.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:t,children:t})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:e.jsxs("span",{className:s.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(s.TrendingUp,{className:"h-3 w-3"}),u.label.split(" ")[0]]})})]})}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(s.Select,{value:l,onValueChange:w=>y({lineStyle:w}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:st.map(({value:w,label:E})=>e.jsx(s.SelectItem,{value:w,className:"text-xs",children:E},w))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(s.Select,{value:String(x),onValueChange:w=>y({pointRadius:Number(w)}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:hl.map(w=>e.jsx(s.SelectItem,{value:String(w),className:"text-xs",children:w===0?"None":w},w))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(s.Select,{value:p,onValueChange:w=>y({pointStyle:w}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:pl.map(({value:w,label:E})=>e.jsx(s.SelectItem,{value:w,className:"text-xs",children:E},w))})]})]})]})]}),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 text-muted-foreground",children:"Data Labels"}),e.jsx(s.SmallSwitch,{checked:h,onCheckedChange:b})]}),h&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(zs,{config:o==null?void 0:o.dataLabels,onChange:m,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const bl=[0,2,4,6,8,10,12,16,20];function vl(){const t=s.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type});return!t||!["bar","horizontalBar","stackedBar"].includes(t)?null:e.jsxs(s.AccordionItem,{value:"bar-series",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.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsx(yl,{})})]})}function yl(){const{transformedMetricKeys:t}=Bs();return t.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:t.map((n,a)=>e.jsx(Nl,{metricKey:n,idx:a},n))})}function Nl({metricKey:t,idx:n}){var b;const[a,r]=C.useState(!1),i=s.useEditorStore(m=>{var g;return(g=m.card)==null?void 0:g.type}),d=s.useEditorStore(m=>{var g;return(g=m.card)==null?void 0:g.preferences}),o=s.useEditorStore(m=>{var g,w;return(w=(g=m.card)==null?void 0:g.preferences)==null?void 0:w.datasetOptions}),c=o==null?void 0:o.find(m=>m.idx===n),{setCardPreferences:l}=s.useEditorStore(m=>m.actions),x=(c==null?void 0:c.borderRadius)??0,p=((b=c==null?void 0:c.dataLabels)==null?void 0:b.enabled)??!1;function h(m){const g={idx:n,borderRadius:x,dataLabels:c==null?void 0:c.dataLabels,...m};if(!c)l({...d||{},datasetOptions:[...o||[],g]});else{const w=o==null?void 0:o.map(E=>E.idx===n?{...E,...g}:E);l({...d||{},datasetOptions:w})}}function u(m){h({dataLabels:{...c==null?void 0:c.dataLabels,enabled:m}})}function y(m){h({dataLabels:m})}return e.jsx(s.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(s.ChevronRight,{className:s.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:t,children:t})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:x>0&&e.jsxs("span",{className:s.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(s.ChartColumn,{className:"h-3 w-3"}),"r:",x]})})]})}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Bar Style"}),e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Corner Radius"}),e.jsxs(s.Select,{value:String(x),onValueChange:m=>h({borderRadius:Number(m)}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:bl.map(m=>e.jsx(s.SelectItem,{value:String(m),className:"text-xs",children:m===0?"None":`${m}px`},m))})]})]})})]}),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 text-muted-foreground",children:"Data Labels"}),e.jsx(s.SmallSwitch,{checked:p,onCheckedChange:u})]}),p&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(zs,{config:c==null?void 0:c.dataLabels,onChange:y,isHorizontal:i==="horizontalBar",showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Cl=[0,1,2,3,4,5,6,8,10],Sl=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],wl=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Tl(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>{var l;return(l=c.card)==null?void 0:l.preferences}),a=Ae.useEffectiveEditorCardType(),r=n==null?void 0:n.lineStyleConfig,{setCardPreferences:i,updateCardInFrame:d}=s.useEditorActions();if(!t||!["line","area","stackedArea"].includes(a))return null;const o=(c,l)=>{const x={...n||{},lineStyleConfig:{...r,[c]:l}};i(x),d({...t,preferences:x})};return e.jsxs(s.AccordionItem,{value:"line-style",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(Nn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Line Style"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Default styles for all series. Override per-series in the Series section."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Line Pattern"}),e.jsxs(s.Select,{value:(r==null?void 0:r.lineStyle)||"solid",onValueChange:c=>o("lineStyle",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:wl.map(({value:c,label:l})=>e.jsx(s.SelectItem,{value:c,className:"text-xs",children:l},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Point Size"}),e.jsxs(s.Select,{value:String((r==null?void 0:r.pointRadius)??3),onValueChange:c=>o("pointRadius",Number(c)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Cl.map(c=>e.jsx(s.SelectItem,{value:String(c),className:"text-xs",children:c===0?"None":c},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Point Shape"}),e.jsxs(s.Select,{value:(r==null?void 0:r.pointStyle)||"circle",onValueChange:c=>o("pointStyle",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Sl.map(({value:c,label:l})=>e.jsx(s.SelectItem,{value:c,className:"text-xs",children:l},c))})]})]})]})})]})}const El=[0,2,4,6,8,10,12,16,20],Il=[{value:"0.5",label:"50%"},{value:"0.6",label:"60%"},{value:"0.7",label:"70%"},{value:"0.8",label:"80%"},{value:"0.9",label:"90%"},{value:"1",label:"100%"}],kl=[{value:"0.5",label:"50%"},{value:"0.6",label:"60%"},{value:"0.7",label:"70%"},{value:"0.8",label:"80%"},{value:"0.9",label:"90%"},{value:"1",label:"100%"}];function Dl(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>{var l;return(l=c.card)==null?void 0:l.preferences}),a=Ae.useEffectiveEditorCardType(),r=n==null?void 0:n.barStyleConfig,{setCardPreferences:i,updateCardInFrame:d}=s.useEditorActions();if(!t||!["bar","horizontalBar","stackedBar"].includes(a))return null;const o=(c,l)=>{const x={...n||{},barStyleConfig:{...r,[c]:l}};i(x),d({...t,preferences:x})};return e.jsxs(s.AccordionItem,{value:"bar-style",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.ChartColumn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bar Style"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Default styles for all bars. Override per-series in the Series section."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Corner Radius"}),e.jsxs(s.Select,{value:String((r==null?void 0:r.borderRadius)??0),onValueChange:c=>o("borderRadius",Number(c)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:El.map(c=>e.jsx(s.SelectItem,{value:String(c),className:"text-xs",children:c===0?"None":`${c}px`},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Bar Width"}),e.jsxs(s.Select,{value:String((r==null?void 0:r.barPercentage)??.9),onValueChange:c=>o("barPercentage",Number(c)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Il.map(({value:c,label:l})=>e.jsx(s.SelectItem,{value:c,className:"text-xs",children:l},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Category Width"}),e.jsxs(s.Select,{value:String((r==null?void 0:r.categoryPercentage)??.8),onValueChange:c=>o("categoryPercentage",Number(c)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:kl.map(({value:c,label:l})=>e.jsx(s.SelectItem,{value:c,className:"text-xs",children:l},c))})]})]})]})})]})}function Al(){const t=s.useEditorStore(a=>{var r,i;return(i=(r=a==null?void 0:a.card)==null?void 0:r.preferences)==null?void 0:i.sortChart}),{setSortChart:n}=s.useEditorActions();return e.jsxs(s.AccordionItem,{value:"stacked-sort",children:[e.jsx(s.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.ArrowUpDown,{className:"h-4 w-4"}),"Sort"]})}),e.jsx(s.AccordionContent,{className:"space-y-4 px-1",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort Order"}),e.jsx(ss,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"Ascending",value:"asc"},{label:"Descending",value:"desc"}],value:t||"none",onValueChange:a=>{n(a)}})]})})]})}const Ll=["kpi"],ga={none:"None",previous_period:"Previous Period",same_period_last_year:"Same Period Last Year",start_vs_end:"Start vs End",target:"Target"},tt=2;function ls(t){return typeof t=="string"?t.trim().toLowerCase():((t==null?void 0:t.id)||(t==null?void 0:t.qualifiedFieldName)||(t==null?void 0:t.name)||(t==null?void 0:t.label)||"").trim().toLowerCase()}function Ml(t){if(!(t!=null&&t.name)||!(t!=null&&t.dataType)||t.role==="metric")return!1;const n=s.getDataType(t.dataType);return["date","string","boolean"].includes(n)}function Ol(t){return{...t,role:"groupby"}}function Rl(){var E,V,A,T;const t=s.useEditorStore(v=>v.card),n=s.useEditorStore(v=>v.actions.updateCardConfig),a=Ae.useEffectiveEditorCardType(),{scopedFields:r}=s.useScopedFields(),i=((E=t.config)==null?void 0:E.metricColumns)||[],d=((V=t.config)==null?void 0:V.summary)||{},o=d.breakdownDimensions||[],c=Ll.includes(a),l=i.length>0,x=d.enabled===!0,p=c&&l,h=((A=t.config)==null?void 0:A.comparisonType)||((T=i.find(v=>v.comparisonType&&v.comparisonType!=="none"))==null?void 0:T.comparisonType)||"none",u=ga[h]||ga.none,y=Array.from(new Map(r.filter(Ml).map(v=>[ls(v),Ol(v)])).values()),b=new Set(y.map(v=>ls(v))),m=new Set(o.map(v=>ls(v)).filter(v=>v&&b.has(v)));if(!c)return null;const g=v=>{n(t.id,{summary:{...d,...v}})},w=(v,D)=>{const M=ls(v),f=y.filter(j=>m.has(ls(j))),I=D?m.has(M)?f:[...f,v].slice(0,tt):f.filter(j=>ls(j)!==M);g({breakdownDimensions:I})};return e.jsxs(s.AccordionItem,{value:"summary",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.FileText,{className:"h-4 w-4"}),e.jsx("span",{children:"Summary"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{htmlFor:"summary-enabled",className:"text-xs",children:"Enable Summary"}),!l&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Add at least one metric to enable summary."})]}),e.jsx(s.SmallSwitch,{id:"summary-enabled",checked:x,disabled:!p,onCheckedChange:v=>{if(!v){g({enabled:!1,showOnCard:!1,includeInDashboardSummary:!1});return}g({enabled:!0,showOnCard:d.showOnCard??!0,includeInDashboardSummary:d.includeInDashboardSummary??!0,anomalyEnabled:d.anomalyEnabled??!0})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Comparison"}),e.jsxs("p",{className:"rounded-md border border-border bg-muted/40 px-2 py-1.5 text-xs",children:["Using: ",u]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Comparison is configured from card/metric comparison settings."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"summary-show-on-card",className:"text-xs",children:"Show summary on card"}),e.jsx(s.SmallSwitch,{id:"summary-show-on-card",checked:d.showOnCard===!0,disabled:!x,onCheckedChange:v=>g({showOnCard:v})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"summary-include-rollup",className:"text-xs",children:"Include in dashboard summary"}),e.jsx(s.SmallSwitch,{id:"summary-include-rollup",checked:d.includeInDashboardSummary===!0,disabled:!x,onCheckedChange:v=>g({includeInDashboardSummary:v})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Breakdown Dimensions"}),e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[o.length,"/",tt]})]}),y.length===0?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"No dimension fields available for breakdown."}):e.jsx("div",{className:"max-h-40 space-y-2 overflow-y-auto rounded-md border border-border p-2",children:y.map(v=>{const D=ls(v),M=m.has(D),f=m.size>=tt,I=!x||!M&&f;return e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx(s.Checkbox,{id:`summary-breakdown-${D}`,checked:M,disabled:I,onCheckedChange:j=>w(v,j===!0)}),e.jsx(s.Label,{htmlFor:`summary-breakdown-${D}`,className:"cursor-pointer text-xs",children:v.label||v.name})]},D)})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"summary-anomaly",className:"text-xs",children:"Detect anomalies"}),e.jsx(s.SmallSwitch,{id:"summary-anomaly",checked:d.anomalyEnabled!==!1,disabled:!x,onCheckedChange:v=>g({anomalyEnabled:v})})]})]})]})}function Pa({mode:t}){const n=s.useEditorStore(a=>{var r;return(r=a.card)==null?void 0:r.type});return e.jsxs(e.Fragment,{children:[n==="combo"&&e.jsx(nl,{}),(n==="area"||n==="stackedArea")&&e.jsx(ul,{}),n==="line"&&e.jsx(fl,{}),(n==="bar"||n==="horizontalBar"||n==="stackedBar")&&e.jsx(vl,{}),e.jsx(Tl,{}),e.jsx(Dl,{}),e.jsx($r,{}),t==="config"&&e.jsx(_r,{}),t==="config"&&e.jsx(qr,{}),t==="config"&&e.jsx(Rl,{}),e.jsx(Kr,{}),n==="bullet"&&e.jsx(Ur,{}),n==="funnel"&&e.jsx(Qr,{}),(n==="bubble"||n==="scatter")&&e.jsx(Hr,{}),(n==="stackedBar"||n==="stackedLine")&&e.jsx(Al,{}),e.jsx(Pr,{}),e.jsx(Vr,{}),e.jsx(Br,{}),e.jsx(zr,{})]})}function Fl(){const t=s.useEditorStore(a=>a.card),n=t==null?void 0:t.type;return n?e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(Ps,{chartType:n}),e.jsx(s.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:e.jsx(Pa,{mode:"dev"})})]}):null}function Pl(){const t=s.useEditorStore(a=>a.card.type);function n(){switch(t){case"kpi":return e.jsx(gr,{});case"table":return e.jsx(Mr,{});case"map":return e.jsx(yr,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(Ma,{})});case"text":return e.jsx(Rr,{});default:return e.jsx(Fl,{})}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[n(),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Vl(){const t=C.useRef(null),n=C.useRef(null),a=s.useEditorStore(h=>h.isShowingVisual),r=s.useEditorStore(h=>h.isDevMode),i=s.useEditorStore(h=>h.showAIDialog),[d,o]=C.useState(!1),c=a&&!i,l=c&&(!r||d),x=r&&c,p=()=>o(h=>!h);return C.useEffect(()=>{var h,u,y,b;i?((h=t.current)==null||h.resize(0),(u=n.current)==null||u.resize(0)):((y=t.current)==null||y.resize(25),(b=n.current)==null||b.resize(25))},[i]),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(Un,{})}),e.jsx(s.ResizableHandle,{withHandle:!0,className:"data-[panel-group-direction=vertical]:ml-2 data-[panel-group-direction=vertical]:mr-6 data-[panel-group-direction=vertical]:w-auto"}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:l?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(Pl,{})})}),!i&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(ia,{visualAsideControl:x?{show:!0,isOpen:d,onToggle:p}:void 0})})]}):e.jsx(ia,{visualAsideControl:x?{show:!0,isOpen:d,onToggle:p}:void 0})})]})}function Bl(t){var Ne;s.useAIInteractionStore(q=>q.currentAIContext);const[n,a]=C.useState(""),[r,i]=C.useState(null),{authToken:d,tokenProps:o}=s.useSemaphorContext(),c=s.useEditorStore(q=>{var Z;return(Z=q==null?void 0:q.card)==null?void 0:Z.sql}),l=s.useEditorStore(q=>q.isDevMode),x=s.useEditorStore(q=>{var Z;return(Z=q==null?void 0:q.card)==null?void 0:Z.python}),{setCardPython:p,setCardSql:h,setRunSql:u,switchCardType:y,setQueryConfig:b}=s.useEditorActions(),m=s.useEditorStore(q=>q.currentAssitantScope)||[],g=s.useEditorStore(q=>q.userInputForAI),w=s.useEditorStore(q=>q.triggerAIRun),E=s.useEditorStore(q=>q.card),V=s.useEditorStore(q=>q.selectedDatabaseName),A=s.useEditorStore(q=>q.selectedTableName),T=s.useEditorStore(q=>q.selectedConnectionId),v=s.useEditorStore(q=>q.selectedSchemaName),D=s.useDashboardStore(q=>q.dashboard.aiScopeTables),{errorMessage:M,refetch:f,data:I}=s.useDashboardCardQuery(E),{setTriggerAIRun:j,setCurrentAssitantScope:k,setCardConfig:R}=s.useEditorActions(),{selectedDatamodelName:P,connectionType:N,selectedDatamodelId:L}=s.useEditorAside(),S=(Ne=s.useDashboardQuery().data)==null?void 0:Ne.assistantProfileId,{messages:F,setMessages:O,regenerate:_,error:Q,sendMessage:B,status:K,addToolResult:se,stop:H,clearError:te}=s.useChat({transport:new s.DefaultChatTransport({api:`${o.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${d==null?void 0:d.accessToken}`}),body:()=>{const q=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:S,isDevMode:l,aiContext:q.currentAIContext,reasoningEffort:q.reasoningEffort,showReasoning:q.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:q,body:Z})=>({body:{...Z,messages:s.cleanupIncompleteMessages(q)}})}),onError:q=>{var Z;if(q.name==="AbortError"||(Z=q.message)!=null&&Z.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)");return}console.error("[Editor Assistant] Stream error:",q)},onToolCall:z,onFinish({isAbort:q,isDisconnect:Z,isError:ie}){a(""),console.log(q?"[Editor Assistant] Stream aborted by user":Z?"[Editor Assistant] Stream disconnected (network error)":ie?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully")}});C.useEffect(()=>{w&&g&&(B({role:"user",parts:[{type:"text",text:g}]}),j(!1))},[w,g,B,j]);async function z({toolCall:q}){var Z,ie,je,ke,Me,we,be,Ce,ae,fe,ge,Ie,ve,pe,Oe,Ye;if(["createChartFromSql","createForecast"].includes(q.toolName)){const Ue=((Z=q.input)==null?void 0:Z.sql)??((ie=q.args)==null?void 0:ie.sql),oe=((je=q.input)==null?void 0:je.python)??((ke=q.args)==null?void 0:ke.python),xe=((Me=q.input)==null?void 0:Me.chartType)??((we=q.args)==null?void 0:we.chartType);y(xe),h(Ue),p(oe),u(!0),se({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(q.toolName==="getUserSql"){if(!c){se({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"error",message:"No SQL found"}});return}se({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",sql:c,python:x||""}})}else if(q.toolName==="generateQueryConfig"){a("Generating query config...");const Ue=((be=q.input)==null?void 0:be.chartType)??((Ce=q.args)==null?void 0:Ce.chartType),oe=((ae=q.input)==null?void 0:ae.queryConfig)??((fe=q.args)==null?void 0:fe.queryConfig);((ge=q.input)==null?void 0:ge.cardConfig)??((Ie=q.args)==null||Ie.cardConfig),y(Ue),R(oe),h(void 0),p(void 0);const xe=await f();if((ve=xe==null?void 0:xe.data)!=null&&ve.error){se({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"error",queryConfig:oe,message:(pe=xe==null?void 0:xe.data)==null?void 0:pe.error.message}});return}if((Oe=xe==null?void 0:xe.data)!=null&&Oe.records){se({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",queryConfig:oe,message:"The data has been visualized"}});return}se({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",queryConfig:oe,message:"The data has been visualized",records:(Ye=xe==null?void 0:xe.data)==null?void 0:Ye.records}})}else a("Analyzing...")}function W(q){const Z=s.removeFromScopeArray(m,q);le(Z)}function le(q){const Z=s.sanitizeAIScope(q);k(Z),O(ie=>[...ie,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(Z)}`}]}])}function X(){const q={databaseName:V||"",schemaName:v||"",tableName:A||"",datamodelId:L||"",datamodelName:s.resolveDatamodelName(P),connectionId:T||"",connectionType:N||""},Z=s.dedup([...m,q]);le(Z)}function ne(){const q={databaseName:V||"",schemaName:v||"",tableName:A||"",datamodelName:s.resolveDatamodelName(P),connectionId:T||"",connectionType:N||"",datamodelId:L||""};if(!s.isInAiScopeArray([...D||[],...m],q)||m.length===0){const ie=s.dedup([...D||[],...m,q]).filter(je=>je.connectionId===q.connectionId);le(ie)}}const me=!["ready","error"].includes(K),ee=s.getErrorMessage(Q);return{messages:F,setMessages:O,sendMessage:B,regenerate:_,isLoading:me,handleSetAIScope:ne,handleAddCurrentTableToScope:X,removeFromCurrentSelections:W,currentAssitantScope:m,setCurrentAssitantScope:k,stop:H,status:K,toolStatus:n,llmUsage:r,onFinish:t,errorMessage:ee,clearError:te}}const zl=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function ja({isFullscreen:t,onFullscreenChange:n,fullscreenContainer:a}){const r=C.useRef(null),[i,d]=C.useState(!1),[o,c]=C.useState(s.isDevEnv),[l,x]=C.useState(!1),[p,h]=C.useState(!1),[u,y]=C.useState(!1),b=t??u,m=s.useCurrentAIContext(),{setCurrentAIContext:g}=s.useAIActions(),{clearQueue:w}=s.useQueueActions(),{clearFileAttachments:E}=s.useFileActions(),V=s.useFileAttachments("editor"),A=s.useDashboardStore(oe=>oe.dashboard.aiContext),T=s.useEditorStore(oe=>oe.card.dataSource),v=s.useEditorStore(oe=>oe.actions.setCardSql),D=s.useEditorStore(oe=>oe.actions.setRunSql),M=s.useEditorStore(oe=>oe.showAIDialog),f=s.useDashboardStore(oe=>oe.handleOpenAssistantProfile),{setShowAIDialog:I,setCardPython:j}=s.useEditorActions(),{setDataSource:k}=s.useEditorActions(),{assistantProfile:R}=s.useAssistantProfile(),{messages:P,setMessages:N,sendMessage:L,isLoading:S,stop:F,status:O,llmUsage:_,errorMessage:Q,clearError:B}=Bl(),[K,se]=C.useState(""),H=oe=>{se(oe.target.value)},te=oe=>{oe.preventDefault();const xe=K.trim();if(!xe&&V.length===0)return;const as=[];xe&&as.push({type:"text",text:xe}),V.forEach(We=>{We.data&&as.push({type:"file",mediaType:We.type,filename:We.name,url:`data:${We.type};base64,${We.data}`})}),L({role:"user",parts:as}),se(""),E("editor"),ie({force:!0})},{visibleMessages:z,hasMoreMessages:W,totalMessageCount:le,loadMoreMessages:X,resetMessageWindow:ne}=s.useMessageWindow(P,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:me,contentRef:ee,isAtBottom:Ne,hasNewMessages:q,newMessageCount:Z,scrollToBottom:ie,handleScroll:je,resetNewMessageCount:ke}=s.useAutoScroll(z,{threshold:40,behavior:"smooth",isStreaming:S});C.useEffect(()=>{var oe;M&&((oe=r.current)==null||oe.focus(),g({selectedEntities:(T==null?void 0:T.selectedEntities)||[]}))},[M,T,g]),s.useAutoSubmitQueue({assistantType:"editor",status:O,isLoading:S,sendMessage:L});const{hasActiveTools:Me}=s.useActiveToolStatus(P),we=C.useCallback(oe=>{n==null||n(oe),t===void 0&&y(oe)},[t,n]);C.useEffect(()=>{if(!b)return;function oe(xe){xe.key==="Escape"&&we(!1)}return window.addEventListener("keydown",oe),()=>{window.removeEventListener("keydown",oe)}},[b,we]);const be=C.useCallback(oe=>{L({role:"user",parts:[{type:"text",text:oe}]}),ie({force:!0})},[L,ie]),Ce=C.useCallback(async()=>{const oe=JSON.stringify(P??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(oe),s.ue.success("Conversation copied")}catch(xe){console.error("Failed to copy conversation",xe),s.ue.error("Unable to copy conversation")}},[P]),ae=C.useCallback(()=>{we(!b)},[b,we]);function fe(oe,xe){xe==="sql"?(v(oe),D(!0)):xe==="python"&&(j(oe),D(!0))}function ge(){m.selectedEntities.length===0&&g({selectedEntities:(A==null?void 0:A.selectedEntities)||[]})}function Ie(oe){ge();const xe={role:"user",parts:[{type:"text",text:oe.title+" "+oe.subtitle}]};L(xe)}function ve(oe){ge(),L({role:"user",parts:[{type:"text",text:oe}]})}function pe(){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:i,onCheckedChange:d,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:c,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:x,children:"System Message"})]})]})}function Oe(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const Ye=(K==null?void 0:K.length)===0&&(P==null?void 0:P.filter(oe=>oe.role==="user").length)===0,Ue=e.jsxs("div",{"data-role":"editor-assistant",className:s.cn("flex h-full w-full flex-col justify-between px-6 py-4",b&&"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:[Oe(),f&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:f,children:(R==null?void 0:R.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[pe(),o&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Ce,children:"Copy Conversation"}),e.jsx(s.IconButton,{tooltip:b?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:ae,children:b?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:()=>{N([]),w("editor"),B(),ne()},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:()=>{I(!1)},children:e.jsx(s.X,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:me,className:"mt-2 flex min-w-0 w-full grow basis-0",onScroll:je,children:e.jsxs("div",{ref:ee,className:"min-w-0 space-y-4 py-2 pr-3","data-role":"messages",children:[W&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:X,className:"text-xs",children:["Load ",Math.min(5,le-z.length)," ","more messages (",le-z.length," ","hidden)"]})}),e.jsx(s.PrintMessages,{messages:z,showTools:o,handleRun:fe,showSystemMessage:l,onQuickReply:be,disableQuickReplies:S}),!Me&&e.jsx(s.AssistantStatus,{status:O,errorMessage:Q})]})}),M&&!Ne&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{ie({force:!0}),ke()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),q&&Z>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:Z>9?"9+":Z})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[Ye&&!R&&e.jsx(s.Placeholders,{onClick:Ie,placeholders:zl}),e.jsx("div",{children:Ye&&R&&e.jsx(s.SeedQuestions,{seedQuestions:R.seedQuestions||[],handleSeedQuestionClick:ve})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:r,setInput:se,stop:F,input:K,handleInputChange:H,handleSubmit:oe=>{ge(),te(oe),ie({force:!0})},isLoading:S,status:O,assistantType:"editor",onFocus:()=>{}})]}),_&&i&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",_.inputTokens," prompt tokens, ",_.outputTokens," ","completion tokens, ",_.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(T==null?void 0:T.selectedEntities)||[],open:p,onOpenChange:h,dataSource:T||s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]});return b&&a?an.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:Ue})}),a):Ue}function ql(t,n,a){if(!n)return!1;const r=n.qualifiedFieldName,i=n.qualifiedEntityName,d=i&&n.name?`${i}.${n.name}`:r;return t.some(o=>{if(!(s.getDataType(o.dataType||"")==="date"))return!1;const l=s.getSelectedDateFilterColumn(o,a),x=l.split("."),p=x[x.length-1]||l,h=x.length>1?x.slice(0,-1).join("."):void 0,u=o.qualifiedTableName||h,y=u?`${u}.${p}`:void 0;return r?y?y===d||y.endsWith(`.${r}`):p===n.name:y?y===d:p===n.name})}const Va=["day","week","month","quarter","year"],_l=[...Va,"hour","minute","second"],$l=t=>/timestamp|datetime|time/i.test(t||""),Gl=t=>$l(t)?_l:Va,ut=({dataType:t})=>s.getFieldIconComponent(t);function Kl({aliasTemplate:t,onAliasTemplateChange:n}){var l;const[a,r]=C.useState(t),[i,d]=C.useState(!1),o=(l=s.useEditorStore(x=>{var p;return(p=x.card.config)==null?void 0:p.pivotByColumns}))==null?void 0:l[0],c=o?`e.g. Min Sales in {{${o.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:c,value:i?a:t,onChange:x=>{r(x.target.value),d(!0)},onFocus:()=>d(!0),onPointerDown:x=>x.stopPropagation(),className:"h-8 text-xs",onKeyDown:x=>{x.key==="Enter"&&i&&a!==t?(n(a),d(!1)):x.key==="Escape"&&(r(t),d(!1))},"aria-label":"Edit alias template"}),i&&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),d(!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),d(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function Ul({valueAliases:t,onValueAliasesChange:n}){const[a,r]=C.useState(null),[i,d]=C.useState(""),[o,c]=C.useState(""),l=()=>{n({...t,"":""})},x=h=>{const u={...t};delete u[h],n(u)},p=h=>{const u={...t};delete u[h],u[i]=o,n(u),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,u],y)=>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:i,onChange:b=>d(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?p(h):b.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:o,onChange:b=>c(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?p(h):b.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>p(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),d(h),c(u)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:u,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),d(h),c(u)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>x(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+y)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:l,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function Hl({idx:t}){var c;const n=s.useEditorStore(l=>{var x;return(x=l.card)==null?void 0:x.preferences}),a=s.useEditorStore(l=>{var x;return(x=l.card.preferences)==null?void 0:x.datasetOptions}),r=s.useEditorStore(l=>l.actions.setCardPreferences),i=(c=n==null?void 0:n.chartOptions)==null?void 0:c.indexAxis,d=a==null?void 0:a.find(l=>l.idx===t);function o(l,x){(l==="end"||l==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const p={display:l!=="none",align:l,anchor:l,clamp:!0};if(!d)r({...n,datasetOptions:[...a||[],{idx:x,datalabels:p}]});else{const h={...d};h.datalabels=p;const u=a==null?void 0:a.map(y=>y.idx===x?h:y);r({...n,datasetOptions:u})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(s.Tag,{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:()=>o("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>o("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(xn,{className:s.cn("h-4 w-4",{"rotate-90":i==="y"})})}),e.jsx("button",{onClick:()=>o("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(pn,{className:s.cn("h-4 w-4",{"rotate-90":i==="y"})})}),e.jsx("button",{onClick:()=>o("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(hn,{className:s.cn("h-4 w-4",{"rotate-90":i==="y"})})})]})})]})}function mt({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 Jl(t,n=30){return t.length>n?t.slice(0,n)+"...":t}function Ql({col:t,idx:n,className:a,iconClassName:r,children:i}){const d=s.useEditorStore(p=>{var h;return(h=p.card)==null?void 0:h.preferences}),o=s.useEditorStore(p=>{var h,u;return(u=(h=p.card)==null?void 0:h.preferences)==null?void 0:u.datasetOptions}),c=o==null?void 0:o.find(p=>p.idx===n),{setCardPreferences:l}=s.useEditorStore(p=>p.actions);function x(p){if(!c)l({...d,datasetOptions:[...o||[],{idx:n,type:p==="area"?"line":p,fill:p==="area"?"origin":""}]});else{const h={...c};h.type=p==="area"?"line":p,h.fill=p==="area"?"origin":"";const u=o==null?void 0:o.map(y=>y.idx===n?h:y);l({...d,datasetOptions:u})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[i||e.jsx(mt,{className:"max-w-[100px]",title:t,children:Jl(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.ChartColumnIncreasing,{onClick:()=>x("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartLine,{onClick:()=>x("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartArea,{onClick:()=>x("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(Hl,{idx:n})]})]})}function Yl(){const t=s.useEditorStore(c=>c.card.type),n=s.useEditorStore(c=>c.isDevMode),a=s.useEditorStore(c=>c.card.preferences),{setCardPreferences:r}=s.useEditorStore(c=>c.actions);function i(c){var p;const l={datalabels:{display:c!=="none",align:c,anchor:c,clamp:!0}},x={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(p=a==null?void 0:a.chartOptions)==null?void 0:p.plugins,...l}}};r(x)}function d(){var c,l,x;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((x=(l=(c=a==null?void 0:a.chartOptions)==null?void 0:c.plugins)==null?void 0:l.datalabels)==null?void 0:x.anchor)||"none",onValueChange:i,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 o(){var c,l,x;return e.jsx("div",{children:e.jsxs(s.Select,{value:((x=(l=(c=a==null?void 0:a.chartOptions)==null?void 0:c.plugins)==null?void 0:l.datalabels)==null?void 0:x.anchor)||"none",onValueChange:i,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?d():o()})}function Wl({column:t}){const n=s.useEditorStore(l=>l.card.type),a=s.useEditorStore(l=>{var x,p;return(p=(x=l.card)==null?void 0:x.config)==null?void 0:p.metricColumns}),r=(a==null?void 0:a.map(l=>l.label))||[],i=r==null?void 0:r.find(l=>l===t.label||l===t.name),d=i?r.indexOf(i):-1;function o(){return e.jsx("div",{className:"pr-1",children:i&&e.jsx(Ql,{idx:d,col:i,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function c(){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(Yl,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&o(),["pie","doughnut"].includes(n)&&c()]})}function Xl({field:t,searchQuery:n="",limit:a=500}){const{authToken:r,tokenProps:i}=s.useSemaphorContext(),d=s.useEditorStore(x=>x.card),o=d==null?void 0:d.dataSource,c=["attribute-values",t.entityName,t.name,n,a],l=s.useQuery({queryKey:c,queryFn:async()=>{if(!(o!=null&&o.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const x={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},p={connection_id:o.connectionId,cardConfig:x,cardDataSource:o,cache_config:s.getCacheConfig({card:d})};console.log("requestBody",p);const h=await s.postRequestRegular(`${i.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",p);if(h!=null&&h.error)return console.error("Error fetching attribute values:",h.error),[];const u=t.name;return((h==null?void 0:h.records)||[]).map(b=>{const m=b[u]||b[t.alias||u]||b[t.label];return{id:m||"",value:m||"",label:String(m||"(empty)")}})}catch(x){return console.error("Error fetching attribute values:",x),[]}},enabled:!!t&&!!(o!=null&&o.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:l.data||[],isLoading:l.isLoading,isFetching:l.isFetching,isError:l.isError,error:l.error,refetch:l.refetch}}function Ba({open:t,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:i,onSave:d}){var V,A;const o=!!i,[c,l]=C.useState(o?"values":"fields"),[x,p]=C.useState(""),[h,u]=C.useState({id:(i==null?void 0:i.id)||s.v4(),field:(i==null?void 0:i.field)||null,selectedValues:i?Array.isArray(i.value)?i.value:[i.value]:[]}),y=a.filter(T=>{var D;return o?!1:!((D=r==null?void 0:r.conditions)==null?void 0:D.some(M=>M.field.id===T.id))&&T.label.toLowerCase().includes(x.toLowerCase())}),b=T=>{u({...h,field:T}),l("values")},m=()=>{if(h.field&&h.selectedValues.length>0){const T={id:h.id,field:h.field,operator:"in",value:h.selectedValues};let v;if(o){const D=((r==null?void 0:r.conditions)||[]).map(M=>M.id===i.id?T:M);v={...r,conditions:D}}else{const D=(r==null?void 0:r.conditions)||[];v={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...D,T],groups:[]}}d(v),n(!1)}},g=()=>{if(!o||!i)return;const T=((r==null?void 0:r.conditions)||[]).filter(v=>v.id!==i.id);if(T.length>0){const v={...r,conditions:T};d(v)}else d(void 0);n(!1)},w=T=>{u({...h,selectedValues:T})},E=()=>{o&&i?(u({id:i.id,field:i.field,selectedValues:Array.isArray(i.value)?i.value:[i.value]}),l("values")):(u({id:s.v4(),field:null,selectedValues:[]}),l("fields")),p("")};return C.useEffect(()=>{t&&E()},[t,o,i]),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:o?`Edit Filter: ${(V=h.field)==null?void 0:V.label}`:c==="fields"?"Select Field to Filter":`Select Values for ${(A=h.field)==null?void 0:A.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!o&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&c==="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(T=>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:[T.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(T.value)?`${T.value.length} values`:String(T.value)})]},T.id))})]}),c==="fields"&&!o?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:x,onChange:T=>p(T.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:y.map(T=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>b(T),children:[e.jsx(ut,{dataType:s.getDataType(T.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:T.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[T.entityName,".",T.name]})]})]},T.id))}),y.length===0&&x&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',x,'"']}),y.length===0&&!x&&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(Zl,{field:h.field,selectedValues:h.selectedValues,onValuesChange:w,onBack:o?void 0:()=>l("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:o?e.jsx(s.Button,{variant:"destructive",onClick:g,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:E,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:m,disabled:!h.field||h.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function Zl({field:t,selectedValues:n,onValuesChange:a,onBack:r}){const[i,d]=C.useState(""),{values:o,isLoading:c,isFetching:l}=Xl({field:t,searchQuery:i,limit:500}),x=i?o.filter(u=>String(u.value).toLowerCase().includes(i.toLowerCase())):o,p=u=>{const y=n.includes(u);a(y?n.filter(b=>b!==u):[...n,u])},h=()=>{n.length===x.length&&x.length>0?a([]):a(x.map(u=>u.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:i,onChange:u=>d(u.target.value),className:"pl-10"})]}),c||l?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===x.length&&x.length>0,onCheckedChange:h}),e.jsxs(s.Label,{className:"text-sm",children:["Select All (",x.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:x.map(u=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>p(u.value),children:[e.jsx(s.Checkbox,{checked:n.includes(u.value),onCheckedChange:()=>p(u.value)}),e.jsx(mt,{className:"text-sm",children:u.label})]},u.id))})]})]})}function eo({field:t,zone:n,index:a,sortDirection:r,onSortDirectionChange:i,hasPivotColumns:d=!1,cardType:o}){var gt,jt,bt,vt,yt,Nt,Ct,St,wt,Tt,Et,It,kt,Dt,At,Lt,Mt,Ot,Rt,Ft,Pt,Vt,Bt,zt,qt,_t,$t,Gt,Kt,Ut,Ht,Jt,Qt,Yt;const{attributes:c,listeners:l,setNodeRef:x,transform:p,transition:h,isDragging:u}=s.useSortable({id:t.id}),y=s.useEditorStore($=>$.card),b=s.useEditorStore($=>$.frame),{scopedFields:m,isLoading:g}=s.useScopedFields(),{userContext:w}=s.useCurrentUserInfo(),E=(w==null?void 0:w.type)==="organization",V=(gt=y.dataSource)==null?void 0:gt.semanticDomainId,{promoteMetric:A}=s.usePromoteCalculatedMetricToDomain({domainId:V}),{updateLabel:T,handleAggregationChange:v,handleDateFormatChange:D,handleGranularityChange:M,handleAliasTemplateChange:f,handleValueAliasesChange:I,removeField:j,handleMetricComparisonChange:k,handleMetricWindowTransformChange:R,handleMetricWindowOrderByChange:P,handleMetricWindowDirectionChange:N,handleMetricWindowPartitionToggle:L,handleMetricMovingAverageWindowSizeChange:S,handleMetricMovingAverageMinPeriodsChange:F,handleMetricPreviousPeriodDeltaModeChange:O,handleMetricPercentOfTotalScopeChange:_,handleMetricPercentOfTotalOutputChange:Q,handleKpiShowTrendlineChange:B,handleKpiTrendlineWindowChange:K,handleKpiTrendlineGranularityChange:se,handleMetricTargetValueChange:H}=s.useFieldManagement(y),[te,z]=C.useState(!1),[W,le]=C.useState(()=>{var $;return!!(($=t.parameters)!=null&&$.windowTransform)}),[X,ne]=C.useState(!1),[me,ee]=C.useState(!1),[Ne,q]=C.useState(null),Z=C.useMemo(()=>{const $=re=>re!=null&&re.startsWith("card-source-")?re.replace("card-source-",""):re,U=$(t.id),ce=m.find(re=>{if(t.qualifiedFieldName&&re.qualifiedFieldName&&re.qualifiedFieldName===t.qualifiedFieldName||t.qualifiedEntityName&&re.qualifiedEntityName&&re.qualifiedEntityName===t.qualifiedEntityName&&re.name===t.name)return!0;const ye=$(re.id);return!!(U&&ye&&U===ye)});return{dataType:(ce==null?void 0:ce.dataType)||t.dataType,resolvedFromScopedField:!!ce}},[t.dataType,t.id,t.name,t.qualifiedEntityName,t.qualifiedFieldName,m]),ie=Gl(Z.dataType),[je,ke]=C.useState(t.dateFormat||"YYYY-MM-DD"),[Me,we]=C.useState(t.customFormat||""),[be,Ce]=C.useState(!!t.customFormat),ae=C.useRef(null),[fe,ge]=C.useState(t.aliasTemplate||""),[Ie,ve]=C.useState(t.valueAliases||{}),[pe,Oe]=C.useState((jt=t.parameters)==null?void 0:jt.filters),Ye=$=>{$==="custom"?Ce(!0):(Ce(!1),ke($),(n==="groupBy"||gs)&&D(a,$,"",n))},Ue=$=>{we($),(n==="groupBy"||gs)&&D(a,"custom",$,n)},oe=$=>{var re;const ce=(re=s.getDateFormatOptionsForGranularity($)[0])==null?void 0:re.value;ce&&!be&&(ke(ce),n==="groupBy"&&D(a,ce,"",n)),n==="groupBy"&&M(a,$)},xe=$=>{ge($),n==="metrics"&&f(a,$)},as=$=>{ve($),n==="metrics"&&I(a,$)},We=$=>{T(n,a,$)},Ns=$=>$!=null&&$.startsWith("card-source-")?$.replace("card-source-",""):$,os=($,U,ce)=>{const re=Ns($.id),ye=Ns(U.id);return re&&ye&&re===ye?!0:$.name===U.name&&$.role===U.role},He=s.getExpressionFieldKind(t),ze=He==="domain_calculated"||He==="user_calculated",Se=He==="user_calculated"?(bt=b==null?void 0:b.calculatedFields)==null?void 0:bt.find($=>os($,t)):void 0,Cs=He==="user_calculated"&&(t.fieldScope==="dashboard"||t.fieldScope===void 0&&!!Se),$e=He==="domain_calculated",Ss=$e?"domain":Cs?"dashboard":"card",is=$e?t:Cs&&Se?Se:t,ws=$=>{var U;if(Oe($),n==="metrics"){const ce={...t,parameters:{...t.parameters,filters:$}},re=[...((U=y.config)==null?void 0:U.metricColumns)||[]];re[a]=ce,s.useEditorStore.getState().actions.updateCardConfig(y.id,{metricColumns:re})}ne(!1)},Ze=async $=>{await A($),en()},Ts=()=>{j(n,a)},Es={transform:s.CSS.Transform.toString(p),transition:h},ns=s.getDataType(Z.dataType||t.dataType),fs=ns==="date",cs=o==="kpi",gs=n==="detailColumns",Is=(vt=y.config)==null?void 0:vt.metricColumns,Ge=(yt=y.config)==null?void 0:yt.groupByColumns,ds=s.useDashboardStore($=>{var U;return(U=$.dashboard)==null?void 0:U.filters}),js=s.useDashboardStore($=>$.filterValues),Xe=t.granularity||"day",us=ie.includes(Xe)?Xe:"day",Je=n==="groupBy"&&!ie.includes(Xe),ks=s.getDateFormatOptionsForGranularity(us),Ds=be?"custom":ks.some($=>$.value===je)?je:((Nt=ks[0])==null?void 0:Nt.value)??"YYYY-MM-DD";C.useEffect(()=>{var ce;if(g||!Je){ae.current=null;return}const $=`${t.id}:${Xe}:${Z.dataType||t.dataType||""}:${a}`;if(ae.current===$)return;ae.current=$;const U="day";if(M(a,U),!be){const re=(ce=s.getDateFormatOptionsForGranularity(U)[0])==null?void 0:ce.value;re&&(ke(re),D(a,re,"",n))}},[t.dataType,t.id,D,M,Je,a,be,g,Xe,Z.dataType,n]);const qs=!!o&&s.COMPARISON_SUPPORTED_CHART_TYPES.includes(o),As=o==="kpi"||o==="table",qe=C.useMemo(()=>Ge==null?void 0:Ge.find($=>s.getDataType($.dataType||"")==="date"),[Ge]),Ls=C.useMemo(()=>(Ge||[]).some($=>s.getDataType($.dataType||"")==="date"),[Ge]),_s=C.useMemo(()=>{var re;if(!qe)return!1;const $=(re=y.config)==null?void 0:re.filters;if(!$)return!1;const U=ye=>{const Ee=ye.field;return Ee?qe.id&&Ee.id===qe.id||qe.qualifiedFieldName&&Ee.qualifiedFieldName===qe.qualifiedFieldName?!0:Ee.name===qe.name:!1},ce=ye=>ye.conditions.some(Be=>s.getDataType(Be.field.dataType||"")==="date"&&U(Be))?!0:ye.groups.some(Be=>ce(Be));return ce($)},[(Ct=y.config)==null?void 0:Ct.filters,qe]),$s=C.useMemo(()=>ql(ds||[],qe,js),[ds,js,qe]),bs=_s||$s,De=t,es=((wt=(St=De.parameters)==null?void 0:St.windowTransform)==null?void 0:wt.function)||"none",Fe=s.isMetricTransformEnabled(De),Pe=Fe?es:null,G=s.supportsMetricTransformForMetric({cardType:o||"table",cardConfig:y.config||{},metric:De,transformMode:Pe||"running_total"}),J=!!De.comparisonType&&De.comparisonType!=="none",Y=s.getRunningTotalOrderByCandidates(Ge||[]),ue=((It=(Et=(Tt=De.parameters)==null?void 0:Tt.windowTransform)==null?void 0:Et.orderBy)==null?void 0:It.fieldId)||"",de=((At=(Dt=(kt=De.parameters)==null?void 0:kt.windowTransform)==null?void 0:Dt.orderBy)==null?void 0:At.direction)||"asc",he=Y.find($=>$.id===ue),Te=Pe==="running_total"||Pe==="moving_average"||Pe==="previous_period_delta",Re=Fe&&Te&&!!he&&s.getDataType(he.dataType||"")!=="date",Qe=s.getDefaultRunningTotalPartitionByFieldIds({cardType:o||"table",cardConfig:y.config||{},orderByFieldId:ue||void 0}),ms=new Set(((Mt=(Lt=De.parameters)==null?void 0:Lt.windowTransform)==null?void 0:Mt.partitionByFieldIds)||Qe),xs=o==="pivotTable"||s.isSubtotalEnabledAggregateTable(o||"table",y.config||{}),Le=[...(Ge||[]).filter($=>$.id&&(!Te||$.id!==ue)),...xs?(((Ot=y.config)==null?void 0:Ot.pivotByColumns)||[]).filter($=>$.id):[]],rs=((Pt=(Ft=(Rt=De.parameters)==null?void 0:Rt.windowTransform)==null?void 0:Ft.movingAverage)==null?void 0:Pt.windowSize)||7,Gs=((zt=(Bt=(Vt=De.parameters)==null?void 0:Vt.windowTransform)==null?void 0:Bt.movingAverage)==null?void 0:zt.minPeriods)||1,Ks=(($t=(_t=(qt=De.parameters)==null?void 0:qt.windowTransform)==null?void 0:_t.previousPeriodDelta)==null?void 0:$t.mode)||"absolute",ht=((Ut=(Kt=(Gt=De.parameters)==null?void 0:Gt.windowTransform)==null?void 0:Kt.percentOfTotal)==null?void 0:Ut.scope)||"grand_total",qa=((Qt=(Jt=(Ht=De.parameters)==null?void 0:Ht.windowTransform)==null?void 0:Jt.percentOfTotal)==null?void 0:Qt.output)||"percent",_a=C.useMemo(()=>(Is||[]).some($=>$.comparisonType==="start_vs_end"),[Is]);C.useEffect(()=>{Fe&&le(!0)},[Fe]);const $a=n!=="pivotBy",Ga=fs&&n==="groupBy"&&(!cs||_a),Ka=!cs&&fs&&(n==="groupBy"||gs),Ua=o==="kpi"&&fs&&n==="groupBy",Ha=n==="metrics",pt=qs&&n==="metrics",Ja=()=>{const $=t,U=n==="metrics"&&ze;return e.jsxs("div",{className:"space-y-1",children:[!U&&e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:ce=>{ce.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-muted-foreground/80",children:`${t.entityName}.${t.name}`}),U&&$.calculatedFormula&&e.jsxs("div",{title:s.formatDisplayFormula($.calculatedFormula),onPointerDown:ce=>{ce.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap rounded bg-muted/50 px-1.5 py-0.5 font-mono text-xs text-primary",children:["= ",s.formatDisplayFormula($.calculatedFormula)]})]})},Qa=()=>$a?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(_e,{value:t.label??"",onSave:We,placeholder:"Display label...",type:"text"})]}):null,ft=()=>Ga?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:us,onValueChange:oe,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:ie.map($=>e.jsx(s.SelectItem,{className:"text-xs",value:$,children:s.toTitleCase($)},$))})]})]}):null,Ya=()=>Ka?e.jsxs(e.Fragment,{children:[ft(),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:Ds,onValueChange:Ye,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:ks.map($=>e.jsx(s.SelectItem,{className:"text-xs",value:$.value,children:$.label},$.value))})]}),be&&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:Me,onChange:$=>{$.stopPropagation(),Ue($.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,Wa=()=>{var U,ce,re,ye;const $=Ua;return $?e.jsx(e.Fragment,{children:$&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(s.SmallSwitch,{checked:((U=y.config)==null?void 0:U.showTrendline)||!1,onCheckedChange:B})]})}),((ce=y.config)==null?void 0:ce.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(s.Input$1,{type:"number",min:"1",max:"365",value:((re=y.config)==null?void 0:re.trendlineWindow)||30,onChange:Ee=>{const Be=parseInt(Ee.target.value)||30;K(Be)},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:((ye=y.config)==null?void 0:ye.trendlineGranularity)||"day",onValueChange:se,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},Xa=()=>{if(!Ha)return null;const $=ze;return e.jsxs(e.Fragment,{children:[$&&E&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Formula"}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>ee(!0),children:[e.jsx(s.Pencil,{className:"mr-2 h-3 w-3"}),"Edit Formula"]})]}),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:U=>{v(a,U)},disabled:$,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsx(s.Collapsible,{open:W,onOpenChange:le,children:e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-muted/20 p-2.5",children:[e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between rounded-sm px-0.5 py-0.5 text-left",children:[e.jsx("div",{className:"text-xs font-medium text-foreground",children:"Metric Transform"}),e.jsxs("div",{className:"flex items-center text-[11px] text-muted-foreground",children:[!W&&e.jsx("span",{className:"mr-2",children:Fe?s.toTitleCase(es.replace(/_/g," ")):"None"}),e.jsx(s.ChevronDown,{className:s.cn("h-3 w-3 transition-transform",W?"rotate-180":"")})]})]})}),e.jsxs(s.CollapsibleContent,{className:"space-y-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Transform"}),e.jsxs(s.Select,{value:Fe?es:"none",onValueChange:U=>R(a,U),disabled:!G.supported&&!Fe,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select transform..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"none",children:"None"}),e.jsx(s.SelectItem,{value:"running_total",disabled:J,children:"Running Total"}),e.jsx(s.SelectItem,{value:"moving_average",disabled:J,children:"Moving Average"}),e.jsx(s.SelectItem,{value:"previous_period_delta",disabled:J,children:"Previous Period Delta"}),e.jsx(s.SelectItem,{value:"percent_of_total",disabled:J,children:"Percent of Total"})]})]}),!G.supported&&!Fe&&e.jsx("div",{className:"text-xs text-muted-foreground",children:G.reason}),J&&!Fe&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"Disable comparison to enable metric transforms."})]}),Fe&&e.jsxs(e.Fragment,{children:[Te&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Order By"}),e.jsxs(s.Select,{value:ue,onValueChange:U=>P(a,U),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select order field..."})}),e.jsx(s.SelectContent,{children:Y.filter(U=>!!U.id).map(U=>e.jsx(s.SelectItem,{value:U.id,className:"text-xs",children:U.label||U.name},U.id))})]}),!ue&&e.jsx("div",{className:"text-xs text-amber-700",children:"No date trend detected. Select an order field."}),Re&&e.jsx("div",{className:"text-xs text-amber-700",children:"No date trend detected. The transform will follow the selected order field."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Direction"}),e.jsxs(s.Select,{value:de,onValueChange:U=>N(a,U),disabled:!ue,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select direction..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"asc",children:"Ascending"}),e.jsx(s.SelectItem,{className:"text-xs",value:"desc",children:"Descending"})]})]})]})]}),Pe==="moving_average"&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Window Size"}),e.jsx(s.Input$1,{type:"number",min:1,className:"h-8 text-xs",value:rs,onChange:U=>S(a,Number(U.target.value))}),e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Min Periods"}),e.jsx(s.Input$1,{type:"number",min:1,max:rs,className:"h-8 text-xs",value:Gs,onChange:U=>F(a,Number(U.target.value))})]}),Pe==="previous_period_delta"&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Output"}),e.jsxs(s.Select,{value:Ks,onValueChange:U=>O(a,U),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select output..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"absolute",children:"Absolute Delta"}),e.jsx(s.SelectItem,{value:"percent",children:"Percent Delta"})]})]})]}),Pe==="percent_of_total"&&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:"Scope"}),e.jsxs(s.Select,{value:ht,onValueChange:U=>_(a,U),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select scope..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"grand_total",children:"Grand Total"}),e.jsx(s.SelectItem,{value:"partition_total",children:"Partition Total"})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Output"}),e.jsxs(s.Select,{value:qa,onValueChange:U=>Q(a,U),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select output..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"percent",children:"Percent"}),e.jsx(s.SelectItem,{value:"fraction",children:"Fraction"})]})]})]})]}),(Pe==="running_total"||Pe==="moving_average"||Pe==="previous_period_delta"||Pe==="percent_of_total"&&ht==="partition_total")&&Le.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Reset By"}),e.jsx("div",{className:"space-y-1",children:Le.map(U=>{const ce=!!U.id&&ms.has(U.id);return e.jsxs("button",{type:"button",onClick:()=>U.id&&L(a,U.id),className:s.cn("flex h-7 w-full items-center justify-between rounded border px-2 text-xs",ce?"border-primary bg-primary/5 text-primary":"border-border text-muted-foreground"),children:[e.jsx("span",{children:U.label||U.name}),ce?e.jsx(s.Check,{className:"h-3 w-3"}):null]},U.id)})})]})]})]})]})}),pt&&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:De.comparisonType||"none",disabled:Fe,onValueChange:U=>k(a,U),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"}),(()=>{const U=!Ls||!bs,ce=Ls?bs?void 0:"Add a date filter to enable":"Add a date groupBy to enable",re=(ye,Ee)=>e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.SelectItem,{value:ye,disabled:U,title:ce,children:Ee})}),U&&ce&&e.jsx(s.TooltipContent,{side:"right",children:ce})]})});return e.jsxs(e.Fragment,{children:[re("previous_period","Previous Period"),re("same_period_last_year","Same Period Last Year"),re("start_vs_end","Start vs End")]})})(),As&&e.jsx(s.SelectItem,{value:"target",children:"Target"})]})]})]}),pt&&De.comparisonType==="target"&&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(s.Input$1,{type:"number",value:De.targetValue!==void 0&&De.targetValue!==null?String(De.targetValue):"",onChange:U=>{const ce=U.target.value;if(ce===""){H(a,void 0);return}const re=Number(ce);H(a,Number.isFinite(re)?re:void 0)},className:"h-8 text-xs",placeholder:"Enter target value..."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(pe==null?void 0:pe.conditions)&&pe.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:pe.conditions.map(U=>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:()=>{q(U),ne(!0)},children:[e.jsxs("span",{className:"font-medium",children:[U.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(U.value)?U.value.length===1?String(U.value[0]):U.value.length<=2?U.value.join(", "):`${U.value.slice(0,2).join(", ")} +${U.value.length-2}`:String(U.value)})}),Array.isArray(U.value)&&U.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 (",U.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:U.value.map((ce,re)=>e.jsx("div",{children:String(ce)},re))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:ce=>{var ye;ce.stopPropagation();const re=pe.conditions.filter(Ee=>Ee.id!==U.id);if(re.length>0){const Ee={...pe,conditions:re};ws(Ee)}else if(Oe(void 0),n==="metrics"){const Ee={...t,parameters:{...t.parameters,filters:void 0}},Be=[...((ye=y.config)==null?void 0:ye.metricColumns)||[]];Be[a]=Ee,s.useEditorStore.getState().actions.updateCardConfig(y.id,{metricColumns:Be})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},U.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{q(null),ne(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(Wl,{column:t}),d&&e.jsxs(e.Fragment,{children:[e.jsx(Kl,{aliasTemplate:fe,onAliasTemplateChange:xe}),e.jsx(Ul,{valueAliases:Ie,onValueAliasesChange:as})]})]})},{columns:Za=[],refetch:en}=s.useColumns(),sn=(pe==null?void 0:pe.conditions)&&pe.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:x,style:Es,...c,...l,className:s.cn("group mx-auto flex w-full flex-col gap-2 rounded-md border border-border/55 bg-background p-2 transition-colors duration-150","hover:border-border/80 hover:bg-muted/20",te&&"border-border/80 bg-muted/20 shadow-[inset_0_1px_0_rgba(255,255,255,0.35)]",u&&"z-50 scale-95 opacity-50",n==="filters"?"cursor-default":"cursor-move"),children:[e.jsxs("div",{className:"flex min-w-0 grow items-center gap-2",children:[e.jsx(ut,{dataType:ns}),e.jsx(mt,{className:s.cn("w-[140px] min-w-0 flex-1 text-sm text-foreground/95",sn&&"w-[120px] min-w-0"),children:s.getMetricDisplayLabel(t)}),n==="metrics"&&((Yt=pe==null?void 0:pe.conditions)==null?void 0:Yt.length)&&!te&&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 text-primary/90",children:[e.jsx(s.Filter,{className:"h-3 w-3"}),e.jsx("span",{children:pe.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:pe.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 text-foreground/55 hover:text-foreground",onClick:$=>{$.stopPropagation(),z(!te)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${te?"rotate-180":""}`})}),n==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-foreground/55 hover:text-foreground",onClick:$=>{$.stopPropagation(),i(r==="asc"?"desc":"asc")},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 text-foreground/55 hover:text-foreground",onClick:$=>{$.stopPropagation(),Ts()},children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]}),te&&e.jsxs("div",{className:"space-y-3 rounded-md bg-muted/20 p-2.5",children:[Ja(),Qa(),o==="kpi"&&ft(),Ya(),Wa(),Xa()]})]}),X&&e.jsx(Ba,{open:X,onOpenChange:$=>{ne($),$||q(null)},availableFields:Za,existingFilters:pe,editingCondition:Ne,onSave:$=>{var U;if($)ws($);else if(Oe(void 0),n==="metrics"){const ce={...t,parameters:{...t.parameters,filters:void 0}},re=[...((U=y.config)==null?void 0:U.metricColumns)||[]];re[a]=ce,s.useEditorStore.getState().actions.updateCardConfig(y.id,{metricColumns:re})}q(null)}}),me&&n==="metrics"&&ze&&e.jsx(s.CalculatedFieldEditor,{open:me,onOpenChange:ee,availableFields:m,existingField:is,existingFieldScope:Ss,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:$=>{var hs;if($.role!=="metric")return;const U=[...((hs=y.config)==null?void 0:hs.metricColumns)||[]];U[a]=$;const{frame:ce,actions:re}=s.useEditorStore.getState();if(re.updateCardConfig(y.id,{metricColumns:U}),!s.isCalculatedMetric($))return;const ye=ce.calculatedFields||[],Ee=ye.findIndex(Ke=>Ke.name===t.name&&Ke.role===t.role);if(Ee<0)return;const Be=ye.map((Ke,Ms)=>Ms===Ee?{...$,id:Ke.id}:Ke);re.updateFrame({calculatedFields:Be})},onSaveToDashboard:$=>{var Ms;if($.role!=="metric")return;const{frame:U,actions:ce}=s.useEditorStore.getState(),re=U.calculatedFields||[],ye=re.findIndex(Us=>os(Us,$)),Ee=ye>=0&&re[ye].id!==$.id?{...$,id:re[ye].id}:$,Be=ye>=0?re.map((Us,tn)=>tn===ye?Ee:Us):[...re,Ee];ce.updateFrame({calculatedFields:Be});const hs=[...((Ms=y.config)==null?void 0:Ms.metricColumns)||[]],Ke=t;hs[a]={...Ee,id:Ke.id,aliasTemplate:Ke.aliasTemplate,valueAliases:Ke.valueAliases,parameters:Ke.parameters,customFormat:Ke.customFormat},ce.updateCardConfig(y.id,{metricColumns:hs})},onPromoteMetricToDomain:V&&E?Ze:void 0,domainId:V,cardId:y.id})]})}function so({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:"Pivot Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metric Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});case"detailColumns":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields to display as columns in the detail table. No aggregation applied - shows raw values from the database."})]});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()})]})})}const to={groupBy:Fs,pivotBy:lt,metrics:yn,detailColumns:s.Table2,sortBy:s.ArrowUpDown};function ys({zone:t,fields:n,label:a,placeholder:r,shouldShow:i,hasPivotColumns:d=!1,activeField:o=null}){const{isOver:c,setNodeRef:l}=s.useDroppable({id:t}),{updateSortByColumn:x}=s.useEditorActions(),p=s.useEditorStore(w=>w.card),h=s.useEditorStore(w=>w.card.type),u=n.length>0,y=C.useMemo(()=>!o||!c?!0:s.validateFieldForChartType(o,t,h).isValid,[o,c,t,h]),b=(w,E)=>{var A;!((A=p.config)!=null&&A.sortByColumns)||p.config.sortByColumns.findIndex(T=>T.id===w)===-1||x(p.id,w,{direction:E})};if(t==="sortBy"&&i===!1)return null;const m=t!=="sortBy"&&h!=="kpi",g=to[t]||s.Plus;return e.jsxs("div",{className:"mb-3 w-full",children:[e.jsxs("div",{className:"mb-1.5 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium text-foreground",{}),children:a}),m&&e.jsx(so,{concept:t})]}),e.jsx("div",{ref:l,className:s.cn("rounded-lg border p-0.5 transition-colors duration-150",{"border-green-500 bg-green-50 shadow-[0_0_0_1px_rgba(34,197,94,0.18)] dark:bg-green-950":c&&y,"border-red-500 bg-red-50 shadow-[0_0_0_1px_rgba(239,68,68,0.18)] dark:bg-red-950":c&&!y,"border-solid border-border/55 bg-background":!c&&u,"min-h-[56px] border-dashed border-border/60 bg-background":!c&&!u}),children:n.length===0?e.jsxs("div",{className:"flex min-h-[56px] items-center justify-center gap-2 text-sm text-muted-foreground/85",children:[e.jsx(g,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground/80"}),e.jsx("span",{children:r})]}):e.jsx(s.SortableContext,{id:t,items:n.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map((w,E)=>{const A=w.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(eo,{field:w,zone:t,index:E,sortDirection:A,onSortDirectionChange:T=>b(w.id,T),hasPivotColumns:d,cardType:h})})},w.id)})})})})]})}function ao({groupByFields:t,pivotByFields:n,metricsFields:a,sortByFields:r,detailFields:i,activeField:d}){var se,H,te,z;const[o,c]=C.useState(!1),l=s.useEditorStore(W=>{var le;return!!((le=W.card.customCardPreferences)!=null&&le.url)}),x=s.useEditorStore(W=>W.card),p=s.useEditorStore(W=>W.frame),h=s.findCustomVisualConfigCard(p,x),{manifest:u}=s.useCustomVisual(((se=h==null?void 0:h.customCardPreferences)==null?void 0:se.url)||""),y=(H=u==null?void 0:u.visuals)==null?void 0:H.find(W=>{var le;return W.name===((le=h==null?void 0:h.customCardPreferences)==null?void 0:le.componentName)}),b=s.resolveMultiInputType(h,y)==="multiple",m=b&&!!((te=h==null?void 0:h.customCardPreferences)!=null&&te.url),g=s.getConfigSlotExpectedType(y==null?void 0:y.slots),w=s.useEditorStore(W=>W.actions.updateCardConfig),E=s.useEditorStore(W=>W.actions.updateFrame),{scopedFields:V,refetch:A}=s.useScopedFields(),{userContext:T}=s.useCurrentUserInfo(),v=b&&(h==null?void 0:h.id)===x.id&&g?g:x==null?void 0:x.type,D=v==="detailTable",M=t.length>0||a.length>0||i.length>0,f=!D&&(v!=="kpi"||a.length<=2),I=!D,j=!D&&v!=="kpi",k=v!=="kpi"&&M,R=D,P="Drop sort fields here",N=(z=x.dataSource)==null?void 0:z.semanticDomainId,{promoteMetric:L}=s.usePromoteCalculatedMetricToDomain({domainId:N}),S=(T==null?void 0:T.type)==="organization",F=W=>{const le=p.calculatedFields||[],X=le.findIndex(Z=>Z.name===W.name&&Z.role===W.role),ne=X>=0?{...W,id:le[X].id}:W,me=X>=0?le.map((Z,ie)=>ie===X?ne:Z):[...le,ne];E({calculatedFields:me});const ee=s.getNewField(ne,"metrics",a),Ne=a.findIndex(Z=>Z.name===ee.name&&Z.role===ee.role),q=Ne>=0?a.map((Z,ie)=>ie===Ne?{...Z,...ee,id:Z.id}:Z):[...a,ee];w(x.id,{metricColumns:q})},O=async W=>{await L(W),A()},_=["pie","doughnut","polar","funnel","aggregateTable","bubble","scatter"].includes(v),Q=j&&!_,B=()=>v==="kpi"?{label:"Trend By",placeholder:"Drop trend field here"}:{label:"Rows",placeholder:"Drop dimensions here"},K=()=>v==="kpi"?{label:"Metric",placeholder:"Drop metric here"}:{label:"Metrics",placeholder:"Drop metrics here"};return e.jsxs(e.Fragment,{children:[e.jsxs(s.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full space-y-2.5",children:[e.jsxs(s.AccordionItem,{value:"fields",className:"rounded-xl border border-border/55 border-b-0 bg-card px-3 shadow-[0_1px_2px_rgba(15,23,42,0.04)]",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2.5 text-xs font-semibold tracking-wide text-foreground/70 hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.List,{className:"h-4 w-4 text-foreground/60"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-3 pt-1.5",children:[f&&e.jsx(ys,{zone:"groupBy",fields:t,label:B().label,placeholder:B().placeholder,activeField:d}),Q&&e.jsx(ys,{zone:"pivotBy",fields:n,label:"Pivot Columns",placeholder:"Drop pivot fields here",activeField:d}),I&&e.jsx(ys,{zone:"metrics",fields:a,label:K().label,placeholder:K().placeholder,hasPivotColumns:n.length>0,activeField:d}),R&&e.jsx(ys,{zone:"detailColumns",fields:i,label:"Columns",placeholder:"Drop columns here"}),a.length>=1&&S&&e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:()=>c(!0),className:"mt-1.5 w-full justify-start border-border/60 border-dashed bg-background text-xs text-foreground/70 hover:bg-muted/40 hover:text-foreground",children:[e.jsx(s.Calculator,{className:"mr-2 h-4 w-4"}),"Create Metric"]}),k&&e.jsx(ys,{zone:"sortBy",fields:r,label:"Sort By",placeholder:P,activeField:d})]})]}),(!l||m)&&e.jsxs(s.AccordionItem,{value:"configuration",className:"rounded-xl border border-border/55 border-b-0 bg-card px-3 shadow-[0_1px_2px_rgba(15,23,42,0.04)]",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2.5 text-xs font-semibold tracking-wide text-foreground/70 hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Settings2,{className:"h-4 w-4 text-foreground/60"}),e.jsx("span",{children:"CHART SETTINGS"})]})}),e.jsx(s.AccordionContent,{className:"mb-2 rounded-md bg-muted/20 px-3 py-0.5",children:e.jsx(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:e.jsx(Pa,{mode:"config"})})})]}),(l||m)&&e.jsxs(s.AccordionItem,{value:"plugin",className:"rounded-xl border border-border/55 border-b-0 bg-card px-3 shadow-[0_1px_2px_rgba(15,23,42,0.04)]",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2.5 text-xs font-semibold tracking-wide text-foreground/70 outline-none ring-0 hover:no-underline focus:outline-none focus-visible:outline-none focus-visible:ring-0 focus-visible:ring-offset-0",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ya,{className:"h-4 w-4 text-foreground/60"}),e.jsx("span",{children:"COMPONENT SETTINGS"})]})}),e.jsx(s.AccordionContent,{className:"mb-2 rounded-md bg-muted/20 px-3 py-0.5",children:e.jsx(Ma,{})})]})]}),e.jsx(s.CalculatedFieldEditor,{open:o,onOpenChange:c,availableFields:V,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:W=>{W.role==="metric"&&w(x.id,{metricColumns:[...a,W]})},onSaveToDashboard:W=>{W.role==="metric"&&F(W)},onPromoteMetricToDomain:N&&S?O:void 0,domainId:N,cardId:x.id})]})}function no({onEditJoins:t}){const n=s.useEditorStore(c=>c.card),{autoJoinMetadata:a}=s.useDashboardCardQuery(n);if(!(a!=null&&a.autoResolved))return null;const{resolvedJoinPlan:r}=a,i=(r==null?void 0:r.joins)||[];if(i.length===0)return null;const d=c=>!c||c.length===0?"No conditions":c.map(l=>{var u,y,b,m;const x=`${(u=l.source)==null?void 0:u.entityName}.${(y=l.source)==null?void 0:y.name}`,p=`${(b=l.target)==null?void 0:b.entityName}.${(m=l.target)==null?void 0:m.name}`,h=l.operator||"=";return`${x} ${h} ${p}`}).join(" AND "),o=c=>!c.joinKeyGroups||c.joinKeyGroups.length===0?"No conditions defined":c.joinKeyGroups.length===1?d(c.joinKeyGroups[0].keys):c.joinKeyGroups.map((l,x)=>({id:x,operator:l.operator,condition:d(l.keys)}));return e.jsx(s.Card,{className:"border-blue-500/20 bg-blue-50/15 shadow-sm dark:bg-blue-950/10",children:e.jsxs("div",{className:"flex items-center justify-between p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Tn,{className:"size-4 text-blue-600/90 dark:text-blue-400"}),e.jsx("h3",{className:"text-xs font-semibold tracking-wide text-blue-900/90 dark:text-blue-100",children:"Resolved Joins"}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"secondary",className:"cursor-help bg-blue-100/80 text-xs text-blue-700 dark:bg-blue-900/70 dark:text-blue-300",children:i.length})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"max-w-md p-3",children:e.jsx("div",{className:"space-y-2",children:i.map((c,l)=>{const x=o(c),p=Array.isArray(x);return e.jsxs("div",{className:"rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"font-medium text-foreground",children:c.source.name}),e.jsx(s.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:c.target.name})]}),e.jsx(s.Badge,{variant:"outline",className:"border-green-500/40 bg-green-50/30 text-xs text-green-700 dark:bg-green-950/30 dark:text-green-300",children:c.joinType})]}),e.jsx("div",{className:"mt-1 space-y-1",children:p?x.map(h=>e.jsxs("div",{className:"rounded bg-muted/30 px-2 py-1",children:[e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:h.condition}),h.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",h.operator,")"]})]},h.id)):e.jsx("div",{className:"rounded bg-muted/30 px-2 py-1",children:e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:x})})})]},c.id||l)})})})]})})]}),t&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:t,className:"h-7 gap-1 p-2 text-xs text-blue-700/80 hover:text-blue-900 dark:text-blue-300 dark:hover:text-blue-100",children:e.jsx(s.SquarePen,{className:"size-3.5"})})]})})}const ba={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 ro({selectedChart:t,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:i,sortByFields:d,detailFields:o,activeField:c}){var f,I;const[l,x]=C.useState(()=>ba.getItem("chart-selector-expanded")==="true"),[p,h]=C.useState(!1),u=s.useEditorStore(j=>j.card),y=s.useEditorStore(j=>j.actions.updateCardConfig),b=a.length>0||r.length>0||i.length>0||o.length>0,{data:m,autoJoinMetadata:g}=s.useDashboardCardQuery(u),w=b||!!m,E=((f=u==null?void 0:u.config)==null?void 0:f.joinPlan)||(g!=null&&g.autoResolved?g.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),V=((I=u==null?void 0:u.dataSource)==null?void 0:I.selectedEntities)||[],A=j=>{y(u.id,{...u==null?void 0:u.config,joinPlan:j}),h(!1)},T=()=>{y(u.id,{...u==null?void 0:u.config,joinPlan:void 0}),h(!1)},v=()=>{h(!1)},D=()=>{h(!0)};C.useEffect(()=>{ba.setItem("chart-selector-expanded",String(l))},[l]);const M=()=>{x(j=>!j)};return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col bg-background",children:[e.jsx("div",{className:"pl-2 pr-4 pt-4",children:e.jsxs("div",{className:"rounded-xl border border-border/60 bg-card p-3 shadow-[0_1px_2px_rgba(15,23,42,0.05)]",children:[e.jsx("div",{className:s.cn("overflow-hidden transition-all duration-300 ease-in-out",l?"max-h-[210px] opacity-100":"max-h-0 opacity-0"),children:l&&e.jsx(it,{selectedChart:t,onChartChange:n,variant:"outline"})}),e.jsx("div",{"data-content":"Chart Quick Selector",className:s.cn("flex items-center justify-center",{"mt-3":l,"mt-2":!l}),children:e.jsx(s.ChartQuickSelector,{selectedChart:t,onChartChange:n,isDropdownExpanded:l,onToggleDropdown:M})})]})}),w&&e.jsx("div",{className:"pl-2 pr-4 py-3",children:e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(Ae.EditorClearButton,{label:"Reset",variant:"secondary",className:"h-7 px-2 text-xs"})})}),e.jsx(s.ScrollArea,{className:"min-h-0 w-full flex-1 basis-0",children:e.jsxs("div",{className:s.cn("space-y-3 pl-2 pr-4 pb-6",w?"pt-1":"pt-4"),children:[e.jsx(no,{onEditJoins:D}),e.jsx(ao,{groupByFields:a,pivotByFields:r,metricsFields:i,sortByFields:d,detailFields:o,activeField:c})]})}),e.jsx(wa,{open:p,onOpenChange:h,joinPlan:E,availableDataSources:V,onSave:A,onCancel:v,onRemove:T,children:e.jsx("div",{})})]})}function lo({initialFilters:t,availableFields:n}={}){const[a,r]=C.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(T=>T.card.dataSource);const{columns:i,isLoading:d}=s.useColumns(),c=n||i||[],l={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},x=T=>{const v=D=>{if(D.id===T){const M=c[0]||l,f=s.getDataType(M.dataType)==="date";return{...D,conditions:[...D.conditions,{id:`condition-${Date.now()}`,field:M,operator:f?"between":"=",value:f?[]:""}]}}return{...D,groups:D.groups.map(v)}};r(v(a))},p=T=>{const v=D=>{if(D.id===T){const M=c[0]||l,f=s.getDataType(M.dataType)==="date";return{...D,groups:[...D.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:M,operator:f?"between":"=",value:f?[]:""}],groups:[]}]}}return{...D,groups:D.groups.map(v)}};r(v(a))},h=(T,v)=>{const D=M=>M.id===T?{...M,conditions:M.conditions.filter(f=>f.id!==v)}:{...M,groups:M.groups.map(D)};r(D(a))},u=(T,v)=>{const D=M=>M.id===T?{...M,groups:M.groups.filter(f=>f.id!==v)}:{...M,groups:M.groups.map(D)};r(D(a))},y=(T,v,D,M)=>{if(D==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const f=I=>I.id===T?{...I,conditions:I.conditions.map(j=>j.id===v?{...j,[D]:M}:j)}:{...I,groups:I.groups.map(f)};r(f(a))},b=(T,v,D)=>{const M=f=>f.id===T?{...f,conditions:f.conditions.map(I=>I.id===v?{...I,...D}:I)}:{...f,groups:f.groups.map(M)};r(M(a))},m=(T,v)=>{const D=M=>M.id===T?{...M,logicalOperator:v}:{...M,groups:M.groups.map(D)};r(D(a))},g=(T,v)=>{const D=M=>M.id===T?{...M,negate:v}:{...M,groups:M.groups.map(D)};r(D(a))},w=(T,v,D)=>{const M=f=>f.id===T?{...f,conditions:s.arrayMove(f.conditions,v,D)}:{...f,groups:f.groups.map(M)};r(M(a))},E=(T,v,D)=>{const M=f=>f.id===T?{...f,groups:s.arrayMove(f.groups,v,D)}:{...f,groups:f.groups.map(M)};r(M(a))},V=T=>{if(!T||T.conditions.length===0&&T.groups.length===0)return"-- No filters defined";const v=M=>{let f="";typeof M.field=="object"?f=M.field.entityName?`${M.field.entityName}.${M.field.name}`:M.field.name:f=String(M.field);const I=M.operator;let j=M.value;if(M.field.dataType==="string"&&!["in","not in"].includes(M.operator))typeof j=="string"?j=`'${j}'`:Array.isArray(j)&&(j=`'${j.join(", ")}'`);else if(M.field.dataType==="date"||M.field.dataType==="datetime"||M.field.dataType==="timestamp")if(M.operator==="between"&&Array.isArray(j)&&j.length===2){const k=j[0]?`'${j[0]}'`:"NULL",R=j[1]?`'${j[1]}'`:"NULL";return`${f} BETWEEN ${k} AND ${R}`}else if((M.operator==="in"||M.operator==="not in")&&Array.isArray(j)){const k=j.map(R=>R?`'${R}'`:"NULL").join(", ");return`${f} ${I} (${k})`}else typeof j=="string"||j instanceof Date?j=`'${j}'`:Array.isArray(j)&&j.length>0&&(j=`'${j[0]}'`);else if(["in","not in"].includes(M.operator)){let k=[];Array.isArray(j)?k=j.map(R=>typeof R=="string"?`'${R}'`:String(R)):typeof j=="string"?k=j.split(",").map(R=>{const P=R.trim();return M.field.dataType==="string"?`'${P}'`:P}):typeof j=="number"&&(k=[String(j)]),j=`(${k.join(", ")})`}switch(I){case"contains":return typeof j=="string"?`${f} LIKE '%${j.replace(/'/g,"")}'`:`${f} LIKE '%${String(j)}'`;case"startsWith":return typeof j=="string"?`${f} LIKE '${j.replace(/'/g,"")}%'`:`${f} LIKE '${String(j)}%'`;case"endsWith":return typeof j=="string"?`${f} LIKE '%${j.replace(/'/g,"")}'`:`${f} LIKE '%${String(j)}'`;case"isNull":return`${f} IS NULL`;case"isNotNull":return`${f} IS NOT NULL`;default:return`${f} ${I} ${j}`}},D=M=>{const f=M.conditions.map(v),I=M.groups.map(P=>D(P)),j=[...f,...I].filter(Boolean);if(j.length===0)return"";const k=j.join(` ${M.logicalOperator} `),R=j.length>1?`(${k})`:k;return M.negate?`NOT ${R}`:R};return D(T)},A=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:c,isLoading:d,addCondition:x,addGroup:p,removeCondition:h,removeGroup:u,updateCondition:y,updateConditionFields:b,updateGroupOperator:m,updateGroupNegate:g,reorderConditions:w,reorderGroups:E,generateSQLPreview:V,hasAnyFilters:A}}function oo({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 io=t=>{if(t.qualifiedEntityName){const n=t.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function co({value:t,onValueChange:n,availableFields:a,placeholder:r="Select field",className:i="w-64"}){const[d,o]=C.useState(!1),c=C.useMemo(()=>{const l={};return a.forEach(x=>{const p=io(x);l[p]||(l[p]={}),l[p][x.entityId]||(l[p][x.entityId]=[]),l[p][x.entityId].push(x)}),l},[a]);return e.jsxs(s.Popover,{modal:!0,open:d,onOpenChange:o,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":d,className:s.cn("justify-between",!t&&"text-muted-foreground",i),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(oo,{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(c).map(([l,x])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),l]}),children:Object.entries(x).map(([p,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:[s.getEntityIcon(h[0].entityType,{size:"h-3 w-3"}),e.jsx("span",{children:h[0].entityName})]}),h.map((u,y)=>e.jsxs(s.CommandItem,{value:u.id,onSelect:()=>{n(u),o(!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)===u.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:u.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:u.description&&e.jsx("span",{children:u.description})})]})]},u.id+y))]},`${l}-${p}`))},l))})]})})]})}function xt(t){var m;const n=s.useEditorStore(g=>g.card),{authToken:a,tokenProps:r}=s.useSemaphorContext(),i=s.useEditorStore(g=>g.card.config),d=i==null?void 0:i.joinPlan,o={...t,alias:t.name,label:"value",role:"groupby"},c={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},l={...o,role:"sortby",direction:"asc"},x={joinPlan:d,groupByColumns:[o],metricColumns:[c],sortByColumns:[l]},p=((m=n.dataSource)==null?void 0:m.connectionId)||n.connectionId,{data:h,isPending:u,error:y}=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:p,cardConfig:x,cardDataSource:n.dataSource})}catch(g){console.log(t),console.error("error",g)}},enabled:!!p,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((h==null?void 0:h.records)||[]).map(g=>({label:g.value||"BLANK",value:g.value||"BLANK",count:(g==null?void 0:g.count)||0})),isPending:u,error:y}}function uo({field:t,selected:n,onChange:a,placeholder:r="Select items...",className:i}){const[d,o]=at.useState(!1),{filterValues:c}=xt(t),l=p=>{a(n.filter(h=>h!==p))},x=p=>{n.includes(p)?a(n.filter(h=>h!==p)):a([...n,p])};return e.jsx("div",{className:s.cn("w-full",i),children:e.jsxs(s.Popover,{open:d,onOpenChange:o,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":d,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(p=>{const h=c.find(u=>u.value===p);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:u=>{u.key==="Enter"&&l(p)},onMouseDown:u=>{u.preventDefault(),u.stopPropagation()},onClick:u=>{u.stopPropagation(),l(p)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},p)}):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:c.map((p,h)=>e.jsxs(s.CommandItem,{onSelect:()=>x(p.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",n.includes(p.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:p.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:p.count})]})]},p.value+h))})]})]})})]})})}function mo({field:t,value:n,onChange:a,placeholder:r="Select value...",className:i}){const{filterValues:d,isPending:o,error:c}=xt(t);return o?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..."]}):c?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:i||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:n})}),e.jsx(s.SelectContent,{children:d.map((l,x)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:l.value,children:l.label},l.value+x))})]})}function xo({value:t,operator:n,onChange:a,className:r}){var y,b,m;const{tokenProps:i}=s.useSemaphorContext(),d=((b=(y=i==null?void 0:i.params)==null?void 0:y.calendarContext)==null?void 0:b.tz)||((m=i==null?void 0:i.params)==null?void 0:m.timezone),o=d||Intl.DateTimeFormat().resolvedOptions().timeZone,c=n==="between"||n==="not between",l=C.useMemo(()=>{if(!(!t||!c)&&Array.isArray(t)&&t.length===2){const g=t[0]?new Date(t[0]):void 0,w=t[1]?new Date(t[1]):void 0;if(g&&w)return{from:g,to:w}}},[t,c]),x=C.useMemo(()=>{if(!t||c)return;const g=Array.isArray(t)?t[0]:t;if(!g)return;const w=new Date(g);if(!isNaN(w.getTime()))return w},[t,c]),p=g=>n==="<="||n===">"?s.endOfDayInTimezone(g,o):s.startOfDayInTimezone(g,o),h=g=>{if(!g){a([]);return}if(g.from&&g.to){a([g.from.toISOString(),g.to.toISOString()]);return}a([])},u=g=>{if(!g){a("");return}const w=p(g);a(w.toISOString())};return e.jsx(s.DateRangePicker,{value:c?l:void 0,selectionMode:c?"range":"single",singleValue:c?void 0:x,onChange:h,onSingleChange:u,timezone:d,showRelativeTab:c,className:r,placeholder:"Select date..."})}const ho=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],po=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],fo=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],go=["=","!=","isNull","isNotNull"],jo=["between","=","!=","<","<=",">",">=","isNull","isNotNull"],bo={"=":"Equals","!=":"Not Equals",">":"Greater Than",">=":"Greater Than or Equal","<":"Less Than","<=":"Less Than or Equal",contains:"Contains",startsWith:"Starts With",endsWith:"Ends With",in:"In","not in":"Not In",between:"Between",isNull:"Is Null",isNotNull:"Is Not Null","not between":"Not Between"};function va(t){return bo[t]||s.titleCase(t)}function vo(t){switch(t){case"string":return po;case"number":return fo;case"boolean":return go;case"date":return jo;default:return ho}}function za({condition:t,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:i,onRemoveCondition:d,onUpdateGroupOperator:o,availableFields:c,updateConditionFields:l}){const{attributes:x,listeners:p,setNodeRef:h,transform:u,transition:y,isDragging:b}=s.useSortable({id:t.id}),{isPending:m,error:g}=xt(t.field),w={transform:s.CSS.Transform.toString(u),transition:y};return e.jsxs("div",{ref:h,style:w,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${b?"z-50 opacity-50":""}`,children:[e.jsx("div",{...x,...p,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:E=>o(a,E),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(co,{value:t.field,onValueChange:E=>{const V=E,A=s.getDataType(V.dataType)==="date";l(a,t.id,{field:V,value:"",operator:A?"between":"="})},availableFields:c,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:E=>{E==="in"||E==="not in"?l(a,t.id,{operator:E,value:[]}):E==="isNull"||E==="isNotNull"?l(a,t.id,{operator:E,value:null}):E==="between"||E==="not between"?l(a,t.id,{operator:E,value:[]}):l(a,t.id,{operator:E,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?va(t.operator):""})}),e.jsx(s.SelectContent,{children:vo(s.getDataType(t.field.dataType)).map(E=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:E,children:va(E)},E))})]}),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"?m?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..."]}):g?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(uo,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(E=>typeof E=="string")?t.value:[],onChange:E=>l(a,t.id,{value:E}),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:E=>l(a,t.id,{value:E.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(mo,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:E=>l(a,t.id,{value:E}),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:E=>l(a,t.id,{value:E==="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(xo,{value:t.value,operator:t.operator,onChange:E=>l(a,t.id,{value:E}),className:"flex-1"}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:E=>i(a,t.id,"value",E.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:()=>d(a,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function yo({group:t,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:i,onRemoveGroup:d,onUpdateCondition:o,onUpdateField:c,onRemoveCondition:l,onReorderConditions:x,onReorderGroups:p,onAddCondition:h,onAddGroup:u,availableFields:y,renderFilterGroup:b,updateConditionFields:m}){const{attributes:g,listeners:w,setNodeRef:E,transform:V,transition:A,isDragging:T}=s.useSortable({id:t.id}),v={transform:s.CSS.Transform.toString(V),transition:A},D=f=>{const{active:I,over:j}=f;if(j&&I.id!==j.id){const k=t.conditions.findIndex(P=>P.id===I.id),R=t.conditions.findIndex(P=>P.id===j.id);k!==-1&&R!==-1&&x(t.id,k,R)}},M=f=>{const{active:I,over:j}=f;if(j&&I.id!==j.id&&a){const k=t.groups.findIndex(P=>P.id===I.id),R=t.groups.findIndex(P=>P.id===j.id);k!==-1&&R!==-1&&p(a,k,R)}};return e.jsxs("div",{ref:E,style:v,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${T?"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",{...g,...w,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:()=>i(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:f=>r(t.id,f),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&&d(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:D,children:e.jsx(s.SortableContext,{items:t.conditions.map(f=>f.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((f,I)=>e.jsx(za,{condition:f,index:I,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:o,onUpdateField:c,onRemoveCondition:l,onUpdateGroupOperator:r,availableFields:y,updateConditionFields:m},f.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:M,children:e.jsx(s.SortableContext,{items:t.groups.map(f=>f.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(f=>b(f,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:()=>u(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function No({filters:t,availableFields:n,onSave:a,onClearAll:r,onCancel:i}){const{currentFilters:d,availableFields:o,isLoading:c,addCondition:l,addGroup:x,removeCondition:p,removeGroup:h,updateCondition:u,updateConditionFields:y,updateGroupOperator:b,updateGroupNegate:m,reorderConditions:g,reorderGroups:w,generateSQLPreview:E,hasAnyFilters:V,setCurrentFilters:A}=lo({initialFilters:t,availableFields:n}),T=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[v,D]=C.useState(!1),M=(j,k,R)=>{const P=N=>N.id===j?{...N,conditions:N.conditions.map(L=>L.id===k?{...L,field:R,dataType:R.dataType}:L)}:{...N,groups:N.groups.map(P)};A(P(d))},f=(j,k=0,R)=>k===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:T,collisionDetection:s.closestCenter,onDragEnd:P=>{const{active:N,over:L}=P;if(L&&N.id!==L.id){const S=j.conditions.findIndex(O=>O.id===N.id),F=j.conditions.findIndex(O=>O.id===L.id);S!==-1&&F!==-1&&g(j.id,S,F)}},children:e.jsx(s.SortableContext,{items:j.conditions.map(P=>P.id),strategy:s.verticalListSortingStrategy,children:j.conditions.map((P,N)=>e.jsx(za,{condition:P,index:N,groupId:j.id,groupLogicalOperator:j.logicalOperator,onUpdateCondition:u,onUpdateField:M,onRemoveCondition:p,onUpdateGroupOperator:b,availableFields:o,updateConditionFields:y},P.id))})}),e.jsx(s.DndContext,{sensors:T,collisionDetection:s.closestCenter,onDragEnd:P=>{const{active:N,over:L}=P;if(L&&N.id!==L.id){const S=j.groups.findIndex(O=>O.id===N.id),F=j.groups.findIndex(O=>O.id===L.id);S!==-1&&F!==-1&&w(j.id,S,F)}},children:e.jsx(s.SortableContext,{items:j.groups.map(P=>P.id),strategy:s.verticalListSortingStrategy,children:j.groups.map(P=>f(P,k+1,j.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:()=>l(j.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),v&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>x(j.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},j.id):e.jsx(yo,{group:j,depth:k,parentGroupId:R,onUpdateGroupOperator:b,onUpdateGroupNegate:m,onRemoveGroup:h,onUpdateCondition:u,onUpdateField:M,onRemoveCondition:p,onReorderConditions:g,onReorderGroups:w,onAddCondition:l,onAddGroup:x,availableFields:o,renderFilterGroup:f,updateConditionFields:y},j.id),I=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:[c?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..."})]}):f(d),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:v,onCheckedChange:j=>D(j)}),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)"})]})}),V&&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:E(d)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:i,children:"Cancel"}),I>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>a(V?d:null),children:"Apply Filters"})]})]})}function Co({cardId:t,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:i,isOpen:d,onOpenChange:o}){const c=x=>{a(t,x),o(!1)},l=()=>{r(t),o(!1)};return e.jsxs(s.Dialog,{modal:!1,open:d,onOpenChange:o,children:[d&&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:x=>{x.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Card Filters"}),e.jsx(s.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(No,{filters:n,availableFields:i,onSave:c,onCancel:()=>o(!1),onClearAll:l})]})]})}function So({activeCardId:t,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var E,V;const[i,d]=C.useState(null),o=s.useEditorStore(A=>A.card),c=s.useEditorStore(A=>A.actions.updateCardConfig),l=s.useEditorStore(A=>A.actions.setCardPreferences),x=(E=o==null?void 0:o.config)==null?void 0:E.joinPlan,p=C.useCallback(A=>A.entityName===s.CALCULATED_FIELD_ENTITY_MARKER||A.entityName==="calculated_fields"||A.qualifiedEntityName==="calculated_fields",[]),h=(V=o==null?void 0:o.dataSource)==null?void 0:V.semanticDomainId,{data:u}=s.useJoinabilityMap(h),y=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy"),...a("detailColumns")],b=C.useCallback(A=>A.startsWith("card-source-")?"source":A.startsWith("card-")?null:A.startsWith("source-")||n.find(T=>T.id===A)?"source":a("groupBy").find(T=>T.id===A)?"groupBy":a("metrics").find(T=>T.id===A)?"metrics":a("pivotBy").find(T=>T.id===A)?"pivotBy":a("sortBy").find(T=>T.id===A)?"sortBy":a("detailColumns").find(T=>T.id===A)?"detailColumns":null,[n,a]),m=C.useCallback(A=>{d(A.active.id)},[]),g=C.useCallback(A=>{var j;const{active:T,over:v}=A;if(!v||!t){d(null);return}const D=T.id,M=v.id,f=b(D),I=b(M)||M;if(I==="sortBy"){if(f==="source"){const k=n.find(P=>P.id===D);if(!k){d(null);return}if(!(a("groupBy").some(P=>P.name===k.name&&P.qualifiedEntityName===k.qualifiedEntityName)||a("metrics").some(P=>P.name===k.name&&P.qualifiedEntityName===k.qualifiedEntityName)||a("detailColumns").some(P=>P.name===k.name&&P.qualifiedEntityName===k.qualifiedEntityName))){d(null);return}}else if(f==="pivotBy"){d(null);return}else if(f!=="groupBy"&&f!=="metrics"&&f!=="sortBy"&&f!=="detailColumns"){d(null);return}}if(f==="source"&&I==="sortBy"){const k=[...n].find(L=>L.id===D);if(!k){d(null);return}const R=a("sortBy");if(s.fieldAlreadyExists(k,R)){d(null);return}const P=s.validateFieldForChartType(k,"sortBy",o.type);if(!P.isValid){s.ue.error("Invalid Field Type",{description:P.reason,position:"top-center",duration:3e3}),d(null);return}const N=s.getNewField(k,"sortBy",R);d(null),r("sortBy",[...R,N]);return}if(f==="source"&&I!=="source"&&I!=="sortBy"){const k=[...n].find(O=>O.id===D);if(!k){d(null);return}const R=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy"),...a("detailColumns")],P=R.filter(O=>!p(O));if(P.length>0){const O=P[0].qualifiedEntityName;if(!O){d(null);return}if(O!==k.qualifiedEntityName&&!p(k)&&k.qualifiedEntityName)if(h&&(u!=null&&u.joinabilityMap)){if(s.calculateFieldState(k,{joinabilityMap:u.joinabilityMap,selectedFields:R,baseEntityName:(j=x==null?void 0:x.baseEntity)==null?void 0:j.name}).state==="unreachable"){s.showJoinRequiredNotification(),d(null);return}}else{if(!x){s.showJoinRequiredNotification(),d(null);return}if(!s.areEntitiesJoined(O,k.qualifiedEntityName,x)){s.showJoinRequiredNotification(),d(null);return}}}const N=a(I);if(s.fieldAlreadyExists(k,N)){d(null);return}const L=s.validateFieldForChartType(k,I,o.type);if(!L.isValid){s.ue.error("Invalid Field Type",{description:L.reason,position:"top-center",duration:3e3}),d(null);return}const S=s.getNewField(k,I,N),F=[...N,S];if(d(null),r(I,F),I==="metrics"&&t){const O=s.seedSemanticMetricFormatDefaults(o,S,o.preferences);O&&l(O),s.cleanupKpiMetricComparisonMode(o.type,o.config,c,t,F)}return}if(f&&I&&f!=="source"&&I!=="source"&&f!==I){const k=a(f),R=a(I),P=k.find(O=>O.id===D);if(!P){d(null);return}const N=s.validateFieldForChartType(P,I,o.type);if(!N.isValid){s.ue.error("Invalid Field Type",{description:N.reason,position:"top-center",duration:3e3}),d(null);return}const L=s.getNewField(P,I,R);if(d(null),I==="sortBy"){s.fieldAlreadyExists(P,R)||r(I,[...R,L]);return}const S=k.filter(O=>O.id!==D),F=[...R,L];if(r(f,S),r(I,F),I==="metrics"&&t){const O=s.seedSemanticMetricFormatDefaults(o,L,o.preferences);O&&l(O),s.cleanupKpiMetricComparisonMode(o.type,o.config,c,t,F)}return}if(f&&I&&f===I&&f!=="source"){const k=a(f),R=k.findIndex(N=>N.id===D),P=k.findIndex(N=>N.id===M);if(R!==P){const N=s.arrayMove(k,R,P);r(f,N)}}d(null)},[t,n,a,r,b,x,h,u,p,o,c,l]),w=i?y.find(A=>A.id===i):null;return{activeId:i,activeField:w,handleDragStart:m,handleDragEnd:g}}function wo({activeView:t,onViewChange:n,splitViewEnabled:a}){const r=s.useEditorStore(c=>c.card),{config:i}=C.useContext(s.SemaphorContext).tokenProps,d=(i==null?void 0:i.showInfoTab)!==!1,o=()=>a?!1:!["table","pivotTable","aggregateTable","detailTable"].includes(r.type);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"}),o()&&e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),r.type!=="kpi"&&d&&e.jsx(s.TabsTrigger,{value:"info",className:"rounded-md transition data-[state=active]:bg-muted",children:"Info"})]})})}const To=[{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 Eo(){var l,x;const t=s.useEditorStore(p=>p.card),{updateRowLimit:n}=s.useEditorActions(),[a,r]=C.useState(!1),[i,d]=C.useState(""),o=p=>{if(p==="custom"){r(!0);return}r(!1),n(t.id,parseInt(p))},c=p=>{const h=p.target.value;d(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:i,onChange:c,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((x=(l=t.config)==null?void 0:l.rowLimit)==null?void 0:x.toString())||"100",onValueChange:o,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:To.map(p=>e.jsx(s.SelectItem,{value:p.value,children:p.label},p.value))})]})})}function Io({card:t,queryData:n,isLoading:a,isFetching:r,pagination:i,onPaginationChange:d,onSortChange:o,sortState:c,splitViewEnabled:l}){const x=C.useMemo(()=>(n==null?void 0:n.records)||[],[n==null?void 0:n.records]);return!l||["table","pivotTable","aggregateTable","detailTable"].includes(t.type)?e.jsx(rt,{}):e.jsxs(s.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(s.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:e.jsx(rt,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{defaultSize:40,minSize:20,role:"results-section",className:"flex flex-col",children:e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 py-4 pl-2 pr-4",children:[(a||r)&&(n==null?void 0:n.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),(n==null?void 0:n.records)&&e.jsx(s.TableVisual,{card:t,data:x,paginationMetadata:i,onPaginationChange:d,isLoading:a||r,onSortChange:o,sortState:c})]})})]})}const ko="semaphor-split-view-enabled";function Do(){return Ta(ko,!0)}function Ao({activeView:t,onViewChange:n,onFiltersClick:a,activeCard:r,columns:i}){var z,W,le;const d=s.useEditorStore(X=>X.card),o=s.useDashboardStore(X=>X.filterValues),c=s.useDashboardStore(X=>X.selectedSheetId),l=s.useDashboardStore(X=>X.inlineFilterValuesMap[(r==null?void 0:r.id)||""]),{updateCardConfig:x,setCard:p,updateCardInFrame:h,setShowAIDialog:u}=s.useEditorActions(),y=s.useEditorStore(X=>X.showAIDialog),b=s.useEditorStore(X=>X.isDevMode),m=s.useDashboardStore(X=>X.isVisualEditing),[g,w]=C.useState(!1),[E,V]=C.useState(!1),[A,T]=C.useState(null),{config:v}=C.useContext(s.SemaphorContext).tokenProps,D=(v==null?void 0:v.showInfoTab)!==!1,M=(v==null?void 0:v.showQueryDebugTools)!==!1,[f,I]=Do();s.useEditorStore(X=>{var ne;return!!((ne=X.card.customCardPreferences)!=null&&ne.url)});const{data:j,errorMessage:k,isLoading:R,isFetching:P,errorSql:N,pagination:L,refetch:S,comparisonMetadata:F,queryRequestPayload:O}=s.useDashboardCardQuery(r),_=C.useMemo(()=>(j==null?void 0:j.records)||[],[j==null?void 0:j.records]),[Q,B]=C.useState(!1);C.useEffect(()=>{P||B(!1)},[P]);const K=()=>{const X=!f;X&&t==="table"&&n("chart"),I(X)},se=(X,ne)=>{const me={...r,paginationConfig:{page:X+1,pageSize:ne}};p(me),h(me)},H=X=>{if(!d.config)return;const ne=s.sortStateToSortByColumns(X,d.config.metricColumns,d.config.groupByColumns,d.config.detailColumns);x(d.id,{...d.config,sortByColumns:ne})},te=C.useMemo(()=>{var X;return s.sortByColumnsToSortState((X=d.config)==null?void 0:X.sortByColumns)},[(z=d.config)==null?void 0:z.sortByColumns]);return e.jsx("div",{className:s.cn("relative flex w-0 grow flex-col",{"border-l":y&&m}),children:e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-3",children:[e.jsxs("div",{className:"flex items-center gap-2 pl-2 pr-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t==="chart"&&y&&e.jsx("div",{className:"w-[200px]",children:e.jsx(it,{variant:b?"secondary":"ghost"})}),e.jsx(wo,{activeView:t,onViewChange:n,splitViewEnabled:f}),e.jsx(s.FilterInfo,{cardId:r.id,cardFilters:(W=r.config)==null?void 0:W.filters,cardFilterCount:s.getFilterCount(((le=r.config)==null?void 0:le.filters)||null),onFiltersClick:a,inlineFilters:r.inlineFilters,inlineFilterValues:l,sheetId:c||""}),F&&d.type!=="table"&&e.jsx(s.ComparisonMetadataBadge,{metadata:F,variant:"compact"}),e.jsx("div",{className:"ml-2",children:e.jsx(Eo,{})}),y&&e.jsx(Ae.EditorClearButton,{})]}),e.jsxs("div",{className:s.cn("flex grow items-center justify-end gap-2"),children:[e.jsx(s.IconButton,{tooltip:"Refresh",disabled:R||P,onClick:()=>{B(!0),S()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":Q})})}),t==="chart"&&e.jsx(La,{showInlineFilters:!1,showDisplayOptions:!1}),!y&&e.jsx(s.IconButton,{onClick:()=>u(!y),tooltip:"AI",className:"h-8","aria-label":"AI",children:e.jsx(s.Sparkles,{className:"size-4"})}),t==="chart"&&e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"More Options",className:"h-8","aria-label":"More options",children:e.jsx(s.EllipsisVertical,{className:"size-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(s.DropdownMenuLabel,{children:"More Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:K,children:[f?e.jsx(dn,{className:"mr-2 h-4 w-4"}):e.jsx(Sn,{className:"mr-2 h-4 w-4"}),f?"Hide Results Table":"Show Results Table"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"px-1 py-1",children:[e.jsx(dt,{triggerVariant:"menu",className:"w-full"}),e.jsx(ct,{triggerVariant:"menu",className:"w-full"})]})]})]})]})]}),e.jsxs("div",{className:"mt-2 flex min-h-0 grow flex-col",children:[t==="chart"&&e.jsx("div",{className:s.cn("flex grow flex-col pb-4",{"pb-0":f&&!["table","pivotTable","aggregateTable","detailTable"].includes(r.type)}),children:e.jsx(Io,{card:r,queryData:j,isLoading:R,isFetching:P,pagination:L,onPaginationChange:se,onSortChange:H,sortState:te,splitViewEnabled:f})}),t==="table"&&(j==null?void 0:j.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 py-4 pl-2 pr-4",children:[(R||P)&&(j==null?void 0:j.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),e.jsx(s.TableVisual,{card:r,data:_,comparisonMetadata:F,paginationMetadata:L,onPaginationChange:se,isLoading:R||P,onSortChange:H,sortState:te})]}),t==="info"&&D&&e.jsx("div",{className:"flex min-h-0 flex-1 flex-col pb-4",children:e.jsx("div",{className:"flex min-h-0 flex-1 flex-col rounded-md bg-background pl-2 pr-4",children:k?e.jsx(ot,{error:k,errorSql:N,onSendFeedback:()=>{const X=s.prepareFeedbackData(s.FeedbackCategory.QUERY_GENERATION,{cardConfig:d.config,dataSource:r.dataSource,dashboardFilters:o,errorMessage:k,errorSql:N,generatedSql:j==null?void 0:j.sql});T(X),V(!0)},onOpenInEditor:()=>{u(!0),setTimeout(()=>{const X=s.useEditorStore.getState().actions;X.setIsDevMode(!0),X.setCardSql(N||""),setTimeout(()=>{X.setRunSql(!0)},100)},100)}}):(j==null?void 0:j.sql)&&e.jsx(ka,{sql:j.sql,showCardDetails:!0,debugPayloads:M?{queryRequest:O,queryResponse:j,columns:i,dashboardFilters:o}:void 0})})})]}),A&&e.jsx(s.FeedbackDialog,{open:E,onOpenChange:V,feedbackData:A})]})})}function Lo({activeField:t}){const[n,a]=C.useState(!0);return C.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(ut,{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 Mo=()=>{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 i;if((i=r.reason)!=null&&i.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 Oo({column:t,isSelected:n,onSelect:a,availableFields:r,width:i,onWidthChange:d}){var O,_,Q;const o=s.useEditorStore(B=>B.card),{updateCardConfig:c,removeGroupByColumn:l,removeMetricColumn:x,updateFilters:p}=s.useEditorActions(),[h,u]=C.useState(!1),[y,b]=C.useState(!1),m=C.useRef(null),g=C.useCallback(B=>{B.preventDefault(),B.stopPropagation(),b(!0),m.current={startX:B.clientX,startWidth:i||150};const K=H=>{if(!m.current)return;const te=H.clientX-m.current.startX,z=Math.max(80,m.current.startWidth+te);d==null||d(t.id,z)},se=()=>{b(!1),m.current=null,document.removeEventListener("mousemove",K),document.removeEventListener("mouseup",se)};document.addEventListener("mousemove",K),document.addEventListener("mouseup",se)},[i,t.id,d]),w=(O=o==null?void 0:o.config)==null?void 0:O.filters,E=(_=w==null?void 0:w.conditions)==null?void 0:_.some(B=>B.field.name===t.name&&B.field.qualifiedEntityName===t.qualifiedEntityName),V=B=>{B?p(o.id,B):c(o.id,{filters:void 0})},{attributes:A,listeners:T,setNodeRef:v,transform:D,transition:M,isDragging:f}=s.useSortable({id:t.id}),I={transform:s.CSS.Transform.toString(D),transition:M},j=s.getDataType(t.dataType),k=Ro(j),R=()=>{var se;const B=((se=o==null?void 0:o.config)==null?void 0:se.sortByColumns)||[],K=B.findIndex(H=>H.name===t.name);if(K!==-1){const H=[...B];H[K]={...H[K],direction:"asc"},c(o.id,{sortByColumns:H})}else c(o.id,{sortByColumns:[...B,{...t,id:`sort-${t.id}`,role:"sortby",direction:"asc"}]})},P=()=>{var se;const B=((se=o==null?void 0:o.config)==null?void 0:se.sortByColumns)||[],K=B.findIndex(H=>H.name===t.name);if(K!==-1){const H=[...B];H[K]={...H[K],direction:"desc"},c(o.id,{sortByColumns:H})}else c(o.id,{sortByColumns:[...B,{...t,id:`sort-${t.id}`,role:"sortby",direction:"desc"}]})},N=()=>{var se;const B=((se=o==null?void 0:o.config)==null?void 0:se.groupByColumns)||[];if(!B.some(H=>H.name===t.name)){const H={...t,id:`groupby-${t.id}-${Date.now()}`,role:"groupby"};c(o.id,{groupByColumns:[...B,H]})}},L=B=>{var H;const K=((H=o==null?void 0:o.config)==null?void 0:H.metricColumns)||[];if(!K.some(te=>te.name===t.name&&te.aggregate===B)){const te={...t,id:`metric-${t.id}-${B}-${Date.now()}`,label:`${B} of ${t.label||t.name}`,role:"metric",aggregate:B};c(o.id,{metricColumns:[...K,te]})}},S=()=>{t.role==="groupby"?l(o.id,t.id):t.role==="metric"&&x(o.id,t.id)},F={...I,width:i?`${i}px`:void 0,minWidth:i?`${i}px`:"120px"};return e.jsxs("th",{ref:v,style:F,className:s.cn("group relative border-r border-border bg-background px-1 py-0",f&&"opacity-50",n&&"bg-primary/10",y&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...A,...T,className:"cursor-grab p-1 text-muted-foreground opacity-0 transition-opacity hover:text-foreground group-hover:opacity-100 active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-3 w-3"})}),e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsxs("button",{onClick:a,className:s.cn("flex flex-1 items-center justify-between gap-1 rounded px-2 py-2 text-left text-sm font-medium transition-colors hover:bg-muted/50",n&&"bg-primary/10"),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(k,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:t.label||t.name}),t.role==="metric"&&t.aggregate&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",t.aggregate,")"]}),E&&e.jsx(s.Filter,{className:"h-3 w-3 text-primary"})]}),e.jsx(s.ChevronDown,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsxs(s.DropdownMenuContent,{align:"start",className:"w-48",children:[e.jsxs(s.DropdownMenuItem,{onClick:()=>u(!0),children:[e.jsx(s.Filter,{className:s.cn("mr-2 h-4 w-4",E&&"text-primary")}),E?"Edit Filter":"Filter"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:R,children:[e.jsx(ln,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(s.DropdownMenuItem,{onClick:P,children:[e.jsx(rn,{className:"mr-2 h-4 w-4"}),"Sort Z → A"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuSub,{children:[e.jsxs(s.DropdownMenuSubTrigger,{children:[e.jsx(s.Calculator,{className:"mr-2 h-4 w-4"}),"Summarize"]}),e.jsxs(s.DropdownMenuSubContent,{children:[e.jsx(s.DropdownMenuItem,{onClick:()=>L("SUM"),children:"Sum"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("AVG"),children:"Average"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("COUNT"),children:"Count"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("DISTINCT"),children:"Count Distinct"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("MIN"),children:"Min"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("MAX"),children:"Max"})]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:N,children:[e.jsx(Fs,{className:"mr-2 h-4 w-4"}),"Group by this column"]}),e.jsxs(s.DropdownMenuItem,{disabled:!0,children:[e.jsx(lt,{className:"mr-2 h-4 w-4"}),"Pivot by this column"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{disabled:!0,children:[e.jsx(s.EyeOff,{className:"mr-2 h-4 w-4"}),"Hide column"]}),e.jsxs(s.DropdownMenuItem,{onClick:S,className:"text-destructive focus:text-destructive",children:[e.jsx(s.Trash2,{className:"mr-2 h-4 w-4"}),"Remove column"]})]})]})]}),e.jsx("div",{onMouseDown:g,className:s.cn("absolute right-0 top-0 h-full w-1 cursor-col-resize bg-transparent hover:bg-primary/50",y&&"bg-primary")}),e.jsx(Ba,{open:h,onOpenChange:u,availableFields:r.length>0?r:[t],existingFilters:w,editingCondition:E?(Q=w==null?void 0:w.conditions)==null?void 0:Q.find(B=>B.field.name===t.name&&B.field.qualifiedEntityName===t.qualifiedEntityName):void 0,onSave:V})]})}function Ro(t){switch(t){case"number":return s.Hash;case"date":return s.Calendar;case"string":default:return s.Type}}function Fo({selectedColumn:t,onColumnSelect:n,isLoading:a=!1,sourceFields:r=[]}){var M,f,I,j;const i=s.useEditorStore(k=>k.card),{updateCardConfig:d}=s.useEditorActions(),[o,c]=C.useState(null),[l,x]=C.useState({}),[p,h]=C.useState(!1),u=C.useMemo(()=>{var P,N;const k=((P=i==null?void 0:i.config)==null?void 0:P.groupByColumns)||[],R=((N=i==null?void 0:i.config)==null?void 0:N.metricColumns)||[];return[...k,...R]},[(M=i==null?void 0:i.config)==null?void 0:M.groupByColumns,(f=i==null?void 0:i.config)==null?void 0:f.metricColumns]),y=C.useMemo(()=>{const k=new Set(u.map(R=>`${R.qualifiedEntityName}.${R.name}`));return r.filter(R=>!k.has(`${R.qualifiedEntityName}.${R.name}`))},[r,u]),{data:b,isLoading:m}=s.useDashboardCardQuery(i),g=(b==null?void 0:b.records)||[],w=C.useCallback((k,R)=>{x(P=>({...P,[k]:R}))},[]),E=C.useCallback(k=>{var L,S;const R=s.getDataType(k.dataType),P=((L=i==null?void 0:i.config)==null?void 0:L.groupByColumns)||[],N=((S=i==null?void 0:i.config)==null?void 0:S.metricColumns)||[];if(R==="number"){const F={...k,id:`metric-${k.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};d(i.id,{metricColumns:[...N,F]})}else{const F={...k,id:`groupby-${k.id}-${Date.now()}`,role:"groupby"};d(i.id,{groupByColumns:[...P,F]})}h(!1)},[(I=i==null?void 0:i.config)==null?void 0:I.groupByColumns,(j=i==null?void 0:i.config)==null?void 0:j.metricColumns,i.id,d]),V=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),A=k=>{c(k.active.id)},T=k=>{const{active:R,over:P}=k;if(c(null),!P||R.id===P.id)return;const N=u.findIndex(S=>S.id===R.id),L=u.findIndex(S=>S.id===P.id);if(N!==-1&&L!==-1){const S=s.arrayMove(u,N,L),F=S.filter(_=>_.role==="groupby"),O=S.filter(_=>_.role==="metric");d(i.id,{groupByColumns:F,metricColumns:O})}},v=o?u.find(k=>k.id===o):null,D=k=>{let R="";for(;k>=0;)R=String.fromCharCode(k%26+65)+R,k=Math.floor(k/26)-1;return R};return a?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):u.length===0?e.jsx("div",{className:"flex h-full flex-col items-center justify-center gap-4 p-8 text-center",children:e.jsxs("div",{className:"rounded-lg border-2 border-dashed border-muted-foreground/25 p-12",children:[e.jsx("h3",{className:"text-lg font-medium text-muted-foreground",children:"No columns selected"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground/75",children:"Select columns from the panel on the right to build your table"})]})}):e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsxs(s.DndContext,{sensors:V,collisionDetection:s.closestCenter,onDragStart:A,onDragEnd:T,children:[e.jsxs("table",{className:"w-full border-collapse",children:[e.jsxs("thead",{children:[e.jsxs("tr",{className:"border-b border-border bg-muted/30",children:[e.jsx("th",{className:"sticky left-0 z-20 w-12 border-r border-border bg-muted/50 px-2 py-1 text-center text-xs font-medium text-muted-foreground"}),e.jsx(s.SortableContext,{items:u.map(k=>k.id),strategy:s.horizontalListSortingStrategy,children:u.map((k,R)=>e.jsx("th",{style:{width:l[k.id]?`${l[k.id]}px`:void 0,minWidth:l[k.id]?`${l[k.id]}px`:"120px"},className:"border-r border-border bg-muted/30 px-2 py-1 text-center text-xs font-medium text-muted-foreground",children:D(R)},`letter-${k.id}`))}),e.jsx("th",{className:"w-10 border-r border-border bg-muted/30 px-2 py-1"})]}),e.jsxs("tr",{className:"border-b-2 border-border bg-background",children:[e.jsx("th",{className:"sticky left-0 z-20 w-12 border-r border-border bg-muted/50 px-2 py-2 text-center text-xs font-medium text-muted-foreground",children:"#"}),e.jsx(s.SortableContext,{items:u.map(k=>k.id),strategy:s.horizontalListSortingStrategy,children:u.map(k=>e.jsx(Oo,{column:k,isSelected:(t==null?void 0:t.id)===k.id,onSelect:()=>n(k),availableFields:r,width:l[k.id],onWidthChange:w},k.id))}),e.jsx("th",{className:"w-10 border-r border-border bg-background px-1 py-2",children:e.jsxs(s.Popover,{open:p,onOpenChange:h,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Add column",children:e.jsx(s.Plus,{className:"h-4 w-4"})})}),e.jsx(s.PopoverContent,{className:"w-[280px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search columns..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No columns available."}),e.jsx(s.CommandGroup,{heading:"Available Columns",children:y.map(k=>{const R=s.getDataType(k.dataType),P=R==="number"?s.Hash:R==="date"?s.Calendar:s.Type;return e.jsxs(s.CommandItem,{value:k.label||k.name,onSelect:()=>E(k),children:[e.jsx(P,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm",children:k.label||k.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:k.entityName})]})]},k.id)})})]})]})})]})})]})]}),e.jsx("tbody",{children:m?e.jsx("tr",{children:e.jsx("td",{colSpan:u.length+2,className:"h-32 text-center",children:e.jsx(s.LoaderCircle,{className:"mx-auto h-6 w-6 animate-spin text-muted-foreground"})})}):g.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:u.length+2,className:"h-32 text-center text-muted-foreground",children:"No data available"})}):g.slice(0,100).map((k,R)=>e.jsxs("tr",{className:s.cn("border-b border-border transition-colors hover:bg-muted/50",R%2===0?"bg-background":"bg-muted/20"),children:[e.jsx("td",{className:"sticky left-0 z-10 w-12 border-r border-border bg-muted/50 px-2 py-2 text-center text-xs font-medium text-muted-foreground",children:R+1}),u.map(P=>{const N=k[P.name]??k[P.label??""];return e.jsx("td",{style:{width:l[P.id]?`${l[P.id]}px`:void 0,minWidth:l[P.id]?`${l[P.id]}px`:"120px"},className:s.cn("border-r border-border px-3 py-2 text-sm",(t==null?void 0:t.id)===P.id&&"bg-primary/5"),children:e.jsx("span",{className:"block truncate",children:Po(N,P)})},`${R}-${P.id}`)}),e.jsx("td",{className:"w-10 border-r border-border"})]},R))})]}),e.jsx(s.DragOverlay,{children:v&&e.jsx("div",{className:"rounded border border-primary bg-background px-3 py-2 text-sm font-medium shadow-lg",children:v.label||v.name})})]})}),e.jsxs("div",{className:"flex items-center justify-between border-t border-border bg-muted/30 px-4 py-2 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Showing ",Math.min(g.length,100)," of ",g.length," rows"]}),e.jsxs("span",{children:[u.length," columns"]})]})]})}function Po(t,n){if(t==null)return"—";if(typeof t=="number")return n.role==="metric"?new Intl.NumberFormat("en-US",{minimumFractionDigits:0,maximumFractionDigits:2}).format(t):t.toString();if(t instanceof Date||typeof t=="string"&&!isNaN(Date.parse(t))){const a=new Date(t);if(!isNaN(a.getTime()))return a.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}return String(t)}function Vo({entityGroups:t,isLoading:n=!1}){var V,A;const a=s.useEditorStore(T=>T.card),{updateCardConfig:r,removeGroupByColumn:i,removeMetricColumn:d}=s.useEditorActions(),[o,c]=C.useState(!0),[l,x]=C.useState(""),[p,h]=C.useState(new Set),u=((V=a==null?void 0:a.config)==null?void 0:V.groupByColumns)||[],y=((A=a==null?void 0:a.config)==null?void 0:A.metricColumns)||[],b=T=>{const v=new Set(p);v.has(T)?v.delete(T):v.add(T),h(v)},m=T=>u.some(v=>v.name===T.name&&v.qualifiedEntityName===T.qualifiedEntityName)||y.some(v=>v.name===T.name&&v.qualifiedEntityName===T.qualifiedEntityName),g=(T,v)=>{if(v)if(s.getDataType(T.dataType)==="number"){const M={...T,id:`metric-${T.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};r(a.id,{metricColumns:[...y,M]})}else{const M={...T,id:`groupby-${T.id}-${Date.now()}`,role:"groupby"};r(a.id,{groupByColumns:[...u,M]})}else{const D=u.findIndex(f=>f.name===T.name&&f.qualifiedEntityName===T.qualifiedEntityName),M=y.findIndex(f=>f.name===T.name&&f.qualifiedEntityName===T.qualifiedEntityName);D!==-1&&i(a.id,u[D].id),M!==-1&&d(a.id,y[M].id)}},w=T=>{if(!l)return T;const v=l.toLowerCase();return T.filter(D=>D.name.toLowerCase().includes(v)||D.label&&D.label.toLowerCase().includes(v))},E=T=>{switch(s.getDataType(T)){case"number":return s.Hash;case"date":return s.Calendar;default:return s.Type}};return o?e.jsxs("div",{className:"flex h-full w-72 flex-col border-l border-border bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border px-3 py-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Columns"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:()=>c(!1),title:"Close panel",children:e.jsx(gn,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"border-b border-border p-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search columns...",value:l,onChange:T=>x(T.target.value),className:"h-8 pl-8 text-sm"})]})}),(u.length>0||y.length>0)&&e.jsxs("div",{className:"border-b border-border",children:[u.length>0&&e.jsxs(s.Collapsible,{defaultOpen:!0,children:[e.jsxs(s.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(s.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(Fs,{className:"h-3.5 w-3.5 text-blue-500"}),e.jsx("span",{children:"Groupings"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:u.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:u.map(T=>{const v=E(T.dataType);return e.jsxs("div",{className:"group flex items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted/50",children:[e.jsx(s.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(v,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:T.label||T.name}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>i(a.id,T.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},T.id)})})})]}),y.length>0&&e.jsxs(s.Collapsible,{defaultOpen:!0,children:[e.jsxs(s.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(s.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(s.Calculator,{className:"h-3.5 w-3.5 text-green-500"}),e.jsx("span",{children:"Metrics"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:y.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:y.map(T=>{const v=E(T.dataType);return e.jsxs("div",{className:"group flex items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted/50",children:[e.jsx(s.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(v,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:T.label||T.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:T.aggregate}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>d(a.id,T.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},T.id)})})})]})]}),e.jsx(s.ScrollArea,{className:"flex-1",children:e.jsx("div",{className:"p-2",children:n?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent"})}):t.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No columns available"}):t.map(T=>{const v=w(T.columns);if(v.length===0)return null;const D=p.has(T.entityId)||l.length>0;return e.jsxs(s.Collapsible,{open:D,onOpenChange:()=>b(T.entityId),children:[e.jsxs(s.CollapsibleTrigger,{className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm font-medium hover:bg-muted/50",children:[e.jsx(s.ChevronRight,{className:s.cn("h-3.5 w-3.5 transition-transform duration-200",D&&"rotate-90")}),e.jsx(s.Table2,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate text-left",children:T.label||T.entityName}),e.jsx("span",{className:"text-xs text-muted-foreground",children:v.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:v.map(M=>{const f=E(M.dataType),I=m(M);return e.jsxs("label",{className:s.cn("flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-sm transition-colors hover:bg-muted/50",I&&"bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:I,onCheckedChange:j=>g(M,j),className:"h-3.5 w-3.5"}),e.jsx(f,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:M.label||M.name})]},M.id)})})})]},T.entityId)})})})]}):e.jsx("div",{className:"flex h-full items-start border-l border-border bg-muted/30 p-2",children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>c(!0),title:"Open panel",children:e.jsx(jn,{className:"h-4 w-4"})})})}const Bo=[{name:"SUM",description:"Sum of values",syntax:"SUM([column])"},{name:"AVG",description:"Average of values",syntax:"AVG([column])"},{name:"COUNT",description:"Count of rows",syntax:"COUNT([column])"},{name:"COUNTD",description:"Count distinct values",syntax:"COUNTD([column])"},{name:"MIN",description:"Minimum value",syntax:"MIN([column])"},{name:"MAX",description:"Maximum value",syntax:"MAX([column])"},{name:"IF",description:"Conditional logic",syntax:"IF(condition, then, else)"},{name:"CASE",description:"Multiple conditions",syntax:"CASE WHEN ... THEN ... END"},{name:"CONCAT",description:"Concatenate text",syntax:"CONCAT([col1], [col2])"},{name:"ROUND",description:"Round number",syntax:"ROUND([column], decimals)"},{name:"FLOOR",description:"Round down",syntax:"FLOOR([column])"},{name:"CEIL",description:"Round up",syntax:"CEIL([column])"},{name:"ABS",description:"Absolute value",syntax:"ABS([column])"},{name:"DATEPART",description:"Extract date part",syntax:"DATEPART(year, [date])"},{name:"DATEDIFF",description:"Difference between dates",syntax:"DATEDIFF(day, [date1], [date2])"}];function zo({value:t,onChange:n,onSubmit:a,onCancel:r,selectedColumn:i,availableColumns:d}){const[o,c]=C.useState(!1),[l,x]=C.useState("column"),p=C.useRef(null);C.useEffect(()=>{const b=m=>{m.key==="Escape"&&t?r():m.key==="Enter"&&t&&!o&&a(t)};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[t,r,a,o]);const h=b=>{const m=`[${b.label||b.name}]`,g=p.current;if(g){const w=g.selectionStart||0,E=g.selectionEnd||0,V=t.slice(0,w)+m+t.slice(E);n(V),setTimeout(()=>{g.setSelectionRange(w+m.length,w+m.length),g.focus()},0)}else n(t+m);c(!1)},u=b=>{const m=p.current;if(m){const g=m.selectionStart||0,w=m.selectionEnd||0,E=t.slice(0,g)+b.syntax+t.slice(w);n(E),setTimeout(()=>{m.setSelectionRange(g+b.name.length+1,g+b.syntax.length-1),m.focus()},0)}else n(t+b.syntax);c(!1)},y=b=>{switch(s.getDataType(b)){case"number":return s.Hash;case"date":return s.Calendar;default:return s.Type}};return e.jsxs("div",{className:"flex items-center gap-2 border-b border-border bg-muted/30 px-3 py-1.5",children:[e.jsx("div",{className:"flex min-w-[100px] items-center justify-center rounded border border-border bg-background px-2 py-1 text-xs font-medium text-muted-foreground",children:i?e.jsx("span",{className:"truncate",children:i.label||i.name}):e.jsx("span",{children:"—"})}),e.jsxs(s.Popover,{open:o&&l==="function",onOpenChange:b=>{c(b),b&&x("function")},children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Insert function",children:e.jsx(Cn,{className:"h-4 w-4"})})}),e.jsx(s.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search functions..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No functions found."}),e.jsx(s.CommandGroup,{heading:"Functions",children:Bo.map(b=>e.jsx(s.CommandItem,{value:b.name,onSelect:()=>u(b),children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-sm font-medium",children:b.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:b.description})]}),e.jsx("span",{className:"font-mono text-xs text-muted-foreground/75",children:b.syntax})]})},b.name))})]})]})})]}),e.jsxs(s.Popover,{open:o&&l==="column",onOpenChange:b=>{c(b),b&&x("column")},children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",className:"h-7 gap-1 px-2 text-xs text-muted-foreground hover:text-foreground",title:"Insert column reference",children:[e.jsx("span",{children:"Columns"}),e.jsx(s.ChevronDown,{className:"h-3 w-3"})]})}),e.jsx(s.PopoverContent,{className:"w-[250px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search columns..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No columns found."}),e.jsx(s.CommandGroup,{heading:"Available Columns",children:d.map(b=>{const m=y(b.dataType);return e.jsxs(s.CommandItem,{value:b.label||b.name,onSelect:()=>h(b),children:[e.jsx(m,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:b.label||b.name})]},b.id)})})]})]})})]}),e.jsx("div",{className:"relative flex-1",children:e.jsx(s.Input,{ref:p,value:t,onChange:b=>n(b.target.value),placeholder:"Enter a formula or select a column...",className:"h-7 border-border bg-background font-mono text-sm"})}),t&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-destructive hover:bg-destructive/10 hover:text-destructive",onClick:r,title:"Cancel (Esc)",children:e.jsx(s.X,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-green-600 hover:bg-green-600/10 hover:text-green-600",onClick:()=>a(t),title:"Apply (Enter)",children:e.jsx(s.Check,{className:"h-4 w-4"})})]})]})}function qo({className:t}){var u,y,b,m;const n=s.useEditorStore(g=>g.card),[a,r]=C.useState(null),[i,d]=C.useState(""),{columns:o=[],columnGroups:c=[],isLoading:l}=s.useColumns();(u=n==null?void 0:n.config)!=null&&u.groupByColumns,(y=n==null?void 0:n.config)!=null&&y.metricColumns,(b=n==null?void 0:n.config)!=null&&b.groupByColumns,(m=n==null?void 0:n.config)!=null&&m.pivotByColumns;const x=g=>{r(g),d(g?`[${g.label||g.name}]`:"")},p=g=>{console.log("Formula submitted:",g),d(""),r(null)},h=()=>{d(""),r(null)};return e.jsxs("div",{className:s.cn("flex h-full w-full flex-col",t),children:[e.jsx(zo,{value:i,onChange:d,onSubmit:p,onCancel:h,selectedColumn:a,availableColumns:o}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(Fo,{selectedColumn:a,onColumnSelect:x,isLoading:l,sourceFields:o})}),e.jsx(Vo,{entityGroups:c,isLoading:l})]})]})}function _o(){var L,S;const[t,n]=C.useState("chart"),[a,r]=C.useState(!1),[i,d]=C.useState(!0),o=s.useEditorStore(F=>F.showAIDialog),c=s.useDashboardStore(F=>F.isVisualEditing),{setCardType:l}=s.useEditorActions(),x=s.useEditorStore(F=>F.card.type);C.useEffect(()=>Mo(),[]);const p=F=>{l(F)},h=s.useEditorStore(F=>F.frame),u=s.useEditorStore(F=>F.card);s.useEditorStore(F=>F.activeTabCardId),s.useEditorStore(F=>F.actions.getAvailableFields);const{addCard:y,removeCard:b,updateCard:m,setActiveCard:g,updateFilters:w}=s.useEditorActions(),{columnFields:E=[],scopedFields:V=[]}=s.useScopedFields(),A=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),T=u,{getFieldsForContainer:v,setFieldsForContainer:D}=s.useFieldManagement(T),{activeField:M,handleDragStart:f,handleDragEnd:I}=So({activeCardId:h.activeCardId,sourceFields:V,getFieldsForContainer:v,setFieldsForContainer:D}),j=(F,O)=>{O&&w(F,O)},k=F=>{var O;m(F,{config:{...(O=h.cards.find(_=>_.id===F))==null?void 0:O.config,filters:void 0}})},R=E,P=F=>{if(!F)return 0;let O=F.conditions.length;return F.groups.forEach(_=>{O+=P(_)}),O},N=P(((L=T==null?void 0:T.config)==null?void 0:L.filters)||null);return e.jsxs(s.DndContext,{sensors:A,collisionDetection:s.closestCenter,onDragStart:f,onDragEnd:I,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Ea,{isVisible:i,onToggleVisibility:()=>d(!i)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:x==="tableBuilder"?e.jsx(qo,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!o&&e.jsx(ro,{selectedChart:x,onChartChange:p,groupByFields:v("groupBy"),pivotByFields:v("pivotBy"),metricsFields:v("metrics"),sortByFields:v("sortBy"),detailFields:v("detailColumns"),activeField:M}),e.jsx(Ao,{selectedChart:x,activeView:t,onViewChange:n,onFiltersClick:()=>r(!0),filterCount:N,activeCard:T,columns:E,getFieldsForContainer:v,cards:h.cards,activeCardId:h.activeCardId,addCard:y,setActiveCard:g})]})}),!i&&c&&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:()=>d(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),T&&e.jsx(Co,{cardId:T.id,filters:((S=T.config)==null?void 0:S.filters)||null,onFiltersChange:j,onClearFilters:k,availableFields:R,isOpen:a,onOpenChange:r}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Lo,{activeField:M||null})})]})}function $o({authToken:t,onSave:n,onClose:a}){const r=C.useRef(null),i=s.useEditorStore(v=>v.showAIDialog),d=s.useEditorStore(v=>v.isDevMode),o=s.useAssistantLayoutStore(v=>v.setFullscreen),c=s.useAssistantLayoutStore(v=>v.setPanelOpen),l=s.useAssistantLayoutStore(v=>v.setContainer),x=s.useAssistantPanel("editor"),p=s.useFullscreenAssistant(),h=s.useAssistantContainer("editor"),u=p==="editor",y=C.useCallback(v=>{l("editor",v)},[l]),{setAuthToken:b}=s.useDashboardActions(),{setShowAIDialog:m,setOnSave:g,setOnClose:w}=s.useEditorActions(),{setActiveAssistantType:E}=s.useAIActions();C.useEffect(()=>{n&&g(n),a&&w(a)},[n,g,a,w]),C.useEffect(()=>{t&&t.accessToken&&b(t)},[t,b]),C.useEffect(()=>{var v,D;i?((v=r.current)==null||v.resize(40),c("editor",!0),E("editor")):((D=r.current)==null||D.resize(0),c("editor",!1),p==="editor"&&o(null),E(null))},[i,c,E,o,p]);function V(v){var D;v<1?(m(!1),c("editor",!1),p==="editor"&&o(null),E(null),(D=r.current)==null||D.resize(0)):(i||(m(!0),E("editor")),x.isOpen||c("editor",!0))}function A(){return e.jsxs(e.Fragment,{children:[e.jsx(Ea,{isVisible:!0,onToggleVisibility:()=>{}}),e.jsxs("div",{className:"relative flex grow",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:s.cn("grow transition-opacity",u&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Vl,{})}),e.jsx(s.ResizableHandle,{disabled:!i}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:V,defaultSize:x.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(ja,{isFullscreen:u,onFullscreenChange:v=>o(v?"editor":null),fullscreenContainer:h})})})]}),e.jsx("div",{ref:y,className:s.cn("absolute inset-0",!u&&"pointer-events-none")})]})]})}function T(){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",u&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(_o,{})}),e.jsx(s.ResizableHandle,{disabled:!i}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:V,defaultSize:x.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(ja,{isFullscreen:u,onFullscreenChange:v=>o(v?"editor":null),fullscreenContainer:h})})})]}),e.jsx("div",{ref:y,className:s.cn("absolute inset-0",!u&&"pointer-events-none")})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:d?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:A()}):T()})}function Go(){s.useDashboardStore(l=>l.selectedCardId);const t=s.useDashboardStore(l=>l.selectedSheetId),n=s.useDashboardStore(l=>l.dashboard),{setIsVisualEditing:a,setSelectedSheetId:r}=s.useDashboardStore(l=>l.actions),i=s.useDashboardStore(l=>l.isVisualEditing),d=s.useDashboardStore(l=>l.actions.updateFrame);function o(l){var u,y,b;const x=t?(u=n==null?void 0:n.sheets)==null?void 0:u.some(m=>{var g;return m.id===t&&((g=m.frames)==null?void 0:g.some(w=>w.id===l.id))}):!1,p=(b=(y=n==null?void 0:n.sheets)==null?void 0:y.find(m=>{var g;return(g=m.frames)==null?void 0:g.some(w=>w.id===l.id)}))==null?void 0:b.id,h=x?t:p||null;h&&(d(h,l),t!==h&&r(h),a(!1))}function c(){a(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!i}),children:e.jsx($o,{onSave:o,onClose:c})})}exports.default=Go;
|