react-semaphor 0.1.287 → 0.1.289
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-B8xnCPTZ.js → dashboard-controls-BZpyFg-k.js} +4 -4
- package/dist/chunks/{dashboard-controls-C25JMBLV.js → dashboard-controls-Dsh15H8E.js} +1 -1
- package/dist/chunks/{dashboard-filter-controls-button-D-o6ofi2.js → dashboard-filter-controls-button-CG5DgZpQ.js} +3 -3
- package/dist/chunks/{dashboard-filter-controls-button-BOJUiKGk.js → dashboard-filter-controls-button-DJvp8skg.js} +1 -1
- package/dist/chunks/{dashboard-json-DFuRB4cG.js → dashboard-json-CPhdiaLF.js} +1 -1
- package/dist/chunks/{dashboard-json-BYCWtm_z.js → dashboard-json-cootX4Nq.js} +1 -1
- package/dist/chunks/{dashboard-summary-settings-dialog-CsnHeIhi.js → dashboard-summary-settings-dialog-DOaMWikr.js} +1 -1
- package/dist/chunks/{dashboard-summary-settings-dialog-CFTJNcmp.js → dashboard-summary-settings-dialog-F6Dl15za.js} +1 -1
- package/dist/chunks/{edit-dashboard-visual-YmESbDUP.js → edit-dashboard-visual-DIpn7oJy.js} +4354 -4315
- package/dist/chunks/edit-dashboard-visual-fAiZdiCV.js +188 -0
- package/dist/chunks/{index-Bz0-3JKw.js → index-Cab2h5Fi.js} +1917 -1915
- package/dist/chunks/{index-BDE8cMG8.js → index-CnmC-NR5.js} +38 -38
- package/dist/chunks/{resource-management-panel-Lxjcn4i0.js → resource-management-panel-AZ46U35q.js} +2 -2
- package/dist/chunks/{resource-management-panel-C6qnO0ID.js → resource-management-panel-gJirpIDQ.js} +1 -1
- package/dist/chunks/{use-create-flow-overlay-state-AXNDXDqV.js → use-create-flow-overlay-state-3oPHFeIs.js} +1 -1
- package/dist/chunks/{use-create-flow-overlay-state-CJiyn4FY.js → use-create-flow-overlay-state-B6yjr4UZ.js} +2 -2
- package/dist/chunks/use-visual-utils-CyzOMb7j.js +334 -0
- package/dist/chunks/use-visual-utils-DmENJikx.js +1 -0
- 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/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +2 -2
- package/dist/types/main.d.ts +5 -0
- package/dist/types/types.d.ts +5 -0
- package/package.json +1 -1
- package/dist/chunks/edit-dashboard-visual-DU3NzdD5.js +0 -193
- package/dist/chunks/use-visual-utils-BygqTxyR.js +0 -1
- package/dist/chunks/use-visual-utils-CWVz-eYg.js +0 -353
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),t=require("./index-CnmC-NR5.js"),y=require("react"),it=require("./use-visual-utils-DmENJikx.js"),De=require("./use-create-flow-overlay-state-3oPHFeIs.js"),cn=require("react-dom");function dn(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 Pt=dn(y);/**
|
|
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 un=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 mn=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 Ta=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 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"}]]);/**
|
|
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 cs=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"}]]);/**
|
|
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 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"}]]);/**
|
|
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 Ea=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"}]]);/**
|
|
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 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"}]]);/**
|
|
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 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"}]]);/**
|
|
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 Ia=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"}]]);/**
|
|
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 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"}]]);/**
|
|
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 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"}]]);/**
|
|
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 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"}]]);/**
|
|
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 sa=t.createLucideIcon("ListFilter",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M7 12h10",key:"b7w52i"}],["path",{d:"M10 18h4",key:"1ulq68"}]]);/**
|
|
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 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"}]]);/**
|
|
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 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"}]]);/**
|
|
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 Wt=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"}]]);/**
|
|
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 Xt=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"}]]);/**
|
|
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 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"}]]);/**
|
|
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 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"}]]);/**
|
|
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 Sn=t.createLucideIcon("PanelRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
|
|
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 os=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"}]]);/**
|
|
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 zt=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"}]]);/**
|
|
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 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"}]]);/**
|
|
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 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"}]]);/**
|
|
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 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"}]]);/**
|
|
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 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"}]]);/**
|
|
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 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"}]]);/**
|
|
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 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"}]]);/**
|
|
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 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"}]]);/**
|
|
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 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 Da({storeValue:s,defaultValue:n="",onStoreUpdate:a,delay:r=300}){const[c,i]=y.useState(s??n),l=y.useRef(null),d=y.useRef(c),o=y.useRef(s),u=y.useRef(!1),p=y.useCallback(()=>{l.current&&(clearTimeout(l.current),l.current=null),u.current&&d.current!==(o.current??n)&&(a(d.current),o.current=d.current)},[n,a]);y.useEffect(()=>{if(s!==o.current){l.current&&(clearTimeout(l.current),l.current=null);const h=s??n;i(h),d.current=h,o.current=s,u.current=!1}},[s,n]),y.useEffect(()=>{if(u.current)return l.current=setTimeout(()=>{p()},r),()=>{l.current&&(clearTimeout(l.current),l.current=null)}},[r,p,c]),y.useEffect(()=>()=>{l.current&&clearTimeout(l.current)},[]);const x=y.useCallback(h=>{const m=h??n;u.current=!0,d.current=m,i(m)},[n]);return{value:c,onChange:x,flush:p}}function Ln({initialJoinPlan:s,availableDataSources:n}){const[a,r]=y.useState(s),[c,i]=y.useState(new Set),l=()=>{const w=a.joins.length>0?Math.max(...a.joins.map(I=>I.sequence))+1:1,D={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:w,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...a,joins:[...a.joins,D]}),i(new Set([...c,D.id]))},d=w=>{r({...a,joins:a.joins.filter(D=>D.id!==w)}),i(new Set([...c].filter(D=>D!==w)))},o=(w,D)=>{var N,L,F,f,A;const I=a.joins.find(T=>T.id===w);if(!I)return;const k={...I,...D};if((N=k.source)!=null&&N.name&&((L=k.target)!=null&&L.name)&&k.source.name===k.target.name){t.ue.error("Self-joins are not yet supported",{description:`Joining ${k.source.name} to itself is not currently supported. Please select a different target table.`});return}const j=a.joins.filter(T=>{var V;return T.id!==w&&T.target.name===((V=k.target)==null?void 0:V.name)});if((F=k.target)!=null&&F.name&&j.length>0){t.ue.error("Duplicate join targets are not supported",{description:`The table ${k.target.name} is already used as a target in another join. Each table can only be joined once.`});return}const R=a.joins.map(T=>T.id===w?k:T);if((f=k.source)!=null&&f.name&&((A=k.target)!=null&&A.name)&&k.joinKeyGroups[0].keys.length===0){const T=n.find(_=>{var z;return _.name===((z=k.source)==null?void 0:z.name)}),V=n.find(_=>{var z;return _.name===((z=k.target)==null?void 0:z.name)}),O={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(T==null?void 0:T.name)||"",entityName:(T==null?void 0:T.name)||"",entityType:(T==null?void 0:T.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(V==null?void 0:V.name)||"",entityName:(V==null?void 0:V.name)||"",entityType:(V==null?void 0:V.type)||"table"},operator:"="},P=[...k.joinKeyGroups];P[0]={...P[0],keys:[O]},k.joinKeyGroups=P,R[R.findIndex(_=>_.id===w)]=k}r({...a,joins:R})};return{joinPlan:a,expandedJoins:c,setJoinPlan:r,addJoin:l,removeJoin:d,updateJoin:o,moveJoinUp:w=>{const D=a.joins.findIndex(I=>I.id===w);if(D>0){const I=[...a.joins],k={...I[D]},j={...I[D-1]};I[D]=j,I[D-1]=k,I.forEach((N,L)=>{N.sequence=L+1});const R={...a,joins:I};r(R)}},moveJoinDown:w=>{const D=a.joins.findIndex(I=>I.id===w);if(D<a.joins.length-1){const I=[...a.joins],k={...I[D]},j={...I[D+1]};I[D]=j,I[D+1]=k,I.forEach((N,L)=>{N.sequence=L+1});const R={...a,joins:I};r(R)}},toggleJoinExpansion:w=>{const D=new Set(c);D.has(w)?D.delete(w):D.add(w),i(D)},getAvailableSourceEntities:w=>{if(a.joins.length===0)return n;const D=a.joins.findIndex(k=>k.id===w);if(D===0)return n.filter(k=>k.name===a.baseEntity.name);const I=new Set;return a.baseEntity.name&&I.add(a.baseEntity.name),a.joins.slice(0,D).forEach(k=>{I.add(k.source.name),I.add(k.target.name)}),n.filter(k=>I.has(k.name))},getAvailableTargetEntities:w=>n.filter(D=>D.name!==w),addJoinKeyGroup:w=>{const D=a.joins.find(k=>k.id===w);if(!D)return;const I=[...D.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];o(w,{joinKeyGroups:I})},updateGroupOperator:(w,D,I)=>{const k=a.joins.find(R=>R.id===w);if(!k)return;const j=[...k.joinKeyGroups];j[D]={...j[D],operator:I},o(w,{joinKeyGroups:j})},removeJoinKeyGroup:(w,D)=>{const I=a.joins.find(j=>j.id===w);if(!I)return;const k=[...I.joinKeyGroups];k.splice(D,1),o(w,{joinKeyGroups:k})},addJoinKey:(w,D)=>{const I=a.joins.find(L=>L.id===w);if(!I)return;const k=n.find(L=>L.name===I.source.name),j=n.find(L=>L.name===I.target.name),R=[...I.joinKeyGroups],N={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(k==null?void 0:k.name)||"",entityName:(k==null?void 0:k.name)||"",entityType:(k==null?void 0:k.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(j==null?void 0:j.name)||"",entityName:(j==null?void 0:j.name)||"",entityType:(j==null?void 0:j.type)||"table"},operator:"="};R[D]={...R[D],keys:[...R[D].keys,N]},o(w,{joinKeyGroups:R})},updateJoinKey:(w,D,I,k,j)=>{const R=a.joins.find(A=>A.id===w);if(!R)return;const N=n.find(A=>A.name===R.source.name),L=n.find(A=>A.name===R.target.name),F=[...R.joinKeyGroups],f=F[D].keys[I];k==="sourceColumnName"&&N?F[D].keys[I]={...f,source:{...f.source,name:j}}:k==="targetColumnName"&&L?F[D].keys[I]={...f,target:{...f.target,name:j}}:k==="operator"&&(F[D].keys[I]={...f,operator:j}),o(w,{joinKeyGroups:F})},removeJoinKey:(w,D,I)=>{const k=a.joins.find(R=>R.id===w);if(!k)return;const j=[...k.joinKeyGroups];j[D].keys.splice(I,1),o(w,{joinKeyGroups:j})},generateSQLPreview:()=>{const w=[...a.joins].sort((k,j)=>k.sequence-j.sequence),D=a.baseEntity;if(!D.name)return"SELECT * FROM table -- Please select a base entity";let I=`SELECT *
|
|
157
|
+
FROM ${D.name}`;return w.forEach(k=>{const j=n.find(L=>L.name===k.target.name);if(!j)return;const R=k.joinKeyGroups.filter(L=>L.keys&&L.keys.length>0).map(L=>{const F=L.keys.filter(f=>{var A,T,V,O;return((A=f.source)==null?void 0:A.name)&&((T=f.target)==null?void 0:T.name)&&((V=f.source)==null?void 0:V.entityName)&&((O=f.target)==null?void 0:O.entityName)}).map(f=>`${f.source.entityName}.${f.source.name} ${f.operator} ${f.target.entityName}.${f.target.name}`);return F.length>1?`(${F.join(` ${L.operator} `)})`:F[0]}).filter(Boolean),N=R.length>1?R.join(" OR "):R[0]||"condition_here";I+=`
|
|
158
|
+
${k.joinType} JOIN ${j.name}
|
|
159
|
+
ON ${N}`}),I},isValidConfiguration:()=>!(!a.baseEntity.name||a.joins.some(k=>!k.source.name||!k.target.name)||a.joins.some(k=>k.joinKeyGroups.some(j=>j.keys.length===0))||a.joins.some(k=>k.joinKeyGroups.some(j=>j.keys.some(R=>!R.source.name||!R.target.name||!R.operator))))}}function Fn({joinPlan:s,availableDataSources:n,onSave:a,onRemove:r,onCancel:c}){const{setCardConfig:i}=t.useEditorActions();t.useEditorStore(N=>N.card.config);const{columnGroups:l}=t.useColumns(),d=l.filter(N=>N.entityName!==t.CALCULATED_FIELDS_GROUP_NAME),{joinPlan:o,expandedJoins:u,setJoinPlan:p,addJoin:x,removeJoin:h,updateJoin:m,moveJoinUp:g,moveJoinDown:v,toggleJoinExpansion:b,getAvailableSourceEntities:C,getAvailableTargetEntities:E,addJoinKeyGroup:B,updateGroupOperator:S,removeJoinKeyGroup:M,addJoinKey:w,updateJoinKey:D,removeJoinKey:I,generateSQLPreview:k,isValidConfiguration:j}=Ln({initialJoinPlan:s,availableDataSources:n}),R=N=>{const L=d.find(F=>F.entityName===N);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:N=>{const L=n.find(F=>F.name===N);p({...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:N,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(N=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:N.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:N.type}),N.name,e.jsx(t.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},N.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:k()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(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(N=>{const L=n.find(A=>A.name===N.source.name),F=n.find(A=>A.name===N.target.name),f=u.has(N.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:N.sequence}),e.jsxs(t.CardTitle,{className:"text-sm",children:["Join ",N.sequence,L&&F&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",L.name," → ",F.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>g(N.id),disabled:N.sequence===1,children:e.jsx(t.ArrowUp,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>v(N.id),disabled:N.sequence===o.joins.length,children:e.jsx(t.ArrowDown,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>b(N.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:()=>h(N.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:N.source.name,onValueChange:A=>{const T=n.find(V=>V.name===A);m(N.id,{source:{connectionId:(T==null?void 0:T.connectionId)||"",connectionType:(T==null?void 0:T.connectionType)||"none",type:(T==null?void 0:T.type)||"table",name:A,database:T==null?void 0:T.database,schema:T==null?void 0:T.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select source..."})}),e.jsx(t.SelectContent,{children:C(N.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:N.joinType,onValueChange:A=>m(N.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:N.target.name,onValueChange:A=>{const T=n.find(V=>V.name===A);m(N.id,{target:{connectionId:(T==null?void 0:T.connectionId)||"",connectionType:(T==null?void 0:T.connectionType)||"none",type:(T==null?void 0:T.type)||"table",name:A,database:T==null?void 0:T.database,schema:T==null?void 0:T.schema}})},disabled:!N.source.name,children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select target..."})}),e.jsx(t.SelectContent,{children:N.source.name?E(N.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===N.source.name&&e.jsx(t.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},A.name)):[]})]})]})]}),N.source.name&&N.target.name&&L&&F&&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:()=>B(N.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),N.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:N.joinKeyGroups.map((A,T)=>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 ",T+1]}),T>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:V=>S(N.id,T,V),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(N.id,T),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((V,O)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[O>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:A.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:V.source.name,onValueChange:P=>D(N.id,T,O,"sourceColumnName",P),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Source column"})}),e.jsx(t.SelectContent,{children:R(N.source.name).map(P=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:P.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:P.name}),e.jsx(t.Badge,{variant:"outline",className:"ml-2 text-xs",children:P.dataType})]})},P.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(t.Select,{value:V.operator,onValueChange:P=>D(N.id,T,O,"operator",P),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:V.target.name,onValueChange:P=>D(N.id,T,O,"targetColumnName",P),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Target column"})}),e.jsx(t.SelectContent,{children:R(N.target.name).map(P=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:P.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:P.name}),e.jsx(t.Badge,{variant:"outline",className:"ml-2 text-xs",children:P.dataType})]})},P.name))})]})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>I(N.id,T,O),children:e.jsx(t.X,{className:"size-3.5"})})]},V.id||O))}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>w(N.id,T),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},A.id))})]})]})]},N.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>{r(),c()},children:"Remove All"}),e.jsx(t.Button,{variant:"outline",onClick:c,children:"Cancel"}),e.jsx(t.Button,{onClick:()=>a(o),disabled:!j(),children:"Save"})]})]})}function ka({children:s,open:n,onOpenChange:a,joinPlan:r,availableDataSources:c,onRemove:i,onSave:l,onCancel:d}){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:c,onSave:l,onCancel:d,onRemove:i})]}),s]})}function Rn({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 c=[...s].sort((l,d)=>l.sequence-d.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"})]}),c.map(l=>{const d=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:d==null?void 0:d.type}),e.jsx("span",{className:"text-xs font-medium",children:d==null?void 0:d.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((c,i)=>c.sequence-i.sequence).map((c,i)=>{const l=a.find(u=>u.name===c.source.name),d=a.find(u=>u.name===c.target.name),o=c.joinKeyGroups.reduce((u,p)=>u+p.keys.length,0);return e.jsxs("div",{className:"rounded-md bg-muted p-2 text-left",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:i+1}),e.jsx(t.Badge,{variant:"outline",className:"shrink-0 text-xs",children:c.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," → ",d==null?void 0:d.name]})]},c.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 aa({open:s,onOpenChange:n,variant:a="button"}={}){var E,B;const r=t.useEditorStore(S=>S.card),{autoJoinMetadata:c}=t.useDashboardCardQuery(r),i=t.useEditorStore(S=>S.actions.updateCardConfig),l=((E=r==null?void 0:r.config)==null?void 0:E.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[d,o]=y.useState(!1),u=s!==void 0,p=u?s:d,x=u?n:o,h=((B=r==null?void 0:r.dataSource)==null?void 0:B.selectedEntities)||[],m=S=>{i(r.id,{...r==null?void 0:r.config,joinPlan:S}),x(!1)},g=()=>{i(r.id,{...r==null?void 0:r.config,joinPlan:void 0})},v=()=>{x(!1)},b=()=>{const S=[...l.joins].sort((D,I)=>D.sequence-I.sequence),M=l.baseEntity;if(!M.name)return"SELECT * FROM table -- Please select a base entity";let w=`SELECT *
|
|
160
|
+
FROM ${M.name}`;return S.forEach(D=>{const I=h.find(R=>R.name===D.target.name);if(!I)return;const k=D.joinKeyGroups.filter(R=>R.keys&&R.keys.length>0).map(R=>{const N=R.keys.filter(L=>{var F,f,A,T;return((F=L.source)==null?void 0:F.name)&&((f=L.target)==null?void 0:f.name)&&((A=L.source)==null?void 0:A.entityName)&&((T=L.target)==null?void 0:T.entityName)}).map(L=>`${L.source.entityName}.${L.source.name} ${L.operator} ${L.target.entityName}.${L.target.name}`);return N.length>1?`(${N.join(` ${R.operator} `)})`:N[0]}).filter(Boolean),j=k.length>1?k.join(" OR "):k[0]||"condition_here";w+=`
|
|
161
|
+
${D.joinType} JOIN ${I.name}
|
|
162
|
+
ON ${j}`}),w};if(h.length<2)return null;const C=l.joins.length>0&&e.jsx(t.TooltipContent,{side:"bottom",className:"ml-4 max-w-md overflow-hidden p-0",children:e.jsx(Rn,{joins:l.joins,baseEntityId:l.baseEntity.name,availableDataSources:h,generateSQLPreview:b})});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:S=>{S.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}),(c==null?void 0:c.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"]})]})}),C]})}),e.jsx(ka,{open:p,onOpenChange:x,joinPlan:l,availableDataSources:h,onSave:m,onCancel:v,onRemove:g,children:e.jsx("div",{})})]})}function On({open:s,onOpenChange:n}){const[a,r]=y.useState([]),{updateDataSource:c}=t.useEditorActions(),{selectedEntities:i}=t.useAssistantContextEntities("dashboard");y.useEffect(()=>{s&&r([])},[s]);const l=m=>{r(g=>g.some(b=>t.areContextEntitiesEqual(b,m))?g.filter(b=>!t.areContextEntitiesEqual(b,m)):[...g,m])},d=()=>{r([...i])},o=()=>{r([])},u=()=>{if(a.length===0)return;const m=a[0],g=m.connectionId||"",v=m.connectionType||"",C=a.some(B=>B.type==="dataset")?"semanticDomain":"database";c({connectionId:g,connectionType:v,mode:C,selectedEntities:a}),n(!1)},p=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(".")},h=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:d,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",h(m)&&"border-primary bg-primary/5"),children:[e.jsx(t.Checkbox,{checked:h(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:p(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 na({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,c)=>{const i=t.getEntityDetails(r),l=i.find(o=>o.label==="Description"&&o.value),d=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})]}),d.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:d.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}-${c}`)})})]})})}function Aa(s,n){const[a,r]=y.useState(()=>{const c=localStorage.getItem(s);return c?JSON.parse(c):n});return y.useEffect(()=>{localStorage.setItem(s,JSON.stringify(a))},[a,s]),[a,r]}function Ma({isVisible:s}){var v,b;const n=t.useEditorStore(C=>C.isDevMode);t.useSyncLegacyEditorState();const[a,r]=y.useState(!1),[c,i]=y.useState(!1),[l,d]=Aa("semaphor:data-source-collapsed",!1),o=t.useEditorStore(C=>C.card.dataSource),u=t.useEditorStore(C=>{var E,B;return(B=(E=C.card)==null?void 0:E.config)==null?void 0:B.joinPlan}),{updateDataSource:p}=t.useEditorActions(),x=((v=o==null?void 0:o.selectedEntities)==null?void 0:v.length)||0,h=((b=u==null?void 0:u.joins)==null?void 0:b.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&&h===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:()=>d(!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:C=>C.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(na,{entities:g.selectedEntities,title:`${x} selected ${x===1?"entity":"entities"}`})]})}),h>0&&!n&&e.jsx(aa,{variant:"badge"})]})]}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:C=>{C.stopPropagation(),d(!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(na,{entities:g.selectedEntities,title:`${x} selected ${x===1?"entity":"entities"}`})]})})}),!n&&x>1&&e.jsx("div",{className:"mt-3 px-1",children:e.jsx(aa,{})})]})]})}),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(On,{open:c,onOpenChange:i})]})}function Pn(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)}const Bn=300;function Vn(){const s=t.useEditorStore(C=>C.card.sql),n=t.useEditorStore(C=>C.sqlGen),a=t.useEditorStore(C=>C.card),r=De.useEffectiveEditorCardType(),{setCardSql:c,setSqlGen:i,setRunSql:l}=t.useEditorActions(),d=y.useMemo(()=>r!==a.type?{...a,type:r}:a,[a,r]),{queryKey:o}=t.useDashboardCardQuery(d),u=t.useQueryClient(),p=y.useRef(o);p.current=o;const x=y.useRef(n);x.current=n;const h=y.useCallback(C=>{c(C)},[c]),{value:m,onChange:g,flush:v}=Da({storeValue:s,defaultValue:"",onStoreUpdate:h,delay:Bn});y.useEffect(()=>it.registerPendingEditorDraftFlusher(v),[v]);function b(C){g(C),t.isObjectEmpty(x.current)||i({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!m&&e.jsx("div",{className:"pointer-events-none absolute left-[56px] top-4 z-10 font-mono text-[12px] leading-[1.55] text-muted-foreground",children:"Write your SQL here"}),e.jsx(t.CodeEditor,{value:m??"",onValueChange:b,language:"sql-jinja",embedded:!0,onKeyDown:C=>{C.key==="Enter"&&C.shiftKey&&(C.preventDefault(),it.flushPendingEditorDrafts(),setTimeout(()=>{u.removeQueries({queryKey:p.current,exact:!0}),l(!0)},0))}})]})}const zn=300;function _n(){const s=t.useEditorStore(h=>h.card.python),n=t.useEditorStore(h=>h.card),a=De.useEffectiveEditorCardType(),{setCardPython:r,setRunSql:c}=t.useEditorActions(),i=y.useMemo(()=>a!==n.type?{...n,type:a}:n,[n,a]),{queryKey:l}=t.useDashboardCardQuery(i),d=t.useQueryClient(),o=y.useRef(l);o.current=l;const{value:u,onChange:p,flush:x}=Da({storeValue:s,defaultValue:t.PYTHON_DEFAULT_CODE,onStoreUpdate:r,delay:zn});return y.useEffect(()=>it.registerPendingEditorDraftFlusher(x),[x]),e.jsx(t.CodeEditor,{value:u??"",onValueChange:p,language:"python",embedded:!0,onKeyDown:h=>{h.key==="Enter"&&h.shiftKey&&(h.preventDefault(),it.flushPendingEditorDrafts(),setTimeout(()=>{d.removeQueries({queryKey:o.current,exact:!0}),c(!0)},0))}})}const qn={async writeTextToClipboard(s){return typeof navigator>"u"||!navigator.clipboard?!1:(await navigator.clipboard.writeText(s),!0)}},Rt=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 ra(s){try{return JSON.stringify(s,null,2)}catch(n){return console.error("Unable to stringify debug payload",n),null}}function gt(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<=Rt?{value:s}:{value:{...s,records:n.slice(0,Rt),previewMeta:{truncatedRecords:!0,displayedRecords:Rt,totalRecords:n.length}},truncationMessage:`Preview showing first ${Rt} records of ${n.length}. Copy actions include full payload.`}}function La({sql:s,showCardDetails:n=!1,debugPayloads:a,className:r}){const[c,i]=y.useState(!1),[l,d]=y.useState(null),o=t.useEditorStore(j=>j.card),u=t.useEditorStore(j=>j.frame),p=t.useEditorStore(j=>j.isDevMode),x=t.useDashboardStore(j=>j.selectedSheetId),h=t.useDashboardStore(j=>{var R;return(R=j.dashboard)==null?void 0:R.id}),{switchEditorMode:m,setRunSql:g}=t.useEditorActions(),v=y.useMemo(()=>({cardId:o.id||null,frameId:u.id||null,sheetId:x||null,dashboardId:h||null}),[o.id,u.id,x,h]),b=y.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]),C=n&&c&&!!a,E=y.useMemo(()=>[{label:"Card ID",value:o.id||""},{label:"Frame ID",value:u.id||""},{label:"Sheet ID",value:x||""},{label:"Dashboard ID",value:h||""}],[o.id,u.id,x,h]),B=()=>{m("dev",{sqlToLoad:s}),setTimeout(()=>{g(!0)},100)},S=j=>b[j]!==void 0,M=y.useMemo(()=>{if(!l)return null;const j=b[l];if(j===void 0)return null;const R=l==="queryResponse"?Kn(j):{value:j},N=ra(R.value);return N?{target:l,title:gt(l),json:N,truncationMessage:R.truncationMessage}:null},[l,b]),w=M?M.title:"Preview Payload",D=async j=>{const R=b[j];if(R===void 0)return t.ue.error(`No ${gt(j).toLowerCase()} available`),!1;const N=ra(R);if(!N)return t.ue.error(`Unable to serialize ${gt(j).toLowerCase()}`),!1;try{return await qn.writeTextToClipboard(N)?(t.ue.success(`${gt(j)} 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 ${gt(j).toLowerCase()}`),!1}},I=async()=>M?D(M.target):!1,k=j=>{if(b[j]===void 0){t.ue.error(`No ${gt(j).toLowerCase()} available`);return}d(j)};return e.jsxs("div",{className:t.cn("flex min-h-0 flex-1 flex-col",r),children:[!p&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsxs(t.Button,{onClick:B,variant:"secondary",size:"sm",children:[e.jsx(Ea,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),n&&e.jsxs(t.Button,{onClick:()=>i(!c),variant:"outline",size:"sm",children:[e.jsx(t.Info,{className:"mr-2 h-4 w-4"}),"Card Details"]})]}),c&&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(De.CircleX,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"grid grid-cols-1 gap-2 md:grid-cols-2",children:E.map(j=>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:j.label}),e.jsx(t.CopyButton,{text:j.value,className:"h-6 w-6 shrink-0"})]}),e.jsx("code",{title:j.value||"N/A",className:"mt-1 block whitespace-normal break-all font-mono text-xs",children:j.value||"N/A"})]},j.label))}),C&&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"}),w,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(j=>e.jsx(t.DropdownMenuItem,{disabled:!S(j.target),onSelect:()=>k(j.target),className:t.cn(l===j.target&&"bg-accent"),children:j.label},`preview-${j.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:I}),e.jsxs(t.Button,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>d(null),children:[e.jsx(De.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})})]})})]})}const Gn=/\{\{-?\s*filters\s*\|\s*where\s*-?\}\}/i,Un=/\{\{-?\s*filters\s*\|\s*and\s*-?\}\}/i,Hn=/\bwhere\b/i;function Qn(s){return s!=null&&s.trim()?Gn.test(s)||Un.test(s):!1}function Jn(s){return!(s!=null&&s.trim())||Qn(s)?null:Hn.test(s)?{helper:"{{ filters | and }}",description:"Use this inside your existing WHERE clause to append dashboard filters."}:{helper:"{{ filters | where }}",description:"Use this when the query does not already have a WHERE clause."}}function Yn(s){const{request:n,mode:a="draft",currentSql:r,selectedTableName:c,selectedSchemaName:i,selectedDatabaseName:l}=s,d=[l?`Database: ${l}`:"",i?`Schema: ${i}`:"",c?`Table: ${c}`:""].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.",d.length>0?`Context:
|
|
163
|
+
${d.join(`
|
|
164
|
+
`)}`:"",r?a==="refine"?`Current SQL (must refine):
|
|
165
|
+
${r}`:`Current SQL (revise if useful):
|
|
166
|
+
${r}`:"",`User request:
|
|
167
|
+
${n}`].filter(Boolean).join(`
|
|
168
|
+
|
|
169
|
+
`)}function Wn(s){const{request:n,failedSql:a,errorMessage:r,errorCode:c,selectedDatabaseName:i,selectedSchemaName:l,selectedTableName:d,contextEntityLabels:o}=s,u=[i?`Database: ${i}`:"",l?`Schema: ${l}`:"",d?`Table: ${d}`:"",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:
|
|
170
|
+
${u.join(`
|
|
171
|
+
`)}`:"",`Original user request:
|
|
172
|
+
${n}`,`Previous SQL draft:
|
|
173
|
+
${a}`,`Validation failure${c?` (${c})`:""}:
|
|
174
|
+
${r}`].filter(Boolean).join(`
|
|
175
|
+
|
|
176
|
+
`)}function Xn(s,n){typeof window>"u"||window.dispatchEvent(new CustomEvent("semaphor:inline-query-writer",{detail:{event:s,...n,timestamp:Date.now()}}))}const Zt={runId:0,phase:"idle",attempt:0,activeStep:"",timelineSteps:[],lastValidation:null,finalOutcome:"idle",hasTools:!1};function Zn(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 la(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 oa(s){return s==="getTableColumns"?"Discovering columns":s==="getDomainRelationships"?"Resolving relationships":s==="getChartSQLSyntax"?"Reviewing SQL syntax":s==="getUserSql"?"Inspecting current query":"Analyzing context"}function er(s,n){return s===t.SELF_HEAL_TIMELINE_STEP&&n>0?`${t.SELF_HEAL_TIMELINE_STEP} ${n}/${t.MAX_SELF_HEAL_ATTEMPTS}`:s}function Ot(s){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`${s}-${crypto.randomUUID()}`:`${s}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function ia(s){var n;for(let a=s.length-1;a>=0;a-=1){const r=s[a];if(r.role!=="user")continue;const c=(n=r.metadata)==null?void 0:n.inlineRunToken;if(typeof c=="string"&&c.length>0)return c}}function tr(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 ca(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 c=a.parts[r];if((c==null?void 0:c.type)!=="text"||typeof(c==null?void 0:c.text)!="string")continue;const i=tr(c.text);if(i)return i}}return""}function sr({currentSql:s,currentPython:n,selectedDatabaseName:a,selectedSchemaName:r,selectedTableName:c,onApplySql:i,onOpenFullAssistant:l}){var Mt,Nt;const{authToken:d,tokenProps:o}=t.useSemaphorContext(),u=(Mt=t.useDashboardQuery().data)==null?void 0:Mt.assistantProfileId,p=t.useEditorStore(q=>q.isDevMode),x=t.useEditorStore(q=>q.selectedConnectionId),h=t.useEditorStore(q=>{var Y;return(Y=q.card.dataSource)==null?void 0:Y.selectedEntities}),m=t.useAIInteractionStore(q=>q.currentAIContext.selectedEntities),g=m.length,{setCurrentAIContext:v}=t.useAIActions(),[b,C]=y.useState(""),[E,B]=y.useState(""),[S,M]=y.useState(""),[w,D]=y.useState("draft"),[I,k]=y.useState("draft"),[j,R]=y.useState(""),[N,L]=y.useState(!1),[F,f]=y.useState({status:"idle"}),[A,T]=y.useState(Zt),[V,O]=y.useState(!1),[P,_]=y.useState(()=>Ot("inline-query-session")),z=y.useRef(null),U=y.useRef(null),W=y.useRef(null),K=y.useRef(0),Z=y.useRef(0),ae=y.useRef(Ot("inline-run-token")),pe=y.useRef(P),fe=y.useRef(new Set),se=y.useRef(new Map),ne=y.useRef(0),me=y.useRef(""),be=y.useRef(!1),ge=y.useRef(!1),te=y.useRef(Zt),X=y.useRef(!1),Ne=y.useRef(null),Se=y.useRef(()=>{}),Oe=(Nt=o.apiServiceUrl)==null?void 0:Nt.replace(/\/$/,""),Ve=Oe?`${Oe}/v1/sql/validate`:"/v1/sql/validate",Ae=y.useCallback(q=>{T(Y=>{const Q=q(Y);return te.current=Q,Q})},[]),Te=y.useCallback((q,Y)=>{Ae(Q=>Q.runId===q?Y(Q):Q)},[Ae]),Ee=y.useCallback(q=>Z.current===q&&!fe.current.has(q),[]),$=y.useCallback((q,Y,Q)=>{Te(q,ce=>{const xe=ce.timelineSteps.includes(Y)?ce.timelineSteps:[...ce.timelineSteps,Y];return{...ce,phase:(Q==null?void 0:Q.phase)||ce.phase,attempt:typeof(Q==null?void 0:Q.attempt)=="number"?Q.attempt:ce.attempt,activeStep:Y,timelineSteps:xe,finalOutcome:(Q==null?void 0:Q.finalOutcome)||ce.finalOutcome,hasTools:Q!=null&&Q.hasTools?!0:ce.hasTools}})},[Te]),oe=y.useCallback(()=>{const q=Z.current+1,Y=Ot("inline-run-token"),Q=Ot("inline-query-session");return Z.current=q,ae.current=Y,pe.current=Q,_(Q),fe.current=new Set,se.current=new Map,ne.current=0,me.current="",X.current=!1,Ae(()=>({runId:q,phase:"drafting",attempt:0,activeStep:"Drafting SQL",timelineSteps:["Drafting SQL"],lastValidation:null,finalOutcome:"drafting",hasTools:!1})),{runId:q,runToken:Y,chatSessionId:Q}},[Ae]),je=y.useCallback(()=>{if(be.current||ge.current||g>0)return;const q=h||[];if(q.length===0)return;const Y=t.useAIInteractionStore.getState().currentAIContext;v({...Y,selectedEntities:q}),ge.current=!0},[g,h,v]),ee=y.useCallback(()=>{be.current=!0},[]),H=y.useCallback((q,Y,Q)=>{Xn(q,{runId:Y,attemptCount:typeof(Q==null?void 0:Q.attemptCount)=="number"?Q.attemptCount:ne.current,errorCode:Q==null?void 0:Q.errorCode,hasTools:typeof(Q==null?void 0:Q.hasTools)=="boolean"?Q.hasTools:A.hasTools,entityCount:g,finalOutcome:(Q==null?void 0:Q.finalOutcome)||A.finalOutcome})},[g,A.finalOutcome,A.hasTools]),le=y.useCallback((q,Y)=>{const Q=W.current;if(!Q)return;const ce={inlineRunToken:Y};Q({role:"user",parts:[{type:"text",text:q}],metadata:ce},{metadata:ce})},[]);y.useEffect(()=>{const q=Ne.current;!q||q.sessionId!==P||(Ne.current=null,le(q.message,q.runToken))},[P,le]);const de=P,Ce=y.useCallback(async({toolCall:q})=>{var Re,Je,rt,st,ze,ft;if(de!==pe.current)return;const Y=String(q.toolName||"").trim();if(!Y)return;const Q=Z.current;if(!Ee(Q)){(Re=U.current)==null||Re.call(U,{tool:Y,toolCallId:q.toolCallId,output:{status:"error",message:"Inline run is no longer active; ignoring tool output."}});return}if(Y==="getUserSql"){$(Q,oa(Y),{hasTools:!0}),H("inline_tool_step",Q,{hasTools:!0}),(Je=U.current)==null||Je.call(U,{tool:Y,toolCallId:q.toolCallId,output:{status:"success",sql:s||"",python:n||""}});return}const ce=t.INLINE_BLOCKED_MUTATING_TOOLS.has(Y),xe=t.INLINE_ALLOWED_READ_ONLY_TOOLS.has(Y);if(ce||!xe){(rt=U.current)==null||rt.call(U,{tool:Y,toolCallId:q.toolCallId,output:{status:"error",message:"This action is unavailable in inline draft mode. Open Full Assistant for this action."}});return}const he=oa(Y);$(Q,he,{phase:A.phase==="self-healing"?"self-healing":"drafting",hasTools:!0}),H("inline_tool_step",Q,{hasTools:!0});const Me=((st=q.input)==null?void 0:st.sql)??((ze=q.args)==null?void 0:ze.sql);typeof Me=="string"&&Me.trim().length>0&&(X.current=!1,M(Me.trim())),(ft=U.current)==null||ft.call(U,{tool:Y,toolCallId:q.toolCallId,output:{status:"success",message:"Read-only tool result received."}})},[n,s,H,A.phase,Ee,de,$]),ve=y.useCallback(({message:q,messages:Y})=>{if(de!==pe.current)return;const Q=ia(Y);if(!Q||Q!==ae.current)return;const ce=Z.current;if(!Ee(ce))return;const xe=ca([q])||ca(Y);if(xe){X.current=!1,M(xe.trim());return}X.current&&te.current.phase==="self-healing"&&Se.current(ce)},[Ee,de]),Fe=y.useCallback(q=>{if(de!==pe.current)return;const Y=Z.current;Ee(Y)&&X.current&&te.current.phase==="self-healing"&&Se.current(Y)},[Ee,de]),{setMessages:Be,sendMessage:Xe,addToolResult:Ye,status:We,stop:re,error:Ie,clearError:Pe}=t.useChat({id:P,transport:new t.DefaultChatTransport({api:`${o.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${d==null?void 0:d.accessToken}`}),body:()=>{const q=t.useAIInteractionStore.getState();return{assistantId:"editor-assistant",assistantProfileId:u,isDevMode:p,aiContext:q.currentAIContext,reasoningEffort:q.reasoningEffort,showReasoning:!1}},credentials:"omit",prepareSendMessagesRequest:({messages:q,body:Y,requestMetadata:Q})=>{const ce=Q==null?void 0:Q.inlineRunToken,xe=ia(q);return{body:{...Y,inlineRunToken:ce||xe,messages:t.cleanupIncompleteMessages(q)}}}}),onToolCall:Ce,onFinish:ve,onError:Fe,sendAutomaticallyWhen:t.lastAssistantMessageIsCompleteWithToolCalls});U.current=Ye,W.current=Xe;const ye=!["ready","error"].includes(We),Ge=(Ie==null?void 0:Ie.message)||"Unable to generate a SQL draft right now. Try again.",we=y.useCallback(q=>{const Y=Z.current,Q=te.current.phase;if(!(Q==="drafting"||Q==="self-healing"||Q==="validating")){q==="stopped"&&ye&&re();return}fe.current.add(Y),X.current=!1,K.current+=1,me.current="",f({status:"idle"}),M(""),Pe(),Be([]),Te(Y,xe=>({...xe,phase:"idle",activeStep:"",finalOutcome:"cancelled"})),H("inline_self_heal_stopped",Y,{finalOutcome:"cancelled"}),(ye||q==="stopped")&&re()},[Pe,H,ye,Be,re,Te]),bt=y.useCallback(async(q,Y)=>{var ce;if(!Ee(Y))return null;const Q=K.current+1;K.current=Q,$(Y,"Validating SQL",{phase:"validating"}),f({status:"validating"});try{const xe=await t.postRequestRegular(Ve,(d==null?void 0:d.accessToken)||"",{sql:q,connectionId:x||void 0});if(K.current!==Q||!Ee(Y))return null;if((xe==null?void 0:xe.valid)===!0)return f({status:"valid",message:"SQL validation passed."}),Te(Y,Re=>({...Re,phase:"ready",finalOutcome:"validated",lastValidation:{valid:!0}})),H("inline_draft_validated",Y,{finalOutcome:"validated"}),{status:"valid"};const he=Zn(xe==null?void 0:xe.errorCode)||"UNKNOWN",Me=typeof(xe==null?void 0:xe.error)=="string"&&xe.error||typeof((ce=xe==null?void 0:xe.details)==null?void 0:ce.error)=="string"&&xe.details.error||"SQL validation failed. Please revise the query draft.";return f({status:"invalid",message:Me,errorCode:he}),Te(Y,Re=>({...Re,lastValidation:{valid:!1,error:Me,errorCode:he}})),H("inline_validation_failed",Y,{errorCode:he,finalOutcome:"validation_failed"}),{status:"invalid",error:Me,errorCode:he}}catch(xe){if(K.current!==Q||!Ee(Y))return null;const he=t.getRequestErrorMessage(xe,"Validation service unavailable. You can still replace and run.");return f({status:"error",message:he,errorCode:"SQL_CONNECTION_ERROR"}),Te(Y,Me=>({...Me,phase:"error",finalOutcome:"error",lastValidation:{valid:!1,error:he,errorCode:"SQL_CONNECTION_ERROR"}})),{status:"error",error:he,errorCode:"SQL_CONNECTION_ERROR"}}},[d==null?void 0:d.accessToken,H,Ee,x,Ve,Te,$]),Ze=y.useCallback((q,Y,Q,ce)=>{let xe=Q,he="validation_failed",Me="Validating SQL";Y==="attempt_limit"?(xe=`Couldn't auto-fix after ${t.MAX_SELF_HEAL_ATTEMPTS} attempts. ${Q}`,he="self_heal_exhausted",Me=`Auto-fix stopped (${t.MAX_SELF_HEAL_ATTEMPTS} attempts)`):Y==="duplicate"&&(xe=`Auto-fix stopped (repeated validation failure). ${Q}`,he="self_heal_duplicate_stopped",Me="Auto-fix stopped (repeated failure)"),f({status:"invalid",message:xe,errorCode:ce}),$(q,Me,{phase:"error",finalOutcome:he}),Te(q,Re=>({...Re,phase:"error",finalOutcome:he,lastValidation:{valid:!1,error:xe,errorCode:ce}})),Y!=="terminal"&&H("inline_self_heal_stopped",q,{errorCode:ce,finalOutcome:he}),X.current=!1},[H,Te,$]),Tt=y.useCallback(q=>{const Y="Auto-fix stopped (no SQL returned). Open Full Assistant to continue.",Q="self_heal_no_draft";f({status:"invalid",message:Y,errorCode:"UNKNOWN"}),$(q,"Auto-fix stopped (no SQL returned)",{phase:"error",finalOutcome:Q}),Te(q,ce=>({...ce,phase:"error",finalOutcome:Q,lastValidation:{valid:!1,error:Y,errorCode:"UNKNOWN"}})),H("inline_self_heal_stopped",q,{errorCode:"UNKNOWN",finalOutcome:Q}),X.current=!1},[H,Te,$]);Se.current=Tt,y.useEffect(()=>{const q=S.trim(),Y=Z.current;if(!q){if(K.current+=1,me.current="",te.current.phase==="error")return;f({status:"idle"});return}if(!Ee(Y)||ye)return;const Q=`${Y}:${ne.current}:${la(q)}`;if(me.current===Q)return;me.current=Q;let ce=!1;return(async()=>{const he=await bt(q,Y);if(!he||ce||!Ee(Y)||he.status!=="invalid")return;if(!t.RECOVERABLE_SQL_ERROR_CODES.has(he.errorCode)){Ze(Y,"terminal",he.error,he.errorCode);return}const Me=`${la(q)}::${he.errorCode}`,Re=(se.current.get(Me)||0)+1;if(se.current.set(Me,Re),Re>=2){Ze(Y,"duplicate",he.error,he.errorCode);return}if(ne.current>=t.MAX_SELF_HEAL_ATTEMPTS){Ze(Y,"attempt_limit",he.error,he.errorCode);return}const Je=ne.current+1;ne.current=Je,$(Y,t.SELF_HEAL_TIMELINE_STEP,{phase:"self-healing",attempt:Je}),H("inline_self_heal_attempt",Y,{attemptCount:Je,errorCode:he.errorCode}),X.current=!0,Pe(),Be([]),M("");const rt=m.map(ze=>{const ft=ze!=null&&ze.database?`${ze.database}.`:"",Jt=ze!=null&&ze.schema?`${ze.schema}.`:"",Yt=(ze==null?void 0:ze.name)||"unknown";return`${ft}${Jt}${Yt}`}),st=Wn({request:E,failedSql:q,errorMessage:he.error,errorCode:he.errorCode,selectedDatabaseName:a||"",selectedSchemaName:r||"",selectedTableName:c||"",contextEntityLabels:rt});le(st,ae.current)})(),()=>{ce=!0}},[Pe,m,H,ye,Ee,E,S,a,r,c,le,Be,Ze,$,bt]);const Ue=(s==null?void 0:s.trim())||"",Et=y.useCallback((q="draft")=>{if(ye)return;const Y=b.trim();if(!Y)return;const Q=q==="refine"&&Ue?"refine":"draft",ce=Q==="refine"?Ue:"",xe=Ue,{runId:he,runToken:Me,chatSessionId:Re}=oe();H("inline_draft_started",he,{attemptCount:0,hasTools:!1,finalOutcome:"drafting"}),je(),Pe(),B(Y),M(""),D(Q),R(ce),L(!1),f({status:"idle"}),K.current+=1,Be([]),O(!0);const Je=Yn({request:Y,mode:Q,currentSql:xe,selectedTableName:c||"",selectedSchemaName:r||"",selectedDatabaseName:a||""});Ne.current={sessionId:Re,message:Je,runToken:Me}},[oe,Pe,Ue,H,ye,b,je,a,r,c,Be]),ct=y.useCallback(q=>{const Y=S.trim();Y&&(i(Y,q),q||O(!1))},[i,S]),et=S.trim().length>0,It=["valid","invalid","error"].includes(F.status),vt=et&&It,Kt=F.status==="invalid",Dt=F.status==="validating",dt=et&&E.length>0&&E===b.trim(),ut=Ue.length>0,mt=b.length>0,xt=dt&&w==="draft",$e=dt&&w==="refine"&&j===Ue,Qe=I==="refine"&&!ut?"draft":I,tt=(Qe==="refine"?$e:xt)?"Open composer preview":"Generate composer SQL",kt=b.trim().length>0||E.trim().length>0||et||F.status!=="idle"||A.timelineSteps.length>0,yt=y.useCallback((q="draft")=>{if(ye)return;if((q==="refine"?$e:xt)&&!V){je(),O(!0);return}Et(q)},[xt,$e,Et,ye,V,je]),ht=y.useCallback(()=>{je(),O(!0)},[je]),Ut=y.useCallback(q=>{we("cancelled"),C(q)},[we]),Ht=y.useCallback(()=>{ye||(we("cancelled"),X.current=!1,K.current+=1,me.current="",ne.current=0,C(""),B(""),M(""),D("draft"),k("draft"),R(""),L(!1),f({status:"idle"}),Pe(),Be([]),Ae(q=>({...Zt,runId:q.runId})))},[we,Pe,ye,Be,Ae]),Qt=y.useCallback(q=>{q||we("cancelled"),O(q)},[we]),Ke=A.timelineSteps.findIndex(q=>q===A.activeStep),At=A.phase==="self-healing"?"Fixing validation issue":A.phase==="validating"?"Validating SQL":A.activeStep||"Drafting SQL",pt=F.status==="valid"?{label:"Validation passed",className:"border-emerald-500/30 bg-emerald-500/10 text-emerald-700",detail:F.message}:F.status==="invalid"?{label:"Validation failed",className:"border-destructive/40 bg-destructive/10 text-destructive",detail:F.message}:F.status==="error"?{label:"Validation unavailable",className:"border-border/60 bg-muted/20 text-muted-foreground",detail:F.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:b,onChange:q=>Ut(q.target.value),onFocus:ht,onClick:ht,onKeyDown:q=>{q.key==="Enter"&&(q.preventDefault(),yt(Qe))},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",mt?"pr-[60px]":"pr-10"].join(" ")}),e.jsxs(t.Popover,{open:V,onOpenChange:Qt,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:[mt&&e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"size-6 p-0",onClick:q=>{q.preventDefault(),we("cancelled"),C("")},disabled:ye,"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:q=>{q.preventDefault(),yt(Qe)},disabled:ye,"aria-label":tt,title:tt,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:q=>{q.preventDefault()},onInteractOutside:q=>{var Q;const Y=q.target;Y&&((Q=z.current)!=null&&Q.contains(Y))&&q.preventDefault()},children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Composer"}),E&&e.jsx("p",{className:"line-clamp-2 text-xs text-muted-foreground",children:E})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"inline-flex h-7 items-center rounded-md border border-border/60 bg-background p-0.5 shadow-sm",children:[e.jsx(t.Button,{type:"button",size:"sm",variant:Qe==="draft"?"secondary":"ghost",className:["h-6 rounded-[6px] px-2 text-xs",Qe!=="draft"?"text-muted-foreground hover:text-foreground":""].join(" "),onClick:()=>{k("draft"),L(!1)},children:"Draft New"}),e.jsx(t.Button,{type:"button",size:"sm",variant:Qe==="refine"?"secondary":"ghost",className:["h-6 rounded-[6px] px-2 text-xs",Qe!=="refine"?"text-muted-foreground hover:text-foreground":""].join(" "),onClick:()=>k("refine"),disabled:!ut,children:"Refine Current"})]}),e.jsx("div",{className:"h-4 w-px bg-border/70"}),ye&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>{we("stopped")},children:"Stop"}),!ye&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:Ht,disabled:!kt,children:"Clear"})]})]}),A.timelineSteps.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[A.timelineSteps.map((q,Y)=>{const Q=q===A.activeStep&&["drafting","validating","self-healing"].includes(A.phase),ce=!Q&&Ke>=0&&Y<Ke;return e.jsx("span",{className:["rounded-full border px-2 py-0.5 text-[11px]",Q?"border-foreground/30 bg-foreground/10 text-foreground":ce?"border-border/60 bg-muted/20 text-muted-foreground":"border-border/50 bg-background text-muted-foreground/80"].join(" "),children:er(q,A.attempt)},`${q}-${Y}`)}),pt&&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]",pt.className].join(" "),children:pt.label})}),e.jsx(t.TooltipContent,{side:"top",align:"start",className:"max-w-[680px] whitespace-pre-wrap break-words text-xs",children:pt.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:ee})}),(ye||A.phase==="self-healing"||F.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"}),At]}),Ie&&e.jsx("div",{className:"rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-xs text-destructive",children:Ge}),w==="refine"&&j&&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(q=>!q),children:N?"Hide base SQL":"View base SQL"})]}),N&&e.jsx("div",{className:"max-h-[120px] overflow-auto rounded-md border border-border/60",children:e.jsx(t.CodeHighlighter,{code:j,language:"sql"})})]}),vt?e.jsxs("div",{className:"space-y-1",children:[w==="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:S,language:"sql"})})]}):et?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."}):!ye&&e.jsx("div",{className:"rounded-md border border-dashed border-border/70 px-3 py-2 text-xs text-muted-foreground",children:ut?"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:ye||!vt,onClick:()=>ct(!1),children:"Replace SQL"}),e.jsx(t.Button,{size:"sm",className:"h-8",disabled:ye||!vt||Dt||Kt,onClick:()=>ct(!0),children:"Replace & Run"})]})]})})]})]})}function ar(){var ge,te;const s=t.useQueryClient(),[n,a]=y.useState(!1),r=t.useEditorStore(X=>X.frame),c=t.useEditorStore(X=>X.card);t.useEditorStore(X=>X.isShowingVisual),t.useEditorStore(X=>X.selectedConnectionId),t.useEditorStore(X=>X.tempQueryData);const i=t.useEditorStore(X=>X.selectedDatabaseName);t.useEditorStore(X=>X.selectedDatamodelId);const l=t.useEditorStore(X=>X.selectedSchemaName);t.useEditorStore(X=>X.showAIDialog);const d=t.useEditorStore(X=>X.selectedTableName),o=t.useDashboardStore(X=>{var Ne,Se;return((Se=(Ne=X.dashboard)==null?void 0:Ne.filters)==null?void 0:Se.length)??0}),{cardFilterValues:u}=t.useCardFilterValues((c==null?void 0:c.id)??""),p=t.useEditorStore(X=>X.inlineFilterValuesMap[(c==null?void 0:c.id)??""]),x=y.useMemo(()=>t.findCustomVisualConfigCard(r,c),[r,c]),{manifest:h}=t.useCustomVisual(((ge=x==null?void 0:x.customCardPreferences)==null?void 0:ge.url)||""),m=y.useMemo(()=>{var X;return(X=h==null?void 0:h.visuals)==null?void 0:X.find(Ne=>{var Se;return Ne.name===((Se=x==null?void 0:x.customCardPreferences)==null?void 0:Se.componentName)})},[h,(te=x==null?void 0:x.customCardPreferences)==null?void 0:te.componentName]),g=t.resolveMultiInputType(x,m),v=y.useMemo(()=>t.getCustomVisualInputCards({frame:r,configCard:x,isMultiInputVisual:g==="multiple"}),[r,x,g]),b=y.useMemo(()=>{const X=v.findIndex(Ne=>(Ne==null?void 0:Ne.id)===(c==null?void 0:c.id));return X<0?-1:t.getSlotIndexForCard(c,X)},[v,c]),C=y.useMemo(()=>!x||g!=="multiple"||b<0?c.type:t.getEffectiveCardTypeForSlot(c,b,m==null?void 0:m.slots)??c.type,[x,g,b,c,m==null?void 0:m.slots]),E=y.useMemo(()=>C!==c.type?{...c,type:C}:c,[c,C]),B=y.useMemo(()=>o===0?null:Jn(c==null?void 0:c.sql),[c==null?void 0:c.sql,o]),S=y.useRef(!0),{setCardCustomCfg:M,setQueryResultColumns:w,setCardSql:D,setTempQueryData:I,setPythonStdOut:k,setCardPreferences:j,setCardType:R,setCardPython:N,setShowAIDialog:L,setCard:F,updateCardInFrame:f}=t.useEditorActions();t.useEditorStore(X=>X.onSave),t.useEditorStore(X=>X.onClose),t.useEditorStore(X=>X.actions.setSqlGen);const A=t.useEditorStore(X=>X.runSql),T=t.useEditorStore(X=>X.actions.setRunSql),V=t.useEditorStore(X=>X.actions.setIsSqlRunning),{data:O,isLoading:P,isFetching:_,isSuccess:z,isError:U,error:W,errorSql:K,queryKey:Z,refetch:ae,errorMessage:pe}=t.useDashboardCardQuery(E),fe=y.useRef(Z);fe.current=Z,y.useEffect(()=>{if(O&&(O.rowLimitExceeded&&t.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),k((O==null?void 0:O.output)||""),O.records.length>0)){const{dimensionKeys:X}=t.getKeys(O.records);w(X)}},[O,w,k]),y.useEffect(()=>{(P||_)&&V(!0),(U||z)&&V(!1),U&&(w([]),k(""))},[P,_,O,k,U,z,V,w,W]),y.useEffect(()=>{A&&(s.getQueryData(Z)||ae(),T(!1))},[A,ae,T,Z,s]);const se=y.useRef(ae);se.current=ae,y.useEffect(()=>{if(S.current){S.current=!1;return}se.current()},[p]);function ne(X,Ne){D(X),Ne&&T(!0)}function me(){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 be(){return e.jsxs("div",{role:"editor-controls",className:"item-center flex w-full flex-wrap items-center gap-2 py-3 pl-2 pr-6",children:[B&&e.jsxs("div",{className:"mr-6 flex w-full items-center gap-1.5 px-1 text-[11px] text-muted-foreground",children:[e.jsx(t.Filter,{className:"h-3 w-3 shrink-0"}),e.jsxs("span",{className:"min-w-0 truncate",children:["Not subscribed to dashboard filters. Add"," ",e.jsx("code",{className:"rounded-[4px] bg-muted px-1 py-0.5 font-mono text-[10px] text-foreground",children:B.helper})," ","to this query."," ",e.jsx("a",{href:"https://docs.semaphor.cloud/docs/concepts/filters",target:"_blank",rel:"noreferrer",className:"underline-offset-2 hover:text-foreground hover:underline",children:"Learn more ↗"})]})]}),e.jsxs("div",{className:"flex w-full items-center gap-3",children:[e.jsxs(t.Button,{title:"Shift + Enter",disabled:P||_,onClick:()=>{it.flushPendingEditorDrafts(),setTimeout(()=>{s.removeQueries({queryKey:fe.current,exact:!0}),T(!0)},0)},className:"h-8 shrink-0",size:"sm",children:[P||_?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"]}),(O==null?void 0:O.sql)&&!pe&&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(La,{sql:O.sql})})]}),e.jsx(De.EditorClearButton,{}),e.jsxs(t.Toggle,{pressed:n,onPressedChange:X=>a(X),className:"h-8",size:"sm",variant:"outline",children:[e.jsx(Pn,{className:"mr-2 size-4 text-foreground/70"}),"Python"]}),e.jsx(sr,{currentSql:c==null?void 0:c.sql,currentPython:c==null?void 0:c.python,selectedDatabaseName:i,selectedSchemaName:l,selectedTableName:d,onApplySql:ne,onOpenFullAssistant:()=>L(!0)}),e.jsx("div",{className:"ml-auto flex shrink-0 items-center gap-3",children:u&&u.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:u.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(u,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:me()}),be()]})}function nr(s,n){var i;let a=0,r=0;const c=Math.min(s.length,50);for(let l=0;l<c;l++){const d=(i=s[l])==null?void 0:i[n];if(!(d==null||d==="")){if(r++,typeof d=="number"||typeof d=="bigint")a++;else if(typeof d=="boolean")return"boolean"}}return r===0?"null":a/r>.7?"number":"text"}function rr(s){if(s===null)return"null";if(s===void 0)return"";if(typeof s=="number"||typeof s=="bigint"||typeof s=="boolean")return String(s);if(typeof s=="string")return s;try{return JSON.stringify(s)}catch{return String(s)}}function lr({data:s,card:n,paginationMetadata:a,onPaginationChange:r,onPageSizePreferenceChange:c,onSortChange:i,isLoading:l}){var I,k,j,R,N,L;const d=y.useMemo(()=>Object.keys(s[0]??{}),[s]),o=n.sql&&!((k=(I=n.preferences)==null?void 0:I.tablePrefs)!=null&&k.enableDevModePagination)?(R=(j=n.preferences)==null?void 0:j.tablePrefs)==null?void 0:R.pageSize:void 0,u=y.useMemo(()=>{var F;return t.sortByColumnsToSortState((F=n.config)==null?void 0:F.sortByColumns)},[(N=n.config)==null?void 0:N.sortByColumns]),{canSort:p,canUseLocalSorting:x,handlePaginationChange:h,handleSortChange:m,pagination:g,paginationMode:v,sorting:b}=t.useTableQueryState({card:n,dataLength:s.length,onPaginationChange:r,onSortChange:i,pageSize:o,paginationMetadata:a,sortState:u}),C=y.useMemo(()=>b.filter(F=>d.includes(F.id)),[b,d]),E=y.useMemo(()=>{const F={};for(const f of d)F[f]=nr(s,f);return F},[d,s]),B=y.useMemo(()=>d.map(F=>{const A=E[F]==="number";return{accessorKey:F,enableSorting:p,header:({column:T})=>{const V=T.getIsSorted();return e.jsxs("div",{className:t.cn("flex select-none items-center gap-1.5 transition-colors",T.getCanSort()&&"cursor-pointer hover:text-foreground",A&&"justify-end"),onClick:()=>T.getCanSort()&&T.toggleSorting(T.getIsSorted()==="asc"),children:[e.jsx("span",{children:F}),V==="asc"?e.jsx(t.ArrowUpIcon,{className:"h-3.5 w-3.5 shrink-0 text-foreground"}):V==="desc"?e.jsx(t.ArrowDownIcon,{className:"h-3.5 w-3.5 shrink-0 text-foreground"}):T.getCanSort()?e.jsx(t.ChevronsUpDown,{className:"h-3 w-3 shrink-0 opacity-0 transition-opacity group-hover/header:opacity-50"}):null]})},cell:({getValue:T})=>{const V=T(),O=V===null;return e.jsx("div",{className:t.cn("whitespace-pre-wrap break-all",A&&"text-right tabular-nums",O&&"text-muted-foreground/50 italic"),children:rr(V)})}}}),[p,E,d]),S=Math.max(B.length,1),M=t.useReactTable({data:s,columns:B,getCoreRowModel:t.getCoreRowModel(),getPaginationRowModel:v==="client"?t.getPaginationRowModel():void 0,onSortingChange:m,getSortedRowModel:x?t.getSortedRowModel():void 0,onPaginationChange:v==="disabled"?void 0:h,manualPagination:v==="server"||v==="disabled",manualSorting:!x,pageCount:v==="server"&&a?a.pageCount:void 0,state:{sorting:C,pagination:g}}),w=v==="server"&&a?a.totalCount:s.length,D=v!=="disabled"&&(v==="server"||w>10);return e.jsxs("div",{className:"relative flex h-full w-full min-h-0 flex-col",children:[l&&e.jsx("div",{className:"absolute inset-0 z-20 flex items-center justify-center bg-background/50",children:e.jsx(t.LoaderCircle,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),e.jsxs(t.CustomScrollArea,{className:"min-h-0 grow overflow-auto text-foreground",children:[e.jsxs("table",{className:"w-full",children:[e.jsx(t.TableHeader,{className:"sticky top-0 z-10",children:M.getHeaderGroups().map(F=>e.jsx(t.TableRow,{className:"border-b-0 hover:bg-transparent",children:F.headers.map(f=>{const T=E[f.id]==="number";return e.jsx(t.TableHead,{className:t.cn("group/header h-9 border-b bg-muted px-3 font-mono text-xs font-medium text-foreground",T&&"text-right"),children:f.isPlaceholder?null:t.flexRender(f.column.columnDef.header,f.getContext())},f.id)})},F.id))}),e.jsx(t.TableBody,{className:"font-mono",children:(L=M.getRowModel().rows)!=null&&L.length?M.getRowModel().rows.map((F,f)=>e.jsx(t.TableRow,{className:t.cn("h-[34px] border-b border-border/40 transition-colors",f%2===1&&"bg-muted/20"),"data-state":F.getIsSelected()&&"selected",children:F.getVisibleCells().map(A=>{const V=E[A.column.id]==="number";return e.jsx(t.TableCell,{className:t.cn("px-3 py-1.5 text-xs",V&&"text-right"),children:t.flexRender(A.column.columnDef.cell,A.getContext())},A.id)})},F.id)):e.jsx(t.TableRow,{children:e.jsx(t.TableCell,{colSpan:S,className:"h-24 text-center font-sans text-sm text-muted-foreground",children:"No results."})})})]}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]}),e.jsx("div",{className:"shrink-0 border-t border-border/60 bg-muted/30 px-3 py-1.5 font-mono text-xs [&_*]:!text-xs",children:D?e.jsx(t.DataTablePagination,{totalColumns:d.length,pageCount:v==="server"&&a?a.pageCount:M.getPageCount(),pageIndex:M.getState().pagination.pageIndex,pageSize:M.getState().pagination.pageSize,rowCount:w,selectedRowCount:0,setPageIndex:M.setPageIndex,setPageSize:M.setPageSize,canPreviousPage:v==="server"&&a?a.hasPrevPage:M.getCanPreviousPage(),canNextPage:v==="server"&&a?a.hasNextPage:M.getCanNextPage(),previousPage:M.previousPage,nextPage:M.nextPage,onPageSizePreferenceChange:c,onClearSelection:()=>{},paginationMode:v,showExport:!1}):e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-[11px] tabular-nums text-muted-foreground",children:[w.toLocaleString()," ",w===1?"row":"rows"," · ",d.length," ",d.length===1?"column":"columns"]}),C.length>0&&e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["Sorted by"," ",e.jsx("span",{className:"font-medium text-foreground/70",children:C[0].id})," ",C[0].desc?"↓":"↑"]})]})})]})}const or=[{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 ir({className:s}){const n=t.useEditorStore(x=>x.card),a=t.useEditorStore(x=>x.frame),r=De.useEffectiveEditorCardType(),{setCard:c,updateCardInFrame:i}=t.useEditorActions(),l=["table","aggregateTable","pivotTable","detailTable"].includes(r),d=t.hasValidCardConfig(n.config),o=t.isCustomVisualConfigCard(n,a.cards);if(!l||!d||o)return null;const u=x=>{if(o)return;const h=x,m=n.config??{},g=p(r,h,m),v={...n,type:h,config:g};c(v),i(v)},p=(x,h,m)=>{var v;if(h==="detailTable"){const b=S=>S==null?void 0:S.toLowerCase().replace(/\s+/g,"").trim(),C=(S,M)=>{const w=[b(S.label),b(S.qualifiedFieldName),b(S.name)].filter(Boolean),D=[b(M.label),b(M.qualifiedFieldName),b(M.name)].filter(Boolean);return w.some(I=>D.includes(I))},E=(m.groupByColumns||[]).map(S=>({...S,role:"detail"})),B=((v=m.sortByColumns)==null?void 0:v.filter(S=>E.some(M=>C(S,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:E,groupByColumns:[],metricColumns:[],pivotByColumns:[],sortByColumns:B,rowAggregates:[],columnAggregates:[],comparisonType:"none"}}let g=m;if(x==="detailTable")if(m.detailTableBackup)g={...m,...m.detailTableBackup,detailColumns:[],detailTableBackup:void 0};else{const b=(m.detailColumns||[]).map(C=>({...C,role:"groupby"}));g={...m,groupByColumns:b,detailColumns:[]}}return h==="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:or.map(x=>{const h=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(h,{className:t.cn("h-3.5 w-3.5",m?"opacity-100":"opacity-75")}),x.label]})]},x.value)})})})}function ds({error:s,errorSql:n,errorTitle:a="Unable to load data",onOpenInEditor:r,onDebugWithAssistant:c,onSendFeedback:i,showFeedbackButton:l=!0,className:d}){const[o,u]=y.useState(!1);return e.jsx("div",{className:t.cn("rounded-lg border border-border bg-muted/40 p-4",d),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(Ea,{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"]}),c&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8",onClick:c,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 Fa(s,n){const a=t.useEditorStore(u=>u.card),r=t.useEditorStore(u=>u.isDevMode),{switchEditorMode:c,setRunSql:i,runAssistant:l}=t.useEditorActions();return{isDevMode:r,handleOpenInEditor:r?void 0:()=>{const u=n||a.sql||a.python||"";c("dev",{sqlToLoad:u}),setTimeout(()=>{i(!0)},100)},handleDebugWithAssistant:r?()=>{const u=`Can you help me debug this query?
|
|
177
|
+
|
|
178
|
+
Error:
|
|
179
|
+
|
|
180
|
+
${s}
|
|
181
|
+
|
|
182
|
+
Error SQL:
|
|
183
|
+
|
|
184
|
+
${n||a.sql||a.python}
|
|
185
|
+
|
|
186
|
+
`;l(u)}:void 0}}function Ra({className:s,...n}){var Te,Ee,$,oe,je;const a=t.useEditorStore(ee=>ee.card);t.useEditorStore(ee=>ee.isDevMode);const r=((Te=a.customCardPreferences)==null?void 0:Te.showCardHeader)??!0,c=(($=(Ee=a.preferences)==null?void 0:Ee.displayOptions)==null?void 0:$.showInlineFilterBar)??!0,i=t.useEditorStore(ee=>ee.frame),l=t.useEditorStore(ee=>ee.inlineFilterValuesMap[a.id]),d=t.useDashboardStore(ee=>ee.dashboard.filters),o=t.useDashboardStore(ee=>ee.selectedSheetId),[u,p]=y.useState(!1),{currentUser:x}=t.useCurrentUserInfo(),{tokenProps:h}=y.useContext(t.SemaphorContext),m=t.useEditorStore(ee=>ee.actions.setRunSql),g=t.useEditorStore(ee=>ee.actions.setCardInlineFilterValue),v=t.useEditorStore(ee=>ee.actions.removeCardInlineFilterValue),{updateFilter:b}=t.useDashboardActions(),C=d==null?void 0:d.find(ee=>ee.id===i.filterId),E=y.useMemo(()=>t.findCustomVisualConfigCard(i,a),[i,a]),{manifest:B}=t.useCustomVisual(((oe=E==null?void 0:E.customCardPreferences)==null?void 0:oe.url)||""),S=y.useMemo(()=>{var ee;return(ee=B==null?void 0:B.visuals)==null?void 0:ee.find(H=>{var le;return H.name===((le=E==null?void 0:E.customCardPreferences)==null?void 0:le.componentName)})},[B,(je=E==null?void 0:E.customCardPreferences)==null?void 0:je.componentName]),M=t.resolveMultiInputType(E,S),w=y.useMemo(()=>t.getCustomVisualInputCards({frame:i,configCard:E,isMultiInputVisual:M==="multiple"}),[i,E,M]),D=y.useMemo(()=>{const ee=w.findIndex(H=>(H==null?void 0:H.id)===(a==null?void 0:a.id));return ee<0?-1:t.getSlotIndexForCard(a,ee)},[w,a]),I=y.useMemo(()=>!E||M!=="multiple"||D<0?a.type:t.getEffectiveCardTypeForSlot(a,D,S==null?void 0:S.slots)??a.type,[E,M,D,a,S==null?void 0:S.slots]),k=I??a.type,j=y.useMemo(()=>k===a.type?a:{...a,type:k},[a,k]),R=y.useMemo(()=>I!==a.type?{...a,type:I}:a,[a,I]),{data:N,isLoading:L,isFetching:F,errorMessage:f,errorSql:A,pagination:T}=t.useDashboardCardQuery(R),{handleOpenInEditor:V,handleDebugWithAssistant:O}=Fa(f,A||a.sql||a.python),P=y.useMemo(()=>(N==null?void 0:N.records)||[],[N==null?void 0:N.records]),{setCard:_,updateCardInFrame:z}=t.useEditorActions(),{data:U}=t.useTopoJson(j),W=j.id,K=j.config,Z=j.interactionConfig,ae=j.customCfg,pe=j.preferences,fe=j.queryConfig,se=!!j.sql,ne=N==null?void 0:N.records,me=y.useMemo(()=>({id:W,type:k,config:K,interactionConfig:Z,sql:se?"__editor_sql__":""}),[W,k,K,Z,se]),be=y.useMemo(()=>{var ee;return k!=="pivotTable"||!((ee=N==null?void 0:N.records)!=null&&ee.length)?null:{records:N.records,columnSubtotalMeta:N.columnSubtotalMeta,subtotalColumns:N.subtotalColumns||[],pivotSchema:N.pivotSchema||[],groupByColumns:N.groupByColumns}},[k,N==null?void 0:N.records,N==null?void 0:N.columnSubtotalMeta,N==null?void 0:N.subtotalColumns,N==null?void 0:N.pivotSchema,N==null?void 0:N.groupByColumns]),ge=t.usePivotTableConfig(j,be),te=()=>{p(!0)},X=y.useMemo(()=>{const ee=typeof window<"u"?window.location.href:"",H=typeof navigator<"u"?navigator.userAgent:"",le=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:t.FeedbackCategory.QUERY_GENERATION,user:x,tokenContext:h,systemState:{cardConfig:a.config,dataSource:a.dataSource,dashboardFilters:d,errorMessage:f||void 0,errorSql:A||a.sql||a.python,generatedSql:A||a.sql},metadata:{url:ee,userAgent:H,timestamp:new Date().toISOString(),viewport:le}}},[x,h,a,d,f,A]),Ne=(ee,H)=>{var de,Ce;const le={...a,paginationConfig:{page:ee+1,pageSize:H}};_(le),z(le),a.sql&&((Ce=(de=a.preferences)==null?void 0:de.tablePrefs)!=null&&Ce.enableDevModePagination)&&m(!0)},Se=ee=>{var de,Ce,ve,Fe,Be;const H=t.sortStateToSortByColumns(ee,(de=a.config)==null?void 0:de.metricColumns,(Ce=a.config)==null?void 0:Ce.groupByColumns,(ve=a.config)==null?void 0:ve.detailColumns),le={...a,config:{...a.config||{},sortByColumns:H}};_(le),z(le),a.sql&&((Be=(Fe=a.preferences)==null?void 0:Fe.tablePrefs)!=null&&Be.enableDevModePagination)&&m(!0)},Oe=y.useMemo(()=>!W||!ne?null:t.createChartConfig({card:me,data:ne,cardType:k,queryConfig:fe,customCfg:ae,preferences:pe,topoJson:U}),[me,W,ae,pe,fe,ne,k,U]);function Ve(ee){return e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackVisual,children:e.jsx(t.EditorCustomVisual,{card:ee})})}function Ae(){var ee;if(N!=null&&N.records&&(N==null?void 0:N.records.length)===0&&!L&&!F)return f?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(ds,{error:f,errorSql:A||a.sql||a.python,onOpenInEditor:V,onDebugWithAssistant:O,onSendFeedback:te,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||F)&&(!(N!=null&&N.records)||N.records.length===0))return k==="table"||k==="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(!j.id)return null;if(k==="custom")return Ve(a);if(!["table","pivotTable","aggregateTable","detailTable","custom"].includes(k)&&Oe)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:L||F?e.jsx(e.Fragment,{}):e.jsx(t.ChartJsVisual,{cfg:Oe})});if(k==="table"||k==="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:j,data:P,comparisonMetadata:(ee=N==null?void 0:N.metadata)==null?void 0:ee.comparisonMetadata,paginationMetadata:T,onPaginationChange:Ne,onSortChange:Se,isLoading:L||F})});if(k==="pivotTable"&&ge)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:j,data:ge.data,options:ge.options,onAggregationChange:H=>{const le=t.handleAggregationChange(H,a.config),de={...a,config:le};_(de),z(de)},onAggregationLabelChange:H=>{const le=t.handleAggregationLabelChange(H,a.config),de={...a,config:le};_(de),z(de)}})});if(k==="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:j,data:(N==null?void 0:N.records)||[],groupByColumns:N==null?void 0:N.groupByColumns,pivotSchema:N==null?void 0:N.pivotSchema,paginationMetadata:T,onPaginationChange:Ne,onAggregationChange:H=>{const le=t.handleAggregationChange(H,a.config),de={...a,config:le};_(de),z(de)},isLoading:L||F})})}return e.jsxs(t.Card,{role:"editor-visual-card",className:t.cn("relative flex h-full flex-col rounded-none",s),...n,children:[(L||F)&&(N==null?void 0:N.records)&&N.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:ee=>_({...a,title:ee}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(t.InfoHover,{card:a}),e.jsx(De.VisualBadge,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(ir,{})})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(t.EditableText,{value:(a.description||"").trim(),onSave:ee=>_({...a,description:ee.trim()}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),C&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Label,{className:"my-1",children:e.jsx(t.EditableText,{value:C.title||C.column,onSave:ee=>b({...C,title:ee}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(t.FilterComponent,{filter:C})]})]}),c&&a.inlineFilters&&a.inlineFilters.length>0&&e.jsx("div",{className:t.cn("pb-2 pr-6","pl-2"),children:e.jsx(t.InlineFilterBar,{card:a,sheetId:o||"",inlineFilterValues:l,setInlineFilterValue:ee=>g(a.id,ee),removeInlineFilterValue:ee=>v(a.id,ee)})}),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:Ae()}),t.isCardSummaryVisibleOnCard(j)&&e.jsx("div",{className:"pt-3",children:e.jsx(t.CardSummary,{card:j,mode:"editor"})})]}),e.jsx(t.FeedbackDialog,{open:u,onOpenChange:p,feedbackData:X,showDebugInfo:!0})]})}const es=({language:s,value:n,onChange:a,readonly:r})=>e.jsx(t.CodeEditor,{className:"h-full w-full text-xs",language:s,value:n,onValueChange:a,readOnly:r,embedded:!0}),cr=()=>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."})]})]}),dr=({customCode:s,cardCustomCfgString:n,mergedConfig:a,onConfigChange:r,onCodeChange:c})=>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(es,{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(es,{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(es,{language:"javascript",value:s,onChange:c})})]}),ur=({error:s,hasCardCustomConfig:n,onReset:a,onApply:r,onClose:c})=>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:c,variant:"outline",children:"Close"})]});function mr({triggerVariant:s="icon",className:n,label:a="Customize Visual"}={}){const[r,c]=y.useState(!1),[i,l]=y.useState(""),[d,o]=y.useState(""),[u,p]=y.useState(""),[x,h]=y.useState(""),m=t.useEditorStore(j=>j.card),g=De.useEffectiveEditorCardType(),v=t.useEditorStore(j=>j.card.customCfg),b=v?JSON.stringify(v,null,2):"",C=y.useMemo(()=>g!==m.type?{...m,type:g}:m,[m,g]),{data:E}=t.useDashboardCardQuery(C),{data:B}=t.useTopoJson(m),{setCardCustomCfg:S,setCustomVisualCode:M}=t.useEditorActions(),w=j=>{var R,N;return JSON.stringify({...j,data:{...j.data,datasets:(N=(R=j.data)==null?void 0:R.datasets)==null?void 0:N.map(L=>({...L,data:[]}))}},null,2)},D=()=>{var R,N;if(!((R=E==null?void 0:E.records)!=null&&R.length))return;const j=t.createChartConfig({card:m,data:E.records,cardType:m.type,queryConfig:m.queryConfig,preferences:m.preferences,topoJson:B});if(j){l(w(j)),p(((N=m.preferences)==null?void 0:N.customVisualCode)||"");const L=t.merge(j,v);o(w(L))}},I=()=>{try{if(u&&M(u),d){const j=JSON.parse(d),R=t.getObjectDiff(JSON.parse(i),j);S(R),h("")}}catch{h("Invalid JSON configuration")}},k=Object.keys(v||{}).length===0;return e.jsxs(t.Dialog,{open:r,onOpenChange:c,children:[e.jsx(t.DialogTrigger,{asChild:!0,children:s==="menu"?e.jsxs(t.Button,{variant:"ghost",onClick:D,className:t.cn("h-8 w-full justify-start gap-2 px-2 text-sm",k?"":"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:D,className:t.cn(k?"":"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(cr,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackVisual,children:e.jsx(Ra,{className:"w-1/2 rounded shadow-none"})}),e.jsx(dr,{customCode:u,cardCustomCfgString:b,mergedConfig:d,onConfigChange:j=>o(j??""),onCodeChange:j=>p(j??"")})]}),e.jsx(ur,{error:x,hasCardCustomConfig:!!v,onReset:()=>{o(i),S(null)},onApply:I,onClose:()=>c(!1)})]})]})}function xr({isStarred:s,onClick:n,className:a}){const r=c=>{c.stopPropagation(),c.preventDefault(),n(c)};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 da({chartType:s,chartName:n,isCustom:a=!1,pluginName:r,isStarred:c,showStar:i=!0,onSelect:l,onToggleStar:d}){return e.jsxs("div",{className:"group relative",children:[i&&e.jsx("div",{className:t.cn("absolute left-1 top-1 z-10 transition-opacity",c?"opacity-100":"opacity-0 group-hover:opacity-100 group-focus-within:opacity-100"),children:e.jsx(xr,{isStarred:c,onClick:()=>d()})}),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 ua=[{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 hr({onChartSelect:s,onClose:n}){const[a,r]=y.useState(""),{starredCharts:c,isStarred:i,toggleStar:l}=t.useStarredChartsStore(),{data:d=[],isLoading:o}=t.useCustomVisualsQuery(),{setCardType:u,setCardPreferences:p,setIsDevMode:x}=t.useEditorStore(j=>j.actions),h=t.useEditorStore(j=>j.card),{setCardCustomCfg:m,setCustomCardPreferences:g,setVisualizationMode:v,setQueryConfig:b,replaceFrameCards:C,clearModeDrafts:E,initializeModeDrafts:B}=t.useEditorActions(),S=y.useMemo(()=>{if(!a)return ua;const j=a.toLowerCase();return ua.filter(R=>R.name.toLowerCase().includes(j))},[a]),M=y.useMemo(()=>{const j=d.filter(N=>N.componentType==="chart"&&N.pluginType!=="standard");if(!a)return j;const R=a.toLowerCase();return j.filter(N=>N.name.toLowerCase().includes(R))},[d,a]),w=j=>{m(null),p({}),v("builtin"),u(j),["custom","text","map"].includes(j)&&(x(!0),b(void 0)),s==null||s(j),n==null||n()},D=j=>{m(null),p({}),v("builtin"),b(void 0);const R=t.resolveMultiInputTypeFromVisual(j);if(R==="multiple"&&j.slots&&j.slots.length>0){E();const L=t.createCardsFromSlots(j.slots,j,h);C(L),L[0]&&B(L[0]),n==null||n();return}else u("custom"),g({type:"component",visualType:R,url:j.url,componentName:j.name,icon:j.icon,pluginChartType:j.chartType,minInputs:j.minInputs,maxInputs:j.maxInputs});s==null||s("custom",j),n==null||n()},I=j=>{const R={type:"default",id:j.id,name:j.name};l(R)},k=j=>{const R={type:"custom",id:j.name,url:j.url,icon:j.icon,name:j.name};l(R)};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,{placeholder:"Search charts...",value:a,onChange:j=>r(j.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:[S.length>0&&e.jsx("div",{className:"mb-3",children:e.jsx("div",{className:"grid grid-cols-3 gap-2",children:S.map(j=>e.jsx(da,{chartType:j.id,chartName:j.name,isCustom:!1,isStarred:i("default",j.id),onSelect:()=>w(j.id),onToggleStar:()=>I(j)},j.id))})}),M.length>0&&e.jsxs(e.Fragment,{children:[S.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((j,R)=>e.jsx(da,{chartName:j.name,isCustom:!0,pluginName:j.pluginName,isStarred:i("custom",j.name),onSelect:()=>D(j),onToggleStar:()=>k(j)},`${j.url}-${j.name}-${R}`))})]})]}),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..."})]}),S.length===0&&M.length===0&&!o&&e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No charts found"})]})]})}function pr({selectedChart:s,onChartChange:n}){var w,D,I,k;const a=t.useEditorStore(j=>j.card),r=t.useEditorStore(j=>j.frame),c=t.useEditorStore(j=>j.isDevMode),{replaceFrameCards:i,clearModeDrafts:l,initializeModeDrafts:d,setIsDevMode:o}=t.useEditorActions(),u=y.useMemo(()=>t.findCustomVisualConfigCard(r,a),[r,a]),{manifest:p}=t.useCustomVisual(((w=u==null?void 0:u.customCardPreferences)==null?void 0:w.url)||""),x=y.useMemo(()=>{var j;return(j=p==null?void 0:p.visuals)==null?void 0:j.find(R=>{var N;return R.name===((N=u==null?void 0:u.customCardPreferences)==null?void 0:N.componentName)})},[p,(D=u==null?void 0:u.customCardPreferences)==null?void 0:D.componentName]),h=t.resolveMultiInputType(u,x)==="multiple",m=De.useEffectiveEditorCardType(),g=h?m:s??a.type,v=(I=a==null?void 0:a.customCardPreferences)==null?void 0:I.componentName,b=(k=u==null?void 0:u.customCardPreferences)==null?void 0:k.componentName,C=h&&!!b,E=y.useMemo(()=>{const j=t.chartTypes.find(R=>R.id===g);return j?j.label:g==="custom"?v||"Custom Visual":"Select chart type"},[g,v]),B=y.useMemo(()=>{const j=t.chartTypes.find(R=>R.id===g);if(j){const R=j.icon;return e.jsx(R,{className:"h-4 w-4"})}if(g==="custom"&&v){const R=t.getAutoDetectedChartIcon(v);return R||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:E,displayIcon:B,showBadge:C,badgeLabel:b,isMultiInputContext:h,handleChartSelect:j=>{n==null||n(j)},handleClearCustomVisual:j=>{j.stopPropagation();const R={...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([R]),l(),d(R),c&&o(!0),n==null||n("bar")}}}function us({selectedChart:s,onChartChange:n,variant:a="ghost",className:r}){const[c,i]=y.useState(!1),{displayLabel:l,displayIcon:d,showBadge:o,badgeLabel:u,handleChartSelect:p,handleClearCustomVisual:x}=pr({selectedChart:s,onChartChange:n});return e.jsxs("div",{className:t.cn("relative w-full",r),children:[e.jsxs(t.Popover,{open:c,onOpenChange:i,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{size:"sm",variant:a,role:"combobox","aria-expanded":c,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:[d,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:h=>h.preventDefault(),children:e.jsx(hr,{onChartSelect:h=>p(h),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 fr(){const s=t.useEditorStore(o=>{var u,p;return(p=(u=o.card.preferences)==null?void 0:u.chartOptions)==null?void 0:p.indexAxis}),n=t.useEditorStore(o=>o.card.type),{setChartOrientation:a,setCardPreferences:r}=t.useEditorStore(o=>o.actions),c=o=>{if(a(o),n!=="bullet")return;const u=o==="y"?"horizontal":"vertical",p=t.useEditorStore.getState().card.preferences,x={...p||{},bulletConfig:{...(p==null?void 0:p.bulletConfig)||{},orientation:u}};r(x)};function i(){const o=s??"x",u=()=>{c(o==="x"?"y":"x")};return e.jsx(t.IconButton,{onClick:u,tooltip:"Chart Orientation",children:o==="x"?e.jsx(Xt,{className:"size-4"}):e.jsx(Wt,{className:"size-4"})})}function l(){const o=()=>{c(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(Xt,{className:"size-4"}):e.jsx(Wt,{className:"size-4"})})}function d(){const o=s??"y",u=()=>{c(o==="y"?"x":"y")};return e.jsx(t.IconButton,{onClick:u,tooltip:"Chart Orientation",children:o==="y"?e.jsx(Wt,{className:"size-4"}):e.jsx(Xt,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?l():n==="bullet"?d():i()})}function ms({className:s,triggerVariant:n="icon",label:a="Display Options"}){var v,b,C,E,B,S,M,w,D,I;const r=t.useEditorStore(k=>k.card),{setCardPreferences:c,updateCardInFrame:i,setCard:l}=t.useEditorActions(),[d,o]=y.useState(!1),u=((b=(v=r.preferences)==null?void 0:v.displayOptions)==null?void 0:b.showFilterInfo)??!0,p=((E=(C=r.preferences)==null?void 0:C.displayOptions)==null?void 0:E.showCardToolbar)??!0,x=((S=(B=r.preferences)==null?void 0:B.displayOptions)==null?void 0:S.showChrome)??!0,h=((w=(M=r.preferences)==null?void 0:M.displayOptions)==null?void 0:w.allowScroll)??!0,m=((I=(D=r.preferences)==null?void 0:D.displayOptions)==null?void 0:I.showInlineFilterBar)??!0,g=(k,j)=>{var L;const R={...r.preferences,displayOptions:{...(L=r.preferences)==null?void 0:L.displayOptions,[k]:j}};c(R);const N={...r,preferences:R};l(N),i(N)};return e.jsx("div",{className:t.cn("flex items-center",s),children:e.jsxs(t.DropdownMenu,{modal:!1,open:d,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:k=>{g("showFilterInfo",k)},onSelect:k=>k.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:p,onCheckedChange:k=>{g("showCardToolbar",k)},onSelect:k=>k.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:k=>{g("showChrome",k)},onSelect:k=>k.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:h,onCheckedChange:k=>{g("allowScroll",k)},onSelect:k=>k.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:k=>{g("showInlineFilterBar",k)},onSelect:k=>k.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 xs({className:s,triggerVariant:n="icon",label:a="Inline Filters"}){var M,w,D;const[r,c]=y.useState(!1),i=t.useEditorStore(I=>I.card),l=t.useEditorStore(I=>I.selectedConnectionId),{tokenProps:d}=t.useSemaphorContext(),{setCard:o}=t.useEditorActions(),u=t.useDashboardStore(I=>I.actions.removeCardInlineFilterValue),p=t.useDashboardStore(I=>I.actions.setCardInlineFilterValue),x=t.useEditorStore(I=>I.actions.removeCardInlineFilterValue),h=t.useEditorStore(I=>I.actions.setCardInlineFilterValue),m=t.useDashboardStore(I=>I.isVisualEditing),g=(i==null?void 0:i.inlineFilters)||[],v=((w=(M=d==null?void 0:d.params)==null?void 0:M.calendarContext)==null?void 0:w.tz)||((D=d==null?void 0:d.params)==null?void 0:D.timezone)||Intl.DateTimeFormat().resolvedOptions().timeZone;function b(I){var O,P,_,z,U;const k=((_=(P=(O=i==null?void 0:i.dataSource)==null?void 0:O.selectedEntities)==null?void 0:P[0])==null?void 0:_.database)||"",j=I.qualifiedFieldName||I.name;if(g.find(W=>t.doesStoredFilterMatchField(W,I)))return;const N=I.qualifiedFieldName?I.qualifiedFieldName.split(".").slice(0,-1).join("."):I.qualifiedEntityName||I.entityName,F=t.fmt(I.name),f=t.buildFilterFieldMeta(I),A=t.buildFilterSemanticContext(i==null?void 0:i.dataSource,{connectionId:l||((z=i==null?void 0:i.dataSource)==null?void 0:z.connectionId),connectionType:(U=i==null?void 0:i.dataSource)==null?void 0:U.connectionType}),T=t.isCalculatedFilterField(f),V={id:t.v4(),column:j,title:I.label||I.name,dataType:I.dataType,table:I.entityName||"",database:k,connectionId:l||"",operation:"in",sql:T?"":t.getDefaultFilterSql(I.dataType,N,F),fieldMeta:f,semanticContext:A,width:250};o({...i,inlineFilters:[...g,V]})}function C(I){const k=g.filter(j=>j.id!==I);o({...i,inlineFilters:k}),m?x(i.id,I):u(i.id,I)}function E(I,k){const j=g.map(F=>F.id===I?{...F,...k}:F);if(o({...i,inlineFilters:j}),!(Object.prototype.hasOwnProperty.call(k,"defaultValues")||Object.prototype.hasOwnProperty.call(k,"defaultDateFilter")))return;const N=j.find(F=>F.id===I);if(!N)return;const L=t.buildFilterValueFromDefaults(N,v);L?m?h(i.id,L):p(i.id,L):m?x(i.id,I):u(i.id,I)}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 S=n==="menu";return e.jsx("div",{className:t.cn("flex items-center gap-1",S&&"w-full",s),children:e.jsxs(t.Popover,{open:r,onOpenChange:c,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:S?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(sa,{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(sa,{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",S&&"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:b,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(I=>e.jsx(gr,{filter:I,onUpdate:k=>E(I.id,k),onRemove:()=>C(I.id)},I.id))})]})]})})]})})}function gr({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 jr={metric_selector:"Displayed metric",field_selector:"Group by field",aggregation_selector:"Aggregation",grain_selector:"Time grain"};function br(s,n){return s&&typeof s=="object"&&"label"in s&&typeof s.label=="string"&&s.label.trim().length>0?s.label:n||null}const vr={metric_selector:"config_metric_selector",field_selector:"config_field_selector",aggregation_selector:"config_aggregation",grain_selector:"config_grain"};function Vt(s,n){return`${s}:${n}`}function yr(s,n,a){const r=new Set(a.filter(i=>i.target!=="sql_param").map(i=>Vt(i.controlId,i.target))),c=n.map(i=>{const l=t.getCompatibleBindingTargetOptions({card:s,control:i}).map(p=>p.value),d=vr[i.type],u=[...d?[d]:[],...l.filter(p=>p!==d)].find(p=>!r.has(Vt(i.id,p)));return u?{controlId:i.id,target:u}:null}).find(Boolean);return c?{controlId:c.controlId,target:c.target,mapping:{}}:null}function Nr({card:s,dashboardControls:n,bindings:a,onChange:r,availableFieldChoices:c,availableMetricChoices:i,suppressTransientStaleState:l=!1}){const d=[...n,...s.controls||[]],[o,u]=y.useState({}),p=t.extractSqlParamReferences({sql:s.sql,controlBindings:s.controlBindings}),x=t.getBindingTargetSuggestions(s),h=new Set(a.map(B=>Vt(B.controlId,B.target))),m=d.some(B=>t.getCompatibleBindingTargetOptions({card:s,control:B}).some(S=>!h.has(Vt(B.id,S.value)))),g=l?0:a.reduce((B,S)=>{const M=v(S.target),w=Object.values(S.mapping).filter(D=>{const I=S.target==="config_metric_selector"||S.target==="config_field_selector"?typeof D=="string"?D:D==null?void 0:D.id:typeof D=="string"?D:void 0;return typeof I=="string"&&!M.some(k=>k.value===I)}).length;return B+w},0);function v(B){var S,M,w,D;switch(B){case"config_metric_selector":return i?i.filter(I=>!!I.target).map(I=>({value:I.target.id,label:I.target.label||I.option.label,target:I.target})):((M=(S=s.config)==null?void 0:S.metricColumns)==null?void 0:M.map(I=>({value:I.id,label:I.label||I.id,target:I})))||[];case"config_field_selector":return c?c.filter(I=>!!I.target).map(I=>({value:I.target.id,label:I.target.label||I.option.label,target:I.target})):((D=(w=s.config)==null?void 0:w.groupByColumns)==null?void 0:D.map(I=>({value:I.id,label:I.label||I.id,target:I})))||[];case"config_aggregation":return(x.config_aggregation||[]).map(I=>({value:I,label:I}));case"config_grain":return(x.config_grain||[]).map(I=>({value:I,label:I.charAt(0).toUpperCase()+I.slice(1)}));default:return[]}}const b=(B,S)=>{r(a.map((M,w)=>w!==B?M:S(M)))},C=B=>{r(a.filter((S,M)=>M!==B))},E=()=>{const B=yr(s,d,a);B&&r([...a,B])};if(typeof s.sql=="string"&&s.sql.trim().length>0){const B=p.map(({controlId:S,paramId:M})=>{const w=d.find(D=>D.id===S);return w?{id:S,paramId:M,label:w.label,reference:`[[param.${M}]]`}:{id:S,paramId:M,label:S,reference:`[[param.${M}]]`}});return e.jsx("div",{className:"space-y-2",children:B.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]]`."}):B.map(S=>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:S.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:S.reference}),e.jsx(t.CopyButton,{text:S.reference,ariaLabel:`Copy ${S.reference}`})]})]})},`${S.id}:${S.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((B,S)=>{const M=x[B.target]||[],w=d.find(f=>f.id===B.controlId),D=w?t.ensureManualSource(w):null,I=(D==null?void 0:D.source.kind)==="manual"?D.source.options:[],k=v(B.target),j=Array.from(new Set([...I.map(f=>f.value),...Object.keys(B.mapping)])).map(f=>{const A=I.find(T=>T.value===f);return{value:f,label:(A==null?void 0:A.label)||f}}),R=`${B.controlId}-${B.target}-${S}`,N=o[R]??S===0,L=Object.keys(B.mapping).length,F=w!=null&&w.type?jr[w.type]||w.type:null;return e.jsxs(t.Collapsible,{open:N,onOpenChange:f=>u(A=>({...A,[R]: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:[N?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:(w==null?void 0:w.label)||"Control"}),F?e.jsx(t.Badge,{variant:"secondary",className:"shrink-0 text-[11px] font-normal text-muted-foreground",children:F}):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:()=>C(S),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:j.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."}):k.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:j.map(f=>{const A=B.mapping[f.value],T=B.target==="config_metric_selector"||B.target==="config_field_selector"?typeof A=="string"?A:A==null?void 0:A.id:typeof A=="string"?A:void 0,V=!l&&typeof T=="string"&&!k.some(_=>_.value===T),O=br(A,T),P=T&&V?[...k,{value:T,label:"Needs remap",target:A}]:k;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:T||"__none__",onValueChange:_=>b(S,z=>{if(z.target==="config_metric_selector"){const W={...z.mapping};if(_==="__none__")delete W[f.value];else{const K=P.find(Z=>Z.value===_);K!=null&&K.target?W[f.value]=K.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 K=P.find(Z=>Z.value===_);K!=null&&K.target?W[f.value]=K.target:delete W[f.value]}return{...z,mapping:W}}const U={...z.mapping};return _==="__none__"?delete U[f.value]:U[f.value]=_,{...z,mapping:U}}),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"}),P.map(_=>e.jsx(t.SelectItem,{value:_.value,children:_.label},_.value))]})]}),V?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",O?` · Previously: ${O}`:""]})]}):null]})]},`${B.controlId}-${B.target}-${f.value}`)})}),M.length>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Available choices for this card: ",M.join(", ")]})]})})]},R)}),m?e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",onClick:E,children:[e.jsx(t.Plus,{className:"mr-2 h-4 w-4"}),"Add another control response"]}):null]})}const Cr=[];function Sr({className:s,triggerVariant:n="icon",label:a="Controls"}){var N,L;const{handleOpenChange:r,preventPassiveDismissDuringCreate:c,resolvedOpen:i,setIsCreateFlowActive:l}=De.useCreateFlowOverlayState({}),d=t.useEditorStore(F=>F.card),o=t.useEditorStore(F=>F.frame),u=t.useDashboardStore(F=>F.dashboard),x=t.useDashboardStore(F=>F.dashboard.controls)||Cr,{setCard:h,updateCardInFrame:m}=t.useEditorActions(),[g,v]=y.useState(null);y.useEffect(()=>{i&&!g&&(d!=null&&d.id)&&v(d.id)},[d==null?void 0:d.id,i,g]),y.useEffect(()=>{!i&&g!==null&&v(null)},[i,g]);const b=y.useMemo(()=>g?(o==null?void 0:o.cards.find(F=>F.id===g))||((d==null?void 0:d.id)===g?d:void 0):d,[d,o==null?void 0:o.cards,g]),C=(b==null?void 0:b.controls)||[],E=b?t.collectDashboardControlIds(u,{excludeCardId:b.id}):x.map(F=>F.id),B=((b==null?void 0:b.controlBindings)||[]).filter(F=>F.target!=="sql_param"),S=t.buildCardControlUsageById({card:b,controls:C}),M={choices:t.getFieldSelectorChoicesForCard(b),targetMap:Object.fromEntries((((N=b==null?void 0:b.config)==null?void 0:N.groupByColumns)||[]).map(F=>[F.id,F]))},w={choices:t.getMetricSelectorChoicesForCard(b),targetMap:Object.fromEntries((((L=b==null?void 0:b.config)==null?void 0:L.metricColumns)||[]).map(F=>[F.id,F]))},D=M.choices.map(F=>({option:F,target:M.targetMap[F.value]})),I=w.choices.map(F=>({option:F,target:w.targetMap[F.value]})),k=(F,f)=>{if(!b)return;const A=(f==null?void 0:f.type)==="rename"?t.applyControlMutationToCard(b,{type:"rename",oldId:f.oldId,newId:f.newId}):(f==null?void 0:f.type)==="remove"?t.applyControlMutationToCard(b,{type:"remove",controlId:f.controlId}):b,T={...A,controls:F,controlBindings:t.syncStructuralBindingsWithControls(A.controlBindings,F)};m(T),(d==null?void 0:d.id)===T.id&&h(T)},j=F=>{if(!b)return;const f={...b,controlBindings:t.mergeConfigBindingsWithSqlParamBindings(F,b.controlBindings)};m(f),(d==null?void 0:d.id)===f.id&&h(f)},R=n==="menu";return e.jsx("div",{className:t.cn("flex items-center gap-1",R&&"w-full",s),children:e.jsxs(t.Popover,{modal:!0,open:i,onOpenChange:r,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:R?e.jsxs(t.Button,{variant:"ghost",className:t.cn("h-8 w-full justify-start gap-2 px-2 text-sm",(C.length>0||B.length>0)&&"text-primary"),children:[e.jsx(t.SlidersHorizontal,{className:"h-4 w-4"}),e.jsx("span",{children:a}),C.length+B.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:C.length+B.length})]}):e.jsxs(t.IconButton,{tooltip:"Configure Controls",className:t.cn("relative",{"text-primary":C.length>0||B.length>0}),children:[e.jsx(t.SlidersHorizontal,{className:"h-4 w-4"}),C.length+B.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:C.length+B.length})]})}),e.jsxs(t.PopoverContent,{className:"flex max-h-[85vh] w-[560px] max-w-[95vw] flex-col",align:"end",onEscapeKeyDown:c,onPointerDownOutside:c,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."}),b!=null&&b.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(De.ControlDefinitionListEditor,{scope:"card",card:b,controls:C,reservedControlIds:E,usageByControlId:S,availableFieldChoices:D,availableMetricChoices:I,onCreateFlowActiveChange:l,onChange:(F,f,A)=>k(F,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."})]}),b?e.jsx(Nr,{card:b,dashboardControls:x,bindings:B,onChange:j,availableFieldChoices:D,availableMetricChoices:I}):null]})})]})]})})}function Oa({showOrientation:s=!0,showGridStyle:n=!0,showInlineFilters:a=!0,showControls:r=!0,showDisplayOptions:c=!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}),d=t.getChartGridStyle(l),{setChartGrid:o}=t.useEditorActions();function u(){const m=["xy","none","x","y"],v=(m.indexOf(d)+1)%m.length;o(m[v])}const p=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 p||x||a||r||c?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[p&&e.jsx(e.Fragment,{children:e.jsx(fr,{})}),x&&e.jsxs(t.IconButton,{tooltip:"Grid Style",onClick:u,children:[(d==="xy"||!d)&&e.jsx(t.Grid3x3,{className:"size-4"}),d==="x"&&e.jsx(cs,{className:"size-4"}),d==="y"&&e.jsx(zt,{className:"size-4"}),d==="none"&&e.jsx(t.Square,{className:"size-4"})]}),a&&e.jsx(xs,{}),r&&e.jsx(Sr,{}),c&&e.jsx(ms,{})]}):null}function wr({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(De.VisualBadge,{showLabel:!0,className:"h-6 w-fit px-2 py-0.5 text-[11px]"})})}function Tr({isPreviewMode:s,onPreviewToggle:n,configCard:a}){var F,f,A,T,V;const r=t.useEditorStore(O=>O.frame),c=t.useEditorStore(O=>O.card),{setFrame:i,setActiveTabCardId:l,setCard:d,updateCardInFrame:o,clearModeDrafts:u,initializeModeDrafts:p}=t.useEditorActions(),{manifest:x}=t.useCustomVisual(((F=a==null?void 0:a.customCardPreferences)==null?void 0:F.url)||""),h=(f=x==null?void 0:x.visuals)==null?void 0:f.find(O=>{var P;return O.name===((P=a==null?void 0:a.customCardPreferences)==null?void 0:P.componentName)}),g=t.resolveMultiInputType(a,h)==="multiple",v=(h==null?void 0:h.minInputs)??((A=a==null?void 0:a.customCardPreferences)==null?void 0:A.minInputs)??1,b=(h==null?void 0:h.maxInputs)??((T=a==null?void 0:a.customCardPreferences)==null?void 0:T.maxInputs),C=y.useMemo(()=>t.getCustomVisualInputCards({frame:r,configCard:a,isMultiInputVisual:g}),[r,a,g]),E=g?C.filter(Boolean).length:r.cards.length,B=b?E<b:!0,S=E>Math.max(v||1,1),M=!!((V=a==null?void 0:a.customCardPreferences)!=null&&V.dataInputCardIds),w=(O,P)=>{O.dataTransfer.setData("tabIndex",P.toString())},D=O=>{O.preventDefault()},I=(O,P)=>{const _=O.dataTransfer.getData("tabIndex");if(_===P.toString())return;const z=Array.from(r.cards),[U]=z.splice(parseInt(_),1);z.splice(P,0,U),i({...r,cards:z})};function k(O){const P=(a==null?void 0:a.id)===O;if(!(M&&P?r.cards.length>1:S))return;let z=r.cards.filter(Z=>Z.id!==O);g&&!M&&(z=t.reindexSlotCards(z));const U=z[0],W={...r,cards:z,activeCardId:U.id},K=O===c.id;K&&u(),i(W),l(U.id),d(U),K&&p(U)}function j(O,P){if(!B)return;const _={...r,cards:[...r.cards,P],activeCardId:O.id};i(_),l(P.id)}function R(){if(g&&(a==null?void 0:a.id)===c.id){N(c);return}const O={...c,id:t.v4(),title:`${c.title} Copy`,tabTitle:`${c.tabTitle||c.title} Copy`,customCardPreferences:c.customCardPreferences?{...c.customCardPreferences,slotIndex:g?Math.max(-1,...C.map((P,_)=>t.getSlotIndexForCard(P,_)))+1:c.customCardPreferences.slotIndex}:void 0};j(c,O)}function N(O){var K;if(!B)return;let P=g?"table":"bar",_="Title",z="";const U=g?Math.max(-1,...C.map((Z,ae)=>t.getSlotIndexForCard(Z,ae)))+1:E;if(g&&((K=h==null?void 0:h.slots)!=null&&K.length)){const Z=t.getSlotDefinitionForIndex(h.slots,U);Z&&(P=t.getSlotExpectedChartType(Z),_=Z.label||`Tab ${U+1}`,z=Z.description||"")}const W={dataSource:O.dataSource,connectionId:O.connectionId,lastSelectedDatabase:O.lastSelectedDatabase,lastSelectedSchema:O.lastSelectedSchema,lastSelectedTable:O.lastSelectedTable,lastSelectedDatamodelId:O.lastSelectedDatamodelId,id:t.v4(),title:_,tabTitle:_,description:z,preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:P,sql:"",data:[],mode:"explorer",...g&&{customCardPreferences:{slotIndex:U}}};j(O,W)}function L(O,P){return O.cards.length===1&&(P.displayTab===!0||P.displayTab===void 0)||O.activeCardId!==P.id&&(P.displayTab===!0||P.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const _=P.displayTab===void 0?!1:!P.displayTab;d({...P,displayTab:_}),o({...P,displayTab:_})},children:P.displayTab===!0||P.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((O,P)=>{var K,Z;const _=g?t.getSlotIndexForCard(O,P):-1,z=g&&((K=h==null?void 0:h.slots)!=null&&K.length)&&_>=0?t.getSlotDefinitionForIndex(h.slots,_):null,U=z?(Array.isArray(z.expectedType)?z.expectedType[0]:z.expectedType)||"table":O.type,W=g&&((Z=h==null?void 0:h.slots)==null?void 0:Z.length)&&h.slots.every(ae=>typeof ae.position=="number"||typeof ae.position=="string"&&!ae.position.includes("+"));return e.jsxs(t.TabsTrigger,{draggable:!g,onDragStart:g?void 0:ae=>w(ae,P),onDragOver:g?void 0:D,onDrop:g?void 0:ae=>I(ae,P),className:"",value:O.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(U,"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,O),e.jsx(t.Editable,{enabled:r.activeCardId===O.id,text:O.tabTitle||O.title,onSave:ae=>{d({...c,tabTitle:ae}),o({...c,tabTitle:ae})},children:O.tabTitle||O.title},O.id)]}),r.activeCardId===O.id&&!W&&e.jsx(t.CopyPlus,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:ae=>{ae.stopPropagation(),R()}}),r.activeCardId===O.id&&(M&&(a==null?void 0:a.id)===O.id?r.cards.length>1:S)&&e.jsx(t.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>k(O.id)})]},O.id)}),e.jsx(t.IconButton,{tooltip:"Add Card",className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",onClick:()=>N(c),disabled:!B,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 ot({renderCardOverride:s,alwaysRenderOverride:n=!1}={}){var Ee,$,oe,je,ee;const a=t.useEditorStore(H=>H.frame),r=t.useEditorStore(H=>H.card),[c,i]=y.useState(!1),l=y.useMemo(()=>t.findCustomVisualConfigCard(a,r),[a,r]),d=t.useEditorStore(H=>H.isSqlRunning);t.useEditorStore(H=>H.isDevMode);const{setFrame:o,setActiveTabCardId:u,setCard:p,setRunSql:x,mergeDraftsIntoCard:h,clearModeDrafts:m,initializeModeDrafts:g}=t.useEditorActions(),[v,b]=y.useState({}),[C,E]=y.useState(()=>new Set),{theme:B}=t.useTheme(),S=t.useDashboardStore(H=>H.themeStyle),{authToken:M}=t.useSemaphorContext(),w=t.getTokenParams(M==null?void 0:M.accessToken),D={mode:B||"system",colors:(($=(Ee=S==null?void 0:S.chart)==null?void 0:Ee.dataset)==null?void 0:$.backgroundColor)||[]},{getCard:I,manifest:k,isLoading:j}=t.useCustomVisual(((oe=l==null?void 0:l.customCardPreferences)==null?void 0:oe.url)||""),R=(je=l==null?void 0:l.customCardPreferences)==null?void 0:je.componentName,N=R?I(R):null,L=(ee=k==null?void 0:k.visuals)==null?void 0:ee.find(H=>H.name===R),F=t.resolveMultiInputType(l,L),f=c&&F==="multiple"&&!!l,A=y.useMemo(()=>t.getCustomVisualInputCards({frame:a,configCard:l,isMultiInputVisual:!0}).map(le=>(le==null?void 0:le.id)===r.id?r:le),[a,l,r]),T=y.useMemo(()=>t.buildSlotOrderedCards(A),[A]),V=y.useMemo(()=>{const H=A.findIndex(le=>(le==null?void 0:le.id)===r.id);return H<0?-1:t.getSlotIndexForCard(r,H)},[A,r]),O=y.useMemo(()=>!l||F!=="multiple"||V<0?r.type:t.getEffectiveCardTypeForSlot(r,V,L==null?void 0:L.slots)??r.type,[l,F,V,r,L==null?void 0:L.slots]),P=y.useMemo(()=>f?{...r,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:O!==r.type?{...r,type:O}:r,[r,O,f]),{data:_,isLoading:z,isFetching:U,isError:W}=t.useDashboardCardQuery(P),K=y.useCallback((H,le)=>{const de=t.normalizeMultiInputPayload(le);b(Ce=>({...Ce,[H]:de}))},[]),Z=y.useCallback((H,le)=>{E(de=>{const Ce=new Set(de);return le?Ce.add(H):Ce.delete(H),Ce})},[]),ae=C.size>0,pe=t.useInteractionStore(H=>H.interactionStates),fe=t.useDashboardStore(H=>{var le;return(le=H.dashboard)==null?void 0:le.id}),se=t.useDashboardStore(H=>H.dashboard.filters),ne=t.useDashboardStore(H=>H.filterValues),me=t.useDashboardStore(H=>H.selectedSheetId),be=t.useEditorStore(H=>H.inlineFilterValuesMap[(l==null?void 0:l.id)||""]),ge=t.useEditorStore(H=>H.actions.setCardInlineFilterValue),te=t.useEditorStore(H=>H.actions.removeCardInlineFilterValue),X=y.useMemo(()=>l?t.buildInlineFilterNodes({card:l,sheetId:me||"",inlineFilterValues:be,setInlineFilterValue:H=>ge(l.id,H),removeInlineFilterValue:H=>te(l.id,H)}):[],[l,me,be,ge,te]),{cardFilters:Ne,cardFilterValues:Se}=y.useMemo(()=>l?t.calculateContextAwareFilters({card:l,interactionStates:pe,currentDashboardId:fe,filters:se,filterValues:ne,selectedSheetId:me}):{cardFilters:[],cardFilterValues:[]},[l,pe,fe,se,ne,me]);function Oe(H){const le=a.cards.find(de=>de.id===H);le&&(it.flushPendingEditorDrafts(),h(),Ve(H),u(H),m(),g(le))}function Ve(H){const le=t.useEditorStore.getState().card,de=t.useEditorStore.getState().frame,Ce={...de,cards:de.cards.map(Fe=>Fe.id===le.id?le:Fe),activeCardId:H};o(Ce);const ve=Ce.cards.find(Fe=>Fe.id===H);ve.sql&&x(!0),p(ve)}function Ae(){if(j)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(!N)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 le=T.map((de,Ce)=>t.getEffectiveCardTypeForSlot(de,Ce,L==null?void 0:L.slots));return e.jsxs("div",{className:"relative flex h-full flex-col pl-2 pr-4",children:[A.map((de,Ce)=>{if(!de)return null;const ve=t.getSlotIndexForCard(de,Ce),Fe=t.getEffectiveCardTypeForSlot(de,ve,L==null?void 0:L.slots);return e.jsx(t.MultiInputEmptyRenderer,{onLoadingStatus:Z,onDataChange:K,card:de,effectiveCardType:Fe},`${de.id}-${ve}`)}),ae&&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",ae&&"opacity-50"),children:e.jsx(y.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(N,{editing:!0,...t.buildMultiInputCustomVisualProps({configCard:l,slotOrderedCards:T,slotTypes:le,multiInputData:v,params:w,theme:D,filters:Ne,filterValues:[...Se||[],...be||[]],inlineFilters:X})})})})]})}function Te(){var H;return f?Ae():s&&(n||!z&&!U&&!W)?s({card:r,data:_,isLoading:z,isFetching:U,isError:W}):r.type==="kpi"?z||U?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(wr,{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||U,isError:W,comparisonMetadata:(H=_==null?void 0:_.metadata)==null?void 0:H.comparisonMetadata})}),t.isCardSummaryVisibleOnCard(r)&&e.jsx(t.CardSummary,{card:r,mode:"editor"})]})}):r.type==="text"?z||U?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:d,card:r,data:_==null?void 0:_.records})})})}):e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackVisual,children:e.jsx(Ra,{className:"grow border-none shadow-none"})})}return e.jsxs(t.Tabs,{onValueChange:Oe,value:a.activeCardId,className:"flex grow flex-col gap-2",children:[f?e.jsx("div",{className:"mt-0 grow",children:Te()}):a.cards.map(H=>e.jsx(t.TabsContent,{className:"mt-0 grow focus-visible:ring-0 focus-visible:ring-offset-0",value:H.id,children:Te()},H.id)),e.jsx(Tr,{isPreviewMode:f,onPreviewToggle:i,configCard:l})]})}function Er({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 Pa({fallbackPreview:s,records:n,title:a,isInspectorOpen:r,onInspectorOpenChange:c}){var L;const i=t.useEditorStore(F=>F.card),l=t.useEditorStore(F=>F.actions.setCard),d=t.useEditorStore(F=>F.actions.updateCardInFrame),o=t.normalizeDynamicRendererSource((L=i.dynamicCardPreferences)==null?void 0:L.rendererCode),[u,p]=y.useState(o),[x,h]=y.useState(o);y.useEffect(()=>{p(o),h(o)},[o,i.id]);const m=y.useMemo(()=>t.normalizeDynamicRendererSource(u),[u]),g=y.useMemo(()=>t.validateDynamicRendererSource(m),[m]),v=!!o,b=y.useMemo(()=>{var F;return t.buildCardWithVisualizationMode(i,x?"dynamic":"builtin",{rendererCode:x||void 0,artifactId:((F=i.dynamicCardPreferences)==null?void 0:F.artifactId)||i.id,title:a||i.title})},[i,x,a]),C=!!x,E=m!==x,B=x!==o,S=!m||!g.valid||E||B,M=m?g.valid?E?"Unapplied changes":"Pending save":"Needs attention":"Draft",w=!m||E||B?"outline":"destructive",D=m?g.valid?E?"The preview still reflects the last applied code until you apply this draft.":B?"Preview reflects pending changes. Accept changes to save them.":"":g.error||"Visual code is invalid.":"Paste visual code or generate one before saving this card.";function I(){if(!g.valid){t.ue.error(g.error||"Visual code is invalid.");return}h(m),t.ue.success("Dynamic preview updated.")}function k(){p(x)}function j(){var f;const F=t.buildCardWithVisualizationMode(i,x?"dynamic":"builtin",{rendererCode:x||void 0,artifactId:((f=i.dynamicCardPreferences)==null?void 0:f.artifactId)||t.v4(),title:a||i.title});l(F),d(F),c(!1),t.ue.success(x?"Dynamic visual changes saved.":"Dynamic visual cleared.")}function R(){p(o),h(o),c(!1)}function N(){p(""),h("")}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:v?e.jsx(t.PersistedDynamicVisual,{card:i,records:n,title:a,layoutMode:"fill",fallback:s},o||"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(Er,{onClick:()=>c(!0)})]})}),e.jsx(t.Dialog,{open:r,onOpenChange:F=>{if(!F){R();return}c(!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:w,children:M})]})}),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:C?e.jsx(t.PersistedDynamicVisual,{card:b,records:n,title:a,layoutMode:"fill",fallback:s},x||"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:!v&&!m,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:N,children:"Clear"})]})]})]}),e.jsxs(t.Button,{type:"button",size:"sm",variant:"outline",className:"h-8 gap-1.5 px-2.5 text-xs",onClick:k,disabled:!E,children:[e.jsx(os,{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:I,disabled:!E||!g.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:[D&&e.jsx("p",{className:t.cn("text-xs",g.valid?"text-muted-foreground":"text-destructive"),children:D}),e.jsx("div",{className:t.cn("min-h-0 flex-1 overflow-hidden rounded-md border",!g.valid&&m&&"border-destructive"),children:e.jsx(t.CodeEditor,{value:u,onValueChange:F=>p(F||""),language:"javascript",embedded:!0})})]})]})})]})}),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:D||"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:R,children:"Cancel"}),e.jsx(t.Button,{type:"button",size:"sm",className:"h-8 px-3 text-xs",onClick:j,disabled:!B,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:c,setDynamicCardPreferences:i}=t.useEditorActions(),d=t.getVisualizationMode(n)==="dynamic";if(a.cards.length!==1||t.isCustomVisualizationCard(n))return null;const o=u=>{var p;u==="dynamic"&&!n.dynamicCardPreferences&&i(t.createEmptyDynamicCardPreferences(n.type,(p=n.preferences)==null?void 0:p.displayOptions)),c(u),r(!0)};return e.jsxs(e.Fragment,{children:[e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{onSelect:u=>{u.preventDefault(),o(d?"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:d,onCheckedChange:u=>o(u?"dynamic":"builtin"),onClick:u=>u.stopPropagation()})]}),d&&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 ma({children:s,visualAsideControl:n}){var fe;const a=t.useQueryClient(),r=t.useEditorStore(se=>se.frame),c=t.useEditorStore(se=>se.card),i=c.type==="table"||c.type==="detailTable",l=t.useEditorStore(se=>se.isDevMode),d=t.useEditorStore(se=>se.isShowingVisual),o=t.useEditorStore(se=>se.actions.setIsShowingVisual),u=t.useDashboardStore(se=>se.isVisualEditing),{isConsoleMode:p}=t.useDashboardPreferences(),x=t.useEditorStore(se=>se.pythonStdOut),h=t.useEditorStore(se=>se.actions.setRunSql),m=De.useEffectiveEditorCardType(),v=t.getVisualizationMode(c)==="dynamic",[b,C]=y.useState(!1),{setFrame:E,setCard:B,setActiveTabCardId:S,setCardPreferences:M,mergeDraftsIntoCard:w,clearModeDrafts:D,initializeModeDrafts:I,updatePageSize:k}=t.useEditorActions(),j=y.useMemo(()=>m!==c.type?{...c,type:m}:c,[c,m]),{data:R,isLoading:N,isFetching:L,errorMessage:F,errorSql:f,refetch:A,queryKey:T,pagination:V}=t.useDashboardCardQuery(j),O=y.useRef(T);O.current=T;const{handleDebugWithAssistant:P}=Fa(F,f),_=y.useMemo(()=>(R==null?void 0:R.records)||[],[R==null?void 0:R.records]),[z,U]=y.useState(!1);y.useEffect(()=>{L||U(!1)},[L]),y.useEffect(()=>{i&&!d&&!l&&!p&&o(!0)},[p,l,i,d,o]);function W(se,ne){var ge,te;const me={...c,paginationConfig:{page:se+1,pageSize:ne}};B(me);const be={...r,cards:r.cards.map(X=>X.id===c.id?me:X)};E(be),c.sql&&((te=(ge=c.preferences)==null?void 0:ge.tablePrefs)!=null&&te.enableDevModePagination)&&h(!0)}function K(se){var ge,te,X,Ne,Se;const ne=t.sortStateToSortByColumns(se,(ge=c.config)==null?void 0:ge.metricColumns,(te=c.config)==null?void 0:te.groupByColumns,(X=c.config)==null?void 0:X.detailColumns),me={...c,config:{...c.config||{},sortByColumns:ne}};B(me);const be={...r,cards:r.cards.map(Oe=>Oe.id===c.id?me:Oe)};E(be),c.sql&&((Se=(Ne=c.preferences)==null?void 0:Ne.tablePrefs)!=null&&Se.enableDevModePagination)&&h(!0)}function Z(){var ne;const se=JSON.stringify(R==null?void 0:R.records,null,2);typeof navigator>"u"||!((ne=navigator.clipboard)!=null&&ne.writeText)||navigator.clipboard.writeText(se).catch(me=>{console.error("Failed to copy JSON",me)})}function ae(){const se=JSON.stringify(R==null?void 0:R.records,null,2),ne=new Blob([se],{type:"application/json"}),me=URL.createObjectURL(ne),be=document.createElement("a");be.href=me,be.download=`${c.title}.json`,be.click()}function pe(){const ne=[Object.keys(R==null?void 0:R.records.reduce((te,X)=>({...te,...X}),{})).join(","),...((R==null?void 0:R.records)||[]).map(te=>Object.values(te).join(","))].join(`
|
|
187
|
+
`),me=new Blob([ne],{type:"text/csv"}),be=URL.createObjectURL(me),ge=document.createElement("a");ge.href=be,ge.download=`${c.title}.csv`,ge.click()}return c?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:[d&&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"})}),!v&&e.jsx("div",{className:"w-[200px]",children:e.jsx(us,{variant:l?"secondary":"ghost"})})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[s,e.jsx(t.IconButton,{tooltip:"Refresh",disabled:N||L,onClick:()=>{if(U(!0),l){it.flushPendingEditorDrafts(),setTimeout(()=>{a.removeQueries({queryKey:O.current,exact:!0}),h(!0)},0);return}A()},children:e.jsx(t.RefreshCcw,{className:t.cn("h-4 w-4",{"animate-spin":z})})}),!v&&e.jsx(Oa,{showInlineFilters:!1,showDisplayOptions:!1}),(l||p)&&e.jsxs(e.Fragment,{children:[e.jsx(kr,{}),i&&e.jsx(Dr,{})]}),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:[!v&&!["table","detailTable","custom"].includes(c.type)&&u&&e.jsx(mr,{triggerVariant:"menu",className:"w-full"}),e.jsx(xs,{triggerVariant:"menu",className:"w-full"}),e.jsx(ms,{triggerVariant:"menu",className:"w-full"}),e.jsx(Ba,{onCustomize:()=>C(!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:pe,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:ae,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"})]})]})]})]})]})]}),d?v?e.jsx(ot,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(Pa,{fallbackPreview:e.jsx(ot,{}),records:_,title:c.title,isInspectorOpen:b,onInspectorOpenChange:C})}):e.jsx(ot,{}):e.jsxs(t.ResizablePanelGroup,{className:"py-2 pl-2 pr-6",direction:"horizontal",children:[x&&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:x&&e.jsx(Ir,{})}),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":x}),children:[Array.isArray(R==null?void 0:R.records)&&!F&&(l?e.jsx(lr,{data:R.records,card:j,paginationMetadata:V,onPaginationChange:W,onPageSizePreferenceChange:k,onSortChange:K,isLoading:N||L}):R.records.length>0?e.jsx(t.TableVisual,{card:c,data:_,comparisonMetadata:(fe=R==null?void 0:R.metadata)==null?void 0:fe.comparisonMetadata,paginationMetadata:V,onPaginationChange:W,onSortChange:K,isLoading:N||L}):null),F&&e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(ds,{error:F,errorSql:f||c.sql||c.python,onDebugWithAssistant:P,showFeedbackButton:!1})})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function Ir(){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 Dr(){var d,o,u,p,x,h,m,g;const s=t.useEditorStore(v=>v.card),n=t.useEditorStore(v=>v.actions.setCard),a=t.useEditorStore(v=>v.actions.setRunSql),r=t.useEditorStore(v=>v.actions.setCardPreferences),c=t.useEditorStore(v=>v.actions.updateCardInFrame),i=y.useMemo(()=>{var v,b;return t.getTablePageSizeOptions((b=(v=s.preferences)==null?void 0:v.tablePrefs)==null?void 0:b.pageSize)},[(o=(d=s.preferences)==null?void 0:d.tablePrefs)==null?void 0:o.pageSize]),l=t.resolveTablePageSize((p=(u=s.preferences)==null?void 0:u.tablePrefs)==null?void 0:p.pageSize);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:((h=(x=s.preferences)==null?void 0:x.tablePrefs)==null?void 0:h.enableDevModePagination)??!1,onCheckedChange:v=>{var b;r({...s.preferences,tablePrefs:{...(b=s.preferences)==null?void 0:b.tablePrefs,enableDevModePagination:v}})}}),e.jsx(t.Label,{htmlFor:"dev-pagination",className:"cursor-pointer text-sm",children:"Paginate"}),((g=(m=s.preferences)==null?void 0:m.tablePrefs)==null?void 0:g.enableDevModePagination)&&e.jsxs(t.Select,{value:String(l),onValueChange:v=>{var E,B,S;const b=Number(v),C={...s,preferences:{...s.preferences,tablePrefs:{...(E=s.preferences)==null?void 0:E.tablePrefs,pageSize:b}},paginationConfig:{page:1,pageSize:b}};n(C),c(C),s.sql&&((S=(B=s.preferences)==null?void 0:B.tablePrefs)!=null&&S.enableDevModePagination)&&a(!0)},children:[e.jsx(t.SelectTrigger,{className:"h-8 w-20",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:i.map(v=>e.jsx(t.SelectItem,{value:String(v),children:v},v))})]})]})}function kr(){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:"Query Output"})]})}function qe({value:s,onCommit:n,type:a="text",placeholder:r,className:c}){const[i,l]=y.useState(s),d=y.useRef(!1);y.useEffect(()=>{l(s)},[s]);const o=()=>{if(d.current){d.current=!1;return}i!==s&&n(i)},u=p=>{if(p.key==="Enter"){p.currentTarget.blur();return}p.key==="Escape"&&(d.current=!0,l(s),p.currentTarget.blur())};return e.jsx(t.Input,{type:a,placeholder:r,value:i,onChange:p=>l(p.target.value),onBlur:o,onKeyDown:u,className:c})}function at({defaultValue:s,label:n,options:a,value:r,onValueChange:c,className:i,icon:l,showPlaceholderLabel:d=!0}){return e.jsxs(t.Select,{defaultValue:s,value:r,onValueChange:c,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}),d&&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 Ar(s,n){return t.getSlotDefinitionForIndex(s,n)||null}function St(s){if(typeof s=="number")return`Tab ${s+1}`;const n=s.match(/^(\d+)-(\d+)$/);if(n){const[,r,c]=n;return`Tabs ${Number(r)+1}-${Number(c)+1}`}const a=s.match(/^(\d+)\+$/);return a?`Tabs ${Number(a[1])+1}+`:`Tab ${s}`}function Mr(s){return s?Array.isArray(s)?s:[s]:[]}function ts(s){var r,c;if(!s)return!1;if(s.type==="text")return!!((r=s.description)!=null&&r.trim());const n=!!((c=s.sql)!=null&&c.trim()),a=t.hasValidCardConfig(s.config);return n||a}function Lr({slots:s,cards:n,minInputs:a}){const r=[],c=n.filter(Boolean).length;return a&&c<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];ts(o)||r.push({type:"missing-required",message:`${St(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 p=o;p<=u;p+=1){const x=n[p];if(!ts(x)){r.push({type:"missing-required",message:`${St(p)} ("${i.label}") is required but has no data configured.`});break}}return}const d=i.position.match(/^(\d+)\+$/);if(d){const o=Number(d[1]);if(n.length<=o){r.push({type:"missing-required",message:`${St(o)} ("${i.label}") is required but has no data configured.`});return}for(let u=o;u<n.length;u+=1){const p=n[u];if(!ts(p)){r.push({type:"missing-required",message:`${St(u)} ("${i.label}") is required but has no data configured.`});break}}}}),n.forEach((i,l)=>{if(!i)return;const d=Ar(s,l);if(!d||!d.expectedType)return;const o=Mr(d.expectedType);o.length!==0&&(o.includes(i.type)||r.push({type:"wrong-type",message:`${St(l)} ("${d.label}") expects ${o.join(", ")}, but is configured as ${i.type}.`}))})),r}const Fr={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 Va(){var N,L,F;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),c=t.useEditorStore(f=>f.frame),{setCustomCardPreferences:i}=t.useEditorActions(),l=y.useMemo(()=>t.findCustomVisualConfigCard(c,r),[c,r]),d=l==null?void 0:l.customCardPreferences,{components:o,manifest:u}=t.useCustomVisual((d==null?void 0:d.url)||(s==null?void 0:s.url)||""),p=(N=u==null?void 0:u.visuals)==null?void 0:N.find(f=>f.name===((d==null?void 0:d.componentName)||(s==null?void 0:s.componentName))),h=t.resolveMultiInputType(l||r,p)==="multiple",m=!!l&&l.id===r.id,g=(p==null?void 0:p.minInputs)??((L=l==null?void 0:l.customCardPreferences)==null?void 0:L.minInputs),v=(p==null?void 0:p.maxInputs)??((F=l==null?void 0:l.customCardPreferences)==null?void 0:F.maxInputs),b=y.useMemo(()=>t.getCustomVisualInputCards({frame:c,configCard:l||r,isMultiInputVisual:h}),[c,l,r,h]),C=y.useMemo(()=>t.buildSlotOrderedCards(b),[b]),E=y.useMemo(()=>C.map((f,A)=>{if(!f)return null;const T=t.getSlotIndexForCard(f,A),V=t.getEffectiveCardTypeForSlot(f,T,p==null?void 0:p.slots);return{...f,type:V??f.type}}),[C,p==null?void 0:p.slots]),B=y.useMemo(()=>Lr({slots:p==null?void 0:p.slots,cards:E,minInputs:g}),[p==null?void 0:p.slots,E,g]),S=y.useMemo(()=>{const f=b.findIndex(A=>(A==null?void 0:A.id)===r.id);return f<0?-1:t.getSlotIndexForCard(r,f)},[b,r]);function M(f){if(typeof f=="number")return`Tab ${f+1}`;const A=f.match(/^(\d+)-(\d+)$/);if(A){const[,V,O]=A;return`Tabs ${Number(V)+1}-${Number(O)+1}`}const T=f.match(/^(\d+)\+$/);return T?`Tabs ${Number(T[1])+1}+`:`Tab ${f}`}function w(f){return f?(Array.isArray(f)?f:[f]).join(", "):null}function D(f,A,T=[],V="",O,P,_){const z=I({key:A,defaultValue:V,settingsValue:P,sourceCard:_});return f==="input"?e.jsx(qe,{className:`h-8 w-full ${t.removeRing}`,value:String(z??""),onCommit:U=>{k({key:A,value:U,settingsField:O,settingsValue:P,sourceCard:_})}},A):f==="select"?e.jsx(at,{className:"h-8 w-full",label:"",options:T,value:String(z!==void 0?z:V??""),onValueChange:U=>{k({key:A,value:U,settingsField:O,settingsValue:P,sourceCard:_})}}):null}function I({key:f,defaultValue:A,settingsValue:T,sourceCard:V}){const O=T==null?void 0:T[f];return O!==void 0?O:f==="title"&&(V==null?void 0:V.title)!==void 0?V.title:f==="description"&&(V==null?void 0:V.description)!==void 0?V.description:A}function k({key:f,value:A,settingsField:T,settingsValue:V,sourceCard:O}){const P={...V||{}},_=f==="title"&&(O==null?void 0:O.title)!==void 0,z=f==="description"&&(O==null?void 0:O.description)!==void 0;_&&A===String((O==null?void 0:O.title)??"")||z&&A===String((O==null?void 0:O.description)??"")?delete P[f]:P[f]=A,i({...s||{},[T]:P})}function j({settingsSchema:f,settingsField:A,settingsValue:T,sourceCard:V,headerLabel:O}){const P=Object.entries(f||{});return e.jsxs("div",{className:"space-y-3",children:[O&&e.jsx(t.Label,{children:O}),P.map(([_,z])=>{var U;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}),((U=z.docs)==null?void 0:U.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})})]})})]}),D(z.ui,_,z.options,z.defaultValue,A,T,V)]},_)})]})}function R(){return e.jsxs(e.Fragment,{children:[h&&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:p!=null&&p.slots&&p.slots.length>0?e.jsx("div",{className:"space-y-3",children:p.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:[w(f.expectedType)&&e.jsxs("span",{children:["Expected: ",w(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`:""]})]})})]}),h&&B.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:B.map((f,A)=>e.jsx("li",{children:f.message},`${f.type}-${A}`))})})}),p&&!h&&p.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:j({settingsSchema:p.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:r})})}),p&&h&&(p.settings||p.slotSettings)&&e.jsxs("div",{className:"mt-4 space-y-4",children:[m&&p.settings&&e.jsx("div",{className:"px-2",children:j({settingsSchema:p.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:l||r,headerLabel:"Global Settings"})}),p.slotSettings&&e.jsx("div",{className:"px-2",children:j({settingsSchema:p.slotSettings,settingsField:"slotSettings",settingsValue:s==null?void 0:s.slotSettings,sourceCard:r,headerLabel:(()=>{const f=r.tabTitle||r.title,A=S>=0?S:0,T=m?"Slot 0":`Slot ${A}`;return f?`${T}: ${f} Settings`:`${T} 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:[(!h||m)&&e.jsx(at,{icon:e.jsx(Ta,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:a,value:(d==null?void 0:d.url)||"",onValueChange:f=>i({...s||{url:"",componentName:""},url:f})}),h&&!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&&(!h||m)&&e.jsx(e.Fragment,{children:o&&e.jsx(at,{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 V;const A=(V=u==null?void 0:u.visuals)==null?void 0:V.find(O=>O.name===f),T=o==null?void 0:o.find(O=>O.name===f);i({...s,componentName:f,visualType:(A==null?void 0:A.visualType)||(T==null?void 0:T.type)||"single",minInputs:A==null?void 0:A.minInputs,maxInputs:A==null?void 0:A.maxInputs,pluginChartType:A==null?void 0:A.chartType})}})})]})})]}),((d==null?void 0:d.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:(p==null?void 0:p.name)||"Settings"}),(p==null?void 0:p.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:[p.docs.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:p.docs.description}),p.docs.dataSchema&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Data Schema"}),e.jsx("div",{className:"prose prose-sm dark:prose-invert prose-pre:bg-muted prose-pre:text-xs max-w-none",children:e.jsx(t.Markdown,{remarkPlugins:[t.remarkGfm],components:Fr,children:p.docs.dataSchema})})]}),(()=>{var A;const f=(A=p.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((T,V)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1 text-primary",children:"•"}),e.jsx("span",{children:T})]},V))})]})})()]})})]})]})}),e.jsx(t.AccordionContent,{children:R()})]})]})}function Rr({colorRanges:s,setColorRanges:n}){const a={start:-1/0,end:100,color:""};function r(l,d,o){const u=[...s];u[l]={...u[l],[d]:o},n(u)}function c(l){const d=[...s];d.splice(l,1),n(d)}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,d)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(t.Input,{onChange:o=>r(d,"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(d,"end",o.target.value),className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx(t.Input,{onChange:o=>r(d,"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:()=>c(d),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(t.X,{className:"size-3"})})]},d))]})}function Or(){var p,x,h,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),c=t.useEditorStore(v=>v.actions.setNumberFormat);t.useEditorStore(v=>{var b,C;return(C=(b=v.card.preferences)==null?void 0:b.formatNumber)==null?void 0:C.decimalPlaces});const i=t.useEditorStore(v=>{var b,C;return(C=(b=v.card.preferences)==null?void 0:b.formatNumber)==null?void 0:C.locale}),l=t.useEditorStore(v=>{var b,C;return(C=(b=v.card.preferences)==null?void 0:b.formatNumber)==null?void 0:C.currency});t.useEditorStore(v=>v.actions.setFilterOnClickField);const d=t.useEditorStore(v=>{var b,C;return(C=(b=v.card.preferences)==null?void 0:b.formatNumber)==null?void 0:C.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:!!((p=s==null?void 0:s.formatNumber)!=null&&p.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 b,C,E;return c(((b=s==null?void 0:s.formatNumber)==null?void 0:b.decimalPlaces)||0,((C=s==null?void 0:s.formatNumber)==null?void 0:C.currency)||"",v,((E=s==null?void 0:s.formatNumber)==null?void 0:E.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 b,C,E;console.log("currency",v),c(((b=s==null?void 0:s.formatNumber)==null?void 0:b.decimalPlaces)||0,v==="none"?"":v,((C=s==null?void 0:s.formatNumber)==null?void 0:C.locale)||"",((E=s==null?void 0:s.formatNumber)==null?void 0:E.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=(h=s==null?void 0:s.formatNumber)==null?void 0:h.decimalPlaces)==null?void 0:m.toString())||"0",onValueChange:v=>{var b,C,E;return c(Number(v),((b=s==null?void 0:s.formatNumber)==null?void 0:b.currency)||"",((C=s==null?void 0:s.formatNumber)==null?void 0:C.locale)||"",((E=s==null?void 0:s.formatNumber)==null?void 0:E.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 b,C,E;return c(((b=s==null?void 0:s.formatNumber)==null?void 0:b.decimalPlaces)||0,((C=s==null?void 0:s.formatNumber)==null?void 0:C.currency)||"",((E=s==null?void 0:s.formatNumber)==null?void 0:E.locale)||"",v.target.value)}})]})]})]})}),e.jsx(t.Separator,{className:"my-3"}),e.jsx(Rr,{colorRanges:d,setColorRanges:o})]})]})}const Pr={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 za(s){return Pr[s]}function Br({chartType:s,showDocsLink:n=!0}){const a=za(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,c)=>e.jsxs("tr",{className:c<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 Vr({chartType:s}){return za(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(Br,{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(Vr,{chartType:s})]})}function zr(){return e.jsxs("div",{className:"space-y-6 px-6 py-4",children:[e.jsx(_t,{chartType:"kpi"}),e.jsx("section",{children:e.jsx(Or,{})})]})}function xa({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 _a(){const[s,n]=y.useState([]),a=t.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:c}=t.useEditorStore(u=>u.actions),i=t.useEditorStore(u=>u.queryResultColumns);t.useEditorStore(u=>{var p;return(p=u.card.preferences)==null?void 0:p.filterOnClickColumnIndex}),y.useEffect(()=>{i&&n(new Array(i.length).fill(!1))},[i]);function l(u,p){var x,h;p?a!=null&&a.onClickFilter&&((x=a==null?void 0:a.onClickFilter)==null?void 0:x.length)>0?c({...a,onClickFilter:[...a.onClickFilter,{columnIndex:u,expression:""}]}):c({...a,onClickFilter:[{columnIndex:u,expression:""}]}):(c({...a,onClickFilter:(h=a==null?void 0:a.onClickFilter)==null?void 0:h.filter(m=>m.columnIndex!==u)}),n(m=>{const g=[...m];return g[u]=!1,g}))}function d(u,p){var h;const x=(h=a==null?void 0:a.onClickFilter)==null?void 0:h.map(m=>m.columnIndex===u?{...m,expression:p.target.value}:m);c({...a,onClickFilter:x})}function o(u){var p,x,h,m;if(s!=null&&s[u]||(x=(p=a==null?void 0:a.onClickFilter)==null?void 0:p.find(g=>g.columnIndex===u))!=null&&x.expression)return e.jsx(t.Input,{value:(m=(h=a==null?void 0:a.onClickFilter)==null?void 0:h.find(g=>g.columnIndex===u))==null?void 0:m.expression,onChange:g=>d(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,p)=>{var x,h;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===p)),onCheckedChange:m=>l(p,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:((h=a==null?void 0:a.onClickFilter)==null?void 0:h.find(m=>m.columnIndex===p))&&e.jsx(t.Pencil,{onClick:()=>{n(m=>{const g=[...m];return g[p]=!m[p],g})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),o(p)]})},u)})})}const _r=[{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"}],qr=["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"],$r=qr.map(s=>({label:s,value:s}));function Kr(){var o,u,p,x,h,m,g,v,b,C,E,B,S,M,w,D,I,k;const s=t.useEditorStore(j=>j.card),n=(u=(o=s==null?void 0:s.preferences)==null?void 0:o.mapVisualOptions)==null?void 0:u.topoJsonUrl,[a,r]=y.useState(((x=(p=s==null?void 0:s.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:x.customTopoJsonUrl)||""),{setCardPreferences:c}=t.useEditorActions(),{data:i}=t.useTopoJson(s),l=Object.keys((i==null?void 0:i.objects)||{}).map(j=>({label:j,value:j}))||[],d=[{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(xa,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(at,{className:"h-9",options:d,onValueChange:j=>{console.log("value",j),c({...s.preferences,mapVisualOptions:{topoJsonUrl:j}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(t.Input,{onChange:j=>{r(j.target.value)},onBlur:()=>{var j;console.log("onBlur",a),c({...s.preferences,mapVisualOptions:{...(j=s.preferences)==null?void 0:j.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(at,{className:"h-9",options:l,value:((m=(h=s.preferences)==null?void 0:h.mapVisualOptions)==null?void 0:m.objectKey)||"",label:"Map Object",onValueChange:j=>{var R;c({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,objectKey:j}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Projection"}),e.jsx(at,{className:"h-9",options:_r,value:((v=(g=s.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:v.projection)||"",label:"Projection",onValueChange:j=>{var R;c({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,projection:j}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Colors"}),e.jsx(at,{className:"h-9",options:$r,value:((C=(b=s.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:C.colorScale)||"",label:"Select Color Scale",onValueChange:j=>{var R;c({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,colorScale:j}})}})]})]})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(xa,{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:((B=(E=s.preferences)==null?void 0:E.mapVisualOptions)==null?void 0:B.projectionScale)||1,onChange:j=>{var R;c({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,projectionScale:Number(j.target.value)}})}}),e.jsx(t.Label,{children:"X"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((w=(M=(S=s.preferences)==null?void 0:S.mapVisualOptions)==null?void 0:M.projectionOffset)==null?void 0:w[0])||0,onChange:j=>{var R,N,L,F;c({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,projectionOffset:[Number(j.target.value),((F=(L=(N=s.preferences)==null?void 0:N.mapVisualOptions)==null?void 0:L.projectionOffset)==null?void 0:F[1])||0]}})}}),e.jsx(t.Label,{children:"Y"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((k=(I=(D=s.preferences)==null?void 0:D.mapVisualOptions)==null?void 0:I.projectionOffset)==null?void 0:k[1])||0,onChange:j=>{var R,N,L,F;c({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,projectionOffset:[((F=(L=(N=s.preferences)==null?void 0:N.mapVisualOptions)==null?void 0:L.projectionOffset)==null?void 0:F[0])||0,Number(j.target.value)]}})}})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(_a,{})]})}function qa({color:s,onColorChange:n,onClose:a}){const[r,c]=y.useState(0),[i,l]=y.useState(100),[d,o]=y.useState(50),[u,p]=y.useState(s);y.useEffect(()=>{const b=ha(s);if(b){const C=pa(b.r,b.g,b.b);c(C.h),l(C.s),o(C.l),p(s)}},[s]);const x=b=>{c(b),m(b,i,d)},h=b=>{const C=b.currentTarget.getBoundingClientRect(),E=Math.max(0,Math.min(1,(b.clientX-C.left)/C.width)),B=Math.max(0,Math.min(1,(b.clientY-C.top)/C.height)),S=E*100,M=(1-B)*100;l(S),o(M),m(r,S,M)},m=(b,C,E)=>{const B=Ur(b,C,E),S=Gr(B.r,B.g,B.b);p(S)},g=b=>{if(p(b),/^#[0-9A-Fa-f]{6}$/.test(b)){const C=ha(b);if(C){const E=pa(C.r,C.g,C.b);c(E.h),l(E.s),o(E.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:h,onMouseMove:b=>{b.buttons===1&&h(b)},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-d}%`,backgroundColor:u}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:b=>x(Number(b.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:b=>g(b.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 ha(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 Gr(s,n,a){return"#"+((1<<24)+(s<<16)+(n<<8)+a).toString(16).slice(1)}function pa(s,n,a){s/=255,n/=255,a/=255;const r=Math.max(s,n,a),c=Math.min(s,n,a);let i=0,l=0;const d=(r+c)/2;if(r!==c){const o=r-c;switch(l=d>.5?o/(2-r-c):o/(r+c),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(d*100)}}function Ur(s,n,a){s/=360,n/=100,a/=100;let r,c,i;if(n===0)r=c=i=a;else{const l=(u,p,x)=>(x<0&&(x+=1),x>1&&(x-=1),x<.16666666666666666?u+(p-u)*6*x:x<.5?p:x<.6666666666666666?u+(p-u)*(.6666666666666666-x)*6:u),d=a<.5?a*(1+n):a+n-a*n,o=2*a-d;r=l(o,d,s+1/3),c=l(o,d,s),i=l(o,d,s-1/3)}return{r:Math.round(r*255),g:Math.round(c*255),b:Math.round(i*255)}}const fa=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],Hr=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function nt({value:s,onChange:n,label:a}){const[r,c]=y.useState(!1),[i,l]=y.useState(!1),d=()=>{const o=fa.find(u=>u.value===s);return o?o.color:s.startsWith("#")?s:fa[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:c,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:d()},"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:Hr.map(o=>e.jsx("button",{className:t.cn("h-5 w-5 rounded border-2 transition-all",d()===o?"border-gray-900":"border-transparent"),style:{backgroundColor:o},onClick:()=>{n(o),c(!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),c(!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(qa,{color:d(),onColorChange:o=>{n(o),l(!1)},onClose:()=>l(!1)})})]})]})}function Bt(s){return s==="currency"?2:s==="percent"?1:s==="scientific"?2:0}function ga(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?is(a,Bt(n)):a}function is(s,n){return{...s,decimalPlaces:n,minimumFractionDigits:n,maximumFractionDigits:n}}const Qr=["auto","number","currency","percent","scientific","date"],Jr=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"GBP",label:"GBP - British Pound"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"CHF",label:"CHF - Swiss Franc"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"},{value:"HKD",label:"HKD - Hong Kong Dollar"},{value:"SGD",label:"SGD - Singapore Dollar"},{value:"NZD",label:"NZD - New Zealand Dollar"},{value:"SEK",label:"SEK - Swedish Krona"},{value:"NOK",label:"NOK - Norwegian Krone"},{value:"DKK",label:"DKK - Danish Krone"},{value:"KRW",label:"KRW - South Korean Won"},{value:"INR",label:"INR - Indian Rupee"},{value:"RUB",label:"RUB - Russian Ruble"},{value:"BRL",label:"BRL - Brazilian Real"},{value:"MXN",label:"MXN - Mexican Peso"},{value:"TRY",label:"TRY - Turkish Lira"},{value:"ZAR",label:"ZAR - South African Rand"},{value:"SAR",label:"SAR - Saudi Riyal"},{value:"AED",label:"AED - UAE Dirham"},{value:"ARS",label:"ARS - Argentine Peso"},{value:"CLP",label:"CLP - Chilean Peso"},{value:"COP",label:"COP - Colombian Peso"},{value:"THB",label:"THB - Thai Baht"},{value:"IDR",label:"IDR - Indonesian Rupiah"},{value:"MYR",label:"MYR - Malaysian Ringgit"},{value:"PHP",label:"PHP - Philippine Peso"},{value:"PLN",label:"PLN - Polish Zloty"},{value:"NGN",label:"NGN - Nigerian Naira"},{value:"KES",label:"KES - Kenyan Shilling"},{value:"GHS",label:"GHS - Ghanaian Cedi"},{value:"ZMW",label:"ZMW - Zambian Kwacha"},{value:"ZWL",label:"ZWL - Zimbabwean Dollar"},{value:"EGP",label:"EGP - Egyptian Pound"},{value:"MAD",label:"MAD - Moroccan Dirham"},{value:"UAH",label:"UAH - Ukrainian Hryvnia"},{value:"HUF",label:"HUF - Hungarian Forint"},{value:"CZK",label:"CZK - Czech Koruna"},{value:"RON",label:"RON - Romanian Leu"},{value:"PKR",label:"PKR - Pakistani Rupee"},{value:"BDT",label:"BDT - Bangladeshi Taka"},{value:"VND",label:"VND - Vietnamese Dong"},{value:"TWD",label:"TWD - New Taiwan Dollar"},{value:"ILS",label:"ILS - Israeli New Shekel"}],Yr=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"en-IN",label:"English (India)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"},{value:"ja-JP",label:"Japanese"},{value:"ko-KR",label:"Korean"},{value:"ru-RU",label:"Russian"},{value:"ar-SA",label:"Arabic"},{value:"hi-IN",label:"Hindi"},{value:"nl-NL",label:"Dutch"},{value:"sv-SE",label:"Swedish"}],Wr=s=>s.charAt(0).toUpperCase()+s.slice(1);function jt({formatOptions:s={},onFormatOptionsChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const c=s.type||"auto",i=c==="auto"?s:ga(s,c),l=m=>{m.stopPropagation()},d=(m,g)=>{n({...i,[m]:g})},[o,u]=y.useState(()=>String(i.decimalPlaces??Bt(c))),[p,x]=y.useState(()=>i.multiplyBy!==void 0?String(i.multiplyBy):""),h=m=>{n(ga(s,m))};return y.useEffect(()=>{u(String(i.decimalPlaces??Bt(c)))},[i.decimalPlaces,c]),y.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:c,onValueChange:m=>h(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:Qr.map(m=>e.jsx(t.SelectItem,{value:m,className:"text-xs",children:m==="auto"?"Auto (Default)":Wr(m)},m))})]})]}),c!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent","scientific"].includes(c)&&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(is(i,Math.max(0,Math.min(10,parseInt(g,10)))))},onBlur:()=>{if(o!=="")return;const m=Bt(c);u(String(m)),n(is(i,m))},className:"h-8 text-xs"})})]}),c==="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=>d("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:Jr.map(m=>e.jsx(t.SelectItem,{value:m.value,className:"text-xs",children:m.label},m.value))})]})]}),["number","currency"].includes(c)&&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.Switch,{size:"sm",checked:s.useSuffix??!1,onClick:m=>m.stopPropagation(),onCheckedChange:m=>d("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=>d("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:Yr.map(m=>e.jsx(t.SelectItem,{value:m.value,className:"text-xs",children:m.label},m.value))})]})]}),c==="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=>d("prefix",m.target.value),className:"h-8 text-xs"})})]}),c==="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=>d("suffix",m.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(c)&&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.Switch,{size:"sm",checked:s.negativeInParentheses??!1,onClick:m=>m.stopPropagation(),onCheckedChange:m=>d("negativeInParentheses",m)})]}),c==="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:p,onClick:l,onPointerDown:l,onKeyDown:l,onChange:m=>{const g=m.target.value.replace(/[^0-9.]/g,"");x(g),d("multiplyBy",g?parseFloat(g):void 0)},className:"h-8 text-xs"})})]}),c==="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=>d("dateFormat",m.target.value),className:"h-8 text-xs"})})]})]})]})}function hs({value:s,onChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const c=t.toTFormatOptions(t.fromSemanticFormat(s))||{},i=l=>{n(t.fromTFormatOptions(l))};return e.jsx(jt,{formatOptions:c,onFormatOptionsChange:i,showTitle:a,title:r})}function Xr(){const s=t.useDashboardStore(d=>d.dashboard.filters),n=t.useEditorStore(d=>d.frame),{setFrame:a}=t.useEditorActions(),{dashboardFilterableFields:r}=t.useFilterableFields(),{assignFilter:c}=t.useAssignFilter();function i(d){const o=c(d,"frame");a({...n,filterId:o})}const l=s==null?void 0:s.find(d=>d.id===n.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Card Filter"}),e.jsx(Zr,{onSelect:i,columns:r}),l&&e.jsx(t.FilterHeader,{filter:l})]})}function Zr({columns:s,onSelect:n}){var d;const[a,r]=Pt.useState(!1),[c,i]=Pt.useState(""),l=Pt.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:[c?((d=s.find(o=>o.id===c))==null?void 0:d.label)||c:"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===c?"":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",c===o.id?"opacity-100":"opacity-0")})]},o.id))})]})]})})]})}const el=[{value:"difference",label:"Difference"},{value:"change",label:"Change (%)"},{value:"change_difference",label:"Change + Difference"},{value:"ratio",label:"Ratio"}],tl=[{value:"arrow_badge",label:"Arrow + Badge"},{value:"arrow",label:"Arrow Only"},{value:"badge",label:"Badge Only"},{value:"none",label:"None"}];function sl({cardType:s="table"}){var p,x,h,m,g;const n=t.useEditorStore(v=>v.card),a=t.useEditorStore(v=>{var b;return(b=v.card)==null?void 0:b.preferences}),r=t.useEditorStore(v=>v.actions.setCardPreferences),c=((p=n.config)==null?void 0:p.metricColumns)||[],i=c.some(v=>v.comparisonType&&v.comparisonType!=="none"),l=((x=a==null?void 0:a.tableVisualOptions)==null?void 0:x.metricComparison)||{},d=v=>{r({...a,tableVisualOptions:{...a==null?void 0:a.tableVisualOptions,metricComparison:{...l,...v}}})},o={increase:((h=l.colors)==null?void 0:h.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(Ia,{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=>d({calculatedAs:v}),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:el.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(jt,{formatOptions:l.formatOptions||{},onFormatOptionsChange:v=>d({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=>d({indicatorStyle:v}),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:tl.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(nt,{value:o.increase,onChange:v=>d({colors:{...o,increase:v}}),label:"Increase"}),e.jsx(nt,{value:o.decrease,onChange:v=>d({colors:{...o,decrease:v}}),label:"Decrease"}),e.jsx(nt,{value:o.neutral,onChange:v=>d({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=>d({lowerIsBetter:!!v})})]})]})]}),c.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:c.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(hs,{value:v.format,onChange:b=>{var E;const C=(((E=n.config)==null?void 0:E.metricColumns)||[]).map(B=>B.id===v.id?{...B,format:b}:B);t.useEditorStore.getState().actions.updateCardConfig(n.id,{metricColumns:C})},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(_a,{}),e.jsx(Xr,{})]})]})]}),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 al(){var r;const s=t.useEditorStore(c=>c.card.preferences),{setCardPreferences:n}=t.useEditorStore(c=>c.actions);function a(c){n({...s,textVisualOptions:{...s==null?void 0:s.textVisualOptions,isDynamicText:c==="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 nl(){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(al,{})]})]})}const rl=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function ll(){var M,w,D,I,k,j,R,N,L,F;const s=t.useEditorStore(f=>f.card),n=t.useEditorStore(f=>{var A;return(A=f.card)==null?void 0:A.preferences}),a=De.useEffectiveEditorCardType(),{setCardPreferences:r,updateCardInFrame:c}=t.useEditorActions(),i=y.useMemo(()=>a!==s.type?{...s,type:a}:s,[s,a]),{data:l}=t.useDashboardCardQuery(i),[d,o]=y.useState({}),[u,p]=y.useState(null),[x,h]=y.useState(null),m=y.useMemo(()=>{var V,O,P,_,z,U,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",T=((V=s==null?void 0:s.config)==null?void 0:V.pivotByColumns)&&s.config.pivotByColumns.length>0;if((f||A)&&T){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const K=new Set;return l.pivotSchema.forEach(Z=>{Z.alias&&K.add(Z.alias)}),Array.from(K)}if(l.records.length>0){const K=l.records[0],Z=Object.keys(K),ae=new Set;(O=s==null?void 0:s.config)!=null&&O.groupByColumns&&s.config.groupByColumns.forEach(se=>{ae.add(se.label||se.name),ae.add(se.alias||se.name)});const pe=new Set;return(P=s==null?void 0:s.config)!=null&&P.metricColumns&&s.config.metricColumns.forEach(se=>{const ne=se.alias||se.name;pe.add(ne),pe.add(`${ne}_count`),pe.add(`${ne}_sum`),pe.add(`${ne}_avg`),pe.add(`${ne}_min`),pe.add(`${ne}_max`);const me=se.entityName||se.qualifiedEntityName;me&&(pe.add(`${me}_${ne}`),pe.add(`${me}_${ne}_count`))}),Z.filter(se=>!ae.has(se)&&!pe.has(se))}}if((A||f)&&!T&&((z=(_=s==null?void 0:s.config)==null?void 0:_.metricColumns)!=null&&z.length))return s.config.metricColumns.map(K=>K.alias||K.label||K.name);if((W=(U=s==null?void 0:s.config)==null?void 0:U.groupByColumns)!=null&&W.length){const K=s.config.groupByColumns[0],Z=K.label||K.name,ae=new Set;return l.records.forEach(pe=>{const fe=pe[Z];fe!=null&&ae.add(String(fe))}),Array.from(ae)}return[]},[l,(M=s==null?void 0:s.config)==null?void 0:M.groupByColumns,(w=s==null?void 0:s.config)==null?void 0:w.pivotByColumns,(D=s==null?void 0:s.config)==null?void 0:D.metricColumns,s==null?void 0:s.type]),g=y.useMemo(()=>t.getDefaultChartColors(),[]);y.useEffect(()=>{const f={};m.forEach((A,T)=>{f[A]=t.getColorForValue(A,T,n==null?void 0:n.colorConfig)}),o(f)},[m,n==null?void 0:n.colorConfig,g]);const v=(f,A)=>{const T={...d,[f]:A};o(T);const V={...n||{},colorConfig:{segments:T}};r(V);const O={...s,preferences:V};c(O)},b=(f,A)=>{var z;const T=g[A%g.length],{[f]:V,...O}=((z=n==null?void 0:n.colorConfig)==null?void 0:z.segments)||{},P={...n||{},colorConfig:{segments:O}};r(P);const _={...s,preferences:P};c(_),o(U=>({...U,[f]:T}))};if(!m.length||!((s==null?void 0:s.type)==="stackedBar"||(s==null?void 0:s.type)==="stackedLine"?((k=(I=s==null?void 0:s.config)==null?void 0:I.groupByColumns)==null?void 0:k.length)||((R=(j=s==null?void 0:s.config)==null?void 0:j.pivotByColumns)==null?void 0:R.length):(L=(N=s==null?void 0:s.config)==null?void 0:N.groupByColumns)==null?void 0:L.length)||["table","kpi","text","custom","heatmap"].includes(a))return null;const B=()=>{const f={...n||{},colorConfig:{segments:{}}};r(f);const A={...s,preferences:f};c(A);const T={};m.forEach((V,O)=>{T[V]=t.getColorForValue(V,O,void 0)}),o(T)},S=Object.keys(((F=n==null?void 0:n.colorConfig)==null?void 0:F.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:S&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:B,children:[e.jsx(os,{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 T=t.isDefaultColor(d[f],A),V=!T;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Popover,{open:u===f,onOpenChange:O=>p(O?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:d[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((O,P)=>e.jsxs("button",{className:t.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",d[f]===O?"border-gray-900":"border-transparent"),style:{backgroundColor:O},onClick:()=>{v(f,O),p(null)},children:[P===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:O})]},`default-${P}`))})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Popular Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:rl.map((O,P)=>e.jsx("button",{className:t.cn("h-5 w-5 rounded border transition-all hover:scale-110",d[f]===O?"border-2 border-gray-900":O==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:O},onClick:()=>{v(f,O),p(null)},children:e.jsx("span",{className:"sr-only",children:O})},`preset-${P}`))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsx("button",{className:"text-sm font-medium text-blue-600 hover:text-blue-700",onClick:()=>{h({value:f,color:d[f]}),p(null)},children:"Custom color"}),!T&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{b(f,A),p(null)},children:[e.jsx(os,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:f}),V&&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:()=>h(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(qa,{color:x.color,onColorChange:f=>{v(x.value,f),h(null)},onClose:()=>h(null)})})]})]})})]})}function He({value:s,onSave:n,placeholder:a="",type:r="text",className:c=""}){const[i,l]=y.useState(s??""),[d,o]=y.useState(!1);y.useEffect(()=>{l(s??"")},[s]);const u=()=>{n(i),o(!1)},p=()=>{l(s??""),o(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${c}`,children:[e.jsx(t.Input,{placeholder:a,type:r,value:d?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"&&d&&i!==s?u():x.key==="Escape"&&p()},"aria-label":a||"Edit field"}),d&&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:p,children:e.jsx(t.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function ss({axis:s,label:n,type:a,config:r,onChange:c,defaultTitle:i,hidePosition:l}){var g,v,b,C,E,B,S,M,w,D,I,k,j,R;const d=t.normalizeContextFormatMode({formatMode:r==null?void 0:r.formatMode,formatOptions:r==null?void 0:r.formatOptions}),o=(N,L)=>{c({...r??{},[N]:L})},u=(N,L)=>{var T,V,O,P;const F=N==="enabled"&&L===!0,f=(T=r==null?void 0:r.name)==null?void 0:T.text,A=F&&!f&&i;c({...r??{},name:{...r==null?void 0:r.name,enabled:N==="enabled"?L:((V=r==null?void 0:r.name)==null?void 0:V.enabled)??!1,text:N==="text"?L:A?i:f,fontSize:N==="fontSize"?L:(O=r==null?void 0:r.name)==null?void 0:O.fontSize,fontWeight:N==="fontWeight"?L:(P=r==null?void 0:r.name)==null?void 0:P.fontWeight}})},p=(N,L)=>{var F,f;c({...r??{},labels:{enabled:N==="enabled"?L:((F=r==null?void 0:r.labels)==null?void 0:F.enabled)??!0,rotation:N==="rotation"?L:(f=r==null?void 0:r.labels)==null?void 0:f.rotation}})},x=(N,L)=>{c({...r??{},scale:{...r==null?void 0:r.scale,[N]:L===""?"auto":Number(L)}})},h=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.Switch,{size:"sm",checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:N=>o("enabled",N),onClick:N=>N.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:N=>u("enabled",N===!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(He,{placeholder:`${n} title`,value:((b=r==null?void 0:r.name)==null?void 0:b.text)||"",onSave:N=>u("text",N),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(He,{type:"number",placeholder:"12",value:String(((C=r==null?void 0:r.name)==null?void 0:C.fontSize)||12),onSave:N=>u("fontSize",Number(N)||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:((E=r==null?void 0:r.name)==null?void 0:E.fontWeight)||"normal",onValueChange:N=>u("fontWeight",N),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:N=>o("position",N),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:h.map(N=>e.jsx(t.SelectItem,{value:N,className:"text-xs",children:N==="auto"?"Auto (Default)":t.titleCase(N)},N))})]})]}),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.Switch,{size:"sm",checked:((B=r==null?void 0:r.labels)==null?void 0:B.enabled)!==!1,onCheckedChange:N=>p("enabled",N)})]}),((S=r==null?void 0:r.labels)==null?void 0:S.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:N=>p("rotation",N==="auto"?"auto":Number(N)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:m.map(N=>e.jsx(t.SelectItem,{value:N,className:"text-xs",children:N==="auto"?"Auto (Default)":`${N}°`},N))})]})]})]}),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.Switch,{size:"sm",checked:d==="override",onCheckedChange:N=>c({...r,formatMode:N?"override":"inherit"})})]}),d==="override"&&e.jsx(jt,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:N=>c({...r,formatMode:"override",formatOptions:N}),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(He,{type:"number",placeholder:"auto",value:((w=r==null?void 0:r.scale)==null?void 0:w.min)==="auto"||((D=r==null?void 0:r.scale)==null?void 0:D.min)===void 0?"":String(r.scale.min),onSave:N=>x("min",N),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(He,{type:"number",placeholder:"auto",value:((I=r==null?void 0:r.scale)==null?void 0:I.max)==="auto"||((k=r==null?void 0:r.scale)==null?void 0:k.max)===void 0?"":String(r.scale.max),onSave:N=>x("max",N),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(He,{type:"number",placeholder:"auto",value:((j=r==null?void 0:r.scale)==null?void 0:j.stepSize)==="auto"||((R=r==null?void 0:r.scale)==null?void 0:R.stepSize)===void 0?"":String(r.scale.stepSize),onSave:N=>x("stepSize",N),className:""})})]})]})]})]})]})}function as(s,n,a){var i,l,d;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=((d=n==null?void 0:n.config)==null?void 0:d.metricColumns)||[],c=(a==null?void 0:a.datasetOptions)||[];if(s==="y"){const o=r.filter((u,p)=>{const x=c.find(h=>h.idx===p);return!x||x.yAxisId!=="y2"});return o.length===1&&(o[0].label||o[0].name)||""}if(s==="y2"){const o=r.filter((u,p)=>{const x=c.find(h=>h.idx===p);return(x==null?void 0:x.yAxisId)==="y2"});return o.length===1&&(o[0].label||o[0].name)||""}return""}function ol(){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(),c=De.useEffectiveEditorCardType();if(!s||["tornado","pyramid","kpi","treemap"].includes(c))return null;const i=t.AxisConfigurator.getAxisInfo(c,n);if(!i.hasXAxis&&!i.hasYAxis)return null;const l=(o,u)=>{let p;o==="x"?p="xAxisConfig":o==="y"?p="yAxisConfig":p="secondaryYAxisConfig";const x={...n||{},[p]:u};a(x);const h={...s,preferences:x};r(h)},d=i.hasY2Axis&&c==="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(ss,{axis:"x",label:"X-Axis",type:i.xAxisType,config:t.mergeAxisConfig(t.getDefaultAxisConfig(c,"x"),n==null?void 0:n.xAxisConfig),onChange:o=>l("x",o),defaultTitle:as("x",s,n)}),i.hasYAxis&&e.jsx(ss,{axis:"y",label:d?"Y-Axis (Left)":"Y-Axis",type:i.yAxisType,config:t.mergeAxisConfig(t.getDefaultAxisConfig(c,"y"),n==null?void 0:n.yAxisConfig),onChange:o=>l("y",o),defaultTitle:as("y",s,n)}),d&&e.jsx(ss,{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:as("y2",s,n),hidePosition:!0})]})})]})}function il(){const s=t.useEditorStore(x=>x.card),n=De.useEffectiveEditorCardType(),a=t.useEditorStore(x=>{var h,m,g,v;return(v=(g=(m=(h=x.card)==null?void 0:h.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 c=t.getDefaultLegendConfig(n),i=(c==null?void 0:c.display)??!0,l=(c==null?void 0:c.position)??"top",d=(c==null?void 0:c.align)??"center",o=(x,h)=>{const m={...a,[x]:h};r(m)},u=["top","bottom","left","right"],p=["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.Switch,{size:"sm",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)||d,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:p.map(x=>e.jsx(t.SelectItem,{value:x,className:"text-xs",children:t.titleCase(x)},x))})]})]})]})]})})]})}function cl(){var L,F,f,A,T,V,O;const s=t.useEditorStore(P=>P.card),n=De.useEffectiveEditorCardType(),a=t.useEditorStore(P=>{var _,z;return(z=(_=P.card)==null?void 0:_.preferences)==null?void 0:z.dataLabelsConfig}),r=t.useEditorStore(P=>{var _;return(_=P.card)==null?void 0:_.preferences}),{setCardPreferences:c,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)??(((F=r==null?void 0:r.chartOptions)==null?void 0:F.indexAxis)==="x"?"vertical":"horizontal"):void 0,d=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",p=n==="bubble"||n==="scatter",x=(T=(A=r==null?void 0:r.chartOptions)==null?void 0:A.plugins)==null?void 0:T.datalabels,h=(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)??h??!1,b=(a==null?void 0:a.enabled)!==void 0?a.enabled:v,C=(P,_)=>{const W={...m??{},...a??{},[P]:_};P==="enabled"&&(W.display=_,_&&p&&!W.position&&(W.position="bottom")),P==="position"&&p&&(W.position="bottom"),P==="formatMode"&&_==="inherit"&&(W.format=void 0,W.formatOptions=void 0);const K={...s.preferences||{},dataLabelsConfig:W};c(K);const Z={...s,preferences:K};i(Z)},E=(P,_)=>{const z=a??{},W={...m??{},...z,font:{...z.font||{},[P]:_}},K={...s.preferences||{},dataLabelsConfig:W};c(K);const Z={...s,preferences:K};i(Z)},B=()=>{const P=n;return P==="stackedBar"||P==="stackedLine"||P==="pie"||P==="doughnut"?"center":d?"right":"top"},S=n!=="treemap"&&n!=="heatmap",M=n!=="treemap",w=B();let D=[];if(S)if(p)D=["bottom"];else if(o||u)D=["center"];else{const P=d?["center","left","right"]:["center","top","bottom"];D=["auto",...n==="bullet"?P:P.filter(z=>z!==w),"custom"]}const I=()=>t.titleCase(w),k=["center","start","end"],j=["center","start","end","top","bottom"],R=(g==null?void 0:g.formatMode)||(g!=null&&g.format&&!["auto"].includes(g.format)?"override":"inherit"),N=(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.Switch,{size:"sm",checked:b,onCheckedChange:P=>C("enabled",P)})]}),b&&e.jsxs(e.Fragment,{children:[S&&!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:p?(g==null?void 0:g.position)||"bottom":(g==null?void 0:g.position)||"auto",onValueChange:P=>C("position",P),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:D.map(P=>e.jsx(t.SelectItem,{value:P,className:"text-xs",children:P==="auto"?I():P==="custom"?"Custom (Advanced)":t.titleCase(P)},P))})]})]}),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.Switch,{size:"sm",checked:(a==null?void 0:a.showTotal)??!1,onCheckedChange:P=>C("showTotal",P)})]}),(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:P=>C("anchor",P),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:k.map(P=>e.jsx(t.SelectItem,{value:P,className:"text-xs",children:t.titleCase(P)},P))})]})]}),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:P=>C("align",P),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:j.map(P=>e.jsx(t.SelectItem,{value:P,className:"text-xs",children:t.titleCase(P)},P))})]})]})]}),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.Switch,{size:"sm",checked:R==="override",onCheckedChange:P=>C("formatMode",P?"override":"inherit")})]}),R==="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.Switch,{size:"sm",checked:N,onCheckedChange:P=>{const _=a??{},U={...m??{},..._,formatMode:"override",format:P?"none":void 0,formatOptions:P?void 0:_.formatOptions},W={...s.preferences||{},dataLabelsConfig:U};c(W),i({...s,preferences:W})}})]}),!N&&e.jsx(jt,{formatOptions:(g==null?void 0:g.formatOptions)||{},onFormatOptionsChange:P=>{const U={...m??{},...a??{},formatMode:"override",format:P.type&&P.type!=="auto"?P.type:void 0,formatOptions:P},W={...s.preferences||{},dataLabelsConfig:U};c(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(He,{type:"number",placeholder:"12",value:String(((V=g==null?void 0:g.font)==null?void 0:V.size)||12),onSave:P=>E("size",Number(P)),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:((O=g==null?void 0:g.font)==null?void 0:O.weight)||"normal",onValueChange:P=>E("weight",P),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:P=>{P==="auto"&&C("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(He,{type:"number",placeholder:"0",value:String((g==null?void 0:g.rotation)||0),onSave:P=>C("rotation",Number(P)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}const ja={difference:{label:"Difference",description:"Shows the exact difference between two values.",formula:"Primary - Secondary",example:"Sales increased by $5,000 compared to last year."},change:{label:"Change",description:"Shows the percentage increase or decrease between two values.",formula:"(Primary - Secondary) / Secondary × 100%",example:"Year-over-year sales change of 25%."},change_difference:{label:"Change (difference)",description:"Shows both the percentage change and the exact difference between two values.",formula:`% Change: (Primary - Secondary) / Secondary × 100%
|
|
188
|
+
Difference: Primary - Secondary`,example:"Sales grew by 25% ($5,000) compared to last year."},ratio:{label:"Ratio",description:"Shows how much of one value is covered by another — useful for quotas and benchmarks.",formula:"Primary / Secondary × 100%",example:"You've achieved 80% of your sales quota."}};function dl(){var h,m,g,v,b,C,E,B,S,M;const s=t.useEditorStore(w=>w.card),{setCardPreferences:n}=t.useEditorActions(),a=De.useEffectiveEditorCardType(),r=((h=s.config)==null?void 0:h.metricColumns)||[],c=((m=s.config)==null?void 0:m.groupByColumns)||[],i=r.length===2&&c.length===0,l=r.some(w=>w.comparisonType&&w.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=w=>{var I;const D={...s.preferences,kpiVisualOptions:{...(I=s.preferences)==null?void 0:I.kpiVisualOptions,metricComparison:{...o,...w}}};n(D)},p=l||o.enabled,x=r.some(w=>w.comparisonType==="previous_period"||w.comparisonType==="same_period_last_year"||w.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(Ia,{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.Switch,{size:"sm",id:"enable-comparison",checked:o.enabled||!1,onCheckedChange:w=>u({enabled:w,...w&&!o.calculationType?{calculationType:"difference"}:{}})})]}),p&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(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 w=o.calculationType||"difference",D=ja[w];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:D==null?void 0:D.label}),e.jsx("p",{children:D==null?void 0:D.description}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Formula:"})," ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-[10px]",children:D==null?void 0:D.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",D==null?void 0:D.example]})]})})()})]})]}),e.jsxs(t.Select,{value:o.calculationType||"difference",onValueChange:w=>u({calculationType:w}),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(ja).map(([w,D])=>e.jsx(t.SelectItem,{value:w,className:"text-xs",children:D.label},w))})]})]}),e.jsx(jt,{formatOptions:o.formatOptions||{},onFormatOptionsChange:w=>u({formatOptions:w}),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:w=>u({position:w}),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:w=>u({showArrow:w})}),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:w=>u({showColor:w})}),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(nt,{value:((b=o.colorConfig)==null?void 0:b.increase)||"green",onChange:w=>u({colorConfig:{...o.colorConfig,increase:w}}),label:"Primary > Secondary"}),e.jsx(nt,{value:((C=o.colorConfig)==null?void 0:C.decrease)||"red",onChange:w=>u({colorConfig:{...o.colorConfig,decrease:w}}),label:"Primary < Secondary"}),e.jsx(nt,{value:((E=o.colorConfig)==null?void 0:E.noChange)||"neutral",onChange:w=>u({colorConfig:{...o.colorConfig,noChange:w}}),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:w=>u({conditionalLabel:w})}),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:((B=o.conditionalLabels)==null?void 0:B.increase)??"Increase",onChange:w=>u({conditionalLabels:{...o.conditionalLabels,increase:w.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:((S=o.conditionalLabels)==null?void 0:S.decrease)??"Decrease",onChange:w=>u({conditionalLabels:{...o.conditionalLabels,decrease:w.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:w=>u({conditionalLabels:{...o.conditionalLabels,noChange:w.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:w=>u({labelName:w.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function ul(){var i;const s=t.useEditorStore(l=>{var d;return(d=l.card)==null?void 0:d.type}),n=t.useEditorStore(l=>{var d;return(d=l.card)==null?void 0:d.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",c=l=>{const d={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,treemapColorMode:l}};a(d)};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=>c(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 ml=Object.keys(t.HEATMAP_PRESET_PALETTES);function xl(){const s=t.useEditorStore(h=>h.card),n=t.useEditorStore(h=>{var m;return(m=h.card)==null?void 0:m.preferences}),{setCardPreferences:a}=t.useEditorActions(),r=(s==null?void 0:s.type)==="heatmap",c=(n==null?void 0:n.heatmapConfig)||{},i=c.colorPalette??"green",l=c.legendPosition??"bottom",d=y.useMemo(()=>c.colorRange&&c.colorRange[0]&&c.colorRange[1]?[c.colorRange[0],c.colorRange[1]]:[...t.DEFAULT_HEATMAP_CUSTOM_RANGE],[c.colorRange]),o=h=>{const m={...c,...h};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=h=>{o({colorPalette:h,colorRange:h==="custom"?c.colorRange??[...t.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},p=(h,m)=>{const g=[...d];g[h]=m,o({colorPalette:"custom",colorRange:g})},x=h=>{o({legendPosition:h})};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:h=>u(h??"blue"),className:"space-y-3",children:[ml.map(h=>{const m=t.HEATMAP_PRESET_PALETTES[h];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-${h}`,value:h}),e.jsxs(t.Label,{htmlFor:`heatmap-${h}`,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})`}})]})]},h)}),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(nt,{value:d[0],onChange:h=>p(0,h),label:"Start color"}),e.jsx(nt,{value:d[1],onChange:h=>p(1,h),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:h=>x(h??"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(h=>e.jsx(t.SelectItem,{value:h,className:"text-xs",children:h[0].toUpperCase()+h.slice(1)},h))})]})]})]})]}):null}const ba=["poor","satisfactory","good"];function va(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 hl(){var L,F;const s=t.useEditorStore(f=>f.card.preferences),n=t.useEditorStore(f=>f.card),a=t.useEditorStore(f=>f.isDevMode),{setCardPreferences:r,setChartOrientation:c}=t.useEditorActions(),i=y.useMemo(()=>(s==null?void 0:s.bulletConfig)||{},[s==null?void 0:s.bulletConfig]),d=t.hasValidCardConfig(n==null?void 0:n.config)&&!a,[o,u]=y.useState(i.showRanges??!1),[p,x]=y.useState(i.rangesArePercentages??!1),h=i.disableAutoComparative?!1:i.comparativeMetricKey!==void 0||!d,[m,g]=y.useState(h);y.useEffect(()=>{u(i.showRanges??!1)},[i.showRanges]),y.useEffect(()=>{x(i.rangesArePercentages??!1)},[i.rangesArePercentages]);const v=i.targetValue===void 0?"":String(i.targetValue);y.useEffect(()=>{const f=i.disableAutoComparative?!1:i.comparativeMetricKey!==void 0||!d;g(f)},[i.disableAutoComparative,i.comparativeMetricKey,d]);const b=y.useMemo(()=>{var f,A;return((A=(f=n==null?void 0:n.config)==null?void 0:f.metricColumns)==null?void 0:A.map(T=>{const V=T.label||T.name||T.alias||"";return{value:V,label:V}}))||[]},[(L=n==null?void 0:n.config)==null?void 0:L.metricColumns]);y.useEffect(()=>{var z,U;if(!s||b.length===0)return;const f={};let A=!1;const T=(z=b[1])==null?void 0:z.value;!i.targetMetricKey&&T&&(f.targetMetricKey=T,A=!0);const V=(U=b[2])==null?void 0:U.value;!i.comparativeMetricKey&&!i.disableAutoComparative&&V&&(f.comparativeMetricKey=V,A=!0);const O=b.slice(3),P={...i.rangeKeys||{}};let _=!1;if(ba.forEach((W,K)=>{!P[W]&&O[K]&&(P[W]=O[K].value,_=!0)}),_&&(f.rangeKeys=P,A=!0,i.showRanges===void 0&&(f.showRanges=!0)),A){const W=va({...i,...f});r({...s,bulletConfig:W})}},[b,i,s,r]);const C=f=>{const A=va({...i,...f});r({...s,bulletConfig:A})},E=(f,A)=>{const T={...i.rangeKeys||{},[f]:A.trim()};A.trim()||delete T[f],C({rangeKeys:Object.keys(T).length>0?T:void 0})},B=(f,A)=>{const T=A===""?void 0:Number(A),V={...i.ranges||{}};T===void 0||Number.isNaN(T)?delete V[f]:V[f]=T,C({ranges:Object.keys(V).length?V:void 0})},S=f=>{if(f===""){C({targetValue:void 0});return}const A=Number(f);C({targetValue:Number.isNaN(A)?void 0:A})},M=(f,A)=>{const T=A.trim(),V={...i.rangeLabels||{}};T?V[f]=T:delete V[f],C({rangeLabels:Object.keys(V).length>0?V:void 0})},w=f=>{u(f),C({showRanges:f})},D=f=>{x(f),C({rangesArePercentages:f})},I=i.orientation||(((F=s==null?void 0:s.chartOptions)==null?void 0:F.indexAxis)==="y"?"horizontal":"vertical"),k=f=>{C({orientation:f}),c(f==="horizontal"?"y":"x")},j=[{value:"__none",label:"None"},...b.map(f=>({value:f.value,label:f.label}))],R=j,N=f=>{if(g(f),!f){C({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!d){C({disableAutoComparative:!1});return}if(i.comparativeMetricKey)C({disableAutoComparative:!1});else{const A=b.find(T=>T.value!==i.targetMetricKey);C({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:I,onValueChange:f=>k(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"})]})]})]}),d&&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=>C({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"}),b.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"}),d?e.jsxs(t.Select,{value:i.comparativeMetricKey||"__none",onValueChange:f=>C({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:j.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.Switch,{size:"sm",checked:m,onCheckedChange:f=>N(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(qe,{type:"number",className:"h-8 text-xs",value:v,onCommit:S,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.Switch,{size:"sm",checked:o,onCheckedChange:w})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:p,disabled:!o,onChange:f=>D(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:ba.map(f=>{var A,T,V,O,P;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(qe,{placeholder:`Display label (${f})`,value:((A=i.rangeLabels)==null?void 0:A[f])||"",onCommit:_=>M(f,_),className:"h-8 text-xs"})]}),d?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:((T=i.rangeKeys)==null?void 0:T[f])||"__none",onValueChange:_=>{_==="__none"?E(f,""):E(f,_)},children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select column"})}),e.jsx(t.SelectContent,{children:R.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(qe,{placeholder:"Column key",value:((V=i.rangeKeys)==null?void 0:V[f])||"",onCommit:_=>E(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(qe,{type:"number",placeholder:p?"0.80":"Static value",value:((O=i.ranges)==null?void 0:O[f])===void 0?"":String((P=i.ranges)==null?void 0:P[f]),onCommit:_=>B(f,_),className:"h-8 text-xs"})]})]},f)})})]})]})]})}function ya(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 pl(){var M,w,D,I,k,j,R,N,L,F,f,A;const s=t.useEditorStore(T=>T.card.preferences),n=t.useEditorStore(T=>T.card),a=De.useEffectiveEditorCardType(),r=t.useEditorStore(T=>T.isDevMode),{setCardPreferences:c,updateCardInFrame:i}=t.useEditorActions(),l=a==="bubble",d=a==="scatter",o=y.useMemo(()=>(s==null?void 0:s.bubbleScatterConfig)||{},[s==null?void 0:s.bubbleScatterConfig]),p=t.hasValidCardConfig(n==null?void 0:n.config)&&!r,x=y.useMemo(()=>{var T,V;return((V=(T=n==null?void 0:n.config)==null?void 0:T.metricColumns)==null?void 0:V.map(O=>{const P=O.label||O.name||O.alias||"";return{value:P,label:P}}))||[]},[(M=n==null?void 0:n.config)==null?void 0:M.metricColumns]),h=y.useMemo(()=>{var T,V;return((V=(T=n==null?void 0:n.config)==null?void 0:T.groupByColumns)==null?void 0:V.map(O=>{const P=O.label||O.name||O.alias||"";return{value:P,label:P}}))||[]},[(w=n==null?void 0:n.config)==null?void 0:w.groupByColumns]),m=y.useMemo(()=>o.enableGrouping!==void 0?o.enableGrouping:!r&&h.length>=2,[o.enableGrouping,r,h.length]),[g,v]=y.useState(m);y.useEffect(()=>{v(m)},[m]);const b=T=>{const V={...s||{},bubbleScatterConfig:T};c(V),n&&i({...n,preferences:V})},C=T=>{c(T),n&&i({...n,preferences:T})};y.useEffect(()=>{if(!s||x.length===0)return;const T={};let V=!1;if(!o.xMetricKey&&x[0]&&(T.xMetricKey=x[0].value,V=!0),!o.yMetricKey&&x[1]&&(T.yMetricKey=x[1].value,V=!0),l&&!o.radiusMetricKey&&x[2]&&(T.radiusMetricKey=x[2].value,V=!0),!o.labelKey&&h[0]&&(T.labelKey=h[0].value,V=!0),m&&!o.groupKey&&h[1]&&(T.groupKey=h[1].value,T.enableGrouping=!0,V=!0),V){const O=ya({...o,...T});b(O)}},[x,h,o,s,c,l,m]);const E=T=>{const V=ya({...o,...T});b(V)},B=T=>{v(T),E({enableGrouping:T,groupKey:T?o.groupKey:void 0})};if(!l&&!d)return null;const S=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(S,{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"}),p?e.jsxs(t.Select,{value:o.labelKey||"",onValueChange:T=>E({labelKey:T}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select label column"})}),e.jsx(t.SelectContent,{children:h.map(T=>e.jsx(t.SelectItem,{value:T.value,children:T.label},T.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for labels",value:o.labelKey||"",onCommit:T=>E({labelKey:T})})]}),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.Switch,{size:"sm",checked:g,onCheckedChange:B})]}),g&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Group By"}),p?e.jsxs(t.Select,{value:o.groupKey||"",onValueChange:T=>E({groupKey:T}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select group column"})}),e.jsx(t.SelectContent,{children:h.map(T=>e.jsx(t.SelectItem,{value:T.value,children:T.label},T.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:o.groupKey||"",onCommit:T=>E({groupKey:T})})]})]}),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"}),p?e.jsxs(t.Select,{value:o.xMetricKey||"",onValueChange:T=>E({xMetricKey:T}),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(T=>e.jsx(t.SelectItem,{value:T.value,children:T.label},T.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:o.xMetricKey||"",onCommit:T=>E({xMetricKey:T})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Axis"}),p?e.jsxs(t.Select,{value:o.yMetricKey||"",onValueChange:T=>E({yMetricKey:T}),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(T=>e.jsx(t.SelectItem,{value:T.value,children:T.label},T.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:o.yMetricKey||"",onCommit:T=>E({yMetricKey:T})})]}),l&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Radius"}),p?e.jsxs(t.Select,{value:o.radiusMetricKey||"",onValueChange:T=>E({radiusMetricKey:T}),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(T=>e.jsx(t.SelectItem,{value:T.value,children:T.label},T.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for radius",value:o.radiusMetricKey||"",onCommit:T=>E({radiusMetricKey:T})})]})]}),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:T=>E({radiusScale:T}),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(qe,{className:"h-8 text-xs",type:"number",placeholder:"5",value:((D=o.minRadius)==null?void 0:D.toString())||"",onCommit:T=>E({minRadius:T?Number(T):void 0})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Max Radius"}),e.jsx(qe,{className:"h-8 text-xs",type:"number",placeholder:"30",value:((I=o.maxRadius)==null?void 0:I.toString())||"",onCommit:T=>E({maxRadius:T?Number(T):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:([T])=>E({fixedRadius:T}),min:3,max:30,step:1,className:"py-2"})]})]}),d&&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:([T])=>E({fixedRadius:T}),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.Switch,{size:"sm",checked:((j=(k=s==null?void 0:s.xAxisConfig)==null?void 0:k.name)==null?void 0:j.enabled)??!1,onCheckedChange:T=>{var P,_,z,U;const V=o.xMetricKey||"X Axis",O=o.yMetricKey||"Y Axis";C({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{enabled:T,text:((_=(P=s==null?void 0:s.xAxisConfig)==null?void 0:P.name)==null?void 0:_.text)||V}},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{enabled:T,text:((U=(z=s==null?void 0:s.yAxisConfig)==null?void 0:z.name)==null?void 0:U.text)||O}}})}})]}),((N=(R=s==null?void 0:s.xAxisConfig)==null?void 0:R.name)==null?void 0:N.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(qe,{className:"h-8 text-xs",placeholder:o.xMetricKey||"X Axis",value:((F=(L=s==null?void 0:s.xAxisConfig)==null?void 0:L.name)==null?void 0:F.text)||"",onCommit:T=>{var V;C({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{...(V=s==null?void 0:s.xAxisConfig)==null?void 0:V.name,enabled:!0,text:T||o.xMetricKey||"X Axis"}}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Title"}),e.jsx(qe,{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:T=>{var V;C({...s??{},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{...(V=s==null?void 0:s.yAxisConfig)==null?void 0:V.name,enabled:!0,text:T||o.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const fl=[{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 gl(){const s=t.useEditorStore(h=>h.card),n=t.useEditorStore(h=>{var m;return(m=h.card)==null?void 0:m.preferences}),{setCardPreferences:a}=t.useEditorActions(),r=(s==null?void 0:s.type)==="funnel",c=(n==null?void 0:n.funnelConfig)||{},i=c.percentMode??"percentOfTotal",l=c.shrinkFraction??1,d=c.labelThreshold??0,o=h=>{const m={...c,...h};a({...n||{},funnelConfig:m})},u=h=>{o({percentMode:h})},p=h=>{o({shrinkFraction:h[0]})},x=h=>{o({labelThreshold:h[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:h=>u(h),className:"space-y-2",children:fl.map(h=>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-${h.value}`,value:h.value,className:"mt-0.5"}),e.jsxs(t.Label,{htmlFor:`funnel-${h.value}`,className:"flex flex-col gap-0.5 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:h.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:h.description})]})]},h.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:p,min:0,max:1,step:.1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Full Shrink"})]}),e.jsxs("p",{className:"text-center text-xs text-muted-foreground",children:["Current: ",Math.round(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:[d],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:d===0?"Showing all labels":`Hide labels below ${d}%`})]})]})]}):null}function qt(){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 c=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);c=l.slice(1)}return{transformedMetricKeys:c,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}const jl=[{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"}],bl=[{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)"}],vl=["center","start","end"],yl=["center","start","end","top","bottom"];function $t({config:s,onChange:n,isHorizontal:a=!1,showAutoFormat:r=!0,positionOptions:c,showAppearance:i=!0}){var g,v,b,C,E,B;const l=c??(a?["auto","center","left","right","custom"]:["auto","center","top","bottom","custom"]),d=r?["auto","number","currency","percent","none"]:["number","currency","percent","none"],o=(S,M)=>{const w={...s,[S]:M};n(w)},u=(S,M)=>{const w={...s,font:{...(s==null?void 0:s.font)||{},[S]:M}};n(w)},p=(S,M)=>{const w={...s,formatOptions:{...(s==null?void 0:s.formatOptions)||{},[S]:M}};n(w)},x=()=>a?"Right":"Top",h=s||{},m=h.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:h.position||"auto",onValueChange:S=>o("position",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:l.map(S=>e.jsx(t.SelectItem,{value:S,className:"text-xs",children:S==="auto"?x():S==="custom"?"Custom (Advanced)":t.titleCase(S)},S))})]})]}),h.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:h.anchor||"center",onValueChange:S=>o("anchor",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:vl.map(S=>e.jsx(t.SelectItem,{value:S,className:"text-xs",children:t.titleCase(S)},S))})]})]}),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(h.align||"center"),onValueChange:S=>o("align",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:yl.map(S=>e.jsx(t.SelectItem,{value:S,className:"text-xs",children:t.titleCase(S)},S))})]})]})]}),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:S=>o("format",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:d.map(S=>e.jsx(t.SelectItem,{value:S,className:"text-xs",children:S==="auto"&&r?"Auto (Use Axis)":S==="none"?"None (Raw Value)":t.titleCase(S)},S))})]})]}),!["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(He,{type:"number",placeholder:"0",value:String(((g=h.formatOptions)==null?void 0:g.decimalPlaces)??(m==="currency"?2:m==="percent"?1:0)),onSave:S=>p("decimalPlaces",Number(S)),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=h.formatOptions)==null?void 0:v.currency)||"USD",onValueChange:S=>p("currency",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:jl.map(S=>e.jsx(t.SelectItem,{value:S.value,className:"text-xs",children:S.label},S.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.Switch,{size:"sm",checked:((b=h.formatOptions)==null?void 0:b.useSuffix)??!1,onCheckedChange:S=>p("useSuffix",S)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Locale"}),e.jsxs(t.Select,{value:((C=h.formatOptions)==null?void 0:C.locale)||"en-US",onValueChange:S=>p("locale",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:bl.map(S=>e.jsx(t.SelectItem,{value:S.value,className:"text-xs",children:S.label},S.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(He,{type:"number",placeholder:"12",value:String(((E=h.font)==null?void 0:E.size)||12),onSave:S=>u("size",Number(S)),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:((B=h.font)==null?void 0:B.weight)||"normal",onValueChange:S=>u("weight",S),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:h.color==="auto"||!h.color?"auto":"custom",onValueChange:S=>{S==="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(He,{type:"number",placeholder:"0",value:String(h.rotation||0),onSave:S=>o("rotation",Number(S)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"°"})]})]})]})]})]})}const Nl=[{type:"bar",icon:t.ChartColumnIncreasing,label:"Bar"},{type:"line",icon:t.ChartLine,label:"Line"}],Cl=[0,1,2,3,4,5,6,8,10],Sl=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],wl=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Tl(){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(El,{})})]})}function El(){const{transformedMetricKeys:s}=qt();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(Il,{metricKey:n,idx:a},n))})}function Il({metricKey:s,idx:n}){var C;const[a,r]=y.useState(!1),c=t.useEditorStore(E=>{var B;return(B=E.card)==null?void 0:B.preferences}),i=t.useEditorStore(E=>{var B,S;return(S=(B=E.card)==null?void 0:B.preferences)==null?void 0:S.datasetOptions}),l=i==null?void 0:i.find(E=>E.idx===n),{setCardPreferences:d}=t.useEditorStore(E=>E.actions),o=(l==null?void 0:l.type)||"bar",u=(l==null?void 0:l.yAxisId)||"y",p=((C=l==null?void 0:l.dataLabels)==null?void 0:C.enabled)??!1,x=o==="line"?t.ChartLine:t.ChartColumnIncreasing;function h(E){const B={idx:n,type:o,yAxisId:u,dataLabels:l==null?void 0:l.dataLabels,...E};if(!l)d({...c||{},datasetOptions:[...i||[],B]});else{const S=i==null?void 0:i.map(M=>M.idx===n?{...M,...B}:M);d({...c||{},datasetOptions:S})}}function m(E){h({type:E})}function g(E){h({yAxisId:E})}function v(E){h({dataLabels:{...l==null?void 0:l.dataLabels,enabled:E}})}function b(E){h({dataLabels:E})}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:Nl.map(({type:E,icon:B,label:S})=>{const M=o===E;return e.jsxs("button",{onClick:()=>m(E),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(B,{className:"h-4 w-4"}),e.jsx("span",{children:S})]},E)})})]}),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:E=>g(E),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:E=>h({lineStyle:E}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:wl.map(({value:E,label:B})=>e.jsx(t.SelectItem,{value:E,className:"text-xs",children:B},E))})]})]}),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:E=>h({pointRadius:Number(E)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Cl.map(E=>e.jsx(t.SelectItem,{value:String(E),className:"text-xs",children:E===0?"None":E},E))})]})]}),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:E=>h({pointStyle:E}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Sl.map(({value:E,label:B})=>e.jsx(t.SelectItem,{value:E,className:"text-xs",children:B},E))})]})]})]})]}),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.Switch,{size:"sm",checked:p,onCheckedChange:v})]}),p&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx($t,{config:l==null?void 0:l.dataLabels,onChange:b,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const ns=[{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"}],Dl=[0,1,2,3,4,5,6,8,10],kl=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],Al=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Ml(s){return s==null?"origin":s===!1?"false":s}function Ll(){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(Fl,{})})]})}function Fl(){const{transformedMetricKeys:s}=qt();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 v;const[a,r]=y.useState(!1),c=t.useEditorStore(b=>{var C;return(C=b.card)==null?void 0:C.preferences}),i=t.useEditorStore(b=>{var C,E;return(E=(C=b.card)==null?void 0:C.preferences)==null?void 0:E.datasetOptions}),l=i==null?void 0:i.find(b=>b.idx===n),{setCardPreferences:d}=t.useEditorStore(b=>b.actions),o=Ml(l==null?void 0:l.fill),u=((v=l==null?void 0:l.dataLabels)==null?void 0:v.enabled)??!1,p=ns.find(b=>b.value===o)||ns[0];function x(b){const C={idx:n,fill:o,dataLabels:l==null?void 0:l.dataLabels,...b};if(!l)d({...c||{},datasetOptions:[...i||[],C]});else{const E=i==null?void 0:i.map(B=>B.idx===n?{...B,...C}:B);d({...c||{},datasetOptions:E})}}function h(b){x({fill:b==="false"?!1:b})}function m(b){x({dataLabels:{...l==null?void 0:l.dataLabels,enabled:b}})}function g(b){x({dataLabels:b})}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"}),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-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Fill Target"}),e.jsxs(t.Select,{value:o,onValueChange:b=>h(b),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ns.map(b=>e.jsx(t.SelectItem,{value:b.value,className:"text-xs",children:e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{children:b.label})})},b.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:b=>x({lineStyle:b}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Al.map(({value:b,label:C})=>e.jsx(t.SelectItem,{value:b,className:"text-xs",children:C},b))})]})]}),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:b=>x({pointRadius:Number(b)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Dl.map(b=>e.jsx(t.SelectItem,{value:String(b),className:"text-xs",children:b===0?"None":b},b))})]})]}),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:b=>x({pointStyle:b}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:kl.map(({value:b,label:C})=>e.jsx(t.SelectItem,{value:b,className:"text-xs",children:C},b))})]})]})]})]}),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.Switch,{size:"sm",checked:u,onCheckedChange:m})]}),u&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx($t,{config:l==null?void 0:l.dataLabels,onChange:g,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Ol=[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 │"}],rs=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Bl(){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(Vl,{})})]})}function Vl(){const{transformedMetricKeys:s}=qt();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(zl,{metricKey:n,idx:a},n))})}function zl({metricKey:s,idx:n}){var b;const[a,r]=y.useState(!1),c=t.useEditorStore(C=>{var E;return(E=C.card)==null?void 0:E.preferences}),i=t.useEditorStore(C=>{var E,B;return(B=(E=C.card)==null?void 0:E.preferences)==null?void 0:B.datasetOptions}),l=i==null?void 0:i.find(C=>C.idx===n),{setCardPreferences:d}=t.useEditorStore(C=>C.actions),o=(l==null?void 0:l.lineStyle)||"solid",u=(l==null?void 0:l.pointRadius)??3,p=(l==null?void 0:l.pointStyle)||"circle",x=((b=l==null?void 0:l.dataLabels)==null?void 0:b.enabled)??!1,h=rs.find(C=>C.value===o)||rs[0];function m(C){const E={idx:n,lineStyle:o,pointRadius:u,pointStyle:p,dataLabels:l==null?void 0:l.dataLabels,...C};if(!l)d({...c||{},datasetOptions:[...i||[],E]});else{const B=i==null?void 0:i.map(S=>S.idx===n?{...S,...E}:S);d({...c||{},datasetOptions:B})}}function g(C){m({dataLabels:{...l==null?void 0:l.dataLabels,enabled:C}})}function v(C){m({dataLabels:C})}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"}),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-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:C=>m({lineStyle:C}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:rs.map(({value:C,label:E})=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:E},C))})]})]}),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:C=>m({pointRadius:Number(C)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ol.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 text-muted-foreground",children:"Point Shape"}),e.jsxs(t.Select,{value:p,onValueChange:C=>m({pointStyle:C}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Pl.map(({value:C,label:E})=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:E},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 text-muted-foreground",children:"Data Labels"}),e.jsx(t.Switch,{size:"sm",checked:x,onCheckedChange:g})]}),x&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx($t,{config:l==null?void 0:l.dataLabels,onChange:v,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const _l=[0,2,4,6,8,10,12,16,20];function ql(){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($l,{})})]})}function $l(){const{transformedMetricKeys:s}=qt();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(Kl,{metricKey:n,idx:a},n))})}function Kl({metricKey:s,idx:n}){var g;const[a,r]=y.useState(!1),c=t.useEditorStore(v=>{var b;return(b=v.card)==null?void 0:b.type}),i=t.useEditorStore(v=>{var b;return(b=v.card)==null?void 0:b.preferences}),l=t.useEditorStore(v=>{var b,C;return(C=(b=v.card)==null?void 0:b.preferences)==null?void 0:C.datasetOptions}),d=l==null?void 0:l.find(v=>v.idx===n),{setCardPreferences:o}=t.useEditorStore(v=>v.actions),u=(d==null?void 0:d.borderRadius)??0,p=((g=d==null?void 0:d.dataLabels)==null?void 0:g.enabled)??!1;function x(v){const b={idx:n,borderRadius:u,dataLabels:d==null?void 0:d.dataLabels,...v};if(!d)o({...i||{},datasetOptions:[...l||[],b]});else{const C=l==null?void 0:l.map(E=>E.idx===n?{...E,...b}:E);o({...i||{},datasetOptions:C})}}function h(v){x({dataLabels:{...d==null?void 0:d.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:_l.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.Switch,{size:"sm",checked:p,onCheckedChange:h})]}),p&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx($t,{config:d==null?void 0:d.dataLabels,onChange:m,isHorizontal:c==="horizontalBar",showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Gl=[0,1,2,3,4,5,6,8,10],Ul=[{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 │"}],Hl=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Ql(){const s=t.useEditorStore(d=>d.card),n=t.useEditorStore(d=>{var o;return(o=d.card)==null?void 0:o.preferences}),a=De.useEffectiveEditorCardType(),r=n==null?void 0:n.lineStyleConfig,{setCardPreferences:c,updateCardInFrame:i}=t.useEditorActions();if(!s||!["line","area","stackedArea"].includes(a))return null;const l=(d,o)=>{const u={...n||{},lineStyleConfig:{...r,[d]:o}};c(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:d=>l("lineStyle",d),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Hl.map(({value:d,label:o})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:o},d))})]})]}),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:d=>l("pointRadius",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Gl.map(d=>e.jsx(t.SelectItem,{value:String(d),className:"text-xs",children:d===0?"None":d},d))})]})]}),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:d=>l("pointStyle",d),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ul.map(({value:d,label:o})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:o},d))})]})]})]})})]})}const Jl=[0,2,4,6,8,10,12,16,20],Yl=[{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%"}],Wl=[{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 Xl(){const s=t.useEditorStore(d=>d.card),n=t.useEditorStore(d=>{var o;return(o=d.card)==null?void 0:o.preferences}),a=De.useEffectiveEditorCardType(),r=n==null?void 0:n.barStyleConfig,{setCardPreferences:c,updateCardInFrame:i}=t.useEditorActions();if(!s||!["bar","horizontalBar","stackedBar"].includes(a))return null;const l=(d,o)=>{const u={...n||{},barStyleConfig:{...r,[d]:o}};c(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:d=>l("borderRadius",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Jl.map(d=>e.jsx(t.SelectItem,{value:String(d),className:"text-xs",children:d===0?"None":`${d}px`},d))})]})]}),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:d=>l("barPercentage",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Yl.map(({value:d,label:o})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:o},d))})]})]}),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:d=>l("categoryPercentage",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Wl.map(({value:d,label:o})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:o},d))})]})]})]})})]})}function Zl(){const s=t.useEditorStore(a=>{var r,c;return(c=(r=a==null?void 0:a.card)==null?void 0:r.preferences)==null?void 0:c.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(at,{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 eo=["kpi"],Na={none:"None",previous_period:"Previous Period",same_period_last_year:"Same Period Last Year",start_vs_end:"Start vs End",target:"Target"},ls=2;function lt(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 to(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 so(s){return{...s,role:"groupby"}}function ao(){var E,B;const s=t.useEditorStore(S=>S.card),n=t.useEditorStore(S=>S.actions.updateCardConfig),a=De.useEffectiveEditorCardType(),{scopedFields:r}=t.useScopedFields(),c=((E=s.config)==null?void 0:E.metricColumns)||[],i=((B=s.config)==null?void 0:B.summary)||{},l=i.breakdownDimensions||[],d=eo.includes(a),o=c.length>0,u=i.enabled===!0,p=d&&o,{comparisonType:x}=t.getEffectiveComparisonSettings(s.config,a),h=Na[x]||Na.none,m=Array.from(new Map(r.filter(to).map(S=>[lt(S),so(S)])).values()),g=new Set(m.map(S=>lt(S))),v=new Set(l.map(S=>lt(S)).filter(S=>S&&g.has(S)));if(!d)return null;const b=S=>{n(s.id,{summary:{...i,...S}})},C=(S,M)=>{const w=lt(S),D=m.filter(k=>v.has(lt(k))),I=M?v.has(w)?D:[...D,S].slice(0,ls):D.filter(k=>lt(k)!==w);b({breakdownDimensions:I})};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.Switch,{size:"sm",id:"summary-enabled",checked:u,disabled:!p,onCheckedChange:S=>{if(!S){b({enabled:!1,showOnCard:!1,includeInDashboardSummary:!1});return}b({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: ",h]}),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.Switch,{size:"sm",id:"summary-show-on-card",checked:i.showOnCard===!0,disabled:!u,onCheckedChange:S=>b({showOnCard:S})})]}),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.Switch,{size:"sm",id:"summary-include-rollup",checked:i.includeInDashboardSummary===!0,disabled:!u,onCheckedChange:S=>b({includeInDashboardSummary:S})})]}),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,"/",ls]})]}),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(S=>{const M=lt(S),w=v.has(M),D=v.size>=ls,I=!u||!w&&D;return e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx(t.Checkbox,{id:`summary-breakdown-${M}`,checked:w,disabled:I,onCheckedChange:k=>C(S,k===!0)}),e.jsx(t.Label,{htmlFor:`summary-breakdown-${M}`,className:"cursor-pointer text-xs",children:S.label||S.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.Switch,{size:"sm",id:"summary-anomaly",checked:i.anomalyEnabled!==!1,disabled:!u,onCheckedChange:S=>b({anomalyEnabled:S})})]})]})]})}const no=[];function ro(){var c;const s=t.useEditorStore(i=>i.card),n=((c=s==null?void 0:s.config)==null?void 0:c.metricColumns)??no,{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(hs,{value:i.format,onChange:l=>{var d;a(s.id,i.id,{format:l}),r({...s,config:{...s.config,metricColumns:(((d=s.config)==null?void 0:d.metricColumns)||[]).map(o=>o.id===i.id?{...o,format:l}:o)}})}})]},i.id))})]})}const lo=new Set(["area","bar","bubble","bullet","combo","doughnut","funnel","horizontalBar","line","pie","polarArea","radar","scatter","stackedArea","stackedBar","stackedLine","tornado"]);function oo(){const s=t.useEditorStore(o=>o.card),n=t.useEditorStore(o=>{var u;return(u=o.card)==null?void 0:u.preferences}),a=De.useEffectiveEditorCardType(),{setCardPreferences:r,updateCardInFrame:c}=t.useEditorActions();if(!s||!lo.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",d=o=>{const u={...n||{},tooltipConfig:{...i||{},...o}};r(u),c({...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.Switch,{size:"sm",checked:l==="override",onCheckedChange:o=>d({formatMode:o?"override":"inherit",mode:o?"override":"inherit"})})]}),l==="override"&&e.jsx(jt,{formatOptions:(i==null?void 0:i.formatOptions)||{},onFormatOptionsChange:o=>d({formatMode:"override",mode:"override",formatOptions:o}),showTitle:!1})]})]})}function $a({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(Tl,{}),(n==="area"||n==="stackedArea")&&e.jsx(Ll,{}),n==="line"&&e.jsx(Bl,{}),(n==="bar"||n==="horizontalBar"||n==="stackedBar")&&e.jsx(ql,{}),e.jsx(Ql,{}),e.jsx(Xl,{}),e.jsx(ul,{}),s==="config"&&e.jsx(dl,{}),s==="config"&&e.jsx(ao,{}),e.jsx(xl,{}),n==="bullet"&&e.jsx(hl,{}),n==="funnel"&&e.jsx(gl,{}),(n==="bubble"||n==="scatter")&&e.jsx(pl,{}),(n==="stackedBar"||n==="stackedLine")&&e.jsx(Zl,{}),e.jsx(ro,{}),e.jsx(ll,{}),e.jsx(ol,{}),e.jsx(il,{}),e.jsx(cl,{}),e.jsx(oo,{})]})}function io(){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($a,{mode:"dev"})})]}):null}function co(){const s=t.useEditorStore(c=>c.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(zr,{});case"table":return e.jsx(sl,{});case"map":return e.jsx(Kr,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(Va,{})});case"text":return e.jsx(nl,{});default:return e.jsx(io,{})}}return e.jsxs(t.ScrollArea,{className:"h-full w-full text-sm",children:[r(),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}function uo(){const s=y.useRef(null),n=y.useRef(null),a=t.useEditorStore(x=>x.isShowingVisual),r=t.useEditorStore(x=>x.isDevMode),c=t.useEditorStore(x=>x.showAIDialog),[i,l]=y.useState(!1),d=a&&!c,o=d&&(!r||i),u=r&&d,p=()=>l(x=>!x);return y.useEffect(()=>{var x,h,m,g;c?((x=s.current)==null||x.resize(0),(h=n.current)==null||h.resize(0)):((m=s.current)==null||m.resize(25),(g=n.current)==null||g.resize(25))},[c]),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(ar,{})}),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(co,{})})}),!c&&e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(ma,{visualAsideControl:u?{show:!0,isOpen:i,onToggle:p}:void 0})})]}):e.jsx(ma,{visualAsideControl:u?{show:!0,isOpen:i,onToggle:p}:void 0})})]})}function mo(s){var Ee;t.useAIInteractionStore($=>$.currentAIContext);const[n,a]=y.useState(""),[r,c]=y.useState(null),{authToken:i,tokenProps:l}=t.useSemaphorContext(),d=t.useEditorStore($=>$.card.id),o=t.useEditorStore($=>{var oe;return(oe=$==null?void 0:$.card)==null?void 0:oe.sql}),u=t.useEditorStore($=>$.isDevMode),p=t.useEditorStore($=>{var oe;return(oe=$==null?void 0:$.card)==null?void 0:oe.python}),{setCardPython:x,setCardSql:h,setRunSql:m,switchCardType:g,setQueryConfig:v}=t.useEditorActions(),b=t.useEditorStore($=>$.currentAssitantScope)||[],C=t.useEditorStore($=>$.userInputForAI),E=t.useEditorStore($=>$.triggerAIRun),B=t.useEditorStore($=>$.card),S=t.useEditorStore($=>$.selectedDatabaseName),M=t.useEditorStore($=>$.selectedTableName),w=t.useEditorStore($=>$.selectedConnectionId),D=t.useEditorStore($=>$.selectedSchemaName),I=t.useDashboardStore($=>$.dashboard.aiScopeTables),{errorMessage:k,refetch:j,data:R}=t.useDashboardCardQuery(B),{setTriggerAIRun:N,setCurrentAssitantScope:L,setCardConfig:F}=t.useEditorActions(),{selectedDatamodelName:f,connectionType:A,selectedDatamodelId:T}=t.useEditorAside(),V=(Ee=t.useDashboardQuery().data)==null?void 0:Ee.assistantProfileId,O=y.useRef(t.createAssistantConversationId()),P=y.useRef(null),_=y.useRef(d),z=y.useRef(!1),U=()=>{const $=P.current;$&&(P.current=null,O.current=t.createAssistantConversationId(),$==="clear"&&K([]))},{messages:W,setMessages:K,regenerate:Z,error:ae,sendMessage:pe,status:fe,addToolResult:se,stop:ne,clearError:me}=t.useChat({transport:new t.DefaultChatTransport({api:`${l.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${i==null?void 0:i.accessToken}`}),body:()=>{const $=t.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:V,conversationId:O.current,assistantRequestId:t.createAssistantRequestId(),isDevMode:u,aiContext:$.currentAIContext,reasoningEffort:$.reasoningEffort,showReasoning:$.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:$,body:oe})=>({body:{...oe,messages:t.cleanupIncompleteMessages($)}})}),onError:$=>{var oe;if(z.current=!1,$.name==="AbortError"||(oe=$.message)!=null&&oe.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)"),U();return}console.error("[Editor Assistant] Stream error:",$),U()},onToolCall:X,onFinish({isAbort:$,isDisconnect:oe,isError:je}){z.current=!1,a(""),console.log($?"[Editor Assistant] Stream aborted by user":oe?"[Editor Assistant] Stream disconnected (network error)":je?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully"),U()}}),be=y.useCallback($=>{z.current=!0;try{const oe=pe($);return t.isPromiseLike(oe)?oe.catch(je=>{throw z.current=!1,je}):oe}catch(oe){throw z.current=!1,oe}},[pe]),ge=y.useCallback(()=>{z.current=!0;try{const $=Z();return t.isPromiseLike($)?$.catch(oe=>{throw z.current=!1,oe}):$}catch($){throw z.current=!1,$}},[Z]),te=$=>{let oe=!1;K(je=>{const ee=typeof $=="function"?$(je):$;if(ee.length===0){if(z.current)return P.current="clear",oe=!0,je;P.current=null,O.current=t.createAssistantConversationId()}return ee}),oe&&ne()};y.useEffect(()=>{if(_.current!==d){if(_.current=d,z.current){P.current!=="clear"&&(P.current="rotate"),ne();return}P.current=null,O.current=t.createAssistantConversationId()}},[d,ne]),y.useEffect(()=>{E&&C&&(be({role:"user",parts:[{type:"text",text:C}]}),N(!1))},[E,C,be,N]);async function X({toolCall:$}){var oe,je,ee,H,le,de,Ce,ve,Fe,Be,Xe,Ye,We,re,Ie,Pe;if(["createChartFromSql","createForecast"].includes($.toolName)){const ye=((oe=$.input)==null?void 0:oe.sql)??((je=$.args)==null?void 0:je.sql),Ge=((ee=$.input)==null?void 0:ee.python)??((H=$.args)==null?void 0:H.python),we=((le=$.input)==null?void 0:le.chartType)??((de=$.args)==null?void 0:de.chartType);g(we),h(ye),x(Ge),m(!0),se({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if($.toolName==="getUserSql"){if(!o){se({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",message:"No SQL found"}});return}se({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",sql:o,python:p||""}})}else if($.toolName==="generateQueryConfig"){a("Generating query config...");const ye=((Ce=$.input)==null?void 0:Ce.chartType)??((ve=$.args)==null?void 0:ve.chartType),Ge=((Fe=$.input)==null?void 0:Fe.queryConfig)??((Be=$.args)==null?void 0:Be.queryConfig);((Xe=$.input)==null?void 0:Xe.cardConfig)??((Ye=$.args)==null||Ye.cardConfig),g(ye),F(Ge),h(void 0),x(void 0);const we=await j();if((We=we==null?void 0:we.data)!=null&&We.error){se({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",queryConfig:Ge,message:(re=we==null?void 0:we.data)==null?void 0:re.error.message}});return}if((Ie=we==null?void 0:we.data)!=null&&Ie.records){se({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:Ge,message:"The data has been visualized"}});return}se({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:Ge,message:"The data has been visualized",records:(Pe=we==null?void 0:we.data)==null?void 0:Pe.records}})}else a("Analyzing...")}function Ne($){const oe=t.removeFromScopeArray(b,$);Se(oe)}function Se($){const oe=t.sanitizeAIScope($);L(oe),K(je=>[...je,{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 Oe(){const $={databaseName:S||"",schemaName:D||"",tableName:M||"",datamodelId:T||"",datamodelName:t.resolveDatamodelName(f),connectionId:w||"",connectionType:A||""},oe=t.dedup([...b,$]);Se(oe)}function Ve(){const $={databaseName:S||"",schemaName:D||"",tableName:M||"",datamodelName:t.resolveDatamodelName(f),connectionId:w||"",connectionType:A||"",datamodelId:T||""};if(!t.isInAiScopeArray([...I||[],...b],$)||b.length===0){const je=t.dedup([...I||[],...b,$]).filter(ee=>ee.connectionId===$.connectionId);Se(je)}}const Ae=!["ready","error"].includes(fe),Te=t.getErrorMessage(ae);return{messages:W,setMessages:te,sendMessage:be,regenerate:ge,isLoading:Ae,handleSetAIScope:Ve,handleAddCurrentTableToScope:Oe,removeFromCurrentSelections:Ne,currentAssitantScope:b,setCurrentAssitantScope:L,stop:ne,status:fe,toolStatus:n,llmUsage:r,onFinish:s,errorMessage:Te,clearError:me}}const xo=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Ca({isFullscreen:s,onFullscreenChange:n,fullscreenContainer:a}){const r=y.useRef(null),c=y.useRef(!1),[i,l]=y.useState(!1),[d,o]=y.useState(t.isDevEnv),[u,p]=y.useState(!1),[x,h]=y.useState(!1),[m,g]=y.useState(!1),v=s??m,b=t.useCurrentAIContext(),{setCurrentAIContext:C,setHasEditorEntitySelectionOverride:E}=t.useAIActions(),{clearQueue:B}=t.useQueueActions(),{clearFileAttachments:S}=t.useFileActions(),M=t.useFileAttachments("editor"),{selectedEntities:w}=t.useAssistantContextEntities("editor"),D=t.useEditorStore(re=>re.card.id),I=t.useEditorStore(re=>re.card.dataSource),k=t.useEditorStore(re=>{var Ie;return(Ie=re.card.dataSource)==null?void 0:Ie.selectedEntities}),j=t.useEditorStore(re=>re.actions.setCardSql),R=t.useEditorStore(re=>re.actions.setRunSql),N=t.useEditorStore(re=>re.showAIDialog),L=t.useDashboardStore(re=>re.handleOpenAssistantProfile),{setShowAIDialog:F,setCardPython:f}=t.useEditorActions(),{setDataSource:A}=t.useEditorActions(),{assistantProfile:T}=t.useAssistantProfile(),{messages:V,setMessages:O,sendMessage:P,isLoading:_,stop:z,status:U,llmUsage:W,errorMessage:K,clearError:Z}=mo(),[ae,pe]=y.useState(""),fe=re=>{pe(re.target.value)},se=re=>{re.preventDefault();const Ie=ae.trim();if(!Ie&&M.length===0)return;const Pe=[];Ie&&Pe.push({type:"text",text:Ie}),M.forEach(ye=>{ye.data&&Pe.push({type:"file",mediaType:ye.type,filename:ye.name,url:`data:${ye.type};base64,${ye.data}`})}),P({role:"user",parts:Pe}),pe(""),S("editor"),Ae({force:!0})},{visibleMessages:ne,hasMoreMessages:me,totalMessageCount:be,loadMoreMessages:ge,resetMessageWindow:te}=t.useMessageWindow(V,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:X,contentRef:Ne,isAtBottom:Se,hasNewMessages:Oe,newMessageCount:Ve,scrollToBottom:Ae,handleScroll:Te,resetNewMessageCount:Ee}=t.useAutoScroll(ne,{threshold:40,behavior:"smooth",isStreaming:_});y.useEffect(()=>{var re;N&&!c.current&&((re=r.current)==null||re.focus()),c.current=N},[N]),y.useEffect(()=>{N&&(E(!1),C({selectedEntities:k||[]}))},[D,k,C,E,N]),t.useAutoSubmitQueue({assistantType:"editor",status:U,isLoading:_,sendMessage:P});const{hasActiveTools:$,activeToolText:oe}=t.useActiveToolStatus(V),je=y.useCallback(re=>{n==null||n(re),s===void 0&&g(re)},[s,n]);y.useEffect(()=>{if(!v)return;function re(Ie){Ie.key==="Escape"&&je(!1)}return window.addEventListener("keydown",re),()=>{window.removeEventListener("keydown",re)}},[v,je]);const ee=y.useCallback(re=>{P({role:"user",parts:[{type:"text",text:re}]}),Ae({force:!0})},[P,Ae]),H=y.useCallback(async()=>{const re=JSON.stringify(V??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(re),t.ue.success("Conversation copied")}catch(Ie){console.error("Failed to copy conversation",Ie),t.ue.error("Unable to copy conversation")}},[V]),le=y.useCallback(()=>{je(!v)},[v,je]);function de(re,Ie){Ie==="sql"?(j(re),R(!0)):Ie==="python"&&(f(re),R(!0))}function Ce(){b.selectedEntities.length===0&&C({selectedEntities:w})}function ve(re){Ce();const Ie={role:"user",parts:[{type:"text",text:re.title+" "+re.subtitle}]};P(Ie)}function Fe(re){Ce(),P({role:"user",parts:[{type:"text",text:re}]})}function Be(){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:d,onCheckedChange:o,children:"Tool Invocations"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:u,onCheckedChange:p,children:"System Message"})]})]})}function Xe(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const Ye=(ae==null?void 0:ae.length)===0&&(V==null?void 0:V.filter(re=>re.role==="user").length)===0,We=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:[Xe(),L&&e.jsx(t.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:L,children:(T==null?void 0:T.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[Be(),d&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:H,children:"Copy Conversation"}),e.jsx(t.IconButton,{tooltip:v?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:le,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:()=>{O([]),B("editor"),Z(),te()},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:()=>{F(!1)},children:e.jsx(t.X,{className:"size-4"})})]})]}),e.jsx(t.CustomScrollArea,{ref:X,className:"mt-2 flex min-w-0 w-full grow basis-0",onScroll:Te,children:e.jsxs("div",{ref:Ne,className:"min-w-0 space-y-4 py-2 pr-3","data-role":"messages",children:[me&&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,be-ne.length)," ","more messages (",be-ne.length," ","hidden)"]})}),e.jsx(t.PrintMessages,{messages:ne,showTools:d,handleRun:de,showSystemMessage:u,onQuickReply:ee,disableQuickReplies:_}),e.jsx(t.AssistantStatus,{status:U,errorMessage:K,activeToolText:_&&$?oe:void 0})]})}),N&&!Se&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(t.Button,{onClick:()=>{Ae({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"}),Oe&&Ve>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:Ve>9?"9+":Ve})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[Ye&&!T&&e.jsx(t.Placeholders,{onClick:ve,placeholders:xo}),e.jsx("div",{children:Ye&&T&&e.jsx(t.SeedQuestions,{seedQuestions:T.seedQuestions||[],handleSeedQuestionClick:Fe})})]}),e.jsx(t.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(t.ChatInputWithContext,{ref:r,setInput:pe,stop:z,input:ae,handleInputChange:fe,handleSubmit:re=>{Ce(),se(re),Ae({force:!0})},isLoading:_,status:U,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:w,open:x,onOpenChange:h,dataSource:I||t.EMPTY_DATA_SOURCE,dialogMode:"aiContext",onSaveSelectedEntities:re=>{E(!0),C({...b,selectedEntities:re})}})]});return v&&a?cn.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:We})}),a):We}function ho(s,n,a){if(!n)return!1;const r=n.qualifiedFieldName,c=n.qualifiedEntityName,i=c&&n.name?`${c}.${n.name}`:r;return s.some(l=>{if(!(t.getDataType(l.dataType||"")==="date"))return!1;const o=t.getSelectedDateFilterColumn(l,a),u=o.split("."),p=u[u.length-1]||o,x=u.length>1?u.slice(0,-1).join("."):void 0,h=l.qualifiedTableName||x,m=h?`${h}.${p}`:void 0;return r?m?m===i||m.endsWith(`.${r}`):p===n.name:m?m===i:p===n.name})}function po({aliasTemplate:s,onAliasTemplateChange:n}){var o;const[a,r]=y.useState(s),[c,i]=y.useState(!1),l=(o=t.useEditorStore(u=>{var p;return(p=u.card.config)==null?void 0:p.pivotByColumns}))==null?void 0:o[0],d=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,{placeholder:d,value:c?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"&&c&&a!==s?(n(a),i(!1)):u.key==="Escape"&&(r(s),i(!1))},"aria-label":"Edit alias template"}),c&&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 fo({valueAliases:s,onValueAliasesChange:n}){const[a,r]=y.useState(null),[c,i]=y.useState(""),[l,d]=y.useState(""),o=()=>{n({...s,"":""})},u=x=>{const h={...s};delete h[x],n(h)},p=x=>{const h={...s};delete h[x],h[c]=l,n(h),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,h],m)=>e.jsx("div",{className:"flex items-center gap-2",children:a===x?e.jsxs(e.Fragment,{children:[e.jsx(t.Input,{placeholder:"Value key",value:c,onChange:g=>i(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?p(x):g.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(t.Input,{placeholder:"Alias label",value:l,onChange:g=>d(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?p(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:()=>p(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,{placeholder:"Value key",value:x,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(x),i(x),d(h)},"aria-label":"Edit value alias key"}),e.jsx(t.Input,{placeholder:"Alias label",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(x),i(x),d(h)},"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 go({idx:s}){var d;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),c=(d=n==null?void 0:n.chartOptions)==null?void 0:d.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 p={display:o!=="none",align:o,anchor:o,clamp:!0};if(!i)r({...n,datasetOptions:[...a||[],{idx:u,datalabels:p}]});else{const x={...i};x.datalabels=p;const h=a==null?void 0:a.map(m=>m.idx===u?x:m);r({...n,datasetOptions:h})}}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":c==="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":c==="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":c==="y"})})})]})})]})}function ps({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 jo(s,n=30){return s.length>n?s.slice(0,n)+"...":s}function bo({col:s,idx:n,className:a,iconClassName:r,children:c}){const i=t.useEditorStore(p=>{var x;return(x=p.card)==null?void 0:x.preferences}),l=t.useEditorStore(p=>{var x,h;return(h=(x=p.card)==null?void 0:x.preferences)==null?void 0:h.datasetOptions}),d=l==null?void 0:l.find(p=>p.idx===n),{setCardPreferences:o}=t.useEditorStore(p=>p.actions);function u(p){if(!d)o({...i,datasetOptions:[...l||[],{idx:n,type:p==="area"?"line":p,fill:p==="area"?"origin":""}]});else{const x={...d};x.type=p==="area"?"line":p,x.fill=p==="area"?"origin":"";const h=l==null?void 0:l.map(m=>m.idx===n?x:m);o({...i,datasetOptions:h})}}return e.jsxs("div",{className:t.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[c||e.jsx(ps,{className:"max-w-[100px]",title:s,children:jo(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(go,{idx:n})]})]})}function vo(){const s=t.useEditorStore(d=>d.card.type),n=t.useEditorStore(d=>d.isDevMode),a=t.useEditorStore(d=>d.card.preferences),{setCardPreferences:r}=t.useEditorStore(d=>d.actions);function c(d){var p;const o={datalabels:{display:d!=="none",align:d,anchor:d,clamp:!0}},u={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(p=a==null?void 0:a.chartOptions)==null?void 0:p.plugins,...o}}};r(u)}function i(){var d,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=(d=a==null?void 0:a.chartOptions)==null?void 0:d.plugins)==null?void 0:o.datalabels)==null?void 0:u.anchor)||"none",onValueChange:c,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 d,o,u;return e.jsx("div",{children:e.jsxs(t.Select,{value:((u=(o=(d=a==null?void 0:a.chartOptions)==null?void 0:d.plugins)==null?void 0:o.datalabels)==null?void 0:u.anchor)||"none",onValueChange:c,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 yo({column:s}){const n=t.useEditorStore(o=>o.card.type),a=t.useEditorStore(o=>{var u,p;return(p=(u=o.card)==null?void 0:u.config)==null?void 0:p.metricColumns}),r=(a==null?void 0:a.map(o=>o.label))||[],c=r==null?void 0:r.find(o=>o===s.label||o===s.name),i=c?r.indexOf(c):-1;function l(){return e.jsx("div",{className:"pr-1",children:c&&e.jsx(bo,{idx:i,col:c,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function d(){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(vo,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&l(),["pie","doughnut"].includes(n)&&d()]})}function No({field:s,searchQuery:n="",limit:a=500}){const{authToken:r,tokenProps:c}=t.useSemaphorContext(),i=t.useEditorStore(u=>u.card),l=i==null?void 0:i.dataSource,d=["attribute-values",s.entityName,s.name,n,a],o=t.useQuery({queryKey:d,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},p={connection_id:l.connectionId,cardConfig:u,cardDataSource:l,cache_config:t.getCacheConfig({card:i})};console.log("requestBody",p);const x=await t.postRequestRegular(`${c.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",p);if(x!=null&&x.error)return console.error("Error fetching attribute values:",x.error),[];const h=s.name;return((x==null?void 0:x.records)||[]).map(g=>{const v=g[h]||g[s.alias||h]||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 Ka({open:s,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:c,onSave:i}){var B,S;const l=!!c,[d,o]=y.useState(l?"values":"fields"),[u,p]=y.useState(""),[x,h]=y.useState({id:(c==null?void 0:c.id)||t.v4(),field:(c==null?void 0:c.field)||null,selectedValues:c?Array.isArray(c.value)?c.value:[c.value]:[]}),m=a.filter(M=>{var D;return l?!1:!((D=r==null?void 0:r.conditions)==null?void 0:D.some(I=>I.field.id===M.id))&&M.label.toLowerCase().includes(u.toLowerCase())}),g=M=>{h({...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 w;if(l){const D=((r==null?void 0:r.conditions)||[]).map(I=>I.id===c.id?M:I);w={...r,conditions:D}}else{const D=(r==null?void 0:r.conditions)||[];w={id:(r==null?void 0:r.id)||t.v4(),logicalOperator:"AND",negate:!1,conditions:[...D,M],groups:[]}}i(w),n(!1)}},b=()=>{if(!l||!c)return;const M=((r==null?void 0:r.conditions)||[]).filter(w=>w.id!==c.id);if(M.length>0){const w={...r,conditions:M};i(w)}else i(void 0);n(!1)},C=M=>{h({...x,selectedValues:M})},E=()=>{l&&c?(h({id:c.id,field:c.field,selectedValues:Array.isArray(c.value)?c.value:[c.value]}),o("values")):(h({id:t.v4(),field:null,selectedValues:[]}),o("fields")),p("")};return y.useEffect(()=>{s&&E()},[s,l,c]),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: ${(B=x.field)==null?void 0:B.label}`:d==="fields"?"Select Field to Filter":`Select Values for ${(S=x.field)==null?void 0:S.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!l&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&d==="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))})]}),d==="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,{placeholder:"Search fields...",value:u,onChange:M=>p(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(Co,{field:x.field,selectedValues:x.selectedValues,onValuesChange:C,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:b,children:"Delete Filter"}):e.jsx(t.Button,{variant:"outline",onClick:E,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 Co({field:s,selectedValues:n,onValuesChange:a,onBack:r}){const[c,i]=y.useState(""),{values:l,isLoading:d,isFetching:o}=No({field:s,searchQuery:c,limit:500}),u=c?l.filter(h=>String(h.value).toLowerCase().includes(c.toLowerCase())):l,p=h=>{const m=n.includes(h);a(m?n.filter(g=>g!==h):[...n,h])},x=()=>{n.length===u.length&&u.length>0?a([]):a(u.map(h=>h.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,{placeholder:"Search values...",value:c,onChange:h=>i(h.target.value),className:"pl-10"})]}),d||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(h=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>p(h.value),children:[e.jsx(t.Checkbox,{checked:n.includes(h.value),onCheckedChange:()=>p(h.value)}),e.jsx(ps,{className:"text-sm",children:h.label})]},h.id))})]})]})}function So({field:s,zone:n,index:a,sortDirection:r,onSortDirectionChange:c,hasPivotColumns:i=!1,cardType:l}){var Ns,Cs,Ss,ws,Ts,Es,Is,Ds,ks,As,Ms,Ls,Fs,Rs,Os,Ps,Bs,Vs,zs,_s,qs,$s,Ks,Gs,Us,Hs,Qs,Js,Ys,Ws,Xs,Zs,ea;const{attributes:d,listeners:o,setNodeRef:u,transform:p,transition:x,isDragging:h}=t.useSortable({id:s.id}),m=t.useEditorStore(G=>G.card),g=t.useEditorStore(G=>G.frame),v=t.useDashboardStore(G=>G.isVisualEditing),b=t.useDashboardStore(G=>G.selectedSheetId),C=t.useDashboardStore(G=>G.actions.updateSheetCalculatedFields),{scopedFields:E,valuePickFilterableFields:B,isLoading:S}=t.useFilterableFields(),{userContext:M}=t.useCurrentUserInfo(),w=(M==null?void 0:M.type)==="organization",{updateLabel:D,handleAggregationChange:I,handleDateFormatChange:k,handleGranularityChange:j,handleAliasTemplateChange:R,handleValueAliasesChange:N,handleMetricFormatChange:L,removeField:F,handleMetricComparisonChange:f,handleMetricWindowTransformChange:A,handleMetricWindowOrderByChange:T,handleMetricWindowDirectionChange:V,handleMetricWindowPartitionToggle:O,handleMetricMovingAverageWindowSizeChange:P,handleMetricMovingAverageMinPeriodsChange:_,handleMetricPreviousPeriodDeltaModeChange:z,handleMetricPercentOfTotalScopeChange:U,handleMetricPercentOfTotalOutputChange:W,handleKpiShowTrendlineChange:K,handleKpiTrendlineWindowChange:Z,handleKpiTrendlineGranularityChange:ae,handleMetricTargetValueChange:pe}=t.useFieldManagement(m),[fe,se]=y.useState(!1),[ne,me]=y.useState(()=>{var G;return!!((G=s.parameters)!=null&&G.windowTransform)}),[be,ge]=y.useState(!1),[te,X]=y.useState(!1),[Ne,Se]=y.useState(null),Oe=y.useMemo(()=>{const G=ie=>ie!=null&&ie.startsWith("card-source-")?ie.replace("card-source-",""):ie,J=G(s.id),ue=E.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=G(ie.id);return!!(J&&ke&&J===ke)});return{dataType:(ue==null?void 0:ue.dataType)||s.dataType,resolvedFromScopedField:!!ue}},[s.dataType,s.id,s.name,s.qualifiedEntityName,s.qualifiedFieldName,E]),Ve=t.getGranularityOptionsForFieldType(Oe.dataType),[Ae,Te]=y.useState(s.dateFormat||"YYYY-MM-DD"),[Ee,$]=y.useState(s.customFormat||""),[oe,je]=y.useState(!!s.customFormat),ee=y.useRef(null),[H,le]=y.useState(s.aliasTemplate||""),[de,Ce]=y.useState(s.valueAliases||{}),[ve,Fe]=y.useState((Ns=s.parameters)==null?void 0:Ns.filters),Be=G=>{G==="custom"?je(!0):(je(!1),Te(G),(n==="groupBy"||mt)&&k(a,G,"",n))},Xe=G=>{$(G),(n==="groupBy"||mt)&&k(a,"custom",G,n)},Ye=G=>{var ie;const ue=(ie=t.getDateFormatOptionsForGranularity(G)[0])==null?void 0:ie.value;ue&&!oe&&(Te(ue),n==="groupBy"&&k(a,ue,"",n)),n==="groupBy"&&j(a,G)},We=G=>{le(G),n==="metrics"&&R(a,G)},re=G=>{Ce(G),n==="metrics"&&N(a,G)},Ie=G=>{D(n,a,G)},Pe=t.getExpressionFieldKind(s),ye=t.getFieldExpressionAnnotation(s),Ge=t.isManagedCalculatedExpressionField(s),we=s.role==="metric"&&Ge,bt=Ge&&(Pe==="user_calculated"||Pe==="inline_expression"&&s.fieldScope!=="domain"),Ze=bt?(Cs=g==null?void 0:g.calculatedFields)==null?void 0:Cs.find(G=>t.matchesCalculatedField(G,s,{allowComparableFallback:!0})):void 0,Tt=bt&&(s.fieldScope==="dashboard"||s.fieldScope===void 0&&!!Ze),Ue=Pe==="domain_calculated"||s.fieldScope==="domain",Et=Ue?t.resolveDomainCalculatedFieldForEdit(s,E):void 0,ct=Ue?"domain":Tt?"dashboard":"card",et=Ue?Et||s:Tt&&Ze?Ze:s,It=G=>{var J;if(Fe(G),n==="metrics"){const ue={...s,parameters:{...s.parameters,filters:G}},ie=[...((J=m.config)==null?void 0:J.metricColumns)||[]];ie[a]=ue,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:ie})}ge(!1)},vt=()=>{F(n,a)},Kt={transform:t.CSS.Transform.toString(p),transition:x},Dt=t.getDataType(Oe.dataType||s.dataType),dt=Dt==="date",ut=l==="kpi",mt=n==="detailColumns",xt=(Ss=m.config)==null?void 0:Ss.metricColumns,$e=(ws=m.config)==null?void 0:ws.groupByColumns,Qe=t.useDashboardStore(G=>{var J;return(J=G.dashboard)==null?void 0:J.filters}),Gt=t.useDashboardStore(G=>G.filterValues),tt=s.granularity||"day",kt=Ve.includes(tt)?tt:"day",yt=n==="groupBy"&&!Ve.includes(tt),ht=t.getDateFormatOptionsForGranularity(kt),Ut=oe?"custom":ht.some(G=>G.value===Ae)?Ae:((Ts=ht[0])==null?void 0:Ts.value)??"YYYY-MM-DD";y.useEffect(()=>{var ue;if(S||!yt){ee.current=null;return}const G=`${s.id}:${tt}:${Oe.dataType||s.dataType||""}:${a}`;if(ee.current===G)return;ee.current=G;const J="day";if(j(a,J),!oe){const ie=(ue=t.getDateFormatOptionsForGranularity(J)[0])==null?void 0:ue.value;ie&&(Te(ie),k(a,ie,"",n))}},[s.dataType,s.id,k,j,yt,a,oe,S,tt,Oe.dataType,n]);const Ht=!!l&&t.COMPARISON_SUPPORTED_CHART_TYPES.includes(l),Qt=l==="kpi"||l==="table",Ke=y.useMemo(()=>$e==null?void 0:$e.find(G=>t.getDataType(G.dataType||"")==="date"),[$e]),At=y.useMemo(()=>($e||[]).some(G=>t.getDataType(G.dataType||"")==="date"),[$e]),pt=y.useMemo(()=>{var ie;if(!Ke)return!1;const G=(ie=m.config)==null?void 0:ie.filters;if(!G)return!1;const J=ke=>{const Le=ke.field;return Le?Ke.id&&Le.id===Ke.id||Ke.qualifiedFieldName&&Le.qualifiedFieldName===Ke.qualifiedFieldName?!0:Le.name===Ke.name:!1},ue=ke=>ke.conditions.some(_e=>t.getDataType(_e.field.dataType||"")==="date"&&J(_e))?!0:ke.groups.some(_e=>ue(_e));return ue(G)},[(Es=m.config)==null?void 0:Es.filters,Ke]),Mt=y.useMemo(()=>ho(Qe||[],Ke,Gt),[Qe,Gt,Ke]),Nt=pt||Mt,q=s,Y=((Ds=(Is=q.parameters)==null?void 0:Is.windowTransform)==null?void 0:Ds.function)||"none",Q=t.isMetricTransformEnabled(q),ce=Q?Y:null,xe=t.supportsMetricTransformForMetric({cardType:l||"table",cardConfig:m.config||{},metric:q,transformMode:ce||"running_total"}),he=!!q.comparisonType&&q.comparisonType!=="none",Me=t.getRunningTotalOrderByCandidates($e||[]),Re=((Ms=(As=(ks=q.parameters)==null?void 0:ks.windowTransform)==null?void 0:As.orderBy)==null?void 0:Ms.fieldId)||"",Je=((Rs=(Fs=(Ls=q.parameters)==null?void 0:Ls.windowTransform)==null?void 0:Fs.orderBy)==null?void 0:Rs.direction)||"asc",rt=Me.find(G=>G.id===Re),st=ce==="running_total"||ce==="moving_average"||ce==="previous_period_delta",ze=Q&&st&&!!rt&&t.getDataType(rt.dataType||"")!=="date",ft=t.getDefaultRunningTotalPartitionByFieldIds({cardType:l||"table",cardConfig:m.config||{},orderByFieldId:Re||void 0}),Jt=new Set(((Ps=(Os=q.parameters)==null?void 0:Os.windowTransform)==null?void 0:Ps.partitionByFieldIds)||ft),Yt=l==="pivotTable"||t.isSubtotalEnabledAggregateTable(l||"table",m.config||{}),gs=[...($e||[]).filter(G=>G.id&&(!st||G.id!==Re)),...Yt?(((Bs=m.config)==null?void 0:Bs.pivotByColumns)||[]).filter(G=>G.id):[]],js=((_s=(zs=(Vs=q.parameters)==null?void 0:Vs.windowTransform)==null?void 0:zs.movingAverage)==null?void 0:_s.windowSize)||7,Ua=((Ks=($s=(qs=q.parameters)==null?void 0:qs.windowTransform)==null?void 0:$s.movingAverage)==null?void 0:Ks.minPeriods)||1,Ha=((Hs=(Us=(Gs=q.parameters)==null?void 0:Gs.windowTransform)==null?void 0:Us.previousPeriodDelta)==null?void 0:Hs.mode)||"absolute",bs=((Ys=(Js=(Qs=q.parameters)==null?void 0:Qs.windowTransform)==null?void 0:Js.percentOfTotal)==null?void 0:Ys.scope)||"grand_total",Qa=((Zs=(Xs=(Ws=q.parameters)==null?void 0:Ws.windowTransform)==null?void 0:Xs.percentOfTotal)==null?void 0:Zs.output)||"percent",Ja=y.useMemo(()=>(xt||[]).some(G=>G.comparisonType==="start_vs_end"),[xt]);y.useEffect(()=>{Q&&me(!0)},[Q]);const Ya=n!=="pivotBy"&&n!=="sortBy",Wa=dt&&n==="groupBy"&&(!ut||Ja),Xa=!ut&&dt&&(n==="groupBy"||mt),Za=l==="kpi"&&dt&&n==="groupBy",en=n==="metrics",vs=Ht&&n==="metrics",tn=()=>{const G=s,J=n==="metrics"&&we;return e.jsxs("div",{className:"space-y-1",children:[!J&&e.jsx("div",{title:`${s.entityName}.${s.name}`,onPointerDown:ue=>{ue.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}`}),J&&G.calculatedFormula&&e.jsxs("div",{title:t.formatDisplayFormula(G.calculatedFormula),onPointerDown:ue=>{ue.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(G.calculatedFormula)]})]})},sn=()=>Ya?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(He,{value:s.label??"",onSave:Ie,placeholder:"Display label...",type:"text"})]}):null,an=()=>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:G=>c(G),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"})]})]})]}),ys=()=>Wa?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:kt,onValueChange:Ye,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:Ve.map(G=>e.jsx(t.SelectItem,{className:"text-xs",value:G,children:t.toTitleCase(G)},G))})]})]}):null,nn=()=>Xa?e.jsxs(e.Fragment,{children:[ys(),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:Ut,onValueChange:Be,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:ht.map(G=>e.jsx(t.SelectItem,{className:"text-xs",value:G.value,children:G.label},G.value))})]}),oe&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(t.Input,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:Ee,onChange:G=>{G.stopPropagation(),Xe(G.target.value)},onClick:G=>G.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,rn=()=>{var J,ue,ie,ke;const G=Za;return G?e.jsx(e.Fragment,{children:G&&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.Switch,{size:"sm",checked:((J=m.config)==null?void 0:J.showTrendline)||!1,onCheckedChange:K})]})}),((ue=m.config)==null?void 0:ue.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,{type:"number",min:"1",max:"365",value:((ie=m.config)==null?void 0:ie.trendlineWindow)||30,onChange:Le=>{const _e=parseInt(Le.target.value)||30;Z(_e)},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:ae,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},ln=()=>{if(!en)return null;const G=we;return e.jsxs(e.Fragment,{children:[G&&w&&!Ue&&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:()=>X(!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:J=>{I(a,J)},disabled:G,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(hs,{value:q.format,onChange:J=>L(a,J),showTitle:!1})]}),e.jsx(t.Collapsible,{open:ne,onOpenChange:me,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:Q?t.toTitleCase(Y.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:Q?Y:"none",onValueChange:J=>A(a,J),disabled:!xe.supported&&!Q,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:he,children:"Running Total"}),e.jsx(t.SelectItem,{value:"moving_average",disabled:he,children:"Moving Average"}),e.jsx(t.SelectItem,{value:"previous_period_delta",disabled:he,children:"Previous Period Delta"}),e.jsx(t.SelectItem,{value:"percent_of_total",disabled:he,children:"Percent of Total"})]})]}),!xe.supported&&!Q&&e.jsx("div",{className:"text-xs text-muted-foreground",children:xe.reason}),he&&!Q&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"Disable comparison to enable metric transforms."})]}),Q&&e.jsxs(e.Fragment,{children:[st&&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:Re,onValueChange:J=>T(a,J),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:Me.filter(J=>!!J.id).map(J=>e.jsx(t.SelectItem,{value:J.id,className:"text-xs",children:J.label||J.name},J.id))})]}),!Re&&e.jsx("div",{className:"text-xs text-amber-700",children:"No date trend detected. Select an order field."}),ze&&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:Je,onValueChange:J=>V(a,J),disabled:!Re,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"})]})]})]})]}),ce==="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,{type:"number",min:1,className:"h-8 text-xs",value:js,onChange:J=>P(a,Number(J.target.value))}),e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Min Periods"}),e.jsx(t.Input,{type:"number",min:1,max:js,className:"h-8 text-xs",value:Ua,onChange:J=>_(a,Number(J.target.value))})]}),ce==="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:Ha,onValueChange:J=>z(a,J),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"})]})]})]}),ce==="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:bs,onValueChange:J=>U(a,J),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:Qa,onValueChange:J=>W(a,J),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"})]})]})]})]}),(ce==="running_total"||ce==="moving_average"||ce==="previous_period_delta"||ce==="percent_of_total"&&bs==="partition_total")&&gs.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:gs.map(J=>{const ue=!!J.id&&Jt.has(J.id);return e.jsxs("button",{type:"button",onClick:()=>J.id&&O(a,J.id),className:t.cn("flex h-7 w-full items-center justify-between rounded border px-2 text-xs",ue?"border-primary bg-primary/5 text-primary":"border-border text-muted-foreground"),children:[e.jsx("span",{children:J.label||J.name}),ue?e.jsx(t.Check,{className:"h-3 w-3"}):null]},J.id)})})]})]})]})]})}),vs&&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:q.comparisonType||"none",disabled:Q,onValueChange:J=>f(a,J),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 J=!At||!Nt,ue=At?Nt?void 0:"Add a date filter to enable":"Add a date groupBy to enable",ie=(ke,Le)=>e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.SelectItem,{value:ke,disabled:J,title:ue,children:Le})}),J&&ue&&e.jsx(t.TooltipContent,{side:"right",children:ue})]})});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"})]})]})]}),vs&&q.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,{type:"number",value:q.targetValue!==void 0&&q.targetValue!==null?String(q.targetValue):"",onChange:J=>{const ue=J.target.value;if(ue===""){pe(a,void 0);return}const ie=Number(ue);pe(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"}),(ve==null?void 0:ve.conditions)&&ve.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:ve.conditions.map(J=>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:()=>{Se(J),ge(!0)},children:[e.jsxs("span",{className:"font-medium",children:[J.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(J.value)?J.value.length===1?String(J.value[0]):J.value.length<=2?J.value.join(", "):`${J.value.slice(0,2).join(", ")} +${J.value.length-2}`:String(J.value)})}),Array.isArray(J.value)&&J.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 (",J.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:J.value.map((ue,ie)=>e.jsx("div",{children:String(ue)},ie))})]})})]})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:ue=>{var ke;ue.stopPropagation();const ie=ve.conditions.filter(Le=>Le.id!==J.id);if(ie.length>0){const Le={...ve,conditions:ie};It(Le)}else if(Fe(void 0),n==="metrics"){const Le={...s,parameters:{...s.parameters,filters:void 0}},_e=[...((ke=m.config)==null?void 0:ke.metricColumns)||[]];_e[a]=Le,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:_e})}},children:e.jsx(t.X,{className:"h-3 w-3"})})]},J.id))}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{Se(null),ge(!0)},children:[e.jsx(t.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(yo,{column:s}),i&&e.jsxs(e.Fragment,{children:[e.jsx(po,{aliasTemplate:H,onAliasTemplateChange:We}),e.jsx(fo,{valueAliases:de,onValueAliasesChange:re})]})]})},on=(ve==null?void 0:ve.conditions)&&ve.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:u,style:Kt,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",fe&&"border-border/80 bg-muted/20 shadow-[inset_0_1px_0_rgba(255,255,255,0.35)]",h&&"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",...d,...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:G=>{G.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:Dt}),ye&&e.jsx("span",{className:t.cn(t.FIELD_EXPRESSION_BADGE_BASE_CLASS,ye.badgeClassName),children:ye.label})]}),e.jsx(ps,{className:t.cn("block w-0 min-w-0 flex-1 text-sm text-foreground/95",on&&"min-w-0"),children:t.getMetricDisplayLabel(s)}),n==="metrics"&&((ea=ve==null?void 0:ve.conditions)==null?void 0:ea.length)&&!fe&&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:ve.conditions.length})]})}),e.jsx(t.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:ve.conditions.map(G=>e.jsxs("div",{children:[G.field.label,":"," ",Array.isArray(G.value)?`${G.value.length} values`:String(G.value)]},G.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:G=>{G.stopPropagation(),c(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:G=>{G.stopPropagation(),se(!fe)},children:e.jsx(t.ChevronDown,{className:`h-3 w-3 transition-transform ${fe?"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:G=>{G.stopPropagation(),vt()},children:e.jsx(t.X,{className:"h-2.5 w-2.5"})})]}),fe&&e.jsxs("div",{className:"space-y-3 rounded-md bg-muted/20 p-2.5",children:[tn(),an(),sn(),l==="kpi"&&ys(),nn(),rn(),ln()]})]}),be&&e.jsx(Ka,{open:be,onOpenChange:G=>{ge(G),G||Se(null)},availableFields:B,existingFilters:ve,editingCondition:Ne,onSave:G=>{var J;if(G)It(G);else if(Fe(void 0),n==="metrics"){const ue={...s,parameters:{...s.parameters,filters:void 0}},ie=[...((J=m.config)==null?void 0:J.metricColumns)||[]];ie[a]=ue,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:ie})}Se(null)}}),te&&n==="metrics"&&we&&e.jsx(t.CalculatedFieldEditor,{open:te,onOpenChange:X,availableFields:E,existingField:et,existingFieldScope:ct,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:G=>{var Ft;if(G.role!=="metric")return;const{card:J,frame:ue,actions:ie}=t.useEditorStore.getState(),ke=((Ft=J.config)==null?void 0:Ft.metricColumns)||[],Le=ue.calculatedFields||[],{nextActiveFields:_e,nextStoredFields:Ct,nextSharedFields:Lt}=t.saveCalculatedFieldToCardScope({activeFields:ke,storedFields:J.calculatedFields||[],sharedFields:Le,updatedField:G,editingField:et,previousScope:ct});_e&&ie.updateCardConfig(m.id,{metricColumns:_e}),ie.updateCard(m.id,{calculatedFields:Ct}),Lt!==Le&&t.commitSharedCalculatedFields({nextSharedFields:Lt,currentSharedFields:Le,isVisualEditing:v,selectedSheetId:b,updateFrame:ie.updateFrame,updateSheetCalculatedFields:C})},onSaveToDashboard:G=>{var ta;if(G.role!=="metric")return;const{card:J,frame:ue,actions:ie}=t.useEditorStore.getState(),ke=s,Le=((ta=J.config)==null?void 0:ta.metricColumns)||[],_e=ue.calculatedFields||[],{nextActiveFields:Ct,nextStoredFields:Lt,nextSharedFields:Ft}=t.saveCalculatedFieldToSharedScope({activeFields:Le,storedFields:J.calculatedFields||[],sharedFields:_e,updatedField:{...G,id:ke.id,aliasTemplate:ke.aliasTemplate,valueAliases:ke.valueAliases,parameters:ke.parameters,customFormat:ke.customFormat},editingField:et,previousScope:ct});t.commitSharedCalculatedFields({nextSharedFields:Ft,currentSharedFields:_e,isVisualEditing:v,selectedSheetId:b,updateFrame:ie.updateFrame,updateSheetCalculatedFields:C}),Ct&&ie.updateCardConfig(m.id,{metricColumns:Ct}),ie.updateCard(m.id,{calculatedFields:Lt})},cardId:m.id})]})}function wo({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 To={groupBy:zt,pivotBy:cs,metrics:En,detailColumns:t.Table2,sortBy:t.ArrowUpDown};function wt({zone:s,fields:n,label:a,placeholder:r,shouldShow:c,hasPivotColumns:i=!1,activeField:l=null}){const{isOver:d,setNodeRef:o}=t.useDroppable({id:s}),{updateSortByColumn:u}=t.useEditorActions(),p=t.useEditorStore(C=>C.card),x=t.useEditorStore(C=>C.card.type),h=n.length>0,m=y.useMemo(()=>!l||!d?!0:t.validateFieldForChartType(l,s,x).isValid,[l,d,s,x]),g=(C,E)=>{var S;!((S=p.config)!=null&&S.sortByColumns)||p.config.sortByColumns.findIndex(M=>M.id===C)===-1||u(p.id,C,{direction:E})};if(s==="sortBy"&&c===!1)return null;const v=s!=="sortBy"&&x!=="kpi",b=To[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":d&&m,"border-red-500 bg-red-50 shadow-[0_0_0_1px_rgba(239,68,68,0.18)] dark:bg-red-950":d&&!m,"border-solid border-border/55 bg-background":!d&&h,"min-h-[56px] border-dashed border-border/60 bg-background":!d&&!h}),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(b,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground/80"}),e.jsx("span",{children:r}),v&&e.jsx(wo,{concept:s})]}):e.jsx(t.SortableContext,{id:s,items:n.map(C=>C.id),strategy:t.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map((C,E)=>{const S=C.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(So,{field:C,zone:s,index:E,sortDirection:S,onSortDirectionChange:M=>g(C.id,M),hasPivotColumns:i,cardType:x})})},C.id)})})})})]})}function Eo({groupByFields:s,pivotByFields:n,metricsFields:a,sortByFields:r,detailFields:c,activeField:i}){var z,U,W;const[l,d]=y.useState(!1),o=t.useEditorStore(K=>{var Z;return!!((Z=K.card.customCardPreferences)!=null&&Z.url)}),u=t.useEditorStore(K=>K.card),p=t.useEditorStore(K=>K.frame),x=t.findCustomVisualConfigCard(p,u),{manifest:h}=t.useCustomVisual(((z=x==null?void 0:x.customCardPreferences)==null?void 0:z.url)||""),m=(U=h==null?void 0:h.visuals)==null?void 0:U.find(K=>{var Z;return K.name===((Z=x==null?void 0:x.customCardPreferences)==null?void 0:Z.componentName)}),g=t.resolveMultiInputType(x,m)==="multiple",v=g&&!!((W=x==null?void 0:x.customCardPreferences)!=null&&W.url),b=t.getConfigSlotExpectedType(m==null?void 0:m.slots);t.useEditorStore(K=>K.actions.updateCardConfig);const C=t.useEditorStore(K=>K.actions.updateCard),E=t.useEditorStore(K=>K.actions.updateFrame),B=t.useDashboardStore(K=>K.isVisualEditing),S=t.useDashboardStore(K=>K.selectedSheetId),M=t.useDashboardStore(K=>K.actions.updateSheetCalculatedFields),{scopedFields:w}=t.useScopedFields(),{userContext:D}=t.useCurrentUserInfo(),I=g&&(x==null?void 0:x.id)===u.id&&b?b:u==null?void 0:u.type,k=I==="detailTable",j=s.length>0||a.length>0||c.length>0,R=!k&&(I!=="kpi"||a.length<=2),N=!k,L=!k&&I!=="kpi",F=I!=="kpi"&&j,f=k,A="Drop sort fields here",T=(D==null?void 0:D.type)==="organization",V=["pie","doughnut","polar","funnel","aggregateTable","bubble","scatter"].includes(I),O=L&&!V,P=()=>I==="kpi"?{label:"Trend By",placeholder:"Drop trend field here"}:{label:"Rows",placeholder:"Drop dimensions here"},_=()=>I==="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:[R&&e.jsx(wt,{zone:"groupBy",fields:s,label:P().label,placeholder:P().placeholder,activeField:i}),O&&e.jsx(wt,{zone:"pivotBy",fields:n,label:"Pivot Columns",placeholder:"Drop pivot fields here",activeField:i}),N&&e.jsx(wt,{zone:"metrics",fields:a,label:_().label,placeholder:_().placeholder,hasPivotColumns:n.length>0,activeField:i}),f&&e.jsx(wt,{zone:"detailColumns",fields:c,label:"Columns",placeholder:"Drop columns here"}),a.length>=1&&T&&e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:()=>d(!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"]}),F&&e.jsx(wt,{zone:"sortBy",fields:r,label:"Sort By",placeholder:A,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($a,{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(Ta,{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(Va,{})})]})]}),e.jsx(t.CalculatedFieldEditor,{open:l,onOpenChange:d,availableFields:w,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:K=>{if(K.role!=="metric")return;const{nextStoredFields:Z}=t.saveCalculatedFieldToCardScope({activeFields:a,storedFields:u.calculatedFields||[],sharedFields:p.calculatedFields||[],updatedField:K,previousScope:"card"});C(u.id,{calculatedFields:Z})},onSaveToDashboard:K=>{if(K.role!=="metric")return;const Z=p.calculatedFields||[],{nextSharedFields:ae}=t.saveCalculatedFieldToSharedScope({activeFields:a,storedFields:u.calculatedFields||[],sharedFields:Z,updatedField:K,previousScope:"dashboard"});t.commitSharedCalculatedFields({nextSharedFields:ae,currentSharedFields:Z,isVisualEditing:B,selectedSheetId:S,updateFrame:E,updateSheetCalculatedFields:M})},cardId:u.id})]})}function Io({onEditJoins:s}){const n=t.useEditorStore(d=>d.card),{autoJoinMetadata:a}=t.useDashboardCardQuery(n);if(!(a!=null&&a.autoResolved))return null;const{resolvedJoinPlan:r}=a,c=(r==null?void 0:r.joins)||[];if(c.length===0)return null;const i=d=>!d||d.length===0?"No conditions":d.map(o=>{var h,m,g,v;const u=`${(h=o.source)==null?void 0:h.entityName}.${(m=o.source)==null?void 0:m.name}`,p=`${(g=o.target)==null?void 0:g.entityName}.${(v=o.target)==null?void 0:v.name}`,x=o.operator||"=";return`${u} ${x} ${p}`}).join(" AND "),l=d=>!d.joinKeyGroups||d.joinKeyGroups.length===0?"No conditions defined":d.joinKeyGroups.length===1?i(d.joinKeyGroups[0].keys):d.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:c.length})}),e.jsx(t.TooltipContent,{side:"bottom",align:"start",className:"max-w-md p-3",children:e.jsx("div",{className:"space-y-2",children:c.map((d,o)=>{const u=l(d),p=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:d.source.name}),e.jsx(t.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:d.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:d.joinType})]}),e.jsx("div",{className:"mt-1 space-y-1",children:p?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})})})]},d.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 Sa={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 Do({selectedChart:s,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:c,sortByFields:i,detailFields:l,activeField:d}){var k,j;const[o,u]=y.useState(()=>Sa.getItem("chart-selector-expanded")==="true"),[p,x]=y.useState(!1),h=t.useEditorStore(R=>R.card),m=t.useEditorStore(R=>R.actions.updateCardConfig),g=a.length>0||r.length>0||c.length>0||l.length>0,{data:v,autoJoinMetadata:b}=t.useDashboardCardQuery(h),C=g||!!v,E=((k=h==null?void 0:h.config)==null?void 0:k.joinPlan)||(b!=null&&b.autoResolved?b.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),B=((j=h==null?void 0:h.dataSource)==null?void 0:j.selectedEntities)||[],S=R=>{m(h.id,{...h==null?void 0:h.config,joinPlan:R}),x(!1)},M=()=>{m(h.id,{...h==null?void 0:h.config,joinPlan:void 0}),x(!1)},w=()=>{x(!1)},D=()=>{x(!0)};y.useEffect(()=>{Sa.setItem("chart-selector-expanded",String(o))},[o]);const I=()=>{u(R=>!R)};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(us,{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:I})})]})}),C&&e.jsx("div",{className:"pl-2 pr-4 py-3",children:e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(De.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",C?"pt-1":"pt-4"),children:[e.jsx(Io,{onEditJoins:D}),e.jsx(Eo,{groupByFields:a,pivotByFields:r,metricsFields:c,sortByFields:i,detailFields:l,activeField:d})]})}),e.jsx(ka,{open:p,onOpenChange:x,joinPlan:E,availableDataSources:B,onSave:S,onCancel:w,onRemove:M,children:e.jsx("div",{})})]})}function ko({initialFilters:s,availableFields:n}={}){const[a,r]=y.useState(s||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});t.useEditorStore(S=>S.card.dataSource);const{filterableFields:c,isLoading:i}=t.useFilterableFields(),l=n||c||[],d={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},o=S=>{const M=w=>{if(w.id===S){const D=l[0]||d,I=t.getDataType(D.dataType)==="date";return{...w,conditions:[...w.conditions,{id:`condition-${Date.now()}`,field:D,operator:I?"between":"=",value:I?[]:""}]}}return{...w,groups:w.groups.map(M)}};r(M(a))},u=S=>{const M=w=>{if(w.id===S){const D=l[0]||d,I=t.getDataType(D.dataType)==="date";return{...w,groups:[...w.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:D,operator:I?"between":"=",value:I?[]:""}],groups:[]}]}}return{...w,groups:w.groups.map(M)}};r(M(a))},p=(S,M)=>{const w=D=>D.id===S?{...D,conditions:D.conditions.filter(I=>I.id!==M)}:{...D,groups:D.groups.map(w)};r(w(a))},x=(S,M)=>{const w=D=>D.id===S?{...D,groups:D.groups.filter(I=>I.id!==M)}:{...D,groups:D.groups.map(w)};r(w(a))},h=(S,M,w,D)=>{if(w==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const I=k=>k.id===S?{...k,conditions:k.conditions.map(j=>j.id===M?{...j,[w]:D}:j)}:{...k,groups:k.groups.map(I)};r(I(a))},m=(S,M,w)=>{const D=I=>I.id===S?{...I,conditions:I.conditions.map(k=>k.id===M?{...k,...w}:k)}:{...I,groups:I.groups.map(D)};r(D(a))},g=(S,M)=>{const w=D=>D.id===S?{...D,logicalOperator:M}:{...D,groups:D.groups.map(w)};r(w(a))},v=(S,M)=>{const w=D=>D.id===S?{...D,negate:M}:{...D,groups:D.groups.map(w)};r(w(a))},b=(S,M,w)=>{const D=I=>I.id===S?{...I,conditions:t.arrayMove(I.conditions,M,w)}:{...I,groups:I.groups.map(D)};r(D(a))},C=(S,M,w)=>{const D=I=>I.id===S?{...I,groups:t.arrayMove(I.groups,M,w)}:{...I,groups:I.groups.map(D)};r(D(a))},E=S=>{if(!S||S.conditions.length===0&&S.groups.length===0)return"-- No filters defined";const M=D=>{let I="";typeof D.field=="object"?I=D.field.entityName?`${D.field.entityName}.${D.field.name}`:D.field.name:I=String(D.field);const k=D.operator;let j=D.value;if(D.field.dataType==="string"&&!["in","not in"].includes(D.operator))typeof j=="string"?j=`'${j}'`:Array.isArray(j)&&(j=`'${j.join(", ")}'`);else if(D.field.dataType==="date"||D.field.dataType==="datetime"||D.field.dataType==="timestamp")if(D.operator==="between"&&Array.isArray(j)&&j.length===2){const R=j[0]?`'${j[0]}'`:"NULL",N=j[1]?`'${j[1]}'`:"NULL";return`${I} BETWEEN ${R} AND ${N}`}else if((D.operator==="in"||D.operator==="not in")&&Array.isArray(j)){const R=j.map(N=>N?`'${N}'`:"NULL").join(", ");return`${I} ${k} (${R})`}else typeof j=="string"||j instanceof Date?j=`'${j}'`:Array.isArray(j)&&j.length>0&&(j=`'${j[0]}'`);else if(["in","not in"].includes(D.operator)){let R=[];Array.isArray(j)?R=j.map(N=>typeof N=="string"?`'${N}'`:String(N)):typeof j=="string"?R=j.split(",").map(N=>{const L=N.trim();return D.field.dataType==="string"?`'${L}'`:L}):typeof j=="number"&&(R=[String(j)]),j=`(${R.join(", ")})`}switch(k){case"contains":return typeof j=="string"?`${I} LIKE '%${j.replace(/'/g,"")}'`:`${I} LIKE '%${String(j)}'`;case"startsWith":return typeof j=="string"?`${I} LIKE '${j.replace(/'/g,"")}%'`:`${I} LIKE '${String(j)}%'`;case"endsWith":return typeof j=="string"?`${I} LIKE '%${j.replace(/'/g,"")}'`:`${I} LIKE '%${String(j)}'`;case"isNull":return`${I} IS NULL`;case"isNotNull":return`${I} IS NOT NULL`;default:return`${I} ${k} ${j}`}},w=D=>{const I=D.conditions.map(M),k=D.groups.map(L=>w(L)),j=[...I,...k].filter(Boolean);if(j.length===0)return"";const R=j.join(` ${D.logicalOperator} `),N=j.length>1?`(${R})`:R;return D.negate?`NOT ${N}`:N};return w(S)},B=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:l,isLoading:i,addCondition:o,addGroup:u,removeCondition:p,removeGroup:x,updateCondition:h,updateConditionFields:m,updateGroupOperator:g,updateGroupNegate:v,reorderConditions:b,reorderGroups:C,generateSQLPreview:E,hasAnyFilters:B}}function Ao({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.TooltipContent,{children:s})]})})}const Mo=s=>{if(s.qualifiedEntityName){const n=s.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function Lo({value:s,onValueChange:n,availableFields:a,placeholder:r="Select field",className:c="w-64"}){const[i,l]=y.useState(!1),d=y.useMemo(()=>{const o={};return a.forEach(u=>{const p=Mo(u);o[p]||(o[p]={}),o[p][u.entityId]||(o[p][u.entityId]=[]),o[p][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",c),children:[s?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Ao,{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(d).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(([p,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((h,m)=>e.jsxs(t.CommandItem,{value:h.id,onSelect:()=>{n(h),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)===h.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:h.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:h.description&&e.jsx("span",{children:h.description})})]})]},h.id+m))]},`${o}-${p}`))},o))})]})})]})}function fs(s){var v;const n=t.useEditorStore(b=>b.card),{authToken:a,tokenProps:r}=t.useSemaphorContext(),c=t.useEditorStore(b=>b.card.config),i=c==null?void 0:c.joinPlan,l={...s,alias:s.name,label:"value",role:"groupby"},d={...s,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},o={...l,role:"sortby",direction:"asc"},u={joinPlan:i,groupByColumns:[l],metricColumns:[d],sortByColumns:[o]},p=((v=n.dataSource)==null?void 0:v.connectionId)||n.connectionId,{data:x,isPending:h,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:p,cardConfig:u,cardDataSource:n.dataSource})}catch(b){console.log(s),console.error("error",b)}},enabled:!!p,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((x==null?void 0:x.records)||[]).map(b=>({label:b.value||"BLANK",value:b.value||"BLANK",count:(b==null?void 0:b.count)||0})),isPending:h,error:m}}function Fo({field:s,selected:n,onChange:a,placeholder:r="Select items...",className:c}){const[i,l]=Pt.useState(!1),{filterValues:d}=fs(s),o=p=>{a(n.filter(x=>x!==p))},u=p=>{n.includes(p)?a(n.filter(x=>x!==p)):a([...n,p])};return e.jsx("div",{className:t.cn("w-full",c),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(p=>{const x=d.find(h=>h.value===p);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:h=>{h.key==="Enter"&&o(p)},onMouseDown:h=>{h.preventDefault(),h.stopPropagation()},onClick:h=>{h.stopPropagation(),o(p)},children:e.jsx(t.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},p)}):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:d.map((p,x)=>e.jsxs(t.CommandItem,{onSelect:()=>u(p.value),children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",n.includes(p.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:p.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:p.count})]})]},p.value+x))})]})]})})]})})}function Ro({field:s,value:n,onChange:a,placeholder:r="Select value...",className:c}){const{filterValues:i,isPending:l,error:d}=fs(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..."]}):d?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:c||"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 Oo({value:s,operator:n,onChange:a,className:r}){var m,g,v;const{tokenProps:c}=t.useSemaphorContext(),i=((g=(m=c==null?void 0:c.params)==null?void 0:m.calendarContext)==null?void 0:g.tz)||((v=c==null?void 0:c.params)==null?void 0:v.timezone),l=i||Intl.DateTimeFormat().resolvedOptions().timeZone,d=n==="between"||n==="not between",o=y.useMemo(()=>{if(!(!s||!d)&&Array.isArray(s)&&s.length===2){const b=s[0]?new Date(s[0]):void 0,C=s[1]?new Date(s[1]):void 0;if(b&&C)return{from:b,to:C}}},[s,d]),u=y.useMemo(()=>{if(!s||d)return;const b=Array.isArray(s)?s[0]:s;if(!b)return;const C=new Date(b);if(!isNaN(C.getTime()))return C},[s,d]),p=b=>n==="<="||n===">"?t.endOfDayInTimezone(b,l):t.startOfDayInTimezone(b,l),x=b=>{if(!b){a([]);return}if(b.from&&b.to){a([b.from.toISOString(),b.to.toISOString()]);return}a([])},h=b=>{if(!b){a("");return}const C=p(b);a(C.toISOString())};return e.jsx(t.DateRangePicker,{value:d?o:void 0,selectionMode:d?"range":"single",singleValue:d?void 0:u,onChange:x,onSingleChange:h,timezone:i,showRelativeTab:d,className:r,placeholder:"Select date..."})}const Po=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Bo=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Vo=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],zo=["=","!=","isNull","isNotNull"],_o=["between","=","!=","<","<=",">",">=","isNull","isNotNull"],qo={"=":"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 wa(s){return qo[s]||t.titleCase(s)}function $o(s){switch(s){case"string":return Bo;case"number":return Vo;case"boolean":return zo;case"date":return _o;default:return Po}}function Ga({condition:s,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:c,onRemoveCondition:i,onUpdateGroupOperator:l,availableFields:d,updateConditionFields:o}){const{attributes:u,listeners:p,setNodeRef:x,transform:h,transition:m,isDragging:g}=t.useSortable({id:s.id}),{isPending:v,error:b}=fs(s.field),C={transform:t.CSS.Transform.toString(h),transition:m};return e.jsxs("div",{ref:x,style:C,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,...p,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:E=>l(a,E),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(Lo,{value:s.field,onValueChange:E=>{const B=E,S=t.getDataType(B.dataType)==="date";o(a,s.id,{field:B,value:"",operator:S?"between":"="})},availableFields:d,placeholder:"Select field",className:"w-64"}),e.jsxs(t.Select,{value:s.operator,onValueChange:E=>{E==="in"||E==="not in"?o(a,s.id,{operator:E,value:[]}):E==="isNull"||E==="isNotNull"?o(a,s.id,{operator:E,value:null}):E==="between"||E==="not between"?o(a,s.id,{operator:E,value:[]}):o(a,s.id,{operator:E,value:""})},children:[e.jsx(t.SelectTrigger,{className:"w-32",children:e.jsx(t.SelectValue,{children:s.operator?wa(s.operator):""})}),e.jsx(t.SelectContent,{children:$o(t.getDataType(s.field.dataType)).map(E=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:E,children:wa(E)},E))})]}),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..."]}):b?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(Fo,{field:s.field,selected:Array.isArray(s.value)&&s.value.every(E=>typeof E=="string")?s.value:[],onChange:E=>o(a,s.id,{value:E}),placeholder:`Select values for ${s.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(s.operator)?e.jsx(t.Input,{value:typeof s.value=="string"?s.value:"",onChange:E=>o(a,s.id,{value:E.target.value}),className:"flex-1",placeholder:s.operator.charAt(0).toUpperCase()+s.operator.slice(1)+"..."}):e.jsx(Ro,{field:s.field,value:typeof s.value=="string"?s.value:"",onChange:E=>o(a,s.id,{value:E}),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:E=>o(a,s.id,{value:E==="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(Oo,{value:s.value,operator:s.operator,onChange:E=>o(a,s.id,{value:E}),className:"flex-1"}):e.jsx(t.Input,{value:typeof s.value=="string"||typeof s.value=="number"?s.value:"",onChange:E=>c(a,s.id,"value",E.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 Ko({group:s,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:c,onRemoveGroup:i,onUpdateCondition:l,onUpdateField:d,onRemoveCondition:o,onReorderConditions:u,onReorderGroups:p,onAddCondition:x,onAddGroup:h,availableFields:m,renderFilterGroup:g,updateConditionFields:v}){const{attributes:b,listeners:C,setNodeRef:E,transform:B,transition:S,isDragging:M}=t.useSortable({id:s.id}),w={transform:t.CSS.Transform.toString(B),transition:S},D=k=>{const{active:j,over:R}=k;if(R&&j.id!==R.id){const N=s.conditions.findIndex(F=>F.id===j.id),L=s.conditions.findIndex(F=>F.id===R.id);N!==-1&&L!==-1&&u(s.id,N,L)}},I=k=>{const{active:j,over:R}=k;if(R&&j.id!==R.id&&a){const N=s.groups.findIndex(F=>F.id===j.id),L=s.groups.findIndex(F=>F.id===R.id);N!==-1&&L!==-1&&p(a,N,L)}};return e.jsxs("div",{ref:E,style:w,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",{...b,...C,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:()=>c(s.id,!s.negate),children:"NOT"}),e.jsxs(t.Select,{value:s.logicalOperator,onValueChange:k=>r(s.id,k),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:D,children:e.jsx(t.SortableContext,{items:s.conditions.map(k=>k.id),strategy:t.verticalListSortingStrategy,children:s.conditions.map((k,j)=>e.jsx(Ga,{condition:k,index:j,groupId:s.id,groupLogicalOperator:s.logicalOperator,onUpdateCondition:l,onUpdateField:d,onRemoveCondition:o,onUpdateGroupOperator:r,availableFields:m,updateConditionFields:v},k.id))})}),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.groups.map(k=>k.id),strategy:t.verticalListSortingStrategy,children:s.groups.map(k=>g(k,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:()=>h(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Go({filters:s,availableFields:n,onSave:a,onClearAll:r,onCancel:c}){const{currentFilters:i,availableFields:l,isLoading:d,addCondition:o,addGroup:u,removeCondition:p,removeGroup:x,updateCondition:h,updateConditionFields:m,updateGroupOperator:g,updateGroupNegate:v,reorderConditions:b,reorderGroups:C,generateSQLPreview:E,hasAnyFilters:B,setCurrentFilters:S}=ko({initialFilters:s,availableFields:n}),M=t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),[w,D]=y.useState(!1),I=(R,N,L)=>{const F=f=>f.id===R?{...f,conditions:f.conditions.map(A=>A.id===N?{...A,field:L,dataType:L.dataType}:A)}:{...f,groups:f.groups.map(F)};S(F(i))},k=(R,N=0,L)=>N===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:F=>{const{active:f,over:A}=F;if(A&&f.id!==A.id){const T=R.conditions.findIndex(O=>O.id===f.id),V=R.conditions.findIndex(O=>O.id===A.id);T!==-1&&V!==-1&&b(R.id,T,V)}},children:e.jsx(t.SortableContext,{items:R.conditions.map(F=>F.id),strategy:t.verticalListSortingStrategy,children:R.conditions.map((F,f)=>e.jsx(Ga,{condition:F,index:f,groupId:R.id,groupLogicalOperator:R.logicalOperator,onUpdateCondition:h,onUpdateField:I,onRemoveCondition:p,onUpdateGroupOperator:g,availableFields:l,updateConditionFields:m},F.id))})}),e.jsx(t.DndContext,{sensors:M,collisionDetection:t.closestCenter,onDragEnd:F=>{const{active:f,over:A}=F;if(A&&f.id!==A.id){const T=R.groups.findIndex(O=>O.id===f.id),V=R.groups.findIndex(O=>O.id===A.id);T!==-1&&V!==-1&&C(R.id,T,V)}},children:e.jsx(t.SortableContext,{items:R.groups.map(F=>F.id),strategy:t.verticalListSortingStrategy,children:R.groups.map(F=>k(F,N+1,R.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(R.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),w&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(R.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},R.id):e.jsx(Ko,{group:R,depth:N,parentGroupId:L,onUpdateGroupOperator:g,onUpdateGroupNegate:v,onRemoveGroup:x,onUpdateCondition:h,onUpdateField:I,onRemoveCondition:p,onReorderConditions:b,onReorderGroups:C,onAddCondition:o,onAddGroup:u,availableFields:l,renderFilterGroup:k,updateConditionFields:m},R.id),j=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:[d?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):k(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.Switch,{size:"sm",id:"advanced-mode",checked:w,onCheckedChange:R=>D(R)}),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)"})]})}),B&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:E(i)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(t.Button,{size:"sm",variant:"outline",onClick:c,children:"Cancel"}),j>0&&e.jsx(t.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(t.Button,{size:"sm",onClick:()=>a(B?i:null),children:"Apply Filters"})]})]})}function Uo({cardId:s,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:c,isOpen:i,onOpenChange:l}){const d=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(Go,{filters:n,availableFields:c,onSave:d,onCancel:()=>l(!1),onClearAll:o})]})]})}function Ho({activeCardId:s,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var E,B;const[c,i]=y.useState(null),l=t.useEditorStore(S=>S.card),d=t.useEditorStore(S=>S.actions.updateCardConfig),o=t.useEditorStore(S=>S.actions.setCardPreferences),u=(E=l==null?void 0:l.config)==null?void 0:E.joinPlan,p=y.useCallback(S=>S.entityName===t.CALCULATED_FIELD_ENTITY_MARKER||S.entityName==="calculated_fields"||S.qualifiedEntityName==="calculated_fields",[]),x=(B=l==null?void 0:l.dataSource)==null?void 0:B.semanticDomainId,{data:h}=t.useJoinabilityMap(x),m=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy"),...a("detailColumns")],g=y.useCallback(S=>S.startsWith("card-source-")?"source":S.startsWith("card-")?null:S.startsWith("source-")||n.find(M=>M.id===S)?"source":a("groupBy").find(M=>M.id===S)?"groupBy":a("metrics").find(M=>M.id===S)?"metrics":a("pivotBy").find(M=>M.id===S)?"pivotBy":a("sortBy").find(M=>M.id===S)?"sortBy":a("detailColumns").find(M=>M.id===S)?"detailColumns":null,[n,a]),v=y.useCallback(S=>{i(S.active.id)},[]),b=y.useCallback(S=>{var R;const{active:M,over:w}=S;if(!w||!s){i(null);return}const D=M.id,I=w.id,k=g(D),j=g(I)||I;if(j==="sortBy"){if(k==="source"){const N=n.find(F=>F.id===D);if(!N){i(null);return}if(!(a("groupBy").some(F=>F.name===N.name&&F.qualifiedEntityName===N.qualifiedEntityName)||a("metrics").some(F=>F.name===N.name&&F.qualifiedEntityName===N.qualifiedEntityName)||a("detailColumns").some(F=>F.name===N.name&&F.qualifiedEntityName===N.qualifiedEntityName))){i(null);return}}else if(k==="pivotBy"){i(null);return}else if(k!=="groupBy"&&k!=="metrics"&&k!=="sortBy"&&k!=="detailColumns"){i(null);return}}if(k==="source"&&j==="sortBy"){const N=[...n].find(A=>A.id===D);if(!N){i(null);return}const L=a("sortBy");if(t.fieldAlreadyExists(N,L)){i(null);return}const F=t.validateFieldForChartType(N,"sortBy",l.type);if(!F.isValid){t.ue.error("Invalid Field Type",{description:F.reason,position:"top-center",duration:3e3}),i(null);return}const f=t.getNewField(N,"sortBy",L);i(null),r("sortBy",[...L,f]);return}if(k==="source"&&j!=="source"&&j!=="sortBy"){const N=[...n].find(O=>O.id===D);if(!N){i(null);return}const L=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy"),...a("detailColumns")],F=L.filter(O=>!p(O));if(F.length>0){const O=F[0].qualifiedEntityName;if(!O){i(null);return}if(O!==N.qualifiedEntityName&&!p(N)&&N.qualifiedEntityName)if(x&&(h!=null&&h.joinabilityMap)){if(t.calculateFieldState(N,{joinabilityMap:h.joinabilityMap,selectedFields:L,baseEntityName:(R=u==null?void 0:u.baseEntity)==null?void 0:R.name}).state==="unreachable"){t.showJoinRequiredNotification(),i(null);return}}else{if(!u){t.showJoinRequiredNotification(),i(null);return}if(!t.areEntitiesJoined(O,N.qualifiedEntityName,u)){t.showJoinRequiredNotification(),i(null);return}}}const f=a(j);if(t.fieldAlreadyExists(N,f)){i(null);return}const A=t.validateFieldForChartType(N,j,l.type);if(!A.isValid){t.ue.error("Invalid Field Type",{description:A.reason,position:"top-center",duration:3e3}),i(null);return}const T=t.getNewField(N,j,f),V=[...f,T];if(i(null),r(j,V),j==="metrics"&&s){const O=t.seedSemanticMetricFormatDefaults(l,T,l.preferences);O&&o(O),t.cleanupKpiMetricComparisonMode(l.type,l.config,d,s,V)}return}if(k&&j&&k!=="source"&&j!=="source"&&k!==j){const N=a(k),L=a(j),F=N.find(O=>O.id===D);if(!F){i(null);return}const f=t.validateFieldForChartType(F,j,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(F,j,L);if(i(null),j==="sortBy"){t.fieldAlreadyExists(F,L)||r(j,[...L,A]);return}const T=N.filter(O=>O.id!==D),V=[...L,A];if(r(k,T),r(j,V),j==="metrics"&&s){const O=t.seedSemanticMetricFormatDefaults(l,A,l.preferences);O&&o(O),t.cleanupKpiMetricComparisonMode(l.type,l.config,d,s,V)}return}if(k&&j&&k===j&&k!=="source"){const N=a(k),L=N.findIndex(f=>f.id===D),F=N.findIndex(f=>f.id===I);if(L!==F){const f=t.arrayMove(N,L,F);r(k,f)}}i(null)},[s,n,a,r,g,u,x,h,p,l,d,o]),C=c?m.find(S=>S.id===c):null;return{activeId:c,activeField:C,handleDragStart:v,handleDragEnd:b}}function Qo({activeView:s,onViewChange:n,splitViewEnabled:a}){const r=t.useEditorStore(d=>d.card),{config:c}=y.useContext(t.SemaphorContext).tokenProps,i=(c==null?void 0:c.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:d=>n(d),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 Jo=[{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 Yo(){var o,u;const s=t.useEditorStore(p=>p.card),{updateRowLimit:n}=t.useEditorActions(),[a,r]=y.useState(!1),[c,i]=y.useState(""),l=p=>{if(p==="custom"){r(!0);return}r(!1),n(s.id,parseInt(p))},d=p=>{const x=p.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:c,onChange:d,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:Jo.map(p=>e.jsx(t.SelectItem,{value:p.value,children:p.label},p.value))})]})})}function Wo({card:s,queryData:n,isLoading:a,isFetching:r,pagination:c,onPaginationChange:i,onSortChange:l,sortState:d,splitViewEnabled:o,isDynamicInspectorOpen:u,onDynamicInspectorOpenChange:p}){const x=y.useMemo(()=>(n==null?void 0:n.records)||[],[n==null?void 0:n.records]),h=t.getVisualizationMode(s)==="dynamic",m=e.jsx(ot,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(Pa,{fallbackPreview:e.jsx(ot,{}),records:x,title:s.title,isInspectorOpen:u,onInspectorOpenChange:p})});return h?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:c,onPaginationChange:i,isLoading:a||r,onSortChange:l,sortState:d})]})})]}):m:!o||["table","pivotTable","aggregateTable","detailTable"].includes(s.type)?e.jsx(ot,{}):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(ot,{})}),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:c,onPaginationChange:i,isLoading:a||r,onSortChange:l,sortState:d})]})})]})}const Xo="semaphor-split-view-enabled";function Zo(){return Aa(Xo,!0)}function ei({activeView:s,onViewChange:n,onFiltersClick:a,activeCard:r,columns:c}){var me,be,ge;const i=t.useEditorStore(te=>te.card),l=t.useEditorStore(te=>te.inlineFilterValuesMap[(r==null?void 0:r.id)||""]),d=t.useEditorStore(te=>te.actions.removeCardInlineFilterValue),o=t.useDashboardStore(te=>te.filterValues),u=t.useDashboardStore(te=>te.selectedSheetId),{updateCardConfig:p,setCard:x,updateCardInFrame:h,setShowAIDialog:m}=t.useEditorActions(),g=t.useEditorStore(te=>te.showAIDialog),v=t.useEditorStore(te=>te.isDevMode),b=t.useDashboardStore(te=>te.isVisualEditing),[C,E]=y.useState(!1),[B,S]=y.useState(!1),[M,w]=y.useState(!1),[D,I]=y.useState(null),{config:k}=y.useContext(t.SemaphorContext).tokenProps,j=(k==null?void 0:k.showInfoTab)!==!1,R=(k==null?void 0:k.showQueryDebugTools)!==!1,[N,L]=Zo();t.useEditorStore(te=>{var X;return!!((X=te.card.customCardPreferences)!=null&&X.url)});const f=t.getVisualizationMode(i)==="dynamic",{data:A,errorMessage:T,isLoading:V,isFetching:O,errorSql:P,pagination:_,refetch:z,comparisonMetadata:U,queryRequestPayload:W}=t.useDashboardCardQuery(r),K=y.useMemo(()=>(A==null?void 0:A.records)||[],[A==null?void 0:A.records]),[Z,ae]=y.useState(!1);y.useEffect(()=>{O||ae(!1)},[O]);const pe=()=>{const te=!N;te&&s==="table"&&n("chart"),L(te)},fe=(te,X)=>{const Ne={...r,paginationConfig:{page:te+1,pageSize:X}};x(Ne),h(Ne)},se=te=>{if(!i.config)return;const X=t.sortStateToSortByColumns(te,i.config.metricColumns,i.config.groupByColumns,i.config.detailColumns);p(i.id,{...i.config,sortByColumns:X})},ne=y.useMemo(()=>{var te;return t.sortByColumnsToSortState((te=i.config)==null?void 0:te.sortByColumns)},[(me=i.config)==null?void 0:me.sortByColumns]);return e.jsx("div",{className:t.cn("relative flex w-0 grow flex-col",{"border-l":g&&b}),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(us,{variant:v?"secondary":"ghost"})}),e.jsx(Qo,{activeView:s,onViewChange:n,splitViewEnabled:N}),e.jsx(t.FilterInfo,{cardId:r.id,cardFilters:(be=r.config)==null?void 0:be.filters,cardFilterCount:t.getFilterCount(((ge=r.config)==null?void 0:ge.filters)||null),onFiltersClick:a,inlineFilters:r.inlineFilters,inlineFilterValues:l,sheetId:u||"",removeInlineFilterValue:te=>d(r.id,te)}),U&&i.type!=="table"&&e.jsx(t.ComparisonMetadataBadge,{metadata:U,variant:"compact"}),e.jsx("div",{className:"ml-2",children:e.jsx(Yo,{})}),g&&e.jsx(De.EditorClearButton,{})]}),e.jsxs("div",{className:t.cn("flex grow items-center justify-end gap-2"),children:[e.jsx(t.IconButton,{tooltip:"Refresh",disabled:V||O,onClick:()=>{ae(!0),z()},children:e.jsx(t.RefreshCcw,{className:t.cn("h-4 w-4",{"animate-spin":Z})})}),s==="chart"&&!f&&e.jsx(Oa,{showInlineFilters:!1,showDisplayOptions:!1}),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:pe,children:[N?e.jsx(fn,{className:"mr-2 h-4 w-4"}):e.jsx(kn,{className:"mr-2 h-4 w-4"}),N?"Hide Results Table":"Show Results Table"]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs("div",{className:"px-1 py-1",children:[e.jsx(xs,{triggerVariant:"menu",className:"w-full"}),e.jsx(ms,{triggerVariant:"menu",className:"w-full"})]}),e.jsx(Ba,{onCustomize:()=>w(!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":N&&!["table","pivotTable","aggregateTable","detailTable"].includes(r.type)}),children:e.jsx(Wo,{card:r,queryData:A,isLoading:V,isFetching:O,pagination:_,onPaginationChange:fe,onSortChange:se,sortState:ne,splitViewEnabled:N,isDynamicInspectorOpen:M,onDynamicInspectorOpenChange:w})}),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:[(V||O)&&(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:K,comparisonMetadata:U,paginationMetadata:_,onPaginationChange:fe,isLoading:V||O,onSortChange:se,sortState:ne})]}),s==="info"&&j&&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:T?e.jsx(ds,{error:T,errorSql:P,onSendFeedback:()=>{const te=t.prepareFeedbackData(t.FeedbackCategory.QUERY_GENERATION,{cardConfig:i.config,dataSource:r.dataSource,dashboardFilters:o,errorMessage:T,errorSql:P,generatedSql:A==null?void 0:A.sql});I(te),S(!0)},onOpenInEditor:()=>{m(!0),setTimeout(()=>{const te=t.useEditorStore.getState().actions;te.setIsDevMode(!0),te.setCardSql(P||""),setTimeout(()=>{te.setRunSql(!0)},100)},100)}}):(A==null?void 0:A.sql)&&e.jsx(La,{sql:A.sql,showCardDetails:!0,debugPayloads:R?{queryRequest:W,queryResponse:A,columns:c,dashboardFilters:o}:void 0})})})]}),D&&e.jsx(t.FeedbackDialog,{open:B,onOpenChange:S,feedbackData:D})]})})}function ti({activeField:s}){const[n,a]=y.useState(!0);return y.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 si=()=>{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 c;if((c=r.reason)!=null&&c.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 ai({column:s,isSelected:n,onSelect:a,availableFields:r,width:c,onWidthChange:i}){var O,P,_;const l=t.useEditorStore(z=>z.card),{updateCardConfig:d,removeGroupByColumn:o,removeMetricColumn:u,updateFilters:p}=t.useEditorActions(),[x,h]=y.useState(!1),[m,g]=y.useState(!1),v=y.useRef(null),b=y.useCallback(z=>{z.preventDefault(),z.stopPropagation(),g(!0),v.current={startX:z.clientX,startWidth:c||150};const U=K=>{if(!v.current)return;const Z=K.clientX-v.current.startX,ae=Math.max(80,v.current.startWidth+Z);i==null||i(s.id,ae)},W=()=>{g(!1),v.current=null,document.removeEventListener("mousemove",U),document.removeEventListener("mouseup",W)};document.addEventListener("mousemove",U),document.addEventListener("mouseup",W)},[c,s.id,i]),C=(O=l==null?void 0:l.config)==null?void 0:O.filters,E=(P=C==null?void 0:C.conditions)==null?void 0:P.some(z=>z.field.name===s.name&&z.field.qualifiedEntityName===s.qualifiedEntityName),B=z=>{z?p(l.id,z):d(l.id,{filters:void 0})},{attributes:S,listeners:M,setNodeRef:w,transform:D,transition:I,isDragging:k}=t.useSortable({id:s.id}),j={transform:t.CSS.Transform.toString(D),transition:I},R=t.getDataType(s.dataType),N=ni(R),L=()=>{var W;const z=((W=l==null?void 0:l.config)==null?void 0:W.sortByColumns)||[],U=z.findIndex(K=>K.name===s.name);if(U!==-1){const K=[...z];K[U]={...K[U],direction:"asc"},d(l.id,{sortByColumns:K})}else d(l.id,{sortByColumns:[...z,{...s,id:`sort-${s.id}`,role:"sortby",direction:"asc"}]})},F=()=>{var W;const z=((W=l==null?void 0:l.config)==null?void 0:W.sortByColumns)||[],U=z.findIndex(K=>K.name===s.name);if(U!==-1){const K=[...z];K[U]={...K[U],direction:"desc"},d(l.id,{sortByColumns:K})}else d(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(K=>K.name===s.name)){const K={...s,id:`groupby-${s.id}-${Date.now()}`,role:"groupby"};d(l.id,{groupByColumns:[...z,K]})}},A=z=>{var K;const U=((K=l==null?void 0:l.config)==null?void 0:K.metricColumns)||[];if(!U.some(Z=>Z.name===s.name&&Z.aggregate===z)){const Z={...s,id:`metric-${s.id}-${z}-${Date.now()}`,label:`${z} of ${s.label||s.name}`,role:"metric",aggregate:z};d(l.id,{metricColumns:[...U,Z]})}},T=()=>{s.role==="groupby"?o(l.id,s.id):s.role==="metric"&&u(l.id,s.id)},V={...j,width:c?`${c}px`:void 0,minWidth:c?`${c}px`:"120px"};return e.jsxs("th",{ref:w,style:V,className:t.cn("group relative border-r border-border bg-background px-1 py-0",k&&"opacity-50",n&&"bg-primary/10",m&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...S,...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(N,{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,")"]}),E&&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:()=>h(!0),children:[e.jsx(t.Filter,{className:t.cn("mr-2 h-4 w-4",E&&"text-primary")}),E?"Edit Filter":"Filter"]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{onClick:L,children:[e.jsx(mn,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(t.DropdownMenuItem,{onClick:F,children:[e.jsx(un,{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(zt,{className:"mr-2 h-4 w-4"}),"Group by this column"]}),e.jsxs(t.DropdownMenuItem,{disabled:!0,children:[e.jsx(cs,{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:T,className:"text-destructive focus:text-destructive",children:[e.jsx(t.Trash2,{className:"mr-2 h-4 w-4"}),"Remove column"]})]})]})]}),e.jsx("div",{onMouseDown:b,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(Ka,{open:x,onOpenChange:h,availableFields:r.length>0?r:[s],existingFilters:C,editingCondition:E?(_=C==null?void 0:C.conditions)==null?void 0:_.find(z=>z.field.name===s.name&&z.field.qualifiedEntityName===s.qualifiedEntityName):void 0,onSave:B})]})}function ni(s){switch(s){case"number":return t.Hash;case"date":return t.Calendar;case"string":default:return t.Type}}function ri({selectedColumn:s,onColumnSelect:n,isLoading:a=!1,sourceFields:r=[],filterableFields:c=r}){var k,j,R,N;const i=t.useEditorStore(L=>L.card),{updateCardConfig:l}=t.useEditorActions(),[d,o]=y.useState(null),[u,p]=y.useState({}),[x,h]=y.useState(!1),m=y.useMemo(()=>{var f,A;const L=((f=i==null?void 0:i.config)==null?void 0:f.groupByColumns)||[],F=((A=i==null?void 0:i.config)==null?void 0:A.metricColumns)||[];return[...L,...F]},[(k=i==null?void 0:i.config)==null?void 0:k.groupByColumns,(j=i==null?void 0:i.config)==null?void 0:j.metricColumns]),g=y.useMemo(()=>{const L=new Set(m.map(F=>`${F.qualifiedEntityName}.${F.name}`));return r.filter(F=>!L.has(`${F.qualifiedEntityName}.${F.name}`))},[r,m]),{data:v,isLoading:b}=t.useDashboardCardQuery(i),C=(v==null?void 0:v.records)||[],E=y.useCallback((L,F)=>{p(f=>({...f,[L]:F}))},[]),B=y.useCallback(L=>{var T,V;const F=t.getDataType(L.dataType),f=((T=i==null?void 0:i.config)==null?void 0:T.groupByColumns)||[],A=((V=i==null?void 0:i.config)==null?void 0:V.metricColumns)||[];if(F==="number"){const O={...L,id:`metric-${L.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};l(i.id,{metricColumns:[...A,O]})}else{const O={...L,id:`groupby-${L.id}-${Date.now()}`,role:"groupby"};l(i.id,{groupByColumns:[...f,O]})}h(!1)},[(R=i==null?void 0:i.config)==null?void 0:R.groupByColumns,(N=i==null?void 0:i.config)==null?void 0:N.metricColumns,i.id,l]),S=t.useSensors(t.useSensor(t.PointerSensor,{activationConstraint:{distance:8}})),M=L=>{o(L.active.id)},w=L=>{const{active:F,over:f}=L;if(o(null),!f||F.id===f.id)return;const A=m.findIndex(V=>V.id===F.id),T=m.findIndex(V=>V.id===f.id);if(A!==-1&&T!==-1){const V=t.arrayMove(m,A,T),O=V.filter(_=>_.role==="groupby"),P=V.filter(_=>_.role==="metric");l(i.id,{groupByColumns:O,metricColumns:P})}},D=d?m.find(L=>L.id===d):null,I=L=>{let F="";for(;L>=0;)F=String.fromCharCode(L%26+65)+F,L=Math.floor(L/26)-1;return F};return a?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(t.LoaderCircle,{className:"h-5 w-5 animate-spin text-muted-foreground/60"})}):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:S,collisionDetection:t.closestCenter,onDragStart:M,onDragEnd:w,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,F)=>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:I(F)},`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(ai,{column:L,isSelected:(s==null?void 0:s.id)===L.id,onSelect:()=>n(L),availableFields:c,width:u[L.id],onWidthChange:E},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:h,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 F=t.getDataType(L.dataType),f=F==="number"?t.Hash:F==="date"?t.Calendar:t.Type;return e.jsxs(t.CommandItem,{value:L.label||L.name,onSelect:()=>B(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:b?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"})})}):C.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"})}):C.slice(0,100).map((L,F)=>e.jsxs("tr",{className:t.cn("border-b border-border transition-colors hover:bg-muted/50",F%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:F+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:li(A,f)})},`${F}-${f.id}`)}),e.jsx("td",{className:"w-10 border-r border-border"})]},F))})]}),e.jsx(t.DragOverlay,{children:D&&e.jsx("div",{className:"rounded border border-primary bg-background px-3 py-2 text-sm font-medium shadow-lg",children:D.label||D.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(C.length,100)," of ",C.length," rows"]}),e.jsxs("span",{children:[m.length," columns"]})]})]})}function li(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 oi({entityGroups:s,isLoading:n=!1}){var B,S;const a=t.useEditorStore(M=>M.card),{updateCardConfig:r,removeGroupByColumn:c,removeMetricColumn:i}=t.useEditorActions(),[l,d]=y.useState(!0),[o,u]=y.useState(""),[p,x]=y.useState(new Set),h=((B=a==null?void 0:a.config)==null?void 0:B.groupByColumns)||[],m=((S=a==null?void 0:a.config)==null?void 0:S.metricColumns)||[],g=M=>{const w=new Set(p);w.has(M)?w.delete(M):w.add(M),x(w)},v=M=>h.some(w=>w.name===M.name&&w.qualifiedEntityName===M.qualifiedEntityName)||m.some(w=>w.name===M.name&&w.qualifiedEntityName===M.qualifiedEntityName),b=(M,w)=>{if(w)if(t.getDataType(M.dataType)==="number"){const I={...M,id:`metric-${M.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};r(a.id,{metricColumns:[...m,I]})}else{const I={...M,id:`groupby-${M.id}-${Date.now()}`,role:"groupby"};r(a.id,{groupByColumns:[...h,I]})}else{const D=h.findIndex(k=>k.name===M.name&&k.qualifiedEntityName===M.qualifiedEntityName),I=m.findIndex(k=>k.name===M.name&&k.qualifiedEntityName===M.qualifiedEntityName);D!==-1&&c(a.id,h[D].id),I!==-1&&i(a.id,m[I].id)}},C=M=>{if(!o)return M;const w=o.toLowerCase();return M.filter(D=>D.name.toLowerCase().includes(w)||D.label&&D.label.toLowerCase().includes(w))},E=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:()=>d(!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"})]})}),(h.length>0||m.length>0)&&e.jsxs("div",{className:"border-b border-border",children:[h.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(zt,{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:h.length})]}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:h.map(M=>{const w=E(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(w,{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:()=>c(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 w=E(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(w,{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 w=C(M.columns);if(w.length===0)return null;const D=p.has(M.entityId)||o.length>0;return e.jsxs(t.Collapsible,{open:D,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",D&&"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:w.length})]}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:w.map(I=>{const k=E(I.dataType),j=v(I);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",j&&"bg-primary/5"),children:[e.jsx(t.Checkbox,{checked:j,onCheckedChange:R=>b(I,R),className:"h-3.5 w-3.5"}),e.jsx(k,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:I.label||I.name})]},I.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:()=>d(!0),title:"Open panel",children:e.jsx(Sn,{className:"h-4 w-4"})})})}const ii=[{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 ci({value:s,onChange:n,onSubmit:a,onCancel:r,selectedColumn:c,availableColumns:i}){const[l,d]=y.useState(!1),[o,u]=y.useState("column"),p=y.useRef(null);y.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}]`,b=p.current;if(b){const C=b.selectionStart||0,E=b.selectionEnd||0,B=s.slice(0,C)+v+s.slice(E);n(B),setTimeout(()=>{b.setSelectionRange(C+v.length,C+v.length),b.focus()},0)}else n(s+v);d(!1)},h=g=>{const v=p.current;if(v){const b=v.selectionStart||0,C=v.selectionEnd||0,E=s.slice(0,b)+g.syntax+s.slice(C);n(E),setTimeout(()=>{v.setSelectionRange(b+g.name.length+1,b+g.syntax.length-1),v.focus()},0)}else n(s+g.syntax);d(!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:c?e.jsx("span",{className:"truncate",children:c.label||c.name}):e.jsx("span",{children:"—"})}),e.jsxs(t.Popover,{open:l&&o==="function",onOpenChange:g=>{d(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:ii.map(g=>e.jsx(t.CommandItem,{value:g.name,onSelect:()=>h(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=>{d(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:p,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 di({className:s}){var m,g,v,b;const n=t.useEditorStore(C=>C.card),[a,r]=y.useState(null),[c,i]=y.useState(""),{columns:l=[],columnGroups:d=[],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,(b=n==null?void 0:n.config)!=null&&b.pivotByColumns;const p=C=>{r(C),i(C?`[${C.label||C.name}]`:"")},x=C=>{console.log("Formula submitted:",C),i(""),r(null)},h=()=>{i(""),r(null)};return e.jsxs("div",{className:t.cn("flex h-full w-full flex-col",s),children:[e.jsx(ci,{value:c,onChange:i,onSubmit:x,onCancel:h,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(ri,{selectedColumn:a,onColumnSelect:p,isLoading:o,sourceFields:l,filterableFields:u})}),e.jsx(oi,{entityGroups:d,isLoading:o})]})]})}function ui(){var T,V;const[s,n]=y.useState("chart"),[a,r]=y.useState(!1),[c,i]=y.useState(!0),l=t.useEditorStore(O=>O.showAIDialog),d=t.useDashboardStore(O=>O.isVisualEditing),{setCardType:o}=t.useEditorActions(),u=t.useEditorStore(O=>O.card.type);y.useEffect(()=>si(),[]);const p=O=>{o(O)},x=t.useEditorStore(O=>O.frame),h=t.useEditorStore(O=>O.card);t.useEditorStore(O=>O.activeTabCardId),t.useEditorStore(O=>O.actions.getAvailableFields);const{addCard:m,removeCard:g,updateCard:v,setActiveCard:b,updateFilters:C}=t.useEditorActions(),{columnFields:E=[],scopedFields:B=[],filterableFields:S=[]}=t.useFilterableFields(),M=t.useSensors(t.useSensor(t.PointerSensor,{activationConstraint:{distance:8}})),w=h,{getFieldsForContainer:D,setFieldsForContainer:I}=t.useFieldManagement(w),{activeField:k,handleDragStart:j,handleDragEnd:R}=Ho({activeCardId:x.activeCardId,sourceFields:B,getFieldsForContainer:D,setFieldsForContainer:I}),N=(O,P)=>{P&&C(O,P)},L=O=>{var P;v(O,{config:{...(P=x.cards.find(_=>_.id===O))==null?void 0:P.config,filters:void 0}})},F=S,f=O=>{if(!O)return 0;let P=O.conditions.length;return O.groups.forEach(_=>{P+=f(_)}),P},A=f(((T=w==null?void 0:w.config)==null?void 0:T.filters)||null);return e.jsxs(t.DndContext,{sensors:M,collisionDetection:t.closestCenter,onDragStart:j,onDragEnd:R,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Ma,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:u==="tableBuilder"?e.jsx(di,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!l&&e.jsx(Do,{selectedChart:u,onChartChange:p,groupByFields:D("groupBy"),pivotByFields:D("pivotBy"),metricsFields:D("metrics"),sortByFields:D("sortBy"),detailFields:D("detailColumns"),activeField:k}),e.jsx(ei,{selectedChart:u,activeView:s,onViewChange:n,onFiltersClick:()=>r(!0),filterCount:A,activeCard:w,columns:E,getFieldsForContainer:D,cards:x.cards,activeCardId:x.activeCardId,addCard:m,setActiveCard:b})]})}),!c&&d&&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"})})})]}),w&&e.jsx(Uo,{cardId:w.id,filters:((V=w.config)==null?void 0:V.filters)||null,onFiltersChange:N,onClearFilters:L,availableFields:F,isOpen:a,onOpenChange:r}),e.jsx(t.DragOverlay,{dropAnimation:null,children:e.jsx(ti,{activeField:k||null})})]})}function mi({authToken:s,onSave:n,onClose:a}){const r=y.useRef(null),c=t.useEditorStore(w=>w.showAIDialog),i=t.useEditorStore(w=>w.isDevMode),l=t.useAssistantLayoutStore(w=>w.setFullscreen),d=t.useAssistantLayoutStore(w=>w.setPanelOpen),o=t.useAssistantLayoutStore(w=>w.setContainer),u=t.useAssistantPanel("editor"),p=t.useFullscreenAssistant(),x=t.useAssistantContainer("editor"),h=p==="editor",m=y.useCallback(w=>{o("editor",w)},[o]),{setAuthToken:g}=t.useDashboardActions(),{setShowAIDialog:v,setOnSave:b,setOnClose:C}=t.useEditorActions(),{setActiveAssistantType:E}=t.useAIActions();y.useEffect(()=>{n&&b(n),a&&C(a)},[n,b,a,C]),y.useEffect(()=>{s&&s.accessToken&&g(s)},[s,g]),y.useEffect(()=>{var w,D;c?((w=r.current)==null||w.resize(40),d("editor",!0),E("editor")):((D=r.current)==null||D.resize(0),d("editor",!1),p==="editor"&&l(null),E(null))},[c,d,E,l,p]);function B(w){var D;w<1?(v(!1),d("editor",!1),p==="editor"&&l(null),E(null),(D=r.current)==null||D.resize(0)):(c||(v(!0),E("editor")),u.isOpen||d("editor",!0))}function S(){return e.jsxs(e.Fragment,{children:[e.jsx(Ma,{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",h&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(uo,{})}),e.jsx(t.ResizableHandle,{disabled:!c}),e.jsx(t.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:B,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Ca,{isFullscreen:h,onFullscreenChange:w=>l(w?"editor":null),fullscreenContainer:x})})})]}),e.jsx("div",{ref:m,className:t.cn("absolute inset-0",!h&&"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",h&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(ui,{})}),e.jsx(t.ResizableHandle,{disabled:!c}),e.jsx(t.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:B,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Ca,{isFullscreen:h,onFullscreenChange:w=>l(w?"editor":null),fullscreenContainer:x})})})]}),e.jsx("div",{ref:m,className:t.cn("absolute inset-0",!h&&"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:S()}):M()})}function xi(){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),c=t.useDashboardStore(o=>o.isVisualEditing),i=t.useDashboardStore(o=>o.actions.updateFrame);function l(o){var h,m,g;const u=s?(h=n==null?void 0:n.sheets)==null?void 0:h.some(v=>{var b;return v.id===s&&((b=v.frames)==null?void 0:b.some(C=>C.id===o.id))}):!1,p=(g=(m=n==null?void 0:n.sheets)==null?void 0:m.find(v=>{var b;return(b=v.frames)==null?void 0:b.some(C=>C.id===o.id)}))==null?void 0:g.id,x=u?s:p||null;x&&(i(x,o),s!==x&&r(x),a(!1))}function d(){a(!1)}return e.jsx("div",{role:"editor-container",className:t.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!c}),children:e.jsx(mi,{onSave:l,onClose:d})})}exports.default=xi;
|