react-semaphor 0.1.271 → 0.1.273
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{dashboard-controls-CXi0Kc8w.js → dashboard-controls-CWk_VHYO.js} +1 -1
- package/dist/chunks/{dashboard-controls-Dfgvs7VL.js → dashboard-controls-DXVPvtdv.js} +4 -4
- package/dist/chunks/{dashboard-filter-controls-button-YHsKcBkN.js → dashboard-filter-controls-button-BwfVbMAn.js} +251 -267
- package/dist/chunks/dashboard-filter-controls-button-CjRyfVQK.js +11 -0
- package/dist/chunks/{dashboard-json-CeiZb0oM.js → dashboard-json-BZQnb-zu.js} +1 -1
- package/dist/chunks/{dashboard-json-BgtFUcgD.js → dashboard-json-DF2gJo97.js} +1 -1
- package/dist/chunks/{dashboard-summary-settings-dialog-CoEmX_jV.js → dashboard-summary-settings-dialog-BpELD3wD.js} +1 -1
- package/dist/chunks/{dashboard-summary-settings-dialog-CuZFi7eP.js → dashboard-summary-settings-dialog-DdwG-S3r.js} +1 -1
- package/dist/chunks/{edit-dashboard-visual-CGYJdPQ8.js → edit-dashboard-visual-0hFfcZi2.js} +6766 -6740
- package/dist/chunks/edit-dashboard-visual-DGPiHVW5.js +193 -0
- package/dist/chunks/index-BOOgwnhm.js +1404 -0
- package/dist/chunks/{index-B9iVxfst.js → index-YLHt8XOf.js} +26260 -25953
- package/dist/chunks/{resource-management-panel-CDPB0Wn6.js → resource-management-panel-B9apTPo3.js} +2 -2
- package/dist/chunks/{resource-management-panel-Cqi9uzkw.js → resource-management-panel-ShFnXy_K.js} +1 -1
- package/dist/chunks/{use-create-flow-overlay-state-4H0O4LVk.js → use-create-flow-overlay-state-DSVyfQTu.js} +2 -2
- package/dist/chunks/{use-create-flow-overlay-state-B5mMajCH.js → use-create-flow-overlay-state-_csxpz3-.js} +1 -1
- package/dist/chunks/{use-visual-utils-S6wmOnYK.js → use-visual-utils-B1ukb8iy.js} +1 -1
- package/dist/chunks/{use-visual-utils-iRJXiZv1.js → use-visual-utils-Ck8d5hcW.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/dashboard.d.ts +7 -1
- package/dist/types/main.d.ts +7 -1
- package/dist/types/shared.d.ts +7 -1
- package/dist/types/surfboard.d.ts +7 -1
- package/dist/types/types.d.ts +7 -1
- package/package.json +1 -1
- package/dist/chunks/dashboard-filter-controls-button-EN4T7uuF.js +0 -11
- package/dist/chunks/edit-dashboard-visual-D8AIf9tr.js +0 -193
- package/dist/chunks/index-Dx42zDJJ.js +0 -1404
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),t=require("./index-BOOgwnhm.js"),N=require("react"),Ae=require("./use-create-flow-overlay-state-_csxpz3-.js"),on=require("react-dom");function cn(s){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const a in s)if(a!=="default"){const r=Object.getOwnPropertyDescriptor(s,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:()=>s[a]})}}return n.default=s,Object.freeze(n)}const Vt=cn(N);/**
|
|
2
|
+
* @license lucide-react v0.453.0 - ISC
|
|
3
|
+
*
|
|
4
|
+
* This source code is licensed under the ISC license.
|
|
5
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
6
|
+
*/const dn=t.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
|
+
* @license lucide-react v0.453.0 - ISC
|
|
8
|
+
*
|
|
9
|
+
* This source code is licensed under the ISC license.
|
|
10
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
11
|
+
*/const un=t.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
|
+
* @license lucide-react v0.453.0 - ISC
|
|
13
|
+
*
|
|
14
|
+
* This source code is licensed under the ISC license.
|
|
15
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
16
|
+
*/const Sa=t.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
|
+
* @license lucide-react v0.453.0 - ISC
|
|
18
|
+
*
|
|
19
|
+
* This source code is licensed under the ISC license.
|
|
20
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
21
|
+
*/const mn=t.createLucideIcon("Bot",[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]]);/**
|
|
22
|
+
* @license lucide-react v0.453.0 - ISC
|
|
23
|
+
*
|
|
24
|
+
* This source code is licensed under the ISC license.
|
|
25
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
26
|
+
*/const xn=t.createLucideIcon("Braces",[["path",{d:"M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1",key:"ezmyqa"}],["path",{d:"M16 21h1a2 2 0 0 0 2-2v-5c0-1.1.9-2 2-2a2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1",key:"e1hn23"}]]);/**
|
|
27
|
+
* @license lucide-react v0.453.0 - ISC
|
|
28
|
+
*
|
|
29
|
+
* This source code is licensed under the ISC license.
|
|
30
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
31
|
+
*/const is=t.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"}]]);/**
|
|
32
|
+
* @license lucide-react v0.453.0 - ISC
|
|
33
|
+
*
|
|
34
|
+
* This source code is licensed under the ISC license.
|
|
35
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
36
|
+
*/const hn=t.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"}]]);/**
|
|
37
|
+
* @license lucide-react v0.453.0 - ISC
|
|
38
|
+
*
|
|
39
|
+
* This source code is licensed under the ISC license.
|
|
40
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
41
|
+
*/const wa=t.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"}]]);/**
|
|
42
|
+
* @license lucide-react v0.453.0 - ISC
|
|
43
|
+
*
|
|
44
|
+
* This source code is licensed under the ISC license.
|
|
45
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
46
|
+
*/const pn=t.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"}]]);/**
|
|
47
|
+
* @license lucide-react v0.453.0 - ISC
|
|
48
|
+
*
|
|
49
|
+
* This source code is licensed under the ISC license.
|
|
50
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
51
|
+
*/const fn=t.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"}]]);/**
|
|
52
|
+
* @license lucide-react v0.453.0 - ISC
|
|
53
|
+
*
|
|
54
|
+
* This source code is licensed under the ISC license.
|
|
55
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
56
|
+
*/const Ta=t.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"}]]);/**
|
|
57
|
+
* @license lucide-react v0.453.0 - ISC
|
|
58
|
+
*
|
|
59
|
+
* This source code is licensed under the ISC license.
|
|
60
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
61
|
+
*/const gn=t.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"}]]);/**
|
|
62
|
+
* @license lucide-react v0.453.0 - ISC
|
|
63
|
+
*
|
|
64
|
+
* This source code is licensed under the ISC license.
|
|
65
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
66
|
+
*/const jn=t.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"}]]);/**
|
|
67
|
+
* @license lucide-react v0.453.0 - ISC
|
|
68
|
+
*
|
|
69
|
+
* This source code is licensed under the ISC license.
|
|
70
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
71
|
+
*/const bn=t.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"}]]);/**
|
|
72
|
+
* @license lucide-react v0.453.0 - ISC
|
|
73
|
+
*
|
|
74
|
+
* This source code is licensed under the ISC license.
|
|
75
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
76
|
+
*/const ea=t.createLucideIcon("ListFilter",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M7 12h10",key:"b7w52i"}],["path",{d:"M10 18h4",key:"1ulq68"}]]);/**
|
|
77
|
+
* @license lucide-react v0.453.0 - ISC
|
|
78
|
+
*
|
|
79
|
+
* This source code is licensed under the ISC license.
|
|
80
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
81
|
+
*/const vn=t.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"}]]);/**
|
|
82
|
+
* @license lucide-react v0.453.0 - ISC
|
|
83
|
+
*
|
|
84
|
+
* This source code is licensed under the ISC license.
|
|
85
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
86
|
+
*/const yn=t.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"}]]);/**
|
|
87
|
+
* @license lucide-react v0.453.0 - ISC
|
|
88
|
+
*
|
|
89
|
+
* This source code is licensed under the ISC license.
|
|
90
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
91
|
+
*/const Yt=t.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"}]]);/**
|
|
92
|
+
* @license lucide-react v0.453.0 - ISC
|
|
93
|
+
*
|
|
94
|
+
* This source code is licensed under the ISC license.
|
|
95
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
96
|
+
*/const Wt=t.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"}]]);/**
|
|
97
|
+
* @license lucide-react v0.453.0 - ISC
|
|
98
|
+
*
|
|
99
|
+
* This source code is licensed under the ISC license.
|
|
100
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
101
|
+
*/const Nn=t.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"}]]);/**
|
|
102
|
+
* @license lucide-react v0.453.0 - ISC
|
|
103
|
+
*
|
|
104
|
+
* This source code is licensed under the ISC license.
|
|
105
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
106
|
+
*/const Cn=t.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"}]]);/**
|
|
107
|
+
* @license lucide-react v0.453.0 - ISC
|
|
108
|
+
*
|
|
109
|
+
* This source code is licensed under the ISC license.
|
|
110
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
111
|
+
*/const Sn=t.createLucideIcon("PanelRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
|
|
112
|
+
* @license lucide-react v0.453.0 - ISC
|
|
113
|
+
*
|
|
114
|
+
* This source code is licensed under the ISC license.
|
|
115
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
116
|
+
*/const ls=t.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"}]]);/**
|
|
117
|
+
* @license lucide-react v0.453.0 - ISC
|
|
118
|
+
*
|
|
119
|
+
* This source code is licensed under the ISC license.
|
|
120
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
121
|
+
*/const qt=t.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"}]]);/**
|
|
122
|
+
* @license lucide-react v0.453.0 - ISC
|
|
123
|
+
*
|
|
124
|
+
* This source code is licensed under the ISC license.
|
|
125
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
126
|
+
*/const wn=t.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"}]]);/**
|
|
127
|
+
* @license lucide-react v0.453.0 - ISC
|
|
128
|
+
*
|
|
129
|
+
* This source code is licensed under the ISC license.
|
|
130
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
131
|
+
*/const Tn=t.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"}]]);/**
|
|
132
|
+
* @license lucide-react v0.453.0 - ISC
|
|
133
|
+
*
|
|
134
|
+
* This source code is licensed under the ISC license.
|
|
135
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
136
|
+
*/const En=t.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"}]]);/**
|
|
137
|
+
* @license lucide-react v0.453.0 - ISC
|
|
138
|
+
*
|
|
139
|
+
* This source code is licensed under the ISC license.
|
|
140
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
141
|
+
*/const In=t.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"}]]);/**
|
|
142
|
+
* @license lucide-react v0.453.0 - ISC
|
|
143
|
+
*
|
|
144
|
+
* This source code is licensed under the ISC license.
|
|
145
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
146
|
+
*/const Dn=t.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"}]]);/**
|
|
147
|
+
* @license lucide-react v0.453.0 - ISC
|
|
148
|
+
*
|
|
149
|
+
* This source code is licensed under the ISC license.
|
|
150
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
151
|
+
*/const kn=t.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"}]]);/**
|
|
152
|
+
* @license lucide-react v0.453.0 - ISC
|
|
153
|
+
*
|
|
154
|
+
* This source code is licensed under the ISC license.
|
|
155
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
156
|
+
*/const An=t.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"}]]);/**
|
|
157
|
+
* @license lucide-react v0.453.0 - ISC
|
|
158
|
+
*
|
|
159
|
+
* This source code is licensed under the ISC license.
|
|
160
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
161
|
+
*/const Mn=t.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 Ea({storeValue:s,defaultValue:n="",onStoreUpdate:a,delay:r=300}){const[d,i]=N.useState(s??n),l=t.useDebounce(d,r),c=N.useRef(s),o=N.useRef(!1);N.useEffect(()=>{s!==c.current&&(i(s??n),c.current=s)},[s,n]),N.useEffect(()=>{o.current&&l!==c.current&&(a(l),c.current=l)},[l,a]);const u=N.useCallback(h=>{o.current=!0,i(h??n)},[n]);return{value:d,onChange:u}}function Ln({initialJoinPlan:s,availableDataSources:n}){const[a,r]=N.useState(s),[d,i]=N.useState(new Set),l=()=>{const S=a.joins.length>0?Math.max(...a.joins.map(D=>D.sequence))+1:1,I={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:S,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...a,joins:[...a.joins,I]}),i(new Set([...d,I.id]))},c=S=>{r({...a,joins:a.joins.filter(I=>I.id!==S)}),i(new Set([...d].filter(I=>I!==S)))},o=(S,I)=>{var y,L,R,f,A;const D=a.joins.find(w=>w.id===S);if(!D)return;const E={...D,...I};if((y=E.source)!=null&&y.name&&((L=E.target)!=null&&L.name)&&E.source.name===E.target.name){t.ue.error("Self-joins are not yet supported",{description:`Joining ${E.source.name} to itself is not currently supported. Please select a different target table.`});return}const b=a.joins.filter(w=>{var P;return w.id!==S&&w.target.name===((P=E.target)==null?void 0:P.name)});if((R=E.target)!=null&&R.name&&b.length>0){t.ue.error("Duplicate join targets are not supported",{description:`The table ${E.target.name} is already used as a target in another join. Each table can only be joined once.`});return}const O=a.joins.map(w=>w.id===S?E:w);if((f=E.source)!=null&&f.name&&((A=E.target)!=null&&A.name)&&E.joinKeyGroups[0].keys.length===0){const w=n.find(_=>{var z;return _.name===((z=E.source)==null?void 0:z.name)}),P=n.find(_=>{var z;return _.name===((z=E.target)==null?void 0:z.name)}),F={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(w==null?void 0:w.name)||"",entityName:(w==null?void 0:w.name)||"",entityType:(w==null?void 0:w.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(P==null?void 0:P.name)||"",entityName:(P==null?void 0:P.name)||"",entityType:(P==null?void 0:P.type)||"table"},operator:"="},B=[...E.joinKeyGroups];B[0]={...B[0],keys:[F]},E.joinKeyGroups=B,O[O.findIndex(_=>_.id===S)]=E}r({...a,joins:O})};return{joinPlan:a,expandedJoins:d,setJoinPlan:r,addJoin:l,removeJoin:c,updateJoin:o,moveJoinUp:S=>{const I=a.joins.findIndex(D=>D.id===S);if(I>0){const D=[...a.joins],E={...D[I]},b={...D[I-1]};D[I]=b,D[I-1]=E,D.forEach((y,L)=>{y.sequence=L+1});const O={...a,joins:D};r(O)}},moveJoinDown:S=>{const I=a.joins.findIndex(D=>D.id===S);if(I<a.joins.length-1){const D=[...a.joins],E={...D[I]},b={...D[I+1]};D[I]=b,D[I+1]=E,D.forEach((y,L)=>{y.sequence=L+1});const O={...a,joins:D};r(O)}},toggleJoinExpansion:S=>{const I=new Set(d);I.has(S)?I.delete(S):I.add(S),i(I)},getAvailableSourceEntities:S=>{if(a.joins.length===0)return n;const I=a.joins.findIndex(E=>E.id===S);if(I===0)return n.filter(E=>E.name===a.baseEntity.name);const D=new Set;return a.baseEntity.name&&D.add(a.baseEntity.name),a.joins.slice(0,I).forEach(E=>{D.add(E.source.name),D.add(E.target.name)}),n.filter(E=>D.has(E.name))},getAvailableTargetEntities:S=>n.filter(I=>I.name!==S),addJoinKeyGroup:S=>{const I=a.joins.find(E=>E.id===S);if(!I)return;const D=[...I.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];o(S,{joinKeyGroups:D})},updateGroupOperator:(S,I,D)=>{const E=a.joins.find(O=>O.id===S);if(!E)return;const b=[...E.joinKeyGroups];b[I]={...b[I],operator:D},o(S,{joinKeyGroups:b})},removeJoinKeyGroup:(S,I)=>{const D=a.joins.find(b=>b.id===S);if(!D)return;const E=[...D.joinKeyGroups];E.splice(I,1),o(S,{joinKeyGroups:E})},addJoinKey:(S,I)=>{const D=a.joins.find(L=>L.id===S);if(!D)return;const E=n.find(L=>L.name===D.source.name),b=n.find(L=>L.name===D.target.name),O=[...D.joinKeyGroups],y={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(E==null?void 0:E.name)||"",entityName:(E==null?void 0:E.name)||"",entityType:(E==null?void 0:E.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(b==null?void 0:b.name)||"",entityName:(b==null?void 0:b.name)||"",entityType:(b==null?void 0:b.type)||"table"},operator:"="};O[I]={...O[I],keys:[...O[I].keys,y]},o(S,{joinKeyGroups:O})},updateJoinKey:(S,I,D,E,b)=>{const O=a.joins.find(A=>A.id===S);if(!O)return;const y=n.find(A=>A.name===O.source.name),L=n.find(A=>A.name===O.target.name),R=[...O.joinKeyGroups],f=R[I].keys[D];E==="sourceColumnName"&&y?R[I].keys[D]={...f,source:{...f.source,name:b}}:E==="targetColumnName"&&L?R[I].keys[D]={...f,target:{...f.target,name:b}}:E==="operator"&&(R[I].keys[D]={...f,operator:b}),o(S,{joinKeyGroups:R})},removeJoinKey:(S,I,D)=>{const E=a.joins.find(O=>O.id===S);if(!E)return;const b=[...E.joinKeyGroups];b[I].keys.splice(D,1),o(S,{joinKeyGroups:b})},generateSQLPreview:()=>{const S=[...a.joins].sort((E,b)=>E.sequence-b.sequence),I=a.baseEntity;if(!I.name)return"SELECT * FROM table -- Please select a base entity";let D=`SELECT *
|
|
162
|
+
FROM ${I.name}`;return S.forEach(E=>{const b=n.find(L=>L.name===E.target.name);if(!b)return;const O=E.joinKeyGroups.filter(L=>L.keys&&L.keys.length>0).map(L=>{const R=L.keys.filter(f=>{var A,w,P,F;return((A=f.source)==null?void 0:A.name)&&((w=f.target)==null?void 0:w.name)&&((P=f.source)==null?void 0:P.entityName)&&((F=f.target)==null?void 0:F.entityName)}).map(f=>`${f.source.entityName}.${f.source.name} ${f.operator} ${f.target.entityName}.${f.target.name}`);return R.length>1?`(${R.join(` ${L.operator} `)})`:R[0]}).filter(Boolean),y=O.length>1?O.join(" OR "):O[0]||"condition_here";D+=`
|
|
163
|
+
${E.joinType} JOIN ${b.name}
|
|
164
|
+
ON ${y}`}),D},isValidConfiguration:()=>!(!a.baseEntity.name||a.joins.some(E=>!E.source.name||!E.target.name)||a.joins.some(E=>E.joinKeyGroups.some(b=>b.keys.length===0))||a.joins.some(E=>E.joinKeyGroups.some(b=>b.keys.some(O=>!O.source.name||!O.target.name||!O.operator))))}}function Fn({joinPlan:s,availableDataSources:n,onSave:a,onRemove:r,onCancel:d}){const{setCardConfig:i}=t.useEditorActions();t.useEditorStore(y=>y.card.config);const{columnGroups:l}=t.useColumns(),c=l.filter(y=>y.entityName!==t.CALCULATED_FIELDS_GROUP_NAME),{joinPlan:o,expandedJoins:u,setJoinPlan:h,addJoin:x,removeJoin:p,updateJoin:m,moveJoinUp:g,moveJoinDown:v,toggleJoinExpansion:j,getAvailableSourceEntities:T,getAvailableTargetEntities:k,addJoinKeyGroup:V,updateGroupOperator:C,removeJoinKeyGroup:M,addJoinKey:S,updateJoinKey:I,removeJoinKey:D,generateSQLPreview:E,isValidConfiguration:b}=Ln({initialJoinPlan:s,availableDataSources:n}),O=y=>{const L=c.find(R=>R.entityName===y);return(L==null?void 0:L.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(t.Select,{value:o.baseEntity.name,onValueChange:y=>{const L=n.find(R=>R.name===y);h({...o,baseEntity:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:y,database:L==null?void 0:L.database,schema:L==null?void 0:L.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(t.SelectContent,{children:n.map(y=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:y.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:y.type}),y.name,e.jsx(t.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},y.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:E()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(t.Label,{children:["Joins Configuration (",o.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:x,children:[e.jsx(t.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),o.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:o.joins.map(y=>{const L=n.find(A=>A.name===y.source.name),R=n.find(A=>A.name===y.target.name),f=u.has(y.id);return e.jsxs(t.Card,{className:"border",children:[e.jsx(t.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(t.Badge,{children:y.sequence}),e.jsxs(t.CardTitle,{className:"text-sm",children:["Join ",y.sequence,L&&R&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",L.name," → ",R.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>g(y.id),disabled:y.sequence===1,children:e.jsx(t.ArrowUp,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>v(y.id),disabled:y.sequence===o.joins.length,children:e.jsx(t.ArrowDown,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>j(y.id),children:f?e.jsx(t.ChevronUp,{className:"h-4 w-4"}):e.jsx(t.ChevronDown,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>p(y.id),children:e.jsx(t.X,{className:"h-4 w-4"})})]})]})}),f&&e.jsxs(t.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(t.Label,{children:"Source"}),e.jsxs(t.Select,{value:y.source.name,onValueChange:A=>{const w=n.find(P=>P.name===A);m(y.id,{source:{connectionId:(w==null?void 0:w.connectionId)||"",connectionType:(w==null?void 0:w.connectionType)||"none",type:(w==null?void 0:w.type)||"table",name:A,database:w==null?void 0:w.database,schema:w==null?void 0:w.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select source..."})}),e.jsx(t.SelectContent,{children:T(y.id).map(A=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:A.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:A.type}),A.name]})},A.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Join Type"}),e.jsxs(t.Select,{value:y.joinType,onValueChange:A=>m(y.id,{joinType:A}),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Target"}),e.jsxs(t.Select,{value:y.target.name,onValueChange:A=>{const w=n.find(P=>P.name===A);m(y.id,{target:{connectionId:(w==null?void 0:w.connectionId)||"",connectionType:(w==null?void 0:w.connectionType)||"none",type:(w==null?void 0:w.type)||"table",name:A,database:w==null?void 0:w.database,schema:w==null?void 0:w.schema}})},disabled:!y.source.name,children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select target..."})}),e.jsx(t.SelectContent,{children:y.source.name?k(y.source.name).map(A=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:A.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:A.type}),A.name,A.name===y.source.name&&e.jsx(t.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},A.name)):[]})]})]})]}),y.source.name&&y.target.name&&L&&R&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{children:"Join Conditions"}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>V(y.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),y.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:y.joinKeyGroups.map((A,w)=>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(t.Label,{children:["Group ",w+1]}),w>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(t.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(t.Select,{value:A.operator,onValueChange:P=>C(y.id,w,P),children:[e.jsx(t.SelectTrigger,{className:"w-[100px]",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>M(y.id,w),children:e.jsx(t.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[A.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:A.keys.map((P,F)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[F>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:A.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:P.source.name,onValueChange:B=>I(y.id,w,F,"sourceColumnName",B),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Source column"})}),e.jsx(t.SelectContent,{children:O(y.source.name).map(B=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:B.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:B.name}),e.jsx(t.Badge,{variant:"outline",className:"ml-2 text-xs",children:B.dataType})]})},B.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(t.Select,{value:P.operator,onValueChange:B=>I(y.id,w,F,"operator",B),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:P.target.name,onValueChange:B=>I(y.id,w,F,"targetColumnName",B),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Target column"})}),e.jsx(t.SelectContent,{children:O(y.target.name).map(B=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:B.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:B.name}),e.jsx(t.Badge,{variant:"outline",className:"ml-2 text-xs",children:B.dataType})]})},B.name))})]})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>D(y.id,w,F),children:e.jsx(t.X,{className:"size-3.5"})})]},P.id||F))}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>S(y.id,w),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},A.id))})]})]})]},y.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>{r(),d()},children:"Remove All"}),e.jsx(t.Button,{variant:"outline",onClick:d,children:"Cancel"}),e.jsx(t.Button,{onClick:()=>a(o),disabled:!b(),children:"Save"})]})]})}function Ia({children:s,open:n,onOpenChange:a,joinPlan:r,availableDataSources:d,onRemove:i,onSave:l,onCancel:c}){return e.jsxs(t.Dialog,{open:n,onOpenChange:a,children:[e.jsxs(t.DialogContent,{className:"max-w-4xl",children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Join Configuration"}),e.jsx(t.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(Fn,{joinPlan:r,availableDataSources:d,onSave:l,onCancel:c,onRemove:i})]}),s]})}function On({joins:s,baseEntityId:n,availableDataSources:a,generateSQLPreview:r}){return e.jsxs("div",{className:"my-2 max-h-[400px] divide-y divide-border overflow-y-auto",children:[s.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 d=[...s].sort((l,c)=>l.sequence-c.sequence),i=a.find(l=>l.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(t.Badge,{variant:"secondary",className:"text-xs",children:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name}),e.jsx(t.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),d.map(l=>{const c=a.find(o=>o.name===l.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(t.Badge,{variant:"outline",className:"text-xs",children:l.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(t.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})]})]},l.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",s.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...s].sort((d,i)=>d.sequence-i.sequence).map((d,i)=>{const l=a.find(u=>u.name===d.source.name),c=a.find(u=>u.name===d.target.name),o=d.joinKeyGroups.reduce((u,h)=>u+h.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(t.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:i+1}),e.jsx(t.Badge,{variant:"outline",className:"shrink-0 text-xs",children:d.joinType}),e.jsxs(t.Badge,{variant:"outline",className:"ml-auto shrink-0 text-xs",children:[o," condition",o>1?"s":""]})]}),e.jsxs("div",{className:"mt-1 truncate pl-1 text-xs text-muted-foreground",children:[l==null?void 0:l.name," → ",c==null?void 0:c.name]})]},d.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 ta({open:s,onOpenChange:n,variant:a="button"}={}){var k,V;const r=t.useEditorStore(C=>C.card),{autoJoinMetadata:d}=t.useDashboardCardQuery(r),i=t.useEditorStore(C=>C.actions.updateCardConfig),l=((k=r==null?void 0:r.config)==null?void 0:k.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[c,o]=N.useState(!1),u=s!==void 0,h=u?s:c,x=u?n:o,p=((V=r==null?void 0:r.dataSource)==null?void 0:V.selectedEntities)||[],m=C=>{i(r.id,{...r==null?void 0:r.config,joinPlan:C}),x(!1)},g=()=>{i(r.id,{...r==null?void 0:r.config,joinPlan:void 0})},v=()=>{x(!1)},j=()=>{const C=[...l.joins].sort((I,D)=>I.sequence-D.sequence),M=l.baseEntity;if(!M.name)return"SELECT * FROM table -- Please select a base entity";let S=`SELECT *
|
|
165
|
+
FROM ${M.name}`;return C.forEach(I=>{const D=p.find(O=>O.name===I.target.name);if(!D)return;const E=I.joinKeyGroups.filter(O=>O.keys&&O.keys.length>0).map(O=>{const y=O.keys.filter(L=>{var R,f,A,w;return((R=L.source)==null?void 0:R.name)&&((f=L.target)==null?void 0:f.name)&&((A=L.source)==null?void 0:A.entityName)&&((w=L.target)==null?void 0:w.entityName)}).map(L=>`${L.source.entityName}.${L.source.name} ${L.operator} ${L.target.entityName}.${L.target.name}`);return y.length>1?`(${y.join(` ${O.operator} `)})`:y[0]}).filter(Boolean),b=E.length>1?E.join(" OR "):E[0]||"condition_here";S+=`
|
|
166
|
+
${I.joinType} JOIN ${D.name}
|
|
167
|
+
ON ${b}`}),S};if(p.length<2)return null;const T=l.joins.length>0&&e.jsx(t.TooltipContent,{side:"bottom",className:"ml-4 max-w-md overflow-hidden p-0",children:e.jsx(On,{joins:l.joins,baseEntityId:l.baseEntity.name,availableDataSources:p,generateSQLPreview:j})});return e.jsxs(e.Fragment,{children:[e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:a==="badge"?e.jsxs(t.Badge,{variant:"secondary",className:"h-5 cursor-pointer gap-1 px-1.5 text-xs transition-colors hover:bg-secondary/80",onClick:C=>{C.stopPropagation(),x(!0)},children:[e.jsx(t.Link,{className:"h-3 w-3"}),l.joins.length]}):e.jsxs(t.Button,{onClick:()=>x(!0),variant:"outline",className:"w-full bg-muted/50",children:[e.jsx(t.Link,{className:"mr-2 h-3.5 w-3.5"}),l.joins.length===0?"Configure Joins":l.joins.length===1?"Join":"Joins",l.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:l.joins.length}),(d==null?void 0:d.autoResolved)&&e.jsxs(t.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(t.Sparkles,{className:"h-3 w-3"}),"Auto"]})]})}),T]})}),e.jsx(Ia,{open:h,onOpenChange:x,joinPlan:l,availableDataSources:p,onSave:m,onCancel:v,onRemove:g,children:e.jsx("div",{})})]})}function Rn({open:s,onOpenChange:n}){const[a,r]=N.useState([]),{updateDataSource:d}=t.useEditorActions(),{selectedEntities:i}=t.useAssistantContextEntities("dashboard");N.useEffect(()=>{s&&r([])},[s]);const l=m=>{r(g=>g.some(j=>t.areContextEntitiesEqual(j,m))?g.filter(j=>!t.areContextEntitiesEqual(j,m)):[...g,m])},c=()=>{r([...i])},o=()=>{r([])},u=()=>{if(a.length===0)return;const m=a[0],g=m.connectionId||"",v=m.connectionType||"",T=a.some(V=>V.type==="dataset")?"semanticDomain":"database";d({connectionId:g,connectionType:v,mode:T,selectedEntities:a}),n(!1)},h=m=>"label"in m&&m.label?m.label:m.name,x=m=>{if("description"in m&&m.description)return m.description;const g=[];return m.database&&g.push(m.database),m.schema&&g.push(m.schema),m.name&&g.push(m.name),g.join(".")},p=m=>a.some(g=>t.areContextEntitiesEqual(g,m));return i.length===0?e.jsx(t.Dialog,{open:s,onOpenChange:n,children:e.jsxs(t.DialogContent,{className:"max-w-md",children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"No Data Available"}),e.jsx(t.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(t.DialogFooter,{children:e.jsx(t.Button,{onClick:()=>n(!1),children:"Close"})})]})}):e.jsx(t.Dialog,{open:s,onOpenChange:n,children:e.jsxs(t.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(t.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(t.Button,{variant:"outline",size:"sm",onClick:c,disabled:a.length===i.length,children:"Select All"}),e.jsx(t.Button,{variant:"outline",size:"sm",onClick:o,disabled:a.length===0,children:"Clear All"})]}),e.jsxs(t.Badge,{variant:"secondary",children:[a.length," of ",i.length," selected"]})]}),e.jsx(t.Separator,{}),e.jsx(t.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:i.map((m,g)=>e.jsxs("div",{className:t.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",p(m)&&"border-primary bg-primary/5"),children:[e.jsx(t.Checkbox,{checked:p(m),onCheckedChange:()=>l(m)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:t.getEntityIcon(m.type)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:h(m)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:x(m)})]}),e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:m.type})]},`${m.type}-${m.name}-${g}`))})})]}),e.jsx(t.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(t.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsxs(t.Button,{onClick:u,disabled:a.length===0,children:["Select"," ",a.length>0?`(${a.length})`:""]})]})})})]})})}function sa({entities:s,title:n}){const{isConsoleMode:a}=t.useDashboardPreferences();return e.jsx(t.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:n??`${s.length} more entities`}),e.jsx("div",{className:"space-y-1",children:s.map((r,d)=>{const i=t.getEntityDetails(r),l=i.find(o=>o.label==="Description"&&o.value),c=i.filter(o=>o.label==="Description"?!1:a?!0:!["Connection","Database","Schema"].includes(o.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:t.getDisplayName(r)}),l&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:l.value})]}),c.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:c.map((o,u)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[o.label,":"]}),e.jsx("span",{className:"font-mono",children:o.value})]},u))})]},`remaining-${r.type}-${r.name}-${d}`)})})]})})}function Da(s,n){const[a,r]=N.useState(()=>{const d=localStorage.getItem(s);return d?JSON.parse(d):n});return N.useEffect(()=>{localStorage.setItem(s,JSON.stringify(a))},[a,s]),[a,r]}function ka({isVisible:s}){var v,j;const n=t.useEditorStore(T=>T.isDevMode);t.useSyncLegacyEditorState();const[a,r]=N.useState(!1),[d,i]=N.useState(!1),[l,c]=Da("semaphor:data-source-collapsed",!1),o=t.useEditorStore(T=>T.card.dataSource),u=t.useEditorStore(T=>{var k,V;return(V=(k=T.card)==null?void 0:k.config)==null?void 0:V.joinPlan}),{updateDataSource:h}=t.useEditorActions(),x=((v=o==null?void 0:o.selectedEntities)==null?void 0:v.length)||0,p=((j=u==null?void 0:u.joins)==null?void 0:j.length)||0,g={...{connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},...o,selectedEntities:(o==null?void 0:o.selectedEntities)||[]};return e.jsxs("div",{className:t.cn("flex shrink-0 flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":s,"min-w-[325px]":s,"w-0":!s,"min-w-0":!s}),children:[x===0&&p===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(t.Button,{className:"w-full bg-background",variant:"outline",onClick:()=>r(!0),children:[e.jsx(t.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:t.cn("flex cursor-pointer items-center justify-between px-1",l?"pb-0":"pb-3"),onClick:()=>c(!l),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:"Data Source"}),l&&e.jsxs("div",{className:"flex items-center gap-1.5",onClick:T=>T.stopPropagation(),children:[x>0&&e.jsx(t.TooltipProvider,{delayDuration:100,children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs(t.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(t.Database,{className:"h-3 w-3"}),x]})}),e.jsx(sa,{entities:g.selectedEntities,title:`${x} selected ${x===1?"entity":"entities"}`})]})}),p>0&&!n&&e.jsx(ta,{variant:"badge"})]})]}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:T=>{T.stopPropagation(),c(!l)},children:l?e.jsx(t.ChevronDown,{className:"h-4 w-4"}):e.jsx(t.ChevronUp,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:t.cn("flex flex-col overflow-hidden transition-all duration-200 ease-in-out",l?"max-h-0 opacity-0":"max-h-96 opacity-100"),children:[e.jsx("div",{className:"px-1",children:e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs(t.Button,{className:"w-full bg-background",variant:"outline",onClick:()=>r(!0),children:[e.jsx(t.Database,{className:"mr-2 h-3.5 w-3.5"}),x===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:x})]})}),e.jsx(sa,{entities:g.selectedEntities,title:`${x} selected ${x===1?"entity":"entities"}`})]})})}),!n&&x>1&&e.jsx("div",{className:"mt-3 px-1",children:e.jsx(ta,{})})]})]})}),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(t.FieldsSection,{})})}),e.jsx(t.DataSourceDialog,{incomingSelectedEntities:(o==null?void 0:o.selectedEntities)||[],dialogMode:"dataSource",open:a,onOpenChange:r,dataSource:g}),e.jsx(Rn,{open:d,onOpenChange:i})]})}function Bn(s){return t.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:[]}]})(s)}function Aa(s){const{theme:n}=t.useTheme(),a=t.useDashboardStore(v=>v.theme),r=t.useEditorStore(v=>v.frame),d=t.useEditorStore(v=>v.card),i=t.useEditorStore(v=>v.activeTabCardId),l=t.Le(),{refetch:c}=t.useDashboardCardQuery(d),{updateCardTab:o,setRunSql:u}=t.useEditorActions(),h=N.useRef(void 0),x=N.useRef({}),p=r.cards.find(v=>v.id===i),m=N.useCallback(()=>{let v="";return s==="python"&&(v=(p==null?void 0:p.python)||t.PYTHON_DEFAULT_CODE),s==="sql"&&(v=(p==null?void 0:p.sql)||""),v},[s,p]);N.useEffect(()=>{if(i&&d.id&&d.id!==i){if(h.current&&l){const v=h.current.getModel();v&&(x.current[d.id]=v);let j=x.current[i];if(!j){const T=m();j=l.editor.createModel(T,s),x.current[i]=j}h.current.setModel(j)}o(i,d),u(!0)}},[i,d,o,l,u,s,m]),N.useEffect(()=>{if(!l)return;const v=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",j=a==="system"?v:a;l.editor.defineTheme("default",{base:j==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":j==="light"?"#ffffff":t.hslStringToHex("240 10% 10%")}}),l.editor.setTheme("default")},[n,a,l]),N.useEffect(()=>{const v=h.current;v&&l&&d&&v.addCommand(l.KeyMod.Shift|l.KeyCode.Enter,function(){return c(),!1})},[l,c,d]);function g(v,j){if(h.current=v,!x.current[d.id]){const T=v.getModel(),k=m();x.current[d.id]=T||(j==null?void 0:j.editor.createModel(k,s))||v.getModel()}v.setModel(x.current[d.id])}return{handleEditorDidMount:g}}const Pn=300;function Vn(){const s=t.useEditorStore(h=>h.card.sql),n=t.useEditorStore(h=>h.sqlGen),{setCardSql:a,setSqlGen:r}=t.useEditorActions(),{handleEditorDidMount:d}=Aa("sql"),i=N.useRef(n);i.current=n;const l=N.useCallback(h=>{a(h)},[a]),{value:c,onChange:o}=Ea({storeValue:s,defaultValue:"",onStoreUpdate:l,delay:Pn});function u(h){o(h),t.isObjectEmpty(i.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(t.Ft,{theme:"default",className:"pt-3",onChange:u,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:d})]})}const zn=300;function _n(){const s=t.useEditorStore(i=>i.card.python),{setCardPython:n}=t.useEditorActions(),{handleEditorDidMount:a}=Aa("python"),{value:r,onChange:d}=Ea({storeValue:s,defaultValue:t.PYTHON_DEFAULT_CODE,onStoreUpdate:n,delay:zn});return e.jsx(t.Ft,{className:"pt-3",theme:"default",onChange:d,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 qn={async writeTextToClipboard(s){return typeof navigator>"u"||!navigator.clipboard?!1:(await navigator.clipboard.writeText(s),!0)}},Bt=50,$n=[{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 aa(s){try{return JSON.stringify(s,null,2)}catch(n){return console.error("Unable to stringify debug payload",n),null}}function ft(s){switch(s){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 Kn(s){if(!s||typeof s!="object")return{value:s};const n=s.records;return!Array.isArray(n)||n.length<=Bt?{value:s}:{value:{...s,records:n.slice(0,Bt),previewMeta:{truncatedRecords:!0,displayedRecords:Bt,totalRecords:n.length}},truncationMessage:`Preview showing first ${Bt} records of ${n.length}. Copy actions include full payload.`}}function Ma({sql:s,showCardDetails:n=!1,debugPayloads:a,className:r}){const[d,i]=N.useState(!1),[l,c]=N.useState(null),o=t.useEditorStore(b=>b.card),u=t.useEditorStore(b=>b.frame),h=t.useEditorStore(b=>b.isDevMode),x=t.useDashboardStore(b=>b.selectedSheetId),p=t.useDashboardStore(b=>{var O;return(O=b.dashboard)==null?void 0:O.id}),{switchEditorMode:m,setRunSql:g}=t.useEditorActions(),v=N.useMemo(()=>({cardId:o.id||null,frameId:u.id||null,sheetId:x||null,dashboardId:p||null}),[o.id,u.id,x,p]),j=N.useMemo(()=>({queryRequest:a==null?void 0:a.queryRequest,queryResponse:a==null?void 0:a.queryResponse,cardConfig:o.config,dataSource:o.dataSource,columns:a==null?void 0:a.columns,dashboardFilters:a==null?void 0:a.dashboardFilters,cardMetadata:v}),[a==null?void 0:a.queryRequest,a==null?void 0:a.queryResponse,a==null?void 0:a.columns,a==null?void 0:a.dashboardFilters,o.config,o.dataSource,v]),T=n&&d&&!!a,k=N.useMemo(()=>[{label:"Card ID",value:o.id||""},{label:"Frame ID",value:u.id||""},{label:"Sheet ID",value:x||""},{label:"Dashboard ID",value:p||""}],[o.id,u.id,x,p]),V=()=>{m("dev",{sqlToLoad:s}),setTimeout(()=>{g(!0)},100)},C=b=>j[b]!==void 0,M=N.useMemo(()=>{if(!l)return null;const b=j[l];if(b===void 0)return null;const O=l==="queryResponse"?Kn(b):{value:b},y=aa(O.value);return y?{target:l,title:ft(l),json:y,truncationMessage:O.truncationMessage}:null},[l,j]),S=M?M.title:"Preview Payload",I=async b=>{const O=j[b];if(O===void 0)return t.ue.error(`No ${ft(b).toLowerCase()} available`),!1;const y=aa(O);if(!y)return t.ue.error(`Unable to serialize ${ft(b).toLowerCase()}`),!1;try{return await qn.writeTextToClipboard(y)?(t.ue.success(`${ft(b)} copied`),!0):(t.ue.error("Clipboard is not available"),!1)}catch(L){return console.error("Failed to copy debug payload",L),t.ue.error(`Unable to copy ${ft(b).toLowerCase()}`),!1}},D=async()=>M?I(M.target):!1,E=b=>{if(j[b]===void 0){t.ue.error(`No ${ft(b).toLowerCase()} available`);return}c(b)};return e.jsxs("div",{className:t.cn("flex min-h-0 flex-1 flex-col",r),children:[!h&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsxs(t.Button,{onClick:V,variant:"secondary",size:"sm",children:[e.jsx(wa,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),n&&e.jsxs(t.Button,{onClick:()=>i(!d),variant:"outline",size:"sm",children:[e.jsx(t.Info,{className:"mr-2 h-4 w-4"}),"Card Details"]})]}),d&&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(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>i(!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:k.map(b=>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:b.label}),e.jsx(t.CopyButton,{text:b.value,className:"h-6 w-6 shrink-0"})]}),e.jsx("code",{title:b.value||"N/A",className:"mt-1 block whitespace-normal break-all font-mono text-xs",children:b.value||"N/A"})]},b.label))}),T&&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(t.DropdownMenu,{children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8","aria-label":"Preview Payload Menu",children:[e.jsx(t.Eye,{className:"mr-1.5 h-3.5 w-3.5"}),S,e.jsx(t.ChevronDown,{className:"ml-1.5 h-3.5 w-3.5"})]})}),e.jsx(t.DropdownMenuContent,{align:"start",className:"w-56",children:$n.map(b=>e.jsx(t.DropdownMenuItem,{disabled:!C(b.target),onSelect:()=>E(b.target),className:t.cn(l===b.target&&"bg-accent"),children:b.label},`preview-${b.target}`))})]})}),M&&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:[M.title," Preview"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(t.CopyButton,{text:M.json,className:"h-6 w-6",ariaLabel:"Copy Payload",onCopy:D}),e.jsxs(t.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"]})]})]}),M.truncationMessage&&e.jsx("p",{className:"text-xs text-muted-foreground",children:M.truncationMessage}),e.jsx("div",{className:"max-h-80 overflow-auto",children:e.jsx(t.CodeHighlighter,{code:M.json,language:"json"})})]})]})]})}),e.jsx("div",{className:"min-h-0 flex-1 overflow-auto",children:e.jsxs("div",{className:"overflow-hidden rounded-xl border border-border/60 bg-gradient-to-b from-background to-muted/[0.18] shadow-sm",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border/50 bg-background/80 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"rounded-md border border-border/60 bg-muted/60 px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.12em] text-muted-foreground",children:"SQL"}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Generated query"})]}),e.jsx("div",{className:"rounded-md border border-border/60 bg-background/85 p-0.5 shadow-sm backdrop-blur-sm",children:e.jsx(t.CopyButton,{text:s,className:"h-6 w-6 px-0 text-muted-foreground/80 hover:text-foreground"})})]}),e.jsx("div",{className:"group relative overflow-auto px-1 py-1 text-xs leading-relaxed text-foreground/80",children:e.jsx(t.CodeHighlighter,{code:s,language:"sql",wrapLongLines:!0})})]})})]})}function Gn(s){const{request:n,mode:a="draft",currentSql:r,selectedTableName:d,selectedSchemaName:i,selectedDatabaseName:l}=s,c=[l?`Database: ${l}`:"",i?`Schema: ${i}`:"",d?`Table: ${d}`:""].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: ${t.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:
|
|
168
|
+
${c.join(`
|
|
169
|
+
`)}`:"",r?a==="refine"?`Current SQL (must refine):
|
|
170
|
+
${r}`:`Current SQL (revise if useful):
|
|
171
|
+
${r}`:"",`User request:
|
|
172
|
+
${n}`].filter(Boolean).join(`
|
|
173
|
+
|
|
174
|
+
`)}function Un(s){const{request:n,failedSql:a,errorMessage:r,errorCode:d,selectedDatabaseName:i,selectedSchemaName:l,selectedTableName:c,contextEntityLabels:o}=s,u=[i?`Database: ${i}`:"",l?`Schema: ${l}`:"",c?`Table: ${c}`:"",o.length>0?`Selected context entities: ${o.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.",u.length>0?`Context:
|
|
175
|
+
${u.join(`
|
|
176
|
+
`)}`:"",`Original user request:
|
|
177
|
+
${n}`,`Previous SQL draft:
|
|
178
|
+
${a}`,`Validation failure${d?` (${d})`:""}:
|
|
179
|
+
${r}`].filter(Boolean).join(`
|
|
180
|
+
|
|
181
|
+
`)}function Hn(s,n){typeof window>"u"||window.dispatchEvent(new CustomEvent("semaphor:inline-query-writer",{detail:{event:s,...n,timestamp:Date.now()}}))}const Xt={runId:0,phase:"idle",attempt:0,activeStep:"",timelineSteps:[],lastValidation:null,finalOutcome:"idle",hasTools:!1};function Qn(s){if(typeof s=="string"&&(s==="SQL_EMPTY"||s==="SQL_PARSE_ERROR"||s==="SQL_MULTI_STATEMENT"||s==="SQL_READ_ONLY_VIOLATION"||s==="SQL_EXPLAIN_ERROR"||s==="SQL_CONNECTION_ERROR"))return s}function na(s){let n=0;for(let a=0;a<s.length;a+=1)n=(n<<5)-n+s.charCodeAt(a),n|=0;return String(n)}function ra(s){return s==="getTableColumns"?"Discovering columns":s==="getDomainRelationships"?"Resolving relationships":s==="getChartSQLSyntax"?"Reviewing SQL syntax":s==="getUserSql"?"Inspecting current query":"Analyzing context"}function Jn(s,n){return s===t.SELF_HEAL_TIMELINE_STEP&&n>0?`${t.SELF_HEAL_TIMELINE_STEP} ${n}/${t.MAX_SELF_HEAL_ATTEMPTS}`:s}function Pt(s){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`${s}-${crypto.randomUUID()}`:`${s}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function la(s){var n;for(let a=s.length-1;a>=0;a-=1){const r=s[a];if(r.role!=="user")continue;const d=(n=r.metadata)==null?void 0:n.inlineRunToken;if(typeof d=="string"&&d.length>0)return d}}function Yn(s){if(!s)return"";const n=s.trim(),a=s.match(/```sql\s*([\s\S]*?)```/i);if(a!=null&&a[1])return a[1].trim();const r=s.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 oa(s){for(let n=s.length-1;n>=0;n-=1){const a=s[n];if(!(a.role!=="assistant"||!Array.isArray(a.parts)))for(let r=a.parts.length-1;r>=0;r-=1){const d=a.parts[r];if((d==null?void 0:d.type)!=="text"||typeof(d==null?void 0:d.text)!="string")continue;const i=Yn(d.text);if(i)return i}}return""}function Wn({currentSql:s,currentPython:n,selectedDatabaseName:a,selectedSchemaName:r,selectedTableName:d,onApplySql:i,onOpenFullAssistant:l}){var Me,mt;const{authToken:c,tokenProps:o}=t.useSemaphorContext(),u=(Me=t.useDashboardQuery().data)==null?void 0:Me.assistantProfileId,h=t.useEditorStore($=>$.isDevMode),x=t.useEditorStore($=>$.selectedConnectionId),p=t.useEditorStore($=>{var H;return(H=$.card.dataSource)==null?void 0:H.selectedEntities}),m=t.useAIInteractionStore($=>$.currentAIContext.selectedEntities),g=m.length,{setCurrentAIContext:v}=t.useAIActions(),[j,T]=N.useState(""),[k,V]=N.useState(""),[C,M]=N.useState(""),[S,I]=N.useState("draft"),[D,E]=N.useState("draft"),[b,O]=N.useState(""),[y,L]=N.useState(!1),[R,f]=N.useState({status:"idle"}),[A,w]=N.useState(Xt),[P,F]=N.useState(!1),[B,_]=N.useState(()=>Pt("inline-query-session")),z=N.useRef(null),G=N.useRef(null),W=N.useRef(null),U=N.useRef(0),Y=N.useRef(0),se=N.useRef(Pt("inline-run-token")),ee=N.useRef(B),ce=N.useRef(new Set),re=N.useRef(new Map),ne=N.useRef(0),xe=N.useRef(""),Z=N.useRef(!1),ge=N.useRef(!1),ae=N.useRef(Xt),ue=N.useRef(!1),Le=N.useRef(null),te=N.useRef(()=>{}),ve=(mt=o.apiServiceUrl)==null?void 0:mt.replace(/\/$/,""),ye=ve?`${ve}/v1/sql/validate`:"/v1/sql/validate",je=N.useCallback($=>{w(H=>{const J=$(H);return ae.current=J,J})},[]),we=N.useCallback(($,H)=>{je(J=>J.runId===$?H(J):J)},[je]),Ee=N.useCallback($=>Y.current===$&&!ce.current.has($),[]),q=N.useCallback(($,H,J)=>{we($,me=>{const pe=me.timelineSteps.includes(H)?me.timelineSteps:[...me.timelineSteps,H];return{...me,phase:(J==null?void 0:J.phase)||me.phase,attempt:typeof(J==null?void 0:J.attempt)=="number"?J.attempt:me.attempt,activeStep:H,timelineSteps:pe,finalOutcome:(J==null?void 0:J.finalOutcome)||me.finalOutcome,hasTools:J!=null&&J.hasTools?!0:me.hasTools}})},[we]),oe=N.useCallback(()=>{const $=Y.current+1,H=Pt("inline-run-token"),J=Pt("inline-query-session");return Y.current=$,se.current=H,ee.current=J,_(J),ce.current=new Set,re.current=new Map,ne.current=0,xe.current="",ue.current=!1,je(()=>({runId:$,phase:"drafting",attempt:0,activeStep:"Drafting SQL",timelineSteps:["Drafting SQL"],lastValidation:null,finalOutcome:"drafting",hasTools:!1})),{runId:$,runToken:H,chatSessionId:J}},[je]),Ne=N.useCallback(()=>{if(Z.current||ge.current||g>0)return;const $=p||[];if($.length===0)return;const H=t.useAIInteractionStore.getState().currentAIContext;v({...H,selectedEntities:$}),ge.current=!0},[g,p,v]),Be=N.useCallback(()=>{Z.current=!0},[]),X=N.useCallback(($,H,J)=>{Hn($,{runId:H,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:A.hasTools,entityCount:g,finalOutcome:(J==null?void 0:J.finalOutcome)||A.finalOutcome})},[g,A.finalOutcome,A.hasTools]),fe=N.useCallback(($,H)=>{const J=W.current;if(!J)return;const me={inlineRunToken:H};J({role:"user",parts:[{type:"text",text:$}],metadata:me},{metadata:me})},[]);N.useEffect(()=>{const $=Le.current;!$||$.sessionId!==B||(Le.current=null,fe($.message,$.runToken))},[B,fe]);const Ce=B,De=N.useCallback(async({toolCall:$})=>{var Ve,Ue,xt,ht,ze,pt;if(Ce!==ee.current)return;const H=String($.toolName||"").trim();if(!H)return;const J=Y.current;if(!Ee(J)){(Ve=G.current)==null||Ve.call(G,{tool:H,toolCallId:$.toolCallId,output:{status:"error",message:"Inline run is no longer active; ignoring tool output."}});return}if(H==="getUserSql"){q(J,ra(H),{hasTools:!0}),X("inline_tool_step",J,{hasTools:!0}),(Ue=G.current)==null||Ue.call(G,{tool:H,toolCallId:$.toolCallId,output:{status:"success",sql:s||"",python:n||""}});return}const me=t.INLINE_BLOCKED_MUTATING_TOOLS.has(H),pe=t.INLINE_ALLOWED_READ_ONLY_TOOLS.has(H);if(me||!pe){(xt=G.current)==null||xt.call(G,{tool:H,toolCallId:$.toolCallId,output:{status:"error",message:"This action is unavailable in inline draft mode. Open Full Assistant for this action."}});return}const he=ra(H);q(J,he,{phase:A.phase==="self-healing"?"self-healing":"drafting",hasTools:!0}),X("inline_tool_step",J,{hasTools:!0});const Oe=((ht=$.input)==null?void 0:ht.sql)??((ze=$.args)==null?void 0:ze.sql);typeof Oe=="string"&&Oe.trim().length>0&&(ue.current=!1,M(Oe.trim())),(pt=G.current)==null||pt.call(G,{tool:H,toolCallId:$.toolCallId,output:{status:"success",message:"Read-only tool result received."}})},[n,s,X,A.phase,Ee,Ce,q]),Se=N.useCallback(({message:$,messages:H})=>{if(Ce!==ee.current)return;const J=la(H);if(!J||J!==se.current)return;const me=Y.current;if(!Ee(me))return;const pe=oa([$])||oa(H);if(pe){ue.current=!1,M(pe.trim());return}ue.current&&ae.current.phase==="self-healing"&&te.current(me)},[Ee,Ce]),Pe=N.useCallback($=>{if(Ce!==ee.current)return;const H=Y.current;Ee(H)&&ue.current&&ae.current.phase==="self-healing"&&te.current(H)},[Ee,Ce]),{setMessages:_e,sendMessage:Ze,addToolResult:We,status:Xe,stop:le,error:Ie,clearError:Fe}=t.useChat({id:B,transport:new t.DefaultChatTransport({api:`${o.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${c==null?void 0:c.accessToken}`}),body:()=>{const $=t.useAIInteractionStore.getState();return{assistantId:"editor-assistant",assistantProfileId:u,isDevMode:h,aiContext:$.currentAIContext,reasoningEffort:$.reasoningEffort,showReasoning:!1}},credentials:"omit",prepareSendMessagesRequest:({messages:$,body:H,requestMetadata:J})=>{const me=J==null?void 0:J.inlineRunToken,pe=la($);return{body:{...H,inlineRunToken:me||pe,messages:t.cleanupIncompleteMessages($)}}}}),onToolCall:De,onFinish:Se,onError:Pe,sendAutomaticallyWhen:t.lastAssistantMessageIsCompleteWithToolCalls});G.current=We,W.current=Ze;const be=!["ready","error"].includes(Xe),Ge=(Ie==null?void 0:Ie.message)||"Unable to generate a SQL draft right now. Try again.",Te=N.useCallback($=>{const H=Y.current,J=ae.current.phase;if(!(J==="drafting"||J==="self-healing"||J==="validating")){$==="stopped"&&be&&le();return}ce.current.add(H),ue.current=!1,U.current+=1,xe.current="",f({status:"idle"}),M(""),Fe(),_e([]),we(H,pe=>({...pe,phase:"idle",activeStep:"",finalOutcome:"cancelled"})),X("inline_self_heal_stopped",H,{finalOutcome:"cancelled"}),(be||$==="stopped")&&le()},[Fe,X,be,_e,le,we]),jt=N.useCallback(async($,H)=>{var me;if(!Ee(H))return null;const J=U.current+1;U.current=J,q(H,"Validating SQL",{phase:"validating"}),f({status:"validating"});try{const pe=await t.postRequestRegular(ye,(c==null?void 0:c.accessToken)||"",{sql:$,connectionId:x||void 0});if(U.current!==J||!Ee(H))return null;if((pe==null?void 0:pe.valid)===!0)return f({status:"valid",message:"SQL validation passed."}),we(H,Ve=>({...Ve,phase:"ready",finalOutcome:"validated",lastValidation:{valid:!0}})),X("inline_draft_validated",H,{finalOutcome:"validated"}),{status:"valid"};const he=Qn(pe==null?void 0:pe.errorCode)||"UNKNOWN",Oe=typeof(pe==null?void 0:pe.error)=="string"&&pe.error||typeof((me=pe==null?void 0:pe.details)==null?void 0:me.error)=="string"&&pe.details.error||"SQL validation failed. Please revise the query draft.";return f({status:"invalid",message:Oe,errorCode:he}),we(H,Ve=>({...Ve,lastValidation:{valid:!1,error:Oe,errorCode:he}})),X("inline_validation_failed",H,{errorCode:he,finalOutcome:"validation_failed"}),{status:"invalid",error:Oe,errorCode:he}}catch(pe){if(U.current!==J||!Ee(H))return null;const he=t.getRequestErrorMessage(pe,"Validation service unavailable. You can still replace and run.");return f({status:"error",message:he,errorCode:"SQL_CONNECTION_ERROR"}),we(H,Oe=>({...Oe,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,X,Ee,x,ye,we,q]),st=N.useCallback(($,H,J,me)=>{let pe=J,he="validation_failed",Oe="Validating SQL";H==="attempt_limit"?(pe=`Couldn't auto-fix after ${t.MAX_SELF_HEAL_ATTEMPTS} attempts. ${J}`,he="self_heal_exhausted",Oe=`Auto-fix stopped (${t.MAX_SELF_HEAL_ATTEMPTS} attempts)`):H==="duplicate"&&(pe=`Auto-fix stopped (repeated validation failure). ${J}`,he="self_heal_duplicate_stopped",Oe="Auto-fix stopped (repeated failure)"),f({status:"invalid",message:pe,errorCode:me}),q($,Oe,{phase:"error",finalOutcome:he}),we($,Ve=>({...Ve,phase:"error",finalOutcome:he,lastValidation:{valid:!1,error:pe,errorCode:me}})),H!=="terminal"&&X("inline_self_heal_stopped",$,{errorCode:me,finalOutcome:he}),ue.current=!1},[X,we,q]),bt=N.useCallback($=>{const H="Auto-fix stopped (no SQL returned). Open Full Assistant to continue.",J="self_heal_no_draft";f({status:"invalid",message:H,errorCode:"UNKNOWN"}),q($,"Auto-fix stopped (no SQL returned)",{phase:"error",finalOutcome:J}),we($,me=>({...me,phase:"error",finalOutcome:J,lastValidation:{valid:!1,error:H,errorCode:"UNKNOWN"}})),X("inline_self_heal_stopped",$,{errorCode:"UNKNOWN",finalOutcome:J}),ue.current=!1},[X,we,q]);te.current=bt,N.useEffect(()=>{const $=C.trim(),H=Y.current;if(!$){if(U.current+=1,xe.current="",ae.current.phase==="error")return;f({status:"idle"});return}if(!Ee(H)||be)return;const J=`${H}:${ne.current}:${na($)}`;if(xe.current===J)return;xe.current=J;let me=!1;return(async()=>{const he=await jt($,H);if(!he||me||!Ee(H)||he.status!=="invalid")return;if(!t.RECOVERABLE_SQL_ERROR_CODES.has(he.errorCode)){st(H,"terminal",he.error,he.errorCode);return}const Oe=`${na($)}::${he.errorCode}`,Ve=(re.current.get(Oe)||0)+1;if(re.current.set(Oe,Ve),Ve>=2){st(H,"duplicate",he.error,he.errorCode);return}if(ne.current>=t.MAX_SELF_HEAL_ATTEMPTS){st(H,"attempt_limit",he.error,he.errorCode);return}const Ue=ne.current+1;ne.current=Ue,q(H,t.SELF_HEAL_TIMELINE_STEP,{phase:"self-healing",attempt:Ue}),X("inline_self_heal_attempt",H,{attemptCount:Ue,errorCode:he.errorCode}),ue.current=!0,Fe(),_e([]),M("");const xt=m.map(ze=>{const pt=ze!=null&&ze.database?`${ze.database}.`:"",Lt=ze!=null&&ze.schema?`${ze.schema}.`:"",Ft=(ze==null?void 0:ze.name)||"unknown";return`${pt}${Lt}${Ft}`}),ht=Un({request:k,failedSql:$,errorMessage:he.error,errorCode:he.errorCode,selectedDatabaseName:a||"",selectedSchemaName:r||"",selectedTableName:d||"",contextEntityLabels:xt});fe(ht,se.current)})(),()=>{me=!0}},[Fe,m,X,be,Ee,k,C,a,r,d,fe,_e,st,q,jt]);const Ye=(s==null?void 0:s.trim())||"",vt=N.useCallback(($="draft")=>{if(be)return;const H=j.trim();if(!H)return;const J=$==="refine"&&Ye?"refine":"draft",me=J==="refine"?Ye:"",pe=Ye,{runId:he,runToken:Oe,chatSessionId:Ve}=oe();X("inline_draft_started",he,{attemptCount:0,hasTools:!1,finalOutcome:"drafting"}),Ne(),Fe(),V(H),M(""),I(J),O(me),L(!1),f({status:"idle"}),U.current+=1,_e([]),F(!0);const Ue=Gn({request:H,mode:J,currentSql:pe,selectedTableName:d||"",selectedSchemaName:r||"",selectedDatabaseName:a||""});Le.current={sessionId:Ve,message:Ue,runToken:Oe}},[oe,Fe,Ye,X,be,j,Ne,a,r,d,_e]),Et=N.useCallback($=>{const H=C.trim();H&&(i(H,$),$||F(!1))},[i,C]),lt=C.trim().length>0,Ut=["valid","invalid","error"].includes(R.status),ot=lt&&Ut,yt=R.status==="invalid",It=R.status==="validating",it=lt&&k.length>0&&k===j.trim(),ct=Ye.length>0,He=j.length>0,dt=it&&S==="draft",ut=it&&S==="refine"&&b===Ye,Ke=D==="refine"&&!ct?"draft":D,Nt=(Ke==="refine"?ut:dt)?"Open composer preview":"Generate composer SQL",Ct=j.trim().length>0||k.trim().length>0||lt||R.status!=="idle"||A.timelineSteps.length>0,Dt=N.useCallback(($="draft")=>{if(be)return;if(($==="refine"?ut:dt)&&!P){Ne(),F(!0);return}vt($)},[dt,ut,vt,be,P,Ne]),kt=N.useCallback(()=>{Ne(),F(!0)},[Ne]),Qt=N.useCallback($=>{Te("cancelled"),T($)},[Te]),Qe=N.useCallback(()=>{be||(Te("cancelled"),ue.current=!1,U.current+=1,xe.current="",ne.current=0,T(""),V(""),M(""),I("draft"),E("draft"),O(""),L(!1),f({status:"idle"}),Fe(),_e([]),je($=>({...Xt,runId:$.runId})))},[Te,Fe,be,_e,je]),At=N.useCallback($=>{$||Te("cancelled"),F($)},[Te]),Mt=A.timelineSteps.findIndex($=>$===A.activeStep),Jt=A.phase==="self-healing"?"Fixing validation issue":A.phase==="validating"?"Validating SQL":A.activeStep||"Drafting SQL",at=R.status==="valid"?{label:"Validation passed",className:"border-emerald-500/30 bg-emerald-500/10 text-emerald-700",detail:R.message}:R.status==="invalid"?{label:"Validation failed",className:"border-destructive/40 bg-destructive/10 text-destructive",detail:R.message}:R.status==="error"?{label:"Validation unavailable",className:"border-border/60 bg-muted/20 text-muted-foreground",detail:R.message}:null;return e.jsxs("div",{ref:z,className:"relative flex h-8 min-w-[320px] flex-1 items-center",children:[e.jsx(t.Input,{value:j,onChange:$=>Qt($.target.value),onFocus:kt,onClick:kt,onKeyDown:$=>{$.key==="Enter"&&($.preventDefault(),Dt(Ke))},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",He?"pr-[60px]":"pr-10"].join(" ")}),e.jsxs(t.Popover,{open:P,onOpenChange:At,children:[e.jsx(t.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:[He&&e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"size-6 p-0",onClick:$=>{$.preventDefault(),Te("cancelled"),T("")},disabled:be,"aria-label":"Clear input",title:"Clear input",children:e.jsx(t.X,{className:"size-3.5"})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"size-6 p-0",onClick:$=>{$.preventDefault(),Dt(Ke)},disabled:be,"aria-label":Nt,title:Nt,children:e.jsx(wn,{className:"size-3.5"})})]}),e.jsx(t.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:$=>{$.preventDefault()},onInteractOutside:$=>{var J;const H=$.target;H&&((J=z.current)!=null&&J.contains(H))&&$.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"}),k&&e.jsx("p",{className:"line-clamp-2 text-xs text-muted-foreground",children:k})]}),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(t.Button,{type:"button",size:"sm",variant:Ke==="draft"?"secondary":"ghost",className:["h-6 rounded-[6px] px-2 text-xs",Ke!=="draft"?"text-muted-foreground hover:text-foreground":""].join(" "),onClick:()=>{E("draft"),L(!1)},children:"Draft New"}),e.jsx(t.Button,{type:"button",size:"sm",variant:Ke==="refine"?"secondary":"ghost",className:["h-6 rounded-[6px] px-2 text-xs",Ke!=="refine"?"text-muted-foreground hover:text-foreground":""].join(" "),onClick:()=>E("refine"),disabled:!ct,children:"Refine Current"})]}),e.jsx("div",{className:"h-4 w-px bg-border/70"}),be&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>{Te("stopped")},children:"Stop"}),!be&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:Qe,disabled:!Ct,children:"Clear"})]})]}),A.timelineSteps.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[A.timelineSteps.map(($,H)=>{const J=$===A.activeStep&&["drafting","validating","self-healing"].includes(A.phase),me=!J&&Mt>=0&&H<Mt;return e.jsx("span",{className:["rounded-full border px-2 py-0.5 text-[11px]",J?"border-foreground/30 bg-foreground/10 text-foreground":me?"border-border/60 bg-muted/20 text-muted-foreground":"border-border/50 bg-background text-muted-foreground/80"].join(" "),children:Jn($,A.attempt)},`${$}-${H}`)}),at&&e.jsx(t.TooltipProvider,{delayDuration:150,children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:["rounded-full border px-2 py-0.5 text-[11px]",at.className].join(" "),children:at.label})}),e.jsx(t.TooltipContent,{side:"top",align:"start",className:"max-w-[680px] whitespace-pre-wrap break-words text-xs",children:at.detail})]})})]}),e.jsx("div",{className:"py-0.5",children:e.jsx(t.AssistantContextEntityControls,{mode:"full",compact:!0,inlineLayout:!0,inlineTriggerFirst:!0,triggerVariant:"outline",triggerIconOnly:!1,triggerLabel:"Context",onSelectionChange:Be})}),(be||A.phase==="self-healing"||R.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(t.LoaderCircle,{className:"size-3.5 animate-spin"}),Jt]}),Ie&&e.jsx("div",{className:"rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-xs text-destructive",children:Ge}),S==="refine"&&b&&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(t.Button,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>L($=>!$),children:y?"Hide base SQL":"View base SQL"})]}),y&&e.jsx("div",{className:"max-h-[120px] overflow-auto rounded-md border border-border/60",children:e.jsx(t.CodeHighlighter,{code:b,language:"sql"})})]}),ot?e.jsxs("div",{className:"space-y-1",children:[S==="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(t.CodeHighlighter,{code:C,language:"sql"})})]}):lt?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."}):!be&&e.jsx("div",{className:"rounded-md border border-dashed border-border/70 px-3 py-2 text-xs text-muted-foreground",children:ct?"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(t.Button,{variant:"outline",size:"sm",className:"h-8",onClick:l,children:"Open Full Assistant"}),e.jsx(t.Button,{variant:"secondary",size:"sm",className:"h-8",disabled:be||!ot,onClick:()=>Et(!1),children:"Replace SQL"}),e.jsx(t.Button,{size:"sm",className:"h-8",disabled:be||!ot||It||yt,onClick:()=>Et(!0),children:"Replace & Run"})]})]})})]})]})}function Xn(){var ne,xe;const s=t.useQueryClient(),[n,a]=N.useState(!1),r=t.useEditorStore(Z=>Z.frame),d=t.useEditorStore(Z=>Z.card);t.useEditorStore(Z=>Z.isShowingVisual),t.useEditorStore(Z=>Z.selectedConnectionId),t.useEditorStore(Z=>Z.tempQueryData);const i=t.useEditorStore(Z=>Z.selectedDatabaseName);t.useEditorStore(Z=>Z.selectedDatamodelId);const l=t.useEditorStore(Z=>Z.selectedSchemaName);t.useEditorStore(Z=>Z.showAIDialog);const c=t.useEditorStore(Z=>Z.selectedTableName),{cardFilterValues:o}=t.useCardFilterValues((d==null?void 0:d.id)??""),u=t.useEditorStore(Z=>Z.inlineFilterValuesMap[(d==null?void 0:d.id)??""]),h=N.useMemo(()=>t.findCustomVisualConfigCard(r,d),[r,d]),{manifest:x}=t.useCustomVisual(((ne=h==null?void 0:h.customCardPreferences)==null?void 0:ne.url)||""),p=N.useMemo(()=>{var Z;return(Z=x==null?void 0:x.visuals)==null?void 0:Z.find(ge=>{var ae;return ge.name===((ae=h==null?void 0:h.customCardPreferences)==null?void 0:ae.componentName)})},[x,(xe=h==null?void 0:h.customCardPreferences)==null?void 0:xe.componentName]),m=t.resolveMultiInputType(h,p),g=N.useMemo(()=>t.getCustomVisualInputCards({frame:r,configCard:h,isMultiInputVisual:m==="multiple"}),[r,h,m]),v=N.useMemo(()=>{const Z=g.findIndex(ge=>(ge==null?void 0:ge.id)===(d==null?void 0:d.id));return Z<0?-1:t.getSlotIndexForCard(d,Z)},[g,d]),j=N.useMemo(()=>!h||m!=="multiple"||v<0?d.type:t.getEffectiveCardTypeForSlot(d,v,p==null?void 0:p.slots)??d.type,[h,m,v,d,p==null?void 0:p.slots]),T=N.useMemo(()=>j!==d.type?{...d,type:j}:d,[d,j]),k=N.useRef(!0),{setCardCustomCfg:V,setQueryResultColumns:C,setCardSql:M,setTempQueryData:S,setPythonStdOut:I,setCardPreferences:D,setCardType:E,setCardPython:b,setShowAIDialog:O,setCard:y,updateCardInFrame:L}=t.useEditorActions();t.useEditorStore(Z=>Z.onSave),t.useEditorStore(Z=>Z.onClose),t.useEditorStore(Z=>Z.actions.setSqlGen);const R=t.useEditorStore(Z=>Z.runSql),f=t.useEditorStore(Z=>Z.actions.setRunSql),A=t.useEditorStore(Z=>Z.actions.setIsSqlRunning),{data:w,isLoading:P,isFetching:F,isSuccess:B,isError:_,error:z,errorSql:G,queryKey:W,refetch:U,errorMessage:Y}=t.useDashboardCardQuery(T);N.useEffect(()=>{if(w&&(w.rowLimitExceeded&&t.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),I((w==null?void 0:w.output)||""),w.records.length>0)){const{dimensionKeys:Z}=t.getKeys(w.records);C(Z)}},[w,C,I]),N.useEffect(()=>{(P||F)&&A(!0),(_||B)&&A(!1),_&&(C([]),I(""))},[P,F,w,I,_,B,A,C,z]),N.useEffect(()=>{R&&(s.getQueryData(W)||U(),f(!1))},[R,U,f,W,s]);const se=N.useRef(U);se.current=U,N.useEffect(()=>{if(k.current){k.current=!1;return}se.current()},[u]);function ee(Z,ge){M(Z),ge&&f(!0)}function ce(){return e.jsxs(t.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(t.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(Vn,{})}),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(t.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(t.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(_n,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function re(){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(t.Button,{title:"Shift + Enter",disabled:P||F,onClick:()=>{U()},className:"h-8 shrink-0",size:"sm",children:[P||F?e.jsx(t.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(t.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),(w==null?void 0:w.sql)&&!Y&&e.jsxs(t.HoverCard,{openDelay:300,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,children:e.jsx(t.Info,{className:"h-4 w-4 shrink-0 cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(t.HoverCardContent,{align:"start",className:"w-[500px] p-0",children:e.jsx(Ma,{sql:w.sql})})]}),e.jsx(Ae.EditorClearButton,{}),e.jsxs(t.Toggle,{pressed:n,onPressedChange:Z=>a(Z),className:"h-8",size:"sm",variant:"outline",children:[e.jsx(Bn,{className:"mr-2 size-4 text-foreground/70"}),"Python"]}),e.jsx(Wn,{currentSql:d==null?void 0:d.sql,currentPython:d==null?void 0:d.python,selectedDatabaseName:i,selectedSchemaName:l,selectedTableName:c,onApplySql:ee,onOpenFullAssistant:()=>O(!0)}),e.jsx("div",{className:"ml-auto flex shrink-0 items-center gap-3",children:o&&o.length>0&&e.jsxs(t.HoverCard,{openDelay:200,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",className:"h-8 gap-2 px-2",children:[e.jsx(t.Filter,{className:"size-4"}),e.jsx(t.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:o.length})]})}),e.jsx(t.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(t.CodeHighlighter,{code:JSON.stringify(o,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:ce()}),re()]})}const Zn=[{value:"table",label:"Table",icon:t.Table2},{value:"aggregateTable",label:"Aggregate",icon:t.Layers},{value:"pivotTable",label:"Pivot",icon:t.Grid3x3},{value:"detailTable",label:"Detail",icon:t.List}];function er({className:s}){const n=t.useEditorStore(x=>x.card),a=t.useEditorStore(x=>x.frame),r=Ae.useEffectiveEditorCardType(),{setCard:d,updateCardInFrame:i}=t.useEditorActions(),l=["table","aggregateTable","pivotTable","detailTable"].includes(r),c=t.hasValidCardConfig(n.config),o=t.isCustomVisualConfigCard(n,a.cards);if(!l||!c||o)return null;const u=x=>{if(o)return;const p=x,m=n.config??{},g=h(r,p,m),v={...n,type:p,config:g};d(v),i(v)},h=(x,p,m)=>{var v;if(p==="detailTable"){const j=C=>C==null?void 0:C.toLowerCase().replace(/\s+/g,"").trim(),T=(C,M)=>{const S=[j(C.label),j(C.qualifiedFieldName),j(C.name)].filter(Boolean),I=[j(M.label),j(M.qualifiedFieldName),j(M.name)].filter(Boolean);return S.some(D=>I.includes(D))},k=(m.groupByColumns||[]).map(C=>({...C,role:"detail"})),V=((v=m.sortByColumns)==null?void 0:v.filter(C=>k.some(M=>T(C,M))))??[];return{...m,detailTableBackup:{groupByColumns:m.groupByColumns,metricColumns:m.metricColumns,pivotByColumns:m.pivotByColumns,sortByColumns:m.sortByColumns,rowAggregates:m.rowAggregates,columnAggregates:m.columnAggregates,comparisonType:m.comparisonType},detailColumns:k,groupByColumns:[],metricColumns:[],pivotByColumns:[],sortByColumns:V,rowAggregates:[],columnAggregates:[],comparisonType:"none"}}let g=m;if(x==="detailTable")if(m.detailTableBackup)g={...m,...m.detailTableBackup,detailColumns:[],detailTableBackup:void 0};else{const j=(m.detailColumns||[]).map(T=>({...T,role:"groupby"}));g={...m,groupByColumns:j,detailColumns:[]}}return p==="aggregateTable"?{...g,pivotByColumns:[]}:g};return e.jsx("div",{className:t.cn("flex items-center",s),children:e.jsx(t.RadioGroup,{value:r,onValueChange:u,className:"flex flex-row items-center gap-1 border-b border-border/60",children:Zn.map(x=>{const p=x.icon,m=r===x.value;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(t.RadioGroupItem,{value:x.value,id:`table-type-${x.value}`,className:"peer sr-only"}),e.jsxs(t.Label,{htmlFor:`table-type-${x.value}`,className:t.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",m?"border-foreground text-foreground":"text-muted-foreground hover:border-foreground/30 hover:text-foreground"),children:[e.jsx(p,{className:t.cn("h-3.5 w-3.5",m?"opacity-100":"opacity-75")}),x.label]})]},x.value)})})})}function cs({error:s,errorSql:n,errorTitle:a="Unable to load data",onOpenInEditor:r,onDebugWithAssistant:d,onSendFeedback:i,showFeedbackButton:l=!0,className:c}){const[o,u]=N.useState(!1);return e.jsx("div",{className:t.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(t.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(t.CopyButton,{text:s,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:s})})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n&&e.jsx(t.Collapsible,{open:o,onOpenChange:u,children:e.jsx(t.CollapsibleTrigger,{asChild:!0,children:e.jsx(t.Button,{variant:"outline",size:"sm",className:"h-8",children:o?e.jsxs(e.Fragment,{children:[e.jsx(t.ChevronUp,{className:"mr-1.5 h-3.5 w-3.5"}),"Hide Details"]}):e.jsxs(e.Fragment,{children:[e.jsx(t.ChevronDown,{className:"mr-1.5 h-3.5 w-3.5"}),"Show Details"]})})})}),r&&n&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8",onClick:r,children:[e.jsx(wa,{className:"mr-1.5 h-3.5 w-3.5"}),"Open in Editor"]}),l&&i&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8",onClick:i,children:[e.jsx(t.MessageSquareWarning,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]}),d&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8",onClick:d,children:[e.jsx(gn,{className:"mr-1.5 h-3.5 w-3.5"}),"Debug with Assistant"]})]}),n&&e.jsx(t.Collapsible,{open:o,onOpenChange:u,children:e.jsx(t.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(t.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(t.CodeHighlighter,{code:n,language:"sql"})})]})})})]})]})})}function La(s,n){const a=t.useEditorStore(u=>u.card),r=t.useEditorStore(u=>u.isDevMode),{switchEditorMode:d,setRunSql:i,runAssistant:l}=t.useEditorActions();return{isDevMode:r,handleOpenInEditor:r?void 0:()=>{const u=n||a.sql||a.python||"";d("dev",{sqlToLoad:u}),setTimeout(()=>{i(!0)},100)},handleDebugWithAssistant:r?()=>{const u=`Can you help me debug this query?
|
|
182
|
+
|
|
183
|
+
Error:
|
|
184
|
+
|
|
185
|
+
${s}
|
|
186
|
+
|
|
187
|
+
Error SQL:
|
|
188
|
+
|
|
189
|
+
${n||a.sql||a.python}
|
|
190
|
+
|
|
191
|
+
`;l(u)}:void 0}}function Fa({className:s,...n}){var Z,ge,ae,ue,Le;const a=t.useEditorStore(te=>te.card);t.useEditorStore(te=>te.isDevMode);const r=((Z=a.customCardPreferences)==null?void 0:Z.showCardHeader)??!0,d=((ae=(ge=a.preferences)==null?void 0:ge.displayOptions)==null?void 0:ae.showInlineFilterBar)??!0,i=t.useEditorStore(te=>te.frame),l=t.useEditorStore(te=>te.inlineFilterValuesMap[a.id]),c=t.useDashboardStore(te=>te.dashboard.filters),o=t.useDashboardStore(te=>te.selectedSheetId),[u,h]=N.useState(!1),{currentUser:x}=t.useCurrentUserInfo(),{tokenProps:p}=N.useContext(t.SemaphorContext),m=t.useEditorStore(te=>te.actions.setRunSql),g=t.useEditorStore(te=>te.actions.setCardInlineFilterValue),v=t.useEditorStore(te=>te.actions.removeCardInlineFilterValue),{updateFilter:j}=t.useDashboardActions(),T=c==null?void 0:c.find(te=>te.id===i.filterId),k=N.useMemo(()=>t.findCustomVisualConfigCard(i,a),[i,a]),{manifest:V}=t.useCustomVisual(((ue=k==null?void 0:k.customCardPreferences)==null?void 0:ue.url)||""),C=N.useMemo(()=>{var te;return(te=V==null?void 0:V.visuals)==null?void 0:te.find(ve=>{var ye;return ve.name===((ye=k==null?void 0:k.customCardPreferences)==null?void 0:ye.componentName)})},[V,(Le=k==null?void 0:k.customCardPreferences)==null?void 0:Le.componentName]),M=t.resolveMultiInputType(k,C),S=N.useMemo(()=>t.getCustomVisualInputCards({frame:i,configCard:k,isMultiInputVisual:M==="multiple"}),[i,k,M]),I=N.useMemo(()=>{const te=S.findIndex(ve=>(ve==null?void 0:ve.id)===(a==null?void 0:a.id));return te<0?-1:t.getSlotIndexForCard(a,te)},[S,a]),D=N.useMemo(()=>!k||M!=="multiple"||I<0?a.type:t.getEffectiveCardTypeForSlot(a,I,C==null?void 0:C.slots)??a.type,[k,M,I,a,C==null?void 0:C.slots]),E=D??a.type,b=N.useMemo(()=>E===a.type?a:{...a,type:E},[a,E]),O=N.useMemo(()=>D!==a.type?{...a,type:D}:a,[a,D]),{data:y,isLoading:L,isFetching:R,errorMessage:f,errorSql:A,pagination:w}=t.useDashboardCardQuery(O),{handleOpenInEditor:P,handleDebugWithAssistant:F}=La(f,A||a.sql||a.python),B=N.useMemo(()=>(y==null?void 0:y.records)||[],[y==null?void 0:y.records]),{setCard:_,updateCardInFrame:z}=t.useEditorActions(),{data:G}=t.useTopoJson(b),W=N.useMemo(()=>{var te;return E!=="pivotTable"||!((te=y==null?void 0:y.records)!=null&&te.length)?null:{records:y.records,columnSubtotalMeta:y.columnSubtotalMeta,subtotalColumns:y.subtotalColumns||[],pivotSchema:y.pivotSchema||[],groupByColumns:y.groupByColumns}},[E,y==null?void 0:y.records,y==null?void 0:y.columnSubtotalMeta,y==null?void 0:y.subtotalColumns,y==null?void 0:y.pivotSchema,y==null?void 0:y.groupByColumns]),U=t.usePivotTableConfig(b,W),Y=()=>{h(!0)},se=N.useMemo(()=>{const te=typeof window<"u"?window.location.href:"",ve=typeof navigator<"u"?navigator.userAgent:"",ye=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:t.FeedbackCategory.QUERY_GENERATION,user:x,tokenContext:p,systemState:{cardConfig:a.config,dataSource:a.dataSource,dashboardFilters:c,errorMessage:f||void 0,errorSql:A||a.sql||a.python,generatedSql:A||a.sql},metadata:{url:te,userAgent:ve,timestamp:new Date().toISOString(),viewport:ye}}},[x,p,a,c,f,A]),ee=(te,ve)=>{var je,we;const ye={...a,paginationConfig:{page:te+1,pageSize:ve}};_(ye),z(ye),a.sql&&((we=(je=a.preferences)==null?void 0:je.tablePrefs)!=null&&we.enableDevModePagination)&&m(!0)},ce=te=>{var je,we,Ee,q,oe;const ve=t.sortStateToSortByColumns(te,(je=a.config)==null?void 0:je.metricColumns,(we=a.config)==null?void 0:we.groupByColumns,(Ee=a.config)==null?void 0:Ee.detailColumns),ye={...a,config:{...a.config||{},sortByColumns:ve}};_(ye),z(ye),a.sql&&((oe=(q=a.preferences)==null?void 0:q.tablePrefs)!=null&&oe.enableDevModePagination)&&m(!0)},re=N.useMemo(()=>!b.id||!(y!=null&&y.records)?null:t.createChartConfig({card:b,data:y==null?void 0:y.records,cardType:E,queryConfig:b.queryConfig,customCfg:b.customCfg,preferences:b.preferences,topoJson:G}),[b,y==null?void 0:y.records,E,G]);function ne(te){return e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackVisual,children:e.jsx(t.EditorCustomVisual,{card:te})})}function xe(){var te;if(y!=null&&y.records&&(y==null?void 0:y.records.length)===0&&!L&&!R)return f?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(cs,{error:f,errorSql:A||a.sql||a.python,onOpenInEditor:P,onDebugWithAssistant:F,onSendFeedback:Y,showFeedbackButton:!0})}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(t.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((L||R)&&(!(y!=null&&y.records)||y.records.length===0))return E==="table"||E==="detailTable"?e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(t.TableSkeleton,{})}):e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!b.id)return null;if(E==="custom")return ne(a);if(!["table","pivotTable","aggregateTable","detailTable","custom"].includes(E)&&re)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:L||R?e.jsx(e.Fragment,{}):e.jsx(t.ChartJsVisual,{cfg:re})});if(E==="table"||E==="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(t.TableVisual,{card:b,data:B,comparisonMetadata:(te=y==null?void 0:y.metadata)==null?void 0:te.comparisonMetadata,paginationMetadata:w,onPaginationChange:ee,onSortChange:ce,isLoading:L||R})});if(E==="pivotTable"&&U)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(t.PivotTableTanstack,{card:b,data:U.data,options:U.options,onAggregationChange:ve=>{const ye=t.handleAggregationChange(ve,a.config),je={...a,config:ye};_(je),z(je)},onAggregationLabelChange:ve=>{const ye=t.handleAggregationLabelChange(ve,a.config),je={...a,config:ye};_(je),z(je)}})});if(E==="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(t.AggregateTable,{card:b,data:(y==null?void 0:y.records)||[],groupByColumns:y==null?void 0:y.groupByColumns,pivotSchema:y==null?void 0:y.pivotSchema,paginationMetadata:w,onPaginationChange:ee,onAggregationChange:ve=>{const ye=t.handleAggregationChange(ve,a.config),je={...a,config:ye};_(je),z(je)},isLoading:L||R})})}return e.jsxs(t.Card,{role:"editor-visual-card",className:t.cn("relative flex h-full flex-col rounded-none",s),...n,children:[(L||R)&&(y==null?void 0:y.records)&&y.records.length>0&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),r&&e.jsxs(t.CardHeader,{className:t.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(t.CardTitle,{className:"text-base",children:e.jsx(t.EditableText,{value:a.title,onSave:te=>_({...a,title:te}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(t.InfoHover,{card:a}),e.jsx(Ae.VisualBadge,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(er,{})})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(t.EditableText,{value:(a.description||"").trim(),onSave:te=>_({...a,description:te.trim()}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),T&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Label,{className:"my-1",children:e.jsx(t.EditableText,{value:T.title||T.column,onSave:te=>j({...T,title:te}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(t.FilterComponent,{filter:T})]})]}),d&&a.inlineFilters&&a.inlineFilters.length>0&&e.jsx("div",{className:t.cn("pb-3 pr-6","pl-2"),children:e.jsx(t.InlineFilterBar,{card:a,sheetId:o||"",inlineFilterValues:l,setInlineFilterValue:te=>g(a.id,te),removeInlineFilterValue:te=>v(a.id,te)})}),e.jsxs(t.CardContent,{className:t.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:xe()}),t.isCardSummaryVisibleOnCard(b)&&e.jsx("div",{className:"pt-3",children:e.jsx(t.CardSummary,{card:b,mode:"editor"})})]}),e.jsx(t.FeedbackDialog,{open:u,onOpenChange:h,feedbackData:se,showDebugInfo:!0})]})}const Zt=({language:s,value:n,onChange:a,readonly:r})=>e.jsx(t.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:s,value:n,onChange:a}),tr=()=>e.jsxs(t.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(t.DialogTitle,{children:"Customize Card"})}),e.jsxs(t.DialogDescription,{children:["See the configuration options and documentation",e.jsx("a",{target:"_blank",className:"ml-1 text-blue-500 underline",href:"https://www.chartjs.org/docs/latest/samples/bar/vertical.html",children:"here."})]})]}),sr=({customCode:s,cardCustomCfgString:n,mergedConfig:a,onConfigChange:r,onCodeChange:d})=>e.jsxs(t.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(t.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(t.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(t.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(t.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(t.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Zt,{language:"json",value:a,onChange:r})}),e.jsx(t.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Zt,{readonly:!0,language:"json",value:n,onChange:()=>{}})}),e.jsx(t.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Zt,{language:"javascript",value:s,onChange:d})})]}),ar=({error:s,hasCardCustomConfig:n,onReset:a,onApply:r,onClose:d})=>e.jsxs(t.DialogFooter,{className:"flex items-center",children:[e.jsx(t.Label,{className:"mr-2 text-red-500",children:s}),e.jsx(t.Button,{disabled:!n,onClick:a,variant:"outline",children:"Reset"}),e.jsx(t.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(t.Button,{onClick:d,variant:"outline",children:"Close"})]});function nr({triggerVariant:s="icon",className:n,label:a="Customize Visual"}={}){const[r,d]=N.useState(!1),[i,l]=N.useState(""),[c,o]=N.useState(""),[u,h]=N.useState(""),[x,p]=N.useState(""),m=t.useEditorStore(b=>b.card),g=Ae.useEffectiveEditorCardType(),v=t.useEditorStore(b=>b.card.customCfg),j=v?JSON.stringify(v,null,2):"",T=N.useMemo(()=>g!==m.type?{...m,type:g}:m,[m,g]),{data:k}=t.useDashboardCardQuery(T),{data:V}=t.useTopoJson(m),{setCardCustomCfg:C,setCustomVisualCode:M}=t.useEditorActions(),S=b=>{var O,y;return JSON.stringify({...b,data:{...b.data,datasets:(y=(O=b.data)==null?void 0:O.datasets)==null?void 0:y.map(L=>({...L,data:[]}))}},null,2)},I=()=>{var O,y;if(!((O=k==null?void 0:k.records)!=null&&O.length))return;const b=t.createChartConfig({card:m,data:k.records,cardType:m.type,queryConfig:m.queryConfig,preferences:m.preferences,topoJson:V});if(b){l(S(b)),h(((y=m.preferences)==null?void 0:y.customVisualCode)||"");const L=t.merge(b,v);o(S(L))}},D=()=>{try{if(u&&M(u),c){const b=JSON.parse(c),O=t.getObjectDiff(JSON.parse(i),b);C(O),p("")}}catch{p("Invalid JSON configuration")}},E=Object.keys(v||{}).length===0;return e.jsxs(t.Dialog,{open:r,onOpenChange:d,children:[e.jsx(t.DialogTrigger,{asChild:!0,children:s==="menu"?e.jsxs(t.Button,{variant:"ghost",onClick:I,className:t.cn("h-8 w-full justify-start gap-2 px-2 text-sm",E?"":"text-green-600 hover:text-green-700",n),children:[e.jsx(t.Settings,{className:"h-4 w-4"}),e.jsx("span",{children:a})]}):e.jsx(t.IconButton,{tooltip:"Customize Visual",onClick:I,className:t.cn(E?"":"text-green-600 hover:text-green-700",n),children:e.jsx(t.Settings,{className:"h-4 w-4"})})}),e.jsxs(t.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(tr,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackVisual,children:e.jsx(Fa,{className:"w-1/2 rounded shadow-none"})}),e.jsx(sr,{customCode:u,cardCustomCfgString:j,mergedConfig:c,onConfigChange:b=>o(b??""),onCodeChange:b=>h(b??"")})]}),e.jsx(ar,{error:x,hasCardCustomConfig:!!v,onReset:()=>{o(i),C(null)},onApply:D,onClose:()=>d(!1)})]})]})}function rr({isStarred:s,onClick:n,className:a}){const r=d=>{d.stopPropagation(),d.preventDefault(),n(d)};return e.jsx("button",{type:"button",onClick:r,className:t.cn("flex items-center justify-center rounded-sm p-0.5 transition-all","hover:bg-muted/80",a),"aria-label":s?"Remove from favorites":"Add to favorites",children:e.jsx(t.Star,{className:t.cn("h-3.5 w-3.5 transition-colors",s?"fill-yellow-400 text-yellow-400":"text-muted-foreground hover:text-foreground")})})}function ia({chartType:s,chartName:n,isCustom:a=!1,pluginName:r,isStarred:d,showStar:i=!0,onSelect:l,onToggleStar:c}){return e.jsxs("div",{className:"group relative",children:[i&&e.jsx("div",{className:t.cn("absolute left-1 top-1 z-10 transition-opacity",d?"opacity-100":"opacity-0 group-hover:opacity-100 group-focus-within:opacity-100"),children:e.jsx(rr,{isStarred:d,onClick:()=>c()})}),a&&r&&e.jsx("div",{className:"absolute right-1 top-1 z-10",children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center justify-center",children:e.jsx(t.Info,{className:"h-3 w-3 text-muted-foreground"})})}),e.jsx(t.TooltipContent,{side:"top",className:"text-xs",children:r})]})}),e.jsxs("button",{type:"button",onClick:l,className:t.cn("flex w-full 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:[e.jsx(t.ChartIcon,{chartType:s,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 ca=[{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 lr({onChartSelect:s,onClose:n}){const[a,r]=N.useState(""),{starredCharts:d,isStarred:i,toggleStar:l}=t.useStarredChartsStore(),{data:c=[],isLoading:o}=t.useCustomVisualsQuery(),{setCardType:u,setCardPreferences:h,setIsDevMode:x}=t.useEditorStore(b=>b.actions),p=t.useEditorStore(b=>b.card),{setCardCustomCfg:m,setCustomCardPreferences:g,setVisualizationMode:v,setQueryConfig:j,replaceFrameCards:T,clearModeDrafts:k,initializeModeDrafts:V}=t.useEditorActions(),C=N.useMemo(()=>{if(!a)return ca;const b=a.toLowerCase();return ca.filter(O=>O.name.toLowerCase().includes(b))},[a]),M=N.useMemo(()=>{const b=c.filter(y=>y.componentType==="chart"&&y.pluginType!=="standard");if(!a)return b;const O=a.toLowerCase();return b.filter(y=>y.name.toLowerCase().includes(O))},[c,a]),S=b=>{m(null),h({}),v("builtin"),u(b),["custom","text","map"].includes(b)&&(x(!0),j(void 0)),s==null||s(b),n==null||n()},I=b=>{m(null),h({}),v("builtin"),j(void 0);const O=t.resolveMultiInputTypeFromVisual(b);if(O==="multiple"&&b.slots&&b.slots.length>0){k();const L=t.createCardsFromSlots(b.slots,b,p);T(L),L[0]&&V(L[0]),n==null||n();return}else u("custom"),g({type:"component",visualType:O,url:b.url,componentName:b.name,icon:b.icon,pluginChartType:b.chartType,minInputs:b.minInputs,maxInputs:b.maxInputs});s==null||s("custom",b),n==null||n()},D=b=>{const O={type:"default",id:b.id,name:b.name};l(O)},E=b=>{const O={type:"custom",id:b.name,url:b.url,icon:b.icon,name:b.name};l(O)};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(t.Search,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(t.Input$1,{placeholder:"Search charts...",value:a,onChange:b=>r(b.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:[C.length>0&&e.jsx("div",{className:"mb-3",children:e.jsx("div",{className:"grid grid-cols-3 gap-2",children:C.map(b=>e.jsx(ia,{chartType:b.id,chartName:b.name,isCustom:!1,isStarred:i("default",b.id),onSelect:()=>S(b.id),onToggleStar:()=>D(b)},b.id))})}),M.length>0&&e.jsxs(e.Fragment,{children:[C.length>0?e.jsx(t.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:M.map((b,O)=>e.jsx(ia,{chartName:b.name,isCustom:!0,pluginName:b.pluginName,isStarred:i("custom",b.name),onSelect:()=>I(b),onToggleStar:()=>E(b)},`${b.url}-${b.name}-${O}`))})]})]}),o&&e.jsxs(e.Fragment,{children:[e.jsx(t.Separator,{className:"my-3"}),e.jsx("div",{className:"py-4 text-center text-sm text-muted-foreground",children:"Loading custom charts..."})]}),C.length===0&&M.length===0&&!o&&e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No charts found"})]})]})}function or({selectedChart:s,onChartChange:n}){var S,I,D,E;const a=t.useEditorStore(b=>b.card),r=t.useEditorStore(b=>b.frame),d=t.useEditorStore(b=>b.isDevMode),{replaceFrameCards:i,clearModeDrafts:l,initializeModeDrafts:c,setIsDevMode:o}=t.useEditorActions(),u=N.useMemo(()=>t.findCustomVisualConfigCard(r,a),[r,a]),{manifest:h}=t.useCustomVisual(((S=u==null?void 0:u.customCardPreferences)==null?void 0:S.url)||""),x=N.useMemo(()=>{var b;return(b=h==null?void 0:h.visuals)==null?void 0:b.find(O=>{var y;return O.name===((y=u==null?void 0:u.customCardPreferences)==null?void 0:y.componentName)})},[h,(I=u==null?void 0:u.customCardPreferences)==null?void 0:I.componentName]),p=t.resolveMultiInputType(u,x)==="multiple",m=Ae.useEffectiveEditorCardType(),g=p?m:s??a.type,v=(D=a==null?void 0:a.customCardPreferences)==null?void 0:D.componentName,j=(E=u==null?void 0:u.customCardPreferences)==null?void 0:E.componentName,T=p&&!!j,k=N.useMemo(()=>{const b=t.chartTypes.find(O=>O.id===g);return b?b.label:g==="custom"?v||"Custom Visual":"Select chart type"},[g,v]),V=N.useMemo(()=>{const b=t.chartTypes.find(O=>O.id===g);if(b){const O=b.icon;return e.jsx(O,{className:"h-4 w-4"})}if(g==="custom"&&v){const O=t.getAutoDetectedChartIcon(v);return O||e.jsx(t.ChartIcon,{chartName:v,isCustom:!0,className:"h-4 w-4"})}return e.jsx(Tn,{className:"h-4 w-4"})},[g,v]);return{displayChartType:g,displayLabel:k,displayIcon:V,showBadge:T,badgeLabel:j,isMultiInputContext:p,handleChartSelect:b=>{n==null||n(b)},handleClearCustomVisual:b=>{b.stopPropagation();const O={...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};i([O]),l(),c(O),d&&o(!0),n==null||n("bar")}}}function ds({selectedChart:s,onChartChange:n,variant:a="ghost",className:r}){const[d,i]=N.useState(!1),{displayLabel:l,displayIcon:c,showBadge:o,badgeLabel:u,handleChartSelect:h,handleClearCustomVisual:x}=or({selectedChart:s,onChartChange:n});return e.jsxs("div",{className:t.cn("relative w-full",r),children:[e.jsxs(t.Popover,{open:d,onOpenChange:i,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{size:"sm",variant:a,role:"combobox","aria-expanded":d,className:t.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:l})]}),e.jsx(t.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-70"})]})}),e.jsx(t.PopoverContent,{className:"w-[360px] p-3",align:"start",onOpenAutoFocus:p=>p.preventDefault(),children:e.jsx(lr,{onChartSelect:p=>h(p),onClose:()=>i(!1)})})]}),o&&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:u,children:[e.jsx(t.Layers,{className:"h-2.5 w-2.5 shrink-0"}),e.jsx("span",{className:"truncate",children:u}),e.jsx("button",{onClick:x,className:"rounded-full p-0.5 hover:bg-muted",title:"Clear custom visual",children:e.jsx(t.X,{className:"h-2.5 w-2.5"})})]})]})}function ir(){const s=t.useEditorStore(o=>{var u,h;return(h=(u=o.card.preferences)==null?void 0:u.chartOptions)==null?void 0:h.indexAxis}),n=t.useEditorStore(o=>o.card.type),{setChartOrientation:a,setCardPreferences:r}=t.useEditorStore(o=>o.actions),d=o=>{if(a(o),n!=="bullet")return;const u=o==="y"?"horizontal":"vertical",h=t.useEditorStore.getState().card.preferences,x={...h||{},bulletConfig:{...(h==null?void 0:h.bulletConfig)||{},orientation:u}};r(x)};function i(){const o=s??"x",u=()=>{d(o==="x"?"y":"x")};return e.jsx(t.IconButton,{onClick:u,tooltip:"Chart Orientation",children:o==="x"?e.jsx(Wt,{className:"size-4"}):e.jsx(Yt,{className:"size-4"})})}function l(){const o=()=>{d(s==="y"||s===void 0?"x":"y")};return e.jsx(t.IconButton,{onClick:o,tooltip:"Chart Orientation",children:s==="y"||s===void 0?e.jsx(Wt,{className:"size-4"}):e.jsx(Yt,{className:"size-4"})})}function c(){const o=s??"y",u=()=>{d(o==="y"?"x":"y")};return e.jsx(t.IconButton,{onClick:u,tooltip:"Chart Orientation",children:o==="y"?e.jsx(Yt,{className:"size-4"}):e.jsx(Wt,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?l():n==="bullet"?c():i()})}function us({className:s,triggerVariant:n="icon",label:a="Display Options"}){var v,j,T,k,V,C,M,S,I,D;const r=t.useEditorStore(E=>E.card),{setCardPreferences:d,updateCardInFrame:i,setCard:l}=t.useEditorActions(),[c,o]=N.useState(!1),u=((j=(v=r.preferences)==null?void 0:v.displayOptions)==null?void 0:j.showFilterInfo)??!0,h=((k=(T=r.preferences)==null?void 0:T.displayOptions)==null?void 0:k.showCardToolbar)??!0,x=((C=(V=r.preferences)==null?void 0:V.displayOptions)==null?void 0:C.showChrome)??!0,p=((S=(M=r.preferences)==null?void 0:M.displayOptions)==null?void 0:S.allowScroll)??!0,m=((D=(I=r.preferences)==null?void 0:I.displayOptions)==null?void 0:D.showInlineFilterBar)??!0,g=(E,b)=>{var L;const O={...r.preferences,displayOptions:{...(L=r.preferences)==null?void 0:L.displayOptions,[E]:b}};d(O);const y={...r,preferences:O};l(y),i(y)};return e.jsx("div",{className:t.cn("flex items-center",s),children:e.jsxs(t.DropdownMenu,{modal:!1,open:c,onOpenChange:o,children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:n==="menu"?e.jsxs(t.Button,{variant:"ghost",className:"h-8 w-full justify-start gap-2 px-2 text-sm",children:[e.jsx(t.SlidersHorizontal,{className:"h-4 w-4"}),e.jsx("span",{children:a})]}):e.jsx(t.IconButton,{className:"h-8 w-8 p-0",tooltip:"Display Options",children:e.jsx(t.SlidersHorizontal,{className:"h-4 w-4"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(t.DropdownMenuLabel,{children:"Display Options"}),e.jsx(t.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(t.DropdownMenuCheckboxItem,{checked:u,onCheckedChange:E=>{g("showFilterInfo",E)},onSelect:E=>E.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Filter Info"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Badge"})]}),e.jsxs(t.DropdownMenuCheckboxItem,{checked:h,onCheckedChange:E=>{g("showCardToolbar",E)},onSelect:E=>E.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Toolbar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Hover actions"})]}),e.jsxs(t.DropdownMenuCheckboxItem,{checked:x,onCheckedChange:E=>{g("showChrome",E)},onSelect:E=>E.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Chrome"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Frame & padding"})]}),e.jsxs(t.DropdownMenuCheckboxItem,{checked:p,onCheckedChange:E=>{g("allowScroll",E)},onSelect:E=>E.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Allow Scroll"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card content scroll"})]}),e.jsxs(t.DropdownMenuCheckboxItem,{checked:m,onCheckedChange:E=>{g("showInlineFilterBar",E)},onSelect:E=>E.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 ms({className:s,triggerVariant:n="icon",label:a="Inline Filters"}){var M,S,I;const[r,d]=N.useState(!1),i=t.useEditorStore(D=>D.card),l=t.useEditorStore(D=>D.selectedConnectionId),{tokenProps:c}=t.useSemaphorContext(),{setCard:o}=t.useEditorActions(),u=t.useDashboardStore(D=>D.actions.removeCardInlineFilterValue),h=t.useDashboardStore(D=>D.actions.setCardInlineFilterValue),x=t.useEditorStore(D=>D.actions.removeCardInlineFilterValue),p=t.useEditorStore(D=>D.actions.setCardInlineFilterValue),m=t.useDashboardStore(D=>D.isVisualEditing),g=(i==null?void 0:i.inlineFilters)||[],v=((S=(M=c==null?void 0:c.params)==null?void 0:M.calendarContext)==null?void 0:S.tz)||((I=c==null?void 0:c.params)==null?void 0:I.timezone)||Intl.DateTimeFormat().resolvedOptions().timeZone;function j(D){var F,B,_,z,G;const E=((_=(B=(F=i==null?void 0:i.dataSource)==null?void 0:F.selectedEntities)==null?void 0:B[0])==null?void 0:_.database)||"",b=D.qualifiedFieldName||D.name;if(g.find(W=>t.doesStoredFilterMatchField(W,D)))return;const y=D.qualifiedFieldName?D.qualifiedFieldName.split(".").slice(0,-1).join("."):D.qualifiedEntityName||D.entityName,R=t.fmt(D.name),f=t.buildFilterFieldMeta(D),A=t.buildFilterSemanticContext(i==null?void 0:i.dataSource,{connectionId:l||((z=i==null?void 0:i.dataSource)==null?void 0:z.connectionId),connectionType:(G=i==null?void 0:i.dataSource)==null?void 0:G.connectionType}),w=t.isCalculatedFilterField(f),P={id:t.v4(),column:b,title:D.label||D.name,dataType:D.dataType,table:D.entityName||"",database:E,connectionId:l||"",operation:"in",sql:w?"":t.getDefaultFilterSql(D.dataType,y,R),fieldMeta:f,semanticContext:A,width:250};o({...i,inlineFilters:[...g,P]})}function T(D){const E=g.filter(b=>b.id!==D);o({...i,inlineFilters:E}),m?x(i.id,D):u(i.id,D)}function k(D,E){const b=g.map(R=>R.id===D?{...R,...E}:R);if(o({...i,inlineFilters:b}),!(Object.prototype.hasOwnProperty.call(E,"defaultValues")||Object.prototype.hasOwnProperty.call(E,"defaultDateFilter")))return;const y=b.find(R=>R.id===D);if(!y)return;const L=t.buildFilterValueFromDefaults(y,v);L?m?p(i.id,L):h(i.id,L):m?x(i.id,D):u(i.id,D)}if(!["bar","line","pie","doughnut","table","detailTable","stackedBar","stackedLine","horizontalBar","radar","polarArea","scatter","bubble","funnel","aggregateTable","custom"].includes(i==null?void 0:i.type))return null;const C=n==="menu";return e.jsx("div",{className:t.cn("flex items-center gap-1",C&&"w-full",s),children:e.jsxs(t.Popover,{open:r,onOpenChange:d,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:C?e.jsxs(t.Button,{variant:"ghost",className:t.cn("h-8 w-full justify-start gap-2 px-2 text-sm",g.length>0&&"text-primary"),children:[e.jsx(ea,{className:"h-4 w-4"}),e.jsx("span",{children:a}),g.length>0&&e.jsx("span",{className:"ml-auto inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-primary text-[10px] font-medium leading-none text-primary-foreground",children:g.length})]}):e.jsxs(t.IconButton,{tooltip:"Add Inline Filter",className:t.cn("relative",{"text-primary":g.length>0}),children:[e.jsx(ea,{className:"h-4 w-4"}),g.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:g.length})]})}),e.jsx(t.PopoverContent,{align:"end",className:t.cn("w-80 p-0",C&&"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 h-[320px] min-h-0 flex-col overflow-hidden",children:e.jsx(t.DndContext,{collisionDetection:t.closestCenter,children:e.jsx(t.SortableContext,{items:[],strategy:t.verticalListSortingStrategy,children:e.jsx(t.FieldsList,{context:"inline-filter",onFieldSelect:j,inlineFilters:g})})})}),g.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:g.map(D=>e.jsx(cr,{filter:D,onUpdate:E=>k(D.id,E),onRemove:()=>T(D.id)},D.id))})]})]})})]})})}function cr({filter:s,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:s.column,children:s.title}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(t.CustomFilterPopover,{filter:s,variant:"inline",onAccept:r=>n(r),trigger:e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0",title:"Configure filter",children:e.jsx(t.Settings2,{className:"h-3 w-3"})})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0 hover:bg-destructive/10 hover:text-destructive",onClick:a,children:e.jsx(t.X,{className:"h-3 w-3"})})]})]})}const dr={metric_selector:"Displayed metric",field_selector:"Group by field",aggregation_selector:"Aggregation",grain_selector:"Time grain"};function ur(s,n){return s&&typeof s=="object"&&"label"in s&&typeof s.label=="string"&&s.label.trim().length>0?s.label:n||null}const mr={metric_selector:"config_metric_selector",field_selector:"config_field_selector",aggregation_selector:"config_aggregation",grain_selector:"config_grain"};function _t(s,n){return`${s}:${n}`}function xr(s,n,a){const r=new Set(a.filter(i=>i.target!=="sql_param").map(i=>_t(i.controlId,i.target))),d=n.map(i=>{const l=t.getCompatibleBindingTargetOptions({card:s,control:i}).map(h=>h.value),c=mr[i.type],u=[...c?[c]:[],...l.filter(h=>h!==c)].find(h=>!r.has(_t(i.id,h)));return u?{controlId:i.id,target:u}:null}).find(Boolean);return d?{controlId:d.controlId,target:d.target,mapping:{}}:null}function hr({card:s,dashboardControls:n,bindings:a,onChange:r,availableFieldChoices:d,availableMetricChoices:i,suppressTransientStaleState:l=!1}){const c=[...n,...s.controls||[]],[o,u]=N.useState({}),h=t.extractSqlParamReferences({sql:s.sql,controlBindings:s.controlBindings}),x=t.getBindingTargetSuggestions(s),p=new Set(a.map(V=>_t(V.controlId,V.target))),m=c.some(V=>t.getCompatibleBindingTargetOptions({card:s,control:V}).some(C=>!p.has(_t(V.id,C.value)))),g=l?0:a.reduce((V,C)=>{const M=v(C.target),S=Object.values(C.mapping).filter(I=>{const D=C.target==="config_metric_selector"||C.target==="config_field_selector"?typeof I=="string"?I:I==null?void 0:I.id:typeof I=="string"?I:void 0;return typeof D=="string"&&!M.some(E=>E.value===D)}).length;return V+S},0);function v(V){var C,M,S,I;switch(V){case"config_metric_selector":return i?i.filter(D=>!!D.target).map(D=>({value:D.target.id,label:D.target.label||D.option.label,target:D.target})):((M=(C=s.config)==null?void 0:C.metricColumns)==null?void 0:M.map(D=>({value:D.id,label:D.label||D.id,target:D})))||[];case"config_field_selector":return d?d.filter(D=>!!D.target).map(D=>({value:D.target.id,label:D.target.label||D.option.label,target:D.target})):((I=(S=s.config)==null?void 0:S.groupByColumns)==null?void 0:I.map(D=>({value:D.id,label:D.label||D.id,target:D})))||[];case"config_aggregation":return(x.config_aggregation||[]).map(D=>({value:D,label:D}));case"config_grain":return(x.config_grain||[]).map(D=>({value:D,label:D.charAt(0).toUpperCase()+D.slice(1)}));default:return[]}}const j=(V,C)=>{r(a.map((M,S)=>S!==V?M:C(M)))},T=V=>{r(a.filter((C,M)=>M!==V))},k=()=>{const V=xr(s,c,a);V&&r([...a,V])};if(typeof s.sql=="string"&&s.sql.trim().length>0){const V=h.map(({controlId:C,paramId:M})=>{const S=c.find(I=>I.id===C);return S?{id:C,paramId:M,label:S.label,reference:`[[param.${M}]]`}:{id:C,paramId:M,label:C,reference:`[[param.${M}]]`}});return e.jsx("div",{className:"space-y-2",children:V.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-sm text-muted-foreground",children:"This card is currently using raw SQL. Reference a control directly in the SQL editor with syntax like `[[param.metric]]`."}):V.map(C=>e.jsx("div",{className:"rounded-md border p-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:C.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Referenced in SQL"})]}),e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted/40 px-2 py-1",children:[e.jsx("code",{className:"text-xs",children:C.reference}),e.jsx(t.CopyButton,{text:C.reference,ariaLabel:`Copy ${C.reference}`})]})]})},`${C.id}:${C.paramId}`))})}return e.jsxs("div",{className:"space-y-4",children:[g>0?e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-950",children:[e.jsx(t.CircleAlert,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{children:[g," ",g===1?"mapping needs":"mappings need"," attention before save. Replace each missing target or choose Not mapped."]})]}):null,a.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-sm text-muted-foreground",children:"This card is not using any controls yet."}):a.map((V,C)=>{const M=x[V.target]||[],S=c.find(f=>f.id===V.controlId),I=S?t.ensureManualSource(S):null,D=(I==null?void 0:I.source.kind)==="manual"?I.source.options:[],E=v(V.target),b=Array.from(new Set([...D.map(f=>f.value),...Object.keys(V.mapping)])).map(f=>{const A=D.find(w=>w.value===f);return{value:f,label:(A==null?void 0:A.label)||f}}),O=`${V.controlId}-${V.target}-${C}`,y=o[O]??C===0,L=Object.keys(V.mapping).length,R=S!=null&&S.type?dr[S.type]||S.type:null;return e.jsxs(t.Collapsible,{open:y,onOpenChange:f=>u(A=>({...A,[O]:f})),className:"rounded-md border",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 p-3",children:[e.jsx(t.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-start gap-2 text-left",children:[y?e.jsx(t.ChevronDown,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}):e.jsx(t.ChevronRight,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:(S==null?void 0:S.label)||"Control"}),R?e.jsx(t.Badge,{variant:"secondary",className:"shrink-0 text-[11px] font-normal text-muted-foreground",children:R}):null]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:L>0?`${L} mapped`:"No mappings yet"})]})]})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>T(C),children:e.jsx(t.Trash2,{className:"h-4 w-4"})})]}),e.jsx(t.CollapsibleContent,{className:"space-y-3 border-t px-3 pb-3 pt-2",children:b.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-sm text-muted-foreground",children:"Add choices to this control first so you can decide what each choice changes in the card."}):E.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-sm text-muted-foreground",children:"No matching targets are available for this binding yet."}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs",children:"Map each choice"}),e.jsx("div",{className:"space-y-2",children:b.map(f=>{const A=V.mapping[f.value],w=V.target==="config_metric_selector"||V.target==="config_field_selector"?typeof A=="string"?A:A==null?void 0:A.id:typeof A=="string"?A:void 0,P=!l&&typeof w=="string"&&!E.some(_=>_.value===w),F=ur(A,w),B=w&&P?[...E,{value:w,label:"Needs remap",target:A}]:E;return e.jsxs("div",{className:"grid gap-2 rounded-md border p-2 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-[11px] text-muted-foreground",children:"Viewer picks"}),e.jsx("div",{className:"rounded-md bg-muted/50 px-3 py-2 text-sm",children:f.label})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-[11px] text-muted-foreground",children:"Switch to"}),e.jsxs(t.Select,{value:w||"__none__",onValueChange:_=>j(C,z=>{if(z.target==="config_metric_selector"){const W={...z.mapping};if(_==="__none__")delete W[f.value];else{const U=B.find(Y=>Y.value===_);U!=null&&U.target?W[f.value]=U.target:delete W[f.value]}return{...z,mapping:W}}if(z.target==="config_field_selector"){const W={...z.mapping};if(_==="__none__")delete W[f.value];else{const U=B.find(Y=>Y.value===_);U!=null&&U.target?W[f.value]=U.target:delete W[f.value]}return{...z,mapping:W}}const G={...z.mapping};return _==="__none__"?delete G[f.value]:G[f.value]=_,{...z,mapping:G}}),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Choose what this should use"})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"__none__",children:"Not mapped"}),B.map(_=>e.jsx(t.SelectItem,{value:_.value,children:_.label},_.value))]})]}),P?e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-amber-700",children:[e.jsx(t.CircleAlert,{className:"h-3 w-3 shrink-0"}),e.jsxs("span",{children:["Needs remap",F?` · Previously: ${F}`:""]})]}):null]})]},`${V.controlId}-${V.target}-${f.value}`)})}),M.length>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Available choices for this card: ",M.join(", ")]})]})})]},O)}),m?e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",onClick:k,children:[e.jsx(t.Plus,{className:"mr-2 h-4 w-4"}),"Add another control response"]}):null]})}const pr=[];function fr({className:s,triggerVariant:n="icon",label:a="Controls"}){var y,L;const{handleOpenChange:r,preventPassiveDismissDuringCreate:d,resolvedOpen:i,setIsCreateFlowActive:l}=Ae.useCreateFlowOverlayState({}),c=t.useEditorStore(R=>R.card),o=t.useEditorStore(R=>R.frame),u=t.useDashboardStore(R=>R.dashboard),x=t.useDashboardStore(R=>R.dashboard.controls)||pr,{setCard:p,updateCardInFrame:m}=t.useEditorActions(),[g,v]=N.useState(null);N.useEffect(()=>{i&&!g&&(c!=null&&c.id)&&v(c.id)},[c==null?void 0:c.id,i,g]),N.useEffect(()=>{!i&&g!==null&&v(null)},[i,g]);const j=N.useMemo(()=>g?(o==null?void 0:o.cards.find(R=>R.id===g))||((c==null?void 0:c.id)===g?c:void 0):c,[c,o==null?void 0:o.cards,g]),T=(j==null?void 0:j.controls)||[],k=j?t.collectDashboardControlIds(u,{excludeCardId:j.id}):x.map(R=>R.id),V=((j==null?void 0:j.controlBindings)||[]).filter(R=>R.target!=="sql_param"),C=t.buildCardControlUsageById({card:j,controls:T}),M={choices:t.getFieldSelectorChoicesForCard(j),targetMap:Object.fromEntries((((y=j==null?void 0:j.config)==null?void 0:y.groupByColumns)||[]).map(R=>[R.id,R]))},S={choices:t.getMetricSelectorChoicesForCard(j),targetMap:Object.fromEntries((((L=j==null?void 0:j.config)==null?void 0:L.metricColumns)||[]).map(R=>[R.id,R]))},I=M.choices.map(R=>({option:R,target:M.targetMap[R.value]})),D=S.choices.map(R=>({option:R,target:S.targetMap[R.value]})),E=(R,f)=>{if(!j)return;const A=(f==null?void 0:f.type)==="rename"?t.applyControlMutationToCard(j,{type:"rename",oldId:f.oldId,newId:f.newId}):(f==null?void 0:f.type)==="remove"?t.applyControlMutationToCard(j,{type:"remove",controlId:f.controlId}):j,w={...A,controls:R,controlBindings:t.syncStructuralBindingsWithControls(A.controlBindings,R)};m(w),(c==null?void 0:c.id)===w.id&&p(w)},b=R=>{if(!j)return;const f={...j,controlBindings:t.mergeConfigBindingsWithSqlParamBindings(R,j.controlBindings)};m(f),(c==null?void 0:c.id)===f.id&&p(f)},O=n==="menu";return e.jsx("div",{className:t.cn("flex items-center gap-1",O&&"w-full",s),children:e.jsxs(t.Popover,{modal:!0,open:i,onOpenChange:r,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:O?e.jsxs(t.Button,{variant:"ghost",className:t.cn("h-8 w-full justify-start gap-2 px-2 text-sm",(T.length>0||V.length>0)&&"text-primary"),children:[e.jsx(t.SlidersHorizontal,{className:"h-4 w-4"}),e.jsx("span",{children:a}),T.length+V.length>0&&e.jsx("span",{className:"ml-auto inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-primary text-[10px] font-medium leading-none text-primary-foreground",children:T.length+V.length})]}):e.jsxs(t.IconButton,{tooltip:"Configure Controls",className:t.cn("relative",{"text-primary":T.length>0||V.length>0}),children:[e.jsx(t.SlidersHorizontal,{className:"h-4 w-4"}),T.length+V.length>0&&e.jsx("span",{className:"absolute -right-1 -top-1 inline-flex h-4 min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[10px] font-medium text-primary-foreground",children:T.length+V.length})]})}),e.jsxs(t.PopoverContent,{className:"flex max-h-[85vh] w-[560px] max-w-[95vw] flex-col",align:"end",onEscapeKeyDown:d,onPointerDownOutside:d,children:[e.jsxs("div",{className:"space-y-1 border-b pb-4",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Card-only controls"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add controls that belong only to this card, or decide how this card should respond to shared dashboard controls."}),j!=null&&j.sql?e.jsx("p",{className:"text-xs text-muted-foreground",children:"SQL cards reference controls explicitly with syntax like `[[param.wac_type]]`."}):null]}),e.jsx("div",{className:"flex-1 overflow-y-auto pt-5",children:e.jsxs("div",{className:"space-y-5 pr-1",children:[e.jsx(Ae.ControlDefinitionListEditor,{scope:"card",card:j,controls:T,reservedControlIds:k,usageByControlId:C,availableFieldChoices:I,availableMetricChoices:D,onCreateFlowActiveChange:l,onChange:(R,f,A)=>E(R,A),emptyMessage:"No card-scoped controls yet."}),e.jsxs("div",{className:"space-y-1 border-t pt-4",children:[e.jsx("h4",{className:"text-sm font-medium",children:"How this card uses controls"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Choose what each control changes in this card."})]}),j?e.jsx(hr,{card:j,dashboardControls:x,bindings:V,onChange:b,availableFieldChoices:I,availableMetricChoices:D}):null]})})]})]})})}function Oa({showOrientation:s=!0,showGridStyle:n=!0,showInlineFilters:a=!0,showControls:r=!0,showDisplayOptions:d=!0}={}){const i=t.useEditorStore(m=>m.card),l=t.useEditorStore(m=>{var g,v;return(v=(g=m.card)==null?void 0:g.preferences)==null?void 0:v.chartOptions}),c=t.getChartGridStyle(l),{setChartGrid:o}=t.useEditorActions();function u(){const m=["xy","none","x","y"],v=(m.indexOf(c)+1)%m.length;o(m[v])}const h=s&&["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel","bullet"].includes(i.type),x=n&&!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(i.type);return h||x||a||r||d?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[h&&e.jsx(e.Fragment,{children:e.jsx(ir,{})}),x&&e.jsxs(t.IconButton,{tooltip:"Grid Style",onClick:u,children:[(c==="xy"||!c)&&e.jsx(t.Grid3x3,{className:"size-4"}),c==="x"&&e.jsx(is,{className:"size-4"}),c==="y"&&e.jsx(qt,{className:"size-4"}),c==="none"&&e.jsx(t.Square,{className:"size-4"})]}),a&&e.jsx(ms,{}),r&&e.jsx(fr,{}),d&&e.jsx(us,{})]}):null}function gr({visible:s}){const n=t.useDashboardStore(l=>l.selectedFrameId),a=t.useManagementStore(l=>l.selectedVisual),r=t.useEditorStore(l=>l.frame),i=!!!(r!=null&&r.visualId||a!=null&&a.id)&&!!n;return!s||i?null:e.jsx("div",{className:"mb-2 flex",children:e.jsx(Ae.VisualBadge,{showLabel:!0,className:"h-6 w-fit px-2 py-0.5 text-[11px]"})})}function jr({isPreviewMode:s,onPreviewToggle:n,configCard:a}){var R,f,A,w,P;const r=t.useEditorStore(F=>F.frame),d=t.useEditorStore(F=>F.card),{setFrame:i,setActiveTabCardId:l,setCard:c,updateCardInFrame:o,clearModeDrafts:u,initializeModeDrafts:h}=t.useEditorActions(),{manifest:x}=t.useCustomVisual(((R=a==null?void 0:a.customCardPreferences)==null?void 0:R.url)||""),p=(f=x==null?void 0:x.visuals)==null?void 0:f.find(F=>{var B;return F.name===((B=a==null?void 0:a.customCardPreferences)==null?void 0:B.componentName)}),g=t.resolveMultiInputType(a,p)==="multiple",v=(p==null?void 0:p.minInputs)??((A=a==null?void 0:a.customCardPreferences)==null?void 0:A.minInputs)??1,j=(p==null?void 0:p.maxInputs)??((w=a==null?void 0:a.customCardPreferences)==null?void 0:w.maxInputs),T=N.useMemo(()=>t.getCustomVisualInputCards({frame:r,configCard:a,isMultiInputVisual:g}),[r,a,g]),k=g?T.filter(Boolean).length:r.cards.length,V=j?k<j:!0,C=k>Math.max(v||1,1),M=!!((P=a==null?void 0:a.customCardPreferences)!=null&&P.dataInputCardIds),S=(F,B)=>{F.dataTransfer.setData("tabIndex",B.toString())},I=F=>{F.preventDefault()},D=(F,B)=>{const _=F.dataTransfer.getData("tabIndex");if(_===B.toString())return;const z=Array.from(r.cards),[G]=z.splice(parseInt(_),1);z.splice(B,0,G),i({...r,cards:z})};function E(F){const B=(a==null?void 0:a.id)===F;if(!(M&&B?r.cards.length>1:C))return;let z=r.cards.filter(Y=>Y.id!==F);g&&!M&&(z=t.reindexSlotCards(z));const G=z[0],W={...r,cards:z,activeCardId:G.id},U=F===d.id;U&&u(),i(W),l(G.id),c(G),U&&h(G)}function b(F,B){if(!V)return;const _={...r,cards:[...r.cards,B],activeCardId:F.id};i(_),l(B.id)}function O(){if(g&&(a==null?void 0:a.id)===d.id){y(d);return}const F={...d,id:t.v4(),title:`${d.title} Copy`,tabTitle:`${d.tabTitle||d.title} Copy`,customCardPreferences:d.customCardPreferences?{...d.customCardPreferences,slotIndex:g?Math.max(-1,...T.map((B,_)=>t.getSlotIndexForCard(B,_)))+1:d.customCardPreferences.slotIndex}:void 0};b(d,F)}function y(F){var U;if(!V)return;let B=g?"table":"bar",_="Title",z="";const G=g?Math.max(-1,...T.map((Y,se)=>t.getSlotIndexForCard(Y,se)))+1:k;if(g&&((U=p==null?void 0:p.slots)!=null&&U.length)){const Y=t.getSlotDefinitionForIndex(p.slots,G);Y&&(B=t.getSlotExpectedChartType(Y),_=Y.label||`Tab ${G+1}`,z=Y.description||"")}const W={dataSource:F.dataSource,connectionId:F.connectionId,lastSelectedDatabase:F.lastSelectedDatabase,lastSelectedSchema:F.lastSelectedSchema,lastSelectedTable:F.lastSelectedTable,lastSelectedDatamodelId:F.lastSelectedDatamodelId,id:t.v4(),title:_,tabTitle:_,description:z,preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:B,sql:"",data:[],mode:"explorer",...g&&{customCardPreferences:{slotIndex:G}}};b(F,W)}function L(F,B){return F.cards.length===1&&(B.displayTab===!0||B.displayTab===void 0)||F.activeCardId!==B.id&&(B.displayTab===!0||B.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const _=B.displayTab===void 0?!1:!B.displayTab;c({...B,displayTab:_}),o({...B,displayTab:_})},children:B.displayTab===!0||B.displayTab===void 0?e.jsx(t.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(t.EyeOff,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(t.TabsList,{className:"group ml-2 mr-6 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[r.cards.map((F,B)=>{var U,Y;const _=g?t.getSlotIndexForCard(F,B):-1,z=g&&((U=p==null?void 0:p.slots)!=null&&U.length)&&_>=0?t.getSlotDefinitionForIndex(p.slots,_):null,G=z?(Array.isArray(z.expectedType)?z.expectedType[0]:z.expectedType)||"table":F.type,W=g&&((Y=p==null?void 0:p.slots)==null?void 0:Y.length)&&p.slots.every(se=>typeof se.position=="number"||typeof se.position=="string"&&!se.position.includes("+"));return e.jsxs(t.TabsTrigger,{draggable:!g,onDragStart:g?void 0:se=>S(se,B),onDragOver:g?void 0:I,onDrop:g?void 0:se=>D(se,B),className:"",value:F.id,children:[g&&z?e.jsx(t.TooltipProvider,{delayDuration:0,children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:t.getChartIconByType(G,"size-3.5")}),e.jsx("span",{children:z.label||`Tab ${_+1}`})]})}),e.jsx(t.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:z.label}),z.description&&e.jsx("p",{className:"whitespace-normal break-words text-xs text-muted-foreground",children:z.description}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[z.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(z.expectedType)?z.expectedType.join(" / "):z.expectedType}),z.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:[L(r,F),e.jsx(t.Editable,{enabled:r.activeCardId===F.id,text:F.tabTitle||F.title,onSave:se=>{c({...d,tabTitle:se}),o({...d,tabTitle:se})},children:F.tabTitle||F.title},F.id)]}),r.activeCardId===F.id&&!W&&e.jsx(t.CopyPlus,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:se=>{se.stopPropagation(),O()}}),r.activeCardId===F.id&&(M&&(a==null?void 0:a.id)===F.id?r.cards.length>1:C)&&e.jsx(t.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>E(F.id)})]},F.id)}),e.jsx(t.IconButton,{tooltip:"Add Card",className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",onClick:()=>y(d),disabled:!V,children:e.jsx(t.Plus,{className:"h-4 w-4"})}),g&&e.jsxs(t.Toggle,{pressed:s,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:[s?e.jsx(t.EyeOff,{className:"h-4 w-4"}):e.jsx(t.Eye,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Preview"})]})]})})}function rt({renderCardOverride:s,alwaysRenderOverride:n=!1}={}){var Ee,q,oe,Ne,Be;const a=t.useEditorStore(X=>X.frame),r=t.useEditorStore(X=>X.card),[d,i]=N.useState(!1),l=N.useMemo(()=>t.findCustomVisualConfigCard(a,r),[a,r]),c=t.useEditorStore(X=>X.isSqlRunning);t.useEditorStore(X=>X.isDevMode);const{setFrame:o,setActiveTabCardId:u,setCard:h,setRunSql:x,mergeDraftsIntoCard:p,clearModeDrafts:m,initializeModeDrafts:g}=t.useEditorActions(),[v,j]=N.useState({}),[T,k]=N.useState(()=>new Set),{theme:V}=t.useTheme(),C=t.useDashboardStore(X=>X.themeStyle),{authToken:M}=t.useSemaphorContext(),S=t.getTokenParams(M==null?void 0:M.accessToken),I={mode:V||"system",colors:((q=(Ee=C==null?void 0:C.chart)==null?void 0:Ee.dataset)==null?void 0:q.backgroundColor)||[]},{getCard:D,manifest:E,isLoading:b}=t.useCustomVisual(((oe=l==null?void 0:l.customCardPreferences)==null?void 0:oe.url)||""),O=(Ne=l==null?void 0:l.customCardPreferences)==null?void 0:Ne.componentName,y=O?D(O):null,L=(Be=E==null?void 0:E.visuals)==null?void 0:Be.find(X=>X.name===O),R=t.resolveMultiInputType(l,L),f=d&&R==="multiple"&&!!l,A=N.useMemo(()=>t.getCustomVisualInputCards({frame:a,configCard:l,isMultiInputVisual:!0}).map(fe=>(fe==null?void 0:fe.id)===r.id?r:fe),[a,l,r]),w=N.useMemo(()=>t.buildSlotOrderedCards(A),[A]),P=N.useMemo(()=>{const X=A.findIndex(fe=>(fe==null?void 0:fe.id)===r.id);return X<0?-1:t.getSlotIndexForCard(r,X)},[A,r]),F=N.useMemo(()=>!l||R!=="multiple"||P<0?r.type:t.getEffectiveCardTypeForSlot(r,P,L==null?void 0:L.slots)??r.type,[l,R,P,r,L==null?void 0:L.slots]),B=N.useMemo(()=>f?{...r,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:F!==r.type?{...r,type:F}:r,[r,F,f]),{data:_,isLoading:z,isFetching:G,isError:W}=t.useDashboardCardQuery(B),U=N.useCallback((X,fe)=>{const Ce=t.normalizeMultiInputPayload(fe);j(De=>({...De,[X]:Ce}))},[]),Y=N.useCallback((X,fe)=>{k(Ce=>{const De=new Set(Ce);return fe?De.add(X):De.delete(X),De})},[]),se=T.size>0,ee=t.useInteractionStore(X=>X.interactionStates),ce=t.useDashboardStore(X=>{var fe;return(fe=X.dashboard)==null?void 0:fe.id}),re=t.useDashboardStore(X=>X.dashboard.filters),ne=t.useDashboardStore(X=>X.filterValues),xe=t.useDashboardStore(X=>X.selectedSheetId),Z=t.useEditorStore(X=>X.inlineFilterValuesMap[(l==null?void 0:l.id)||""]),ge=t.useEditorStore(X=>X.actions.setCardInlineFilterValue),ae=t.useEditorStore(X=>X.actions.removeCardInlineFilterValue),ue=N.useMemo(()=>l?t.buildInlineFilterNodes({card:l,sheetId:xe||"",inlineFilterValues:Z,setInlineFilterValue:X=>ge(l.id,X),removeInlineFilterValue:X=>ae(l.id,X)}):[],[l,xe,Z,ge,ae]),{cardFilters:Le,cardFilterValues:te}=N.useMemo(()=>l?t.calculateContextAwareFilters({card:l,interactionStates:ee,currentDashboardId:ce,filters:re,filterValues:ne,selectedSheetId:xe}):{cardFilters:[],cardFilterValues:[]},[l,ee,ce,re,ne,xe]);function ve(X){const fe=a.cards.find(Ce=>Ce.id===X);fe&&(p(),ye(X),u(X),m(),g(fe))}function ye(X){const fe=t.useEditorStore.getState().card,Ce=t.useEditorStore.getState().frame,De={...Ce,cards:Ce.cards.map(Pe=>Pe.id===fe.id?fe:Pe),activeCardId:X};o(De);const Se=De.cards.find(Pe=>Pe.id===X);Se.sql&&x(!0),h(Se)}function je(){if(b)return e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading manifest"})});if(!y)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=w.map((Ce,De)=>t.getEffectiveCardTypeForSlot(Ce,De,L==null?void 0:L.slots));return e.jsxs("div",{className:"relative flex h-full flex-col pl-2 pr-4",children:[A.map((Ce,De)=>{if(!Ce)return null;const Se=t.getSlotIndexForCard(Ce,De),Pe=t.getEffectiveCardTypeForSlot(Ce,Se,L==null?void 0:L.slots);return e.jsx(t.MultiInputEmptyRenderer,{onLoadingStatus:Y,onDataChange:U,card:Ce,effectiveCardType:Pe},`${Ce.id}-${Se}`)}),se&&e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/50",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading preview"})}),e.jsx("div",{className:t.cn("flex h-full min-h-0 flex-1 flex-col gap-2",se&&"opacity-50"),children:e.jsx(N.Suspense,{fallback:e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(t.LoadingDots,{size:"md",color:"muted"})}),children:e.jsx(y,{editing:!0,...t.buildMultiInputCustomVisualProps({configCard:l,slotOrderedCards:w,slotTypes:fe,multiInputData:v,params:S,theme:I,filters:Le,filterValues:[...te||[],...Z||[]],inlineFilters:ue})})})})]})}function we(){var X;return f?je():s&&(n||!z&&!G&&!W)?s({card:r,data:_,isLoading:z,isFetching:G,isError:W}):r.type==="kpi"?z||G?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(t.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(gr,{visible:!0}),e.jsx("div",{className:"rounded-md border border-border",children:e.jsx(t.KPICard,{card:r,data:_==null?void 0:_.records,isPending:z||G,isError:W,comparisonMetadata:(X=_==null?void 0:_.metadata)==null?void 0:X.comparisonMetadata})}),t.isCardSummaryVisibleOnCard(r)&&e.jsx(t.CardSummary,{card:r,mode:"editor"})]})}):r.type==="text"?z||G?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(t.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(t.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(t.TextCard,{isLoading:c,card:r,data:_==null?void 0:_.records})})})}):e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackVisual,children:e.jsx(Fa,{className:"grow border-none shadow-none"})})}return e.jsxs(t.Tabs,{onValueChange:ve,value:a.activeCardId,className:"flex grow flex-col gap-2",children:[f?e.jsx("div",{className:"mt-0 grow",children:we()}):a.cards.map(X=>e.jsx(t.TabsContent,{className:"mt-0 grow focus-visible:ring-0 focus-visible:ring-offset-0",value:X.id,children:we()},X.id)),e.jsx(jr,{isPreviewMode:f,onPreviewToggle:i,configCard:l})]})}function br({onClick:s,className:n}){return e.jsxs(t.Button,{type:"button",size:"sm",variant:"outline",className:t.cn("h-8 gap-1.5 px-3 text-xs",n),onClick:s,children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5 shrink-0"}),"Customize"]})}function Ra({fallbackPreview:s,records:n,title:a,isInspectorOpen:r,onInspectorOpenChange:d}){var w;const i=t.useEditorStore(P=>P.card),l=t.useEditorStore(P=>P.actions.setCard),c=t.useEditorStore(P=>P.actions.updateCardInFrame),{theme:o}=t.useTheme(),u=t.useDashboardStore(P=>P.theme),h=t.normalizeDynamicRendererSource((w=i.dynamicCardPreferences)==null?void 0:w.rendererCode),[x,p]=N.useState(h),[m,g]=N.useState(h);N.useEffect(()=>{p(h),g(h)},[h,i.id]);const v=N.useMemo(()=>t.normalizeDynamicRendererSource(x),[x]),j=N.useMemo(()=>t.validateDynamicRendererSource(v),[v]),T=!!h,k=N.useMemo(()=>{var P;return t.buildCardWithVisualizationMode(i,m?"dynamic":"builtin",{rendererCode:m||void 0,artifactId:((P=i.dynamicCardPreferences)==null?void 0:P.artifactId)||i.id,title:a||i.title})},[i,m,a]),V=!!m,C=v!==m,M=m!==h,S=!v||!j.valid||C||M,I=v?j.valid?C?"Unapplied changes":"Pending save":"Needs attention":"Draft",D=!v||C||M?"outline":"destructive",E=v?j.valid?C?"The preview still reflects the last applied code until you apply this draft.":M?"Preview reflects pending changes. Accept changes to save them.":"":j.error||"Visual code is invalid.":"Paste visual code or generate one before saving this card.",b=typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",O=(u==="system"?b:u||o)==="dark"?"vs-dark":"vs";function y(){if(!j.valid){t.ue.error(j.error||"Visual code is invalid.");return}g(v),t.ue.success("Dynamic preview updated.")}function L(){p(m)}function R(){var F;const P=t.buildCardWithVisualizationMode(i,m?"dynamic":"builtin",{rendererCode:m||void 0,artifactId:((F=i.dynamicCardPreferences)==null?void 0:F.artifactId)||t.v4(),title:a||i.title});l(P),c(P),d(!1),t.ue.success(m?"Dynamic visual changes saved.":"Dynamic visual cleared.")}function f(){p(h),g(h),d(!1)}function A(){p(""),g("")}return e.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[e.jsx("div",{className:"min-h-0 flex-1 bg-background px-2",children:T?e.jsx(t.PersistedDynamicVisual,{card:i,records:n,title:a,layoutMode:"fill",fallback:s},h||"applied-empty"):e.jsxs("div",{className:"flex h-full min-h-[280px] flex-col items-center justify-center gap-3 rounded-md border border-dashed border-border/70 bg-muted/20 px-6 text-center",children:[e.jsx("div",{className:"flex size-10 items-center justify-center rounded-full border bg-background",children:e.jsx(t.CodeXml,{className:"text-muted-foreground"})}),e.jsxs("div",{className:"flex max-w-md flex-col gap-1",children:[e.jsx("p",{className:"text-sm font-medium",children:"No applied dynamic visual yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Open Customize, paste visual code, and apply it to preview the renderer here."})]}),e.jsx(br,{onClick:()=>d(!0)})]})}),e.jsx(t.Dialog,{open:r,onOpenChange:P=>{if(!P){f();return}d(!0)},children:e.jsxs(t.DialogContent,{className:"flex h-[min(88vh,860px)] max-w-[min(1280px,calc(100vw-2rem))] flex-col gap-0 overflow-hidden p-0",children:[e.jsx(t.DialogHeader,{className:"border-b px-6 py-4 pr-20 text-left",children:e.jsxs("div",{className:"flex items-start justify-between gap-4 pr-4",children:[e.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[e.jsx(t.DialogTitle,{children:"Dynamic Visual Editor"}),e.jsx(t.DialogDescription,{children:"Adjust the preview and visual code here. Query editing stays in the normal editor controls."})]}),S&&e.jsx(t.Badge,{className:"mr-4 shrink-0",variant:D,children:I})]})}),e.jsx("div",{className:"min-h-0 flex-1",children:e.jsxs(t.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(t.ResizablePanel,{defaultSize:54,minSize:38,children:e.jsx("div",{className:"flex h-full min-h-0 flex-col",children:e.jsx("div",{className:"min-h-0 flex-1 bg-background p-4",children:V?e.jsx(t.PersistedDynamicVisual,{card:k,records:n,title:a,layoutMode:"fill",fallback:s},m||"preview-empty"):e.jsx("div",{className:"flex h-full min-h-[280px] items-center justify-center rounded-md border border-dashed border-border/70 bg-muted/20 px-6 text-center text-sm text-muted-foreground",children:"Apply valid visual code to preview the dynamic visual here."})})})}),e.jsx(t.ResizableHandle,{withHandle:!0}),e.jsx(t.ResizablePanel,{defaultSize:46,minSize:30,children:e.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between border-b px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(t.CodeXml,{className:"h-4 w-4 text-muted-foreground"}),"Visual Code"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.AlertDialog,{children:[e.jsx(t.AlertDialogTrigger,{asChild:!0,children:e.jsxs(t.Button,{type:"button",size:"sm",variant:"ghost",className:"h-8 gap-1.5 px-2.5 text-xs",disabled:!T&&!v,children:[e.jsx(t.X,{className:"h-3.5 w-3.5 shrink-0"}),"Clear"]})}),e.jsxs(t.AlertDialogContent,{children:[e.jsxs(t.AlertDialogHeader,{children:[e.jsx(t.AlertDialogTitle,{children:"Clear dynamic visual?"}),e.jsx(t.AlertDialogDescription,{children:"This removes the saved dynamic renderer and switches the card back to built-in mode. The underlying query and built-in chart type will remain."})]}),e.jsxs(t.AlertDialogFooter,{children:[e.jsx(t.AlertDialogCancel,{children:"Cancel"}),e.jsx(t.AlertDialogAction,{className:"bg-foreground text-background hover:bg-foreground/90",onClick:A,children:"Clear"})]})]})]}),e.jsxs(t.Button,{type:"button",size:"sm",variant:"outline",className:"h-8 gap-1.5 px-2.5 text-xs",onClick:L,disabled:!C,children:[e.jsx(ls,{className:"h-3.5 w-3.5 shrink-0"}),"Reset"]}),e.jsxs(t.Button,{type:"button",size:"sm",className:"h-8 gap-1.5 px-3 text-xs",onClick:y,disabled:!C||!j.valid,children:[e.jsx(t.Play,{className:"h-3.5 w-3.5 shrink-0"}),"Apply to Preview"]})]})]}),e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3 p-4",children:[E&&e.jsx("p",{className:t.cn("text-xs",j.valid?"text-muted-foreground":"text-destructive"),children:E}),e.jsx(t.Ft,{value:x,onChange:P=>p(P||""),theme:O,defaultLanguage:"javascript",className:t.cn("min-h-0 flex-1 overflow-hidden rounded-md border",!j.valid&&v&&"border-destructive"),options:{minimap:{enabled:!1},glyphMargin:!1,lineNumbersMinChars:3,lineDecorationsWidth:0,wordWrap:"on",scrollbar:{verticalScrollbarSize:10,horizontalScrollbarSize:10},fontSize:13,renderLineHighlight:"none",automaticLayout:!0,padding:{top:16,bottom:16}}})]})]})})]})}),e.jsxs(t.DialogFooter,{className:"border-t px-6 py-4 sm:justify-between",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:E||"Preview changes here before saving them."}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{type:"button",variant:"outline",size:"sm",className:"h-8 px-3 text-xs",onClick:f,children:"Cancel"}),e.jsx(t.Button,{type:"button",size:"sm",className:"h-8 px-3 text-xs",onClick:R,disabled:!M,children:"Accept changes"})]})]})]})})]})}function Ba({onCustomize:s}){const n=t.useEditorStore(u=>u.card),a=t.useEditorStore(u=>u.frame),r=t.useEditorStore(u=>u.actions.setIsShowingVisual),{setVisualizationMode:d,setDynamicCardPreferences:i}=t.useEditorActions(),c=t.getVisualizationMode(n)==="dynamic";if(a.cards.length!==1||t.isCustomVisualizationCard(n))return null;const o=u=>{var h;u==="dynamic"&&!n.dynamicCardPreferences&&i(t.createEmptyDynamicCardPreferences(n.type,(h=n.preferences)==null?void 0:h.displayOptions)),d(u),r(!0)};return e.jsxs(e.Fragment,{children:[e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{onSelect:u=>{u.preventDefault(),o(c?"builtin":"dynamic")},className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx(t.CodeXml,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Dynamic"})]}),e.jsx(t.Switch,{checked:c,onCheckedChange:u=>o(u?"dynamic":"builtin"),onClick:u=>u.stopPropagation()})]}),c&&s?e.jsxs(t.DropdownMenuItem,{onSelect:u=>{u.preventDefault(),s()},children:[e.jsx(t.SlidersHorizontal,{className:"mr-2 h-4 w-4"}),"Customize Visual"]}):null]})}function da({children:s,visualAsideControl:n}){var U;const a=t.useEditorStore(Y=>Y.frame),r=t.useEditorStore(Y=>Y.card),d=r.type==="table"||r.type==="detailTable",i=t.useEditorStore(Y=>Y.isDevMode),l=t.useEditorStore(Y=>Y.isShowingVisual),c=t.useEditorStore(Y=>Y.actions.setIsShowingVisual),o=t.useDashboardStore(Y=>Y.isVisualEditing),{isConsoleMode:u}=t.useDashboardPreferences(),h=t.useEditorStore(Y=>Y.pythonStdOut),x=t.useEditorStore(Y=>Y.actions.setRunSql),p=Ae.useEffectiveEditorCardType(),g=t.getVisualizationMode(r)==="dynamic",[v,j]=N.useState(!1),{setFrame:T,setCard:k,setActiveTabCardId:V,setCardPreferences:C,mergeDraftsIntoCard:M,clearModeDrafts:S,initializeModeDrafts:I}=t.useEditorActions(),D=N.useMemo(()=>p!==r.type?{...r,type:p}:r,[r,p]),{data:E,isLoading:b,isFetching:O,errorMessage:y,errorSql:L,refetch:R,pagination:f}=t.useDashboardCardQuery(D),{handleDebugWithAssistant:A}=La(y,L),w=N.useMemo(()=>(E==null?void 0:E.records)||[],[E==null?void 0:E.records]),[P,F]=N.useState(!1);N.useEffect(()=>{O||F(!1)},[O]),N.useEffect(()=>{d&&!l&&c(!0)},[d,l,c]);function B(Y,se){var re,ne;const ee={...r,paginationConfig:{page:Y+1,pageSize:se}};k(ee);const ce={...a,cards:a.cards.map(xe=>xe.id===r.id?ee:xe)};T(ce),r.sql&&((ne=(re=r.preferences)==null?void 0:re.tablePrefs)!=null&&ne.enableDevModePagination)&&x(!0)}function _(Y){var re,ne,xe,Z,ge;const se=t.sortStateToSortByColumns(Y,(re=r.config)==null?void 0:re.metricColumns,(ne=r.config)==null?void 0:ne.groupByColumns,(xe=r.config)==null?void 0:xe.detailColumns),ee={...r,config:{...r.config||{},sortByColumns:se}};k(ee);const ce={...a,cards:a.cards.map(ae=>ae.id===r.id?ee:ae)};T(ce),r.sql&&((ge=(Z=r.preferences)==null?void 0:Z.tablePrefs)!=null&&ge.enableDevModePagination)&&x(!0)}function z(){var se;const Y=JSON.stringify(E==null?void 0:E.records,null,2);typeof navigator>"u"||!((se=navigator.clipboard)!=null&&se.writeText)||navigator.clipboard.writeText(Y).catch(ee=>{console.error("Failed to copy JSON",ee)})}function G(){const Y=JSON.stringify(E==null?void 0:E.records,null,2),se=new Blob([Y],{type:"application/json"}),ee=URL.createObjectURL(se),ce=document.createElement("a");ce.href=ee,ce.download=`${r.title}.json`,ce.click()}function W(){const se=[Object.keys(E==null?void 0:E.records.reduce((ne,xe)=>({...ne,...xe}),{})).join(","),...((E==null?void 0:E.records)||[]).map(ne=>Object.values(ne).join(","))].join(`
|
|
192
|
+
`),ee=new Blob([se],{type:"text/csv"}),ce=URL.createObjectURL(ee),re=document.createElement("a");re.href=ce,re.download=`${r.title}.csv`,re.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:[l&&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(t.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(t.ChevronLeft,{className:"size-4"}):e.jsx(t.ChevronRight,{className:"size-4"})}),!g&&e.jsx("div",{className:"w-[200px]",children:e.jsx(ds,{variant:i?"secondary":"ghost"})})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[s,e.jsx(t.IconButton,{tooltip:"Refresh",disabled:b||O,onClick:()=>{F(!0),R()},children:e.jsx(t.RefreshCcw,{className:t.cn("h-4 w-4",{"animate-spin":P})})}),!g&&e.jsx(Oa,{showInlineFilters:!1,showDisplayOptions:!1}),(i||u)&&e.jsxs(e.Fragment,{children:[!d&&e.jsx(Nr,{}),d&&e.jsx(yr,{})]}),e.jsxs(t.DropdownMenu,{modal:!1,children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"More Options",className:"h-8 w-8 px-0","aria-label":"More options",children:e.jsx(t.EllipsisVertical,{className:"size-4"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(t.DropdownMenuLabel,{children:"More Options"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs("div",{className:"px-1 py-1",children:[!g&&!["table","detailTable","custom"].includes(r.type)&&o&&e.jsx(nr,{triggerVariant:"menu",className:"w-full"}),e.jsx(ms,{triggerVariant:"menu",className:"w-full"}),e.jsx(us,{triggerVariant:"menu",className:"w-full"}),e.jsx(Ba,{onCustomize:()=>j(!0)}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.Button,{variant:"ghost",className:"h-8 w-full justify-start gap-2 px-2 text-sm",onClick:W,children:[e.jsx(t.Download,{className:"h-4 w-4"}),e.jsx("span",{children:"Download CSV"})]}),e.jsxs(t.Button,{variant:"ghost",className:"h-8 w-full justify-start gap-2 px-2 text-sm",onClick:G,children:[e.jsx(pn,{className:"h-4 w-4"}),e.jsx("span",{children:"Download JSON"})]}),e.jsxs(t.Button,{variant:"ghost",className:"h-8 w-full justify-start gap-2 px-2 text-sm",onClick:z,children:[e.jsx(t.Copy,{className:"h-4 w-4"}),e.jsx("span",{children:"Copy JSON"})]})]})]})]})]})]}),l?g?e.jsx(rt,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(Ra,{fallbackPreview:e.jsx(rt,{}),records:w,title:r.title,isInspectorOpen:v,onInspectorOpenChange:j})}):e.jsx(rt,{}):e.jsxs(t.ResizablePanelGroup,{className:"py-2 pl-2 pr-6",direction:"horizontal",children:[h&&e.jsxs(e.Fragment,{children:[e.jsx(t.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:h&&e.jsx(vr,{})}),e.jsx(t.ResizableHandle,{})]}),e.jsxs(t.ResizablePanel,{id:"2",order:2,minSize:10,className:t.cn("relative flex h-full min-h-0 w-full flex-1 basis-0",{"py-2 pl-2 pr-6":h}),children:[(E==null?void 0:E.records)&&(E==null?void 0:E.records.length)>0&&e.jsx(t.TableVisual,{card:r,data:w,comparisonMetadata:(U=E==null?void 0:E.metadata)==null?void 0:U.comparisonMetadata,paginationMetadata:f,onPaginationChange:B,onSortChange:_,isLoading:b||O}),y&&e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(cs,{error:y,errorSql:L||r.sql||r.python,onDebugWithAssistant:A,showFeedbackButton:!1})})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function vr(){const s=t.useEditorStore(a=>a.pythonStdOut);if(!s)return null;const n=s.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(t.ScrollArea,{className:"overflow-y-auto pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:n}}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function yr(){var i,l,c,o,u,h;const s=t.useEditorStore(x=>x.card),n=t.useEditorStore(x=>x.actions.setCard),a=t.useEditorStore(x=>x.actions.setRunSql),r=t.useEditorStore(x=>x.actions.setCardPreferences),d=t.useEditorStore(x=>x.actions.updateCardInFrame);return s.type!=="table"&&s.type!=="detailTable"?null:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Checkbox,{id:"dev-pagination",checked:((l=(i=s.preferences)==null?void 0:i.tablePrefs)==null?void 0:l.enableDevModePagination)??!1,onCheckedChange:x=>{var p;r({...s.preferences,tablePrefs:{...(p=s.preferences)==null?void 0:p.tablePrefs,enableDevModePagination:x}})}}),e.jsx(t.Label,{htmlFor:"dev-pagination",className:"cursor-pointer text-sm",children:"Paginate"}),((o=(c=s.preferences)==null?void 0:c.tablePrefs)==null?void 0:o.enableDevModePagination)&&e.jsxs(t.Select,{value:String(((h=(u=s.preferences)==null?void 0:u.tablePrefs)==null?void 0:h.pageSize)||50),onValueChange:x=>{var g,v,j;const p=Number(x),m={...s,preferences:{...s.preferences,tablePrefs:{...(g=s.preferences)==null?void 0:g.tablePrefs,pageSize:p}},paginationConfig:{page:1,pageSize:p}};n(m),d(m),s.sql&&((j=(v=s.preferences)==null?void 0:v.tablePrefs)!=null&&j.enableDevModePagination)&&a(!0)},children:[e.jsx(t.SelectTrigger,{className:"h-8 w-20",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"10",children:"10"}),e.jsx(t.SelectItem,{value:"25",children:"25"}),e.jsx(t.SelectItem,{value:"50",children:"50"}),e.jsx(t.SelectItem,{value:"100",children:"100"}),e.jsx(t.SelectItem,{value:"500",children:"500"}),e.jsx(t.SelectItem,{value:"1000",children:"1000"})]})]})]})}function Nr(){const s=t.useEditorStore(a=>a.isShowingVisual),n=t.useEditorStore(a=>a.actions.setIsShowingVisual);return e.jsxs(t.Toggle,{pressed:!s,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(t.Table2,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:"Results"})]})}function $e({value:s,onCommit:n,type:a="text",placeholder:r,className:d}){const[i,l]=N.useState(s),c=N.useRef(!1);N.useEffect(()=>{l(s)},[s]);const o=()=>{if(c.current){c.current=!1;return}i!==s&&n(i)},u=h=>{if(h.key==="Enter"){h.currentTarget.blur();return}h.key==="Escape"&&(c.current=!0,l(s),h.currentTarget.blur())};return e.jsx(t.Input,{type:a,placeholder:r,value:i,onChange:h=>l(h.target.value),onBlur:o,onKeyDown:u,className:d})}function et({defaultValue:s,label:n,options:a,value:r,onValueChange:d,className:i,icon:l,showPlaceholderLabel:c=!0}){return e.jsxs(t.Select,{defaultValue:s,value:r,onValueChange:d,children:[e.jsx(t.SelectTrigger,{className:t.cn("w-full focus:ring-0 focus:ring-offset-0",i),children:e.jsxs("div",{className:"flex items-center gap-2",children:[l&&e.jsx("span",{children:l}),c&&e.jsx(t.SelectValue,{placeholder:n})]})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:n}),a.map(o=>e.jsx(t.SelectItem,{value:o.value,children:o.label},o.value))]})})]})}function Cr(s,n){return t.getSlotDefinitionForIndex(s,n)||null}function wt(s){if(typeof s=="number")return`Tab ${s+1}`;const n=s.match(/^(\d+)-(\d+)$/);if(n){const[,r,d]=n;return`Tabs ${Number(r)+1}-${Number(d)+1}`}const a=s.match(/^(\d+)\+$/);return a?`Tabs ${Number(a[1])+1}+`:`Tab ${s}`}function Sr(s){return s?Array.isArray(s)?s:[s]:[]}function es(s){var r,d;if(!s)return!1;if(s.type==="text")return!!((r=s.description)!=null&&r.trim());const n=!!((d=s.sql)!=null&&d.trim()),a=t.hasValidCardConfig(s.config);return n||a}function wr({slots:s,cards:n,minInputs:a}){const r=[],d=n.filter(Boolean).length;return a&&d<a&&r.push({type:"too-few-inputs",message:`This visual requires at least ${a} tab${a===1?"":"s"}.`}),!s||s.length===0||(s.forEach(i=>{if(!i.required)return;if(typeof i.position=="number"){const o=n[i.position];es(o)||r.push({type:"missing-required",message:`${wt(i.position)} ("${i.label}") is required but has no data configured.`});return}const l=i.position.match(/^(\d+)-(\d+)$/);if(l){const[,o,u]=l.map(Number);for(let h=o;h<=u;h+=1){const x=n[h];if(!es(x)){r.push({type:"missing-required",message:`${wt(h)} ("${i.label}") is required but has no data configured.`});break}}return}const c=i.position.match(/^(\d+)\+$/);if(c){const o=Number(c[1]);if(n.length<=o){r.push({type:"missing-required",message:`${wt(o)} ("${i.label}") is required but has no data configured.`});return}for(let u=o;u<n.length;u+=1){const h=n[u];if(!es(h)){r.push({type:"missing-required",message:`${wt(u)} ("${i.label}") is required but has no data configured.`});break}}}}),n.forEach((i,l)=>{if(!i)return;const c=Cr(s,l);if(!c||!c.expectedType)return;const o=Sr(c.expectedType);o.length!==0&&(o.includes(i.type)||r.push({type:"wrong-type",message:`${wt(l)} ("${c.label}") expects ${o.join(", ")}, but is configured as ${i.type}.`}))})),r}const Tr={table:({children:s})=>e.jsx("table",{className:"my-3 w-full border-collapse overflow-hidden rounded-md border border-border text-sm",children:s}),thead:({children:s})=>e.jsx("thead",{className:"bg-muted",children:s}),th:({children:s})=>e.jsx("th",{className:"border border-border px-3 py-2 text-left font-medium",children:s}),td:({children:s})=>e.jsx("td",{className:"border border-border px-3 py-2",children:s}),code:({children:s,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:s})}):e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-xs",children:s}),pre:({children:s})=>e.jsx(e.Fragment,{children:s})};function Pa(){var y,L,R;const s=t.useEditorStore(f=>f.card.customCardPreferences),{data:n}=t.usePluginQuery(),a=(n==null?void 0:n.plugins)||[],r=t.useEditorStore(f=>f.card),d=t.useEditorStore(f=>f.frame),{setCustomCardPreferences:i}=t.useEditorActions(),l=N.useMemo(()=>t.findCustomVisualConfigCard(d,r),[d,r]),c=l==null?void 0:l.customCardPreferences,{components:o,manifest:u}=t.useCustomVisual((c==null?void 0:c.url)||(s==null?void 0:s.url)||""),h=(y=u==null?void 0:u.visuals)==null?void 0:y.find(f=>f.name===((c==null?void 0:c.componentName)||(s==null?void 0:s.componentName))),p=t.resolveMultiInputType(l||r,h)==="multiple",m=!!l&&l.id===r.id,g=(h==null?void 0:h.minInputs)??((L=l==null?void 0:l.customCardPreferences)==null?void 0:L.minInputs),v=(h==null?void 0:h.maxInputs)??((R=l==null?void 0:l.customCardPreferences)==null?void 0:R.maxInputs),j=N.useMemo(()=>t.getCustomVisualInputCards({frame:d,configCard:l||r,isMultiInputVisual:p}),[d,l,r,p]),T=N.useMemo(()=>t.buildSlotOrderedCards(j),[j]),k=N.useMemo(()=>T.map((f,A)=>{if(!f)return null;const w=t.getSlotIndexForCard(f,A),P=t.getEffectiveCardTypeForSlot(f,w,h==null?void 0:h.slots);return{...f,type:P??f.type}}),[T,h==null?void 0:h.slots]),V=N.useMemo(()=>wr({slots:h==null?void 0:h.slots,cards:k,minInputs:g}),[h==null?void 0:h.slots,k,g]),C=N.useMemo(()=>{const f=j.findIndex(A=>(A==null?void 0:A.id)===r.id);return f<0?-1:t.getSlotIndexForCard(r,f)},[j,r]);function M(f){if(typeof f=="number")return`Tab ${f+1}`;const A=f.match(/^(\d+)-(\d+)$/);if(A){const[,P,F]=A;return`Tabs ${Number(P)+1}-${Number(F)+1}`}const w=f.match(/^(\d+)\+$/);return w?`Tabs ${Number(w[1])+1}+`:`Tab ${f}`}function S(f){return f?(Array.isArray(f)?f:[f]).join(", "):null}function I(f,A,w=[],P="",F,B,_){const z=D({key:A,defaultValue:P,settingsValue:B,sourceCard:_});return f==="input"?e.jsx($e,{className:`h-8 w-full ${t.removeRing}`,value:String(z??""),onCommit:G=>{E({key:A,value:G,settingsField:F,settingsValue:B,sourceCard:_})}},A):f==="select"?e.jsx(et,{className:"h-8 w-full",label:"",options:w,value:String(z!==void 0?z:P??""),onValueChange:G=>{E({key:A,value:G,settingsField:F,settingsValue:B,sourceCard:_})}}):null}function D({key:f,defaultValue:A,settingsValue:w,sourceCard:P}){const F=w==null?void 0:w[f];return F!==void 0?F:f==="title"&&(P==null?void 0:P.title)!==void 0?P.title:f==="description"&&(P==null?void 0:P.description)!==void 0?P.description:A}function E({key:f,value:A,settingsField:w,settingsValue:P,sourceCard:F}){const B={...P||{}},_=f==="title"&&(F==null?void 0:F.title)!==void 0,z=f==="description"&&(F==null?void 0:F.description)!==void 0;_&&A===String((F==null?void 0:F.title)??"")||z&&A===String((F==null?void 0:F.description)??"")?delete B[f]:B[f]=A,i({...s||{},[w]:B})}function b({settingsSchema:f,settingsField:A,settingsValue:w,sourceCard:P,headerLabel:F}){const B=Object.entries(f||{});return e.jsxs("div",{className:"space-y-3",children:[F&&e.jsx(t.Label,{children:F}),B.map(([_,z])=>{var G;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{children:z.title}),((G=z.docs)==null?void 0:G.description)&&e.jsx(t.TooltipProvider,{delayDuration:0,children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{className:"text-xs",children:z.docs.description})})]})})]}),I(z.ui,_,z.options,z.defaultValue,A,w,P)]},_)})]})}function O(){return e.jsxs(e.Fragment,{children:[p&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.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:h!=null&&h.slots&&h.slots.length>0?e.jsx("div",{className:"space-y-3",children:h.slots.map((f,A)=>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:M(f.position)}),e.jsx("span",{className:"text-muted-foreground",children:"•"}),e.jsx("span",{className:"font-medium",children:f.label})]}),f.description&&e.jsx("p",{className:"text-muted-foreground",children:f.description}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-muted-foreground",children:[S(f.expectedType)&&e.jsxs("span",{children:["Expected: ",S(f.expectedType)]}),f.required&&e.jsx("span",{children:"Required"})]})]},`${f.label}-${A}`))}):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."}),(g||v)&&e.jsxs("p",{children:[g?`Min ${g} tabs`:"",g&&v?" • ":"",v?`Max ${v} tabs`:""]})]})})]}),p&&V.length>0&&e.jsx(t.Alert,{className:"mt-3 border-yellow-500/40 bg-yellow-500/10 text-yellow-900 dark:text-yellow-100",children:e.jsx(t.AlertDescription,{children:e.jsx("ul",{className:"list-disc space-y-1 pl-4 text-xs",children:V.map((f,A)=>e.jsx("li",{children:f.message},`${f.type}-${A}`))})})}),h&&!p&&h.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:b({settingsSchema:h.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:r})})}),h&&p&&(h.settings||h.slotSettings)&&e.jsxs("div",{className:"mt-4 space-y-4",children:[m&&h.settings&&e.jsx("div",{className:"px-2",children:b({settingsSchema:h.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:l||r,headerLabel:"Global Settings"})}),h.slotSettings&&e.jsx("div",{className:"px-2",children:b({settingsSchema:h.slotSettings,settingsField:"slotSettings",settingsValue:s==null?void 0:s.slotSettings,sourceCard:r,headerLabel:(()=>{const f=r.tabTitle||r.title,A=C>=0?C:0,w=m?"Slot 0":`Slot ${A}`;return f?`${w}: ${f} Settings`:`${w} Settings`})()})})]})]})}return e.jsxs(t.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"",children:[e.jsxs(t.AccordionItem,{value:"plugin-settings",children:[e.jsx(t.AccordionTrigger,{children:"Plugin"}),e.jsx(t.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:[(!p||m)&&e.jsx(et,{icon:e.jsx(Sa,{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:f=>i({...s||{url:"",componentName:""},url:f})}),p&&!m&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Switch to the config tab to change the plugin or component."})]})}),((s==null?void 0:s.type)==="component"||(s==null?void 0:s.type)===void 0)&&s&&(!p||m)&&e.jsx(e.Fragment,{children:o&&e.jsx(et,{icon:e.jsx(hn,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(o==null?void 0:o.map(f=>({value:f.name,label:f.name})))||[],value:s.componentName||"",onValueChange:f=>{var P;const A=(P=u==null?void 0:u.visuals)==null?void 0:P.find(F=>F.name===f),w=o==null?void 0:o.find(F=>F.name===f);i({...s,componentName:f,visualType:(A==null?void 0:A.visualType)||(w==null?void 0:w.type)||"single",minInputs:A==null?void 0:A.minInputs,maxInputs:A==null?void 0:A.maxInputs,pluginChartType:A==null?void 0:A.chartType})}})})]})})]}),((c==null?void 0:c.componentName)||(s==null?void 0:s.componentName))&&e.jsxs(t.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(t.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:(h==null?void 0:h.name)||"Settings"}),(h==null?void 0:h.docs)&&e.jsxs(t.HoverCard,{openDelay:0,closeDelay:100,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,onClick:f=>f.stopPropagation(),children:e.jsx(t.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground transition-colors hover:text-foreground"})}),e.jsx(t.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:[h.docs.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:h.docs.description}),h.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(t.Markdown,{remarkPlugins:[t.remarkGfm],components:Tr,children:h.docs.dataSchema})})]}),(()=>{var A;const f=(A=h.docs)==null?void 0:A.useCases;return!f||f.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:f.map((w,P)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1 text-primary",children:"•"}),e.jsx("span",{children:w})]},P))})]})})()]})})]})]})}),e.jsx(t.AccordionContent,{children:O()})]})]})}function Er({colorRanges:s,setColorRanges:n}){const a={start:-1/0,end:100,color:""};function r(l,c,o){const u=[...s];u[l]={...u[l],[c]:o},n(u)}function d(l){const c=[...s];c.splice(l,1),n(c)}function i(){n([...s,a])}return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{children:"Color Range"}),e.jsx(t.Button,{onClick:i,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(t.Plus,{className:"size-3"})})]}),s.map((l,c)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(t.Input,{onChange:o=>r(c,"start",o.target.value),value:l.start,className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(t.Input,{value:l.end,onChange:o=>r(c,"end",o.target.value),className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx(t.Input,{onChange:o=>r(c,"color",o.target.value),value:l.color,className:t.cn(`h-7 min-w-14 p-0 ${t.removeRing}`),type:"color",list:"presetColors"}),e.jsxs("datalist",{id:"presetColors",children:[e.jsx("option",{children:t.colors.green[600]}),e.jsx("option",{children:t.colors.red[500]}),e.jsx("option",{children:t.colors.yellow[400]}),e.jsx("option",{children:t.colors.orange[500]})]}),e.jsx(t.Button,{onClick:()=>d(c),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(t.X,{className:"size-3"})})]},c))]})}function Ir(){var h,x,p,m,g;const s=t.useEditorStore(v=>v.card.preferences),n=t.useEditorStore(v=>v.actions.setCardPreferences),a=t.useEditorStore(v=>v.card),r=t.hasValidCardConfig(a.config),d=t.useEditorStore(v=>v.actions.setNumberFormat);t.useEditorStore(v=>{var j,T;return(T=(j=v.card.preferences)==null?void 0:j.formatNumber)==null?void 0:T.decimalPlaces});const i=t.useEditorStore(v=>{var j,T;return(T=(j=v.card.preferences)==null?void 0:j.formatNumber)==null?void 0:T.locale}),l=t.useEditorStore(v=>{var j,T;return(T=(j=v.card.preferences)==null?void 0:j.formatNumber)==null?void 0:T.currency});t.useEditorStore(v=>v.actions.setFilterOnClickField);const c=t.useEditorStore(v=>{var j,T;return(T=(j=v.card.preferences)==null?void 0:j.formatNumber)==null?void 0:T.colorRanges})||[],o=t.useEditorStore(v=>v.actions.setColorRanges),u=[...new Set(t.LOCALE_CURRENCY_PAIRS.map(v=>v.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(t.Checkbox,{checked:!!((h=s==null?void 0:s.formatNumber)!=null&&h.enabled),onCheckedChange:v=>{n({...s,formatNumber:{...s==null?void 0:s.formatNumber,enabled:v}})}}),e.jsx(t.Label,{children:"Format Number"})]}),(((x=s==null?void 0:s.formatNumber)==null?void 0:x.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(t.Label,{children:"Locale"}),e.jsxs(t.Select,{value:i||"none",onValueChange:v=>{var j,T,k;return d(((j=s==null?void 0:s.formatNumber)==null?void 0:j.decimalPlaces)||0,((T=s==null?void 0:s.formatNumber)==null?void 0:T.currency)||"",v,((k=s==null?void 0:s.formatNumber)==null?void 0:k.suffix)||"")},children:[e.jsx(t.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Format"}),e.jsx(t.SelectItem,{value:"none",children:"Auto"},"none"),t.LOCALE_CURRENCY_PAIRS.map(v=>e.jsx(t.SelectItem,{value:v.locale,children:v.locale},v.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Currency"}),e.jsxs(t.Select,{value:l||"none",onValueChange:v=>{var j,T,k;console.log("currency",v),d(((j=s==null?void 0:s.formatNumber)==null?void 0:j.decimalPlaces)||0,v==="none"?"":v,((T=s==null?void 0:s.formatNumber)==null?void 0:T.locale)||"",((k=s==null?void 0:s.formatNumber)==null?void 0:k.suffix)||"")},children:[e.jsx(t.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Currency"}),e.jsx(t.SelectItem,{value:"none",children:"None"},"none"),u.map(v=>e.jsx(t.SelectItem,{value:v,children:v},v))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Decimals"}),e.jsxs(t.Select,{value:((m=(p=s==null?void 0:s.formatNumber)==null?void 0:p.decimalPlaces)==null?void 0:m.toString())||"0",onValueChange:v=>{var j,T,k;return d(Number(v),((j=s==null?void 0:s.formatNumber)==null?void 0:j.currency)||"",((T=s==null?void 0:s.formatNumber)==null?void 0:T.locale)||"",((k=s==null?void 0:s.formatNumber)==null?void 0:k.suffix)||"")},children:[e.jsx(t.SelectTrigger,{className:"col-span-3 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:["0","1","2","3","4"].map(v=>e.jsx(t.SelectItem,{value:v,children:v},v))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Suffix"}),e.jsx(t.Input,{value:((g=s==null?void 0:s.formatNumber)==null?void 0:g.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:v=>{var j,T,k;return d(((j=s==null?void 0:s.formatNumber)==null?void 0:j.decimalPlaces)||0,((T=s==null?void 0:s.formatNumber)==null?void 0:T.currency)||"",((k=s==null?void 0:s.formatNumber)==null?void 0:k.locale)||"",v.target.value)}})]})]})]})}),e.jsx(t.Separator,{className:"my-3"}),e.jsx(Er,{colorRanges:c,setColorRanges:o})]})]})}const Dr={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 Va(s){return Dr[s]}function kr({chartType:s,showDocsLink:n=!0}){const a=Va(s);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,d)=>e.jsxs("tr",{className:d<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(t.ExternalLink,{className:"h-3 w-3"})]})]}):null}function Ar({chartType:s}){return Va(s)?e.jsxs(t.HoverCard,{openDelay:200,children:[e.jsx(t.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(t.HoverCardContent,{className:"w-80 p-4",side:"left",align:"start",sideOffset:8,children:e.jsx(kr,{chartType:s})})]}):null}function $t({chartType:s,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(Ar,{chartType:s})]})}function Mr(){return e.jsxs("div",{className:"space-y-6 px-6 py-4",children:[e.jsx($t,{chartType:"kpi"}),e.jsx("section",{children:e.jsx(Ir,{})})]})}function ua({children:s,summary:n,open:a,className:r}){return e.jsxs("details",{open:a,className:t.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(t.Label,{children:n}),e.jsx(t.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:s})]})}function za(){const[s,n]=N.useState([]),a=t.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:d}=t.useEditorStore(u=>u.actions),i=t.useEditorStore(u=>u.queryResultColumns);t.useEditorStore(u=>{var h;return(h=u.card.preferences)==null?void 0:h.filterOnClickColumnIndex}),N.useEffect(()=>{i&&n(new Array(i.length).fill(!1))},[i]);function l(u,h){var x,p;h?a!=null&&a.onClickFilter&&((x=a==null?void 0:a.onClickFilter)==null?void 0:x.length)>0?d({...a,onClickFilter:[...a.onClickFilter,{columnIndex:u,expression:""}]}):d({...a,onClickFilter:[{columnIndex:u,expression:""}]}):(d({...a,onClickFilter:(p=a==null?void 0:a.onClickFilter)==null?void 0:p.filter(m=>m.columnIndex!==u)}),n(m=>{const g=[...m];return g[u]=!1,g}))}function c(u,h){var p;const x=(p=a==null?void 0:a.onClickFilter)==null?void 0:p.map(m=>m.columnIndex===u?{...m,expression:h.target.value}:m);d({...a,onClickFilter:x})}function o(u){var h,x,p,m;if(s!=null&&s[u]||(x=(h=a==null?void 0:a.onClickFilter)==null?void 0:h.find(g=>g.columnIndex===u))!=null&&x.expression)return e.jsx(t.Input,{value:(m=(p=a==null?void 0:a.onClickFilter)==null?void 0:p.find(g=>g.columnIndex===u))==null?void 0:m.expression,onChange:g=>c(u,g),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:i==null?void 0:i.map((u,h)=>{var x,p;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(t.Checkbox,{checked:!!((x=a==null?void 0:a.onClickFilter)!=null&&x.find(m=>m.columnIndex===h)),onCheckedChange:m=>l(h,m)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:u}),e.jsx("div",{className:"flex items-center gap-2",children:((p=a==null?void 0:a.onClickFilter)==null?void 0:p.find(m=>m.columnIndex===h))&&e.jsx(t.Pencil,{onClick:()=>{n(m=>{const g=[...m];return g[h]=!m[h],g})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),o(h)]})},u)})})}const Lr=[{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"}],Fr=["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"],Or=Fr.map(s=>({label:s,value:s}));function Rr(){var o,u,h,x,p,m,g,v,j,T,k,V,C,M,S,I,D,E;const s=t.useEditorStore(b=>b.card),n=(u=(o=s==null?void 0:s.preferences)==null?void 0:o.mapVisualOptions)==null?void 0:u.topoJsonUrl,[a,r]=N.useState(((x=(h=s==null?void 0:s.preferences)==null?void 0:h.mapVisualOptions)==null?void 0:x.customTopoJsonUrl)||""),{setCardPreferences:d}=t.useEditorActions(),{data:i}=t.useTopoJson(s),l=Object.keys((i==null?void 0:i.objects)||{}).map(b=>({label:b,value:b}))||[],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($t,{chartType:"map"}),e.jsx(ua,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(et,{className:"h-9",options:c,onValueChange:b=>{console.log("value",b),d({...s.preferences,mapVisualOptions:{topoJsonUrl:b}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(t.Input,{onChange:b=>{r(b.target.value)},onBlur:()=>{var b;console.log("onBlur",a),d({...s.preferences,mapVisualOptions:{...(b=s.preferences)==null?void 0:b.mapVisualOptions,customTopoJsonUrl:a}})},value:a,className:`h-9 w-full ${t.removeRing}`,placeholder:"Custom URL"}),i&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Map Object"}),e.jsx(et,{className:"h-9",options:l,value:((m=(p=s.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:m.objectKey)||"",label:"Map Object",onValueChange:b=>{var O;d({...s.preferences,mapVisualOptions:{...(O=s.preferences)==null?void 0:O.mapVisualOptions,objectKey:b}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Projection"}),e.jsx(et,{className:"h-9",options:Lr,value:((v=(g=s.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:v.projection)||"",label:"Projection",onValueChange:b=>{var O;d({...s.preferences,mapVisualOptions:{...(O=s.preferences)==null?void 0:O.mapVisualOptions,projection:b}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Colors"}),e.jsx(et,{className:"h-9",options:Or,value:((T=(j=s.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:T.colorScale)||"",label:"Select Color Scale",onValueChange:b=>{var O;d({...s.preferences,mapVisualOptions:{...(O=s.preferences)==null?void 0:O.mapVisualOptions,colorScale:b}})}})]})]})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(ua,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:.1,value:((V=(k=s.preferences)==null?void 0:k.mapVisualOptions)==null?void 0:V.projectionScale)||1,onChange:b=>{var O;d({...s.preferences,mapVisualOptions:{...(O=s.preferences)==null?void 0:O.mapVisualOptions,projectionScale:Number(b.target.value)}})}}),e.jsx(t.Label,{children:"X"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((S=(M=(C=s.preferences)==null?void 0:C.mapVisualOptions)==null?void 0:M.projectionOffset)==null?void 0:S[0])||0,onChange:b=>{var O,y,L,R;d({...s.preferences,mapVisualOptions:{...(O=s.preferences)==null?void 0:O.mapVisualOptions,projectionOffset:[Number(b.target.value),((R=(L=(y=s.preferences)==null?void 0:y.mapVisualOptions)==null?void 0:L.projectionOffset)==null?void 0:R[1])||0]}})}}),e.jsx(t.Label,{children:"Y"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((E=(D=(I=s.preferences)==null?void 0:I.mapVisualOptions)==null?void 0:D.projectionOffset)==null?void 0:E[1])||0,onChange:b=>{var O,y,L,R;d({...s.preferences,mapVisualOptions:{...(O=s.preferences)==null?void 0:O.mapVisualOptions,projectionOffset:[((R=(L=(y=s.preferences)==null?void 0:y.mapVisualOptions)==null?void 0:L.projectionOffset)==null?void 0:R[0])||0,Number(b.target.value)]}})}})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(za,{})]})}function _a({color:s,onColorChange:n,onClose:a}){const[r,d]=N.useState(0),[i,l]=N.useState(100),[c,o]=N.useState(50),[u,h]=N.useState(s);N.useEffect(()=>{const j=ma(s);if(j){const T=xa(j.r,j.g,j.b);d(T.h),l(T.s),o(T.l),h(s)}},[s]);const x=j=>{d(j),m(j,i,c)},p=j=>{const T=j.currentTarget.getBoundingClientRect(),k=Math.max(0,Math.min(1,(j.clientX-T.left)/T.width)),V=Math.max(0,Math.min(1,(j.clientY-T.top)/T.height)),C=k*100,M=(1-V)*100;l(C),o(M),m(r,C,M)},m=(j,T,k)=>{const V=Pr(j,T,k),C=Br(V.r,V.g,V.b);h(C)},g=j=>{if(h(j),/^#[0-9A-Fa-f]{6}$/.test(j)){const T=ma(j);if(T){const k=xa(T.r,T.g,T.b);d(k.h),l(k.s),o(k.l)}}},v=()=>{/^#[0-9A-Fa-f]{6}$/.test(u)&&(n(u),a())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:p,onMouseMove:j=>{j.buttons===1&&p(j)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${i}%`,top:`${100-c}%`,backgroundColor:u}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:j=>x(Number(j.target.value)),className:"w-full h-4 rounded-lg appearance-none cursor-pointer",style:{background:"linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"}})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"HEX"}),e.jsx(t.Input,{value:u,onChange:j=>g(j.target.value),placeholder:"#000000",className:"font-mono"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:s}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:u}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(t.Button,{variant:"outline",onClick:a,children:"Cancel"}),e.jsx(t.Button,{onClick:v,children:"OK"})]})]})}function ma(s){const n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(s);return n?{r:parseInt(n[1],16),g:parseInt(n[2],16),b:parseInt(n[3],16)}:null}function Br(s,n,a){return"#"+((1<<24)+(s<<16)+(n<<8)+a).toString(16).slice(1)}function xa(s,n,a){s/=255,n/=255,a/=255;const r=Math.max(s,n,a),d=Math.min(s,n,a);let i=0,l=0;const c=(r+d)/2;if(r!==d){const o=r-d;switch(l=c>.5?o/(2-r-d):o/(r+d),r){case s:i=((n-a)/o+(n<a?6:0))/6;break;case n:i=((a-s)/o+2)/6;break;case a:i=((s-n)/o+4)/6;break}}return{h:Math.round(i*360),s:Math.round(l*100),l:Math.round(c*100)}}function Pr(s,n,a){s/=360,n/=100,a/=100;let r,d,i;if(n===0)r=d=i=a;else{const l=(u,h,x)=>(x<0&&(x+=1),x>1&&(x-=1),x<.16666666666666666?u+(h-u)*6*x:x<.5?h:x<.6666666666666666?u+(h-u)*(.6666666666666666-x)*6:u),c=a<.5?a*(1+n):a+n-a*n,o=2*a-c;r=l(o,c,s+1/3),d=l(o,c,s),i=l(o,c,s-1/3)}return{r:Math.round(r*255),g:Math.round(d*255),b:Math.round(i*255)}}const ha=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],Vr=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function tt({value:s,onChange:n,label:a}){const[r,d]=N.useState(!1),[i,l]=N.useState(!1),c=()=>{const o=ha.find(u=>u.value===s);return o?o.color:s.startsWith("#")?s:ha[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Popover,{open:r,onOpenChange:d,children:[e.jsx(t.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(t.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:Vr.map(o=>e.jsx("button",{className:t.cn("h-5 w-5 rounded border-2 transition-all",c()===o?"border-gray-900":"border-transparent"),style:{backgroundColor:o},onClick:()=>{n(o),d(!1)},children:e.jsx("span",{className:"sr-only",children:o})},o))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{l(!0),d(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a})]}),i&&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:()=>l(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(_a,{color:c(),onColorChange:o=>{n(o),l(!1)},onClose:()=>l(!1)})})]})]})}function zt(s){return s==="currency"?2:s==="percent"?1:s==="scientific"?2:0}function pa(s,n){if(!n||n==="auto")return{type:"auto"};const a={...s,type:n,multiplyBy:n==="percent"?s.multiplyBy:void 0,percentValueMode:n==="percent"?s.percentValueMode:void 0};return n&&["number","currency","percent","scientific"].includes(n)&&s.decimalPlaces===void 0&&s.minimumFractionDigits===void 0&&s.maximumFractionDigits===void 0?os(a,zt(n)):a}function os(s,n){return{...s,decimalPlaces:n,minimumFractionDigits:n,maximumFractionDigits:n}}const zr=["auto","number","currency","percent","scientific","date"],_r=[{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"}],qr=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"en-IN",label:"English (India)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"},{value:"ja-JP",label:"Japanese"},{value:"ko-KR",label:"Korean"},{value:"ru-RU",label:"Russian"},{value:"ar-SA",label:"Arabic"},{value:"hi-IN",label:"Hindi"},{value:"nl-NL",label:"Dutch"},{value:"sv-SE",label:"Swedish"}],$r=s=>s.charAt(0).toUpperCase()+s.slice(1);function gt({formatOptions:s={},onFormatOptionsChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const d=s.type||"auto",i=d==="auto"?s:pa(s,d),l=m=>{m.stopPropagation()},c=(m,g)=>{n({...i,[m]:g})},[o,u]=N.useState(()=>String(i.decimalPlaces??zt(d))),[h,x]=N.useState(()=>i.multiplyBy!==void 0?String(i.multiplyBy):""),p=m=>{n(pa(s,m))};return N.useEffect(()=>{u(String(i.decimalPlaces??zt(d)))},[i.decimalPlaces,d]),N.useEffect(()=>{x(i.multiplyBy!==void 0?String(i.multiplyBy):"")},[i.multiplyBy]),e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[a&&e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(t.Select,{value:d,onValueChange:m=>p(m),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",onClick:l,onPointerDown:l,onKeyDown:l,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:zr.map(m=>e.jsx(t.SelectItem,{value:m,className:"text-xs",children:m==="auto"?"Auto (Default)":$r(m)},m))})]})]}),d!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent","scientific"].includes(d)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{type:"text",inputMode:"numeric",min:"0",max:"10",placeholder:"0",value:o,onClick:l,onPointerDown:l,onKeyDown:l,onChange:m=>{const g=m.target.value.replace(/[^\d]/g,"");u(g),g!==""&&n(os(i,Math.max(0,Math.min(10,parseInt(g,10)))))},onBlur:()=>{if(o!=="")return;const m=zt(d);u(String(m)),n(os(i,m))},className:"h-8 text-xs"})})]}),d==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(t.Select,{value:s.currency||"USD",onValueChange:m=>c("currency",m),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:l,onPointerDown:l,onKeyDown:l,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:_r.map(m=>e.jsx(t.SelectItem,{value:m.value,className:"text-xs",children:m.label},m.value))})]})]}),["number","currency"].includes(d)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(t.SmallSwitch,{checked:s.useSuffix??!1,onClick:m=>m.stopPropagation(),onCheckedChange:m=>c("useSuffix",m)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(t.Select,{value:s.locale||"en-US",onValueChange:m=>c("locale",m),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:l,onPointerDown:l,onKeyDown:l,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:qr.map(m=>e.jsx(t.SelectItem,{value:m.value,className:"text-xs",children:m.label},m.value))})]})]}),d==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{placeholder:"e.g., $",value:s.prefix||"",onClick:l,onPointerDown:l,onKeyDown:l,onChange:m=>c("prefix",m.target.value),className:"h-8 text-xs"})})]}),d==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{placeholder:"e.g., units",value:s.suffix||"",onClick:l,onPointerDown:l,onKeyDown:l,onChange:m=>c("suffix",m.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(d)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Negative in ()"}),e.jsx(t.SmallSwitch,{checked:s.negativeInParentheses??!1,onClick:m=>m.stopPropagation(),onCheckedChange:m=>c("negativeInParentheses",m)})]}),d==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{type:"text",inputMode:"decimal",placeholder:"100",value:h,onClick:l,onPointerDown:l,onKeyDown:l,onChange:m=>{const g=m.target.value.replace(/[^0-9.]/g,"");x(g),c("multiplyBy",g?parseFloat(g):void 0)},className:"h-8 text-xs"})})]}),d==="date"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Format"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{type:"text",placeholder:"MM/DD/YYYY",value:s.dateFormat||"",onClick:l,onPointerDown:l,onKeyDown:l,onChange:m=>c("dateFormat",m.target.value),className:"h-8 text-xs"})})]})]})]})}function xs({value:s,onChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const d=t.toTFormatOptions(t.fromSemanticFormat(s))||{},i=l=>{n(t.fromTFormatOptions(l))};return e.jsx(gt,{formatOptions:d,onFormatOptionsChange:i,showTitle:a,title:r})}function Kr(){const s=t.useDashboardStore(c=>c.dashboard.filters),n=t.useEditorStore(c=>c.frame),{setFrame:a}=t.useEditorActions(),{filterableFields:r}=t.useFilterableFields(),{assignFilter:d}=t.useAssignFilter();function i(c){const o=d(c,"frame");a({...n,filterId:o})}const l=s==null?void 0:s.find(c=>c.id===n.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Card Filter"}),e.jsx(Gr,{onSelect:i,columns:r}),l&&e.jsx(t.FilterHeader,{filter:l})]})}function Gr({columns:s,onSelect:n}){var c;const[a,r]=Vt.useState(!1),[d,i]=Vt.useState(""),l=Vt.useCallback(o=>[o.label,o.name,o.qualifiedEntityName].filter(Boolean).join(" "),[]);return e.jsxs(t.Popover,{open:a,onOpenChange:r,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between font-normal",children:[d?((c=s.find(o=>o.id===d))==null?void 0:c.label)||d:"Select Column...",e.jsx(t.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No column found."}),e.jsx(t.CommandGroup,{children:s==null?void 0:s.map(o=>e.jsxs(t.CommandItem,{value:l(o),onSelect:()=>{const u=o.id===d?"":o.id;i(u),r(!1),u&&n(o)},children:[o.label||o.name,e.jsx(t.CheckIcon,{className:t.cn("ml-auto h-4 w-4",d===o.id?"opacity-100":"opacity-0")})]},o.id))})]})]})})]})}const Ur=[{value:"difference",label:"Difference"},{value:"change",label:"Change (%)"},{value:"change_difference",label:"Change + Difference"},{value:"ratio",label:"Ratio"}],Hr=[{value:"arrow_badge",label:"Arrow + Badge"},{value:"arrow",label:"Arrow Only"},{value:"badge",label:"Badge Only"},{value:"none",label:"None"}];function Qr({cardType:s="table"}){var h,x,p,m,g;const n=t.useEditorStore(v=>v.card),a=t.useEditorStore(v=>{var j;return(j=v.card)==null?void 0:j.preferences}),r=t.useEditorStore(v=>v.actions.setCardPreferences),d=((h=n.config)==null?void 0:h.metricColumns)||[],i=d.some(v=>v.comparisonType&&v.comparisonType!=="none"),l=((x=a==null?void 0:a.tableVisualOptions)==null?void 0:x.metricComparison)||{},c=v=>{r({...a,tableVisualOptions:{...a==null?void 0:a.tableVisualOptions,metricComparison:{...l,...v}}})},o={increase:((p=l.colors)==null?void 0:p.increase)||"green",decrease:((m=l.colors)==null?void 0:m.decrease)||"red",neutral:((g=l.colors)==null?void 0:g.neutral)||"neutral"},u=v=>{r({...a,allowDownload:v})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsxs(t.Accordion,{defaultValue:["item-3"],type:"multiple",children:[i&&e.jsxs(t.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(t.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(Ta,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison Settings"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated As"}),e.jsxs(t.Select,{value:l.calculatedAs||"change_difference",onValueChange:v=>c({calculatedAs:v}),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ur.map(v=>e.jsx(t.SelectItem,{value:v.value,className:"text-xs",children:v.label},v.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Number Format"}),e.jsx(gt,{formatOptions:l.formatOptions||{},onFormatOptionsChange:v=>c({formatOptions:v}),showTitle:!1})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator Style"}),e.jsxs(t.Select,{value:l.indicatorStyle||"arrow_badge",onValueChange:v=>c({indicatorStyle:v}),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Hr.map(v=>e.jsx(t.SelectItem,{value:v.value,className:"text-xs",children:v.label},v.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Colors"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(tt,{value:o.increase,onChange:v=>c({colors:{...o,increase:v}}),label:"Increase"}),e.jsx(tt,{value:o.decrease,onChange:v=>c({colors:{...o,decrease:v}}),label:"Decrease"}),e.jsx(tt,{value:o.neutral,onChange:v=>c({colors:{...o,neutral:v}}),label:"No Change"})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Lower is Better"}),e.jsx(t.Checkbox,{checked:l.lowerIsBetter||!1,onCheckedChange:v=>c({lowerIsBetter:!!v})})]})]})]}),d.length>0&&e.jsxs(t.AccordionItem,{value:"metric-formats",className:"border-none",children:[e.jsx(t.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsx("span",{children:"Metric Formats"})}),e.jsx(t.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:d.map(v=>e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 p-3",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:v.label||v.name}),e.jsx(xs,{value:v.format,onChange:j=>{var k;const T=(((k=n.config)==null?void 0:k.metricColumns)||[]).map(V=>V.id===v.id?{...V,format:j}:V);t.useEditorStore.getState().actions.updateCardConfig(n.id,{metricColumns:T})},showTitle:!1})]},v.id))})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Click Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(za,{}),e.jsx(Kr,{})]})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Checkbox,{onCheckedChange:u,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 Jr(){var r;const s=t.useEditorStore(d=>d.card.preferences),{setCardPreferences:n}=t.useEditorStore(d=>d.actions);function a(d){n({...s,textVisualOptions:{...s==null?void 0:s.textVisualOptions,isDynamicText:d==="dynamic"}})}return e.jsxs(t.RadioGroup,{value:(r=s==null?void 0:s.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(t.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(t.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function Yr(){return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx($t,{chartType:"text"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Text Type"}),e.jsx(Jr,{})]})]})}const Wr=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function Xr(){var M,S,I,D,E,b,O,y,L,R;const s=t.useEditorStore(f=>f.card),n=t.useEditorStore(f=>{var A;return(A=f.card)==null?void 0:A.preferences}),a=Ae.useEffectiveEditorCardType(),{setCardPreferences:r,updateCardInFrame:d}=t.useEditorActions(),i=N.useMemo(()=>a!==s.type?{...s,type:a}:s,[s,a]),{data:l}=t.useDashboardCardQuery(i),[c,o]=N.useState({}),[u,h]=N.useState(null),[x,p]=N.useState(null),m=N.useMemo(()=>{var P,F,B,_,z,G,W;if(!(l!=null&&l.records)||l.records.length===0)return[];const f=a==="stackedBar"||a==="stackedLine",A=a==="bar"||a==="line"||a==="horizontalBar"||a==="bullet"||a==="combo"||a==="area"||a==="stackedArea",w=((P=s==null?void 0:s.config)==null?void 0:P.pivotByColumns)&&s.config.pivotByColumns.length>0;if((f||A)&&w){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const U=new Set;return l.pivotSchema.forEach(Y=>{Y.alias&&U.add(Y.alias)}),Array.from(U)}if(l.records.length>0){const U=l.records[0],Y=Object.keys(U),se=new Set;(F=s==null?void 0:s.config)!=null&&F.groupByColumns&&s.config.groupByColumns.forEach(re=>{se.add(re.label||re.name),se.add(re.alias||re.name)});const ee=new Set;return(B=s==null?void 0:s.config)!=null&&B.metricColumns&&s.config.metricColumns.forEach(re=>{const ne=re.alias||re.name;ee.add(ne),ee.add(`${ne}_count`),ee.add(`${ne}_sum`),ee.add(`${ne}_avg`),ee.add(`${ne}_min`),ee.add(`${ne}_max`);const xe=re.entityName||re.qualifiedEntityName;xe&&(ee.add(`${xe}_${ne}`),ee.add(`${xe}_${ne}_count`))}),Y.filter(re=>!se.has(re)&&!ee.has(re))}}if((A||f)&&!w&&((z=(_=s==null?void 0:s.config)==null?void 0:_.metricColumns)!=null&&z.length))return s.config.metricColumns.map(U=>U.alias||U.label||U.name);if((W=(G=s==null?void 0:s.config)==null?void 0:G.groupByColumns)!=null&&W.length){const U=s.config.groupByColumns[0],Y=U.label||U.name,se=new Set;return l.records.forEach(ee=>{const ce=ee[Y];ce!=null&&se.add(String(ce))}),Array.from(se)}return[]},[l,(M=s==null?void 0:s.config)==null?void 0:M.groupByColumns,(S=s==null?void 0:s.config)==null?void 0:S.pivotByColumns,(I=s==null?void 0:s.config)==null?void 0:I.metricColumns,s==null?void 0:s.type]),g=N.useMemo(()=>t.getDefaultChartColors(),[]);N.useEffect(()=>{const f={};m.forEach((A,w)=>{f[A]=t.getColorForValue(A,w,n==null?void 0:n.colorConfig)}),o(f)},[m,n==null?void 0:n.colorConfig,g]);const v=(f,A)=>{const w={...c,[f]:A};o(w);const P={...n||{},colorConfig:{segments:w}};r(P);const F={...s,preferences:P};d(F)},j=(f,A)=>{var z;const w=g[A%g.length],{[f]:P,...F}=((z=n==null?void 0:n.colorConfig)==null?void 0:z.segments)||{},B={...n||{},colorConfig:{segments:F}};r(B);const _={...s,preferences:B};d(_),o(G=>({...G,[f]:w}))};if(!m.length||!((s==null?void 0:s.type)==="stackedBar"||(s==null?void 0:s.type)==="stackedLine"?((E=(D=s==null?void 0:s.config)==null?void 0:D.groupByColumns)==null?void 0:E.length)||((O=(b=s==null?void 0:s.config)==null?void 0:b.pivotByColumns)==null?void 0:O.length):(L=(y=s==null?void 0:s.config)==null?void 0:y.groupByColumns)==null?void 0:L.length)||["table","kpi","text","custom","heatmap"].includes(a))return null;const V=()=>{const f={...n||{},colorConfig:{segments:{}}};r(f);const A={...s,preferences:f};d(A);const w={};m.forEach((P,F)=>{w[P]=t.getColorForValue(P,F,void 0)}),o(w)},C=Object.keys(((R=n==null?void 0:n.colorConfig)==null?void 0:R.segments)||{}).length>0;return e.jsxs(t.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(t.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:"Colors"})]})}),e.jsx(t.AccordionContent,{className:"",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("div",{className:"flex items-center justify-between",children:C&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:V,children:[e.jsx(ls,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:m.map((f,A)=>{const w=t.isDefaultColor(c[f],A),P=!w;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Popover,{open:u===f,onOpenChange:F=>h(F?f:null),children:[e.jsx(t.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[f]}})}),e.jsx(t.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:g.slice(0,10).map((F,B)=>e.jsxs("button",{className:t.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",c[f]===F?"border-gray-900":"border-transparent"),style:{backgroundColor:F},onClick:()=>{v(f,F),h(null)},children:[B===A%g.length&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-white/90 px-0.5 text-[8px] font-bold text-gray-900 shadow-sm",children:"D"})}),e.jsx("span",{className:"sr-only",children:F})]},`default-${B}`))})]}),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:Wr.map((F,B)=>e.jsx("button",{className:t.cn("h-5 w-5 rounded border transition-all hover:scale-110",c[f]===F?"border-2 border-gray-900":F==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:F},onClick:()=>{v(f,F),h(null)},children:e.jsx("span",{className:"sr-only",children:F})},`preset-${B}`))})]}),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:()=>{p({value:f,color:c[f]}),h(null)},children:"Custom color"}),!w&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{j(f,A),h(null)},children:[e.jsx(ls,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:f}),P&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},f)})}),x&&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:()=>p(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(_a,{color:x.color,onColorChange:f=>{v(x.value,f),p(null)},onClose:()=>p(null)})})]})]})})]})}function Je({value:s,onSave:n,placeholder:a="",type:r="text",className:d=""}){const[i,l]=N.useState(s??""),[c,o]=N.useState(!1);N.useEffect(()=>{l(s??"")},[s]);const u=()=>{n(i),o(!1)},h=()=>{l(s??""),o(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${d}`,children:[e.jsx(t.Input$1,{placeholder:a,type:r,value:c?i:s??"",onChange:x=>{l(x.target.value),o(!0)},onFocus:()=>o(!0),onClick:x=>x.stopPropagation(),className:"h-8 text-xs",onPointerDown:x=>x.stopPropagation(),onKeyDown:x=>{x.stopPropagation(),x.key==="Enter"&&c&&i!==s?u():x.key==="Escape"&&h()},"aria-label":a||"Edit field"}),c&&i!==s&&e.jsxs(e.Fragment,{children:[e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:u,children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:h,children:e.jsx(t.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function ts({axis:s,label:n,type:a,config:r,onChange:d,defaultTitle:i,hidePosition:l}){var g,v,j,T,k,V,C,M,S,I,D,E,b,O;const c=t.normalizeContextFormatMode({formatMode:r==null?void 0:r.formatMode,formatOptions:r==null?void 0:r.formatOptions}),o=(y,L)=>{d({...r??{},[y]:L})},u=(y,L)=>{var w,P,F,B;const R=y==="enabled"&&L===!0,f=(w=r==null?void 0:r.name)==null?void 0:w.text,A=R&&!f&&i;d({...r??{},name:{...r==null?void 0:r.name,enabled:y==="enabled"?L:((P=r==null?void 0:r.name)==null?void 0:P.enabled)??!1,text:y==="text"?L:A?i:f,fontSize:y==="fontSize"?L:(F=r==null?void 0:r.name)==null?void 0:F.fontSize,fontWeight:y==="fontWeight"?L:(B=r==null?void 0:r.name)==null?void 0:B.fontWeight}})},h=(y,L)=>{var R,f;d({...r??{},labels:{enabled:y==="enabled"?L:((R=r==null?void 0:r.labels)==null?void 0:R.enabled)??!0,rotation:y==="rotation"?L:(f=r==null?void 0:r.labels)==null?void 0:f.rotation}})},x=(y,L)=>{d({...r??{},scale:{...r==null?void 0:r.scale,[y]:L===""?"auto":Number(L)}})},p=s==="x"?["auto","top","bottom"]:["auto","left","right"],m=["auto","0","45","90","-45","-90"];return e.jsxs(t.AccordionItem,{value:`${s}-axis`,className:"border-b-0",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx(t.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(t.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:y=>o("enabled",y),onClick:y=>y.stopPropagation()})]}),e.jsxs(t.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(t.Checkbox,{id:`${s}-title-enabled`,checked:((g=r==null?void 0:r.name)==null?void 0:g.enabled)??!1,onCheckedChange:y=>u("enabled",y===!0)}),e.jsx(t.Label,{htmlFor:`${s}-title-enabled`,className:"text-xs font-medium cursor-pointer",children:"TITLE"})]}),((v=r==null?void 0:r.name)==null?void 0:v.enabled)&&e.jsxs("div",{className:"space-y-2 pl-6",children:[e.jsx(Je,{placeholder:`${n} title`,value:((j=r==null?void 0:r.name)==null?void 0:j.text)||"",onSave:y=>u("text",y),className:""}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Size"}),e.jsx("div",{className:"w-14",children:e.jsx(Je,{type:"number",placeholder:"12",value:String(((T=r==null?void 0:r.name)==null?void 0:T.fontSize)||12),onSave:y=>u("fontSize",Number(y)||12),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Weight"}),e.jsxs(t.Select,{value:((k=r==null?void 0:r.name)==null?void 0:k.fontWeight)||"normal",onValueChange:y=>u("fontWeight",y),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(t.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]})]})]})]}),!l&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(t.Select,{value:(r==null?void 0:r.position)||"auto",onValueChange:y=>o("position",y),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:p.map(y=>e.jsx(t.SelectItem,{value:y,className:"text-xs",children:y==="auto"?"Auto (Default)":t.titleCase(y)},y))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(t.SmallSwitch,{checked:((V=r==null?void 0:r.labels)==null?void 0:V.enabled)!==!1,onCheckedChange:y=>h("enabled",y)})]}),((C=r==null?void 0:r.labels)==null?void 0:C.enabled)!==!1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Rotation"}),e.jsxs(t.Select,{value:String(((M=r==null?void 0:r.labels)==null?void 0:M.rotation)||"auto"),onValueChange:y=>h("rotation",y==="auto"?"auto":Number(y)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:m.map(y=>e.jsx(t.SelectItem,{value:y,className:"text-xs",children:y==="auto"?"Auto (Default)":`${y}°`},y))})]})]})]}),a==="value"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"FORMAT"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Inherit from the bound metric by default."})]}),e.jsx(t.SmallSwitch,{checked:c==="override",onCheckedChange:y=>d({...r,formatMode:y?"override":"inherit"})})]}),c==="override"&&e.jsx(gt,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:y=>d({...r,formatMode:"override",formatOptions:y}),showTitle:!1})]}),a==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.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(t.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(Je,{type:"number",placeholder:"auto",value:((S=r==null?void 0:r.scale)==null?void 0:S.min)==="auto"||((I=r==null?void 0:r.scale)==null?void 0:I.min)===void 0?"":String(r.scale.min),onSave:y=>x("min",y),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-8 text-xs text-muted-foreground",children:"Max"}),e.jsx("div",{className:"flex-1",children:e.jsx(Je,{type:"number",placeholder:"auto",value:((D=r==null?void 0:r.scale)==null?void 0:D.max)==="auto"||((E=r==null?void 0:r.scale)==null?void 0:E.max)===void 0?"":String(r.scale.max),onSave:y=>x("max",y),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-8 text-xs text-muted-foreground",children:"Step"}),e.jsx("div",{className:"flex-1",children:e.jsx(Je,{type:"number",placeholder:"auto",value:((b=r==null?void 0:r.scale)==null?void 0:b.stepSize)==="auto"||((O=r==null?void 0:r.scale)==null?void 0:O.stepSize)===void 0?"":String(r.scale.stepSize),onSave:y=>x("stepSize",y),className:""})})]})]})]})]})]})}function ss(s,n,a){var i,l,c;if(s==="x"){const o=(l=(i=n==null?void 0:n.config)==null?void 0:i.groupByColumns)==null?void 0:l[0];return(o==null?void 0:o.label)||(o==null?void 0:o.name)||""}const r=((c=n==null?void 0:n.config)==null?void 0:c.metricColumns)||[],d=(a==null?void 0:a.datasetOptions)||[];if(s==="y"){const o=r.filter((u,h)=>{const x=d.find(p=>p.idx===h);return!x||x.yAxisId!=="y2"});return o.length===1&&(o[0].label||o[0].name)||""}if(s==="y2"){const o=r.filter((u,h)=>{const x=d.find(p=>p.idx===h);return(x==null?void 0:x.yAxisId)==="y2"});return o.length===1&&(o[0].label||o[0].name)||""}return""}function Zr(){const s=t.useEditorStore(o=>o.card),n=t.useEditorStore(o=>{var u;return(u=o.card)==null?void 0:u.preferences}),{setCardPreferences:a,updateCardInFrame:r}=t.useEditorActions(),d=Ae.useEffectiveEditorCardType();if(!s||["tornado","pyramid","kpi","treemap"].includes(d))return null;const i=t.AxisConfigurator.getAxisInfo(d,n);if(!i.hasXAxis&&!i.hasYAxis)return null;const l=(o,u)=>{let h;o==="x"?h="xAxisConfig":o==="y"?h="yAxisConfig":h="secondaryYAxisConfig";const x={...n||{},[h]:u};a(x);const p={...s,preferences:x};r(p)},c=i.hasY2Axis&&d==="combo";return e.jsxs(t.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(t.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(t.SlidersHorizontal,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Axes"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsxs(t.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[i.hasXAxis&&e.jsx(ts,{axis:"x",label:"X-Axis",type:i.xAxisType,config:t.mergeAxisConfig(t.getDefaultAxisConfig(d,"x"),n==null?void 0:n.xAxisConfig),onChange:o=>l("x",o),defaultTitle:ss("x",s,n)}),i.hasYAxis&&e.jsx(ts,{axis:"y",label:c?"Y-Axis (Left)":"Y-Axis",type:i.yAxisType,config:t.mergeAxisConfig(t.getDefaultAxisConfig(d,"y"),n==null?void 0:n.yAxisConfig),onChange:o=>l("y",o),defaultTitle:ss("y",s,n)}),c&&e.jsx(ts,{axis:"y2",label:"Y2-Axis (Right)",type:"value",config:t.mergeAxisConfig({enabled:!0,position:"right"},n==null?void 0:n.secondaryYAxisConfig),onChange:o=>l("y2",o),defaultTitle:ss("y2",s,n),hidePosition:!0})]})})]})}function el(){const s=t.useEditorStore(x=>x.card),n=Ae.useEffectiveEditorCardType(),a=t.useEditorStore(x=>{var p,m,g,v;return(v=(g=(m=(p=x.card)==null?void 0:p.preferences)==null?void 0:m.chartOptions)==null?void 0:g.plugins)==null?void 0:v.legend}),{setLegendOptions:r}=t.useEditorActions();if(!s||!t.chartSupportsLegend(n))return null;const d=t.getDefaultLegendConfig(n),i=(d==null?void 0:d.display)??!0,l=(d==null?void 0:d.position)??"top",c=(d==null?void 0:d.align)??"center",o=(x,p)=>{const m={...a,[x]:p};r(m)},u=["top","bottom","left","right"],h=["start","center","end"];return e.jsxs(t.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(t.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(jn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(t.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(t.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(t.SmallSwitch,{checked:(a==null?void 0:a.display)??i,onCheckedChange:x=>o("display",x)})]}),((a==null?void 0:a.display)??i)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(t.Select,{value:(a==null?void 0:a.position)||l,onValueChange:x=>o("position",x),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:u.map(x=>e.jsx(t.SelectItem,{value:x,className:"text-xs",children:t.titleCase(x)},x))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(t.Select,{value:(a==null?void 0:a.align)||c,onValueChange:x=>o("align",x),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:h.map(x=>e.jsx(t.SelectItem,{value:x,className:"text-xs",children:t.titleCase(x)},x))})]})]})]})]})})]})}function tl(){var L,R,f,A,w,P,F;const s=t.useEditorStore(B=>B.card),n=Ae.useEffectiveEditorCardType(),a=t.useEditorStore(B=>{var _,z;return(z=(_=B.card)==null?void 0:_.preferences)==null?void 0:z.dataLabelsConfig}),r=t.useEditorStore(B=>{var _;return(_=B.card)==null?void 0:_.preferences}),{setCardPreferences:d,updateCardInFrame:i}=t.useEditorActions();if(!s||!t.chartSupportsDataLabels(n))return null;const l=n==="bullet"?((L=r==null?void 0:r.bulletConfig)==null?void 0:L.orientation)??(((R=r==null?void 0:r.chartOptions)==null?void 0:R.indexAxis)==="x"?"vertical":"horizontal"):void 0,c=l!=null?l==="horizontal":((f=r==null?void 0:r.chartOptions)==null?void 0:f.indexAxis)==="y",o=n==="stackedBar"||n==="stackedLine",u=n==="pie"||n==="doughnut"||n==="polarArea"||n==="funnel",h=n==="bubble"||n==="scatter",x=(w=(A=r==null?void 0:r.chartOptions)==null?void 0:A.plugins)==null?void 0:w.datalabels,p=(x==null?void 0:x.display)!==!1&&((x==null?void 0:x.anchor)||(x==null?void 0:x.align)),m=t.getDefaultDataLabelsConfig(n,s.preferences),g=a??m,v=(m==null?void 0:m.enabled)??p??!1,j=(a==null?void 0:a.enabled)!==void 0?a.enabled:v,T=(B,_)=>{const W={...m??{},...a??{},[B]:_};B==="enabled"&&(W.display=_,_&&h&&!W.position&&(W.position="bottom")),B==="position"&&h&&(W.position="bottom"),B==="formatMode"&&_==="inherit"&&(W.format=void 0,W.formatOptions=void 0);const U={...s.preferences||{},dataLabelsConfig:W};d(U);const Y={...s,preferences:U};i(Y)},k=(B,_)=>{const z=a??{},W={...m??{},...z,font:{...z.font||{},[B]:_}},U={...s.preferences||{},dataLabelsConfig:W};d(U);const Y={...s,preferences:U};i(Y)},V=()=>{const B=n;return B==="stackedBar"||B==="stackedLine"||B==="pie"||B==="doughnut"?"center":c?"right":"top"},C=n!=="treemap"&&n!=="heatmap",M=n!=="treemap",S=V();let I=[];if(C)if(h)I=["bottom"];else if(o||u)I=["center"];else{const B=c?["center","left","right"]:["center","top","bottom"];I=["auto",...n==="bullet"?B:B.filter(z=>z!==S),"custom"]}const D=()=>t.titleCase(S),E=["center","start","end"],b=["center","start","end","top","bottom"],O=(g==null?void 0:g.formatMode)||(g!=null&&g.format&&!["auto"].includes(g.format)?"override":"inherit"),y=(g==null?void 0:g.format)==="none";return e.jsxs(t.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(t.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(An,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(t.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(t.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(t.SmallSwitch,{checked:j,onCheckedChange:B=>T("enabled",B)})]}),j&&e.jsxs(e.Fragment,{children:[C&&!o&&!u&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(t.Select,{value:h?(g==null?void 0:g.position)||"bottom":(g==null?void 0:g.position)||"auto",onValueChange:B=>T("position",B),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:I.map(B=>e.jsx(t.SelectItem,{value:B,className:"text-xs",children:B==="auto"?D():B==="custom"?"Custom (Advanced)":t.titleCase(B)},B))})]})]}),o&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Show Total"}),e.jsx(t.SmallSwitch,{checked:(a==null?void 0:a.showTotal)??!1,onCheckedChange:B=>T("showTotal",B)})]}),(g==null?void 0:g.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(t.Label,{className:"text-xs text-muted-foreground w-16",children:"Anchor"}),e.jsxs(t.Select,{value:(g==null?void 0:g.anchor)||"center",onValueChange:B=>T("anchor",B),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:E.map(B=>e.jsx(t.SelectItem,{value:B,className:"text-xs",children:t.titleCase(B)},B))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground w-16",children:"Align"}),e.jsxs(t.Select,{value:String((g==null?void 0:g.align)||"center"),onValueChange:B=>T("align",B),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:b.map(B=>e.jsx(t.SelectItem,{value:B,className:"text-xs",children:t.titleCase(B)},B))})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Format"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Keep this off to inherit from the bound metric."})]}),e.jsx(t.SmallSwitch,{checked:O==="override",onCheckedChange:B=>T("formatMode",B?"override":"inherit")})]}),O==="override"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Raw Value"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Show the unformatted numeric value."})]}),e.jsx(t.SmallSwitch,{checked:y,onCheckedChange:B=>{const _=a??{},G={...m??{},..._,formatMode:"override",format:B?"none":void 0,formatOptions:B?void 0:_.formatOptions},W={...s.preferences||{},dataLabelsConfig:G};d(W),i({...s,preferences:W})}})]}),!y&&e.jsx(gt,{formatOptions:(g==null?void 0:g.formatOptions)||{},onFormatOptionsChange:B=>{const G={...m??{},...a??{},formatMode:"override",format:B.type&&B.type!=="auto"?B.type:void 0,formatOptions:B},W={...s.preferences||{},dataLabelsConfig:G};d(W),i({...s,preferences:W})},showTitle:!1})]})]}),M&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Appearance"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground w-20",children:"Size"}),e.jsx("div",{className:"flex-1",children:e.jsx(Je,{type:"number",placeholder:"12",value:String(((P=g==null?void 0:g.font)==null?void 0:P.size)||12),onSave:B=>k("size",Number(B)),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground w-20",children:"Weight"}),e.jsxs(t.Select,{value:((F=g==null?void 0:g.font)==null?void 0:F.weight)||"normal",onValueChange:B=>k("weight",B),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(t.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground w-20",children:"Color"}),e.jsxs(t.Select,{value:(g==null?void 0:g.color)==="auto"||!(g!=null&&g.color)?"auto":"custom",onValueChange:B=>{B==="auto"&&T("color","auto")},children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Smart Contrast)"}),e.jsx(t.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom (Coming Soon)"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground w-20",children:"Rotation"}),e.jsx("div",{className:"flex-1",children:e.jsx(Je,{type:"number",placeholder:"0",value:String((g==null?void 0:g.rotation)||0),onSave:B=>T("rotation",Number(B)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}const fa={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%
|
|
193
|
+
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 sl(){var p,m,g,v,j,T,k,V,C,M;const s=t.useEditorStore(S=>S.card),{setCardPreferences:n}=t.useEditorActions(),a=Ae.useEffectiveEditorCardType(),r=((p=s.config)==null?void 0:p.metricColumns)||[],d=((m=s.config)==null?void 0:m.groupByColumns)||[],i=r.length===2&&d.length===0,l=r.some(S=>S.comparisonType&&S.comparisonType!=="none");if(!(a==="kpi"&&(i||l)))return null;const o=((v=(g=s.preferences)==null?void 0:g.kpiVisualOptions)==null?void 0:v.metricComparison)||{},u=S=>{var D;const I={...s.preferences,kpiVisualOptions:{...(D=s.preferences)==null?void 0:D.kpiVisualOptions,metricComparison:{...o,...S}}};n(I)},h=l||o.enabled,x=r.some(S=>S.comparisonType==="previous_period"||S.comparisonType==="same_period_last_year"||S.comparisonType==="start_vs_end");return e.jsxs(t.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(t.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(Ta,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[i&&r.length===2&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(t.SmallSwitch,{id:"enable-comparison",checked:o.enabled||!1,onCheckedChange:S=>u({enabled:S,...S&&!o.calculationType?{calculationType:"difference"}:{}})})]}),h&&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(t.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.Info,{className:"h-3 w-3 cursor-help text-muted-foreground"})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:(()=>{const S=o.calculationType||"difference",I=fa[S];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:I==null?void 0:I.label}),e.jsx("p",{children:I==null?void 0:I.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:I==null?void 0:I.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",I==null?void 0:I.example]})]})})()})]})]}),e.jsxs(t.Select,{value:o.calculationType||"difference",onValueChange:S=>u({calculationType:S}),children:[e.jsx(t.SelectTrigger,{id:"calculation-type",className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Object.entries(fa).map(([S,I])=>e.jsx(t.SelectItem,{value:S,className:"text-xs",children:I.label},S))})]})]}),e.jsx(gt,{formatOptions:o.formatOptions||{},onFormatOptionsChange:S=>u({formatOptions:S}),showTitle:!0,title:"COMPARISON FORMAT"}),(x||i)&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator"}),i&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(t.Select,{value:o.position||"right",onValueChange:S=>u({position:S}),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"right",className:"text-xs",children:"Right"}),e.jsx(t.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(t.SelectItem,{value:"top",className:"text-xs",children:"Top"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Checkbox,{id:"show-arrow",checked:o.showArrow!==!1,onCheckedChange:S=>u({showArrow:S})}),e.jsx(t.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(t.Checkbox,{id:"show-color",checked:o.showColor!==!1,onCheckedChange:S=>u({showColor:S})}),e.jsx(t.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),o.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(tt,{value:((j=o.colorConfig)==null?void 0:j.increase)||"green",onChange:S=>u({colorConfig:{...o.colorConfig,increase:S}}),label:"Primary > Secondary"}),e.jsx(tt,{value:((T=o.colorConfig)==null?void 0:T.decrease)||"red",onChange:S=>u({colorConfig:{...o.colorConfig,decrease:S}}),label:"Primary < Secondary"}),e.jsx(tt,{value:((k=o.colorConfig)==null?void 0:k.noChange)||"neutral",onChange:S=>u({colorConfig:{...o.colorConfig,noChange:S}}),label:"Primary = Secondary"})]})]}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Checkbox,{id:"conditional-label",checked:o.conditionalLabel||!1,onCheckedChange:S=>u({conditionalLabel:S})}),e.jsx(t.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),o.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(t.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(t.Input,{id:"label-increase",type:"text",value:((V=o.conditionalLabels)==null?void 0:V.increase)??"Increase",onChange:S=>u({conditionalLabels:{...o.conditionalLabels,increase:S.target.value}}),placeholder:"Increase",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(t.Label,{htmlFor:"label-decrease",className:"text-xs text-muted-foreground",children:["Primary ","<"," Secondary"]}),e.jsx(t.Input,{id:"label-decrease",type:"text",value:((C=o.conditionalLabels)==null?void 0:C.decrease)??"Decrease",onChange:S=>u({conditionalLabels:{...o.conditionalLabels,decrease:S.target.value}}),placeholder:"Decrease",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{htmlFor:"label-no-change",className:"text-xs text-muted-foreground",children:"Primary = Secondary"}),e.jsx(t.Input,{id:"label-no-change",type:"text",value:((M=o.conditionalLabels)==null?void 0:M.noChange)??"No change",onChange:S=>u({conditionalLabels:{...o.conditionalLabels,noChange:S.target.value}}),placeholder:"No change",className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{htmlFor:"label-name",className:"text-xs text-muted-foreground",children:"Previous Label"}),e.jsx(t.Input,{id:"label-name",type:"text",value:o.labelName??"",onChange:S=>u({labelName:S.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function al(){var i;const s=t.useEditorStore(l=>{var c;return(c=l.card)==null?void 0:c.type}),n=t.useEditorStore(l=>{var c;return(c=l.card)==null?void 0:c.preferences}),{setCardPreferences:a}=t.useEditorActions();if(s!=="treemap")return null;const r=((i=n==null?void 0:n.chartOptions)==null?void 0:i.treemapColorMode)??"branch",d=l=>{const c={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,treemapColorMode:l}};a(c)};return e.jsxs(t.AccordionItem,{value:"treemap-color-mode",className:"border-none",children:[e.jsx(t.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(t.TbChartTreemap,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Treemap Colors"})]})}),e.jsx(t.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:e.jsxs(t.RadioGroup,{value:r,onValueChange:l=>d(l??"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(t.RadioGroupItem,{id:"treemap-color-branch",value:"branch"}),e.jsxs(t.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(t.RadioGroupItem,{id:"treemap-color-category",value:"category"}),e.jsxs(t.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 nl=Object.keys(t.HEATMAP_PRESET_PALETTES);function rl(){const s=t.useEditorStore(p=>p.card),n=t.useEditorStore(p=>{var m;return(m=p.card)==null?void 0:m.preferences}),{setCardPreferences:a}=t.useEditorActions(),r=(s==null?void 0:s.type)==="heatmap",d=(n==null?void 0:n.heatmapConfig)||{},i=d.colorPalette??"green",l=d.legendPosition??"bottom",c=N.useMemo(()=>d.colorRange&&d.colorRange[0]&&d.colorRange[1]?[d.colorRange[0],d.colorRange[1]]:[...t.DEFAULT_HEATMAP_CUSTOM_RANGE],[d.colorRange]),o=p=>{const m={...d,...p};m.colorPalette!=="custom"?delete m.colorRange:(!m.colorRange||!m.colorRange[0]||!m.colorRange[1])&&(m.colorRange=[...t.DEFAULT_HEATMAP_CUSTOM_RANGE]),a({...n||{},heatmapConfig:m})},u=p=>{o({colorPalette:p,colorRange:p==="custom"?d.colorRange??[...t.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},h=(p,m)=>{const g=[...c];g[p]=m,o({colorPalette:"custom",colorRange:g})},x=p=>{o({legendPosition:p})};return r?e.jsxs(t.AccordionItem,{value:"heatmap-color-config",className:"border-none",children:[e.jsx(t.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(t.Grid3x3,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Heatmap Settings"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs(t.RadioGroup,{value:i,onValueChange:p=>u(p??"blue"),className:"space-y-3",children:[nl.map(p=>{const m=t.HEATMAP_PRESET_PALETTES[p];return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(t.RadioGroupItem,{id:`heatmap-${p}`,value:p}),e.jsxs(t.Label,{htmlFor:`heatmap-${p}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:m.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${m.start}, ${m.end})`}})]})]},p)}),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(t.RadioGroupItem,{id:"heatmap-custom",value:"custom"}),e.jsx(t.Label,{htmlFor:"heatmap-custom",className:"text-sm font-medium",children:"Custom colors"})]}),i==="custom"&&e.jsxs("div",{className:"flex flex-col gap-3 pl-6",children:[e.jsx(tt,{value:c[0],onChange:p=>h(0,p),label:"Start color"}),e.jsx(tt,{value:c[1],onChange:p=>h(1,p),label:"End color"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Color scale position"}),e.jsxs(t.Select,{value:l,onValueChange:p=>x(p??"bottom"),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:["top","bottom","left","right"].map(p=>e.jsx(t.SelectItem,{value:p,className:"text-xs",children:p[0].toUpperCase()+p.slice(1)},p))})]})]})]})]}):null}const ga=["poor","satisfactory","good"];function ja(s){if(!s)return;const n={...s};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 ll(){var L,R;const s=t.useEditorStore(f=>f.card.preferences),n=t.useEditorStore(f=>f.card),a=t.useEditorStore(f=>f.isDevMode),{setCardPreferences:r,setChartOrientation:d}=t.useEditorActions(),i=N.useMemo(()=>(s==null?void 0:s.bulletConfig)||{},[s==null?void 0:s.bulletConfig]),c=t.hasValidCardConfig(n==null?void 0:n.config)&&!a,[o,u]=N.useState(i.showRanges??!1),[h,x]=N.useState(i.rangesArePercentages??!1),p=i.disableAutoComparative?!1:i.comparativeMetricKey!==void 0||!c,[m,g]=N.useState(p);N.useEffect(()=>{u(i.showRanges??!1)},[i.showRanges]),N.useEffect(()=>{x(i.rangesArePercentages??!1)},[i.rangesArePercentages]);const v=i.targetValue===void 0?"":String(i.targetValue);N.useEffect(()=>{const f=i.disableAutoComparative?!1:i.comparativeMetricKey!==void 0||!c;g(f)},[i.disableAutoComparative,i.comparativeMetricKey,c]);const j=N.useMemo(()=>{var f,A;return((A=(f=n==null?void 0:n.config)==null?void 0:f.metricColumns)==null?void 0:A.map(w=>{const P=w.label||w.name||w.alias||"";return{value:P,label:P}}))||[]},[(L=n==null?void 0:n.config)==null?void 0:L.metricColumns]);N.useEffect(()=>{var z,G;if(!s||j.length===0)return;const f={};let A=!1;const w=(z=j[1])==null?void 0:z.value;!i.targetMetricKey&&w&&(f.targetMetricKey=w,A=!0);const P=(G=j[2])==null?void 0:G.value;!i.comparativeMetricKey&&!i.disableAutoComparative&&P&&(f.comparativeMetricKey=P,A=!0);const F=j.slice(3),B={...i.rangeKeys||{}};let _=!1;if(ga.forEach((W,U)=>{!B[W]&&F[U]&&(B[W]=F[U].value,_=!0)}),_&&(f.rangeKeys=B,A=!0,i.showRanges===void 0&&(f.showRanges=!0)),A){const W=ja({...i,...f});r({...s,bulletConfig:W})}},[j,i,s,r]);const T=f=>{const A=ja({...i,...f});r({...s,bulletConfig:A})},k=(f,A)=>{const w={...i.rangeKeys||{},[f]:A.trim()};A.trim()||delete w[f],T({rangeKeys:Object.keys(w).length>0?w:void 0})},V=(f,A)=>{const w=A===""?void 0:Number(A),P={...i.ranges||{}};w===void 0||Number.isNaN(w)?delete P[f]:P[f]=w,T({ranges:Object.keys(P).length?P:void 0})},C=f=>{if(f===""){T({targetValue:void 0});return}const A=Number(f);T({targetValue:Number.isNaN(A)?void 0:A})},M=(f,A)=>{const w=A.trim(),P={...i.rangeLabels||{}};w?P[f]=w:delete P[f],T({rangeLabels:Object.keys(P).length>0?P:void 0})},S=f=>{u(f),T({showRanges:f})},I=f=>{x(f),T({rangesArePercentages:f})},D=i.orientation||(((R=s==null?void 0:s.chartOptions)==null?void 0:R.indexAxis)==="y"?"horizontal":"vertical"),E=f=>{T({orientation:f}),d(f==="horizontal"?"y":"x")},b=[{value:"__none",label:"None"},...j.map(f=>({value:f.value,label:f.label}))],O=b,y=f=>{if(g(f),!f){T({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!c){T({disableAutoComparative:!1});return}if(i.comparativeMetricKey)T({disableAutoComparative:!1});else{const A=j.find(w=>w.value!==i.targetMetricKey);T({comparativeMetricKey:A==null?void 0:A.value,disableAutoComparative:!1})}};return e.jsxs(t.AccordionItem,{value:"bullet-config",className:"border-b-0",children:[e.jsx(t.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(t.BulletChartIcon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bullet Chart"})]})}),e.jsxs(t.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(t.Label,{className:"text-xs font-medium",children:"ORIENTATION"}),e.jsxs(t.Select,{value:D,onValueChange:f=>E(f),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"horizontal",className:"text-xs",children:"Horizontal"}),e.jsx(t.SelectItem,{value:"vertical",className:"text-xs",children:"Vertical"})]})]})]}),c&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"TARGET METRIC"}),e.jsxs(t.Select,{value:i.targetMetricKey||"__none",onValueChange:f=>T({targetMetricKey:f==="__none"?void 0:f}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select metric"})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"__none",className:"text-xs",children:"None"}),j.map(f=>e.jsx(t.SelectItem,{value:f.value,className:"text-xs",children:f.label},f.value))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"COMPARATIVE METRIC"}),c?e.jsxs(t.Select,{value:i.comparativeMetricKey||"__none",onValueChange:f=>T({comparativeMetricKey:f==="__none"?void 0:f,disableAutoComparative:f==="__none"}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select metric"})}),e.jsx(t.SelectContent,{children:b.map(f=>e.jsx(t.SelectItem,{value:f.value,className:"text-xs",children:f.label},f.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(t.SmallSwitch,{checked:m,onCheckedChange:f=>y(f)})]}),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(t.Label,{className:"text-xs font-medium",children:"TARGET VALUE (FALLBACK)"}),e.jsx($e,{type:"number",className:"h-8 text-xs",value:v,onCommit:C,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(t.Label,{className:"text-xs font-medium",children:"QUALITATIVE RANGES"}),e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:200,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"text-muted-foreground transition-colors hover:text-foreground",children:e.jsx(t.Info,{className:"h-3.5 w-3.5"})})}),e.jsx(t.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(t.SmallSwitch,{checked:o,onCheckedChange:S})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:h,disabled:!o,onChange:f=>I(f.target.checked),className:"h-3.5 w-3.5 accent-primary disabled:opacity-50"}),e.jsx("span",{children:"Use % of value"})]})]}),o&&e.jsx("div",{className:"space-y-3",children:ga.map(f=>{var A,w,P,F,B;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(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[f," LABEL"]}),e.jsx($e,{placeholder:`Display label (${f})`,value:((A=i.rangeLabels)==null?void 0:A[f])||"",onCommit:_=>M(f,_),className:"h-8 text-xs"})]}),c?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[f," COLUMN"]}),e.jsxs(t.Select,{value:((w=i.rangeKeys)==null?void 0:w[f])||"__none",onValueChange:_=>{_==="__none"?k(f,""):k(f,_)},children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select column"})}),e.jsx(t.SelectContent,{children:O.map(_=>e.jsx(t.SelectItem,{value:_.value,className:"text-xs",children:_.label},_.value))})]})]}):e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[f," COLUMN KEY"]}),e.jsx($e,{placeholder:"Column key",value:((P=i.rangeKeys)==null?void 0:P[f])||"",onCommit:_=>k(f,_),className:"h-8 text-xs"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[f," VALUE"]}),e.jsx($e,{type:"number",placeholder:h?"0.80":"Static value",value:((F=i.ranges)==null?void 0:F[f])===void 0?"":String((B=i.ranges)==null?void 0:B[f]),onCommit:_=>V(f,_),className:"h-8 text-xs"})]})]},f)})})]})]})]})}function ba(s){if(!s)return;const n={...s};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 ol(){var M,S,I,D,E,b,O,y,L,R,f,A;const s=t.useEditorStore(w=>w.card.preferences),n=t.useEditorStore(w=>w.card),a=Ae.useEffectiveEditorCardType(),r=t.useEditorStore(w=>w.isDevMode),{setCardPreferences:d,updateCardInFrame:i}=t.useEditorActions(),l=a==="bubble",c=a==="scatter",o=N.useMemo(()=>(s==null?void 0:s.bubbleScatterConfig)||{},[s==null?void 0:s.bubbleScatterConfig]),h=t.hasValidCardConfig(n==null?void 0:n.config)&&!r,x=N.useMemo(()=>{var w,P;return((P=(w=n==null?void 0:n.config)==null?void 0:w.metricColumns)==null?void 0:P.map(F=>{const B=F.label||F.name||F.alias||"";return{value:B,label:B}}))||[]},[(M=n==null?void 0:n.config)==null?void 0:M.metricColumns]),p=N.useMemo(()=>{var w,P;return((P=(w=n==null?void 0:n.config)==null?void 0:w.groupByColumns)==null?void 0:P.map(F=>{const B=F.label||F.name||F.alias||"";return{value:B,label:B}}))||[]},[(S=n==null?void 0:n.config)==null?void 0:S.groupByColumns]),m=N.useMemo(()=>o.enableGrouping!==void 0?o.enableGrouping:!r&&p.length>=2,[o.enableGrouping,r,p.length]),[g,v]=N.useState(m);N.useEffect(()=>{v(m)},[m]);const j=w=>{const P={...s||{},bubbleScatterConfig:w};d(P),n&&i({...n,preferences:P})},T=w=>{d(w),n&&i({...n,preferences:w})};N.useEffect(()=>{if(!s||x.length===0)return;const w={};let P=!1;if(!o.xMetricKey&&x[0]&&(w.xMetricKey=x[0].value,P=!0),!o.yMetricKey&&x[1]&&(w.yMetricKey=x[1].value,P=!0),l&&!o.radiusMetricKey&&x[2]&&(w.radiusMetricKey=x[2].value,P=!0),!o.labelKey&&p[0]&&(w.labelKey=p[0].value,P=!0),m&&!o.groupKey&&p[1]&&(w.groupKey=p[1].value,w.enableGrouping=!0,P=!0),P){const F=ba({...o,...w});j(F)}},[x,p,o,s,d,l,m]);const k=w=>{const P=ba({...o,...w});j(P)},V=w=>{v(w),k({enableGrouping:w,groupKey:w?o.groupKey:void 0})};if(!l&&!c)return null;const C=l?t.Circle:t.ChartScatter;return e.jsxs(t.AccordionItem,{value:"bubble-scatter-config",children:[e.jsx(t.AccordionTrigger,{className:"py-2 text-sm",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(C,{className:"h-4 w-4"}),e.jsxs("span",{children:[l?"Bubble":"Scatter"," Configuration"]})]})}),e.jsxs(t.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(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{children:e.jsx(t.Info,{className:"h-3 w-3"})}),e.jsx(t.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(t.Label,{className:"text-xs",children:"Label Column"}),h?e.jsxs(t.Select,{value:o.labelKey||"",onValueChange:w=>k({labelKey:w}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select label column"})}),e.jsx(t.SelectContent,{children:p.map(w=>e.jsx(t.SelectItem,{value:w.value,children:w.label},w.value))})]}):e.jsx($e,{className:"h-8 text-xs",placeholder:"Column name for labels",value:o.labelKey||"",onCommit:w=>k({labelKey:w})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Group points into series"}),e.jsx(t.SmallSwitch,{checked:g,onCheckedChange:V})]}),g&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Group By"}),h?e.jsxs(t.Select,{value:o.groupKey||"",onValueChange:w=>k({groupKey:w}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select group column"})}),e.jsx(t.SelectContent,{children:p.map(w=>e.jsx(t.SelectItem,{value:w.value,children:w.label},w.value))})]}):e.jsx($e,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:o.groupKey||"",onCommit:w=>k({groupKey:w})})]})]}),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(t.Label,{className:"text-xs",children:"X Axis"}),h?e.jsxs(t.Select,{value:o.xMetricKey||"",onValueChange:w=>k({xMetricKey:w}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select X metric"})}),e.jsx(t.SelectContent,{children:x.map(w=>e.jsx(t.SelectItem,{value:w.value,children:w.label},w.value))})]}):e.jsx($e,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:o.xMetricKey||"",onCommit:w=>k({xMetricKey:w})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Axis"}),h?e.jsxs(t.Select,{value:o.yMetricKey||"",onValueChange:w=>k({yMetricKey:w}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select Y metric"})}),e.jsx(t.SelectContent,{children:x.map(w=>e.jsx(t.SelectItem,{value:w.value,children:w.label},w.value))})]}):e.jsx($e,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:o.yMetricKey||"",onCommit:w=>k({yMetricKey:w})})]}),l&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Radius"}),h?e.jsxs(t.Select,{value:o.radiusMetricKey||"",onValueChange:w=>k({radiusMetricKey:w}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select radius metric"})}),e.jsx(t.SelectContent,{children:x.map(w=>e.jsx(t.SelectItem,{value:w.value,children:w.label},w.value))})]}):e.jsx($e,{className:"h-8 text-xs",placeholder:"Column name for radius",value:o.radiusMetricKey||"",onCommit:w=>k({radiusMetricKey:w})})]})]}),l&&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(t.Label,{className:"text-xs",children:"Scale Mode"}),e.jsxs(t.Select,{value:o.radiusScale||"sqrt",onValueChange:w=>k({radiusScale:w}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"sqrt",children:"Square Root (area-proportional)"}),e.jsx(t.SelectItem,{value:"linear",children:"Linear"}),e.jsx(t.SelectItem,{value:"fixed",children:"Fixed Size"})]})]})]}),o.radiusScale!=="fixed"&&e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Min Radius"}),e.jsx($e,{className:"h-8 text-xs",type:"number",placeholder:"5",value:((I=o.minRadius)==null?void 0:I.toString())||"",onCommit:w=>k({minRadius:w?Number(w):void 0})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Max Radius"}),e.jsx($e,{className:"h-8 text-xs",type:"number",placeholder:"30",value:((D=o.maxRadius)==null?void 0:D.toString())||"",onCommit:w=>k({maxRadius:w?Number(w):void 0})})]})]}),o.radiusScale==="fixed"&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs(t.Label,{className:"text-xs",children:["Fixed Radius: ",o.fixedRadius||10]}),e.jsx(t.Slider,{value:[o.fixedRadius||10],onValueChange:([w])=>k({fixedRadius:w}),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(t.Label,{className:"text-xs",children:["Point Size: ",o.fixedRadius||5]}),e.jsx(t.Slider,{value:[o.fixedRadius||5],onValueChange:([w])=>k({fixedRadius:w}),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(t.SmallSwitch,{checked:((b=(E=s==null?void 0:s.xAxisConfig)==null?void 0:E.name)==null?void 0:b.enabled)??!1,onCheckedChange:w=>{var B,_,z,G;const P=o.xMetricKey||"X Axis",F=o.yMetricKey||"Y Axis";T({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{enabled:w,text:((_=(B=s==null?void 0:s.xAxisConfig)==null?void 0:B.name)==null?void 0:_.text)||P}},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{enabled:w,text:((G=(z=s==null?void 0:s.yAxisConfig)==null?void 0:z.name)==null?void 0:G.text)||F}}})}})]}),((y=(O=s==null?void 0:s.xAxisConfig)==null?void 0:O.name)==null?void 0:y.enabled)&&e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"X Title"}),e.jsx($e,{className:"h-8 text-xs",placeholder:o.xMetricKey||"X Axis",value:((R=(L=s==null?void 0:s.xAxisConfig)==null?void 0:L.name)==null?void 0:R.text)||"",onCommit:w=>{var P;T({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{...(P=s==null?void 0:s.xAxisConfig)==null?void 0:P.name,enabled:!0,text:w||o.xMetricKey||"X Axis"}}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Title"}),e.jsx($e,{className:"h-8 text-xs",placeholder:o.yMetricKey||"Y Axis",value:((A=(f=s==null?void 0:s.yAxisConfig)==null?void 0:f.name)==null?void 0:A.text)||"",onCommit:w=>{var P;T({...s??{},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{...(P=s==null?void 0:s.yAxisConfig)==null?void 0:P.name,enabled:!0,text:w||o.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const il=[{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 cl(){const s=t.useEditorStore(p=>p.card),n=t.useEditorStore(p=>{var m;return(m=p.card)==null?void 0:m.preferences}),{setCardPreferences:a}=t.useEditorActions(),r=(s==null?void 0:s.type)==="funnel",d=(n==null?void 0:n.funnelConfig)||{},i=d.percentMode??"percentOfTotal",l=d.shrinkFraction??1,c=d.labelThreshold??0,o=p=>{const m={...d,...p};a({...n||{},funnelConfig:m})},u=p=>{o({percentMode:p})},h=p=>{o({shrinkFraction:p[0]})},x=p=>{o({labelThreshold:p[0]})};return r?e.jsxs(t.AccordionItem,{value:"funnel-config",className:"border-none",children:[e.jsx(t.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(t.Filter,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Funnel Settings"})]})}),e.jsxs(t.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(t.Label,{className:"text-xs font-medium",children:"PERCENTAGE MODE"}),e.jsx(t.RadioGroup,{value:i,onValueChange:p=>u(p),className:"space-y-2",children:il.map(p=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(t.RadioGroupItem,{id:`funnel-${p.value}`,value:p.value,className:"mt-0.5"}),e.jsxs(t.Label,{htmlFor:`funnel-${p.value}`,className:"flex flex-col gap-0.5 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:p.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:p.description})]})]},p.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.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(t.Slider,{value:[l],onValueChange:h,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(l*100),"%"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.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(t.Slider,{value:[c],onValueChange:x,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 Kt(){const s=t.useEditorStore(i=>i.card),{data:n}=t.useDashboardCardQuery(s),{keys:a}=t.getKeys((n==null?void 0:n.records)||[]),r=a.slice(1).filter(i=>!t.METADATA_KEYS.includes(i));let d=r;if(["stackedBar","stackedLine"].includes(s.type)){const i=t.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:l}=t.getKeys(i);d=l.slice(1)}return{transformedMetricKeys:d,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}const dl=[{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"}],ul=[{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)"}],ml=["center","start","end"],xl=["center","start","end","top","bottom"];function Gt({config:s,onChange:n,isHorizontal:a=!1,showAutoFormat:r=!0,positionOptions:d,showAppearance:i=!0}){var g,v,j,T,k,V;const l=d??(a?["auto","center","left","right","custom"]:["auto","center","top","bottom","custom"]),c=r?["auto","number","currency","percent","none"]:["number","currency","percent","none"],o=(C,M)=>{const S={...s,[C]:M};n(S)},u=(C,M)=>{const S={...s,font:{...(s==null?void 0:s.font)||{},[C]:M}};n(S)},h=(C,M)=>{const S={...s,formatOptions:{...(s==null?void 0:s.formatOptions)||{},[C]:M}};n(S)},x=()=>a?"Right":"Top",p=s||{},m=p.format||(r?"auto":"number");return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(t.Select,{value:p.position||"auto",onValueChange:C=>o("position",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:l.map(C=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:C==="auto"?x():C==="custom"?"Custom (Advanced)":t.titleCase(C)},C))})]})]}),p.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(t.Label,{className:"text-xs",children:"Anchor"}),e.jsxs(t.Select,{value:p.anchor||"center",onValueChange:C=>o("anchor",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ml.map(C=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:t.titleCase(C)},C))})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Align"}),e.jsxs(t.Select,{value:String(p.align||"center"),onValueChange:C=>o("align",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:xl.map(C=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:t.titleCase(C)},C))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Format"}),e.jsxs(t.Select,{value:m,onValueChange:C=>o("format",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:c.map(C=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:C==="auto"&&r?"Auto (Use Axis)":C==="none"?"None (Raw Value)":t.titleCase(C)},C))})]})]}),!["auto","none"].includes(m)&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[["number","currency","percent"].includes(m)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Decimals"}),e.jsx("div",{className:"w-16",children:e.jsx(Je,{type:"number",placeholder:"0",value:String(((g=p.formatOptions)==null?void 0:g.decimalPlaces)??(m==="currency"?2:m==="percent"?1:0)),onSave:C=>h("decimalPlaces",Number(C)),className:""})})]}),m==="currency"&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Currency"}),e.jsxs(t.Select,{value:((v=p.formatOptions)==null?void 0:v.currency)||"USD",onValueChange:C=>h("currency",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:dl.map(C=>e.jsx(t.SelectItem,{value:C.value,className:"text-xs",children:C.label},C.value))})]})]}),["number","currency"].includes(m)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Abbreviate (K, M, B)"}),e.jsx(t.SmallSwitch,{checked:((j=p.formatOptions)==null?void 0:j.useSuffix)??!1,onCheckedChange:C=>h("useSuffix",C)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Locale"}),e.jsxs(t.Select,{value:((T=p.formatOptions)==null?void 0:T.locale)||"en-US",onValueChange:C=>h("locale",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ul.map(C=>e.jsx(t.SelectItem,{value:C.value,className:"text-xs",children:C.label},C.value))})]})]})]}),i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.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(t.Label,{className:"text-xs",children:"Size"}),e.jsx("div",{className:"w-16",children:e.jsx(Je,{type:"number",placeholder:"12",value:String(((k=p.font)==null?void 0:k.size)||12),onSave:C=>u("size",Number(C)),className:""})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Weight"}),e.jsxs(t.Select,{value:((V=p.font)==null?void 0:V.weight)||"normal",onValueChange:C=>u("weight",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(t.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Color"}),e.jsxs(t.Select,{value:p.color==="auto"||!p.color?"auto":"custom",onValueChange:C=>{C==="auto"&&o("color","auto")},children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Contrast)"}),e.jsx(t.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.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(Je,{type:"number",placeholder:"0",value:String(p.rotation||0),onSave:C=>o("rotation",Number(C)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"°"})]})]})]})]})]})}const hl=[{type:"bar",icon:t.ChartColumnIncreasing,label:"Bar"},{type:"line",icon:t.ChartLine,label:"Line"}],pl=[0,1,2,3,4,5,6,8,10],fl=[{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 │"}],gl=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function jl(){return t.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type})!=="combo"?null:e.jsxs(t.AccordionItem,{value:"combo-series",className:"border-b-0",children:[e.jsx(t.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(t.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsx(bl,{})})]})}function bl(){const{transformedMetricKeys:s}=Kt();return s.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:s.map((n,a)=>e.jsx(vl,{metricKey:n,idx:a},n))})}function vl({metricKey:s,idx:n}){var T;const[a,r]=N.useState(!1),d=t.useEditorStore(k=>{var V;return(V=k.card)==null?void 0:V.preferences}),i=t.useEditorStore(k=>{var V,C;return(C=(V=k.card)==null?void 0:V.preferences)==null?void 0:C.datasetOptions}),l=i==null?void 0:i.find(k=>k.idx===n),{setCardPreferences:c}=t.useEditorStore(k=>k.actions),o=(l==null?void 0:l.type)||"bar",u=(l==null?void 0:l.yAxisId)||"y",h=((T=l==null?void 0:l.dataLabels)==null?void 0:T.enabled)??!1,x=o==="line"?t.ChartLine:t.ChartColumnIncreasing;function p(k){const V={idx:n,type:o,yAxisId:u,dataLabels:l==null?void 0:l.dataLabels,...k};if(!l)c({...d||{},datasetOptions:[...i||[],V]});else{const C=i==null?void 0:i.map(M=>M.idx===n?{...M,...V}:M);c({...d||{},datasetOptions:C})}}function m(k){p({type:k})}function g(k){p({yAxisId:k})}function v(k){p({dataLabels:{...l==null?void 0:l.dataLabels,enabled:k}})}function j(k){p({dataLabels:k})}return e.jsx(t.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(t.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(t.ChevronRight,{className:t.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:s,children:s})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[e.jsxs("span",{className:t.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(x,{className:"h-3 w-3"}),o==="line"?"Line":"Bar"]}),e.jsx("span",{className:t.cn("rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:u==="y2"?"Y2":"Y1"})]})]})}),e.jsx(t.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(t.Label,{className:"text-xs text-muted-foreground",children:"Chart Type"}),e.jsx("div",{className:"flex gap-2",children:hl.map(({type:k,icon:V,label:C})=>{const M=o===k;return e.jsxs("button",{onClick:()=>m(k),className:t.cn("flex items-center gap-2 rounded-md border px-3 py-1.5 text-xs transition-colors",M?"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:C})]},k)})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Axis"}),e.jsxs(t.Select,{value:u,onValueChange:k=>g(k),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-20 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"y",className:"text-xs",children:"Y1 (Left)"}),e.jsx(t.SelectItem,{value:"y2",className:"text-xs",children:"Y2 (Right)"})]})]})]})]}),o==="line"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.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(t.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(t.Select,{value:(l==null?void 0:l.lineStyle)||"solid",onValueChange:k=>p({lineStyle:k}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:gl.map(({value:k,label:V})=>e.jsx(t.SelectItem,{value:k,className:"text-xs",children:V},k))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(t.Select,{value:String((l==null?void 0:l.pointRadius)??3),onValueChange:k=>p({pointRadius:Number(k)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:pl.map(k=>e.jsx(t.SelectItem,{value:String(k),className:"text-xs",children:k===0?"None":k},k))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(t.Select,{value:(l==null?void 0:l.pointStyle)||"circle",onValueChange:k=>p({pointStyle:k}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:fl.map(({value:k,label:V})=>e.jsx(t.SelectItem,{value:k,className:"text-xs",children:V},k))})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(t.SmallSwitch,{checked:h,onCheckedChange:v})]}),h&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Gt,{config:l==null?void 0:l.dataLabels,onChange:j,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const as=[{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"}],yl=[0,1,2,3,4,5,6,8,10],Nl=[{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 Sl(s){return s==null?"origin":s===!1?"false":s}function wl(){const s=t.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type});return s!=="area"&&s!=="stackedArea"?null:e.jsxs(t.AccordionItem,{value:"area-series",className:"border-b-0",children:[e.jsx(t.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(t.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsx(Tl,{})})]})}function Tl(){const{transformedMetricKeys:s}=Kt();return s.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:s.map((n,a)=>e.jsx(El,{metricKey:n,idx:a},n))})}function El({metricKey:s,idx:n}){var v;const[a,r]=N.useState(!1),d=t.useEditorStore(j=>{var T;return(T=j.card)==null?void 0:T.preferences}),i=t.useEditorStore(j=>{var T,k;return(k=(T=j.card)==null?void 0:T.preferences)==null?void 0:k.datasetOptions}),l=i==null?void 0:i.find(j=>j.idx===n),{setCardPreferences:c}=t.useEditorStore(j=>j.actions),o=Sl(l==null?void 0:l.fill),u=((v=l==null?void 0:l.dataLabels)==null?void 0:v.enabled)??!1,h=as.find(j=>j.value===o)||as[0];function x(j){const T={idx:n,fill:o,dataLabels:l==null?void 0:l.dataLabels,...j};if(!l)c({...d||{},datasetOptions:[...i||[],T]});else{const k=i==null?void 0:i.map(V=>V.idx===n?{...V,...T}:V);c({...d||{},datasetOptions:k})}}function p(j){x({fill:j==="false"?!1:j})}function m(j){x({dataLabels:{...l==null?void 0:l.dataLabels,enabled:j}})}function g(j){x({dataLabels:j})}return e.jsx(t.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(t.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(t.ChevronRight,{className:t.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:s,children:s})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:e.jsxs("span",{className:t.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(t.ChartArea,{className:"h-3 w-3"}),h.label.split(" ")[0]]})})]})}),e.jsx(t.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(t.Label,{className:"text-xs text-muted-foreground",children:"Fill Target"}),e.jsxs(t.Select,{value:o,onValueChange:j=>p(j),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:as.map(j=>e.jsx(t.SelectItem,{value:j.value,className:"text-xs",children:e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{children:j.label})})},j.value))})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.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(t.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(t.Select,{value:(l==null?void 0:l.lineStyle)||"solid",onValueChange:j=>x({lineStyle:j}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Cl.map(({value:j,label:T})=>e.jsx(t.SelectItem,{value:j,className:"text-xs",children:T},j))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(t.Select,{value:String((l==null?void 0:l.pointRadius)??3),onValueChange:j=>x({pointRadius:Number(j)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:yl.map(j=>e.jsx(t.SelectItem,{value:String(j),className:"text-xs",children:j===0?"None":j},j))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(t.Select,{value:(l==null?void 0:l.pointStyle)||"circle",onValueChange:j=>x({pointStyle:j}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Nl.map(({value:j,label:T})=>e.jsx(t.SelectItem,{value:j,className:"text-xs",children:T},j))})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(t.SmallSwitch,{checked:u,onCheckedChange:m})]}),u&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Gt,{config:l==null?void 0:l.dataLabels,onChange:g,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Il=[0,1,2,3,4,5,6,8,10],Dl=[{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 │"}],ns=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function kl(){return t.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type})!=="line"?null:e.jsxs(t.AccordionItem,{value:"line-series",className:"border-b-0",children:[e.jsx(t.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(t.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsx(Al,{})})]})}function Al(){const{transformedMetricKeys:s}=Kt();return s.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:s.map((n,a)=>e.jsx(Ml,{metricKey:n,idx:a},n))})}function Ml({metricKey:s,idx:n}){var j;const[a,r]=N.useState(!1),d=t.useEditorStore(T=>{var k;return(k=T.card)==null?void 0:k.preferences}),i=t.useEditorStore(T=>{var k,V;return(V=(k=T.card)==null?void 0:k.preferences)==null?void 0:V.datasetOptions}),l=i==null?void 0:i.find(T=>T.idx===n),{setCardPreferences:c}=t.useEditorStore(T=>T.actions),o=(l==null?void 0:l.lineStyle)||"solid",u=(l==null?void 0:l.pointRadius)??3,h=(l==null?void 0:l.pointStyle)||"circle",x=((j=l==null?void 0:l.dataLabels)==null?void 0:j.enabled)??!1,p=ns.find(T=>T.value===o)||ns[0];function m(T){const k={idx:n,lineStyle:o,pointRadius:u,pointStyle:h,dataLabels:l==null?void 0:l.dataLabels,...T};if(!l)c({...d||{},datasetOptions:[...i||[],k]});else{const V=i==null?void 0:i.map(C=>C.idx===n?{...C,...k}:C);c({...d||{},datasetOptions:V})}}function g(T){m({dataLabels:{...l==null?void 0:l.dataLabels,enabled:T}})}function v(T){m({dataLabels:T})}return e.jsx(t.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(t.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(t.ChevronRight,{className:t.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:s,children:s})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:e.jsxs("span",{className:t.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(t.TrendingUp,{className:"h-3 w-3"}),p.label.split(" ")[0]]})})]})}),e.jsx(t.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(t.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(t.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(t.Select,{value:o,onValueChange:T=>m({lineStyle:T}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ns.map(({value:T,label:k})=>e.jsx(t.SelectItem,{value:T,className:"text-xs",children:k},T))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(t.Select,{value:String(u),onValueChange:T=>m({pointRadius:Number(T)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Il.map(T=>e.jsx(t.SelectItem,{value:String(T),className:"text-xs",children:T===0?"None":T},T))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(t.Select,{value:h,onValueChange:T=>m({pointStyle:T}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Dl.map(({value:T,label:k})=>e.jsx(t.SelectItem,{value:T,className:"text-xs",children:k},T))})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(t.SmallSwitch,{checked:x,onCheckedChange:g})]}),x&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Gt,{config:l==null?void 0:l.dataLabels,onChange:v,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Ll=[0,2,4,6,8,10,12,16,20];function Fl(){const s=t.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type});return!s||!["bar","horizontalBar","stackedBar"].includes(s)?null:e.jsxs(t.AccordionItem,{value:"bar-series",className:"border-b-0",children:[e.jsx(t.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(t.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsx(Ol,{})})]})}function Ol(){const{transformedMetricKeys:s}=Kt();return s.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:s.map((n,a)=>e.jsx(Rl,{metricKey:n,idx:a},n))})}function Rl({metricKey:s,idx:n}){var g;const[a,r]=N.useState(!1),d=t.useEditorStore(v=>{var j;return(j=v.card)==null?void 0:j.type}),i=t.useEditorStore(v=>{var j;return(j=v.card)==null?void 0:j.preferences}),l=t.useEditorStore(v=>{var j,T;return(T=(j=v.card)==null?void 0:j.preferences)==null?void 0:T.datasetOptions}),c=l==null?void 0:l.find(v=>v.idx===n),{setCardPreferences:o}=t.useEditorStore(v=>v.actions),u=(c==null?void 0:c.borderRadius)??0,h=((g=c==null?void 0:c.dataLabels)==null?void 0:g.enabled)??!1;function x(v){const j={idx:n,borderRadius:u,dataLabels:c==null?void 0:c.dataLabels,...v};if(!c)o({...i||{},datasetOptions:[...l||[],j]});else{const T=l==null?void 0:l.map(k=>k.idx===n?{...k,...j}:k);o({...i||{},datasetOptions:T})}}function p(v){x({dataLabels:{...c==null?void 0:c.dataLabels,enabled:v}})}function m(v){x({dataLabels:v})}return e.jsx(t.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(t.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(t.ChevronRight,{className:t.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:s,children:s})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:u>0&&e.jsxs("span",{className:t.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(t.ChartColumn,{className:"h-3 w-3"}),"r:",u]})})]})}),e.jsx(t.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(t.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(t.Label,{className:"text-xs text-muted-foreground",children:"Corner Radius"}),e.jsxs(t.Select,{value:String(u),onValueChange:v=>x({borderRadius:Number(v)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ll.map(v=>e.jsx(t.SelectItem,{value:String(v),className:"text-xs",children:v===0?"None":`${v}px`},v))})]})]})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(t.SmallSwitch,{checked:h,onCheckedChange:p})]}),h&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Gt,{config:c==null?void 0:c.dataLabels,onChange:m,isHorizontal:d==="horizontalBar",showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Bl=[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 │"}],Vl=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function zl(){const s=t.useEditorStore(c=>c.card),n=t.useEditorStore(c=>{var o;return(o=c.card)==null?void 0:o.preferences}),a=Ae.useEffectiveEditorCardType(),r=n==null?void 0:n.lineStyleConfig,{setCardPreferences:d,updateCardInFrame:i}=t.useEditorActions();if(!s||!["line","area","stackedArea"].includes(a))return null;const l=(c,o)=>{const u={...n||{},lineStyleConfig:{...r,[c]:o}};d(u),i({...s,preferences:u})};return e.jsxs(t.AccordionItem,{value:"line-style",className:"border-b-0",children:[e.jsx(t.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(In,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Line Style"})]})}),e.jsx(t.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(t.Label,{className:"text-xs font-medium",children:"Line Pattern"}),e.jsxs(t.Select,{value:(r==null?void 0:r.lineStyle)||"solid",onValueChange:c=>l("lineStyle",c),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Vl.map(({value:c,label:o})=>e.jsx(t.SelectItem,{value:c,className:"text-xs",children:o},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Point Size"}),e.jsxs(t.Select,{value:String((r==null?void 0:r.pointRadius)??3),onValueChange:c=>l("pointRadius",Number(c)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Bl.map(c=>e.jsx(t.SelectItem,{value:String(c),className:"text-xs",children:c===0?"None":c},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Point Shape"}),e.jsxs(t.Select,{value:(r==null?void 0:r.pointStyle)||"circle",onValueChange:c=>l("pointStyle",c),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Pl.map(({value:c,label:o})=>e.jsx(t.SelectItem,{value:c,className:"text-xs",children:o},c))})]})]})]})})]})}const _l=[0,2,4,6,8,10,12,16,20],ql=[{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%"}],$l=[{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 s=t.useEditorStore(c=>c.card),n=t.useEditorStore(c=>{var o;return(o=c.card)==null?void 0:o.preferences}),a=Ae.useEffectiveEditorCardType(),r=n==null?void 0:n.barStyleConfig,{setCardPreferences:d,updateCardInFrame:i}=t.useEditorActions();if(!s||!["bar","horizontalBar","stackedBar"].includes(a))return null;const l=(c,o)=>{const u={...n||{},barStyleConfig:{...r,[c]:o}};d(u),i({...s,preferences:u})};return e.jsxs(t.AccordionItem,{value:"bar-style",className:"border-b-0",children:[e.jsx(t.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(t.ChartColumn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bar Style"})]})}),e.jsx(t.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(t.Label,{className:"text-xs font-medium",children:"Corner Radius"}),e.jsxs(t.Select,{value:String((r==null?void 0:r.borderRadius)??0),onValueChange:c=>l("borderRadius",Number(c)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:_l.map(c=>e.jsx(t.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(t.Label,{className:"text-xs font-medium",children:"Bar Width"}),e.jsxs(t.Select,{value:String((r==null?void 0:r.barPercentage)??.9),onValueChange:c=>l("barPercentage",Number(c)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ql.map(({value:c,label:o})=>e.jsx(t.SelectItem,{value:c,className:"text-xs",children:o},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Category Width"}),e.jsxs(t.Select,{value:String((r==null?void 0:r.categoryPercentage)??.8),onValueChange:c=>l("categoryPercentage",Number(c)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:$l.map(({value:c,label:o})=>e.jsx(t.SelectItem,{value:c,className:"text-xs",children:o},c))})]})]})]})})]})}function Gl(){const s=t.useEditorStore(a=>{var r,d;return(d=(r=a==null?void 0:a.card)==null?void 0:r.preferences)==null?void 0:d.sortChart}),{setSortChart:n}=t.useEditorActions();return e.jsxs(t.AccordionItem,{value:"stacked-sort",children:[e.jsx(t.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.ArrowUpDown,{className:"h-4 w-4"}),"Sort"]})}),e.jsx(t.AccordionContent,{className:"space-y-4 px-1",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Sort Order"}),e.jsx(et,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"Ascending",value:"asc"},{label:"Descending",value:"desc"}],value:s||"none",onValueChange:a=>{n(a)}})]})})]})}const Ul=["kpi"],va={none:"None",previous_period:"Previous Period",same_period_last_year:"Same Period Last Year",start_vs_end:"Start vs End",target:"Target"},rs=2;function nt(s){return typeof s=="string"?s.trim().toLowerCase():((s==null?void 0:s.id)||(s==null?void 0:s.qualifiedFieldName)||(s==null?void 0:s.name)||(s==null?void 0:s.label)||"").trim().toLowerCase()}function Hl(s){if(!(s!=null&&s.name)||!(s!=null&&s.dataType)||s.role==="metric")return!1;const n=t.getDataType(s.dataType);return["date","string","boolean"].includes(n)}function Ql(s){return{...s,role:"groupby"}}function Jl(){var k,V;const s=t.useEditorStore(C=>C.card),n=t.useEditorStore(C=>C.actions.updateCardConfig),a=Ae.useEffectiveEditorCardType(),{scopedFields:r}=t.useScopedFields(),d=((k=s.config)==null?void 0:k.metricColumns)||[],i=((V=s.config)==null?void 0:V.summary)||{},l=i.breakdownDimensions||[],c=Ul.includes(a),o=d.length>0,u=i.enabled===!0,h=c&&o,{comparisonType:x}=t.getEffectiveComparisonSettings(s.config,a),p=va[x]||va.none,m=Array.from(new Map(r.filter(Hl).map(C=>[nt(C),Ql(C)])).values()),g=new Set(m.map(C=>nt(C))),v=new Set(l.map(C=>nt(C)).filter(C=>C&&g.has(C)));if(!c)return null;const j=C=>{n(s.id,{summary:{...i,...C}})},T=(C,M)=>{const S=nt(C),I=m.filter(E=>v.has(nt(E))),D=M?v.has(S)?I:[...I,C].slice(0,rs):I.filter(E=>nt(E)!==S);j({breakdownDimensions:D})};return e.jsxs(t.AccordionItem,{value:"summary",className:"border-none",children:[e.jsx(t.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(t.FileText,{className:"h-4 w-4"}),e.jsx("span",{children:"Summary"})]})}),e.jsxs(t.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(t.Label,{htmlFor:"summary-enabled",className:"text-xs",children:"Enable Summary"}),!o&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Add at least one metric to enable summary."})]}),e.jsx(t.SmallSwitch,{id:"summary-enabled",checked:u,disabled:!h,onCheckedChange:C=>{if(!C){j({enabled:!1,showOnCard:!1,includeInDashboardSummary:!1});return}j({enabled:!0,showOnCard:i.showOnCard??!0,includeInDashboardSummary:i.includeInDashboardSummary??!0,anomalyEnabled:i.anomalyEnabled??!0})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.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: ",p]}),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(t.Label,{htmlFor:"summary-show-on-card",className:"text-xs",children:"Show summary on card"}),e.jsx(t.SmallSwitch,{id:"summary-show-on-card",checked:i.showOnCard===!0,disabled:!u,onCheckedChange:C=>j({showOnCard:C})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"summary-include-rollup",className:"text-xs",children:"Include in dashboard summary"}),e.jsx(t.SmallSwitch,{id:"summary-include-rollup",checked:i.includeInDashboardSummary===!0,disabled:!u,onCheckedChange:C=>j({includeInDashboardSummary:C})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Breakdown Dimensions"}),e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[l.length,"/",rs]})]}),m.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:m.map(C=>{const M=nt(C),S=v.has(M),I=v.size>=rs,D=!u||!S&&I;return e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx(t.Checkbox,{id:`summary-breakdown-${M}`,checked:S,disabled:D,onCheckedChange:E=>T(C,E===!0)}),e.jsx(t.Label,{htmlFor:`summary-breakdown-${M}`,className:"cursor-pointer text-xs",children:C.label||C.name})]},M)})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"summary-anomaly",className:"text-xs",children:"Detect anomalies"}),e.jsx(t.SmallSwitch,{id:"summary-anomaly",checked:i.anomalyEnabled!==!1,disabled:!u,onCheckedChange:C=>j({anomalyEnabled:C})})]})]})]})}const Yl=[];function Wl(){var d;const s=t.useEditorStore(i=>i.card),n=((d=s==null?void 0:s.config)==null?void 0:d.metricColumns)??Yl,{updateMetricColumn:a,updateCardInFrame:r}=t.useEditorActions();return!s||s.type==="kpi"||n.length===0?null:e.jsxs(t.AccordionItem,{value:"metric-formats",className:"border-b-0",children:[e.jsx(t.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(xn,{className:"h-4 w-4"}),e.jsx("span",{children:"Metric Formats"})]})}),e.jsx(t.AccordionContent,{className:"space-y-4 pt-2",children:n.map(i=>e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 p-3",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:i.label||i.name}),e.jsx(xs,{value:i.format,onChange:l=>{var c;a(s.id,i.id,{format:l}),r({...s,config:{...s.config,metricColumns:(((c=s.config)==null?void 0:c.metricColumns)||[]).map(o=>o.id===i.id?{...o,format:l}:o)}})}})]},i.id))})]})}const Xl=new Set(["area","bar","bubble","bullet","combo","doughnut","funnel","horizontalBar","line","pie","polarArea","radar","scatter","stackedArea","stackedBar","stackedLine","tornado"]);function Zl(){const s=t.useEditorStore(o=>o.card),n=t.useEditorStore(o=>{var u;return(u=o.card)==null?void 0:u.preferences}),a=Ae.useEffectiveEditorCardType(),{setCardPreferences:r,updateCardInFrame:d}=t.useEditorActions();if(!s||!Xl.has(a||""))return null;const i=n==null?void 0:n.tooltipConfig,l=(i==null?void 0:i.formatMode)||(i==null?void 0:i.mode)||"inherit",c=o=>{const u={...n||{},tooltipConfig:{...i||{},...o}};r(u),d({...s,preferences:u})};return e.jsxs(t.AccordionItem,{value:"tooltip-format",className:"border-b-0",children:[e.jsx(t.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(t.Info,{className:"h-4 w-4"}),e.jsx("span",{children:"Tooltip Format"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Override metric format"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Keep this off to inherit from each metric."})]}),e.jsx(t.SmallSwitch,{checked:l==="override",onCheckedChange:o=>c({formatMode:o?"override":"inherit",mode:o?"override":"inherit"})})]}),l==="override"&&e.jsx(gt,{formatOptions:(i==null?void 0:i.formatOptions)||{},onFormatOptionsChange:o=>c({formatMode:"override",mode:"override",formatOptions:o}),showTitle:!1})]})]})}function qa({mode:s}){const n=t.useEditorStore(a=>{var r;return(r=a.card)==null?void 0:r.type});return e.jsxs(e.Fragment,{children:[n==="combo"&&e.jsx(jl,{}),(n==="area"||n==="stackedArea")&&e.jsx(wl,{}),n==="line"&&e.jsx(kl,{}),(n==="bar"||n==="horizontalBar"||n==="stackedBar")&&e.jsx(Fl,{}),e.jsx(zl,{}),e.jsx(Kl,{}),e.jsx(al,{}),s==="config"&&e.jsx(sl,{}),s==="config"&&e.jsx(Jl,{}),e.jsx(rl,{}),n==="bullet"&&e.jsx(ll,{}),n==="funnel"&&e.jsx(cl,{}),(n==="bubble"||n==="scatter")&&e.jsx(ol,{}),(n==="stackedBar"||n==="stackedLine")&&e.jsx(Gl,{}),e.jsx(Wl,{}),e.jsx(Xr,{}),e.jsx(Zr,{}),e.jsx(el,{}),e.jsx(tl,{}),e.jsx(Zl,{})]})}function eo(){const s=t.useEditorStore(a=>a.card),n=s==null?void 0:s.type;return n?e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx($t,{chartType:n}),e.jsx(t.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:e.jsx(qa,{mode:"dev"})})]}):null}function to(){const s=t.useEditorStore(d=>d.card),n=s.type;if(t.getVisualizationMode(s)==="dynamic")return e.jsx("div",{className:"p-6",children:e.jsxs(t.Alert,{children:[e.jsx(t.Info,{className:"h-4 w-4"}),e.jsx(t.AlertTitle,{children:"Dynamic mode manages presentation"}),e.jsx(t.AlertDescription,{children:"Built-in chart settings are hidden while this card is in dynamic mode. Query and data edits still apply, and the dynamic visual editor in the main panel controls the rendered output."})]})});function r(){switch(n){case"kpi":return e.jsx(Mr,{});case"table":return e.jsx(Qr,{});case"map":return e.jsx(Rr,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(Pa,{})});case"text":return e.jsx(Yr,{});default:return e.jsx(eo,{})}}return e.jsxs(t.ScrollArea,{className:"h-full w-full text-sm",children:[r(),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}function so(){const s=N.useRef(null),n=N.useRef(null),a=t.useEditorStore(x=>x.isShowingVisual),r=t.useEditorStore(x=>x.isDevMode),d=t.useEditorStore(x=>x.showAIDialog),[i,l]=N.useState(!1),c=a&&!d,o=c&&(!r||i),u=r&&c,h=()=>l(x=>!x);return N.useEffect(()=>{var x,p,m,g;d?((x=s.current)==null||x.resize(0),(p=n.current)==null||p.resize(0)):((m=s.current)==null||m.resize(25),(g=n.current)==null||g.resize(25))},[d]),e.jsxs(t.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:[e.jsx(t.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(Xn,{})}),e.jsx(t.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(t.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:o?e.jsxs(t.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(t.ResizablePanel,{ref:s,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(to,{})})}),!d&&e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(da,{visualAsideControl:u?{show:!0,isOpen:i,onToggle:h}:void 0})})]}):e.jsx(da,{visualAsideControl:u?{show:!0,isOpen:i,onToggle:h}:void 0})})]})}function ao(s){var Ee;t.useAIInteractionStore(q=>q.currentAIContext);const[n,a]=N.useState(""),[r,d]=N.useState(null),{authToken:i,tokenProps:l}=t.useSemaphorContext(),c=t.useEditorStore(q=>q.card.id),o=t.useEditorStore(q=>{var oe;return(oe=q==null?void 0:q.card)==null?void 0:oe.sql}),u=t.useEditorStore(q=>q.isDevMode),h=t.useEditorStore(q=>{var oe;return(oe=q==null?void 0:q.card)==null?void 0:oe.python}),{setCardPython:x,setCardSql:p,setRunSql:m,switchCardType:g,setQueryConfig:v}=t.useEditorActions(),j=t.useEditorStore(q=>q.currentAssitantScope)||[],T=t.useEditorStore(q=>q.userInputForAI),k=t.useEditorStore(q=>q.triggerAIRun),V=t.useEditorStore(q=>q.card),C=t.useEditorStore(q=>q.selectedDatabaseName),M=t.useEditorStore(q=>q.selectedTableName),S=t.useEditorStore(q=>q.selectedConnectionId),I=t.useEditorStore(q=>q.selectedSchemaName),D=t.useDashboardStore(q=>q.dashboard.aiScopeTables),{errorMessage:E,refetch:b,data:O}=t.useDashboardCardQuery(V),{setTriggerAIRun:y,setCurrentAssitantScope:L,setCardConfig:R}=t.useEditorActions(),{selectedDatamodelName:f,connectionType:A,selectedDatamodelId:w}=t.useEditorAside(),P=(Ee=t.useDashboardQuery().data)==null?void 0:Ee.assistantProfileId,F=N.useRef(t.createAssistantConversationId()),B=N.useRef(null),_=N.useRef(c),z=N.useRef(!1),G=()=>{const q=B.current;q&&(B.current=null,F.current=t.createAssistantConversationId(),q==="clear"&&U([]))},{messages:W,setMessages:U,regenerate:Y,error:se,sendMessage:ee,status:ce,addToolResult:re,stop:ne,clearError:xe}=t.useChat({transport:new t.DefaultChatTransport({api:`${l.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${i==null?void 0:i.accessToken}`}),body:()=>{const q=t.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:P,conversationId:F.current,assistantRequestId:t.createAssistantRequestId(),isDevMode:u,aiContext:q.currentAIContext,reasoningEffort:q.reasoningEffort,showReasoning:q.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:q,body:oe})=>({body:{...oe,messages:t.cleanupIncompleteMessages(q)}})}),onError:q=>{var oe;if(z.current=!1,q.name==="AbortError"||(oe=q.message)!=null&&oe.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)"),G();return}console.error("[Editor Assistant] Stream error:",q),G()},onToolCall:ue,onFinish({isAbort:q,isDisconnect:oe,isError:Ne}){z.current=!1,a(""),console.log(q?"[Editor Assistant] Stream aborted by user":oe?"[Editor Assistant] Stream disconnected (network error)":Ne?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully"),G()}}),Z=N.useCallback(q=>{z.current=!0;try{const oe=ee(q);return t.isPromiseLike(oe)?oe.catch(Ne=>{throw z.current=!1,Ne}):oe}catch(oe){throw z.current=!1,oe}},[ee]),ge=N.useCallback(()=>{z.current=!0;try{const q=Y();return t.isPromiseLike(q)?q.catch(oe=>{throw z.current=!1,oe}):q}catch(q){throw z.current=!1,q}},[Y]),ae=q=>{let oe=!1;U(Ne=>{const Be=typeof q=="function"?q(Ne):q;if(Be.length===0){if(z.current)return B.current="clear",oe=!0,Ne;B.current=null,F.current=t.createAssistantConversationId()}return Be}),oe&&ne()};N.useEffect(()=>{if(_.current!==c){if(_.current=c,z.current){B.current!=="clear"&&(B.current="rotate"),ne();return}B.current=null,F.current=t.createAssistantConversationId()}},[c,ne]),N.useEffect(()=>{k&&T&&(Z({role:"user",parts:[{type:"text",text:T}]}),y(!1))},[k,T,Z,y]);async function ue({toolCall:q}){var oe,Ne,Be,X,fe,Ce,De,Se,Pe,_e,Ze,We,Xe,le,Ie,Fe;if(["createChartFromSql","createForecast"].includes(q.toolName)){const be=((oe=q.input)==null?void 0:oe.sql)??((Ne=q.args)==null?void 0:Ne.sql),Ge=((Be=q.input)==null?void 0:Be.python)??((X=q.args)==null?void 0:X.python),Te=((fe=q.input)==null?void 0:fe.chartType)??((Ce=q.args)==null?void 0:Ce.chartType);g(Te),p(be),x(Ge),m(!0),re({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(q.toolName==="getUserSql"){if(!o){re({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"error",message:"No SQL found"}});return}re({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",sql:o,python:h||""}})}else if(q.toolName==="generateQueryConfig"){a("Generating query config...");const be=((De=q.input)==null?void 0:De.chartType)??((Se=q.args)==null?void 0:Se.chartType),Ge=((Pe=q.input)==null?void 0:Pe.queryConfig)??((_e=q.args)==null?void 0:_e.queryConfig);((Ze=q.input)==null?void 0:Ze.cardConfig)??((We=q.args)==null||We.cardConfig),g(be),R(Ge),p(void 0),x(void 0);const Te=await b();if((Xe=Te==null?void 0:Te.data)!=null&&Xe.error){re({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"error",queryConfig:Ge,message:(le=Te==null?void 0:Te.data)==null?void 0:le.error.message}});return}if((Ie=Te==null?void 0:Te.data)!=null&&Ie.records){re({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",queryConfig:Ge,message:"The data has been visualized"}});return}re({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",queryConfig:Ge,message:"The data has been visualized",records:(Fe=Te==null?void 0:Te.data)==null?void 0:Fe.records}})}else a("Analyzing...")}function Le(q){const oe=t.removeFromScopeArray(j,q);te(oe)}function te(q){const oe=t.sanitizeAIScope(q);L(oe),U(Ne=>[...Ne,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(oe)}`}]}])}function ve(){const q={databaseName:C||"",schemaName:I||"",tableName:M||"",datamodelId:w||"",datamodelName:t.resolveDatamodelName(f),connectionId:S||"",connectionType:A||""},oe=t.dedup([...j,q]);te(oe)}function ye(){const q={databaseName:C||"",schemaName:I||"",tableName:M||"",datamodelName:t.resolveDatamodelName(f),connectionId:S||"",connectionType:A||"",datamodelId:w||""};if(!t.isInAiScopeArray([...D||[],...j],q)||j.length===0){const Ne=t.dedup([...D||[],...j,q]).filter(Be=>Be.connectionId===q.connectionId);te(Ne)}}const je=!["ready","error"].includes(ce),we=t.getErrorMessage(se);return{messages:W,setMessages:ae,sendMessage:Z,regenerate:ge,isLoading:je,handleSetAIScope:ye,handleAddCurrentTableToScope:ve,removeFromCurrentSelections:Le,currentAssitantScope:j,setCurrentAssitantScope:L,stop:ne,status:ce,toolStatus:n,llmUsage:r,onFinish:s,errorMessage:we,clearError:xe}}const no=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function ya({isFullscreen:s,onFullscreenChange:n,fullscreenContainer:a}){const r=N.useRef(null),d=N.useRef(!1),[i,l]=N.useState(!1),[c,o]=N.useState(t.isDevEnv),[u,h]=N.useState(!1),[x,p]=N.useState(!1),[m,g]=N.useState(!1),v=s??m,j=t.useCurrentAIContext(),{setCurrentAIContext:T,setHasEditorEntitySelectionOverride:k}=t.useAIActions(),{clearQueue:V}=t.useQueueActions(),{clearFileAttachments:C}=t.useFileActions(),M=t.useFileAttachments("editor"),{selectedEntities:S}=t.useAssistantContextEntities("editor"),I=t.useEditorStore(le=>le.card.id),D=t.useEditorStore(le=>le.card.dataSource),E=t.useEditorStore(le=>{var Ie;return(Ie=le.card.dataSource)==null?void 0:Ie.selectedEntities}),b=t.useEditorStore(le=>le.actions.setCardSql),O=t.useEditorStore(le=>le.actions.setRunSql),y=t.useEditorStore(le=>le.showAIDialog),L=t.useDashboardStore(le=>le.handleOpenAssistantProfile),{setShowAIDialog:R,setCardPython:f}=t.useEditorActions(),{setDataSource:A}=t.useEditorActions(),{assistantProfile:w}=t.useAssistantProfile(),{messages:P,setMessages:F,sendMessage:B,isLoading:_,stop:z,status:G,llmUsage:W,errorMessage:U,clearError:Y}=ao(),[se,ee]=N.useState(""),ce=le=>{ee(le.target.value)},re=le=>{le.preventDefault();const Ie=se.trim();if(!Ie&&M.length===0)return;const Fe=[];Ie&&Fe.push({type:"text",text:Ie}),M.forEach(be=>{be.data&&Fe.push({type:"file",mediaType:be.type,filename:be.name,url:`data:${be.type};base64,${be.data}`})}),B({role:"user",parts:Fe}),ee(""),C("editor"),je({force:!0})},{visibleMessages:ne,hasMoreMessages:xe,totalMessageCount:Z,loadMoreMessages:ge,resetMessageWindow:ae}=t.useMessageWindow(P,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:ue,contentRef:Le,isAtBottom:te,hasNewMessages:ve,newMessageCount:ye,scrollToBottom:je,handleScroll:we,resetNewMessageCount:Ee}=t.useAutoScroll(ne,{threshold:40,behavior:"smooth",isStreaming:_});N.useEffect(()=>{var le;y&&!d.current&&((le=r.current)==null||le.focus()),d.current=y},[y]),N.useEffect(()=>{y&&(k(!1),T({selectedEntities:E||[]}))},[I,E,T,k,y]),t.useAutoSubmitQueue({assistantType:"editor",status:G,isLoading:_,sendMessage:B});const{hasActiveTools:q,activeToolText:oe}=t.useActiveToolStatus(P),Ne=N.useCallback(le=>{n==null||n(le),s===void 0&&g(le)},[s,n]);N.useEffect(()=>{if(!v)return;function le(Ie){Ie.key==="Escape"&&Ne(!1)}return window.addEventListener("keydown",le),()=>{window.removeEventListener("keydown",le)}},[v,Ne]);const Be=N.useCallback(le=>{B({role:"user",parts:[{type:"text",text:le}]}),je({force:!0})},[B,je]),X=N.useCallback(async()=>{const le=JSON.stringify(P??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(le),t.ue.success("Conversation copied")}catch(Ie){console.error("Failed to copy conversation",Ie),t.ue.error("Unable to copy conversation")}},[P]),fe=N.useCallback(()=>{Ne(!v)},[v,Ne]);function Ce(le,Ie){Ie==="sql"?(b(le),O(!0)):Ie==="python"&&(f(le),O(!0))}function De(){j.selectedEntities.length===0&&T({selectedEntities:S})}function Se(le){De();const Ie={role:"user",parts:[{type:"text",text:le.title+" "+le.subtitle}]};B(Ie)}function Pe(le){De(),B({role:"user",parts:[{type:"text",text:le}]})}function _e(){return e.jsxs(t.DropdownMenu,{children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.Button,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(t.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",children:[e.jsx(t.DropdownMenuLabel,{children:"Options"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsx(t.DropdownMenuCheckboxItem,{checked:i,onCheckedChange:l,children:"Token Usage"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:o,children:"Tool Invocations"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:u,onCheckedChange:h,children:"System Message"})]})]})}function Ze(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const We=(se==null?void 0:se.length)===0&&(P==null?void 0:P.filter(le=>le.role==="user").length)===0,Xe=e.jsxs("div",{"data-role":"editor-assistant",className:t.cn("flex h-full w-full flex-col justify-between px-6 py-4",v&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Ze(),L&&e.jsx(t.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:L,children:(w==null?void 0:w.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[_e(),c&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:X,children:"Copy Conversation"}),e.jsx(t.IconButton,{tooltip:v?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:fe,children:v?e.jsx(t.Minimize2,{className:"size-4"}):e.jsx(t.Maximize2,{className:"size-4"})}),e.jsx(t.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{F([]),V("editor"),Y(),ae()},children:e.jsx(t.SquarePen,{className:"size-4"})}),e.jsx(t.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{R(!1)},children:e.jsx(t.X,{className:"size-4"})})]})]}),e.jsx(t.CustomScrollArea,{ref:ue,className:"mt-2 flex min-w-0 w-full grow basis-0",onScroll:we,children:e.jsxs("div",{ref:Le,className:"min-w-0 space-y-4 py-2 pr-3","data-role":"messages",children:[xe&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:ge,className:"text-xs",children:["Load ",Math.min(5,Z-ne.length)," ","more messages (",Z-ne.length," ","hidden)"]})}),e.jsx(t.PrintMessages,{messages:ne,showTools:c,handleRun:Ce,showSystemMessage:u,onQuickReply:Be,disableQuickReplies:_}),e.jsx(t.AssistantStatus,{status:G,errorMessage:U,activeToolText:_&&q?oe:void 0})]})}),y&&!te&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(t.Button,{onClick:()=>{je({force:!0}),Ee()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(t.ChevronDown,{className:"h-4 w-4"}),ve&&ye>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:ye>9?"9+":ye})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[We&&!w&&e.jsx(t.Placeholders,{onClick:Se,placeholders:no}),e.jsx("div",{children:We&&w&&e.jsx(t.SeedQuestions,{seedQuestions:w.seedQuestions||[],handleSeedQuestionClick:Pe})})]}),e.jsx(t.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(t.ChatInputWithContext,{ref:r,setInput:ee,stop:z,input:se,handleInputChange:ce,handleSubmit:le=>{De(),re(le),je({force:!0})},isLoading:_,status:G,assistantType:"editor",onFocus:()=>{}})]}),W&&i&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",W.inputTokens," prompt tokens, ",W.outputTokens," ","completion tokens, ",W.totalTokens," total tokens"]})}),e.jsx(t.DataSourceDialog,{incomingSelectedEntities:S,open:x,onOpenChange:p,dataSource:D||t.EMPTY_DATA_SOURCE,dialogMode:"aiContext",onSaveSelectedEntities:le=>{k(!0),T({...j,selectedEntities:le})}})]});return v&&a?on.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:Xe})}),a):Xe}function ro(s,n,a){if(!n)return!1;const r=n.qualifiedFieldName,d=n.qualifiedEntityName,i=d&&n.name?`${d}.${n.name}`:r;return s.some(l=>{if(!(t.getDataType(l.dataType||"")==="date"))return!1;const o=t.getSelectedDateFilterColumn(l,a),u=o.split("."),h=u[u.length-1]||o,x=u.length>1?u.slice(0,-1).join("."):void 0,p=l.qualifiedTableName||x,m=p?`${p}.${h}`:void 0;return r?m?m===i||m.endsWith(`.${r}`):h===n.name:m?m===i:h===n.name})}function lo({aliasTemplate:s,onAliasTemplateChange:n}){var o;const[a,r]=N.useState(s),[d,i]=N.useState(!1),l=(o=t.useEditorStore(u=>{var h;return(h=u.card.config)==null?void 0:h.pivotByColumns}))==null?void 0:o[0],c=l?`e.g. Min Sales in {{${l.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.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(t.Input$1,{placeholder:c,value:d?a:s,onChange:u=>{r(u.target.value),i(!0)},onFocus:()=>i(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&d&&a!==s?(n(a),i(!1)):u.key==="Escape"&&(r(s),i(!1))},"aria-label":"Edit alias template"}),d&&a!==s&&e.jsxs(e.Fragment,{children:[e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{n(a),i(!1)},children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(s),i(!1)},children:e.jsx(t.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function oo({valueAliases:s,onValueAliasesChange:n}){const[a,r]=N.useState(null),[d,i]=N.useState(""),[l,c]=N.useState(""),o=()=>{n({...s,"":""})},u=x=>{const p={...s};delete p[x],n(p)},h=x=>{const p={...s};delete p[x],p[d]=l,n(p),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(s).map(([x,p],m)=>e.jsx("div",{className:"flex items-center gap-2",children:a===x?e.jsxs(e.Fragment,{children:[e.jsx(t.Input$1,{placeholder:"Value key",value:d,onChange:g=>i(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?h(x):g.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(t.Input$1,{placeholder:"Alias label",value:l,onChange:g=>c(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?h(x):g.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>h(x),children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(t.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(t.Input$1,{placeholder:"Value key",value:x,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(x),i(x),c(p)},"aria-label":"Edit value alias key"}),e.jsx(t.Input$1,{placeholder:"Alias label",value:p,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(x),i(x),c(p)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(x),"aria-label":"Remove value alias",children:e.jsx(t.X,{className:"h-3 w-3"})})]})},x+m)),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:o,children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function io({idx:s}){var c;const n=t.useEditorStore(o=>{var u;return(u=o.card)==null?void 0:u.preferences}),a=t.useEditorStore(o=>{var u;return(u=o.card.preferences)==null?void 0:u.datasetOptions}),r=t.useEditorStore(o=>o.actions.setCardPreferences),d=(c=n==null?void 0:n.chartOptions)==null?void 0:c.indexAxis,i=a==null?void 0:a.find(o=>o.idx===s);function l(o,u){(o==="end"||o==="start")&&t.getContrastColor(t.getCanvasBackgroundColor());const h={display:o!=="none",align:o,anchor:o,clamp:!0};if(!i)r({...n,datasetOptions:[...a||[],{idx:u,datalabels:h}]});else{const x={...i};x.datalabels=h;const p=a==null?void 0:a.map(m=>m.idx===u?x:m);r({...n,datasetOptions:p})}}return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{children:e.jsx(t.Tag,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(t.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>l("none",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(t.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>l("start",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(bn,{className:t.cn("h-4 w-4",{"rotate-90":d==="y"})})}),e.jsx("button",{onClick:()=>l("center",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(yn,{className:t.cn("h-4 w-4",{"rotate-90":d==="y"})})}),e.jsx("button",{onClick:()=>l("end",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(vn,{className:t.cn("h-4 w-4",{"rotate-90":d==="y"})})})]})})]})}function hs({children:s,className:n,delayDuration:a}){return e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:a,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:t.cn("overflow-hidden text-ellipsis whitespace-nowrap",n),children:s})}),e.jsx(t.TooltipContent,{children:s})]})})}function co(s,n=30){return s.length>n?s.slice(0,n)+"...":s}function uo({col:s,idx:n,className:a,iconClassName:r,children:d}){const i=t.useEditorStore(h=>{var x;return(x=h.card)==null?void 0:x.preferences}),l=t.useEditorStore(h=>{var x,p;return(p=(x=h.card)==null?void 0:x.preferences)==null?void 0:p.datasetOptions}),c=l==null?void 0:l.find(h=>h.idx===n),{setCardPreferences:o}=t.useEditorStore(h=>h.actions);function u(h){if(!c)o({...i,datasetOptions:[...l||[],{idx:n,type:h==="area"?"line":h,fill:h==="area"?"origin":""}]});else{const x={...c};x.type=h==="area"?"line":h,x.fill=h==="area"?"origin":"";const p=l==null?void 0:l.map(m=>m.idx===n?x:m);o({...i,datasetOptions:p})}}return e.jsxs("div",{className:t.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[d||e.jsx(hs,{className:"max-w-[100px]",title:s,children:co(s)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(t.ChartColumnIncreasing,{onClick:()=>u("bar"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(t.ChartLine,{onClick:()=>u("line"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(t.ChartArea,{onClick:()=>u("area"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(io,{idx:n})]})]})}function mo(){const s=t.useEditorStore(c=>c.card.type),n=t.useEditorStore(c=>c.isDevMode),a=t.useEditorStore(c=>c.card.preferences),{setCardPreferences:r}=t.useEditorStore(c=>c.actions);function d(c){var h;const o={datalabels:{display:c!=="none",align:c,anchor:c,clamp:!0}},u={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(h=a==null?void 0:a.chartOptions)==null?void 0:h.plugins,...o}}};r(u)}function i(){var c,o,u;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(t.Select,{value:((u=(o=(c=a==null?void 0:a.chartOptions)==null?void 0:c.plugins)==null?void 0:o.datalabels)==null?void 0:u.anchor)||"none",onValueChange:d,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Data Labels"}),e.jsx(t.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"start",children:"Start"}),e.jsx(t.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"end",children:"End"})]})})]})]})}function l(){var c,o,u;return e.jsx("div",{children:e.jsxs(t.Select,{value:((u=(o=(c=a==null?void 0:a.chartOptions)==null?void 0:c.plugins)==null?void 0:o.datalabels)==null?void 0:u.anchor)||"none",onValueChange:d,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(t.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:n?i():l()})}function xo({column:s}){const n=t.useEditorStore(o=>o.card.type),a=t.useEditorStore(o=>{var u,h;return(h=(u=o.card)==null?void 0:u.config)==null?void 0:h.metricColumns}),r=(a==null?void 0:a.map(o=>o.label))||[],d=r==null?void 0:r.find(o=>o===s.label||o===s.name),i=d?r.indexOf(d):-1;function l(){return e.jsx("div",{className:"pr-1",children:d&&e.jsx(uo,{idx:i,col:d,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(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(mo,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&l(),["pie","doughnut"].includes(n)&&c()]})}function ho({field:s,searchQuery:n="",limit:a=500}){const{authToken:r,tokenProps:d}=t.useSemaphorContext(),i=t.useEditorStore(u=>u.card),l=i==null?void 0:i.dataSource,c=["attribute-values",s.entityName,s.name,n,a],o=t.useQuery({queryKey:c,queryFn:async()=>{if(!(l!=null&&l.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const u={groupByColumns:[{...s,role:"groupby"}],metricColumns:[],filters:n?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:s,operator:"contains",value:n}],groups:[]}:void 0,rowLimit:a},h={connection_id:l.connectionId,cardConfig:u,cardDataSource:l,cache_config:t.getCacheConfig({card:i})};console.log("requestBody",h);const x=await t.postRequestRegular(`${d.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",h);if(x!=null&&x.error)return console.error("Error fetching attribute values:",x.error),[];const p=s.name;return((x==null?void 0:x.records)||[]).map(g=>{const v=g[p]||g[s.alias||p]||g[s.label];return{id:v||"",value:v||"",label:String(v||"(empty)")}})}catch(u){return console.error("Error fetching attribute values:",u),[]}},enabled:!!s&&!!(l!=null&&l.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:o.data||[],isLoading:o.isLoading,isFetching:o.isFetching,isError:o.isError,error:o.error,refetch:o.refetch}}function $a({open:s,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:d,onSave:i}){var V,C;const l=!!d,[c,o]=N.useState(l?"values":"fields"),[u,h]=N.useState(""),[x,p]=N.useState({id:(d==null?void 0:d.id)||t.v4(),field:(d==null?void 0:d.field)||null,selectedValues:d?Array.isArray(d.value)?d.value:[d.value]:[]}),m=a.filter(M=>{var I;return l?!1:!((I=r==null?void 0:r.conditions)==null?void 0:I.some(D=>D.field.id===M.id))&&M.label.toLowerCase().includes(u.toLowerCase())}),g=M=>{p({...x,field:M}),o("values")},v=()=>{if(x.field&&x.selectedValues.length>0){const M={id:x.id,field:x.field,operator:"in",value:x.selectedValues};let S;if(l){const I=((r==null?void 0:r.conditions)||[]).map(D=>D.id===d.id?M:D);S={...r,conditions:I}}else{const I=(r==null?void 0:r.conditions)||[];S={id:(r==null?void 0:r.id)||t.v4(),logicalOperator:"AND",negate:!1,conditions:[...I,M],groups:[]}}i(S),n(!1)}},j=()=>{if(!l||!d)return;const M=((r==null?void 0:r.conditions)||[]).filter(S=>S.id!==d.id);if(M.length>0){const S={...r,conditions:M};i(S)}else i(void 0);n(!1)},T=M=>{p({...x,selectedValues:M})},k=()=>{l&&d?(p({id:d.id,field:d.field,selectedValues:Array.isArray(d.value)?d.value:[d.value]}),o("values")):(p({id:t.v4(),field:null,selectedValues:[]}),o("fields")),h("")};return N.useEffect(()=>{s&&k()},[s,l,d]),e.jsx(t.Dialog,{open:s,onOpenChange:n,children:e.jsxs(t.DialogContent,{className:"max-w-2xl",children:[e.jsx(t.DialogHeader,{children:e.jsx(t.DialogTitle,{children:l?`Edit Filter: ${(V=x.field)==null?void 0:V.label}`:c==="fields"?"Select Field to Filter":`Select Values for ${(C=x.field)==null?void 0:C.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!l&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&c==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.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(M=>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:[M.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(M.value)?`${M.value.length} values`:String(M.value)})]},M.id))})]}),c==="fields"&&!l?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(t.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(t.Input$1,{placeholder:"Search fields...",value:u,onChange:M=>h(M.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:m.map(M=>e.jsxs(t.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>g(M),children:[e.jsx(t.IconForFieldType,{dataType:t.getDataType(M.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:M.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[M.entityName,".",M.name]})]})]},M.id))}),m.length===0&&u&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',u,'"']}),m.length===0&&!u&&a.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(po,{field:x.field,selectedValues:x.selectedValues,onValuesChange:T,onBack:l?void 0:()=>o("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:l?e.jsx(t.Button,{variant:"destructive",onClick:j,children:"Delete Filter"}):e.jsx(t.Button,{variant:"outline",onClick:k,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(t.Button,{onClick:v,disabled:!x.field||x.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function po({field:s,selectedValues:n,onValuesChange:a,onBack:r}){const[d,i]=N.useState(""),{values:l,isLoading:c,isFetching:o}=ho({field:s,searchQuery:d,limit:500}),u=d?l.filter(p=>String(p.value).toLowerCase().includes(d.toLowerCase())):l,h=p=>{const m=n.includes(p);a(m?n.filter(g=>g!==p):[...n,p])},x=()=>{n.length===u.length&&u.length>0?a([]):a(u.map(p=>p.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:r,children:"← Back"}),e.jsxs(t.Label,{className:"text-sm font-medium",children:["Select values for ",s.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(t.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(t.Input$1,{placeholder:"Search values...",value:d,onChange:p=>i(p.target.value),className:"pl-10"})]}),c||o?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(t.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(t.Checkbox,{checked:n.length===u.length&&u.length>0,onCheckedChange:x}),e.jsxs(t.Label,{className:"text-sm",children:["Select All (",u.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:u.map(p=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>h(p.value),children:[e.jsx(t.Checkbox,{checked:n.includes(p.value),onCheckedChange:()=>h(p.value)}),e.jsx(hs,{className:"text-sm",children:p.label})]},p.id))})]})]})}function fo({field:s,zone:n,index:a,sortDirection:r,onSortDirectionChange:d,hasPivotColumns:i=!1,cardType:l}){var bs,vs,ys,Ns,Cs,Ss,ws,Ts,Es,Is,Ds,ks,As,Ms,Ls,Fs,Os,Rs,Bs,Ps,Vs,zs,_s,qs,$s,Ks,Gs,Us,Hs,Qs,Js,Ys,Ws,Xs;const{attributes:c,listeners:o,setNodeRef:u,transform:h,transition:x,isDragging:p}=t.useSortable({id:s.id}),m=t.useEditorStore(K=>K.card),g=t.useEditorStore(K=>K.frame),{scopedFields:v,valuePickFilterableFields:j,isLoading:T,refetch:k}=t.useFilterableFields(),{userContext:V}=t.useCurrentUserInfo(),C=(V==null?void 0:V.type)==="organization",M=(bs=m.dataSource)==null?void 0:bs.semanticDomainId,{promoteMetric:S}=t.usePromoteCalculatedMetricToDomain({domainId:M}),{updateLabel:I,handleAggregationChange:D,handleDateFormatChange:E,handleGranularityChange:b,handleAliasTemplateChange:O,handleValueAliasesChange:y,handleMetricFormatChange:L,removeField:R,handleMetricComparisonChange:f,handleMetricWindowTransformChange:A,handleMetricWindowOrderByChange:w,handleMetricWindowDirectionChange:P,handleMetricWindowPartitionToggle:F,handleMetricMovingAverageWindowSizeChange:B,handleMetricMovingAverageMinPeriodsChange:_,handleMetricPreviousPeriodDeltaModeChange:z,handleMetricPercentOfTotalScopeChange:G,handleMetricPercentOfTotalOutputChange:W,handleKpiShowTrendlineChange:U,handleKpiTrendlineWindowChange:Y,handleKpiTrendlineGranularityChange:se,handleMetricTargetValueChange:ee}=t.useFieldManagement(m),[ce,re]=N.useState(!1),[ne,xe]=N.useState(()=>{var K;return!!((K=s.parameters)!=null&&K.windowTransform)}),[Z,ge]=N.useState(!1),[ae,ue]=N.useState(!1),[Le,te]=N.useState(null),ve=N.useMemo(()=>{const K=ie=>ie!=null&&ie.startsWith("card-source-")?ie.replace("card-source-",""):ie,Q=K(s.id),de=v.find(ie=>{if(s.qualifiedFieldName&&ie.qualifiedFieldName&&ie.qualifiedFieldName===s.qualifiedFieldName||s.qualifiedEntityName&&ie.qualifiedEntityName&&ie.qualifiedEntityName===s.qualifiedEntityName&&ie.name===s.name)return!0;const ke=K(ie.id);return!!(Q&&ke&&Q===ke)});return{dataType:(de==null?void 0:de.dataType)||s.dataType,resolvedFromScopedField:!!de}},[s.dataType,s.id,s.name,s.qualifiedEntityName,s.qualifiedFieldName,v]),ye=t.getGranularityOptionsForFieldType(ve.dataType),[je,we]=N.useState(s.dateFormat||"YYYY-MM-DD"),[Ee,q]=N.useState(s.customFormat||""),[oe,Ne]=N.useState(!!s.customFormat),Be=N.useRef(null),[X,fe]=N.useState(s.aliasTemplate||""),[Ce,De]=N.useState(s.valueAliases||{}),[Se,Pe]=N.useState((vs=s.parameters)==null?void 0:vs.filters),_e=K=>{K==="custom"?Ne(!0):(Ne(!1),we(K),(n==="groupBy"||it)&&E(a,K,"",n))},Ze=K=>{q(K),(n==="groupBy"||it)&&E(a,"custom",K,n)},We=K=>{var ie;const de=(ie=t.getDateFormatOptionsForGranularity(K)[0])==null?void 0:ie.value;de&&!oe&&(we(de),n==="groupBy"&&E(a,de,"",n)),n==="groupBy"&&b(a,K)},Xe=K=>{fe(K),n==="metrics"&&O(a,K)},le=K=>{De(K),n==="metrics"&&y(a,K)},Ie=K=>{I(n,a,K)},Fe=t.getExpressionFieldKind(s),be=t.getFieldExpressionAnnotation(s),Ge=Fe==="domain_calculated"||Fe==="user_calculated",Te=Fe==="user_calculated"?(ys=g==null?void 0:g.calculatedFields)==null?void 0:ys.find(K=>t.matchesCalculatedField(K,s,{allowComparableFallback:!0})):void 0,jt=Fe==="user_calculated"&&(s.fieldScope==="dashboard"||s.fieldScope===void 0&&!!Te),st=Fe==="domain_calculated",bt=st?"domain":jt?"dashboard":"card",Ye=st?s:jt&&Te?Te:s,vt=K=>{var Q;if(Pe(K),n==="metrics"){const de={...s,parameters:{...s.parameters,filters:K}},ie=[...((Q=m.config)==null?void 0:Q.metricColumns)||[]];ie[a]=de,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:ie})}ge(!1)},Et=async K=>{await S(K),k()},lt=()=>{R(n,a)},Ut={transform:t.CSS.Transform.toString(h),transition:x},ot=t.getDataType(ve.dataType||s.dataType),yt=ot==="date",It=l==="kpi",it=n==="detailColumns",ct=(Ns=m.config)==null?void 0:Ns.metricColumns,He=(Cs=m.config)==null?void 0:Cs.groupByColumns,dt=t.useDashboardStore(K=>{var Q;return(Q=K.dashboard)==null?void 0:Q.filters}),ut=t.useDashboardStore(K=>K.filterValues),Ke=s.granularity||"day",Ht=ye.includes(Ke)?Ke:"day",Nt=n==="groupBy"&&!ye.includes(Ke),Ct=t.getDateFormatOptionsForGranularity(Ht),Dt=oe?"custom":Ct.some(K=>K.value===je)?je:((Ss=Ct[0])==null?void 0:Ss.value)??"YYYY-MM-DD";N.useEffect(()=>{var de;if(T||!Nt){Be.current=null;return}const K=`${s.id}:${Ke}:${ve.dataType||s.dataType||""}:${a}`;if(Be.current===K)return;Be.current=K;const Q="day";if(b(a,Q),!oe){const ie=(de=t.getDateFormatOptionsForGranularity(Q)[0])==null?void 0:de.value;ie&&(we(ie),E(a,ie,"",n))}},[s.dataType,s.id,E,b,Nt,a,oe,T,Ke,ve.dataType,n]);const kt=!!l&&t.COMPARISON_SUPPORTED_CHART_TYPES.includes(l),Qt=l==="kpi"||l==="table",Qe=N.useMemo(()=>He==null?void 0:He.find(K=>t.getDataType(K.dataType||"")==="date"),[He]),At=N.useMemo(()=>(He||[]).some(K=>t.getDataType(K.dataType||"")==="date"),[He]),Mt=N.useMemo(()=>{var ie;if(!Qe)return!1;const K=(ie=m.config)==null?void 0:ie.filters;if(!K)return!1;const Q=ke=>{const Re=ke.field;return Re?Qe.id&&Re.id===Qe.id||Qe.qualifiedFieldName&&Re.qualifiedFieldName===Qe.qualifiedFieldName?!0:Re.name===Qe.name:!1},de=ke=>ke.conditions.some(qe=>t.getDataType(qe.field.dataType||"")==="date"&&Q(qe))?!0:ke.groups.some(qe=>de(qe));return de(K)},[(ws=m.config)==null?void 0:ws.filters,Qe]),Jt=N.useMemo(()=>ro(dt||[],Qe,ut),[dt,ut,Qe]),at=Mt||Jt,Me=s,mt=((Es=(Ts=Me.parameters)==null?void 0:Ts.windowTransform)==null?void 0:Es.function)||"none",$=t.isMetricTransformEnabled(Me),H=$?mt:null,J=t.supportsMetricTransformForMetric({cardType:l||"table",cardConfig:m.config||{},metric:Me,transformMode:H||"running_total"}),me=!!Me.comparisonType&&Me.comparisonType!=="none",pe=t.getRunningTotalOrderByCandidates(He||[]),he=((ks=(Ds=(Is=Me.parameters)==null?void 0:Is.windowTransform)==null?void 0:Ds.orderBy)==null?void 0:ks.fieldId)||"",Oe=((Ls=(Ms=(As=Me.parameters)==null?void 0:As.windowTransform)==null?void 0:Ms.orderBy)==null?void 0:Ls.direction)||"asc",Ve=pe.find(K=>K.id===he),Ue=H==="running_total"||H==="moving_average"||H==="previous_period_delta",xt=$&&Ue&&!!Ve&&t.getDataType(Ve.dataType||"")!=="date",ht=t.getDefaultRunningTotalPartitionByFieldIds({cardType:l||"table",cardConfig:m.config||{},orderByFieldId:he||void 0}),ze=new Set(((Os=(Fs=Me.parameters)==null?void 0:Fs.windowTransform)==null?void 0:Os.partitionByFieldIds)||ht),pt=l==="pivotTable"||t.isSubtotalEnabledAggregateTable(l||"table",m.config||{}),Lt=[...(He||[]).filter(K=>K.id&&(!Ue||K.id!==he)),...pt?(((Rs=m.config)==null?void 0:Rs.pivotByColumns)||[]).filter(K=>K.id):[]],Ft=((Vs=(Ps=(Bs=Me.parameters)==null?void 0:Bs.windowTransform)==null?void 0:Ps.movingAverage)==null?void 0:Vs.windowSize)||7,Ga=((qs=(_s=(zs=Me.parameters)==null?void 0:zs.windowTransform)==null?void 0:_s.movingAverage)==null?void 0:qs.minPeriods)||1,Ua=((Gs=(Ks=($s=Me.parameters)==null?void 0:$s.windowTransform)==null?void 0:Ks.previousPeriodDelta)==null?void 0:Gs.mode)||"absolute",fs=((Qs=(Hs=(Us=Me.parameters)==null?void 0:Us.windowTransform)==null?void 0:Hs.percentOfTotal)==null?void 0:Qs.scope)||"grand_total",Ha=((Ws=(Ys=(Js=Me.parameters)==null?void 0:Js.windowTransform)==null?void 0:Ys.percentOfTotal)==null?void 0:Ws.output)||"percent",Qa=N.useMemo(()=>(ct||[]).some(K=>K.comparisonType==="start_vs_end"),[ct]);N.useEffect(()=>{$&&xe(!0)},[$]);const Ja=n!=="pivotBy"&&n!=="sortBy",Ya=yt&&n==="groupBy"&&(!It||Qa),Wa=!It&&yt&&(n==="groupBy"||it),Xa=l==="kpi"&&yt&&n==="groupBy",Za=n==="metrics",gs=kt&&n==="metrics",en=()=>{const K=s,Q=n==="metrics"&&Ge;return e.jsxs("div",{className:"space-y-1",children:[!Q&&e.jsx("div",{title:`${s.entityName}.${s.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:`${s.entityName}.${s.name}`}),Q&&K.calculatedFormula&&e.jsxs("div",{title:t.formatDisplayFormula(K.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:["= ",t.formatDisplayFormula(K.calculatedFormula)]})]})},tn=()=>Ja?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(Je,{value:s.label??"",onSave:Ie,placeholder:"Display label...",type:"text"})]}):null,sn=()=>n!=="sortBy"?null:e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Order"}),e.jsxs(t.Select,{value:r||"asc",onValueChange:K=>d(K),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"asc",children:"Ascending"}),e.jsx(t.SelectItem,{className:"text-xs",value:"desc",children:"Descending"})]})]})]}),js=()=>Ya?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(t.Select,{value:Ht,onValueChange:We,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select granularity..."})}),e.jsx(t.SelectContent,{children:ye.map(K=>e.jsx(t.SelectItem,{className:"text-xs",value:K,children:t.toTitleCase(K)},K))})]})]}):null,an=()=>Wa?e.jsxs(e.Fragment,{children:[js(),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Date Format"}),e.jsxs(t.Select,{value:Dt,onValueChange:_e,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select date format..."})}),e.jsx(t.SelectContent,{children:Ct.map(K=>e.jsx(t.SelectItem,{className:"text-xs",value:K.value,children:K.label},K.value))})]}),oe&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(t.Input$1,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:Ee,onChange:K=>{K.stopPropagation(),Ze(K.target.value)},onClick:K=>K.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,nn=()=>{var Q,de,ie,ke;const K=Xa;return K?e.jsx(e.Fragment,{children:K&&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(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(t.SmallSwitch,{checked:((Q=m.config)==null?void 0:Q.showTrendline)||!1,onCheckedChange:U})]})}),((de=m.config)==null?void 0:de.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(t.Input$1,{type:"number",min:"1",max:"365",value:((ie=m.config)==null?void 0:ie.trendlineWindow)||30,onChange:Re=>{const qe=parseInt(Re.target.value)||30;Y(qe)},className:"h-8 text-xs",placeholder:"30"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Granularity"}),e.jsxs(t.Select,{value:((ke=m.config)==null?void 0:ke.trendlineGranularity)||"day",onValueChange:se,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"day",children:"Day"}),e.jsx(t.SelectItem,{value:"week",children:"Week"}),e.jsx(t.SelectItem,{value:"month",children:"Month"})]})]})]})]})]})}):null},rn=()=>{if(!Za)return null;const K=Ge;return e.jsxs(e.Fragment,{children:[K&&C&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Formula"}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>ue(!0),children:[e.jsx(t.Pencil,{className:"mr-2 h-3 w-3"}),"Edit Formula"]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(t.Select,{value:s.aggregate,onValueChange:Q=>{D(a,Q)},disabled:K,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select function..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(t.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),t.getDataType(s.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(t.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(t.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(t.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(t.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Number Format"}),e.jsx(xs,{value:Me.format,onChange:Q=>L(a,Q),showTitle:!1})]}),e.jsx(t.Collapsible,{open:ne,onOpenChange:xe,children:e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-muted/20 p-2.5",children:[e.jsx(t.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:[!ne&&e.jsx("span",{className:"mr-2",children:$?t.toTitleCase(mt.replace(/_/g," ")):"None"}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 transition-transform",ne?"rotate-180":"")})]})]})}),e.jsxs(t.CollapsibleContent,{className:"space-y-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Transform"}),e.jsxs(t.Select,{value:$?mt:"none",onValueChange:Q=>A(a,Q),disabled:!J.supported&&!$,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select transform..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"none",children:"None"}),e.jsx(t.SelectItem,{value:"running_total",disabled:me,children:"Running Total"}),e.jsx(t.SelectItem,{value:"moving_average",disabled:me,children:"Moving Average"}),e.jsx(t.SelectItem,{value:"previous_period_delta",disabled:me,children:"Previous Period Delta"}),e.jsx(t.SelectItem,{value:"percent_of_total",disabled:me,children:"Percent of Total"})]})]}),!J.supported&&!$&&e.jsx("div",{className:"text-xs text-muted-foreground",children:J.reason}),me&&!$&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"Disable comparison to enable metric transforms."})]}),$&&e.jsxs(e.Fragment,{children:[Ue&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Order By"}),e.jsxs(t.Select,{value:he,onValueChange:Q=>w(a,Q),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select order field..."})}),e.jsx(t.SelectContent,{children:pe.filter(Q=>!!Q.id).map(Q=>e.jsx(t.SelectItem,{value:Q.id,className:"text-xs",children:Q.label||Q.name},Q.id))})]}),!he&&e.jsx("div",{className:"text-xs text-amber-700",children:"No date trend detected. Select an order field."}),xt&&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(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Direction"}),e.jsxs(t.Select,{value:Oe,onValueChange:Q=>P(a,Q),disabled:!he,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select direction..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"asc",children:"Ascending"}),e.jsx(t.SelectItem,{className:"text-xs",value:"desc",children:"Descending"})]})]})]})]}),H==="moving_average"&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Window Size"}),e.jsx(t.Input$1,{type:"number",min:1,className:"h-8 text-xs",value:Ft,onChange:Q=>B(a,Number(Q.target.value))}),e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Min Periods"}),e.jsx(t.Input$1,{type:"number",min:1,max:Ft,className:"h-8 text-xs",value:Ga,onChange:Q=>_(a,Number(Q.target.value))})]}),H==="previous_period_delta"&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Output"}),e.jsxs(t.Select,{value:Ua,onValueChange:Q=>z(a,Q),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select output..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"absolute",children:"Absolute Delta"}),e.jsx(t.SelectItem,{value:"percent",children:"Percent Delta"})]})]})]}),H==="percent_of_total"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Scope"}),e.jsxs(t.Select,{value:fs,onValueChange:Q=>G(a,Q),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select scope..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"grand_total",children:"Grand Total"}),e.jsx(t.SelectItem,{value:"partition_total",children:"Partition Total"})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Output"}),e.jsxs(t.Select,{value:Ha,onValueChange:Q=>W(a,Q),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select output..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"percent",children:"Percent"}),e.jsx(t.SelectItem,{value:"fraction",children:"Fraction"})]})]})]})]}),(H==="running_total"||H==="moving_average"||H==="previous_period_delta"||H==="percent_of_total"&&fs==="partition_total")&&Lt.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Reset By"}),e.jsx("div",{className:"space-y-1",children:Lt.map(Q=>{const de=!!Q.id&&ze.has(Q.id);return e.jsxs("button",{type:"button",onClick:()=>Q.id&&F(a,Q.id),className:t.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:Q.label||Q.name}),de?e.jsx(t.Check,{className:"h-3 w-3"}):null]},Q.id)})})]})]})]})]})}),gs&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(t.Select,{value:Me.comparisonType||"none",disabled:$,onValueChange:Q=>f(a,Q),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"none",children:"No Comparison"}),(()=>{const Q=!At||!at,de=At?at?void 0:"Add a date filter to enable":"Add a date groupBy to enable",ie=(ke,Re)=>e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.SelectItem,{value:ke,disabled:Q,title:de,children:Re})}),Q&&de&&e.jsx(t.TooltipContent,{side:"right",children:de})]})});return e.jsxs(e.Fragment,{children:[ie("previous_period","Previous Period"),ie("same_period_last_year","Same Period Last Year"),ie("start_vs_end","Start vs End")]})})(),Qt&&e.jsx(t.SelectItem,{value:"target",children:"Target"})]})]})]}),gs&&Me.comparisonType==="target"&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(t.Input$1,{type:"number",value:Me.targetValue!==void 0&&Me.targetValue!==null?String(Me.targetValue):"",onChange:Q=>{const de=Q.target.value;if(de===""){ee(a,void 0);return}const ie=Number(de);ee(a,Number.isFinite(ie)?ie:void 0)},className:"h-8 text-xs",placeholder:"Enter target value..."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(Se==null?void 0:Se.conditions)&&Se.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:Se.conditions.map(Q=>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:()=>{te(Q),ge(!0)},children:[e.jsxs("span",{className:"font-medium",children:[Q.field.label,":"]}),e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"cursor-help text-muted-foreground",children:Array.isArray(Q.value)?Q.value.length===1?String(Q.value[0]):Q.value.length<=2?Q.value.join(", "):`${Q.value.slice(0,2).join(", ")} +${Q.value.length-2}`:String(Q.value)})}),Array.isArray(Q.value)&&Q.value.length>1&&e.jsx(t.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 (",Q.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:Q.value.map((de,ie)=>e.jsx("div",{children:String(de)},ie))})]})})]})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:de=>{var ke;de.stopPropagation();const ie=Se.conditions.filter(Re=>Re.id!==Q.id);if(ie.length>0){const Re={...Se,conditions:ie};vt(Re)}else if(Pe(void 0),n==="metrics"){const Re={...s,parameters:{...s.parameters,filters:void 0}},qe=[...((ke=m.config)==null?void 0:ke.metricColumns)||[]];qe[a]=Re,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:qe})}},children:e.jsx(t.X,{className:"h-3 w-3"})})]},Q.id))}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{te(null),ge(!0)},children:[e.jsx(t.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(xo,{column:s}),i&&e.jsxs(e.Fragment,{children:[e.jsx(lo,{aliasTemplate:X,onAliasTemplateChange:Xe}),e.jsx(oo,{valueAliases:Ce,onValueAliasesChange:le})]})]})},ln=(Se==null?void 0:Se.conditions)&&Se.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:u,style:Ut,className:t.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",ce&&"border-border/80 bg-muted/20 shadow-[inset_0_1px_0_rgba(255,255,255,0.35)]",p&&"z-50 scale-95 opacity-50","cursor-default"),children:[e.jsxs("div",{className:"flex min-w-0 grow items-center gap-2",children:[e.jsx("button",{type:"button",...c,...o,className:"flex shrink-0 cursor-grab items-center rounded-sm p-0.5 text-muted-foreground transition-colors hover:text-foreground active:cursor-grabbing","aria-label":`Drag ${t.getMetricDisplayLabel(s)}`,onClick:K=>{K.stopPropagation()},children:e.jsx(t.GripVertical,{className:"h-3.5 w-3.5"})}),e.jsxs("div",{className:"relative shrink-0",children:[e.jsx(t.IconForFieldType,{dataType:ot}),be&&e.jsx("span",{className:t.cn(t.FIELD_EXPRESSION_BADGE_BASE_CLASS,be.badgeClassName),children:be.label})]}),e.jsx(hs,{className:t.cn("block w-0 min-w-0 flex-1 text-sm text-foreground/95",ln&&"min-w-0"),children:t.getMetricDisplayLabel(s)}),n==="metrics"&&((Xs=Se==null?void 0:Se.conditions)==null?void 0:Xs.length)&&!ce&&e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.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(t.Filter,{className:"h-3 w-3"}),e.jsx("span",{children:Se.conditions.length})]})}),e.jsx(t.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:Se.conditions.map(K=>e.jsxs("div",{children:[K.field.label,":"," ",Array.isArray(K.value)?`${K.value.length} values`:String(K.value)]},K.id))})})]})}),n==="sortBy"&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 shrink-0 p-0 text-foreground/55 hover:text-foreground",onClick:K=>{K.stopPropagation(),d(r==="asc"?"desc":"asc")},children:r==="asc"?e.jsx(t.ArrowUp,{className:"h-3 w-3"}):e.jsx(t.ArrowDown,{className:"h-3 w-3"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 shrink-0 p-0 text-foreground/55 hover:text-foreground",onClick:K=>{K.stopPropagation(),re(!ce)},children:e.jsx(t.ChevronDown,{className:`h-3 w-3 transition-transform ${ce?"rotate-180":""}`})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 shrink-0 p-0 text-foreground/55 hover:text-foreground",onClick:K=>{K.stopPropagation(),lt()},children:e.jsx(t.X,{className:"h-2.5 w-2.5"})})]}),ce&&e.jsxs("div",{className:"space-y-3 rounded-md bg-muted/20 p-2.5",children:[en(),sn(),tn(),l==="kpi"&&js(),an(),nn(),rn()]})]}),Z&&e.jsx($a,{open:Z,onOpenChange:K=>{ge(K),K||te(null)},availableFields:j,existingFilters:Se,editingCondition:Le,onSave:K=>{var Q;if(K)vt(K);else if(Pe(void 0),n==="metrics"){const de={...s,parameters:{...s.parameters,filters:void 0}},ie=[...((Q=m.config)==null?void 0:Q.metricColumns)||[]];ie[a]=de,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:ie})}te(null)}}),ae&&n==="metrics"&&Ge&&e.jsx(t.CalculatedFieldEditor,{open:ae,onOpenChange:ue,availableFields:v,existingField:Ye,existingFieldScope:bt,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:K=>{var Rt;if(K.role!=="metric")return;const{card:Q,frame:de,actions:ie}=t.useEditorStore.getState(),ke=((Rt=Q.config)==null?void 0:Rt.metricColumns)||[],Re=de.calculatedFields||[],{nextActiveFields:qe,nextStoredFields:St,nextSharedFields:Ot}=t.saveCalculatedFieldToCardScope({activeFields:ke,storedFields:Q.calculatedFields||[],sharedFields:Re,updatedField:K,editingField:Ye,previousScope:bt});qe&&ie.updateCardConfig(m.id,{metricColumns:qe}),ie.updateCard(m.id,{calculatedFields:St}),Ot!==Re&&ie.updateFrame({calculatedFields:Ot})},onSaveToDashboard:K=>{var Zs;if(K.role!=="metric")return;const{card:Q,frame:de,actions:ie}=t.useEditorStore.getState(),ke=s,Re=((Zs=Q.config)==null?void 0:Zs.metricColumns)||[],qe=de.calculatedFields||[],{nextActiveFields:St,nextStoredFields:Ot,nextSharedFields:Rt}=t.saveCalculatedFieldToSharedScope({activeFields:Re,storedFields:Q.calculatedFields||[],sharedFields:qe,updatedField:{...K,id:ke.id,aliasTemplate:ke.aliasTemplate,valueAliases:ke.valueAliases,parameters:ke.parameters,customFormat:ke.customFormat},editingField:Ye,previousScope:bt});ie.updateFrame({calculatedFields:Rt}),St&&ie.updateCardConfig(m.id,{metricColumns:St}),ie.updateCard(m.id,{calculatedFields:Ot})},onPromoteMetricToDomain:M&&C?Et:void 0,domainId:M,cardId:m.id})]})}function go({concept:s}){const n=()=>{switch(s){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(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:300,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(t.TooltipContent,{side:"right",align:"start",className:"p-3",children:n()})]})})}const jo={groupBy:qt,pivotBy:is,metrics:En,detailColumns:t.Table2,sortBy:t.ArrowUpDown};function Tt({zone:s,fields:n,label:a,placeholder:r,shouldShow:d,hasPivotColumns:i=!1,activeField:l=null}){const{isOver:c,setNodeRef:o}=t.useDroppable({id:s}),{updateSortByColumn:u}=t.useEditorActions(),h=t.useEditorStore(T=>T.card),x=t.useEditorStore(T=>T.card.type),p=n.length>0,m=N.useMemo(()=>!l||!c?!0:t.validateFieldForChartType(l,s,x).isValid,[l,c,s,x]),g=(T,k)=>{var C;!((C=h.config)!=null&&C.sortByColumns)||h.config.sortByColumns.findIndex(M=>M.id===T)===-1||u(h.id,T,{direction:k})};if(s==="sortBy"&&d===!1)return null;const v=s!=="sortBy"&&x!=="kpi",j=jo[s]||t.Plus;return e.jsxs("div",{className:"mb-3 w-full",children:[e.jsx("div",{className:"mb-1.5 flex items-center gap-2",children:e.jsx(t.Label,{className:t.cn("block text-sm font-medium text-foreground",{}),children:a})}),e.jsx("div",{ref:o,className:t.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&&m,"border-red-500 bg-red-50 shadow-[0_0_0_1px_rgba(239,68,68,0.18)] dark:bg-red-950":c&&!m,"border-solid border-border/55 bg-background":!c&&p,"min-h-[56px] border-dashed border-border/60 bg-background":!c&&!p}),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(j,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground/80"}),e.jsx("span",{children:r}),v&&e.jsx(go,{concept:s})]}):e.jsx(t.SortableContext,{id:s,items:n.map(T=>T.id),strategy:t.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map((T,k)=>{const C=T.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(fo,{field:T,zone:s,index:k,sortDirection:C,onSortDirectionChange:M=>g(T.id,M),hasPivotColumns:i,cardType:x})})},T.id)})})})})]})}function bo({groupByFields:s,pivotByFields:n,metricsFields:a,sortByFields:r,detailFields:d,activeField:i}){var W,U,Y,se;const[l,c]=N.useState(!1),o=t.useEditorStore(ee=>{var ce;return!!((ce=ee.card.customCardPreferences)!=null&&ce.url)}),u=t.useEditorStore(ee=>ee.card),h=t.useEditorStore(ee=>ee.frame),x=t.findCustomVisualConfigCard(h,u),{manifest:p}=t.useCustomVisual(((W=x==null?void 0:x.customCardPreferences)==null?void 0:W.url)||""),m=(U=p==null?void 0:p.visuals)==null?void 0:U.find(ee=>{var ce;return ee.name===((ce=x==null?void 0:x.customCardPreferences)==null?void 0:ce.componentName)}),g=t.resolveMultiInputType(x,m)==="multiple",v=g&&!!((Y=x==null?void 0:x.customCardPreferences)!=null&&Y.url),j=t.getConfigSlotExpectedType(m==null?void 0:m.slots),T=t.useEditorStore(ee=>ee.actions.updateCardConfig),k=t.useEditorStore(ee=>ee.actions.updateFrame),{scopedFields:V,refetch:C}=t.useScopedFields(),{userContext:M}=t.useCurrentUserInfo(),S=g&&(x==null?void 0:x.id)===u.id&&j?j:u==null?void 0:u.type,I=S==="detailTable",D=s.length>0||a.length>0||d.length>0,E=!I&&(S!=="kpi"||a.length<=2),b=!I,O=!I&&S!=="kpi",y=S!=="kpi"&&D,L=I,R="Drop sort fields here",f=(se=u.dataSource)==null?void 0:se.semanticDomainId,{promoteMetric:A}=t.usePromoteCalculatedMetricToDomain({domainId:f}),w=(M==null?void 0:M.type)==="organization",P=ee=>{const ce=h.calculatedFields||[],re=ce.findIndex(ue=>ue.name===ee.name&&ue.role===ee.role),ne=re>=0?{...ee,id:ce[re].id}:ee,xe=re>=0?ce.map((ue,Le)=>Le===re?ne:ue):[...ce,ne];k({calculatedFields:xe});const Z=t.getNewField(ne,"metrics",a),ge=a.findIndex(ue=>ue.name===Z.name&&ue.role===Z.role),ae=ge>=0?a.map((ue,Le)=>Le===ge?{...ue,...Z,id:ue.id}:ue):[...a,Z];T(u.id,{metricColumns:ae})},F=async ee=>{await A(ee),C()},B=["pie","doughnut","polar","funnel","aggregateTable","bubble","scatter"].includes(S),_=O&&!B,z=()=>S==="kpi"?{label:"Trend By",placeholder:"Drop trend field here"}:{label:"Rows",placeholder:"Drop dimensions here"},G=()=>S==="kpi"?{label:"Metric",placeholder:"Drop metric here"}:{label:"Metrics",placeholder:"Drop metrics here"};return e.jsxs(e.Fragment,{children:[e.jsxs(t.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full space-y-2.5",children:[e.jsxs(t.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(t.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(t.List,{className:"h-4 w-4 text-foreground/60"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-3 pt-1.5",children:[E&&e.jsx(Tt,{zone:"groupBy",fields:s,label:z().label,placeholder:z().placeholder,activeField:i}),_&&e.jsx(Tt,{zone:"pivotBy",fields:n,label:"Pivot Columns",placeholder:"Drop pivot fields here",activeField:i}),b&&e.jsx(Tt,{zone:"metrics",fields:a,label:G().label,placeholder:G().placeholder,hasPivotColumns:n.length>0,activeField:i}),L&&e.jsx(Tt,{zone:"detailColumns",fields:d,label:"Columns",placeholder:"Drop columns here"}),a.length>=1&&w&&e.jsxs(t.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(t.Calculator,{className:"mr-2 h-4 w-4"}),"Create Metric"]}),y&&e.jsx(Tt,{zone:"sortBy",fields:r,label:"Sort By",placeholder:R,activeField:i})]})]}),(!o||v)&&e.jsxs(t.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(t.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(t.Settings2,{className:"h-4 w-4 text-foreground/60"}),e.jsx("span",{children:"CHART SETTINGS"})]})}),e.jsx(t.AccordionContent,{className:"mb-2 rounded-md bg-muted/20 px-3 py-0.5",children:e.jsx(t.Accordion,{type:"single",collapsible:!0,className:"w-full",children:e.jsx(qa,{mode:"config"})})})]}),(o||v)&&e.jsxs(t.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(t.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(Sa,{className:"h-4 w-4 text-foreground/60"}),e.jsx("span",{children:"COMPONENT SETTINGS"})]})}),e.jsx(t.AccordionContent,{className:"mb-2 rounded-md bg-muted/20 px-3 py-0.5",children:e.jsx(Pa,{})})]})]}),e.jsx(t.CalculatedFieldEditor,{open:l,onOpenChange:c,availableFields:V,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:ee=>{ee.role==="metric"&&T(u.id,{metricColumns:[...a,ee]})},onSaveToDashboard:ee=>{ee.role==="metric"&&P(ee)},onPromoteMetricToDomain:f&&w?F:void 0,domainId:f,cardId:u.id})]})}function vo({onEditJoins:s}){const n=t.useEditorStore(c=>c.card),{autoJoinMetadata:a}=t.useDashboardCardQuery(n);if(!(a!=null&&a.autoResolved))return null;const{resolvedJoinPlan:r}=a,d=(r==null?void 0:r.joins)||[];if(d.length===0)return null;const i=c=>!c||c.length===0?"No conditions":c.map(o=>{var p,m,g,v;const u=`${(p=o.source)==null?void 0:p.entityName}.${(m=o.source)==null?void 0:m.name}`,h=`${(g=o.target)==null?void 0:g.entityName}.${(v=o.target)==null?void 0:v.name}`,x=o.operator||"=";return`${u} ${x} ${h}`}).join(" AND "),l=c=>!c.joinKeyGroups||c.joinKeyGroups.length===0?"No conditions defined":c.joinKeyGroups.length===1?i(c.joinKeyGroups[0].keys):c.joinKeyGroups.map((o,u)=>({id:u,operator:o.operator,condition:i(o.keys)}));return e.jsx(t.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(Mn,{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(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.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:d.length})}),e.jsx(t.TooltipContent,{side:"bottom",align:"start",className:"max-w-md p-3",children:e.jsx("div",{className:"space-y-2",children:d.map((c,o)=>{const u=l(c),h=Array.isArray(u);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(t.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:c.target.name})]}),e.jsx(t.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:h?u.map(x=>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:x.condition}),x.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",x.operator,")"]})]},x.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:u})})})]},c.id||o)})})})]})})]}),s&&e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:s,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(t.SquarePen,{className:"size-3.5"})})]})})}const Na={getItem(s){if(typeof window>"u")return null;try{return localStorage.getItem(s)}catch(n){return console.warn(`Failed to read from localStorage (${s}):`,n),null}},setItem(s,n){if(!(typeof window>"u"))try{localStorage.setItem(s,n)}catch(a){console.warn(`Failed to write to localStorage (${s}):`,a)}}};function yo({selectedChart:s,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:d,sortByFields:i,detailFields:l,activeField:c}){var E,b;const[o,u]=N.useState(()=>Na.getItem("chart-selector-expanded")==="true"),[h,x]=N.useState(!1),p=t.useEditorStore(O=>O.card),m=t.useEditorStore(O=>O.actions.updateCardConfig),g=a.length>0||r.length>0||d.length>0||l.length>0,{data:v,autoJoinMetadata:j}=t.useDashboardCardQuery(p),T=g||!!v,k=((E=p==null?void 0:p.config)==null?void 0:E.joinPlan)||(j!=null&&j.autoResolved?j.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),V=((b=p==null?void 0:p.dataSource)==null?void 0:b.selectedEntities)||[],C=O=>{m(p.id,{...p==null?void 0:p.config,joinPlan:O}),x(!1)},M=()=>{m(p.id,{...p==null?void 0:p.config,joinPlan:void 0}),x(!1)},S=()=>{x(!1)},I=()=>{x(!0)};N.useEffect(()=>{Na.setItem("chart-selector-expanded",String(o))},[o]);const D=()=>{u(O=>!O)};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:t.cn("overflow-hidden transition-all duration-300 ease-in-out",o?"max-h-[210px] opacity-100":"max-h-0 opacity-0"),children:o&&e.jsx(ds,{selectedChart:s,onChartChange:n,variant:"outline"})}),e.jsx("div",{"data-content":"Chart Quick Selector",className:t.cn("flex items-center justify-center",{"mt-3":o,"mt-2":!o}),children:e.jsx(t.ChartQuickSelector,{selectedChart:s,onChartChange:n,isDropdownExpanded:o,onToggleDropdown:D})})]})}),T&&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(t.ScrollArea,{className:"min-h-0 w-full flex-1 basis-0",children:e.jsxs("div",{className:t.cn("space-y-3 pl-2 pr-4 pb-6",T?"pt-1":"pt-4"),children:[e.jsx(vo,{onEditJoins:I}),e.jsx(bo,{groupByFields:a,pivotByFields:r,metricsFields:d,sortByFields:i,detailFields:l,activeField:c})]})}),e.jsx(Ia,{open:h,onOpenChange:x,joinPlan:k,availableDataSources:V,onSave:C,onCancel:S,onRemove:M,children:e.jsx("div",{})})]})}function No({initialFilters:s,availableFields:n}={}){const[a,r]=N.useState(s||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});t.useEditorStore(C=>C.card.dataSource);const{filterableFields:d,isLoading:i}=t.useFilterableFields(),l=n||d||[],c={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},o=C=>{const M=S=>{if(S.id===C){const I=l[0]||c,D=t.getDataType(I.dataType)==="date";return{...S,conditions:[...S.conditions,{id:`condition-${Date.now()}`,field:I,operator:D?"between":"=",value:D?[]:""}]}}return{...S,groups:S.groups.map(M)}};r(M(a))},u=C=>{const M=S=>{if(S.id===C){const I=l[0]||c,D=t.getDataType(I.dataType)==="date";return{...S,groups:[...S.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:I,operator:D?"between":"=",value:D?[]:""}],groups:[]}]}}return{...S,groups:S.groups.map(M)}};r(M(a))},h=(C,M)=>{const S=I=>I.id===C?{...I,conditions:I.conditions.filter(D=>D.id!==M)}:{...I,groups:I.groups.map(S)};r(S(a))},x=(C,M)=>{const S=I=>I.id===C?{...I,groups:I.groups.filter(D=>D.id!==M)}:{...I,groups:I.groups.map(S)};r(S(a))},p=(C,M,S,I)=>{if(S==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const D=E=>E.id===C?{...E,conditions:E.conditions.map(b=>b.id===M?{...b,[S]:I}:b)}:{...E,groups:E.groups.map(D)};r(D(a))},m=(C,M,S)=>{const I=D=>D.id===C?{...D,conditions:D.conditions.map(E=>E.id===M?{...E,...S}:E)}:{...D,groups:D.groups.map(I)};r(I(a))},g=(C,M)=>{const S=I=>I.id===C?{...I,logicalOperator:M}:{...I,groups:I.groups.map(S)};r(S(a))},v=(C,M)=>{const S=I=>I.id===C?{...I,negate:M}:{...I,groups:I.groups.map(S)};r(S(a))},j=(C,M,S)=>{const I=D=>D.id===C?{...D,conditions:t.arrayMove(D.conditions,M,S)}:{...D,groups:D.groups.map(I)};r(I(a))},T=(C,M,S)=>{const I=D=>D.id===C?{...D,groups:t.arrayMove(D.groups,M,S)}:{...D,groups:D.groups.map(I)};r(I(a))},k=C=>{if(!C||C.conditions.length===0&&C.groups.length===0)return"-- No filters defined";const M=I=>{let D="";typeof I.field=="object"?D=I.field.entityName?`${I.field.entityName}.${I.field.name}`:I.field.name:D=String(I.field);const E=I.operator;let b=I.value;if(I.field.dataType==="string"&&!["in","not in"].includes(I.operator))typeof b=="string"?b=`'${b}'`:Array.isArray(b)&&(b=`'${b.join(", ")}'`);else if(I.field.dataType==="date"||I.field.dataType==="datetime"||I.field.dataType==="timestamp")if(I.operator==="between"&&Array.isArray(b)&&b.length===2){const O=b[0]?`'${b[0]}'`:"NULL",y=b[1]?`'${b[1]}'`:"NULL";return`${D} BETWEEN ${O} AND ${y}`}else if((I.operator==="in"||I.operator==="not in")&&Array.isArray(b)){const O=b.map(y=>y?`'${y}'`:"NULL").join(", ");return`${D} ${E} (${O})`}else typeof b=="string"||b instanceof Date?b=`'${b}'`:Array.isArray(b)&&b.length>0&&(b=`'${b[0]}'`);else if(["in","not in"].includes(I.operator)){let O=[];Array.isArray(b)?O=b.map(y=>typeof y=="string"?`'${y}'`:String(y)):typeof b=="string"?O=b.split(",").map(y=>{const L=y.trim();return I.field.dataType==="string"?`'${L}'`:L}):typeof b=="number"&&(O=[String(b)]),b=`(${O.join(", ")})`}switch(E){case"contains":return typeof b=="string"?`${D} LIKE '%${b.replace(/'/g,"")}'`:`${D} LIKE '%${String(b)}'`;case"startsWith":return typeof b=="string"?`${D} LIKE '${b.replace(/'/g,"")}%'`:`${D} LIKE '${String(b)}%'`;case"endsWith":return typeof b=="string"?`${D} LIKE '%${b.replace(/'/g,"")}'`:`${D} LIKE '%${String(b)}'`;case"isNull":return`${D} IS NULL`;case"isNotNull":return`${D} IS NOT NULL`;default:return`${D} ${E} ${b}`}},S=I=>{const D=I.conditions.map(M),E=I.groups.map(L=>S(L)),b=[...D,...E].filter(Boolean);if(b.length===0)return"";const O=b.join(` ${I.logicalOperator} `),y=b.length>1?`(${O})`:O;return I.negate?`NOT ${y}`:y};return S(C)},V=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:l,isLoading:i,addCondition:o,addGroup:u,removeCondition:h,removeGroup:x,updateCondition:p,updateConditionFields:m,updateGroupOperator:g,updateGroupNegate:v,reorderConditions:j,reorderGroups:T,generateSQLPreview:k,hasAnyFilters:V}}function Co({children:s,className:n,delayDuration:a}){return e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:a,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:t.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",n),children:s})}),e.jsx(t.PortalTooltipContent,{children:s})]})})}const So=s=>{if(s.qualifiedEntityName){const n=s.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function wo({value:s,onValueChange:n,availableFields:a,placeholder:r="Select field",className:d="w-64"}){const[i,l]=N.useState(!1),c=N.useMemo(()=>{const o={};return a.forEach(u=>{const h=So(u);o[h]||(o[h]={}),o[h][u.entityId]||(o[h][u.entityId]=[]),o[h][u.entityId].push(u)}),o},[a]);return e.jsxs(t.Popover,{modal:!0,open:i,onOpenChange:l,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:t.cn("justify-between",!s&&"text-muted-foreground",d),children:[s?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Co,{children:[s.entityName,".",s.name]})}):r,e.jsx(t.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(t.CommandEmpty,{children:"No fields found."}),e.jsx(t.CommandList,{className:"max-h-80",children:Object.entries(c).map(([o,u])=>e.jsx(t.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Database,{className:"h-3 w-3"}),o]}),children:Object.entries(u).map(([h,x])=>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:[t.getEntityIcon(x[0].entityType,{size:"h-3 w-3"}),e.jsx("span",{children:x[0].entityName})]}),x.map((p,m)=>e.jsxs(t.CommandItem,{value:p.id,onSelect:()=>{n(p),l(!1)},className:"overflow-x-auto",children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",(s==null?void 0:s.id)===p.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:p.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:p.description&&e.jsx("span",{children:p.description})})]})]},p.id+m))]},`${o}-${h}`))},o))})]})})]})}function ps(s){var v;const n=t.useEditorStore(j=>j.card),{authToken:a,tokenProps:r}=t.useSemaphorContext(),d=t.useEditorStore(j=>j.card.config),i=d==null?void 0:d.joinPlan,l={...s,alias:s.name,label:"value",role:"groupby"},c={...s,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},o={...l,role:"sortby",direction:"asc"},u={joinPlan:i,groupByColumns:[l],metricColumns:[c],sortByColumns:[o]},h=((v=n.dataSource)==null?void 0:v.connectionId)||n.connectionId,{data:x,isPending:p,error:m}=t.useQuery({queryKey:["filterValues",s.entityId,s.name,s.qualifiedEntityName],queryFn:async()=>{try{return await t.postRequestRegular(`${r.apiServiceUrl}/v1/query`,(a==null?void 0:a.accessToken)||"",{connection_id:h,cardConfig:u,cardDataSource:n.dataSource})}catch(j){console.log(s),console.error("error",j)}},enabled:!!h,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((x==null?void 0:x.records)||[]).map(j=>({label:j.value||"BLANK",value:j.value||"BLANK",count:(j==null?void 0:j.count)||0})),isPending:p,error:m}}function To({field:s,selected:n,onChange:a,placeholder:r="Select items...",className:d}){const[i,l]=Vt.useState(!1),{filterValues:c}=ps(s),o=h=>{a(n.filter(x=>x!==h))},u=h=>{n.includes(h)?a(n.filter(x=>x!==h)):a([...n,h])};return e.jsx("div",{className:t.cn("w-full",d),children:e.jsxs(t.Popover,{open:i,onOpenChange:l,modal:!0,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":i,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(h=>{const x=c.find(p=>p.value===h);return e.jsxs(t.Badge,{variant:"secondary",className:"text-xs",children:[x==null?void 0:x.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:p=>{p.key==="Enter"&&o(h)},onMouseDown:p=>{p.preventDefault(),p.stopPropagation()},onClick:p=>{p.stopPropagation(),o(h)},children:e.jsx(t.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},h)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(t.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No results found."}),e.jsx(t.CommandGroup,{children:c.map((h,x)=>e.jsxs(t.CommandItem,{onSelect:()=>u(h.value),children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",n.includes(h.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:h.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:h.count})]})]},h.value+x))})]})]})})]})})}function Eo({field:s,value:n,onChange:a,placeholder:r="Select value...",className:d}){const{filterValues:i,isPending:l,error:c}=ps(s);return l?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(t.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(t.Select,{value:n,onValueChange:a,children:[e.jsx(t.SelectTrigger,{className:d||"flex-1",children:e.jsx(t.SelectValue,{placeholder:r,children:n})}),e.jsx(t.SelectContent,{children:i.map((o,u)=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:o.value,children:o.label},o.value+u))})]})}function Io({value:s,operator:n,onChange:a,className:r}){var m,g,v;const{tokenProps:d}=t.useSemaphorContext(),i=((g=(m=d==null?void 0:d.params)==null?void 0:m.calendarContext)==null?void 0:g.tz)||((v=d==null?void 0:d.params)==null?void 0:v.timezone),l=i||Intl.DateTimeFormat().resolvedOptions().timeZone,c=n==="between"||n==="not between",o=N.useMemo(()=>{if(!(!s||!c)&&Array.isArray(s)&&s.length===2){const j=s[0]?new Date(s[0]):void 0,T=s[1]?new Date(s[1]):void 0;if(j&&T)return{from:j,to:T}}},[s,c]),u=N.useMemo(()=>{if(!s||c)return;const j=Array.isArray(s)?s[0]:s;if(!j)return;const T=new Date(j);if(!isNaN(T.getTime()))return T},[s,c]),h=j=>n==="<="||n===">"?t.endOfDayInTimezone(j,l):t.startOfDayInTimezone(j,l),x=j=>{if(!j){a([]);return}if(j.from&&j.to){a([j.from.toISOString(),j.to.toISOString()]);return}a([])},p=j=>{if(!j){a("");return}const T=h(j);a(T.toISOString())};return e.jsx(t.DateRangePicker,{value:c?o:void 0,selectionMode:c?"range":"single",singleValue:c?void 0:u,onChange:x,onSingleChange:p,timezone:i,showRelativeTab:c,className:r,placeholder:"Select date..."})}const Do=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],ko=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Ao=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],Mo=["=","!=","isNull","isNotNull"],Lo=["between","=","!=","<","<=",">",">=","isNull","isNotNull"],Fo={"=":"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 Ca(s){return Fo[s]||t.titleCase(s)}function Oo(s){switch(s){case"string":return ko;case"number":return Ao;case"boolean":return Mo;case"date":return Lo;default:return Do}}function Ka({condition:s,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:d,onRemoveCondition:i,onUpdateGroupOperator:l,availableFields:c,updateConditionFields:o}){const{attributes:u,listeners:h,setNodeRef:x,transform:p,transition:m,isDragging:g}=t.useSortable({id:s.id}),{isPending:v,error:j}=ps(s.field),T={transform:t.CSS.Transform.toString(p),transition:m};return e.jsxs("div",{ref:x,style:T,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${g?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...h,className:"cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),n>0&&e.jsxs(t.Select,{value:r,onValueChange:k=>l(a,k),children:[e.jsx(t.SelectTrigger,{className:"w-24",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),n===0&&e.jsx("div",{className:"w-24"}),e.jsx(wo,{value:s.field,onValueChange:k=>{const V=k,C=t.getDataType(V.dataType)==="date";o(a,s.id,{field:V,value:"",operator:C?"between":"="})},availableFields:c,placeholder:"Select field",className:"w-64"}),e.jsxs(t.Select,{value:s.operator,onValueChange:k=>{k==="in"||k==="not in"?o(a,s.id,{operator:k,value:[]}):k==="isNull"||k==="isNotNull"?o(a,s.id,{operator:k,value:null}):k==="between"||k==="not between"?o(a,s.id,{operator:k,value:[]}):o(a,s.id,{operator:k,value:""})},children:[e.jsx(t.SelectTrigger,{className:"w-32",children:e.jsx(t.SelectValue,{children:s.operator?Ca(s.operator):""})}),e.jsx(t.SelectContent,{children:Oo(t.getDataType(s.field.dataType)).map(k=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:k,children:Ca(k)},k))})]}),s.operator==="isNull"||s.operator==="isNotNull"?e.jsx("div",{className:"flex-1"}):t.getDataType(s.field.dataType)==="string"?s.operator==="in"||s.operator==="not in"?v?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(t.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):j?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(To,{field:s.field,selected:Array.isArray(s.value)&&s.value.every(k=>typeof k=="string")?s.value:[],onChange:k=>o(a,s.id,{value:k}),placeholder:`Select values for ${s.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(s.operator)?e.jsx(t.Input$1,{value:typeof s.value=="string"?s.value:"",onChange:k=>o(a,s.id,{value:k.target.value}),className:"flex-1",placeholder:s.operator.charAt(0).toUpperCase()+s.operator.slice(1)+"..."}):e.jsx(Eo,{field:s.field,value:typeof s.value=="string"?s.value:"",onChange:k=>o(a,s.id,{value:k}),placeholder:"Select value...",className:"flex-1"}):t.getDataType(s.field.dataType)==="boolean"?e.jsxs(t.Select,{value:typeof s.value=="boolean"?String(s.value):"",onValueChange:k=>o(a,s.id,{value:k==="true"}),children:[e.jsx(t.SelectTrigger,{className:"flex-1",children:e.jsx(t.SelectValue,{placeholder:"Select value..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"true",children:"True"}),e.jsx(t.SelectItem,{value:"false",children:"False"})]})]}):t.getDataType(s.field.dataType)==="date"?e.jsx(Io,{value:s.value,operator:s.operator,onChange:k=>o(a,s.id,{value:k}),className:"flex-1"}):e.jsx(t.Input$1,{value:typeof s.value=="string"||typeof s.value=="number"?s.value:"",onChange:k=>d(a,s.id,"value",k.target.value),className:"flex-1",placeholder:s.operator==="in"||s.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>i(a,s.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]})}function Ro({group:s,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:d,onRemoveGroup:i,onUpdateCondition:l,onUpdateField:c,onRemoveCondition:o,onReorderConditions:u,onReorderGroups:h,onAddCondition:x,onAddGroup:p,availableFields:m,renderFilterGroup:g,updateConditionFields:v}){const{attributes:j,listeners:T,setNodeRef:k,transform:V,transition:C,isDragging:M}=t.useSortable({id:s.id}),S={transform:t.CSS.Transform.toString(V),transition:C},I=E=>{const{active:b,over:O}=E;if(O&&b.id!==O.id){const y=s.conditions.findIndex(R=>R.id===b.id),L=s.conditions.findIndex(R=>R.id===O.id);y!==-1&&L!==-1&&u(s.id,y,L)}},D=E=>{const{active:b,over:O}=E;if(O&&b.id!==O.id&&a){const y=s.groups.findIndex(R=>R.id===b.id),L=s.groups.findIndex(R=>R.id===O.id);y!==-1&&L!==-1&&h(a,y,L)}};return e.jsxs("div",{ref:k,style:S,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${M?"z-50 opacity-50":""}`,children:[n>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...j,...T,className:"cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(t.Button,{variant:s.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>d(s.id,!s.negate),children:"NOT"}),e.jsxs(t.Select,{value:s.logicalOperator,onValueChange:E=>r(s.id,E),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>a&&i(a,s.id),children:e.jsx(t.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${n>0?"":"px-0"}`,children:[e.jsx(t.DndContext,{sensors:t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),collisionDetection:t.closestCenter,onDragEnd:I,children:e.jsx(t.SortableContext,{items:s.conditions.map(E=>E.id),strategy:t.verticalListSortingStrategy,children:s.conditions.map((E,b)=>e.jsx(Ka,{condition:E,index:b,groupId:s.id,groupLogicalOperator:s.logicalOperator,onUpdateCondition:l,onUpdateField:c,onRemoveCondition:o,onUpdateGroupOperator:r,availableFields:m,updateConditionFields:v},E.id))})}),e.jsx(t.DndContext,{sensors:t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),collisionDetection:t.closestCenter,onDragEnd:D,children:e.jsx(t.SortableContext,{items:s.groups.map(E=>E.id),strategy:t.verticalListSortingStrategy,children:s.groups.map(E=>g(E,n+1,s.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(t.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>x(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>p(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Bo({filters:s,availableFields:n,onSave:a,onClearAll:r,onCancel:d}){const{currentFilters:i,availableFields:l,isLoading:c,addCondition:o,addGroup:u,removeCondition:h,removeGroup:x,updateCondition:p,updateConditionFields:m,updateGroupOperator:g,updateGroupNegate:v,reorderConditions:j,reorderGroups:T,generateSQLPreview:k,hasAnyFilters:V,setCurrentFilters:C}=No({initialFilters:s,availableFields:n}),M=t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),[S,I]=N.useState(!1),D=(O,y,L)=>{const R=f=>f.id===O?{...f,conditions:f.conditions.map(A=>A.id===y?{...A,field:L,dataType:L.dataType}:A)}:{...f,groups:f.groups.map(R)};C(R(i))},E=(O,y=0,L)=>y===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(t.DndContext,{sensors:M,collisionDetection:t.closestCenter,onDragEnd:R=>{const{active:f,over:A}=R;if(A&&f.id!==A.id){const w=O.conditions.findIndex(F=>F.id===f.id),P=O.conditions.findIndex(F=>F.id===A.id);w!==-1&&P!==-1&&j(O.id,w,P)}},children:e.jsx(t.SortableContext,{items:O.conditions.map(R=>R.id),strategy:t.verticalListSortingStrategy,children:O.conditions.map((R,f)=>e.jsx(Ka,{condition:R,index:f,groupId:O.id,groupLogicalOperator:O.logicalOperator,onUpdateCondition:p,onUpdateField:D,onRemoveCondition:h,onUpdateGroupOperator:g,availableFields:l,updateConditionFields:m},R.id))})}),e.jsx(t.DndContext,{sensors:M,collisionDetection:t.closestCenter,onDragEnd:R=>{const{active:f,over:A}=R;if(A&&f.id!==A.id){const w=O.groups.findIndex(F=>F.id===f.id),P=O.groups.findIndex(F=>F.id===A.id);w!==-1&&P!==-1&&T(O.id,w,P)}},children:e.jsx(t.SortableContext,{items:O.groups.map(R=>R.id),strategy:t.verticalListSortingStrategy,children:O.groups.map(R=>E(R,y+1,O.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(t.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>o(O.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),S&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(O.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},O.id):e.jsx(Ro,{group:O,depth:y,parentGroupId:L,onUpdateGroupOperator:g,onUpdateGroupNegate:v,onRemoveGroup:x,onUpdateCondition:p,onUpdateField:D,onRemoveCondition:h,onReorderConditions:j,onReorderGroups:T,onAddCondition:o,onAddGroup:u,availableFields:l,renderFilterGroup:E,updateConditionFields:m},O.id),b=t.getFilterCount(s);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(t.Card,{children:e.jsx(t.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..."})]}):E(i),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(t.SmallSwitch,{id:"advanced-mode",checked:S,onCheckedChange:O=>I(O)}),e.jsx(t.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:k(i)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(t.Button,{size:"sm",variant:"outline",onClick:d,children:"Cancel"}),b>0&&e.jsx(t.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(t.Button,{size:"sm",onClick:()=>a(V?i:null),children:"Apply Filters"})]})]})}function Po({cardId:s,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:d,isOpen:i,onOpenChange:l}){const c=u=>{a(s,u),l(!1)},o=()=>{r(s),l(!1)};return e.jsxs(t.Dialog,{modal:!1,open:i,onOpenChange:l,children:[i&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(t.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:u=>{u.preventDefault()},children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Card Filters"}),e.jsx(t.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(Bo,{filters:n,availableFields:d,onSave:c,onCancel:()=>l(!1),onClearAll:o})]})]})}function Vo({activeCardId:s,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var k,V;const[d,i]=N.useState(null),l=t.useEditorStore(C=>C.card),c=t.useEditorStore(C=>C.actions.updateCardConfig),o=t.useEditorStore(C=>C.actions.setCardPreferences),u=(k=l==null?void 0:l.config)==null?void 0:k.joinPlan,h=N.useCallback(C=>C.entityName===t.CALCULATED_FIELD_ENTITY_MARKER||C.entityName==="calculated_fields"||C.qualifiedEntityName==="calculated_fields",[]),x=(V=l==null?void 0:l.dataSource)==null?void 0:V.semanticDomainId,{data:p}=t.useJoinabilityMap(x),m=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy"),...a("detailColumns")],g=N.useCallback(C=>C.startsWith("card-source-")?"source":C.startsWith("card-")?null:C.startsWith("source-")||n.find(M=>M.id===C)?"source":a("groupBy").find(M=>M.id===C)?"groupBy":a("metrics").find(M=>M.id===C)?"metrics":a("pivotBy").find(M=>M.id===C)?"pivotBy":a("sortBy").find(M=>M.id===C)?"sortBy":a("detailColumns").find(M=>M.id===C)?"detailColumns":null,[n,a]),v=N.useCallback(C=>{i(C.active.id)},[]),j=N.useCallback(C=>{var O;const{active:M,over:S}=C;if(!S||!s){i(null);return}const I=M.id,D=S.id,E=g(I),b=g(D)||D;if(b==="sortBy"){if(E==="source"){const y=n.find(R=>R.id===I);if(!y){i(null);return}if(!(a("groupBy").some(R=>R.name===y.name&&R.qualifiedEntityName===y.qualifiedEntityName)||a("metrics").some(R=>R.name===y.name&&R.qualifiedEntityName===y.qualifiedEntityName)||a("detailColumns").some(R=>R.name===y.name&&R.qualifiedEntityName===y.qualifiedEntityName))){i(null);return}}else if(E==="pivotBy"){i(null);return}else if(E!=="groupBy"&&E!=="metrics"&&E!=="sortBy"&&E!=="detailColumns"){i(null);return}}if(E==="source"&&b==="sortBy"){const y=[...n].find(A=>A.id===I);if(!y){i(null);return}const L=a("sortBy");if(t.fieldAlreadyExists(y,L)){i(null);return}const R=t.validateFieldForChartType(y,"sortBy",l.type);if(!R.isValid){t.ue.error("Invalid Field Type",{description:R.reason,position:"top-center",duration:3e3}),i(null);return}const f=t.getNewField(y,"sortBy",L);i(null),r("sortBy",[...L,f]);return}if(E==="source"&&b!=="source"&&b!=="sortBy"){const y=[...n].find(F=>F.id===I);if(!y){i(null);return}const L=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy"),...a("detailColumns")],R=L.filter(F=>!h(F));if(R.length>0){const F=R[0].qualifiedEntityName;if(!F){i(null);return}if(F!==y.qualifiedEntityName&&!h(y)&&y.qualifiedEntityName)if(x&&(p!=null&&p.joinabilityMap)){if(t.calculateFieldState(y,{joinabilityMap:p.joinabilityMap,selectedFields:L,baseEntityName:(O=u==null?void 0:u.baseEntity)==null?void 0:O.name}).state==="unreachable"){t.showJoinRequiredNotification(),i(null);return}}else{if(!u){t.showJoinRequiredNotification(),i(null);return}if(!t.areEntitiesJoined(F,y.qualifiedEntityName,u)){t.showJoinRequiredNotification(),i(null);return}}}const f=a(b);if(t.fieldAlreadyExists(y,f)){i(null);return}const A=t.validateFieldForChartType(y,b,l.type);if(!A.isValid){t.ue.error("Invalid Field Type",{description:A.reason,position:"top-center",duration:3e3}),i(null);return}const w=t.getNewField(y,b,f),P=[...f,w];if(i(null),r(b,P),b==="metrics"&&s){const F=t.seedSemanticMetricFormatDefaults(l,w,l.preferences);F&&o(F),t.cleanupKpiMetricComparisonMode(l.type,l.config,c,s,P)}return}if(E&&b&&E!=="source"&&b!=="source"&&E!==b){const y=a(E),L=a(b),R=y.find(F=>F.id===I);if(!R){i(null);return}const f=t.validateFieldForChartType(R,b,l.type);if(!f.isValid){t.ue.error("Invalid Field Type",{description:f.reason,position:"top-center",duration:3e3}),i(null);return}const A=t.getNewField(R,b,L);if(i(null),b==="sortBy"){t.fieldAlreadyExists(R,L)||r(b,[...L,A]);return}const w=y.filter(F=>F.id!==I),P=[...L,A];if(r(E,w),r(b,P),b==="metrics"&&s){const F=t.seedSemanticMetricFormatDefaults(l,A,l.preferences);F&&o(F),t.cleanupKpiMetricComparisonMode(l.type,l.config,c,s,P)}return}if(E&&b&&E===b&&E!=="source"){const y=a(E),L=y.findIndex(f=>f.id===I),R=y.findIndex(f=>f.id===D);if(L!==R){const f=t.arrayMove(y,L,R);r(E,f)}}i(null)},[s,n,a,r,g,u,x,p,h,l,c,o]),T=d?m.find(C=>C.id===d):null;return{activeId:d,activeField:T,handleDragStart:v,handleDragEnd:j}}function zo({activeView:s,onViewChange:n,splitViewEnabled:a}){const r=t.useEditorStore(c=>c.card),{config:d}=N.useContext(t.SemaphorContext).tokenProps,i=(d==null?void 0:d.showInfoTab)!==!1,l=()=>a?!1:t.getVisualizationMode(r)==="dynamic"?!0:!["table","pivotTable","aggregateTable","detailTable"].includes(r.type);return e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(t.Tabs,{value:s,onValueChange:c=>n(c),children:e.jsxs(t.TabsList,{className:"h-9 w-fit gap-1 bg-background p-0",children:[e.jsx(t.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),l()&&e.jsx(t.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),r.type!=="kpi"&&i&&e.jsx(t.TabsTrigger,{value:"info",className:"rounded-md transition data-[state=active]:bg-muted",children:"Info"})]})})})}const _o=[{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 qo(){var o,u;const s=t.useEditorStore(h=>h.card),{updateRowLimit:n}=t.useEditorActions(),[a,r]=N.useState(!1),[d,i]=N.useState(""),l=h=>{if(h==="custom"){r(!0);return}r(!1),n(s.id,parseInt(h))},c=h=>{const x=h.target.value;i(x),x&&!isNaN(parseInt(x))&&n(s.id,parseInt(x))};return e.jsx("div",{className:"flex items-center gap-2",children:a?e.jsx(t.Input,{type:"number",value:d,onChange:c,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(t.Select,{value:((u=(o=s.config)==null?void 0:o.rowLimit)==null?void 0:u.toString())||"100",onValueChange:l,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(t.SelectValue,{placeholder:"Select limit"})}),e.jsx(t.SelectContent,{children:_o.map(h=>e.jsx(t.SelectItem,{value:h.value,children:h.label},h.value))})]})})}function $o({card:s,queryData:n,isLoading:a,isFetching:r,pagination:d,onPaginationChange:i,onSortChange:l,sortState:c,splitViewEnabled:o,isDynamicInspectorOpen:u,onDynamicInspectorOpenChange:h}){const x=N.useMemo(()=>(n==null?void 0:n.records)||[],[n==null?void 0:n.records]),p=t.getVisualizationMode(s)==="dynamic",m=e.jsx(rt,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(Ra,{fallbackPreview:e.jsx(rt,{}),records:x,title:s.title,isInspectorOpen:u,onInspectorOpenChange:h})});return p?o?e.jsxs(t.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(t.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:m}),e.jsx(t.ResizableHandle,{withHandle:!0}),e.jsx(t.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(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),(n==null?void 0:n.records)&&e.jsx(t.TableVisual,{card:s,data:x,paginationMetadata:d,onPaginationChange:i,isLoading:a||r,onSortChange:l,sortState:c})]})})]}):m:!o||["table","pivotTable","aggregateTable","detailTable"].includes(s.type)?e.jsx(rt,{}):e.jsxs(t.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(t.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:e.jsx(rt,{})}),e.jsx(t.ResizableHandle,{withHandle:!0}),e.jsx(t.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(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),(n==null?void 0:n.records)&&e.jsx(t.TableVisual,{card:s,data:x,paginationMetadata:d,onPaginationChange:i,isLoading:a||r,onSortChange:l,sortState:c})]})})]})}const Ko="semaphor-split-view-enabled";function Go(){return Da(Ko,!0)}function Uo({activeView:s,onViewChange:n,onFiltersClick:a,activeCard:r,columns:d}){var xe,Z,ge;const i=t.useEditorStore(ae=>ae.card),l=t.useEditorStore(ae=>ae.inlineFilterValuesMap[(r==null?void 0:r.id)||""]),c=t.useEditorStore(ae=>ae.actions.removeCardInlineFilterValue),o=t.useDashboardStore(ae=>ae.filterValues),u=t.useDashboardStore(ae=>ae.selectedSheetId),{updateCardConfig:h,setCard:x,updateCardInFrame:p,setShowAIDialog:m}=t.useEditorActions(),g=t.useEditorStore(ae=>ae.showAIDialog),v=t.useEditorStore(ae=>ae.isDevMode),j=t.useDashboardStore(ae=>ae.isVisualEditing),[T,k]=N.useState(!1),[V,C]=N.useState(!1),[M,S]=N.useState(!1),[I,D]=N.useState(null),{config:E}=N.useContext(t.SemaphorContext).tokenProps,b=(E==null?void 0:E.showInfoTab)!==!1,O=(E==null?void 0:E.showQueryDebugTools)!==!1,[y,L]=Go();t.useEditorStore(ae=>{var ue;return!!((ue=ae.card.customCardPreferences)!=null&&ue.url)});const f=t.getVisualizationMode(i)==="dynamic",{data:A,errorMessage:w,isLoading:P,isFetching:F,errorSql:B,pagination:_,refetch:z,comparisonMetadata:G,queryRequestPayload:W}=t.useDashboardCardQuery(r),U=N.useMemo(()=>(A==null?void 0:A.records)||[],[A==null?void 0:A.records]),[Y,se]=N.useState(!1);N.useEffect(()=>{F||se(!1)},[F]);const ee=()=>{const ae=!y;ae&&s==="table"&&n("chart"),L(ae)},ce=(ae,ue)=>{const Le={...r,paginationConfig:{page:ae+1,pageSize:ue}};x(Le),p(Le)},re=ae=>{if(!i.config)return;const ue=t.sortStateToSortByColumns(ae,i.config.metricColumns,i.config.groupByColumns,i.config.detailColumns);h(i.id,{...i.config,sortByColumns:ue})},ne=N.useMemo(()=>{var ae;return t.sortByColumnsToSortState((ae=i.config)==null?void 0:ae.sortByColumns)},[(xe=i.config)==null?void 0:xe.sortByColumns]);return e.jsx("div",{className:t.cn("relative flex w-0 grow flex-col",{"border-l":g&&j}),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:[s==="chart"&&g&&!f&&e.jsx("div",{className:"w-[200px]",children:e.jsx(ds,{variant:v?"secondary":"ghost"})}),e.jsx(zo,{activeView:s,onViewChange:n,splitViewEnabled:y}),e.jsx(t.FilterInfo,{cardId:r.id,cardFilters:(Z=r.config)==null?void 0:Z.filters,cardFilterCount:t.getFilterCount(((ge=r.config)==null?void 0:ge.filters)||null),onFiltersClick:a,inlineFilters:r.inlineFilters,inlineFilterValues:l,sheetId:u||"",removeInlineFilterValue:ae=>c(r.id,ae)}),G&&i.type!=="table"&&e.jsx(t.ComparisonMetadataBadge,{metadata:G,variant:"compact"}),e.jsx("div",{className:"ml-2",children:e.jsx(qo,{})}),g&&e.jsx(Ae.EditorClearButton,{})]}),e.jsxs("div",{className:t.cn("flex grow items-center justify-end gap-2"),children:[e.jsx(t.IconButton,{tooltip:"Refresh",disabled:P||F,onClick:()=>{se(!0),z()},children:e.jsx(t.RefreshCcw,{className:t.cn("h-4 w-4",{"animate-spin":Y})})}),s==="chart"&&!f&&e.jsx(Oa,{showInlineFilters:!1,showDisplayOptions:!1}),!g&&e.jsx(t.IconButton,{onClick:()=>m(!g),tooltip:"AI",className:"h-8","aria-label":"AI",children:e.jsx(mn,{className:"size-4"})}),s==="chart"&&e.jsxs(t.DropdownMenu,{modal:!1,children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"More Options",className:"h-8","aria-label":"More options",children:e.jsx(t.EllipsisVertical,{className:"size-4"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(t.DropdownMenuLabel,{children:"More Options"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{onClick:ee,children:[y?e.jsx(fn,{className:"mr-2 h-4 w-4"}):e.jsx(kn,{className:"mr-2 h-4 w-4"}),y?"Hide Results Table":"Show Results Table"]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs("div",{className:"px-1 py-1",children:[e.jsx(ms,{triggerVariant:"menu",className:"w-full"}),e.jsx(us,{triggerVariant:"menu",className:"w-full"})]}),e.jsx(Ba,{onCustomize:()=>S(!0)})]})]})]})]}),e.jsxs("div",{className:"mt-2 flex min-h-0 grow flex-col",children:[s==="chart"&&e.jsx("div",{className:t.cn("flex grow flex-col pb-4",{"pb-0":y&&!["table","pivotTable","aggregateTable","detailTable"].includes(r.type)}),children:e.jsx($o,{card:r,queryData:A,isLoading:P,isFetching:F,pagination:_,onPaginationChange:ce,onSortChange:re,sortState:ne,splitViewEnabled:y,isDynamicInspectorOpen:M,onDynamicInspectorOpenChange:S})}),s==="table"&&(A==null?void 0:A.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:[(P||F)&&(A==null?void 0:A.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),e.jsx(t.TableVisual,{card:r,data:U,comparisonMetadata:G,paginationMetadata:_,onPaginationChange:ce,isLoading:P||F,onSortChange:re,sortState:ne})]}),s==="info"&&b&&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:w?e.jsx(cs,{error:w,errorSql:B,onSendFeedback:()=>{const ae=t.prepareFeedbackData(t.FeedbackCategory.QUERY_GENERATION,{cardConfig:i.config,dataSource:r.dataSource,dashboardFilters:o,errorMessage:w,errorSql:B,generatedSql:A==null?void 0:A.sql});D(ae),C(!0)},onOpenInEditor:()=>{m(!0),setTimeout(()=>{const ae=t.useEditorStore.getState().actions;ae.setIsDevMode(!0),ae.setCardSql(B||""),setTimeout(()=>{ae.setRunSql(!0)},100)},100)}}):(A==null?void 0:A.sql)&&e.jsx(Ma,{sql:A.sql,showCardDetails:!0,debugPayloads:O?{queryRequest:W,queryResponse:A,columns:d,dashboardFilters:o}:void 0})})})]}),I&&e.jsx(t.FeedbackDialog,{open:V,onOpenChange:C,feedbackData:I})]})})}function Ho({activeField:s}){const[n,a]=N.useState(!0);return N.useEffect(()=>{s&&a(!0)},[s]),s?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(t.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(t.IconForFieldType,{dataType:s.dataType}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-sm dark:text-muted-foreground",children:s.label||s.name})]}):null}const Qo=()=>{const s=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||s.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 d;if((d=r.reason)!=null&&d.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=s,window.removeEventListener("error",n,!0),window.removeEventListener("unhandledrejection",a,!0)}};function Jo({column:s,isSelected:n,onSelect:a,availableFields:r,width:d,onWidthChange:i}){var F,B,_;const l=t.useEditorStore(z=>z.card),{updateCardConfig:c,removeGroupByColumn:o,removeMetricColumn:u,updateFilters:h}=t.useEditorActions(),[x,p]=N.useState(!1),[m,g]=N.useState(!1),v=N.useRef(null),j=N.useCallback(z=>{z.preventDefault(),z.stopPropagation(),g(!0),v.current={startX:z.clientX,startWidth:d||150};const G=U=>{if(!v.current)return;const Y=U.clientX-v.current.startX,se=Math.max(80,v.current.startWidth+Y);i==null||i(s.id,se)},W=()=>{g(!1),v.current=null,document.removeEventListener("mousemove",G),document.removeEventListener("mouseup",W)};document.addEventListener("mousemove",G),document.addEventListener("mouseup",W)},[d,s.id,i]),T=(F=l==null?void 0:l.config)==null?void 0:F.filters,k=(B=T==null?void 0:T.conditions)==null?void 0:B.some(z=>z.field.name===s.name&&z.field.qualifiedEntityName===s.qualifiedEntityName),V=z=>{z?h(l.id,z):c(l.id,{filters:void 0})},{attributes:C,listeners:M,setNodeRef:S,transform:I,transition:D,isDragging:E}=t.useSortable({id:s.id}),b={transform:t.CSS.Transform.toString(I),transition:D},O=t.getDataType(s.dataType),y=Yo(O),L=()=>{var W;const z=((W=l==null?void 0:l.config)==null?void 0:W.sortByColumns)||[],G=z.findIndex(U=>U.name===s.name);if(G!==-1){const U=[...z];U[G]={...U[G],direction:"asc"},c(l.id,{sortByColumns:U})}else c(l.id,{sortByColumns:[...z,{...s,id:`sort-${s.id}`,role:"sortby",direction:"asc"}]})},R=()=>{var W;const z=((W=l==null?void 0:l.config)==null?void 0:W.sortByColumns)||[],G=z.findIndex(U=>U.name===s.name);if(G!==-1){const U=[...z];U[G]={...U[G],direction:"desc"},c(l.id,{sortByColumns:U})}else c(l.id,{sortByColumns:[...z,{...s,id:`sort-${s.id}`,role:"sortby",direction:"desc"}]})},f=()=>{var W;const z=((W=l==null?void 0:l.config)==null?void 0:W.groupByColumns)||[];if(!z.some(U=>U.name===s.name)){const U={...s,id:`groupby-${s.id}-${Date.now()}`,role:"groupby"};c(l.id,{groupByColumns:[...z,U]})}},A=z=>{var U;const G=((U=l==null?void 0:l.config)==null?void 0:U.metricColumns)||[];if(!G.some(Y=>Y.name===s.name&&Y.aggregate===z)){const Y={...s,id:`metric-${s.id}-${z}-${Date.now()}`,label:`${z} of ${s.label||s.name}`,role:"metric",aggregate:z};c(l.id,{metricColumns:[...G,Y]})}},w=()=>{s.role==="groupby"?o(l.id,s.id):s.role==="metric"&&u(l.id,s.id)},P={...b,width:d?`${d}px`:void 0,minWidth:d?`${d}px`:"120px"};return e.jsxs("th",{ref:S,style:P,className:t.cn("group relative border-r border-border bg-background px-1 py-0",E&&"opacity-50",n&&"bg-primary/10",m&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...C,...M,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(t.GripVertical,{className:"h-3 w-3"})}),e.jsxs(t.DropdownMenu,{children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsxs("button",{onClick:a,className:t.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(y,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:s.label||s.name}),s.role==="metric"&&s.aggregate&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",s.aggregate,")"]}),k&&e.jsx(t.Filter,{className:"h-3 w-3 text-primary"})]}),e.jsx(t.ChevronDown,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsxs(t.DropdownMenuContent,{align:"start",className:"w-48",children:[e.jsxs(t.DropdownMenuItem,{onClick:()=>p(!0),children:[e.jsx(t.Filter,{className:t.cn("mr-2 h-4 w-4",k&&"text-primary")}),k?"Edit Filter":"Filter"]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{onClick:L,children:[e.jsx(un,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(t.DropdownMenuItem,{onClick:R,children:[e.jsx(dn,{className:"mr-2 h-4 w-4"}),"Sort Z → A"]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuSub,{children:[e.jsxs(t.DropdownMenuSubTrigger,{children:[e.jsx(t.Calculator,{className:"mr-2 h-4 w-4"}),"Summarize"]}),e.jsxs(t.DropdownMenuSubContent,{children:[e.jsx(t.DropdownMenuItem,{onClick:()=>A("SUM"),children:"Sum"}),e.jsx(t.DropdownMenuItem,{onClick:()=>A("AVG"),children:"Average"}),e.jsx(t.DropdownMenuItem,{onClick:()=>A("COUNT"),children:"Count"}),e.jsx(t.DropdownMenuItem,{onClick:()=>A("DISTINCT"),children:"Count Distinct"}),e.jsx(t.DropdownMenuItem,{onClick:()=>A("MIN"),children:"Min"}),e.jsx(t.DropdownMenuItem,{onClick:()=>A("MAX"),children:"Max"})]})]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{onClick:f,children:[e.jsx(qt,{className:"mr-2 h-4 w-4"}),"Group by this column"]}),e.jsxs(t.DropdownMenuItem,{disabled:!0,children:[e.jsx(is,{className:"mr-2 h-4 w-4"}),"Pivot by this column"]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{disabled:!0,children:[e.jsx(t.EyeOff,{className:"mr-2 h-4 w-4"}),"Hide column"]}),e.jsxs(t.DropdownMenuItem,{onClick:w,className:"text-destructive focus:text-destructive",children:[e.jsx(t.Trash2,{className:"mr-2 h-4 w-4"}),"Remove column"]})]})]})]}),e.jsx("div",{onMouseDown:j,className:t.cn("absolute right-0 top-0 h-full w-1 cursor-col-resize bg-transparent hover:bg-primary/50",m&&"bg-primary")}),e.jsx($a,{open:x,onOpenChange:p,availableFields:r.length>0?r:[s],existingFilters:T,editingCondition:k?(_=T==null?void 0:T.conditions)==null?void 0:_.find(z=>z.field.name===s.name&&z.field.qualifiedEntityName===s.qualifiedEntityName):void 0,onSave:V})]})}function Yo(s){switch(s){case"number":return t.Hash;case"date":return t.Calendar;case"string":default:return t.Type}}function Wo({selectedColumn:s,onColumnSelect:n,isLoading:a=!1,sourceFields:r=[],filterableFields:d=r}){var E,b,O,y;const i=t.useEditorStore(L=>L.card),{updateCardConfig:l}=t.useEditorActions(),[c,o]=N.useState(null),[u,h]=N.useState({}),[x,p]=N.useState(!1),m=N.useMemo(()=>{var f,A;const L=((f=i==null?void 0:i.config)==null?void 0:f.groupByColumns)||[],R=((A=i==null?void 0:i.config)==null?void 0:A.metricColumns)||[];return[...L,...R]},[(E=i==null?void 0:i.config)==null?void 0:E.groupByColumns,(b=i==null?void 0:i.config)==null?void 0:b.metricColumns]),g=N.useMemo(()=>{const L=new Set(m.map(R=>`${R.qualifiedEntityName}.${R.name}`));return r.filter(R=>!L.has(`${R.qualifiedEntityName}.${R.name}`))},[r,m]),{data:v,isLoading:j}=t.useDashboardCardQuery(i),T=(v==null?void 0:v.records)||[],k=N.useCallback((L,R)=>{h(f=>({...f,[L]:R}))},[]),V=N.useCallback(L=>{var w,P;const R=t.getDataType(L.dataType),f=((w=i==null?void 0:i.config)==null?void 0:w.groupByColumns)||[],A=((P=i==null?void 0:i.config)==null?void 0:P.metricColumns)||[];if(R==="number"){const F={...L,id:`metric-${L.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};l(i.id,{metricColumns:[...A,F]})}else{const F={...L,id:`groupby-${L.id}-${Date.now()}`,role:"groupby"};l(i.id,{groupByColumns:[...f,F]})}p(!1)},[(O=i==null?void 0:i.config)==null?void 0:O.groupByColumns,(y=i==null?void 0:i.config)==null?void 0:y.metricColumns,i.id,l]),C=t.useSensors(t.useSensor(t.PointerSensor,{activationConstraint:{distance:8}})),M=L=>{o(L.active.id)},S=L=>{const{active:R,over:f}=L;if(o(null),!f||R.id===f.id)return;const A=m.findIndex(P=>P.id===R.id),w=m.findIndex(P=>P.id===f.id);if(A!==-1&&w!==-1){const P=t.arrayMove(m,A,w),F=P.filter(_=>_.role==="groupby"),B=P.filter(_=>_.role==="metric");l(i.id,{groupByColumns:F,metricColumns:B})}},I=c?m.find(L=>L.id===c):null,D=L=>{let R="";for(;L>=0;)R=String.fromCharCode(L%26+65)+R,L=Math.floor(L/26)-1;return R};return a?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(t.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):m.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(t.DndContext,{sensors:C,collisionDetection:t.closestCenter,onDragStart:M,onDragEnd:S,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(t.SortableContext,{items:m.map(L=>L.id),strategy:t.horizontalListSortingStrategy,children:m.map((L,R)=>e.jsx("th",{style:{width:u[L.id]?`${u[L.id]}px`:void 0,minWidth:u[L.id]?`${u[L.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-${L.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(t.SortableContext,{items:m.map(L=>L.id),strategy:t.horizontalListSortingStrategy,children:m.map(L=>e.jsx(Jo,{column:L,isSelected:(s==null?void 0:s.id)===L.id,onSelect:()=>n(L),availableFields:d,width:u[L.id],onWidthChange:k},L.id))}),e.jsx("th",{className:"w-10 border-r border-border bg-background px-1 py-2",children:e.jsxs(t.Popover,{open:x,onOpenChange:p,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Add column",children:e.jsx(t.Plus,{className:"h-4 w-4"})})}),e.jsx(t.PopoverContent,{className:"w-[280px] p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search columns..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No columns available."}),e.jsx(t.CommandGroup,{heading:"Available Columns",children:g.map(L=>{const R=t.getDataType(L.dataType),f=R==="number"?t.Hash:R==="date"?t.Calendar:t.Type;return e.jsxs(t.CommandItem,{value:L.label||L.name,onSelect:()=>V(L),children:[e.jsx(f,{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:L.label||L.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:L.entityName})]})]},L.id)})})]})]})})]})})]})]}),e.jsx("tbody",{children:j?e.jsx("tr",{children:e.jsx("td",{colSpan:m.length+2,className:"h-32 text-center",children:e.jsx(t.LoaderCircle,{className:"mx-auto h-6 w-6 animate-spin text-muted-foreground"})})}):T.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:m.length+2,className:"h-32 text-center text-muted-foreground",children:"No data available"})}):T.slice(0,100).map((L,R)=>e.jsxs("tr",{className:t.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}),m.map(f=>{const A=L[f.name]??L[f.label??""];return e.jsx("td",{style:{width:u[f.id]?`${u[f.id]}px`:void 0,minWidth:u[f.id]?`${u[f.id]}px`:"120px"},className:t.cn("border-r border-border px-3 py-2 text-sm",(s==null?void 0:s.id)===f.id&&"bg-primary/5"),children:e.jsx("span",{className:"block truncate",children:Xo(A,f)})},`${R}-${f.id}`)}),e.jsx("td",{className:"w-10 border-r border-border"})]},R))})]}),e.jsx(t.DragOverlay,{children:I&&e.jsx("div",{className:"rounded border border-primary bg-background px-3 py-2 text-sm font-medium shadow-lg",children:I.label||I.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(T.length,100)," of ",T.length," rows"]}),e.jsxs("span",{children:[m.length," columns"]})]})]})}function Xo(s,n){if(s==null)return"—";if(typeof s=="number")return n.role==="metric"?new Intl.NumberFormat("en-US",{minimumFractionDigits:0,maximumFractionDigits:2}).format(s):s.toString();if(s instanceof Date||typeof s=="string"&&!isNaN(Date.parse(s))){const a=new Date(s);if(!isNaN(a.getTime()))return a.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}return String(s)}function Zo({entityGroups:s,isLoading:n=!1}){var V,C;const a=t.useEditorStore(M=>M.card),{updateCardConfig:r,removeGroupByColumn:d,removeMetricColumn:i}=t.useEditorActions(),[l,c]=N.useState(!0),[o,u]=N.useState(""),[h,x]=N.useState(new Set),p=((V=a==null?void 0:a.config)==null?void 0:V.groupByColumns)||[],m=((C=a==null?void 0:a.config)==null?void 0:C.metricColumns)||[],g=M=>{const S=new Set(h);S.has(M)?S.delete(M):S.add(M),x(S)},v=M=>p.some(S=>S.name===M.name&&S.qualifiedEntityName===M.qualifiedEntityName)||m.some(S=>S.name===M.name&&S.qualifiedEntityName===M.qualifiedEntityName),j=(M,S)=>{if(S)if(t.getDataType(M.dataType)==="number"){const D={...M,id:`metric-${M.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};r(a.id,{metricColumns:[...m,D]})}else{const D={...M,id:`groupby-${M.id}-${Date.now()}`,role:"groupby"};r(a.id,{groupByColumns:[...p,D]})}else{const I=p.findIndex(E=>E.name===M.name&&E.qualifiedEntityName===M.qualifiedEntityName),D=m.findIndex(E=>E.name===M.name&&E.qualifiedEntityName===M.qualifiedEntityName);I!==-1&&d(a.id,p[I].id),D!==-1&&i(a.id,m[D].id)}},T=M=>{if(!o)return M;const S=o.toLowerCase();return M.filter(I=>I.name.toLowerCase().includes(S)||I.label&&I.label.toLowerCase().includes(S))},k=M=>{switch(t.getDataType(M)){case"number":return t.Hash;case"date":return t.Calendar;default:return t.Type}};return l?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(t.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(Cn,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"border-b border-border p-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(t.Search,{className:"absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),e.jsx(t.Input,{placeholder:"Search columns...",value:o,onChange:M=>u(M.target.value),className:"h-8 pl-8 text-sm"})]})}),(p.length>0||m.length>0)&&e.jsxs("div",{className:"border-b border-border",children:[p.length>0&&e.jsxs(t.Collapsible,{defaultOpen:!0,children:[e.jsxs(t.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(t.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(qt,{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:p.length})]}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:p.map(M=>{const S=k(M.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(t.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(S,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:M.label||M.name}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>d(a.id,M.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]},M.id)})})})]}),m.length>0&&e.jsxs(t.Collapsible,{defaultOpen:!0,children:[e.jsxs(t.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(t.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(t.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:m.length})]}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:m.map(M=>{const S=k(M.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(t.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(S,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:M.label||M.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:M.aggregate}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>i(a.id,M.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]},M.id)})})})]})]}),e.jsx(t.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"})}):s.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No columns available"}):s.map(M=>{const S=T(M.columns);if(S.length===0)return null;const I=h.has(M.entityId)||o.length>0;return e.jsxs(t.Collapsible,{open:I,onOpenChange:()=>g(M.entityId),children:[e.jsxs(t.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(t.ChevronRight,{className:t.cn("h-3.5 w-3.5 transition-transform duration-200",I&&"rotate-90")}),e.jsx(t.Table2,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate text-left",children:M.label||M.entityName}),e.jsx("span",{className:"text-xs text-muted-foreground",children:S.length})]}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:S.map(D=>{const E=k(D.dataType),b=v(D);return e.jsxs("label",{className:t.cn("flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-sm transition-colors hover:bg-muted/50",b&&"bg-primary/5"),children:[e.jsx(t.Checkbox,{checked:b,onCheckedChange:O=>j(D,O),className:"h-3.5 w-3.5"}),e.jsx(E,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:D.label||D.name})]},D.id)})})})]},M.entityId)})})})]}):e.jsx("div",{className:"flex h-full items-start border-l border-border bg-muted/30 p-2",children:e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>c(!0),title:"Open panel",children:e.jsx(Sn,{className:"h-4 w-4"})})})}const ei=[{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 ti({value:s,onChange:n,onSubmit:a,onCancel:r,selectedColumn:d,availableColumns:i}){const[l,c]=N.useState(!1),[o,u]=N.useState("column"),h=N.useRef(null);N.useEffect(()=>{const g=v=>{v.key==="Escape"&&s?r():v.key==="Enter"&&s&&!l&&a(s)};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[s,r,a,l]);const x=g=>{const v=`[${g.label||g.name}]`,j=h.current;if(j){const T=j.selectionStart||0,k=j.selectionEnd||0,V=s.slice(0,T)+v+s.slice(k);n(V),setTimeout(()=>{j.setSelectionRange(T+v.length,T+v.length),j.focus()},0)}else n(s+v);c(!1)},p=g=>{const v=h.current;if(v){const j=v.selectionStart||0,T=v.selectionEnd||0,k=s.slice(0,j)+g.syntax+s.slice(T);n(k),setTimeout(()=>{v.setSelectionRange(j+g.name.length+1,j+g.syntax.length-1),v.focus()},0)}else n(s+g.syntax);c(!1)},m=g=>{switch(t.getDataType(g)){case"number":return t.Hash;case"date":return t.Calendar;default:return t.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:d?e.jsx("span",{className:"truncate",children:d.label||d.name}):e.jsx("span",{children:"—"})}),e.jsxs(t.Popover,{open:l&&o==="function",onOpenChange:g=>{c(g),g&&u("function")},children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Insert function",children:e.jsx(Dn,{className:"h-4 w-4"})})}),e.jsx(t.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search functions..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No functions found."}),e.jsx(t.CommandGroup,{heading:"Functions",children:ei.map(g=>e.jsx(t.CommandItem,{value:g.name,onSelect:()=>p(g),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:g.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:g.description})]}),e.jsx("span",{className:"font-mono text-xs text-muted-foreground/75",children:g.syntax})]})},g.name))})]})]})})]}),e.jsxs(t.Popover,{open:l&&o==="column",onOpenChange:g=>{c(g),g&&u("column")},children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.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(t.ChevronDown,{className:"h-3 w-3"})]})}),e.jsx(t.PopoverContent,{className:"w-[250px] p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search columns..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No columns found."}),e.jsx(t.CommandGroup,{heading:"Available Columns",children:i.map(g=>{const v=m(g.dataType);return e.jsxs(t.CommandItem,{value:g.label||g.name,onSelect:()=>x(g),children:[e.jsx(v,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:g.label||g.name})]},g.id)})})]})]})})]}),e.jsx("div",{className:"relative flex-1",children:e.jsx(t.Input,{ref:h,value:s,onChange:g=>n(g.target.value),placeholder:"Enter a formula or select a column...",className:"h-7 border-border bg-background font-mono text-sm"})}),s&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(t.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(t.X,{className:"h-4 w-4"})}),e.jsx(t.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(s),title:"Apply (Enter)",children:e.jsx(t.Check,{className:"h-4 w-4"})})]})]})}function si({className:s}){var m,g,v,j;const n=t.useEditorStore(T=>T.card),[a,r]=N.useState(null),[d,i]=N.useState(""),{columns:l=[],columnGroups:c=[],isLoading:o}=t.useColumns(),{valuePickFilterableFields:u=[]}=t.useFilterableFields();(m=n==null?void 0:n.config)!=null&&m.groupByColumns,(g=n==null?void 0:n.config)!=null&&g.metricColumns,(v=n==null?void 0:n.config)!=null&&v.groupByColumns,(j=n==null?void 0:n.config)!=null&&j.pivotByColumns;const h=T=>{r(T),i(T?`[${T.label||T.name}]`:"")},x=T=>{console.log("Formula submitted:",T),i(""),r(null)},p=()=>{i(""),r(null)};return e.jsxs("div",{className:t.cn("flex h-full w-full flex-col",s),children:[e.jsx(ti,{value:d,onChange:i,onSubmit:x,onCancel:p,selectedColumn:a,availableColumns:l}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(Wo,{selectedColumn:a,onColumnSelect:h,isLoading:o,sourceFields:l,filterableFields:u})}),e.jsx(Zo,{entityGroups:c,isLoading:o})]})]})}function ai(){var w,P;const[s,n]=N.useState("chart"),[a,r]=N.useState(!1),[d,i]=N.useState(!0),l=t.useEditorStore(F=>F.showAIDialog),c=t.useDashboardStore(F=>F.isVisualEditing),{setCardType:o}=t.useEditorActions(),u=t.useEditorStore(F=>F.card.type);N.useEffect(()=>Qo(),[]);const h=F=>{o(F)},x=t.useEditorStore(F=>F.frame),p=t.useEditorStore(F=>F.card);t.useEditorStore(F=>F.activeTabCardId),t.useEditorStore(F=>F.actions.getAvailableFields);const{addCard:m,removeCard:g,updateCard:v,setActiveCard:j,updateFilters:T}=t.useEditorActions(),{columnFields:k=[],scopedFields:V=[],filterableFields:C=[]}=t.useFilterableFields(),M=t.useSensors(t.useSensor(t.PointerSensor,{activationConstraint:{distance:8}})),S=p,{getFieldsForContainer:I,setFieldsForContainer:D}=t.useFieldManagement(S),{activeField:E,handleDragStart:b,handleDragEnd:O}=Vo({activeCardId:x.activeCardId,sourceFields:V,getFieldsForContainer:I,setFieldsForContainer:D}),y=(F,B)=>{B&&T(F,B)},L=F=>{var B;v(F,{config:{...(B=x.cards.find(_=>_.id===F))==null?void 0:B.config,filters:void 0}})},R=C,f=F=>{if(!F)return 0;let B=F.conditions.length;return F.groups.forEach(_=>{B+=f(_)}),B},A=f(((w=S==null?void 0:S.config)==null?void 0:w.filters)||null);return e.jsxs(t.DndContext,{sensors:M,collisionDetection:t.closestCenter,onDragStart:b,onDragEnd:O,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(ka,{isVisible:d,onToggleVisibility:()=>i(!d)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:u==="tableBuilder"?e.jsx(si,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!l&&e.jsx(yo,{selectedChart:u,onChartChange:h,groupByFields:I("groupBy"),pivotByFields:I("pivotBy"),metricsFields:I("metrics"),sortByFields:I("sortBy"),detailFields:I("detailColumns"),activeField:E}),e.jsx(Uo,{selectedChart:u,activeView:s,onViewChange:n,onFiltersClick:()=>r(!0),filterCount:A,activeCard:S,columns:k,getFieldsForContainer:I,cards:x.cards,activeCardId:x.activeCardId,addCard:m,setActiveCard:j})]})}),!d&&c&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(t.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>i(!0),title:"Show Data Source Panel",children:e.jsx(t.Database,{className:"h-4 w-4"})})})]}),S&&e.jsx(Po,{cardId:S.id,filters:((P=S.config)==null?void 0:P.filters)||null,onFiltersChange:y,onClearFilters:L,availableFields:R,isOpen:a,onOpenChange:r}),e.jsx(t.DragOverlay,{dropAnimation:null,children:e.jsx(Ho,{activeField:E||null})})]})}function ni({authToken:s,onSave:n,onClose:a}){const r=N.useRef(null),d=t.useEditorStore(S=>S.showAIDialog),i=t.useEditorStore(S=>S.isDevMode),l=t.useAssistantLayoutStore(S=>S.setFullscreen),c=t.useAssistantLayoutStore(S=>S.setPanelOpen),o=t.useAssistantLayoutStore(S=>S.setContainer),u=t.useAssistantPanel("editor"),h=t.useFullscreenAssistant(),x=t.useAssistantContainer("editor"),p=h==="editor",m=N.useCallback(S=>{o("editor",S)},[o]),{setAuthToken:g}=t.useDashboardActions(),{setShowAIDialog:v,setOnSave:j,setOnClose:T}=t.useEditorActions(),{setActiveAssistantType:k}=t.useAIActions();N.useEffect(()=>{n&&j(n),a&&T(a)},[n,j,a,T]),N.useEffect(()=>{s&&s.accessToken&&g(s)},[s,g]),N.useEffect(()=>{var S,I;d?((S=r.current)==null||S.resize(40),c("editor",!0),k("editor")):((I=r.current)==null||I.resize(0),c("editor",!1),h==="editor"&&l(null),k(null))},[d,c,k,l,h]);function V(S){var I;S<1?(v(!1),c("editor",!1),h==="editor"&&l(null),k(null),(I=r.current)==null||I.resize(0)):(d||(v(!0),k("editor")),u.isOpen||c("editor",!0))}function C(){return e.jsxs(e.Fragment,{children:[e.jsx(ka,{isVisible:!0,onToggleVisibility:()=>{}}),e.jsxs("div",{className:"relative flex grow",children:[e.jsxs(t.ResizablePanelGroup,{"data-content":"editor-main",className:t.cn("grow transition-opacity",p&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(so,{})}),e.jsx(t.ResizableHandle,{disabled:!d}),e.jsx(t.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:V,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(ya,{isFullscreen:p,onFullscreenChange:S=>l(S?"editor":null),fullscreenContainer:x})})})]}),e.jsx("div",{ref:m,className:t.cn("absolute inset-0",!p&&"pointer-events-none")})]})]})}function M(){return e.jsxs("div",{className:"relative flex h-full grow",children:[e.jsxs(t.ResizablePanelGroup,{"data-content":"explorer",className:t.cn("flex grow transition-opacity",p&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(ai,{})}),e.jsx(t.ResizableHandle,{disabled:!d}),e.jsx(t.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:V,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(ya,{isFullscreen:p,onFullscreenChange:S=>l(S?"editor":null),fullscreenContainer:x})})})]}),e.jsx("div",{ref:m,className:t.cn("absolute inset-0",!p&&"pointer-events-none")})]})}return e.jsx(t.ErrorBoundary,{FallbackComponent:t.Fallback,children:i?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:C()}):M()})}function ri(){t.useDashboardStore(o=>o.selectedCardId);const s=t.useDashboardStore(o=>o.selectedSheetId),n=t.useDashboardStore(o=>o.dashboard),{setIsVisualEditing:a,setSelectedSheetId:r}=t.useDashboardStore(o=>o.actions),d=t.useDashboardStore(o=>o.isVisualEditing),i=t.useDashboardStore(o=>o.actions.updateFrame);function l(o){var p,m,g;const u=s?(p=n==null?void 0:n.sheets)==null?void 0:p.some(v=>{var j;return v.id===s&&((j=v.frames)==null?void 0:j.some(T=>T.id===o.id))}):!1,h=(g=(m=n==null?void 0:n.sheets)==null?void 0:m.find(v=>{var j;return(j=v.frames)==null?void 0:j.some(T=>T.id===o.id)}))==null?void 0:g.id,x=u?s:h||null;x&&(i(x,o),s!==x&&r(x),a(!1))}function c(){a(!1)}return e.jsx("div",{role:"editor-container",className:t.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!d}),children:e.jsx(ni,{onSave:l,onClose:c})})}exports.default=ri;
|