react-semaphor 0.1.298 → 0.1.299
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/{braces-BXBFWlAT.js → braces-DytC2b1M.js} +1 -1
- package/dist/chunks/{braces-CEx3WpxL.js → braces-uehz1QT7.js} +1 -1
- package/dist/chunks/{dashboard-controls-CQoGNPbq.js → dashboard-controls-Cpjx2gxm.js} +1 -1
- package/dist/chunks/{dashboard-controls-DOLk9rEX.js → dashboard-controls-poI7wP8s.js} +5 -5
- package/dist/chunks/{dashboard-filter-controls-button-BrY1-2jJ.js → dashboard-filter-controls-button-94HgSpK_.js} +1 -1
- package/dist/chunks/{dashboard-filter-controls-button-4NblToDI.js → dashboard-filter-controls-button-DMf1fdxi.js} +3 -3
- package/dist/chunks/{dashboard-json-C_xXlB_B.js → dashboard-json-BRe2AM7l.js} +1 -1
- package/dist/chunks/{dashboard-json-CsUlFwt8.js → dashboard-json-D0F8qMeN.js} +1 -1
- package/dist/chunks/{dashboard-summary-settings-dialog-qhAdT7at.js → dashboard-summary-settings-dialog-CEwWfmp2.js} +1 -1
- package/dist/chunks/{dashboard-summary-settings-dialog-DCLKq8Mt.js → dashboard-summary-settings-dialog-DC7cZ5lN.js} +1 -1
- package/dist/chunks/{edit-dashboard-visual-CsqWmj2Y.js → edit-dashboard-visual-Ceiypy27.js} +7513 -7228
- package/dist/chunks/edit-dashboard-visual-DuPcJx1w.js +188 -0
- package/dist/chunks/{index-CdK808cy.js → index-BMkPMHd1.js} +247 -247
- package/dist/chunks/{index-Bf_uZ5mY.js → index-DaSdwe0q.js} +25608 -25894
- package/dist/chunks/{resource-management-panel-DF6KUEvo.js → resource-management-panel-DBAwCjlr.js} +2 -2
- package/dist/chunks/{resource-management-panel-BPfrEjkZ.js → resource-management-panel-elCFmiX9.js} +1 -1
- package/dist/chunks/{use-create-flow-overlay-state-rTygImH3.js → use-create-flow-overlay-state-DK53WJCX.js} +1 -1
- package/dist/chunks/{use-create-flow-overlay-state-DHJX6gTj.js → use-create-flow-overlay-state-D_k2LA86.js} +2 -2
- package/dist/chunks/{use-visual-utils-D_WYtybQ.js → use-visual-utils-BIQHlvEU.js} +1 -1
- package/dist/chunks/{use-visual-utils-Cc8AW73h.js → use-visual-utils-lNM_pQBw.js} +1 -1
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +5 -5
- package/dist/style.css +1 -1
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +2 -2
- package/package.json +1 -1
- package/dist/chunks/edit-dashboard-visual--qZzelMR.js +0 -188
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),N=require("react"),t=require("./index-BMkPMHd1.js"),it=require("./use-visual-utils-lNM_pQBw.js"),Ae=require("./use-create-flow-overlay-state-DK53WJCX.js"),xa=require("react-dom"),ha=require("./braces-DytC2b1M.js");function pa(s){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const n in s)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(s,n);Object.defineProperty(a,n,r.get?r:{enumerable:!0,get:()=>s[n]})}}return a.default=s,Object.freeze(a)}const Pt=pa(N);/**
|
|
2
|
+
* @license lucide-react v0.453.0 - ISC
|
|
3
|
+
*
|
|
4
|
+
* This source code is licensed under the ISC license.
|
|
5
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
6
|
+
*/const fa=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 ga=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 Dn=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 ds=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"}]]);/**
|
|
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 ba=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"}]]);/**
|
|
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 An=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"}]]);/**
|
|
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 ja=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"}]]);/**
|
|
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 va=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"}]]);/**
|
|
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 Mn=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"}]]);/**
|
|
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 ya=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"}]]);/**
|
|
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 Na=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"}]]);/**
|
|
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 Ca=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"}]]);/**
|
|
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 nn=t.createLucideIcon("ListFilter",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M7 12h10",key:"b7w52i"}],["path",{d:"M10 18h4",key:"1ulq68"}]]);/**
|
|
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("ListStart",[["path",{d:"M16 12H3",key:"1a2rj7"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"M10 6H3",key:"lf8lx7"}],["path",{d:"M21 18V8a2 2 0 0 0-2-2h-5",key:"1hghli"}],["path",{d:"m16 8-2-2 2-2",key:"160uvd"}]]);/**
|
|
72
|
+
* @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 wa=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"}]]);/**
|
|
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 Yt=t.createLucideIcon("MoveHorizontal",[["path",{d:"m18 8 4 4-4 4",key:"1ak13k"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}]]);/**
|
|
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 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"}]]);/**
|
|
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 Ta=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"}]]);/**
|
|
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 Ea=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"}]]);/**
|
|
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 Ia=t.createLucideIcon("PanelRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
|
|
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 is=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"}]]);/**
|
|
107
|
+
* @license lucide-react v0.453.0 - ISC
|
|
108
|
+
*
|
|
109
|
+
* This source code is licensed under the ISC license.
|
|
110
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
111
|
+
*/const zt=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"}]]);/**
|
|
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 ka=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"}]]);/**
|
|
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 Da=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"}]]);/**
|
|
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 Aa=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"}]]);/**
|
|
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 Ma=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"}]]);/**
|
|
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 La=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"}]]);/**
|
|
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 Fa=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"}]]);/**
|
|
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 Ra=t.createLucideIcon("Tag",[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]]);/**
|
|
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 Oa=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 Pa=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 Ln({storeValue:s,defaultValue:a="",onStoreUpdate:n,delay:r=300}){const[c,i]=N.useState(s??a),l=N.useRef(null),d=N.useRef(c),o=N.useRef(s),m=N.useRef(!1),h=N.useCallback(()=>{l.current&&(clearTimeout(l.current),l.current=null),m.current&&d.current!==(o.current??a)&&(n(d.current),o.current=d.current)},[a,n]);N.useEffect(()=>{if(s!==o.current){l.current&&(clearTimeout(l.current),l.current=null);const x=s??a;i(x),d.current=x,o.current=s,m.current=!1}},[s,a]),N.useEffect(()=>{if(m.current)return l.current=setTimeout(()=>{h()},r),()=>{l.current&&(clearTimeout(l.current),l.current=null)}},[r,h,c]),N.useEffect(()=>()=>{l.current&&clearTimeout(l.current)},[]);const f=N.useCallback(x=>{const u=x??a;m.current=!0,d.current=u,i(u)},[a]);return{value:c,onChange:f,flush:h}}function Ba({open:s,onOpenChange:a}){const[n,r]=N.useState([]),{updateDataSource:c}=t.useEditorActions(),{selectedEntities:i}=t.useAssistantContextEntities("dashboard");N.useEffect(()=>{s&&r([])},[s]);const l=u=>{r(g=>g.some(b=>t.areContextEntitiesEqual(b,u))?g.filter(b=>!t.areContextEntitiesEqual(b,u)):[...g,u])},d=()=>{r([...i])},o=()=>{r([])},m=()=>{if(n.length===0)return;const u=n[0],g=u.connectionId||"",v=u.connectionType||"",S=n.some(P=>P.type==="dataset")?"semanticDomain":"database";c({connectionId:g,connectionType:v,mode:S,selectedEntities:n}),a(!1)},h=u=>"label"in u&&u.label?u.label:u.name,f=u=>{if("description"in u&&u.description)return u.description;const g=[];return u.database&&g.push(u.database),u.schema&&g.push(u.schema),u.name&&g.push(u.name),g.join(".")},x=u=>n.some(g=>t.areContextEntitiesEqual(g,u));return i.length===0?e.jsx(t.Dialog,{open:s,onOpenChange:a,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:()=>a(!1),children:"Close"})})]})}):e.jsx(t.Dialog,{open:s,onOpenChange:a,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:n.length===i.length,children:"Select All"}),e.jsx(t.Button,{variant:"outline",size:"sm",onClick:o,disabled:n.length===0,children:"Clear All"})]}),e.jsxs(t.Badge,{variant:"secondary",children:[n.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((u,g)=>e.jsxs("div",{className:t.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",x(u)&&"border-primary bg-primary/5"),children:[e.jsx(t.Checkbox,{checked:x(u),onCheckedChange:()=>l(u)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:t.getEntityIcon(u.type)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:h(u)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:f(u)})]}),e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:u.type})]},`${u.type}-${u.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:()=>a(!1),children:"Cancel"}),e.jsxs(t.Button,{onClick:m,disabled:n.length===0,children:["Select"," ",n.length>0?`(${n.length})`:""]})]})})})]})})}function Va({initialJoinPlan:s,availableDataSources:a}){const[n,r]=N.useState(s),[c,i]=N.useState(new Set),l=()=>{const y=n.joins.length>0?Math.max(...n.joins.map(E=>E.sequence))+1:1,T={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:y,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...n,joins:[...n.joins,T]}),i(new Set([...c,T.id]))},d=y=>{r({...n,joins:n.joins.filter(T=>T.id!==y)}),i(new Set([...c].filter(T=>T!==y)))},o=(y,T)=>{var w,M,F,j,L;const E=n.joins.find(k=>k.id===y);if(!E)return;const D={...E,...T};if((w=D.source)!=null&&w.name&&((M=D.target)!=null&&M.name)&&D.source.name===D.target.name){t.ue.error("Self-joins are not yet supported",{description:`Joining ${D.source.name} to itself is not currently supported. Please select a different target table.`});return}const p=n.joins.filter(k=>{var O;return k.id!==y&&k.target.name===((O=D.target)==null?void 0:O.name)});if((F=D.target)!=null&&F.name&&p.length>0){t.ue.error("Duplicate join targets are not supported",{description:`The table ${D.target.name} is already used as a target in another join. Each table can only be joined once.`});return}const R=n.joins.map(k=>k.id===y?D:k);if((j=D.source)!=null&&j.name&&((L=D.target)!=null&&L.name)&&D.joinKeyGroups[0].keys.length===0){const k=a.find(B=>{var _;return B.name===((_=D.source)==null?void 0:_.name)}),O=a.find(B=>{var _;return B.name===((_=D.target)==null?void 0:_.name)}),z={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:(O==null?void 0:O.name)||"",entityName:(O==null?void 0:O.name)||"",entityType:(O==null?void 0:O.type)||"table"},operator:"="},V=[...D.joinKeyGroups];V[0]={...V[0],keys:[z]},D.joinKeyGroups=V,R[R.findIndex(B=>B.id===y)]=D}r({...n,joins:R})};return{joinPlan:n,expandedJoins:c,setJoinPlan:r,addJoin:l,removeJoin:d,updateJoin:o,moveJoinUp:y=>{const T=n.joins.findIndex(E=>E.id===y);if(T>0){const E=[...n.joins],D={...E[T]},p={...E[T-1]};E[T]=p,E[T-1]=D,E.forEach((w,M)=>{w.sequence=M+1});const R={...n,joins:E};r(R)}},moveJoinDown:y=>{const T=n.joins.findIndex(E=>E.id===y);if(T<n.joins.length-1){const E=[...n.joins],D={...E[T]},p={...E[T+1]};E[T]=p,E[T+1]=D,E.forEach((w,M)=>{w.sequence=M+1});const R={...n,joins:E};r(R)}},toggleJoinExpansion:y=>{const T=new Set(c);T.has(y)?T.delete(y):T.add(y),i(T)},getAvailableSourceEntities:y=>{if(n.joins.length===0)return a;const T=n.joins.findIndex(D=>D.id===y);if(T===0)return a.filter(D=>D.name===n.baseEntity.name);const E=new Set;return n.baseEntity.name&&E.add(n.baseEntity.name),n.joins.slice(0,T).forEach(D=>{E.add(D.source.name),E.add(D.target.name)}),a.filter(D=>E.has(D.name))},getAvailableTargetEntities:y=>a.filter(T=>T.name!==y),addJoinKeyGroup:y=>{const T=n.joins.find(D=>D.id===y);if(!T)return;const E=[...T.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];o(y,{joinKeyGroups:E})},updateGroupOperator:(y,T,E)=>{const D=n.joins.find(R=>R.id===y);if(!D)return;const p=[...D.joinKeyGroups];p[T]={...p[T],operator:E},o(y,{joinKeyGroups:p})},removeJoinKeyGroup:(y,T)=>{const E=n.joins.find(p=>p.id===y);if(!E)return;const D=[...E.joinKeyGroups];D.splice(T,1),o(y,{joinKeyGroups:D})},addJoinKey:(y,T)=>{const E=n.joins.find(M=>M.id===y);if(!E)return;const D=a.find(M=>M.name===E.source.name),p=a.find(M=>M.name===E.target.name),R=[...E.joinKeyGroups],w={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(D==null?void 0:D.name)||"",entityName:(D==null?void 0:D.name)||"",entityType:(D==null?void 0:D.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(p==null?void 0:p.name)||"",entityName:(p==null?void 0:p.name)||"",entityType:(p==null?void 0:p.type)||"table"},operator:"="};R[T]={...R[T],keys:[...R[T].keys,w]},o(y,{joinKeyGroups:R})},updateJoinKey:(y,T,E,D,p)=>{const R=n.joins.find(L=>L.id===y);if(!R)return;const w=a.find(L=>L.name===R.source.name),M=a.find(L=>L.name===R.target.name),F=[...R.joinKeyGroups],j=F[T].keys[E];D==="sourceColumnName"&&w?F[T].keys[E]={...j,source:{...j.source,name:p}}:D==="targetColumnName"&&M?F[T].keys[E]={...j,target:{...j.target,name:p}}:D==="operator"&&(F[T].keys[E]={...j,operator:p}),o(y,{joinKeyGroups:F})},removeJoinKey:(y,T,E)=>{const D=n.joins.find(R=>R.id===y);if(!D)return;const p=[...D.joinKeyGroups];p[T].keys.splice(E,1),o(y,{joinKeyGroups:p})},generateSQLPreview:()=>{const y=[...n.joins].sort((D,p)=>D.sequence-p.sequence),T=n.baseEntity;if(!T.name)return"SELECT * FROM table -- Please select a base entity";let E=`SELECT *
|
|
157
|
+
FROM ${T.name}`;return y.forEach(D=>{const p=a.find(M=>M.name===D.target.name);if(!p)return;const R=D.joinKeyGroups.filter(M=>M.keys&&M.keys.length>0).map(M=>{const F=M.keys.filter(j=>{var L,k,O,z;return((L=j.source)==null?void 0:L.name)&&((k=j.target)==null?void 0:k.name)&&((O=j.source)==null?void 0:O.entityName)&&((z=j.target)==null?void 0:z.entityName)}).map(j=>`${j.source.entityName}.${j.source.name} ${j.operator} ${j.target.entityName}.${j.target.name}`);return F.length>1?`(${F.join(` ${M.operator} `)})`:F[0]}).filter(Boolean),w=R.length>1?R.join(" OR "):R[0]||"condition_here";E+=`
|
|
158
|
+
${D.joinType} JOIN ${p.name}
|
|
159
|
+
ON ${w}`}),E},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(D=>!D.source.name||!D.target.name)||n.joins.some(D=>D.joinKeyGroups.some(p=>p.keys.length===0))||n.joins.some(D=>D.joinKeyGroups.some(p=>p.keys.some(R=>!R.source.name||!R.target.name||!R.operator))))}}function za({joinPlan:s,availableDataSources:a,onSave:n,onRemove:r,onCancel:c}){const{setCardConfig:i}=t.useEditorActions();t.useEditorStore(w=>w.card.config);const{columnGroups:l}=t.useColumns(),d=l.filter(w=>w.entityName!==t.CALCULATED_FIELDS_GROUP_NAME),{joinPlan:o,expandedJoins:m,setJoinPlan:h,addJoin:f,removeJoin:x,updateJoin:u,moveJoinUp:g,moveJoinDown:v,toggleJoinExpansion:b,getAvailableSourceEntities:S,getAvailableTargetEntities:I,addJoinKeyGroup:P,updateGroupOperator:C,removeJoinKeyGroup:A,addJoinKey:y,updateJoinKey:T,removeJoinKey:E,generateSQLPreview:D,isValidConfiguration:p}=Va({initialJoinPlan:s,availableDataSources:a}),R=w=>{const M=d.find(F=>F.entityName===w);return(M==null?void 0:M.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:w=>{const M=a.find(F=>F.name===w);h({...o,baseEntity:{connectionId:(M==null?void 0:M.connectionId)||"",connectionType:(M==null?void 0:M.connectionType)||"none",type:(M==null?void 0:M.type)||"table",name:w,database:M==null?void 0:M.database,schema:M==null?void 0:M.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(t.SelectContent,{children:a.map(w=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:w.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:w.type}),w.name,e.jsx(t.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},w.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:D()})]}),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:f,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(w=>{const M=a.find(L=>L.name===w.source.name),F=a.find(L=>L.name===w.target.name),j=m.has(w.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:w.sequence}),e.jsxs(t.CardTitle,{className:"text-sm",children:["Join ",w.sequence,M&&F&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",M.name," → ",F.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>g(w.id),disabled:w.sequence===1,children:e.jsx(t.ArrowUp,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>v(w.id),disabled:w.sequence===o.joins.length,children:e.jsx(t.ArrowDown,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>b(w.id),children:j?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:()=>x(w.id),children:e.jsx(t.X,{className:"h-4 w-4"})})]})]})}),j&&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:w.source.name,onValueChange:L=>{const k=a.find(O=>O.name===L);u(w.id,{source:{connectionId:(k==null?void 0:k.connectionId)||"",connectionType:(k==null?void 0:k.connectionType)||"none",type:(k==null?void 0:k.type)||"table",name:L,database:k==null?void 0:k.database,schema:k==null?void 0:k.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select source..."})}),e.jsx(t.SelectContent,{children:S(w.id).map(L=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:L.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:L.type}),L.name]})},L.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Join Type"}),e.jsxs(t.Select,{value:w.joinType,onValueChange:L=>u(w.id,{joinType:L}),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:w.target.name,onValueChange:L=>{const k=a.find(O=>O.name===L);u(w.id,{target:{connectionId:(k==null?void 0:k.connectionId)||"",connectionType:(k==null?void 0:k.connectionType)||"none",type:(k==null?void 0:k.type)||"table",name:L,database:k==null?void 0:k.database,schema:k==null?void 0:k.schema}})},disabled:!w.source.name,children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select target..."})}),e.jsx(t.SelectContent,{children:w.source.name?I(w.source.name).map(L=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:L.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:L.type}),L.name,L.name===w.source.name&&e.jsx(t.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},L.name)):[]})]})]})]}),w.source.name&&w.target.name&&M&&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:()=>P(w.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),w.joinKeyGroups.length===0?e.jsx("div",{className:"rounded-md border p-3 text-center text-sm text-gray-500",children:"No join conditions defined. Add condition groups to specify how data sources should be joined."}):e.jsx("div",{className:"space-y-4",children:w.joinKeyGroups.map((L,k)=>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 ",k+1]}),k>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:L.operator,onValueChange:O=>C(w.id,k,O),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:()=>A(w.id,k),children:e.jsx(t.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[L.keys.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-sm text-gray-500",children:"No conditions in this group. Add conditions to specify join criteria."}):e.jsx("div",{className:"space-y-2",children:L.keys.map((O,z)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[z>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:L.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:O.source.name,onValueChange:V=>T(w.id,k,z,"sourceColumnName",V),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Source column"})}),e.jsx(t.SelectContent,{children:R(w.source.name).map(V=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:V.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:V.name}),e.jsx(t.Badge,{variant:"outline",className:"ml-2 text-xs",children:V.dataType})]})},V.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(t.Select,{value:O.operator,onValueChange:V=>T(w.id,k,z,"operator",V),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:O.target.name,onValueChange:V=>T(w.id,k,z,"targetColumnName",V),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Target column"})}),e.jsx(t.SelectContent,{children:R(w.target.name).map(V=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:V.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:V.name}),e.jsx(t.Badge,{variant:"outline",className:"ml-2 text-xs",children:V.dataType})]})},V.name))})]})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>E(w.id,k,z),children:e.jsx(t.X,{className:"size-3.5"})})]},O.id||z))}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>y(w.id,k),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},L.id))})]})]})]},w.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:()=>n(o),disabled:!p(),children:"Save"})]})]})}function Fn({children:s,open:a,onOpenChange:n,joinPlan:r,availableDataSources:c,onRemove:i,onSave:l,onCancel:d}){return e.jsxs(t.Dialog,{open:a,onOpenChange:n,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(za,{joinPlan:r,availableDataSources:c,onSave:l,onCancel:d,onRemove:i})]}),s]})}function _a({joins:s,baseEntityId:a,availableDataSources:n,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=n.find(l=>l.name===a);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(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=n.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=n.find(m=>m.name===c.source.name),d=n.find(m=>m.name===c.target.name),o=c.joinKeyGroups.reduce((m,h)=>m+h.keys.length,0);return e.jsxs("div",{className:"rounded-md bg-muted p-2 text-left",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:i+1}),e.jsx(t.Badge,{variant:"outline",className:"shrink-0 text-xs",children: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 qa({open:s,onOpenChange:a,variant:n="button"}={}){var I,P;const r=t.useEditorStore(C=>C.card),{autoJoinMetadata:c}=t.useEditorCardQuery(r),i=t.useEditorStore(C=>C.actions.updateCardConfig),l=((I=r==null?void 0:r.config)==null?void 0:I.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[d,o]=N.useState(!1),m=s!==void 0,h=m?s:d,f=m?a:o,x=((P=r==null?void 0:r.dataSource)==null?void 0:P.selectedEntities)||[],u=C=>{i(r.id,{...r==null?void 0:r.config,joinPlan:C}),f(!1)},g=()=>{i(r.id,{...r==null?void 0:r.config,joinPlan:void 0})},v=()=>{f(!1)},b=()=>{const C=[...l.joins].sort((T,E)=>T.sequence-E.sequence),A=l.baseEntity;if(!A.name)return"SELECT * FROM table -- Please select a base entity";let y=`SELECT *
|
|
160
|
+
FROM ${A.name}`;return C.forEach(T=>{const E=x.find(R=>R.name===T.target.name);if(!E)return;const D=T.joinKeyGroups.filter(R=>R.keys&&R.keys.length>0).map(R=>{const w=R.keys.filter(M=>{var F,j,L,k;return((F=M.source)==null?void 0:F.name)&&((j=M.target)==null?void 0:j.name)&&((L=M.source)==null?void 0:L.entityName)&&((k=M.target)==null?void 0:k.entityName)}).map(M=>`${M.source.entityName}.${M.source.name} ${M.operator} ${M.target.entityName}.${M.target.name}`);return w.length>1?`(${w.join(` ${R.operator} `)})`:w[0]}).filter(Boolean),p=D.length>1?D.join(" OR "):D[0]||"condition_here";y+=`
|
|
161
|
+
${T.joinType} JOIN ${E.name}
|
|
162
|
+
ON ${p}`}),y};if(x.length<2)return null;const S=l.joins.length>0&&e.jsx(t.TooltipContent,{side:"bottom",className:"ml-4 max-w-md overflow-hidden p-0",children:e.jsx(_a,{joins:l.joins,baseEntityId:l.baseEntity.name,availableDataSources:x,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:n==="badge"?e.jsxs(t.Badge,{variant:"secondary",className:"h-5 cursor-pointer gap-1 px-1.5 text-xs transition-colors hover:bg-secondary/80",onClick:C=>{C.stopPropagation(),f(!0)},children:[e.jsx(t.Link,{className:"h-3 w-3"}),l.joins.length]}):e.jsxs("button",{type:"button",onClick:()=>f(!0),className:"flex h-7 w-full items-center gap-2 rounded-[5px] border border-border bg-background px-2 text-left transition-colors hover:bg-muted focus:outline-none focus-visible:border-ring",children:[e.jsx(t.Link,{className:"h-3 w-3 shrink-0 text-muted-foreground",strokeWidth:1.75}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-[13px] text-foreground",children:l.joins.length===0?"Configure joins":`${l.joins.length} ${l.joins.length===1?"join":"joins"}`}),(c==null?void 0:c.autoResolved)&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-muted-foreground",children:[e.jsx(t.Sparkles,{className:"h-3 w-3",strokeWidth:1.75}),"Auto"]})]})}),S]})}),e.jsx(Fn,{open:h,onOpenChange:f,joinPlan:l,availableDataSources:x,onSave:u,onCancel:v,onRemove:g,children:e.jsx("div",{})})]})}function $a(){var C,A,y,T,E,D;const[s,a]=N.useState(!1),[n,r]=N.useState(!1),[c,i]=N.useState(!1),l=t.useEditorStore(p=>p.card.dataSource),d=t.useEditorStore(p=>p.card),o=t.useEditorStore(p=>p.isDevMode),{updateDataSource:m}=t.useEditorActions(),{autoJoinMetadata:h}=t.useEditorCardQuery(d),x={...{connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},...l,selectedEntities:(l==null?void 0:l.selectedEntities)||[]},u=t.toEntityArray(x.selectedEntities),g=u.length,v=g===0?"Choose dataset":g===1?Zt(u[0]):`${g} datasets`,b=((y=(A=(C=d==null?void 0:d.config)==null?void 0:C.joinPlan)==null?void 0:A.joins)==null?void 0:y.length)??0,S=!!(h!=null&&h.autoResolved);((E=(T=h==null?void 0:h.resolvedJoinPlan)==null?void 0:T.joins)==null?void 0:E.length)??((D=h==null?void 0:h.relationshipsUsed)==null||D.length);const I=g<2?null:b>0?`${b} join${b===1?"":"s"}`:S?"auto":null,P=p=>{const R=u.filter(w=>!t.areContextEntitiesEqual(w,p));m({...x,selectedEntities:R})};return e.jsxs(e.Fragment,{children:[e.jsxs(t.Popover,{open:s,onOpenChange:a,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex h-7 w-full items-center gap-2 rounded-[5px] border border-border bg-background px-2 text-left transition-colors hover:bg-muted focus:outline-none focus-visible:border-ring",children:[e.jsx(t.Database,{className:"h-3 w-3 shrink-0 text-muted-foreground",strokeWidth:1.75}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-[13px] text-foreground",children:v}),I&&e.jsxs("span",{className:"shrink-0 text-[11px] text-muted-foreground",children:["· ",I]}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform",s&&"rotate-180")})]})}),e.jsx(t.PopoverContent,{align:"start",sideOffset:4,className:"w-[320px] overflow-hidden rounded-[6px] border border-border bg-popover p-0 shadow-[0_4px_16px_rgba(0,0,0,0.08)]",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between px-3 pb-1.5 pt-2.5",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Datasets"}),e.jsx("span",{className:"font-mono text-[10px] tabular-nums text-muted-foreground/70",children:g})]}),g===0?e.jsx("div",{className:"px-3 pb-2 text-[12px] text-muted-foreground",children:"No datasets selected."}):e.jsx("ul",{className:"mb-1",children:u.map((p,R)=>e.jsxs("li",{className:"flex items-start gap-2 px-3 py-1.5 hover:bg-muted/50",children:[e.jsx(t.Database,{className:"mt-[3px] h-3 w-3 shrink-0 text-muted-foreground",strokeWidth:1.75}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-[13px] text-foreground",children:Zt(p)}),e.jsx("p",{className:"truncate text-[11px] text-muted-foreground",children:Ka(p)})]}),e.jsx("button",{type:"button",onClick:()=>P(p),"aria-label":`Remove ${Zt(p)}`,className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:e.jsx(t.X,{className:"h-3 w-3"})})]},`${p.connectionId}-${p.name}-${R}`))}),e.jsxs("button",{type:"button",onClick:()=>{a(!1),r(!0)},className:"flex w-full items-center gap-1.5 px-3 py-1.5 text-left text-[12px] text-muted-foreground transition-colors hover:bg-muted/50 hover:text-foreground",children:[e.jsx(t.Plus,{className:"h-3 w-3"}),"Add dataset"]})]}),g>1&&!o&&e.jsxs("div",{className:"border-t border-border/60 px-3 py-2.5",children:[e.jsx("div",{className:"mb-1.5 flex items-center justify-between",children:e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Join"})}),e.jsxs("button",{type:"button",onClick:()=>{a(!1),i(!0)},className:"flex h-7 w-full items-center gap-2 rounded-[5px] border border-border bg-background px-2 text-left transition-colors hover:bg-muted focus:outline-none focus-visible:border-ring",children:[e.jsx(t.Link,{className:"h-3 w-3 shrink-0 text-muted-foreground",strokeWidth:1.75}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-[13px] text-foreground",children:b>0?`${b} ${b===1?"join":"joins"}`:"Configure joins"}),S&&b===0&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-muted-foreground",children:[e.jsx(t.Sparkles,{className:"h-3 w-3",strokeWidth:1.75}),"Auto"]})]})]}),e.jsx("div",{className:"flex items-center justify-end border-t border-border/60 px-2 py-1.5",children:e.jsx("button",{type:"button",onClick:()=>a(!1),className:"inline-flex h-6 items-center rounded-[4px] px-2 text-[11px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:"Done"})})]})})]}),e.jsx(t.AddDataPicker,{incomingSelectedEntities:(l==null?void 0:l.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:r,dataSource:x}),g>1&&!o&&e.jsx("div",{className:"hidden",children:e.jsx(qa,{open:c,onOpenChange:i})})]})}function Zt(s){return"label"in s&&s.label?s.label:s.name||"Dataset"}function Ka(s){const a=[];return s.connectionType&&a.push(String(s.connectionType)),s.database&&a.push(s.database),s.schema&&a.push(s.schema),a.join(" · ")}function Rn({isVisible:s}){t.useSyncLegacyEditorState();const[a,n]=N.useState(!1);return e.jsxs("div",{className:t.cn("flex shrink-0 flex-col overflow-hidden border-r border-border bg-background transition-all duration-300 ease-in-out",{"w-[290px]":s,"min-w-[290px]":s,"w-0 border-r-0":!s,"min-w-0":!s}),children:[e.jsx("div",{className:"px-4 pt-4",children:e.jsx($a,{})}),e.jsx("div",{className:"min-h-0 flex-1",children:e.jsx(t.FieldsSection,{})}),e.jsx(Ba,{open:a,onOpenChange:n})]})}function Ga(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 Ua=300;function Ha(){const s=t.useEditorStore(S=>S.card.sql),a=t.useEditorStore(S=>S.sqlGen),n=t.useEditorStore(S=>S.card),r=Ae.useEffectiveEditorCardType(),{setCardSql:c,setSqlGen:i,setRunSql:l}=t.useEditorActions(),d=N.useMemo(()=>r!==n.type?{...n,type:r}:n,[n,r]),{queryKey:o}=t.useEditorCardQuery(d),m=t.useQueryClient(),h=N.useRef(o);h.current=o;const f=N.useRef(a);f.current=a;const x=N.useCallback(S=>{c(S)},[c]),{value:u,onChange:g,flush:v}=Ln({storeValue:s,defaultValue:"",onStoreUpdate:x,delay:Ua});N.useEffect(()=>it.registerPendingEditorDraftFlusher(v),[v]);function b(S){g(S),t.isObjectEmpty(f.current)||i({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!u&&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:u??"",onValueChange:b,language:"sql-jinja",embedded:!0,flushGutter:!0,onKeyDown:S=>{S.key==="Enter"&&S.shiftKey&&(S.preventDefault(),it.flushPendingEditorDrafts(),setTimeout(()=>{m.removeQueries({queryKey:h.current,exact:!0}),l(!0)},0))}})]})}const Qa=300;function Ja(){const s=t.useEditorStore(x=>x.card.python),a=t.useEditorStore(x=>x.card),n=Ae.useEffectiveEditorCardType(),{setCardPython:r,setRunSql:c}=t.useEditorActions(),i=N.useMemo(()=>n!==a.type?{...a,type:n}:a,[a,n]),{queryKey:l}=t.useEditorCardQuery(i),d=t.useQueryClient(),o=N.useRef(l);o.current=l;const{value:m,onChange:h,flush:f}=Ln({storeValue:s,defaultValue:t.PYTHON_DEFAULT_CODE,onStoreUpdate:r,delay:Qa});return N.useEffect(()=>it.registerPendingEditorDraftFlusher(f),[f]),e.jsx(t.CodeEditor,{value:m??"",onValueChange:h,language:"python",embedded:!0,flushGutter:!0,onKeyDown:x=>{x.key==="Enter"&&x.shiftKey&&(x.preventDefault(),it.flushPendingEditorDrafts(),setTimeout(()=>{d.removeQueries({queryKey:o.current,exact:!0}),c(!0)},0))}})}const Wa={async writeTextToClipboard(s){return typeof navigator>"u"||!navigator.clipboard?!1:(await navigator.clipboard.writeText(s),!0)}},Rt=50,Ya=[{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 an(s){try{return JSON.stringify(s,null,2)}catch(a){return console.error("Unable to stringify debug payload",a),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 Xa(s){if(!s||typeof s!="object")return{value:s};const a=s.records;return!Array.isArray(a)||a.length<=Rt?{value:s}:{value:{...s,records:a.slice(0,Rt),previewMeta:{truncatedRecords:!0,displayedRecords:Rt,totalRecords:a.length}},truncationMessage:`Preview showing first ${Rt} records of ${a.length}. Copy actions include full payload.`}}function On({sql:s,showCardDetails:a=!1,debugPayloads:n,className:r}){const[c,i]=N.useState(!1),[l,d]=N.useState(null),o=t.useEditorStore(p=>p.card),m=t.useEditorStore(p=>p.frame),h=t.useEditorStore(p=>p.isDevMode),f=t.useDashboardStore(p=>p.selectedSheetId),x=t.useDashboardStore(p=>{var R;return(R=p.dashboard)==null?void 0:R.id}),{switchEditorMode:u,setRunSql:g}=t.useEditorActions(),v=N.useMemo(()=>({cardId:o.id||null,frameId:m.id||null,sheetId:f||null,dashboardId:x||null}),[o.id,m.id,f,x]),b=N.useMemo(()=>({queryRequest:n==null?void 0:n.queryRequest,queryResponse:n==null?void 0:n.queryResponse,cardConfig:o.config,dataSource:o.dataSource,columns:n==null?void 0:n.columns,dashboardFilters:n==null?void 0:n.dashboardFilters,cardMetadata:v}),[n==null?void 0:n.queryRequest,n==null?void 0:n.queryResponse,n==null?void 0:n.columns,n==null?void 0:n.dashboardFilters,o.config,o.dataSource,v]),S=a&&c&&!!n,I=N.useMemo(()=>[{label:"Card ID",value:o.id||""},{label:"Frame ID",value:m.id||""},{label:"Sheet ID",value:f||""},{label:"Dashboard ID",value:x||""}],[o.id,m.id,f,x]),P=()=>{u("dev",{sqlToLoad:s}),setTimeout(()=>{g(!0)},100)},C=p=>b[p]!==void 0,A=N.useMemo(()=>{if(!l)return null;const p=b[l];if(p===void 0)return null;const R=l==="queryResponse"?Xa(p):{value:p},w=an(R.value);return w?{target:l,title:gt(l),json:w,truncationMessage:R.truncationMessage}:null},[l,b]),y=A?A.title:"Preview Payload",T=async p=>{const R=b[p];if(R===void 0)return t.ue.error(`No ${gt(p).toLowerCase()} available`),!1;const w=an(R);if(!w)return t.ue.error(`Unable to serialize ${gt(p).toLowerCase()}`),!1;try{return await Wa.writeTextToClipboard(w)?(t.ue.success(`${gt(p)} copied`),!0):(t.ue.error("Clipboard is not available"),!1)}catch(M){return console.error("Failed to copy debug payload",M),t.ue.error(`Unable to copy ${gt(p).toLowerCase()}`),!1}},E=async()=>A?T(A.target):!1,D=p=>{if(b[p]===void 0){t.ue.error(`No ${gt(p).toLowerCase()} available`);return}d(p)};return e.jsxs("div",{className:t.cn("flex min-h-0 flex-1 flex-col pt-3",r),children:[!h&&e.jsxs("div",{className:"mb-3 flex items-center gap-1.5",children:[e.jsxs(t.Button,{onClick:P,variant:"outline",size:"xs",children:[e.jsx(An,{className:"mr-1.5 h-3 w-3"}),"View in SQL Editor"]}),a&&e.jsxs(t.Button,{onClick:()=>i(!c),variant:"outline",size:"xs",children:[e.jsx(t.Info,{className:"mr-1.5 h-3 w-3"}),"Card Details"]})]}),c&&a&&e.jsx("div",{className:"mb-3 rounded-[6px] border border-border bg-card p-3",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-[12px] font-semibold uppercase tracking-[0.08em] text-foreground/70",children:"Card Information"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 rounded-[3px] p-0",onClick:()=>i(!1),children:e.jsx(Ae.CircleX,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"grid grid-cols-1 gap-2 md:grid-cols-2",children:I.map(p=>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:p.label}),e.jsx(t.CopyButton,{text:p.value,className:"h-6 w-6 shrink-0"})]}),e.jsx("code",{title:p.value||"N/A",className:"mt-1 block whitespace-normal break-all font-mono text-xs",children:p.value||"N/A"})]},p.label))}),S&&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"}),y,e.jsx(t.ChevronDown,{className:"ml-1.5 h-3.5 w-3.5"})]})}),e.jsx(t.DropdownMenuContent,{align:"start",className:"w-56",children:Ya.map(p=>e.jsx(t.DropdownMenuItem,{disabled:!C(p.target),onSelect:()=>D(p.target),className:t.cn(l===p.target&&"bg-accent"),children:p.label},`preview-${p.target}`))})]})}),A&&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:[A.title," Preview"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(t.CopyButton,{text:A.json,className:"h-6 w-6",ariaLabel:"Copy Payload",onCopy:E}),e.jsxs(t.Button,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>d(null),children:[e.jsx(Ae.CircleX,{className:"mr-1 h-3.5 w-3.5"}),"Hide"]})]})]}),A.truncationMessage&&e.jsx("p",{className:"text-xs text-muted-foreground",children:A.truncationMessage}),e.jsx("div",{className:"max-h-80 overflow-auto",children:e.jsx(t.CodeHighlighter,{code:A.json,language:"json"})})]})]})]})}),e.jsx("div",{className:"min-h-0 flex-1 overflow-auto",children:e.jsxs("div",{className:"overflow-hidden rounded-[6px] border border-border bg-card",children:[e.jsxs("div",{className:"flex h-9 items-center justify-between border-b border-border px-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"rounded-[3px] bg-muted px-1.5 py-0.5 font-mono text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"SQL"}),e.jsx("span",{className:"text-[12px] text-muted-foreground",children:"Generated query"})]}),e.jsx(t.CopyButton,{text:s,className:"h-6 w-6 rounded-[3px] px-0 text-muted-foreground hover:bg-muted hover:text-foreground"})]}),e.jsx("div",{className:"group relative overflow-auto px-3 py-2 text-[12px] leading-[1.5] text-foreground/80",children:e.jsx(t.CodeHighlighter,{code:s,language:"sql",wrapLongLines:!0})})]})})]})}const Za=/\{\{-?\s*filters\s*\|\s*where\s*-?\}\}/i,er=/\{\{-?\s*filters\s*\|\s*and\s*-?\}\}/i,tr=/\bwhere\b/i;function sr(s){return s!=null&&s.trim()?Za.test(s)||er.test(s):!1}function nr(s){return!(s!=null&&s.trim())||sr(s)?null:tr.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 ar(s){const{request:a,mode:n="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.",n==="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?n==="refine"?`Current SQL (must refine):
|
|
165
|
+
${r}`:`Current SQL (revise if useful):
|
|
166
|
+
${r}`:"",`User request:
|
|
167
|
+
${a}`].filter(Boolean).join(`
|
|
168
|
+
|
|
169
|
+
`)}function rr(s){const{request:a,failedSql:n,errorMessage:r,errorCode:c,selectedDatabaseName:i,selectedSchemaName:l,selectedTableName:d,contextEntityLabels:o}=s,m=[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.",m.length>0?`Context:
|
|
170
|
+
${m.join(`
|
|
171
|
+
`)}`:"",`Original user request:
|
|
172
|
+
${a}`,`Previous SQL draft:
|
|
173
|
+
${n}`,`Validation failure${c?` (${c})`:""}:
|
|
174
|
+
${r}`].filter(Boolean).join(`
|
|
175
|
+
|
|
176
|
+
`)}function lr(s,a){typeof window>"u"||window.dispatchEvent(new CustomEvent("semaphor:inline-query-writer",{detail:{event:s,...a,timestamp:Date.now()}}))}const es={runId:0,phase:"idle",attempt:0,activeStep:"",timelineSteps:[],lastValidation:null,finalOutcome:"idle",hasTools:!1};function or(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 rn(s){let a=0;for(let n=0;n<s.length;n+=1)a=(a<<5)-a+s.charCodeAt(n),a|=0;return String(a)}function ln(s){return s==="getTableColumns"?"Discovering columns":s==="getDomainRelationships"?"Resolving relationships":s==="getChartSQLSyntax"?"Reviewing SQL syntax":s==="getUserSql"?"Inspecting current query":"Analyzing context"}function ir(s,a){return s===t.SELF_HEAL_TIMELINE_STEP&&a>0?`${t.SELF_HEAL_TIMELINE_STEP} ${a}/${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 on(s){var a;for(let n=s.length-1;n>=0;n-=1){const r=s[n];if(r.role!=="user")continue;const c=(a=r.metadata)==null?void 0:a.inlineRunToken;if(typeof c=="string"&&c.length>0)return c}}function cr(s){if(!s)return"";const a=s.trim(),n=s.match(/```sql\s*([\s\S]*?)```/i);if(n!=null&&n[1])return n[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(a)?a:""}function cn(s){for(let a=s.length-1;a>=0;a-=1){const n=s[a];if(!(n.role!=="assistant"||!Array.isArray(n.parts)))for(let r=n.parts.length-1;r>=0;r-=1){const c=n.parts[r];if((c==null?void 0:c.type)!=="text"||typeof(c==null?void 0:c.text)!="string")continue;const i=cr(c.text);if(i)return i}}return""}function dr({currentSql:s,currentPython:a,selectedDatabaseName:n,selectedSchemaName:r,selectedTableName:c,onApplySql:i,onOpenFullAssistant:l}){var Mt,Nt;const{authToken:d,tokenProps:o}=t.useSemaphorContext(),m=(Mt=t.useDashboardQuery().data)==null?void 0:Mt.assistantProfileId,h=t.useEditorStore($=>$.isDevMode),f=t.useEditorStore($=>$.selectedConnectionId),x=t.useEditorStore($=>{var Y;return(Y=$.card.dataSource)==null?void 0:Y.selectedEntities}),u=t.useAIInteractionStore($=>$.currentAIContext.selectedEntities),g=u.length,{setCurrentAIContext:v}=t.useAIActions(),[b,S]=N.useState(""),[I,P]=N.useState(""),[C,A]=N.useState(""),[y,T]=N.useState("draft"),[E,D]=N.useState("draft"),[p,R]=N.useState(""),[w,M]=N.useState(!1),[F,j]=N.useState({status:"idle"}),[L,k]=N.useState(es),[O,z]=N.useState(!1),[V,B]=N.useState(()=>Ot("inline-query-session")),_=N.useRef(null),G=N.useRef(null),q=N.useRef(null),H=N.useRef(0),te=N.useRef(0),ie=N.useRef(Ot("inline-run-token")),oe=N.useRef(V),de=N.useRef(new Set),he=N.useRef(new Map),me=N.useRef(0),se=N.useRef(""),je=N.useRef(!1),be=N.useRef(!1),ye=N.useRef(es),X=N.useRef(!1),ge=N.useRef(null),Z=N.useRef(()=>{}),Te=(Nt=o.apiServiceUrl)==null?void 0:Nt.replace(/\/$/,""),Le=Te?`${Te}/v1/sql/validate`:"/v1/sql/validate",De=N.useCallback($=>{k(Y=>{const J=$(Y);return ye.current=J,J})},[]),Ee=N.useCallback(($,Y)=>{De(J=>J.runId===$?Y(J):J)},[De]),Ie=N.useCallback($=>te.current===$&&!de.current.has($),[]),K=N.useCallback(($,Y,J)=>{Ee($,ce=>{const pe=ce.timelineSteps.includes(Y)?ce.timelineSteps:[...ce.timelineSteps,Y];return{...ce,phase:(J==null?void 0:J.phase)||ce.phase,attempt:typeof(J==null?void 0:J.attempt)=="number"?J.attempt:ce.attempt,activeStep:Y,timelineSteps:pe,finalOutcome:(J==null?void 0:J.finalOutcome)||ce.finalOutcome,hasTools:J!=null&&J.hasTools?!0:ce.hasTools}})},[Ee]),re=N.useCallback(()=>{const $=te.current+1,Y=Ot("inline-run-token"),J=Ot("inline-query-session");return te.current=$,ie.current=Y,oe.current=J,B(J),de.current=new Set,he.current=new Map,me.current=0,se.current="",X.current=!1,De(()=>({runId:$,phase:"drafting",attempt:0,activeStep:"Drafting SQL",timelineSteps:["Drafting SQL"],lastValidation:null,finalOutcome:"drafting",hasTools:!1})),{runId:$,runToken:Y,chatSessionId:J}},[De]),ve=N.useCallback(()=>{if(je.current||be.current||g>0)return;const $=x||[];if($.length===0)return;const Y=t.useAIInteractionStore.getState().currentAIContext;v({...Y,selectedEntities:$}),be.current=!0},[g,x,v]),ee=N.useCallback(()=>{je.current=!0},[]),Q=N.useCallback(($,Y,J)=>{lr($,{runId:Y,attemptCount:typeof(J==null?void 0:J.attemptCount)=="number"?J.attemptCount:me.current,errorCode:J==null?void 0:J.errorCode,hasTools:typeof(J==null?void 0:J.hasTools)=="boolean"?J.hasTools:L.hasTools,entityCount:g,finalOutcome:(J==null?void 0:J.finalOutcome)||L.finalOutcome})},[g,L.finalOutcome,L.hasTools]),ae=N.useCallback(($,Y)=>{const J=q.current;if(!J)return;const ce={inlineRunToken:Y};J({role:"user",parts:[{type:"text",text:$}],metadata:ce},{metadata:ce})},[]);N.useEffect(()=>{const $=ge.current;!$||$.sessionId!==V||(ge.current=null,ae($.message,$.runToken))},[V,ae]);const ue=V,Se=N.useCallback(async({toolCall:$})=>{var Pe,Qe,rt,st,ze,ft;if(ue!==oe.current)return;const Y=String($.toolName||"").trim();if(!Y)return;const J=te.current;if(!Ie(J)){(Pe=G.current)==null||Pe.call(G,{tool:Y,toolCallId:$.toolCallId,output:{status:"error",message:"Inline run is no longer active; ignoring tool output."}});return}if(Y==="getUserSql"){K(J,ln(Y),{hasTools:!0}),Q("inline_tool_step",J,{hasTools:!0}),(Qe=G.current)==null||Qe.call(G,{tool:Y,toolCallId:$.toolCallId,output:{status:"success",sql:s||"",python:a||""}});return}const ce=t.INLINE_BLOCKED_MUTATING_TOOLS.has(Y),pe=t.INLINE_ALLOWED_READ_ONLY_TOOLS.has(Y);if(ce||!pe){(rt=G.current)==null||rt.call(G,{tool:Y,toolCallId:$.toolCallId,output:{status:"error",message:"This action is unavailable in inline draft mode. Open Full Assistant for this action."}});return}const fe=ln(Y);K(J,fe,{phase:L.phase==="self-healing"?"self-healing":"drafting",hasTools:!0}),Q("inline_tool_step",J,{hasTools:!0});const Fe=((st=$.input)==null?void 0:st.sql)??((ze=$.args)==null?void 0:ze.sql);typeof Fe=="string"&&Fe.trim().length>0&&(X.current=!1,A(Fe.trim())),(ft=G.current)==null||ft.call(G,{tool:Y,toolCallId:$.toolCallId,output:{status:"success",message:"Read-only tool result received."}})},[a,s,Q,L.phase,Ie,ue,K]),Ne=N.useCallback(({message:$,messages:Y})=>{if(ue!==oe.current)return;const J=on(Y);if(!J||J!==ie.current)return;const ce=te.current;if(!Ie(ce))return;const pe=cn([$])||cn(Y);if(pe){X.current=!1,A(pe.trim());return}X.current&&ye.current.phase==="self-healing"&&Z.current(ce)},[Ie,ue]),Oe=N.useCallback($=>{if(ue!==oe.current)return;const Y=te.current;Ie(Y)&&X.current&&ye.current.phase==="self-healing"&&Z.current(Y)},[Ie,ue]),{setMessages:Ve,sendMessage:Ye,addToolResult:Je,status:We,stop:ne,error:ke,clearError:Be}=t.useChat({id:V,transport:new t.DefaultChatTransport({api:`${o.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${d==null?void 0:d.accessToken}`}),body:()=>{const $=t.useAIInteractionStore.getState();return{assistantId:"editor-assistant",assistantProfileId:m,isDevMode:h,aiContext:$.currentAIContext,reasoningEffort:$.reasoningEffort,showReasoning:!1}},credentials:"omit",prepareSendMessagesRequest:({messages:$,body:Y,requestMetadata:J})=>{const ce=J==null?void 0:J.inlineRunToken,pe=on($);return{body:{...Y,inlineRunToken:ce||pe,messages:t.cleanupIncompleteMessages($)}}}}),onToolCall:Se,onFinish:Ne,onError:Oe,sendAutomaticallyWhen:t.lastAssistantMessageIsCompleteWithToolCalls});G.current=Je,q.current=Ye;const Ce=!["ready","error"].includes(We),Ge=(ke==null?void 0:ke.message)||"Unable to generate a SQL draft right now. Try again.",we=N.useCallback($=>{const Y=te.current,J=ye.current.phase;if(!(J==="drafting"||J==="self-healing"||J==="validating")){$==="stopped"&&Ce&&ne();return}de.current.add(Y),X.current=!1,H.current+=1,se.current="",j({status:"idle"}),A(""),Be(),Ve([]),Ee(Y,pe=>({...pe,phase:"idle",activeStep:"",finalOutcome:"cancelled"})),Q("inline_self_heal_stopped",Y,{finalOutcome:"cancelled"}),(Ce||$==="stopped")&&ne()},[Be,Q,Ce,Ve,ne,Ee]),jt=N.useCallback(async($,Y)=>{var ce;if(!Ie(Y))return null;const J=H.current+1;H.current=J,K(Y,"Validating SQL",{phase:"validating"}),j({status:"validating"});try{const pe=await t.postRequestRegular(Le,(d==null?void 0:d.accessToken)||"",{sql:$,connectionId:f||void 0});if(H.current!==J||!Ie(Y))return null;if((pe==null?void 0:pe.valid)===!0)return j({status:"valid",message:"SQL validation passed."}),Ee(Y,Pe=>({...Pe,phase:"ready",finalOutcome:"validated",lastValidation:{valid:!0}})),Q("inline_draft_validated",Y,{finalOutcome:"validated"}),{status:"valid"};const fe=or(pe==null?void 0:pe.errorCode)||"UNKNOWN",Fe=typeof(pe==null?void 0:pe.error)=="string"&&pe.error||typeof((ce=pe==null?void 0:pe.details)==null?void 0:ce.error)=="string"&&pe.details.error||"SQL validation failed. Please revise the query draft.";return j({status:"invalid",message:Fe,errorCode:fe}),Ee(Y,Pe=>({...Pe,lastValidation:{valid:!1,error:Fe,errorCode:fe}})),Q("inline_validation_failed",Y,{errorCode:fe,finalOutcome:"validation_failed"}),{status:"invalid",error:Fe,errorCode:fe}}catch(pe){if(H.current!==J||!Ie(Y))return null;const fe=t.getRequestErrorMessage(pe,"Validation service unavailable. You can still replace and run.");return j({status:"error",message:fe,errorCode:"SQL_CONNECTION_ERROR"}),Ee(Y,Fe=>({...Fe,phase:"error",finalOutcome:"error",lastValidation:{valid:!1,error:fe,errorCode:"SQL_CONNECTION_ERROR"}})),{status:"error",error:fe,errorCode:"SQL_CONNECTION_ERROR"}}},[d==null?void 0:d.accessToken,Q,Ie,f,Le,Ee,K]),Xe=N.useCallback(($,Y,J,ce)=>{let pe=J,fe="validation_failed",Fe="Validating SQL";Y==="attempt_limit"?(pe=`Couldn't auto-fix after ${t.MAX_SELF_HEAL_ATTEMPTS} attempts. ${J}`,fe="self_heal_exhausted",Fe=`Auto-fix stopped (${t.MAX_SELF_HEAL_ATTEMPTS} attempts)`):Y==="duplicate"&&(pe=`Auto-fix stopped (repeated validation failure). ${J}`,fe="self_heal_duplicate_stopped",Fe="Auto-fix stopped (repeated failure)"),j({status:"invalid",message:pe,errorCode:ce}),K($,Fe,{phase:"error",finalOutcome:fe}),Ee($,Pe=>({...Pe,phase:"error",finalOutcome:fe,lastValidation:{valid:!1,error:pe,errorCode:ce}})),Y!=="terminal"&&Q("inline_self_heal_stopped",$,{errorCode:ce,finalOutcome:fe}),X.current=!1},[Q,Ee,K]),Tt=N.useCallback($=>{const Y="Auto-fix stopped (no SQL returned). Open Full Assistant to continue.",J="self_heal_no_draft";j({status:"invalid",message:Y,errorCode:"UNKNOWN"}),K($,"Auto-fix stopped (no SQL returned)",{phase:"error",finalOutcome:J}),Ee($,ce=>({...ce,phase:"error",finalOutcome:J,lastValidation:{valid:!1,error:Y,errorCode:"UNKNOWN"}})),Q("inline_self_heal_stopped",$,{errorCode:"UNKNOWN",finalOutcome:J}),X.current=!1},[Q,Ee,K]);Z.current=Tt,N.useEffect(()=>{const $=C.trim(),Y=te.current;if(!$){if(H.current+=1,se.current="",ye.current.phase==="error")return;j({status:"idle"});return}if(!Ie(Y)||Ce)return;const J=`${Y}:${me.current}:${rn($)}`;if(se.current===J)return;se.current=J;let ce=!1;return(async()=>{const fe=await jt($,Y);if(!fe||ce||!Ie(Y)||fe.status!=="invalid")return;if(!t.RECOVERABLE_SQL_ERROR_CODES.has(fe.errorCode)){Xe(Y,"terminal",fe.error,fe.errorCode);return}const Fe=`${rn($)}::${fe.errorCode}`,Pe=(he.current.get(Fe)||0)+1;if(he.current.set(Fe,Pe),Pe>=2){Xe(Y,"duplicate",fe.error,fe.errorCode);return}if(me.current>=t.MAX_SELF_HEAL_ATTEMPTS){Xe(Y,"attempt_limit",fe.error,fe.errorCode);return}const Qe=me.current+1;me.current=Qe,K(Y,t.SELF_HEAL_TIMELINE_STEP,{phase:"self-healing",attempt:Qe}),Q("inline_self_heal_attempt",Y,{attemptCount:Qe,errorCode:fe.errorCode}),X.current=!0,Be(),Ve([]),A("");const rt=u.map(ze=>{const ft=ze!=null&&ze.database?`${ze.database}.`:"",Jt=ze!=null&&ze.schema?`${ze.schema}.`:"",Wt=(ze==null?void 0:ze.name)||"unknown";return`${ft}${Jt}${Wt}`}),st=rr({request:I,failedSql:$,errorMessage:fe.error,errorCode:fe.errorCode,selectedDatabaseName:n||"",selectedSchemaName:r||"",selectedTableName:c||"",contextEntityLabels:rt});ae(st,ie.current)})(),()=>{ce=!0}},[Be,u,Q,Ce,Ie,I,C,n,r,c,ae,Ve,Xe,K,jt]);const Ue=(s==null?void 0:s.trim())||"",Et=N.useCallback(($="draft")=>{if(Ce)return;const Y=b.trim();if(!Y)return;const J=$==="refine"&&Ue?"refine":"draft",ce=J==="refine"?Ue:"",pe=Ue,{runId:fe,runToken:Fe,chatSessionId:Pe}=re();Q("inline_draft_started",fe,{attemptCount:0,hasTools:!1,finalOutcome:"drafting"}),ve(),Be(),P(Y),A(""),T(J),R(ce),M(!1),j({status:"idle"}),H.current+=1,Ve([]),z(!0);const Qe=ar({request:Y,mode:J,currentSql:pe,selectedTableName:c||"",selectedSchemaName:r||"",selectedDatabaseName:n||""});ge.current={sessionId:Pe,message:Qe,runToken:Fe}},[re,Be,Ue,Q,Ce,b,ve,n,r,c,Ve]),ct=N.useCallback($=>{const Y=C.trim();Y&&(i(Y,$),$||z(!1))},[i,C]),Ze=C.trim().length>0,It=["valid","invalid","error"].includes(F.status),vt=Ze&&It,Kt=F.status==="invalid",kt=F.status==="validating",dt=Ze&&I.length>0&&I===b.trim(),ut=Ue.length>0,mt=b.length>0,xt=dt&&y==="draft",$e=dt&&y==="refine"&&p===Ue,et=E==="refine"&&!ut?"draft":E,tt=(et==="refine"?$e:xt)?"Open composer preview":"Generate composer SQL",Dt=b.trim().length>0||I.trim().length>0||Ze||F.status!=="idle"||L.timelineSteps.length>0,yt=N.useCallback(($="draft")=>{if(Ce)return;if(($==="refine"?$e:xt)&&!O){ve(),z(!0);return}Et($)},[xt,$e,Et,Ce,O,ve]),ht=N.useCallback(()=>{ve(),z(!0)},[ve]),Ut=N.useCallback($=>{we("cancelled"),S($)},[we]),Ht=N.useCallback(()=>{Ce||(we("cancelled"),X.current=!1,H.current+=1,se.current="",me.current=0,S(""),P(""),A(""),T("draft"),D("draft"),R(""),M(!1),j({status:"idle"}),Be(),Ve([]),De($=>({...es,runId:$.runId})))},[we,Be,Ce,Ve,De]),Qt=N.useCallback($=>{$||we("cancelled"),z($)},[we]),Ke=L.timelineSteps.findIndex($=>$===L.activeStep),At=L.phase==="self-healing"?"Fixing validation issue":L.phase==="validating"?"Validating SQL":L.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:_,className:"relative flex h-7 min-w-[320px] flex-1 items-center",children:[e.jsx(t.Input,{value:b,onChange:$=>Ut($.target.value),onFocus:ht,onClick:ht,onKeyDown:$=>{$.key==="Enter"&&($.preventDefault(),yt(et))},placeholder:"Type your question...",className:["h-7 rounded-[5px] border border-border/60 bg-background text-[12px] shadow-none focus-visible:border-ring focus-visible:ring-0",mt?"pr-[56px]":"pr-9"].join(" ")}),e.jsxs(t.Popover,{open:O,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:$=>{$.preventDefault(),we("cancelled"),S("")},disabled:Ce,"aria-label":"Clear input",title:"Clear input",children:e.jsx(t.X,{className:"size-3.5"})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"size-6 p-0",onClick:$=>{$.preventDefault(),yt(et)},disabled:Ce,"aria-label":tt,title:tt,children:e.jsx(ka,{className:"size-3.5"})})]}),e.jsx(t.PopoverContent,{align:"start",alignOffset:0,side:"bottom",sideOffset:8,className:"w-[min(92vw,var(--radix-popover-trigger-width))] max-w-[760px] p-2.5",onOpenAutoFocus:$=>{$.preventDefault()},onInteractOutside:$=>{var J;const Y=$.target;Y&&((J=_.current)!=null&&J.contains(Y))&&$.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-[13px] font-medium",children:"Composer"}),I&&e.jsx("p",{className:"line-clamp-2 text-[11px] text-muted-foreground",children:I})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"inline-flex h-7 items-center rounded-[5px] border border-border/60 bg-background p-0.5",children:[e.jsx(t.Button,{type:"button",variant:"ghost",className:["h-6 rounded-[4px] px-2 text-[12px]",et==="draft"?"bg-accent text-foreground":"text-muted-foreground hover:text-foreground"].join(" "),onClick:()=>{D("draft"),M(!1)},children:"Draft New"}),e.jsx(t.Button,{type:"button",variant:"ghost",className:["h-6 rounded-[4px] px-2 text-[12px]",et==="refine"?"bg-accent text-foreground":"text-muted-foreground hover:text-foreground"].join(" "),onClick:()=>D("refine"),disabled:!ut,children:"Refine Current"})]}),e.jsx("div",{className:"h-4 w-px bg-border/70"}),Ce&&e.jsx(t.Button,{variant:"ghost",size:"xs",onClick:()=>{we("stopped")},children:"Stop"}),!Ce&&e.jsx(t.Button,{variant:"ghost",size:"xs",onClick:Ht,disabled:!Dt,children:"Clear"})]})]}),L.timelineSteps.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[L.timelineSteps.map(($,Y)=>{const J=$===L.activeStep&&["drafting","validating","self-healing"].includes(L.phase),ce=!J&&Ke>=0&&Y<Ke;return e.jsx("span",{className:["rounded-full border px-2 py-0.5 text-[11px]",J?"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:ir($,L.attempt)},`${$}-${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})}),(Ce||L.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]}),ke&&e.jsx("div",{className:"rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-xs text-destructive",children:Ge}),y==="refine"&&p&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-[5px] border border-border/60 bg-muted/20 px-2.5 py-1.5 text-[11px]",children:[e.jsx("span",{className:"text-muted-foreground",children:"Refining editor SQL"}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"xs",onClick:()=>M($=>!$),children:w?"Hide base SQL":"View base SQL"})]}),w&&e.jsx("div",{className:"max-h-[120px] overflow-auto rounded-[5px] border border-border/60",children:e.jsx(t.CodeHighlighter,{code:p,language:"sql"})})]}),vt?e.jsxs("div",{className:"space-y-1",children:[y==="refine"&&e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Refined SQL"}),e.jsx("div",{className:"max-h-[200px] overflow-auto rounded-[5px] border border-border/60",children:e.jsx(t.CodeHighlighter,{code:C,language:"sql"})})]}):Ze?e.jsx("div",{className:"rounded-[5px] border border-dashed border-border/70 px-3 py-2 text-[11px] text-muted-foreground",children:"Validating SQL draft before preview."}):!Ce&&e.jsx("div",{className:"rounded-[5px] border border-dashed border-border/70 px-3 py-2 text-[11px] 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-1.5",children:[e.jsx(t.Button,{variant:"outline",size:"xs",onClick:l,children:"Open Full Assistant"}),e.jsx(t.Button,{variant:"secondary",size:"xs",disabled:Ce||!vt,onClick:()=>ct(!1),children:"Replace SQL"}),e.jsx(t.Button,{size:"xs",disabled:Ce||!vt||kt||Kt,onClick:()=>ct(!0),children:"Replace & Run"})]})]})})]})]})}function ur(){var be,ye;const s=t.useQueryClient(),[a,n]=N.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 ge,Z;return((Z=(ge=X.dashboard)==null?void 0:ge.filters)==null?void 0:Z.length)??0}),{cardFilterValues:m}=t.useCardFilterValues((c==null?void 0:c.id)??""),h=t.useEditorStore(X=>X.inlineFilterValuesMap[(c==null?void 0:c.id)??""]),f=N.useMemo(()=>t.findCustomVisualConfigCard(r,c),[r,c]),{manifest:x}=t.useCustomVisual(((be=f==null?void 0:f.customCardPreferences)==null?void 0:be.url)||""),u=N.useMemo(()=>{var X;return(X=x==null?void 0:x.visuals)==null?void 0:X.find(ge=>{var Z;return ge.name===((Z=f==null?void 0:f.customCardPreferences)==null?void 0:Z.componentName)})},[x,(ye=f==null?void 0:f.customCardPreferences)==null?void 0:ye.componentName]),g=t.resolveMultiInputType(f,u),v=N.useMemo(()=>t.getCustomVisualInputCards({frame:r,configCard:f,isMultiInputVisual:g==="multiple"}),[r,f,g]),b=N.useMemo(()=>{const X=v.findIndex(ge=>(ge==null?void 0:ge.id)===(c==null?void 0:c.id));return X<0?-1:t.getSlotIndexForCard(c,X)},[v,c]),S=N.useMemo(()=>!f||g!=="multiple"||b<0?c.type:t.getEffectiveCardTypeForSlot(c,b,u==null?void 0:u.slots)??c.type,[f,g,b,c,u==null?void 0:u.slots]),I=N.useMemo(()=>S!==c.type?{...c,type:S}:c,[c,S]),P=N.useMemo(()=>o===0?null:nr(c==null?void 0:c.sql),[c==null?void 0:c.sql,o]),C=N.useRef(!0),{setCardCustomCfg:A,setQueryResultColumns:y,setCardSql:T,setTempQueryData:E,setPythonStdOut:D,setCardPreferences:p,setCardType:R,setCardPython:w,setShowAIDialog:M,setCard:F,updateCardInFrame:j}=t.useEditorActions();t.useEditorStore(X=>X.onSave),t.useEditorStore(X=>X.onClose),t.useEditorStore(X=>X.actions.setSqlGen);const L=t.useEditorStore(X=>X.runSql),k=t.useEditorStore(X=>X.actions.setRunSql),O=t.useEditorStore(X=>X.actions.setIsSqlRunning),{data:z,isLoading:V,isFetching:B,isSuccess:_,isError:G,error:q,errorSql:H,queryKey:te,refetch:ie,errorMessage:oe}=t.useEditorCardQuery(I),de=N.useRef(te);de.current=te,N.useEffect(()=>{if(z&&(z.rowLimitExceeded&&t.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),D((z==null?void 0:z.output)||""),z.records.length>0)){const{dimensionKeys:X}=t.getKeys(z.records);y(X)}},[z,y,D]),N.useEffect(()=>{(V||B)&&O(!0),(G||_)&&O(!1),G&&(y([]),D(""))},[V,B,z,D,G,_,O,y,q]),N.useEffect(()=>{L&&(s.getQueryData(te)||ie(),k(!1))},[L,ie,k,te,s]);const he=N.useRef(ie);he.current=ie,N.useEffect(()=>{if(C.current){C.current=!1;return}he.current()},[h]);function me(X,ge){T(X),ge&&k(!0)}function se(){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:a?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(Ha,{})}),a&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),a&&e.jsxs(e.Fragment,{children:[e.jsx(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(Ja,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function je(){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:[P&&e.jsxs("div",{className:"mb-1.5 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:P.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:V||B,onClick:()=>{it.flushPendingEditorDrafts(),setTimeout(()=>{s.removeQueries({queryKey:de.current,exact:!0}),k(!0)},0)},className:"shrink-0",size:"xs",children:[V||B?e.jsx(t.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(t.Play,{className:"h-3.5 w-3.5"}),"Run"]}),(z==null?void 0:z.sql)&&!oe&&e.jsxs(t.HoverCard,{openDelay:300,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,children:e.jsx(t.Info,{className:"h-3.5 w-3.5 shrink-0 cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(t.HoverCardContent,{align:"start",className:"w-[500px] p-0",children:e.jsx(On,{sql:z.sql})})]}),e.jsx(Ae.EditorClearButton,{}),e.jsxs(t.Toggle,{pressed:a,onPressedChange:X=>n(X),className:"h-7 gap-1.5 rounded-[5px] px-2.5 text-[12px]",size:"sm",variant:"outline",children:[e.jsx(Ga,{className:"h-3.5 w-3.5 text-foreground/70"}),"Python"]}),e.jsx(dr,{currentSql:c==null?void 0:c.sql,currentPython:c==null?void 0:c.python,selectedDatabaseName:i,selectedSchemaName:l,selectedTableName:d,onApplySql:me,onOpenFullAssistant:()=>M(!0)}),e.jsx("div",{className:"ml-auto flex shrink-0 items-center gap-3",children:m&&m.length>0&&e.jsxs(t.HoverCard,{openDelay:200,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",size:"xs",className:"px-2",children:[e.jsx(t.Filter,{className:"h-3.5 w-3.5"}),e.jsx(t.Badge,{variant:"secondary",className:"h-4 min-w-4 rounded-[4px] px-1 text-[10px] font-medium",children:m.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-[13px] font-medium",children:"Active Dashboard Filters"}),e.jsx(t.CodeHighlighter,{code:JSON.stringify(m,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:se()}),je()]})}function mr(s,a){var i;let n=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[a];if(!(d==null||d==="")){if(r++,typeof d=="number"||typeof d=="bigint")n++;else if(typeof d=="boolean")return"boolean"}}return r===0?"null":n/r>.7?"number":"text"}function xr(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 hr({data:s,card:a,paginationMetadata:n,onPaginationChange:r,onPageSizePreferenceChange:c,onSortChange:i,isLoading:l}){var E,D,p,R,w,M;const d=N.useMemo(()=>Object.keys(s[0]??{}),[s]),o=a.sql&&!((D=(E=a.preferences)==null?void 0:E.tablePrefs)!=null&&D.enableDevModePagination)?(R=(p=a.preferences)==null?void 0:p.tablePrefs)==null?void 0:R.pageSize:void 0,m=N.useMemo(()=>{var F;return t.sortByColumnsToSortState((F=a.config)==null?void 0:F.sortByColumns)},[(w=a.config)==null?void 0:w.sortByColumns]),{canSort:h,canUseLocalSorting:f,handlePaginationChange:x,handleSortChange:u,pagination:g,paginationMode:v,sorting:b}=t.useTableQueryState({card:a,dataLength:s.length,onPaginationChange:r,onSortChange:i,pageSize:o,paginationMetadata:n,sortState:m}),S=N.useMemo(()=>b.filter(F=>d.includes(F.id)),[b,d]),I=N.useMemo(()=>{const F={};for(const j of d)F[j]=mr(s,j);return F},[d,s]),P=N.useMemo(()=>d.map(F=>{const L=I[F]==="number";return{accessorKey:F,enableSorting:h,header:({column:k})=>{const O=k.getIsSorted();return e.jsxs("div",{className:t.cn("flex select-none items-center gap-1.5 transition-colors",k.getCanSort()&&"cursor-pointer hover:text-foreground",L&&"justify-end"),onClick:()=>k.getCanSort()&&k.toggleSorting(k.getIsSorted()==="asc"),children:[e.jsx("span",{children:F}),O==="asc"?e.jsx(t.ArrowUpIcon,{className:"h-3.5 w-3.5 shrink-0 text-foreground"}):O==="desc"?e.jsx(t.ArrowDownIcon,{className:"h-3.5 w-3.5 shrink-0 text-foreground"}):k.getCanSort()?e.jsx(t.ChevronsUpDown,{className:"h-3 w-3 shrink-0 opacity-0 transition-opacity group-hover/header:opacity-50"}):null]})},cell:({getValue:k})=>{const O=k(),z=O===null;return e.jsx("div",{className:t.cn("whitespace-pre-wrap break-all",L&&"text-right tabular-nums",z&&"text-muted-foreground/50 italic"),children:xr(O)})}}}),[h,I,d]),C=Math.max(P.length,1),A=t.useReactTable({data:s,columns:P,getCoreRowModel:t.getCoreRowModel(),getPaginationRowModel:v==="client"?t.getPaginationRowModel():void 0,onSortingChange:u,getSortedRowModel:f?t.getSortedRowModel():void 0,onPaginationChange:v==="disabled"?void 0:x,manualPagination:v==="server"||v==="disabled",manualSorting:!f,pageCount:v==="server"&&n?n.pageCount:void 0,state:{sorting:S,pagination:g}}),y=v==="server"&&n?n.totalCount:s.length,T=v!=="disabled"&&(v==="server"||y>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:A.getHeaderGroups().map(F=>e.jsx(t.TableRow,{className:"border-b-0 hover:bg-transparent",children:F.headers.map(j=>{const k=I[j.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",k&&"text-right"),children:j.isPlaceholder?null:t.flexRender(j.column.columnDef.header,j.getContext())},j.id)})},F.id))}),e.jsx(t.TableBody,{className:"font-mono",children:(M=A.getRowModel().rows)!=null&&M.length?A.getRowModel().rows.map((F,j)=>e.jsx(t.TableRow,{className:t.cn("h-[34px] border-b border-border/40 transition-colors",j%2===1&&"bg-muted/20"),"data-state":F.getIsSelected()&&"selected",children:F.getVisibleCells().map(L=>{const O=I[L.column.id]==="number";return e.jsx(t.TableCell,{className:t.cn("px-3 py-1.5 text-xs",O&&"text-right"),children:t.flexRender(L.column.columnDef.cell,L.getContext())},L.id)})},F.id)):e.jsx(t.TableRow,{children:e.jsx(t.TableCell,{colSpan:C,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:T?e.jsx(t.DataTablePagination,{totalColumns:d.length,pageCount:v==="server"&&n?n.pageCount:A.getPageCount(),pageIndex:A.getState().pagination.pageIndex,pageSize:A.getState().pagination.pageSize,rowCount:y,selectedRowCount:0,setPageIndex:A.setPageIndex,setPageSize:A.setPageSize,canPreviousPage:v==="server"&&n?n.hasPrevPage:A.getCanPreviousPage(),canNextPage:v==="server"&&n?n.hasNextPage:A.getCanNextPage(),previousPage:A.previousPage,nextPage:A.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:[y.toLocaleString()," ",y===1?"row":"rows"," · ",d.length," ",d.length===1?"column":"columns"]}),S.length>0&&e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["Sorted by"," ",e.jsx("span",{className:"font-medium text-foreground/70",children:S[0].id})," ",S[0].desc?"↓":"↑"]})]})})]})}const dn=[{value:"table",label:"Table"},{value:"aggregateTable",label:"Aggregate"},{value:"pivotTable",label:"Pivot"},{value:"detailTable",label:"Detail"}];function pr({className:s}){const a=t.useEditorStore(u=>u.card),n=t.useEditorStore(u=>u.frame),r=t.useEditorStore(u=>u.editorContext),c=Ae.useEffectiveEditorCardType(),{setCard:i,updateCardInFrame:l}=t.useEditorActions(),d=(r==null?void 0:r.type)==="documentSection"?dn.filter(u=>["table","pivotTable"].includes(u.value)):dn,o=["table","aggregateTable","pivotTable","detailTable"].includes(c),m=t.hasValidCardConfig(a.config),h=t.isCustomVisualConfigCard(a,n.cards);if(!o||!m||h)return null;const f=u=>{if(u===c||h)return;const g=u,v=a.config??{},b=x(c,g,v),S={...a,type:g,config:b};i(S),l(S)},x=(u,g,v)=>{var S;if(u===g)return v;if(g==="detailTable"){const I=y=>y==null?void 0:y.toLowerCase().replace(/\s+/g,"").trim(),P=(y,T)=>{const E=[I(y.label),I(y.qualifiedFieldName),I(y.name)].filter(Boolean),D=[I(T.label),I(T.qualifiedFieldName),I(T.name)].filter(Boolean);return E.some(p=>D.includes(p))},C=(v.groupByColumns||[]).map(y=>({...y,role:"detail"})),A=((S=v.sortByColumns)==null?void 0:S.filter(y=>C.some(T=>P(y,T))))??[];return{...v,detailTableBackup:{groupByColumns:v.groupByColumns,metricColumns:v.metricColumns,pivotByColumns:v.pivotByColumns,sortByColumns:v.sortByColumns,rowAggregates:v.rowAggregates,columnAggregates:v.columnAggregates,comparisonType:v.comparisonType},detailColumns:C,groupByColumns:[],metricColumns:[],pivotByColumns:[],sortByColumns:A,rowAggregates:[],columnAggregates:[],comparisonType:"none"}}let b=v;if(u==="detailTable")if(v.detailTableBackup)b={...v,...v.detailTableBackup,detailColumns:[],detailTableBackup:void 0};else{const I=(v.detailColumns||[]).map(P=>({...P,role:"groupby"}));b={...v,groupByColumns:I,detailColumns:[]}}return g==="aggregateTable"?{...b,pivotByColumns:[]}:b};return e.jsx("div",{role:"tablist",className:t.cn("flex items-center gap-5",s),children:d.map(u=>{const g=c===u.value;return e.jsx("button",{type:"button",role:"tab","aria-selected":g,onClick:()=>f(u.value),className:t.cn("-mb-px flex h-9 items-center border-b-2 text-[12px] transition-colors",g?"border-foreground font-medium text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),children:u.label},u.value)})})}const un="text-[11px] text-muted-foreground underline-offset-2 hover:text-foreground hover:underline";function us({error:s,errorSql:a,errorTitle:n="Unable to load data",onOpenInEditor:r,onDebugWithAssistant:c,onSendFeedback:i,showFeedbackButton:l=!0,className:d}){const[o,m]=N.useState(!1),x=!!c||!!(r&&a);return e.jsxs("div",{className:t.cn("w-full space-y-3 rounded-[6px] border border-border/60 bg-card p-4",d),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.TriangleAlert,{"aria-hidden":!0,className:"h-3.5 w-3.5 shrink-0 text-amber-600 dark:text-amber-500"}),e.jsx("span",{className:"text-[13px] font-medium text-foreground",children:n})]}),e.jsxs("div",{className:"relative rounded-[5px] border border-border/60 bg-background",children:[e.jsx(t.CopyButton,{text:s,className:"absolute right-1.5 top-1.5 z-10 h-6 w-6"}),e.jsx("div",{className:"max-h-60 overflow-auto px-2.5 py-2 pr-9",children:e.jsx("p",{className:"whitespace-pre-wrap break-all font-mono text-[12px] leading-[1.55] text-muted-foreground",children:s})})]}),x&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[c&&e.jsxs(t.Button,{variant:"outline",size:"xs",onClick:c,children:[e.jsx(ya,{className:"h-3.5 w-3.5"}),"Debug with Assistant"]}),r&&a&&e.jsxs(t.Button,{variant:"outline",size:"xs",onClick:r,children:[e.jsx(An,{className:"h-3.5 w-3.5"}),"Open in editor"]})]}),e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-3 gap-y-1",children:[a&&e.jsx("button",{type:"button",onClick:()=>m(u=>!u),className:un,children:o?"Hide query details":"Show query details"}),l&&i&&e.jsx("button",{type:"button",onClick:i,className:un,children:"Report this issue"})]}),a&&e.jsx(t.Collapsible,{open:o,onOpenChange:m,children:e.jsxs(t.CollapsibleContent,{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between pt-1",children:[e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Query"}),e.jsx(t.CopyButton,{text:a,className:"h-6 w-6"})]}),e.jsx("div",{className:"max-h-80 overflow-auto rounded-[5px] border border-border/60 bg-background p-2",children:e.jsx(t.CodeHighlighter,{code:a,language:"sql"})})]})})]})}function Pn(s,a){const n=t.useEditorStore(m=>m.card),r=t.useEditorStore(m=>m.isDevMode),{switchEditorMode:c,setRunSql:i,runAssistant:l}=t.useEditorActions();return{isDevMode:r,handleOpenInEditor:r?void 0:()=>{const m=a||n.sql||n.python||"";c("dev",{sqlToLoad:m}),setTimeout(()=>{i(!0)},100)},handleDebugWithAssistant:r?()=>{const m=`Can you help me debug this query?
|
|
177
|
+
|
|
178
|
+
Error:
|
|
179
|
+
|
|
180
|
+
${s}
|
|
181
|
+
|
|
182
|
+
Error SQL:
|
|
183
|
+
|
|
184
|
+
${a||n.sql||n.python}
|
|
185
|
+
|
|
186
|
+
`;l(m)}:void 0}}function Bn({className:s,...a}){var Ee,Ie,K,re,ve;const n=t.useEditorStore(ee=>ee.card);t.useEditorStore(ee=>ee.isDevMode);const r=((Ee=n.customCardPreferences)==null?void 0:Ee.showCardHeader)??!0,c=((K=(Ie=n.preferences)==null?void 0:Ie.displayOptions)==null?void 0:K.showInlineFilterBar)??!0,i=t.useEditorStore(ee=>ee.frame),l=t.useEditorStore(ee=>ee.inlineFilterValuesMap[n.id]),d=t.useDashboardStore(ee=>ee.dashboard.filters),o=t.useDashboardStore(ee=>ee.selectedSheetId),[m,h]=N.useState(!1),{currentUser:f}=t.useCurrentUserInfo(),{tokenProps:x}=N.useContext(t.SemaphorContext),u=t.useEditorStore(ee=>ee.actions.setRunSql),g=t.useEditorStore(ee=>ee.actions.setCardInlineFilterValue),v=t.useEditorStore(ee=>ee.actions.removeCardInlineFilterValue),{updateFilter:b}=t.useDashboardActions(),S=d==null?void 0:d.find(ee=>ee.id===i.filterId),I=N.useMemo(()=>t.findCustomVisualConfigCard(i,n),[i,n]),{manifest:P}=t.useCustomVisual(((re=I==null?void 0:I.customCardPreferences)==null?void 0:re.url)||""),C=N.useMemo(()=>{var ee;return(ee=P==null?void 0:P.visuals)==null?void 0:ee.find(Q=>{var ae;return Q.name===((ae=I==null?void 0:I.customCardPreferences)==null?void 0:ae.componentName)})},[P,(ve=I==null?void 0:I.customCardPreferences)==null?void 0:ve.componentName]),A=t.resolveMultiInputType(I,C),y=N.useMemo(()=>t.getCustomVisualInputCards({frame:i,configCard:I,isMultiInputVisual:A==="multiple"}),[i,I,A]),T=N.useMemo(()=>{const ee=y.findIndex(Q=>(Q==null?void 0:Q.id)===(n==null?void 0:n.id));return ee<0?-1:t.getSlotIndexForCard(n,ee)},[y,n]),E=N.useMemo(()=>!I||A!=="multiple"||T<0?n.type:t.getEffectiveCardTypeForSlot(n,T,C==null?void 0:C.slots)??n.type,[I,A,T,n,C==null?void 0:C.slots]),D=E??n.type,p=N.useMemo(()=>D===n.type?n:{...n,type:D},[n,D]),R=N.useMemo(()=>E!==n.type?{...n,type:E}:n,[n,E]),{data:w,isLoading:M,isFetching:F,errorMessage:j,errorSql:L,pagination:k}=t.useEditorCardQuery(R),{handleOpenInEditor:O,handleDebugWithAssistant:z}=Pn(j,L||n.sql||n.python),V=N.useMemo(()=>(w==null?void 0:w.records)||[],[w==null?void 0:w.records]),{setCard:B,updateCardInFrame:_}=t.useEditorActions(),{data:G}=t.useTopoJson(p),q=p.id,H=p.config,te=p.interactionConfig,ie=p.customCfg,oe=p.preferences,de=p.queryConfig,he=!!p.sql,me=w==null?void 0:w.records,se=N.useMemo(()=>({id:q,type:D,config:H,interactionConfig:te,sql:he?"__editor_sql__":""}),[q,D,H,te,he]),je=N.useMemo(()=>{var ee;return D!=="pivotTable"||!((ee=w==null?void 0:w.records)!=null&&ee.length)?null:{records:w.records,columnSubtotalMeta:w.columnSubtotalMeta,subtotalColumns:w.subtotalColumns||[],pivotSchema:w.pivotSchema||[],groupByColumns:w.groupByColumns}},[D,w==null?void 0:w.records,w==null?void 0:w.columnSubtotalMeta,w==null?void 0:w.subtotalColumns,w==null?void 0:w.pivotSchema,w==null?void 0:w.groupByColumns]),be=t.usePivotTableConfig(p,je),ye=()=>{h(!0)},X=N.useMemo(()=>{const ee=typeof window<"u"?window.location.href:"",Q=typeof navigator<"u"?navigator.userAgent:"",ae=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:t.FeedbackCategory.QUERY_GENERATION,user:f,tokenContext:x,systemState:{cardConfig:n.config,dataSource:n.dataSource,dashboardFilters:d,errorMessage:j||void 0,errorSql:L||n.sql||n.python,generatedSql:L||n.sql},metadata:{url:ee,userAgent:Q,timestamp:new Date().toISOString(),viewport:ae}}},[f,x,n,d,j,L]),ge=(ee,Q)=>{var ue,Se;const ae={...n,paginationConfig:{page:ee+1,pageSize:Q}};B(ae),_(ae),n.sql&&((Se=(ue=n.preferences)==null?void 0:ue.tablePrefs)!=null&&Se.enableDevModePagination)&&u(!0)},Z=ee=>{var ue,Se,Ne,Oe,Ve;const Q=t.sortStateToSortByColumns(ee,(ue=n.config)==null?void 0:ue.metricColumns,(Se=n.config)==null?void 0:Se.groupByColumns,(Ne=n.config)==null?void 0:Ne.detailColumns),ae={...n,config:{...n.config||{},sortByColumns:Q}};B(ae),_(ae),n.sql&&((Ve=(Oe=n.preferences)==null?void 0:Oe.tablePrefs)!=null&&Ve.enableDevModePagination)&&u(!0)},Te=N.useMemo(()=>!q||!me?null:t.createChartConfig({card:se,data:me,cardType:D,queryConfig:de,customCfg:ie,preferences:oe,topoJson:G}),[se,q,ie,oe,de,me,D,G]);function Le(ee){return e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackVisual,children:e.jsx(t.EditorCustomVisual,{card:ee})})}function De(){var ee;if(w!=null&&w.records&&(w==null?void 0:w.records.length)===0&&!M&&!F)return j?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(us,{error:j,errorSql:L||n.sql||n.python,onOpenInEditor:O,onDebugWithAssistant:z,onSendFeedback:ye,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((M||F)&&(!(w!=null&&w.records)||w.records.length===0))return D==="table"||D==="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(!p.id)return null;if(D==="custom")return Le(n);if(!["table","pivotTable","aggregateTable","detailTable","custom"].includes(D)&&Te)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:M||F?e.jsx(e.Fragment,{}):e.jsx(t.ChartJsVisual,{cfg:Te})});if(D==="table"||D==="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:p,data:V,comparisonMetadata:(ee=w==null?void 0:w.metadata)==null?void 0:ee.comparisonMetadata,paginationMetadata:k,onPaginationChange:ge,onSortChange:Z,isLoading:M||F})});if(D==="pivotTable"&&be)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:p,data:be.data,options:be.options,onAggregationChange:Q=>{const ae=t.handleAggregationChange(Q,n.config),ue={...n,config:ae};B(ue),_(ue)},onAggregationLabelChange:Q=>{const ae=t.handleAggregationLabelChange(Q,n.config),ue={...n,config:ae};B(ue),_(ue)}})});if(D==="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:p,data:(w==null?void 0:w.records)||[],groupByColumns:w==null?void 0:w.groupByColumns,pivotSchema:w==null?void 0:w.pivotSchema,paginationMetadata:k,onPaginationChange:ge,onAggregationChange:Q=>{const ae=t.handleAggregationChange(Q,n.config),ue={...n,config:ae};B(ue),_(ue)},isLoading:M||F})})}return e.jsxs(t.Card,{role:"editor-visual-card",className:t.cn("relative flex h-full flex-col rounded-none",s),...a,children:[(M||F)&&(w==null?void 0:w.records)&&w.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 gap-4 px-4 pb-3 pt-2"),children:[e.jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.CardTitle,{className:"min-w-0 text-[17px] font-semibold leading-tight tracking-[-0.005em]",children:e.jsx(t.EditableText,{value:n.title,onSave:ee=>B({...n,title:ee}),isEditable:!0,placeholder:"Add title",displayClassName:"text-[17px] font-semibold leading-tight tracking-[-0.005em]",inputClassName:"text-[17px] font-semibold leading-tight tracking-[-0.005em]"})}),e.jsx(t.InfoHover,{card:n}),e.jsx(Ae.VisualBadge,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(pr,{})})]}),e.jsx("div",{className:"min-w-0",children:e.jsx(t.EditableText,{value:(n.description||"").trim(),onSave:ee=>B({...n,description:ee.trim()}),isEditable:!0,placeholder:"Add description",displayClassName:"text-[12px] leading-snug text-muted-foreground",inputClassName:"text-[12px] leading-snug"})})]}),S&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Label,{className:"my-1",children:e.jsx(t.EditableText,{value:S.title||S.column,onSave:ee=>b({...S,title:ee}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(t.FilterComponent,{filter:S})]})]}),c&&n.inlineFilters&&n.inlineFilters.length>0&&e.jsx("div",{className:"px-4 pb-2",children:e.jsx(t.InlineFilterBar,{card:n,sheetId:o||"",inlineFilterValues:l,setInlineFilterValue:ee=>g(n.id,ee),removeInlineFilterValue:ee=>v(n.id,ee)})}),e.jsxs(t.CardContent,{className:t.cn("flex min-h-0 grow flex-col px-4"),children:[e.jsx("div",{className:"min-h-0 flex-1 grow basis-0",children:De()}),t.isCardSummaryVisibleOnCard(p)&&e.jsx("div",{className:"pt-3",children:e.jsx(t.CardSummary,{card:p,mode:"editor"})})]}),e.jsx(t.FeedbackDialog,{open:m,onOpenChange:h,feedbackData:X,showDebugInfo:!0})]})}const ts=({language:s,value:a,onChange:n,readonly:r})=>e.jsx(t.CodeEditor,{className:"h-full w-full text-xs",language:s,value:a,onValueChange:n,readOnly:r,embedded:!0}),fr=()=>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."})]})]}),gr=({customCode:s,cardCustomCfgString:a,mergedConfig:n,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(ts,{language:"json",value:n,onChange:r})}),e.jsx(t.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ts,{readonly:!0,language:"json",value:a,onChange:()=>{}})}),e.jsx(t.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ts,{language:"javascript",value:s,onChange:c})})]}),br=({error:s,hasCardCustomConfig:a,onReset:n,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:!a,onClick:n,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 jr({triggerVariant:s="icon",className:a,label:n="Customize Visual"}={}){const[r,c]=N.useState(!1),[i,l]=N.useState(""),[d,o]=N.useState(""),[m,h]=N.useState(""),[f,x]=N.useState(""),u=t.useEditorStore(p=>p.card),g=Ae.useEffectiveEditorCardType(),v=t.useEditorStore(p=>p.card.customCfg),b=v?JSON.stringify(v,null,2):"",S=N.useMemo(()=>g!==u.type?{...u,type:g}:u,[u,g]),{data:I}=t.useEditorCardQuery(S),{data:P}=t.useTopoJson(u),{setCardCustomCfg:C,setCustomVisualCode:A}=t.useEditorActions(),y=p=>{var R,w;return JSON.stringify({...p,data:{...p.data,datasets:(w=(R=p.data)==null?void 0:R.datasets)==null?void 0:w.map(M=>({...M,data:[]}))}},null,2)},T=()=>{var R,w;if(!((R=I==null?void 0:I.records)!=null&&R.length))return;const p=t.createChartConfig({card:u,data:I.records,cardType:u.type,queryConfig:u.queryConfig,preferences:u.preferences,topoJson:P});if(p){l(y(p)),h(((w=u.preferences)==null?void 0:w.customVisualCode)||"");const M=t.merge(p,v);o(y(M))}},E=()=>{try{if(m&&A(m),d){const p=JSON.parse(d),R=t.getObjectDiff(JSON.parse(i),p);C(R),x("")}}catch{x("Invalid JSON configuration")}},D=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:T,className:t.cn("h-8 w-full justify-start gap-2 px-2 text-sm",D?"":"text-green-600 hover:text-green-700",a),children:[e.jsx(t.Settings,{className:"h-4 w-4"}),e.jsx("span",{children:n})]}):e.jsx(t.IconButton,{tooltip:"Customize Visual",onClick:T,className:t.cn(D?"":"text-green-600 hover:text-green-700",a),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(fr,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackVisual,children:e.jsx(Bn,{className:"w-1/2 rounded shadow-none"})}),e.jsx(gr,{customCode:m,cardCustomCfgString:b,mergedConfig:d,onConfigChange:p=>o(p??""),onCodeChange:p=>h(p??"")})]}),e.jsx(br,{error:f,hasCardCustomConfig:!!v,onReset:()=>{o(i),C(null)},onApply:E,onClose:()=>c(!1)})]})]})}function vr(s){let a=0;for(let r=0;r<s.length;r++)a=s.charCodeAt(r)+((a<<5)-a);return`hsl(${Math.abs(a%360)}, 65%, 45%)`}function yr(s){const a=s.trim().split(/\s+/);return a.length>1?(a[0][0]+a[1][0]).toUpperCase():s.slice(0,2).toUpperCase()}function ms({chartType:s,chartName:a,isCustom:n=!1,className:r="h-6 w-6"}){if(!n&&s)return t.getChartIconByType(s,r);const c=t.getAutoDetectedChartIcon(a);if(c)return N.cloneElement(c,{className:r});const i=yr(a),l=vr(a);return e.jsx("div",{className:t.cn("flex items-center justify-center rounded text-white font-semibold text-xs",r),style:{backgroundColor:l},children:i})}function Nr({isStarred:s,onClick:a,className:n}){const r=c=>{c.stopPropagation(),c.preventDefault(),a(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",n),"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 mn({chartType:s,chartName:a,isCustom:n=!1,pluginName:r,isStarred:c,showStar:i=!0,isSelected:l=!1,onSelect:d,onToggleStar:o}){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(Nr,{isStarred:c,onClick:()=>o()})}),n&&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",children:r})]})}),e.jsxs("button",{type:"button",onClick:d,"aria-pressed":l,className:t.cn("flex w-full flex-col items-center justify-center gap-1.5 rounded-[5px] border border-border bg-background px-2 py-2.5 transition-colors","hover:border-foreground/30 hover:bg-muted/40",l&&"border-foreground/50 bg-muted/50 hover:border-foreground/50"),children:[e.jsx(ms,{chartType:s,chartName:a,isCustom:n,className:"h-4 w-4 text-foreground/80"}),e.jsx("span",{title:a,className:"line-clamp-2 text-center text-[11px] text-foreground/80",children:a})]})]})}const xn=[{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 Vn({onChartSelect:s,onClose:a}){const[n,r]=N.useState(""),{starredCharts:c,isStarred:i,toggleStar:l}=t.useStarredChartsStore(),{data:d=[],isLoading:o}=t.useCustomVisualsQuery(),{setCardType:m,setCardPreferences:h,setIsDevMode:f}=t.useEditorStore(p=>p.actions),x=t.useEditorStore(p=>p.card),{setCardCustomCfg:u,setCustomCardPreferences:g,setVisualizationMode:v,setQueryConfig:b,replaceFrameCards:S,clearModeDrafts:I,initializeModeDrafts:P}=t.useEditorActions(),C=N.useMemo(()=>{if(!n)return xn;const p=n.toLowerCase();return xn.filter(R=>R.name.toLowerCase().includes(p))},[n]),A=N.useMemo(()=>{const p=d.filter(w=>w.componentType==="chart"&&w.pluginType!=="standard");if(!n)return p;const R=n.toLowerCase();return p.filter(w=>w.name.toLowerCase().includes(R))},[d,n]),y=p=>{u(null),h({}),v("builtin"),m(p),["custom","text","map"].includes(p)&&(f(!0),b(void 0)),s==null||s(p),a==null||a()},T=p=>{u(null),h({}),v("builtin"),b(void 0);const R=t.resolveMultiInputTypeFromVisual(p);if(R==="multiple"&&p.slots&&p.slots.length>0){I();const M=t.createCardsFromSlots(p.slots,p,x);S(M),M[0]&&P(M[0]),a==null||a();return}else m("custom"),g({type:"component",visualType:R,url:p.url,componentName:p.name,icon:p.icon,pluginChartType:p.chartType,minInputs:p.minInputs,maxInputs:p.maxInputs});s==null||s("custom",p),a==null||a()},E=p=>{const R={type:"default",id:p.id,name:p.name};l(R)},D=p=>{const R={type:"custom",id:p.name,url:p.url,icon:p.icon,name:p.name};l(R)};return e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"mb-2 flex h-7 items-center gap-1.5 rounded-[5px] border border-border bg-background px-2 focus-within:border-ring",children:[e.jsx(t.Search,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx("input",{type:"text",placeholder:"Search charts",value:n,onChange:p=>r(p.target.value),className:"h-full w-full bg-transparent text-[12px] text-foreground placeholder:text-muted-foreground focus:outline-none"})]}),e.jsxs("div",{className:"max-h-[360px] overflow-y-auto pr-1",children:[C.length>0&&e.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:C.map(p=>e.jsx(mn,{chartType:p.id,chartName:p.name,isCustom:!1,isStarred:i("default",p.id),onSelect:()=>y(p.id),onToggleStar:()=>E(p)},p.id))}),A.length>0&&e.jsxs(e.Fragment,{children:[C.length>0&&e.jsxs("div",{className:"my-3 flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Custom charts"}),e.jsx("span",{className:"font-mono text-[10px] tabular-nums text-muted-foreground/70",children:A.length})]}),e.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:A.map((p,R)=>e.jsx(mn,{chartName:p.name,isCustom:!0,pluginName:p.pluginName,isStarred:i("custom",p.name),onSelect:()=>T(p),onToggleStar:()=>D(p)},`${p.url}-${p.name}-${R}`))})]}),o&&e.jsx("div",{className:"mt-3 py-4 text-center text-[11px] text-muted-foreground",children:"Loading custom charts…"}),C.length===0&&A.length===0&&!o&&e.jsx("div",{className:"py-8 text-center text-[11px] text-muted-foreground",children:"No charts found"})]})]})}function Cr({selectedChart:s,onChartChange:a}){var y,T,E,D;const n=t.useEditorStore(p=>p.card),r=t.useEditorStore(p=>p.frame),c=t.useEditorStore(p=>p.isDevMode),{replaceFrameCards:i,clearModeDrafts:l,initializeModeDrafts:d,setIsDevMode:o}=t.useEditorActions(),m=N.useMemo(()=>t.findCustomVisualConfigCard(r,n),[r,n]),{manifest:h}=t.useCustomVisual(((y=m==null?void 0:m.customCardPreferences)==null?void 0:y.url)||""),f=N.useMemo(()=>{var p;return(p=h==null?void 0:h.visuals)==null?void 0:p.find(R=>{var w;return R.name===((w=m==null?void 0:m.customCardPreferences)==null?void 0:w.componentName)})},[h,(T=m==null?void 0:m.customCardPreferences)==null?void 0:T.componentName]),x=t.resolveMultiInputType(m,f)==="multiple",u=Ae.useEffectiveEditorCardType(),g=x?u:s??n.type,v=(E=n==null?void 0:n.customCardPreferences)==null?void 0:E.componentName,b=(D=m==null?void 0:m.customCardPreferences)==null?void 0:D.componentName,S=x&&!!b,I=N.useMemo(()=>{const p=t.chartTypes.find(R=>R.id===g);return p?p.label:g==="custom"?v||"Custom Visual":"Select chart type"},[g,v]),P=N.useMemo(()=>{const p=t.chartTypes.find(R=>R.id===g);if(p){const R=p.icon;return e.jsx(R,{className:"h-4 w-4"})}if(g==="custom"&&v){const R=t.getAutoDetectedChartIcon(v);return R||e.jsx(ms,{chartName:v,isCustom:!0,className:"h-4 w-4"})}return e.jsx(Da,{className:"h-4 w-4"})},[g,v]);return{displayChartType:g,displayLabel:I,displayIcon:P,showBadge:S,badgeLabel:b,isMultiInputContext:x,handleChartSelect:p=>{a==null||a(p)},handleClearCustomVisual:p=>{p.stopPropagation();const R={...n,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),a==null||a("bar")}}}function zn({selectedChart:s,onChartChange:a,variant:n="ghost",className:r}){const[c,i]=N.useState(!1),{displayLabel:l,displayIcon:d,showBadge:o,badgeLabel:m,handleChartSelect:h,handleClearCustomVisual:f}=Cr({selectedChart:s,onChartChange:a}),x=n==="header";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:x?e.jsxs("button",{type:"button",role:"combobox","aria-expanded":c,className:"flex h-9 w-full items-center justify-between gap-2 border-b border-border bg-card px-3 text-left transition-colors hover:bg-muted/50 focus:outline-none focus-visible:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[d,e.jsx("span",{className:"truncate text-[12px] font-medium text-foreground",children:l})]}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform",c&&"rotate-180")})]}):e.jsxs(t.Button,{size:"xs",variant:n,role:"combobox","aria-expanded":c,className:t.cn("w-full justify-between gap-2",n==="ghost"&&"border border-border/70 bg-background text-foreground/90",n==="outline"&&"border-border/70 bg-background text-foreground/90",n==="secondary"&&"text-foreground"),children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[d,e.jsx("span",{className:"truncate",children:l})]}),e.jsx(t.ChevronDown,{className:"h-3.5 w-3.5 shrink-0 opacity-70"})]})}),e.jsx(t.PopoverContent,{className:"w-[360px] p-3",align:"start",onOpenAutoFocus:u=>u.preventDefault(),children:e.jsx(Vn,{onChartSelect:u=>h(u),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:m,children:[e.jsx(t.Layers,{className:"h-2.5 w-2.5 shrink-0"}),e.jsx("span",{className:"truncate",children:m}),e.jsx("button",{onClick:f,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 Sr(){const s=t.useEditorStore(o=>{var m,h;return(h=(m=o.card.preferences)==null?void 0:m.chartOptions)==null?void 0:h.indexAxis}),a=t.useEditorStore(o=>o.card.type),{setChartOrientation:n,setCardPreferences:r}=t.useEditorStore(o=>o.actions),c=o=>{if(n(o),a!=="bullet")return;const m=o==="y"?"horizontal":"vertical",h=t.useEditorStore.getState().card.preferences,f={...h||{},bulletConfig:{...(h==null?void 0:h.bulletConfig)||{},orientation:m}};r(f)};function i(){const o=s??"x",m=()=>{c(o==="x"?"y":"x")};return e.jsx(t.IconButton,{onClick:m,tooltip:"Chart Orientation",className:"h-7 w-7 px-0",children:o==="x"?e.jsx(Xt,{className:"h-3.5 w-3.5"}):e.jsx(Yt,{className:"h-3.5 w-3.5"})})}function l(){const o=()=>{c(s==="y"||s===void 0?"x":"y")};return e.jsx(t.IconButton,{onClick:o,tooltip:"Chart Orientation",className:"h-7 w-7 px-0",children:s==="y"||s===void 0?e.jsx(Xt,{className:"h-3.5 w-3.5"}):e.jsx(Yt,{className:"h-3.5 w-3.5"})})}function d(){const o=s??"y",m=()=>{c(o==="y"?"x":"y")};return e.jsx(t.IconButton,{onClick:m,tooltip:"Chart Orientation",className:"h-7 w-7 px-0",children:o==="y"?e.jsx(Yt,{className:"h-3.5 w-3.5"}):e.jsx(Xt,{className:"h-3.5 w-3.5"})})}return e.jsx(e.Fragment,{children:a==="funnel"?l():a==="bullet"?d():i()})}function xs({className:s,triggerVariant:a="icon",label:n="Display Options"}){var v,b,S,I,P,C,A,y,T,E;const r=t.useEditorStore(D=>D.card),{setCardPreferences:c,updateCardInFrame:i,setCard:l}=t.useEditorActions(),[d,o]=N.useState(!1),m=((b=(v=r.preferences)==null?void 0:v.displayOptions)==null?void 0:b.showFilterInfo)??!0,h=((I=(S=r.preferences)==null?void 0:S.displayOptions)==null?void 0:I.showCardToolbar)??!0,f=((C=(P=r.preferences)==null?void 0:P.displayOptions)==null?void 0:C.showChrome)??!0,x=((y=(A=r.preferences)==null?void 0:A.displayOptions)==null?void 0:y.allowScroll)??!0,u=((E=(T=r.preferences)==null?void 0:T.displayOptions)==null?void 0:E.showInlineFilterBar)??!0,g=(D,p)=>{var M;const R={...r.preferences,displayOptions:{...(M=r.preferences)==null?void 0:M.displayOptions,[D]:p}};c(R);const w={...r,preferences:R};l(w),i(w)};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:a==="menu"?e.jsxs(t.Button,{variant:"ghost",className:"h-7 w-full justify-start gap-2 px-2 text-[13px]",children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:n})]}):e.jsx(t.IconButton,{className:"h-7 w-7 p-0",tooltip:"Display Options",children:e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"})})}),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:m,onCheckedChange:D=>{g("showFilterInfo",D)},onSelect:D=>D.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Filter Info"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Badge"})]}),e.jsxs(t.DropdownMenuCheckboxItem,{checked:h,onCheckedChange:D=>{g("showCardToolbar",D)},onSelect:D=>D.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:f,onCheckedChange:D=>{g("showChrome",D)},onSelect:D=>D.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:x,onCheckedChange:D=>{g("allowScroll",D)},onSelect:D=>D.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:u,onCheckedChange:D=>{g("showInlineFilterBar",D)},onSelect:D=>D.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 hs({className:s,triggerVariant:a="icon",label:n="Inline Filters"}){var A,y,T;const[r,c]=N.useState(!1),i=t.useEditorStore(E=>E.card),l=t.useEditorStore(E=>E.selectedConnectionId),{tokenProps:d}=t.useSemaphorContext(),{setCard:o}=t.useEditorActions(),m=t.useDashboardStore(E=>E.actions.removeCardInlineFilterValue),h=t.useDashboardStore(E=>E.actions.setCardInlineFilterValue),f=t.useEditorStore(E=>E.actions.removeCardInlineFilterValue),x=t.useEditorStore(E=>E.actions.setCardInlineFilterValue),u=t.useDashboardStore(E=>E.isVisualEditing),g=(i==null?void 0:i.inlineFilters)||[],v=((y=(A=d==null?void 0:d.params)==null?void 0:A.calendarContext)==null?void 0:y.tz)||((T=d==null?void 0:d.params)==null?void 0:T.timezone)||Intl.DateTimeFormat().resolvedOptions().timeZone;function b(E){var V,B,_,G,q,H,te;const D=((_=(B=(V=i==null?void 0:i.dataSource)==null?void 0:V.selectedEntities)==null?void 0:B[0])==null?void 0:_.database)||"",p=E.qualifiedFieldName||E.name;if(g.find(ie=>t.doesStoredFilterMatchField(ie,E)))return;const w=E.qualifiedFieldName?E.qualifiedFieldName.split(".").slice(0,-1).join("."):E.qualifiedEntityName||E.entityName,F=t.fmt(E.name),j=t.buildFilterFieldMeta(E),L=t.buildFilterSemanticContext(i==null?void 0:i.dataSource,{connectionId:l||((G=i==null?void 0:i.dataSource)==null?void 0:G.connectionId),connectionType:(q=i==null?void 0:i.dataSource)==null?void 0:q.connectionType}),k=t.isCalculatedFilterField(j),O=!!(((H=i==null?void 0:i.dataSource)==null?void 0:H.mode)==="semanticDomain"&&((te=L==null?void 0:L.selectedEntities)!=null&&te.length||L!=null&&L.semanticDomainId)),z={id:t.v4(),column:p,title:E.label||E.name,dataType:E.dataType,table:E.entityName||"",database:D,qualifiedTableName:w,connectionId:l||"",operation:"in",sql:k||O?"":t.getDefaultFilterSql(E.dataType,w,F),fieldMeta:j,semanticContext:L,width:250};o({...i,inlineFilters:[...g,z]})}function S(E){const D=g.filter(p=>p.id!==E);o({...i,inlineFilters:D}),u?f(i.id,E):m(i.id,E)}function I(E,D){const p=g.map(F=>F.id===E?{...F,...D}:F);if(o({...i,inlineFilters:p}),!(Object.prototype.hasOwnProperty.call(D,"defaultValues")||Object.prototype.hasOwnProperty.call(D,"defaultDateFilter")))return;const w=p.find(F=>F.id===E);if(!w)return;const M=t.buildFilterValueFromDefaults(w,v);M?u?x(i.id,M):h(i.id,M):u?f(i.id,E):m(i.id,E)}if(!["bar","line","pie","doughnut","table","detailTable","stackedBar","stackedLine","horizontalBar","radar","polarArea","scatter","bubble","funnel","aggregateTable","custom"].includes(i==null?void 0:i.type))return null;const C=a==="menu";return e.jsx("div",{className:t.cn("flex items-center gap-1",C&&"w-full",s),children:e.jsxs(t.Popover,{open:r,onOpenChange:c,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:C?e.jsxs(t.Button,{variant:"ghost",className:t.cn("h-7 w-full justify-start gap-2 px-2 text-[13px]",g.length>0&&"text-primary"),children:[e.jsx(nn,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:n}),g.length>0&&e.jsx("span",{className:"ml-auto inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-[4px] 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 h-7 w-7 px-0",{"text-primary":g.length>0}),children:[e.jsx(nn,{className:"h-3.5 w-3.5"}),g.length>0&&e.jsx("span",{className:"absolute -right-1 -top-1 flex h-4 w-4 items-center justify-center rounded-full bg-primary text-[10px] font-medium text-primary-foreground",children:g.length})]})}),e.jsx(t.PopoverContent,{align:"end",className:t.cn("w-80 p-0",C&&"z-[60]"),children:e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"border-b px-4 py-3",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Inline Filters"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"On-card filters for fast, focused exploration."})]}),e.jsx("div",{className:"flex h-[320px] min-h-0 flex-col overflow-hidden",children:e.jsx(t.DndContext,{collisionDetection:t.closestCenter,children:e.jsx(t.SortableContext,{items:[],strategy:t.verticalListSortingStrategy,children:e.jsx(t.FieldsList,{context:"inline-filter",onFieldSelect: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(E=>e.jsx(wr,{filter:E,onUpdate:D=>I(E.id,D),onRemove:()=>S(E.id)},E.id))})]})]})})]})})}function wr({filter:s,onUpdate:a,onRemove:n}){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=>a(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:n,children:e.jsx(t.X,{className:"h-3 w-3"})})]})]})}const Tr={metric_selector:"Displayed metric",field_selector:"Group by field",aggregation_selector:"Aggregation",grain_selector:"Time grain"};function Er(s,a){return s&&typeof s=="object"&&"label"in s&&typeof s.label=="string"&&s.label.trim().length>0?s.label:a||null}const Ir={metric_selector:"config_metric_selector",field_selector:"config_field_selector",aggregation_selector:"config_aggregation",grain_selector:"config_grain"};function Vt(s,a){return`${s}:${a}`}function kr(s,a,n){const r=new Set(n.filter(i=>i.target!=="sql_param").map(i=>Vt(i.controlId,i.target))),c=a.map(i=>{const l=t.getCompatibleBindingTargetOptions({card:s,control:i}).map(h=>h.value),d=Ir[i.type],m=[...d?[d]:[],...l.filter(h=>h!==d)].find(h=>!r.has(Vt(i.id,h)));return m?{controlId:i.id,target:m}:null}).find(Boolean);return c?{controlId:c.controlId,target:c.target,mapping:{}}:null}function Dr({card:s,dashboardControls:a,bindings:n,onChange:r,availableFieldChoices:c,availableMetricChoices:i,suppressTransientStaleState:l=!1}){const d=[...a,...s.controls||[]],[o,m]=N.useState({}),h=t.extractSqlParamReferences({sql:s.sql,controlBindings:s.controlBindings}),f=t.getBindingTargetSuggestions(s),x=new Set(n.map(P=>Vt(P.controlId,P.target))),u=d.some(P=>t.getCompatibleBindingTargetOptions({card:s,control:P}).some(C=>!x.has(Vt(P.id,C.value)))),g=l?0:n.reduce((P,C)=>{const A=v(C.target),y=Object.values(C.mapping).filter(T=>{const E=C.target==="config_metric_selector"||C.target==="config_field_selector"?typeof T=="string"?T:T==null?void 0:T.id:typeof T=="string"?T:void 0;return typeof E=="string"&&!A.some(D=>D.value===E)}).length;return P+y},0);function v(P){var C,A,y,T;switch(P){case"config_metric_selector":return i?i.filter(E=>!!E.target).map(E=>({value:E.target.id,label:E.target.label||E.option.label,target:E.target})):((A=(C=s.config)==null?void 0:C.metricColumns)==null?void 0:A.map(E=>({value:E.id,label:E.label||E.id,target:E})))||[];case"config_field_selector":return c?c.filter(E=>!!E.target).map(E=>({value:E.target.id,label:E.target.label||E.option.label,target:E.target})):((T=(y=s.config)==null?void 0:y.groupByColumns)==null?void 0:T.map(E=>({value:E.id,label:E.label||E.id,target:E})))||[];case"config_aggregation":return(f.config_aggregation||[]).map(E=>({value:E,label:E}));case"config_grain":return(f.config_grain||[]).map(E=>({value:E,label:E.charAt(0).toUpperCase()+E.slice(1)}));default:return[]}}const b=(P,C)=>{r(n.map((A,y)=>y!==P?A:C(A)))},S=P=>{r(n.filter((C,A)=>A!==P))},I=()=>{const P=kr(s,d,n);P&&r([...n,P])};if(typeof s.sql=="string"&&s.sql.trim().length>0){const P=h.map(({controlId:C,paramId:A})=>{const y=d.find(T=>T.id===C);return y?{id:C,paramId:A,label:y.label,reference:`[[param.${A}]]`}:{id:C,paramId:A,label:C,reference:`[[param.${A}]]`}});return e.jsx("div",{className:"space-y-2",children:P.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]]`."}):P.map(C=>e.jsx("div",{className:"rounded-md border p-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:C.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Referenced in SQL"})]}),e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted/40 px-2 py-1",children:[e.jsx("code",{className:"text-xs",children:C.reference}),e.jsx(t.CopyButton,{text:C.reference,ariaLabel:`Copy ${C.reference}`})]})]})},`${C.id}:${C.paramId}`))})}return e.jsxs("div",{className:"space-y-4",children:[g>0?e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-950",children:[e.jsx(t.CircleAlert,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{children:[g," ",g===1?"mapping needs":"mappings need"," attention before save. Replace each missing target or choose Not mapped."]})]}):null,n.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."}):n.map((P,C)=>{const A=f[P.target]||[],y=d.find(j=>j.id===P.controlId),T=y?t.ensureManualSource(y):null,E=(T==null?void 0:T.source.kind)==="manual"?T.source.options:[],D=v(P.target),p=Array.from(new Set([...E.map(j=>j.value),...Object.keys(P.mapping)])).map(j=>{const L=E.find(k=>k.value===j);return{value:j,label:(L==null?void 0:L.label)||j}}),R=`${P.controlId}-${P.target}-${C}`,w=o[R]??C===0,M=Object.keys(P.mapping).length,F=y!=null&&y.type?Tr[y.type]||y.type:null;return e.jsxs(t.Collapsible,{open:w,onOpenChange:j=>m(L=>({...L,[R]:j})),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:[w?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:(y==null?void 0:y.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:M>0?`${M} mapped`:"No mappings yet"})]})]})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>S(C),children:e.jsx(t.Trash2,{className:"h-4 w-4"})})]}),e.jsx(t.CollapsibleContent,{className:"space-y-3 border-t px-3 pb-3 pt-2",children:p.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."}):D.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:p.map(j=>{const L=P.mapping[j.value],k=P.target==="config_metric_selector"||P.target==="config_field_selector"?typeof L=="string"?L:L==null?void 0:L.id:typeof L=="string"?L:void 0,O=!l&&typeof k=="string"&&!D.some(B=>B.value===k),z=Er(L,k),V=k&&O?[...D,{value:k,label:"Needs remap",target:L}]:D;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:j.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:k||"__none__",onValueChange:B=>b(C,_=>{if(_.target==="config_metric_selector"){const q={..._.mapping};if(B==="__none__")delete q[j.value];else{const H=V.find(te=>te.value===B);H!=null&&H.target?q[j.value]=H.target:delete q[j.value]}return{..._,mapping:q}}if(_.target==="config_field_selector"){const q={..._.mapping};if(B==="__none__")delete q[j.value];else{const H=V.find(te=>te.value===B);H!=null&&H.target?q[j.value]=H.target:delete q[j.value]}return{..._,mapping:q}}const G={..._.mapping};return B==="__none__"?delete G[j.value]:G[j.value]=B,{..._,mapping:G}}),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Choose what this should use"})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"__none__",children:"Not mapped"}),V.map(B=>e.jsx(t.SelectItem,{value:B.value,children:B.label},B.value))]})]}),O?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",z?` · Previously: ${z}`:""]})]}):null]})]},`${P.controlId}-${P.target}-${j.value}`)})}),A.length>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Available choices for this card: ",A.join(", ")]})]})})]},R)}),u?e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",onClick:I,children:[e.jsx(t.Plus,{className:"mr-2 h-4 w-4"}),"Add another control response"]}):null]})}const Ar=[];function Mr({className:s,triggerVariant:a="icon",label:n="Controls"}){var w,M;const{handleOpenChange:r,preventPassiveDismissDuringCreate:c,resolvedOpen:i,setIsCreateFlowActive:l}=Ae.useCreateFlowOverlayState({}),d=t.useEditorStore(F=>F.card),o=t.useEditorStore(F=>F.frame),m=t.useDashboardStore(F=>F.dashboard),f=t.useDashboardStore(F=>F.dashboard.controls)||Ar,{setCard:x,updateCardInFrame:u}=t.useEditorActions(),[g,v]=N.useState(null);N.useEffect(()=>{i&&!g&&(d!=null&&d.id)&&v(d.id)},[d==null?void 0:d.id,i,g]),N.useEffect(()=>{!i&&g!==null&&v(null)},[i,g]);const b=N.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]),S=(b==null?void 0:b.controls)||[],I=b?t.collectDashboardControlIds(m,{excludeCardId:b.id}):f.map(F=>F.id),P=((b==null?void 0:b.controlBindings)||[]).filter(F=>F.target!=="sql_param"),C=t.buildCardControlUsageById({card:b,controls:S}),A={choices:t.getFieldSelectorChoicesForCard(b),targetMap:Object.fromEntries((((w=b==null?void 0:b.config)==null?void 0:w.groupByColumns)||[]).map(F=>[F.id,F]))},y={choices:t.getMetricSelectorChoicesForCard(b),targetMap:Object.fromEntries((((M=b==null?void 0:b.config)==null?void 0:M.metricColumns)||[]).map(F=>[F.id,F]))},T=A.choices.map(F=>({option:F,target:A.targetMap[F.value]})),E=y.choices.map(F=>({option:F,target:y.targetMap[F.value]})),D=(F,j)=>{if(!b)return;const L=(j==null?void 0:j.type)==="rename"?t.applyControlMutationToCard(b,{type:"rename",oldId:j.oldId,newId:j.newId}):(j==null?void 0:j.type)==="remove"?t.applyControlMutationToCard(b,{type:"remove",controlId:j.controlId}):b,k={...L,controls:F,controlBindings:t.syncStructuralBindingsWithControls(L.controlBindings,F)};u(k),(d==null?void 0:d.id)===k.id&&x(k)},p=F=>{if(!b)return;const j={...b,controlBindings:t.mergeConfigBindingsWithSqlParamBindings(F,b.controlBindings)};u(j),(d==null?void 0:d.id)===j.id&&x(j)},R=a==="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-7 w-full justify-start gap-2 px-2 text-[13px]",(S.length>0||P.length>0)&&"text-primary"),children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:n}),S.length+P.length>0&&e.jsx("span",{className:"ml-auto inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-[4px] bg-primary text-[10px] font-medium leading-none text-primary-foreground",children:S.length+P.length})]}):e.jsxs(t.IconButton,{tooltip:"Configure Controls",className:t.cn("relative h-7 w-7 px-0",{"text-primary":S.length>0||P.length>0}),children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"}),S.length+P.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:S.length+P.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(Ae.ControlDefinitionListEditor,{scope:"card",card:b,controls:S,reservedControlIds:I,usageByControlId:C,availableFieldChoices:T,availableMetricChoices:E,onCreateFlowActiveChange:l,onChange:(F,j,L)=>D(F,L),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(Dr,{card:b,dashboardControls:f,bindings:P,onChange:p,availableFieldChoices:T,availableMetricChoices:E}):null]})})]})]})})}function _n({showOrientation:s=!0,showGridStyle:a=!0,showInlineFilters:n=!0,showControls:r=!0,showDisplayOptions:c=!0}={}){const i=t.useEditorStore(u=>u.card),l=t.useEditorStore(u=>{var g,v;return(v=(g=u.card)==null?void 0:g.preferences)==null?void 0:v.chartOptions}),d=t.getChartGridStyle(l),{setChartGrid:o}=t.useEditorActions();function m(){const u=["xy","none","x","y"],v=(u.indexOf(d)+1)%u.length;o(u[v])}const h=s&&["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel","bullet"].includes(i.type),f=a&&!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(i.type);return h||f||n||r||c?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[h&&e.jsx(e.Fragment,{children:e.jsx(Sr,{})}),f&&e.jsxs(t.IconButton,{tooltip:"Grid Style",onClick:m,className:"h-7 w-7 px-0",children:[(d==="xy"||!d)&&e.jsx(t.Grid3x3,{className:"h-3.5 w-3.5"}),d==="x"&&e.jsx(ds,{className:"h-3.5 w-3.5"}),d==="y"&&e.jsx(zt,{className:"h-3.5 w-3.5"}),d==="none"&&e.jsx(t.Square,{className:"h-3.5 w-3.5"})]}),n&&e.jsx(hs,{}),r&&e.jsx(Mr,{}),c&&e.jsx(xs,{})]}):null}function Lr({visible:s}){const a=t.useDashboardStore(l=>l.selectedFrameId),n=t.useManagementStore(l=>l.selectedVisual),r=t.useEditorStore(l=>l.frame),i=!!!(r!=null&&r.visualId||n!=null&&n.id)&&!!a;return!s||i?null:e.jsx("div",{className:"mb-2 flex",children:e.jsx(Ae.VisualBadge,{showLabel:!0,className:"h-6 w-fit px-2 py-0.5 text-[11px]"})})}function Fr({isPreviewMode:s,onPreviewToggle:a,configCard:n}){var L,k,O,z,V;const r=t.useEditorStore(B=>B.frame),c=t.useEditorStore(B=>B.card),i=t.useEditorStore(B=>B.editorContext),l=(i==null?void 0:i.type)==="documentSection",{setFrame:d,setActiveTabCardId:o,setCard:m,updateCardInFrame:h,clearModeDrafts:f,initializeModeDrafts:x}=t.useEditorActions(),{manifest:u}=t.useCustomVisual(((L=n==null?void 0:n.customCardPreferences)==null?void 0:L.url)||""),g=(k=u==null?void 0:u.visuals)==null?void 0:k.find(B=>{var _;return B.name===((_=n==null?void 0:n.customCardPreferences)==null?void 0:_.componentName)}),b=t.resolveMultiInputType(n,g)==="multiple",S=(g==null?void 0:g.minInputs)??((O=n==null?void 0:n.customCardPreferences)==null?void 0:O.minInputs)??1,I=(g==null?void 0:g.maxInputs)??((z=n==null?void 0:n.customCardPreferences)==null?void 0:z.maxInputs),P=N.useMemo(()=>t.getCustomVisualInputCards({frame:r,configCard:n,isMultiInputVisual:b}),[r,n,b]),C=b?P.filter(Boolean).length:r.cards.length,A=l?!1:I?C<I:!0,y=C>Math.max(S||1,1),T=!!((V=n==null?void 0:n.customCardPreferences)!=null&&V.dataInputCardIds),E=(B,_)=>{B.dataTransfer.setData("tabIndex",_.toString())},D=B=>{B.preventDefault()},p=(B,_)=>{const G=B.dataTransfer.getData("tabIndex");if(G===_.toString())return;const q=Array.from(r.cards),[H]=q.splice(parseInt(G),1);q.splice(_,0,H),d({...r,cards:q})};function R(B){const _=(n==null?void 0:n.id)===B;if(!(T&&_?r.cards.length>1:y))return;let q=r.cards.filter(oe=>oe.id!==B);b&&!T&&(q=t.reindexSlotCards(q));const H=q[0],te={...r,cards:q,activeCardId:H.id},ie=B===c.id;ie&&f(),d(te),o(H.id),m(H),ie&&x(H)}function w(B,_){if(!A)return;const G={...r,cards:[...r.cards,_],activeCardId:B.id};d(G),o(_.id)}function M(){if(l)return;if(b&&(n==null?void 0:n.id)===c.id){F(c);return}const B={...c,id:t.v4(),title:`${c.title} Copy`,tabTitle:`${c.tabTitle||c.title} Copy`,customCardPreferences:c.customCardPreferences?{...c.customCardPreferences,slotIndex:b?Math.max(-1,...P.map((_,G)=>t.getSlotIndexForCard(_,G)))+1:c.customCardPreferences.slotIndex}:void 0};w(c,B)}function F(B){var ie;if(l||!A)return;let _=b?"table":"bar",G="Title",q="";const H=b?Math.max(-1,...P.map((oe,de)=>t.getSlotIndexForCard(oe,de)))+1:C;if(b&&((ie=g==null?void 0:g.slots)!=null&&ie.length)){const oe=t.getSlotDefinitionForIndex(g.slots,H);oe&&(_=t.getSlotExpectedChartType(oe),G=oe.label||`Tab ${H+1}`,q=oe.description||"")}const te={dataSource:B.dataSource,connectionId:B.connectionId,lastSelectedDatabase:B.lastSelectedDatabase,lastSelectedSchema:B.lastSelectedSchema,lastSelectedTable:B.lastSelectedTable,lastSelectedDatamodelId:B.lastSelectedDatamodelId,id:t.v4(),title:G,tabTitle:G,description:q,preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:_,sql:"",data:[],mode:"explorer",...b&&{customCardPreferences:{slotIndex:H}}};w(B,te)}function j(B,_){return B.cards.length===1&&(_.displayTab===!0||_.displayTab===void 0)||B.activeCardId!==_.id&&(_.displayTab===!0||_.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const G=_.displayTab===void 0?!1:!_.displayTab;m({..._,displayTab:G}),h({..._,displayTab:G})},children:_.displayTab===!0||_.displayTab===void 0?e.jsx(t.Eye,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"}):e.jsx(t.EyeOff,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})}return e.jsx(t.TabsList,{variant:"underline",className:"group flex h-9 items-center justify-start gap-1 overflow-x-auto rounded-none border-b-0 border-t border-border bg-background px-4",children:e.jsxs("div",{className:"flex items-center gap-1",children:[r.cards.map((B,_)=>{var ie,oe;const G=b?t.getSlotIndexForCard(B,_):-1,q=b&&((ie=g==null?void 0:g.slots)!=null&&ie.length)&&G>=0?t.getSlotDefinitionForIndex(g.slots,G):null,H=q?(Array.isArray(q.expectedType)?q.expectedType[0]:q.expectedType)||"table":B.type,te=b&&((oe=g==null?void 0:g.slots)==null?void 0:oe.length)&&g.slots.every(de=>typeof de.position=="number"||typeof de.position=="string"&&!de.position.includes("+"));return e.jsxs(t.TabsTrigger,{draggable:!b&&!l,onDragStart:b||l?void 0:de=>E(de,_),onDragOver:b||l?void 0:D,onDrop:b||l?void 0:de=>p(de,_),className:t.cn("inline-flex h-6 shrink-0 items-center gap-1.5 rounded-[5px] border px-2 text-[12px] font-normal text-muted-foreground transition-colors","mb-0 border-transparent pb-0","hover:bg-muted/40 hover:text-foreground","data-[state=active]:border-border data-[state=active]:bg-card data-[state=active]:text-foreground"),value:B.id,children:[b&&q?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(H,"size-3.5")}),e.jsx("span",{children:q.label||`Tab ${G+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:q.label}),q.description&&e.jsx("p",{className:"whitespace-normal break-words text-xs text-muted-foreground",children:q.description}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[q.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(q.expectedType)?q.expectedType.join(" / "):q.expectedType}),q.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:[j(r,B),e.jsx(t.Editable,{enabled:r.activeCardId===B.id,text:B.tabTitle||B.title,onSave:de=>{m({...c,tabTitle:de}),h({...c,tabTitle:de})},children:B.tabTitle||B.title},B.id)]}),!l&&r.activeCardId===B.id&&!te&&e.jsx(t.CopyPlus,{className:"h-3 w-3 text-muted-foreground hover:text-foreground",onClick:de=>{de.stopPropagation(),M()}}),!l&&r.activeCardId===B.id&&(T&&(n==null?void 0:n.id)===B.id?r.cards.length>1:y)&&e.jsx(t.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground",onClick:()=>R(B.id)})]},B.id)}),!l&&e.jsx(t.IconButton,{tooltip:"Add Card",className:"h-6 w-6 rounded-[5px] p-0 text-muted-foreground hover:bg-muted hover:text-foreground",onClick:()=>F(c),disabled:!A,children:e.jsx(t.Plus,{className:"h-3 w-3"})}),b&&e.jsxs(t.Toggle,{pressed:s,onPressedChange:a,size:"sm",className:"ml-1 h-6 gap-1 rounded-[5px] px-2 text-[11px] data-[state=on]:bg-muted data-[state=on]:text-foreground","aria-label":"Toggle preview",children:[s?e.jsx(t.EyeOff,{className:"h-3 w-3"}):e.jsx(t.Eye,{className:"h-3 w-3"}),e.jsx("span",{children:"Preview"})]})]})})}function ot({renderCardOverride:s,alwaysRenderOverride:a=!1}={}){var Ie,K,re,ve,ee;const n=t.useEditorStore(Q=>Q.frame),r=t.useEditorStore(Q=>Q.card),[c,i]=N.useState(!1),l=N.useMemo(()=>t.findCustomVisualConfigCard(n,r),[n,r]),d=t.useEditorStore(Q=>Q.isSqlRunning);t.useEditorStore(Q=>Q.isDevMode);const{setFrame:o,setActiveTabCardId:m,setCard:h,setRunSql:f,mergeDraftsIntoCard:x,clearModeDrafts:u,initializeModeDrafts:g}=t.useEditorActions(),[v,b]=N.useState({}),[S,I]=N.useState(()=>new Set),{theme:P}=t.useTheme(),C=t.useDashboardStore(Q=>Q.themeStyle),{authToken:A}=t.useSemaphorContext(),y=t.getTokenParams(A==null?void 0:A.accessToken),T={mode:P||"system",colors:((K=(Ie=C==null?void 0:C.chart)==null?void 0:Ie.dataset)==null?void 0:K.backgroundColor)||[]},{getCard:E,manifest:D,isLoading:p}=t.useCustomVisual(((re=l==null?void 0:l.customCardPreferences)==null?void 0:re.url)||""),R=(ve=l==null?void 0:l.customCardPreferences)==null?void 0:ve.componentName,w=R?E(R):null,M=(ee=D==null?void 0:D.visuals)==null?void 0:ee.find(Q=>Q.name===R),F=t.resolveMultiInputType(l,M),j=c&&F==="multiple"&&!!l,L=N.useMemo(()=>t.getCustomVisualInputCards({frame:n,configCard:l,isMultiInputVisual:!0}).map(ae=>(ae==null?void 0:ae.id)===r.id?r:ae),[n,l,r]),k=N.useMemo(()=>t.buildSlotOrderedCards(L),[L]),O=N.useMemo(()=>{const Q=L.findIndex(ae=>(ae==null?void 0:ae.id)===r.id);return Q<0?-1:t.getSlotIndexForCard(r,Q)},[L,r]),z=N.useMemo(()=>!l||F!=="multiple"||O<0?r.type:t.getEffectiveCardTypeForSlot(r,O,M==null?void 0:M.slots)??r.type,[l,F,O,r,M==null?void 0:M.slots]),V=N.useMemo(()=>j?{...r,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:z!==r.type?{...r,type:z}:r,[r,z,j]),{data:B,isLoading:_,isFetching:G,isError:q}=t.useEditorCardQuery(V),H=N.useCallback((Q,ae)=>{const ue=t.normalizeMultiInputPayload(ae);b(Se=>({...Se,[Q]:ue}))},[]),te=N.useCallback((Q,ae)=>{I(ue=>{const Se=new Set(ue);return ae?Se.add(Q):Se.delete(Q),Se})},[]),ie=S.size>0,oe=t.useInteractionStore(Q=>Q.interactionStates),de=t.useDashboardStore(Q=>{var ae;return(ae=Q.dashboard)==null?void 0:ae.id}),he=t.useDashboardStore(Q=>Q.dashboard.filters),me=t.useDashboardStore(Q=>Q.filterValues),se=t.useDashboardStore(Q=>Q.selectedSheetId),je=t.useEditorStore(Q=>Q.inlineFilterValuesMap[(l==null?void 0:l.id)||""]),be=t.useEditorStore(Q=>Q.actions.setCardInlineFilterValue),ye=t.useEditorStore(Q=>Q.actions.removeCardInlineFilterValue),X=N.useMemo(()=>l?t.buildInlineFilterNodes({card:l,sheetId:se||"",inlineFilterValues:je,setInlineFilterValue:Q=>be(l.id,Q),removeInlineFilterValue:Q=>ye(l.id,Q)}):[],[l,se,je,be,ye]),{cardFilters:ge,cardFilterValues:Z}=N.useMemo(()=>l?t.calculateContextAwareFilters({card:l,interactionStates:oe,currentDashboardId:de,filters:he,filterValues:me,selectedSheetId:se}):{cardFilters:[],cardFilterValues:[]},[l,oe,de,he,me,se]);function Te(Q){const ae=n.cards.find(ue=>ue.id===Q);ae&&(it.flushPendingEditorDrafts(),x(),Le(Q),m(Q),u(),g(ae))}function Le(Q){const ae=t.useEditorStore.getState().card,ue=t.useEditorStore.getState().frame,Se={...ue,cards:ue.cards.map(Oe=>Oe.id===ae.id?ae:Oe),activeCardId:Q};o(Se);const Ne=Se.cards.find(Oe=>Oe.id===Q);Ne.sql&&f(!0),h(Ne)}function De(){if(p)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(!w)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 ae=k.map((ue,Se)=>t.getEffectiveCardTypeForSlot(ue,Se,M==null?void 0:M.slots));return e.jsxs("div",{className:"relative flex h-full flex-col pl-2 pr-4",children:[L.map((ue,Se)=>{if(!ue)return null;const Ne=t.getSlotIndexForCard(ue,Se),Oe=t.getEffectiveCardTypeForSlot(ue,Ne,M==null?void 0:M.slots);return e.jsx(t.MultiInputEmptyRenderer,{onLoadingStatus:te,onDataChange:H,card:ue,effectiveCardType:Oe},`${ue.id}-${Ne}`)}),ie&&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",ie&&"opacity-50"),children:e.jsx(N.Suspense,{fallback:e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(t.LoadingDots,{size:"md",color:"muted"})}),children:e.jsx(w,{editing:!0,...t.buildMultiInputCustomVisualProps({configCard:l,slotOrderedCards:k,slotTypes:ae,multiInputData:v,params:y,theme:T,filters:ge,filterValues:[...Z||[],...je||[]],inlineFilters:X})})})})]})}function Ee(){var Q;return j?De():s&&(a||!_&&!G&&!q)?s({card:r,data:B,isLoading:_,isFetching:G,isError:q}):r.type==="kpi"?_||G?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"w-1/2 space-y-3",children:[e.jsx(Lr,{visible:!0}),e.jsx("div",{className:"rounded-md border border-border",children:e.jsx(t.KPICard,{card:r,data:B==null?void 0:B.records,isPending:_||G,isError:q,comparisonMetadata:(Q=B==null?void 0:B.metadata)==null?void 0:Q.comparisonMetadata})}),t.isCardSummaryVisibleOnCard(r)&&e.jsx(t.CardSummary,{card:r,mode:"editor"})]})}):r.type==="text"?_||G?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(t.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(t.TextCard,{isLoading:d,card:r,data:B==null?void 0:B.records})})})}):e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackVisual,children:e.jsx(Bn,{className:"grow border-none shadow-none"})})}return e.jsxs(t.Tabs,{onValueChange:Te,value:n.activeCardId,className:"flex grow flex-col gap-2",children:[j?e.jsx("div",{className:"mt-0 grow",children:Ee()}):n.cards.map(Q=>e.jsx(t.TabsContent,{className:"mt-0 grow focus-visible:ring-0 focus-visible:ring-offset-0",value:Q.id,children:Ee()},Q.id)),e.jsx(Fr,{isPreviewMode:j,onPreviewToggle:i,configCard:l})]})}function Rr({onClick:s,className:a}){return e.jsxs(t.Button,{type:"button",size:"sm",variant:"outline",className:t.cn("h-8 gap-1.5 px-3 text-xs",a),onClick:s,children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5 shrink-0"}),"Customize"]})}function qn({fallbackPreview:s,records:a,title:n,isInspectorOpen:r,onInspectorOpenChange:c}){var M;const i=t.useEditorStore(F=>F.card),l=t.useEditorStore(F=>F.actions.setCard),d=t.useEditorStore(F=>F.actions.updateCardInFrame),o=t.normalizeDynamicRendererSource((M=i.dynamicCardPreferences)==null?void 0:M.rendererCode),[m,h]=N.useState(o),[f,x]=N.useState(o);N.useEffect(()=>{h(o),x(o)},[o,i.id]);const u=N.useMemo(()=>t.normalizeDynamicRendererSource(m),[m]),g=N.useMemo(()=>t.validateDynamicRendererSource(u),[u]),v=!!o,b=N.useMemo(()=>{var F;return t.buildCardWithVisualizationMode(i,f?"dynamic":"builtin",{rendererCode:f||void 0,artifactId:((F=i.dynamicCardPreferences)==null?void 0:F.artifactId)||i.id,title:n||i.title})},[i,f,n]),S=!!f,I=u!==f,P=f!==o,C=!u||!g.valid||I||P,A=u?g.valid?I?"Unapplied changes":"Pending save":"Needs attention":"Draft",y=!u||I||P?"outline":"destructive",T=u?g.valid?I?"The preview still reflects the last applied code until you apply this draft.":P?"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 E(){if(!g.valid){t.ue.error(g.error||"Visual code is invalid.");return}x(u),t.ue.success("Dynamic preview updated.")}function D(){h(f)}function p(){var j;const F=t.buildCardWithVisualizationMode(i,f?"dynamic":"builtin",{rendererCode:f||void 0,artifactId:((j=i.dynamicCardPreferences)==null?void 0:j.artifactId)||t.v4(),title:n||i.title});l(F),d(F),c(!1),t.ue.success(f?"Dynamic visual changes saved.":"Dynamic visual cleared.")}function R(){h(o),x(o),c(!1)}function w(){h(""),x("")}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:a,title:n,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(Rr,{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."})]}),C&&e.jsx(t.Badge,{className:"mr-4 shrink-0",variant:y,children:A})]})}),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:S?e.jsx(t.PersistedDynamicVisual,{card:b,records:a,title:n,layoutMode:"fill",fallback:s},f||"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&&!u,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:w,children:"Clear"})]})]})]}),e.jsxs(t.Button,{type:"button",size:"sm",variant:"outline",className:"h-8 gap-1.5 px-2.5 text-xs",onClick:D,disabled:!I,children:[e.jsx(is,{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:E,disabled:!I||!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:[T&&e.jsx("p",{className:t.cn("text-xs",g.valid?"text-muted-foreground":"text-destructive"),children:T}),e.jsx("div",{className:t.cn("min-h-0 flex-1 overflow-hidden rounded-md border",!g.valid&&u&&"border-destructive"),children:e.jsx(t.CodeEditor,{value:m,onValueChange:F=>h(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:T||"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:p,disabled:!P,children:"Accept changes"})]})]})]})})]})}function $n({onCustomize:s}){const a=t.useEditorStore(m=>m.card),n=t.useEditorStore(m=>m.frame),r=t.useEditorStore(m=>m.actions.setIsShowingVisual),{setVisualizationMode:c,setDynamicCardPreferences:i}=t.useEditorActions(),d=t.getVisualizationMode(a)==="dynamic";if(n.cards.length!==1||t.isCustomVisualizationCard(a))return null;const o=m=>{var h;m==="dynamic"&&!a.dynamicCardPreferences&&i(t.createEmptyDynamicCardPreferences(a.type,(h=a.preferences)==null?void 0:h.displayOptions)),c(m),r(!0)};return e.jsxs(e.Fragment,{children:[e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{onSelect:m=>{m.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:m=>o(m?"dynamic":"builtin"),onClick:m=>m.stopPropagation()})]}),d&&s?e.jsxs(t.DropdownMenuItem,{onSelect:m=>{m.preventDefault(),s()},children:[e.jsx(t.SlidersHorizontal,{className:"mr-2 h-4 w-4"}),"Customize Visual"]}):null]})}function hn({children:s,visualAsideControl:a}){var me;const n=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.editorContext),o=(d==null?void 0:d.type)==="documentSection",m=t.useEditorStore(se=>se.isShowingVisual),h=t.useEditorStore(se=>se.actions.setIsShowingVisual),f=t.useDashboardStore(se=>se.isVisualEditing),{isConsoleMode:x}=t.useDashboardPreferences(),u=t.useEditorStore(se=>se.pythonStdOut),g=t.useEditorStore(se=>se.actions.setRunSql),v=Ae.useEffectiveEditorCardType(),S=t.getVisualizationMode(c)==="dynamic",[I,P]=N.useState(!1),{setFrame:C,setCard:A,setActiveTabCardId:y,setCardPreferences:T,mergeDraftsIntoCard:E,clearModeDrafts:D,initializeModeDrafts:p,updatePageSize:R}=t.useEditorActions(),w=N.useMemo(()=>v!==c.type?{...c,type:v}:c,[c,v]),{data:M,isLoading:F,isFetching:j,errorMessage:L,errorSql:k,refetch:O,queryKey:z,pagination:V}=t.useEditorCardQuery(w),B=N.useRef(z);B.current=z;const{handleDebugWithAssistant:_}=Pn(L,k),G=N.useMemo(()=>(M==null?void 0:M.records)||[],[M==null?void 0:M.records]),[q,H]=N.useState(!1);N.useEffect(()=>{j||H(!1)},[j]),N.useEffect(()=>{i&&!m&&!l&&!x&&h(!0)},[x,l,i,m,h]);function te(se,je){var X,ge;const be={...c,paginationConfig:{page:se+1,pageSize:je}};A(be);const ye={...r,cards:r.cards.map(Z=>Z.id===c.id?be:Z)};C(ye),c.sql&&((ge=(X=c.preferences)==null?void 0:X.tablePrefs)!=null&&ge.enableDevModePagination)&&g(!0)}function ie(se){var X,ge,Z,Te,Le;const je=t.sortStateToSortByColumns(se,(X=c.config)==null?void 0:X.metricColumns,(ge=c.config)==null?void 0:ge.groupByColumns,(Z=c.config)==null?void 0:Z.detailColumns),be={...c,config:{...c.config||{},sortByColumns:je}};A(be);const ye={...r,cards:r.cards.map(De=>De.id===c.id?be:De)};C(ye),c.sql&&((Le=(Te=c.preferences)==null?void 0:Te.tablePrefs)!=null&&Le.enableDevModePagination)&&g(!0)}function oe(){var je;const se=JSON.stringify(M==null?void 0:M.records,null,2);typeof navigator>"u"||!((je=navigator.clipboard)!=null&&je.writeText)||navigator.clipboard.writeText(se).catch(be=>{console.error("Failed to copy JSON",be)})}function de(){const se=JSON.stringify(M==null?void 0:M.records,null,2),je=new Blob([se],{type:"application/json"}),be=URL.createObjectURL(je),ye=document.createElement("a");ye.href=be,ye.download=`${c.title}.json`,ye.click()}function he(){const je=[Object.keys(M==null?void 0:M.records.reduce((ge,Z)=>({...ge,...Z}),{})).join(","),...((M==null?void 0:M.records)||[]).map(ge=>Object.values(ge).join(","))].join(`
|
|
187
|
+
`),be=new Blob([je],{type:"text/csv"}),ye=URL.createObjectURL(be),X=document.createElement("a");X.href=ye,X.download=`${c.title}.csv`,X.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:[m&&e.jsx("div",{className:"flex grow items-center",children:e.jsxs("div",{className:"flex items-center gap-3",children:[(a==null?void 0:a.show)&&e.jsx(t.IconButton,{tooltip:a.isOpen?"Hide Visual Aside":"Show Visual Aside",className:"h-7 w-7 px-0",buttonProps:{variant:"outline"},onClick:a.onToggle,children:a.isOpen?e.jsx(t.ChevronLeft,{className:"h-3.5 w-3.5"}):e.jsx(t.ChevronRight,{className:"h-3.5 w-3.5"})}),!o&&!S&&e.jsx("div",{className:"w-[200px]",children:e.jsx(zn,{variant:l?"secondary":"ghost"})})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[s,e.jsx(t.IconButton,{tooltip:"Refresh",disabled:F||j,className:"h-7 w-7 px-0",onClick:()=>{if(H(!0),l){it.flushPendingEditorDrafts(),setTimeout(()=>{n.removeQueries({queryKey:B.current,exact:!0}),g(!0)},0);return}O()},children:e.jsx(t.RefreshCcw,{className:t.cn("h-3.5 w-3.5",{"animate-spin":q})})}),!S&&e.jsx(_n,{showInlineFilters:!1,showDisplayOptions:!1}),(l||x)&&e.jsxs(e.Fragment,{children:[e.jsx(Vr,{}),i&&e.jsxs(e.Fragment,{children:[e.jsx(Pr,{}),e.jsx(Br,{})]})]}),e.jsxs(t.DropdownMenu,{modal:!1,children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"More Options",className:"h-7 w-7 px-0","aria-label":"More options",children:e.jsx(t.EllipsisVertical,{className:"h-3.5 w-3.5"})})}),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:[!S&&!["table","detailTable","custom"].includes(c.type)&&f&&e.jsx(jr,{triggerVariant:"menu",className:"w-full"}),e.jsx(hs,{triggerVariant:"menu",className:"w-full"}),e.jsx(xs,{triggerVariant:"menu",className:"w-full"}),e.jsx($n,{onCustomize:()=>P(!0)}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.Button,{variant:"ghost",className:"h-7 w-full justify-start gap-2 px-2 text-[13px]",onClick:he,children:[e.jsx(t.Download,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Download CSV"})]}),e.jsxs(t.Button,{variant:"ghost",className:"h-7 w-full justify-start gap-2 px-2 text-[13px]",onClick:de,children:[e.jsx(ja,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Download JSON"})]}),e.jsxs(t.Button,{variant:"ghost",className:"h-7 w-full justify-start gap-2 px-2 text-[13px]",onClick:oe,children:[e.jsx(t.Copy,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Copy JSON"})]})]})]})]})]})]}),m?S?e.jsx(ot,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(qn,{fallbackPreview:e.jsx(ot,{}),records:G,title:c.title,isInspectorOpen:I,onInspectorOpenChange:P})}):e.jsx(ot,{}):e.jsxs(t.ResizablePanelGroup,{className:"py-2 pl-2 pr-6",direction:"horizontal",children:[u&&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:u&&e.jsx(Or,{})}),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":u}),children:[Array.isArray(M==null?void 0:M.records)&&!L&&(l?e.jsx(hr,{data:M.records,card:w,paginationMetadata:V,onPaginationChange:te,onPageSizePreferenceChange:R,onSortChange:ie,isLoading:F||j}):M.records.length>0?e.jsx(t.TableVisual,{card:c,data:G,comparisonMetadata:(me=M==null?void 0:M.metadata)==null?void 0:me.comparisonMetadata,paginationMetadata:V,onPaginationChange:te,onSortChange:ie,isLoading:F||j}):null),L&&e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(us,{error:L,errorSql:k||c.sql||c.python,onDebugWithAssistant:_,showFeedbackButton:!1})})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function Or(){const s=t.useEditorStore(n=>n.pythonStdOut);if(!s)return null;const a=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:a}}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function Pr(){var n,r;const s=t.useEditorStore(c=>c.card),a=t.useEditorStore(c=>c.actions.setCardPreferences);return s.type!=="table"&&s.type!=="detailTable"?null:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(t.Label,{htmlFor:"table-density",className:"text-[13px]",children:"Density"}),e.jsxs(t.Select,{value:((r=(n=s.preferences)==null?void 0:n.tablePrefs)==null?void 0:r.density)??"compact",onValueChange:c=>{var i;a({...s.preferences,tablePrefs:{...(i=s.preferences)==null?void 0:i.tablePrefs,density:c}})},children:[e.jsx(t.SelectTrigger,{id:"table-density",className:"h-7 w-[116px] rounded-[5px] px-2 text-[12px]",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"compact",children:"Compact"}),e.jsx(t.SelectItem,{value:"comfortable",children:"Comfortable"}),e.jsx(t.SelectItem,{value:"spacious",children:"Spacious"})]})]})]})}function Br(){var d,o,m,h,f,x,u,g;const s=t.useEditorStore(v=>v.card),a=t.useEditorStore(v=>v.actions.setCard),n=t.useEditorStore(v=>v.actions.setRunSql),r=t.useEditorStore(v=>v.actions.setCardPreferences),c=t.useEditorStore(v=>v.actions.updateCardInFrame),i=N.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((h=(m=s.preferences)==null?void 0:m.tablePrefs)==null?void 0:h.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:((x=(f=s.preferences)==null?void 0:f.tablePrefs)==null?void 0:x.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-[13px]",children:"Paginate"}),((g=(u=s.preferences)==null?void 0:u.tablePrefs)==null?void 0:g.enableDevModePagination)&&e.jsxs(t.Select,{value:String(l),onValueChange:v=>{var I,P,C;const b=Number(v),S={...s,preferences:{...s.preferences,tablePrefs:{...(I=s.preferences)==null?void 0:I.tablePrefs,pageSize:b}},paginationConfig:{page:1,pageSize:b}};a(S),c(S),s.sql&&((C=(P=s.preferences)==null?void 0:P.tablePrefs)!=null&&C.enableDevModePagination)&&n(!0)},children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20 rounded-[5px] px-2 text-[12px]",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:i.map(v=>e.jsx(t.SelectItem,{value:String(v),children:v},v))})]})]})}function Vr(){const s=t.useEditorStore(n=>n.isShowingVisual),a=t.useEditorStore(n=>n.actions.setIsShowingVisual);return e.jsxs(t.Toggle,{pressed:!s,onPressedChange:n=>{a(!n)},variant:"default",size:"sm",className:"h-7 gap-1.5 rounded-[5px] border border-transparent px-2.5 text-[12px] 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-3.5 w-3.5"}),e.jsx("span",{children:"Query Output"})]})}function qe({value:s,onCommit:a,type:n="text",placeholder:r,className:c}){const[i,l]=N.useState(s),d=N.useRef(!1);N.useEffect(()=>{l(s)},[s]);const o=()=>{if(d.current){d.current=!1;return}i!==s&&a(i)},m=h=>{if(h.key==="Enter"){h.currentTarget.blur();return}h.key==="Escape"&&(d.current=!0,l(s),h.currentTarget.blur())};return e.jsx(t.Input,{type:n,placeholder:r,value:i,onChange:h=>l(h.target.value),onBlur:o,onKeyDown:m,className:c})}function nt({defaultValue:s,label:a,options:n,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:a})]})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:a}),n.map(o=>e.jsx(t.SelectItem,{value:o.value,children:o.label},o.value))]})})]})}function zr(s,a){return t.getSlotDefinitionForIndex(s,a)||null}function St(s){if(typeof s=="number")return`Tab ${s+1}`;const a=s.match(/^(\d+)-(\d+)$/);if(a){const[,r,c]=a;return`Tabs ${Number(r)+1}-${Number(c)+1}`}const n=s.match(/^(\d+)\+$/);return n?`Tabs ${Number(n[1])+1}+`:`Tab ${s}`}function _r(s){return s?Array.isArray(s)?s:[s]:[]}function ss(s){var r,c;if(!s)return!1;if(s.type==="text")return!!((r=s.description)!=null&&r.trim());const a=!!((c=s.sql)!=null&&c.trim()),n=t.hasValidCardConfig(s.config);return a||n}function qr({slots:s,cards:a,minInputs:n}){const r=[],c=a.filter(Boolean).length;return n&&c<n&&r.push({type:"too-few-inputs",message:`This visual requires at least ${n} tab${n===1?"":"s"}.`}),!s||s.length===0||(s.forEach(i=>{if(!i.required)return;if(typeof i.position=="number"){const o=a[i.position];ss(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,m]=l.map(Number);for(let h=o;h<=m;h+=1){const f=a[h];if(!ss(f)){r.push({type:"missing-required",message:`${St(h)} ("${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(a.length<=o){r.push({type:"missing-required",message:`${St(o)} ("${i.label}") is required but has no data configured.`});return}for(let m=o;m<a.length;m+=1){const h=a[m];if(!ss(h)){r.push({type:"missing-required",message:`${St(m)} ("${i.label}") is required but has no data configured.`});break}}}}),a.forEach((i,l)=>{if(!i)return;const d=zr(s,l);if(!d||!d.expectedType)return;const o=_r(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 $r={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:a})=>(a==null?void 0:a.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 Kn(){var w,M,F;const s=t.useEditorStore(j=>j.card.customCardPreferences),{data:a}=t.usePluginQuery(),n=(a==null?void 0:a.plugins)||[],r=t.useEditorStore(j=>j.card),c=t.useEditorStore(j=>j.frame),{setCustomCardPreferences:i}=t.useEditorActions(),l=N.useMemo(()=>t.findCustomVisualConfigCard(c,r),[c,r]),d=l==null?void 0:l.customCardPreferences,{components:o,manifest:m}=t.useCustomVisual((d==null?void 0:d.url)||(s==null?void 0:s.url)||""),h=(w=m==null?void 0:m.visuals)==null?void 0:w.find(j=>j.name===((d==null?void 0:d.componentName)||(s==null?void 0:s.componentName))),x=t.resolveMultiInputType(l||r,h)==="multiple",u=!!l&&l.id===r.id,g=(h==null?void 0:h.minInputs)??((M=l==null?void 0:l.customCardPreferences)==null?void 0:M.minInputs),v=(h==null?void 0:h.maxInputs)??((F=l==null?void 0:l.customCardPreferences)==null?void 0:F.maxInputs),b=N.useMemo(()=>t.getCustomVisualInputCards({frame:c,configCard:l||r,isMultiInputVisual:x}),[c,l,r,x]),S=N.useMemo(()=>t.buildSlotOrderedCards(b),[b]),I=N.useMemo(()=>S.map((j,L)=>{if(!j)return null;const k=t.getSlotIndexForCard(j,L),O=t.getEffectiveCardTypeForSlot(j,k,h==null?void 0:h.slots);return{...j,type:O??j.type}}),[S,h==null?void 0:h.slots]),P=N.useMemo(()=>qr({slots:h==null?void 0:h.slots,cards:I,minInputs:g}),[h==null?void 0:h.slots,I,g]),C=N.useMemo(()=>{const j=b.findIndex(L=>(L==null?void 0:L.id)===r.id);return j<0?-1:t.getSlotIndexForCard(r,j)},[b,r]);function A(j){if(typeof j=="number")return`Tab ${j+1}`;const L=j.match(/^(\d+)-(\d+)$/);if(L){const[,O,z]=L;return`Tabs ${Number(O)+1}-${Number(z)+1}`}const k=j.match(/^(\d+)\+$/);return k?`Tabs ${Number(k[1])+1}+`:`Tab ${j}`}function y(j){return j?(Array.isArray(j)?j:[j]).join(", "):null}function T(j,L,k=[],O="",z,V,B){const _=E({key:L,defaultValue:O,settingsValue:V,sourceCard:B});return j==="input"?e.jsx(qe,{className:`h-8 w-full ${t.removeRing}`,value:String(_??""),onCommit:G=>{D({key:L,value:G,settingsField:z,settingsValue:V,sourceCard:B})}},L):j==="select"?e.jsx(nt,{className:"h-8 w-full",label:"",options:k,value:String(_!==void 0?_:O??""),onValueChange:G=>{D({key:L,value:G,settingsField:z,settingsValue:V,sourceCard:B})}}):null}function E({key:j,defaultValue:L,settingsValue:k,sourceCard:O}){const z=k==null?void 0:k[j];return z!==void 0?z:j==="title"&&(O==null?void 0:O.title)!==void 0?O.title:j==="description"&&(O==null?void 0:O.description)!==void 0?O.description:L}function D({key:j,value:L,settingsField:k,settingsValue:O,sourceCard:z}){const V={...O||{}},B=j==="title"&&(z==null?void 0:z.title)!==void 0,_=j==="description"&&(z==null?void 0:z.description)!==void 0;B&&L===String((z==null?void 0:z.title)??"")||_&&L===String((z==null?void 0:z.description)??"")?delete V[j]:V[j]=L,i({...s||{},[k]:V})}function p({settingsSchema:j,settingsField:L,settingsValue:k,sourceCard:O,headerLabel:z}){const V=Object.entries(j||{});return e.jsxs("div",{className:"space-y-3",children:[z&&e.jsx(t.Label,{children:z}),V.map(([B,_])=>{var G;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{children:_.title}),((G=_.docs)==null?void 0:G.description)&&e.jsx(t.TooltipProvider,{delayDuration:0,children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{className:"text-xs",children:_.docs.description})})]})})]}),T(_.ui,B,_.options,_.defaultValue,L,k,O)]},B)})]})}function R(){return e.jsxs(e.Fragment,{children:[x&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Slot Guide"}),e.jsx("div",{className:"space-y-3 rounded-md border border-border bg-muted/40 px-3 py-2 text-xs",children:h!=null&&h.slots&&h.slots.length>0?e.jsx("div",{className:"space-y-3",children:h.slots.map((j,L)=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-foreground",children:[e.jsx("span",{className:"font-medium",children:A(j.position)}),e.jsx("span",{className:"text-muted-foreground",children:"•"}),e.jsx("span",{className:"font-medium",children:j.label})]}),j.description&&e.jsx("p",{className:"text-muted-foreground",children:j.description}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-muted-foreground",children:[y(j.expectedType)&&e.jsxs("span",{children:["Expected: ",y(j.expectedType)]}),j.required&&e.jsx("span",{children:"Required"})]})]},`${j.label}-${L}`))}):e.jsxs("div",{className:"space-y-1 text-muted-foreground",children:[e.jsx("p",{children:"This visual renders all tabs in a flexible layout. Add as many tabs as needed."}),(g||v)&&e.jsxs("p",{children:[g?`Min ${g} tabs`:"",g&&v?" • ":"",v?`Max ${v} tabs`:""]})]})})]}),x&&P.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:P.map((j,L)=>e.jsx("li",{children:j.message},`${j.type}-${L}`))})})}),h&&!x&&h.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:p({settingsSchema:h.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:r})})}),h&&x&&(h.settings||h.slotSettings)&&e.jsxs("div",{className:"mt-4 space-y-4",children:[u&&h.settings&&e.jsx("div",{className:"px-2",children:p({settingsSchema:h.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:l||r,headerLabel:"Global Settings"})}),h.slotSettings&&e.jsx("div",{className:"px-2",children:p({settingsSchema:h.slotSettings,settingsField:"slotSettings",settingsValue:s==null?void 0:s.slotSettings,sourceCard:r,headerLabel:(()=>{const j=r.tabTitle||r.title,L=C>=0?C:0,k=u?"Slot 0":`Slot ${L}`;return j?`${k}: ${j} Settings`:`${k} 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:[(!x||u)&&e.jsx(nt,{icon:e.jsx(Dn,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(d==null?void 0:d.url)||"",onValueChange:j=>i({...s||{url:"",componentName:""},url:j})}),x&&!u&&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&&(!x||u)&&e.jsx(e.Fragment,{children:o&&e.jsx(nt,{icon:e.jsx(ba,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(o==null?void 0:o.map(j=>({value:j.name,label:j.name})))||[],value:s.componentName||"",onValueChange:j=>{var O;const L=(O=m==null?void 0:m.visuals)==null?void 0:O.find(z=>z.name===j),k=o==null?void 0:o.find(z=>z.name===j);i({...s,componentName:j,visualType:(L==null?void 0:L.visualType)||(k==null?void 0:k.type)||"single",minInputs:L==null?void 0:L.minInputs,maxInputs:L==null?void 0:L.maxInputs,pluginChartType:L==null?void 0:L.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:(h==null?void 0:h.name)||"Settings"}),(h==null?void 0:h.docs)&&e.jsxs(t.HoverCard,{openDelay:0,closeDelay:100,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,onClick:j=>j.stopPropagation(),children:e.jsx(t.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground transition-colors hover:text-foreground"})}),e.jsx(t.HoverCardContent,{side:"right",align:"start",className:"max-h-[40vh] w-[500px] overflow-y-auto text-left",children:e.jsxs("div",{className:"space-y-4 text-left",children:[h.docs.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:h.docs.description}),h.docs.dataSchema&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Data Schema"}),e.jsx("div",{className:"prose prose-sm dark:prose-invert prose-pre:bg-muted prose-pre:text-xs max-w-none",children:e.jsx(t.Markdown,{remarkPlugins:[t.remarkGfm],components:$r,children:h.docs.dataSchema})})]}),(()=>{var L;const j=(L=h.docs)==null?void 0:L.useCases;return!j||j.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:j.map((k,O)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1 text-primary",children:"•"}),e.jsx("span",{children:k})]},O))})]})})()]})})]})]})}),e.jsx(t.AccordionContent,{children:R()})]})]})}function Kr({colorRanges:s,setColorRanges:a}){const n={start:-1/0,end:100,color:""};function r(l,d,o){const m=[...s];m[l]={...m[l],[d]:o},a(m)}function c(l){const d=[...s];d.splice(l,1),a(d)}function i(){a([...s,n])}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 Gr(){var h,f,x,u,g;const s=t.useEditorStore(v=>v.card.preferences),a=t.useEditorStore(v=>v.actions.setCardPreferences),n=t.useEditorStore(v=>v.card),r=t.hasValidCardConfig(n.config),c=t.useEditorStore(v=>v.actions.setNumberFormat);t.useEditorStore(v=>{var b,S;return(S=(b=v.card.preferences)==null?void 0:b.formatNumber)==null?void 0:S.decimalPlaces});const i=t.useEditorStore(v=>{var b,S;return(S=(b=v.card.preferences)==null?void 0:b.formatNumber)==null?void 0:S.locale}),l=t.useEditorStore(v=>{var b,S;return(S=(b=v.card.preferences)==null?void 0:b.formatNumber)==null?void 0:S.currency});t.useEditorStore(v=>v.actions.setFilterOnClickField);const d=t.useEditorStore(v=>{var b,S;return(S=(b=v.card.preferences)==null?void 0:b.formatNumber)==null?void 0:S.colorRanges})||[],o=t.useEditorStore(v=>v.actions.setColorRanges),m=[...new Set(t.LOCALE_CURRENCY_PAIRS.map(v=>v.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(t.Checkbox,{checked:!!((h=s==null?void 0:s.formatNumber)!=null&&h.enabled),onCheckedChange:v=>{a({...s,formatNumber:{...s==null?void 0:s.formatNumber,enabled:v}})}}),e.jsx(t.Label,{children:"Format Number"})]}),(((f=s==null?void 0:s.formatNumber)==null?void 0:f.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,S,I;return c(((b=s==null?void 0:s.formatNumber)==null?void 0:b.decimalPlaces)||0,((S=s==null?void 0:s.formatNumber)==null?void 0:S.currency)||"",v,((I=s==null?void 0:s.formatNumber)==null?void 0:I.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,S,I;console.log("currency",v),c(((b=s==null?void 0:s.formatNumber)==null?void 0:b.decimalPlaces)||0,v==="none"?"":v,((S=s==null?void 0:s.formatNumber)==null?void 0:S.locale)||"",((I=s==null?void 0:s.formatNumber)==null?void 0:I.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"),m.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:((u=(x=s==null?void 0:s.formatNumber)==null?void 0:x.decimalPlaces)==null?void 0:u.toString())||"0",onValueChange:v=>{var b,S,I;return c(Number(v),((b=s==null?void 0:s.formatNumber)==null?void 0:b.currency)||"",((S=s==null?void 0:s.formatNumber)==null?void 0:S.locale)||"",((I=s==null?void 0:s.formatNumber)==null?void 0:I.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,S,I;return c(((b=s==null?void 0:s.formatNumber)==null?void 0:b.decimalPlaces)||0,((S=s==null?void 0:s.formatNumber)==null?void 0:S.currency)||"",((I=s==null?void 0:s.formatNumber)==null?void 0:I.locale)||"",v.target.value)}})]})]})]})}),e.jsx(t.Separator,{className:"my-3"}),e.jsx(Kr,{colorRanges:d,setColorRanges:o})]})]})}const Ur={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 Gn(s){return Ur[s]}function Hr({chartType:s,showDocsLink:a=!0}){const n=Gn(s);return n?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:n.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:n.fields.map((r,c)=>e.jsxs("tr",{className:c<n.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:n.description}),a&&n.docsUrl&&e.jsxs("a",{href:n.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 Qr({chartType:s}){return Gn(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(Hr,{chartType:s})})]}):null}function _t({chartType:s,suffix:a="Configuration"}){return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-medium",children:a}),e.jsx(Qr,{chartType:s})]})}function Jr(){return e.jsxs("div",{className:"space-y-6 px-6 py-4",children:[e.jsx(_t,{chartType:"kpi"}),e.jsx("section",{children:e.jsx(Gr,{})})]})}function pn({children:s,summary:a,open:n,className:r}){return e.jsxs("details",{open:n,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:a}),e.jsx(t.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:s})]})}function Un(){const[s,a]=N.useState([]),n=t.useEditorStore(m=>m.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:c}=t.useEditorStore(m=>m.actions),i=t.useEditorStore(m=>m.queryResultColumns);t.useEditorStore(m=>{var h;return(h=m.card.preferences)==null?void 0:h.filterOnClickColumnIndex}),N.useEffect(()=>{i&&a(new Array(i.length).fill(!1))},[i]);function l(m,h){var f,x;h?n!=null&&n.onClickFilter&&((f=n==null?void 0:n.onClickFilter)==null?void 0:f.length)>0?c({...n,onClickFilter:[...n.onClickFilter,{columnIndex:m,expression:""}]}):c({...n,onClickFilter:[{columnIndex:m,expression:""}]}):(c({...n,onClickFilter:(x=n==null?void 0:n.onClickFilter)==null?void 0:x.filter(u=>u.columnIndex!==m)}),a(u=>{const g=[...u];return g[m]=!1,g}))}function d(m,h){var x;const f=(x=n==null?void 0:n.onClickFilter)==null?void 0:x.map(u=>u.columnIndex===m?{...u,expression:h.target.value}:u);c({...n,onClickFilter:f})}function o(m){var h,f,x,u;if(s!=null&&s[m]||(f=(h=n==null?void 0:n.onClickFilter)==null?void 0:h.find(g=>g.columnIndex===m))!=null&&f.expression)return e.jsx(t.Input,{value:(u=(x=n==null?void 0:n.onClickFilter)==null?void 0:x.find(g=>g.columnIndex===m))==null?void 0:u.expression,onChange:g=>d(m,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((m,h)=>{var f,x;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(t.Checkbox,{checked:!!((f=n==null?void 0:n.onClickFilter)!=null&&f.find(u=>u.columnIndex===h)),onCheckedChange:u=>l(h,u)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:m}),e.jsx("div",{className:"flex items-center gap-2",children:((x=n==null?void 0:n.onClickFilter)==null?void 0:x.find(u=>u.columnIndex===h))&&e.jsx(t.Pencil,{onClick:()=>{a(u=>{const g=[...u];return g[h]=!u[h],g})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),o(h)]})},m)})})}const Wr=[{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"}],Yr=["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"],Xr=Yr.map(s=>({label:s,value:s}));function Zr(){var o,m,h,f,x,u,g,v,b,S,I,P,C,A,y,T,E,D;const s=t.useEditorStore(p=>p.card),a=(m=(o=s==null?void 0:s.preferences)==null?void 0:o.mapVisualOptions)==null?void 0:m.topoJsonUrl,[n,r]=N.useState(((f=(h=s==null?void 0:s.preferences)==null?void 0:h.mapVisualOptions)==null?void 0:f.customTopoJsonUrl)||""),{setCardPreferences:c}=t.useEditorActions(),{data:i}=t.useTopoJson(s),l=Object.keys((i==null?void 0:i.objects)||{}).map(p=>({label:p,value:p}))||[],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(pn,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(nt,{className:"h-9",options:d,onValueChange:p=>{console.log("value",p),c({...s.preferences,mapVisualOptions:{topoJsonUrl:p}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(t.Input,{onChange:p=>{r(p.target.value)},onBlur:()=>{var p;console.log("onBlur",n),c({...s.preferences,mapVisualOptions:{...(p=s.preferences)==null?void 0:p.mapVisualOptions,customTopoJsonUrl:n}})},value:n,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(nt,{className:"h-9",options:l,value:((u=(x=s.preferences)==null?void 0:x.mapVisualOptions)==null?void 0:u.objectKey)||"",label:"Map Object",onValueChange:p=>{var R;c({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,objectKey:p}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Projection"}),e.jsx(nt,{className:"h-9",options:Wr,value:((v=(g=s.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:v.projection)||"",label:"Projection",onValueChange:p=>{var R;c({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,projection:p}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Colors"}),e.jsx(nt,{className:"h-9",options:Xr,value:((S=(b=s.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:S.colorScale)||"",label:"Select Color Scale",onValueChange:p=>{var R;c({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,colorScale:p}})}})]})]})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(pn,{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:((P=(I=s.preferences)==null?void 0:I.mapVisualOptions)==null?void 0:P.projectionScale)||1,onChange:p=>{var R;c({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,projectionScale:Number(p.target.value)}})}}),e.jsx(t.Label,{children:"X"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((y=(A=(C=s.preferences)==null?void 0:C.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:y[0])||0,onChange:p=>{var R,w,M,F;c({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,projectionOffset:[Number(p.target.value),((F=(M=(w=s.preferences)==null?void 0:w.mapVisualOptions)==null?void 0:M.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:((D=(E=(T=s.preferences)==null?void 0:T.mapVisualOptions)==null?void 0:E.projectionOffset)==null?void 0:D[1])||0,onChange:p=>{var R,w,M,F;c({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,projectionOffset:[((F=(M=(w=s.preferences)==null?void 0:w.mapVisualOptions)==null?void 0:M.projectionOffset)==null?void 0:F[0])||0,Number(p.target.value)]}})}})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(Un,{})]})}function Hn({color:s,onColorChange:a,onClose:n}){const[r,c]=N.useState(0),[i,l]=N.useState(100),[d,o]=N.useState(50),[m,h]=N.useState(s);N.useEffect(()=>{const b=fn(s);if(b){const S=gn(b.r,b.g,b.b);c(S.h),l(S.s),o(S.l),h(s)}},[s]);const f=b=>{c(b),u(b,i,d)},x=b=>{const S=b.currentTarget.getBoundingClientRect(),I=Math.max(0,Math.min(1,(b.clientX-S.left)/S.width)),P=Math.max(0,Math.min(1,(b.clientY-S.top)/S.height)),C=I*100,A=(1-P)*100;l(C),o(A),u(r,C,A)},u=(b,S,I)=>{const P=tl(b,S,I),C=el(P.r,P.g,P.b);h(C)},g=b=>{if(h(b),/^#[0-9A-Fa-f]{6}$/.test(b)){const S=fn(b);if(S){const I=gn(S.r,S.g,S.b);c(I.h),l(I.s),o(I.l)}}},v=()=>{/^#[0-9A-Fa-f]{6}$/.test(m)&&(a(m),n())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:x,onMouseMove:b=>{b.buttons===1&&x(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:m}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:b=>f(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:m,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:m}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(t.Button,{variant:"outline",onClick:n,children:"Cancel"}),e.jsx(t.Button,{onClick:v,children:"OK"})]})]})}function fn(s){const a=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(s);return a?{r:parseInt(a[1],16),g:parseInt(a[2],16),b:parseInt(a[3],16)}:null}function el(s,a,n){return"#"+((1<<24)+(s<<16)+(a<<8)+n).toString(16).slice(1)}function gn(s,a,n){s/=255,a/=255,n/=255;const r=Math.max(s,a,n),c=Math.min(s,a,n);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=((a-n)/o+(a<n?6:0))/6;break;case a:i=((n-s)/o+2)/6;break;case n:i=((s-a)/o+4)/6;break}}return{h:Math.round(i*360),s:Math.round(l*100),l:Math.round(d*100)}}function tl(s,a,n){s/=360,a/=100,n/=100;let r,c,i;if(a===0)r=c=i=n;else{const l=(m,h,f)=>(f<0&&(f+=1),f>1&&(f-=1),f<.16666666666666666?m+(h-m)*6*f:f<.5?h:f<.6666666666666666?m+(h-m)*(.6666666666666666-f)*6:m),d=n<.5?n*(1+a):n+a-n*a,o=2*n-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 bn=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],sl=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function at({value:s,onChange:a,label:n}){const[r,c]=N.useState(!1),[i,l]=N.useState(!1),d=()=>{const o=bn.find(m=>m.value===s);return o?o.color:s.startsWith("#")?s:bn[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 ${n}`})}),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:sl.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:()=>{a(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:n})]}),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(Hn,{color:d(),onColorChange:o=>{a(o),l(!1)},onClose:()=>l(!1)})})]})]})}function Bt(s){return s==="currency"?2:s==="percent"?1:s==="scientific"?2:0}function jn(s,a){if(!a||a==="auto")return{type:"auto"};const n={...s,type:a,multiplyBy:a==="percent"?s.multiplyBy:void 0,percentValueMode:a==="percent"?s.percentValueMode:void 0};return a&&["number","currency","percent","scientific"].includes(a)&&s.decimalPlaces===void 0&&s.minimumFractionDigits===void 0&&s.maximumFractionDigits===void 0?cs(n,Bt(a)):n}function cs(s,a){return{...s,decimalPlaces:a,minimumFractionDigits:a,maximumFractionDigits:a}}const nl=["auto","number","currency","percent","scientific","date"],al=[{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"}],rl=[{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"}],ll=s=>s.charAt(0).toUpperCase()+s.slice(1);function bt({formatOptions:s={},onFormatOptionsChange:a,showTitle:n=!0,title:r="NUMBER FORMAT"}){const c=s.type||"auto",i=c==="auto"?s:jn(s,c),l=u=>{u.stopPropagation()},d=(u,g)=>{a({...i,[u]:g})},[o,m]=N.useState(()=>String(i.decimalPlaces??Bt(c))),[h,f]=N.useState(()=>i.multiplyBy!==void 0?String(i.multiplyBy):""),x=u=>{a(jn(s,u))};return N.useEffect(()=>{m(String(i.decimalPlaces??Bt(c)))},[i.decimalPlaces,c]),N.useEffect(()=>{f(i.multiplyBy!==void 0?String(i.multiplyBy):"")},[i.multiplyBy]),e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[n&&e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(t.Select,{value:c,onValueChange:u=>x(u),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:nl.map(u=>e.jsx(t.SelectItem,{value:u,className:"text-xs",children:u==="auto"?"Auto (Default)":ll(u)},u))})]})]}),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:u=>{const g=u.target.value.replace(/[^\d]/g,"");m(g),g!==""&&a(cs(i,Math.max(0,Math.min(10,parseInt(g,10)))))},onBlur:()=>{if(o!=="")return;const u=Bt(c);m(String(u)),a(cs(i,u))},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:u=>d("currency",u),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:al.map(u=>e.jsx(t.SelectItem,{value:u.value,className:"text-xs",children:u.label},u.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:u=>u.stopPropagation(),onCheckedChange:u=>d("useSuffix",u)})]}),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:u=>d("locale",u),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:rl.map(u=>e.jsx(t.SelectItem,{value:u.value,className:"text-xs",children:u.label},u.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:u=>d("prefix",u.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:u=>d("suffix",u.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:u=>u.stopPropagation(),onCheckedChange:u=>d("negativeInParentheses",u)})]}),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:h,onClick:l,onPointerDown:l,onKeyDown:l,onChange:u=>{const g=u.target.value.replace(/[^0-9.]/g,"");f(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:u=>d("dateFormat",u.target.value),className:"h-8 text-xs"})})]})]})]})}function ps({value:s,onChange:a,showTitle:n=!0,title:r="NUMBER FORMAT"}){const c=t.toTFormatOptions(t.fromSemanticFormat(s))||{},i=l=>{a(t.fromTFormatOptions(l))};return e.jsx(bt,{formatOptions:c,onFormatOptionsChange:i,showTitle:n,title:r})}function ol(){const s=t.useDashboardStore(d=>d.dashboard.filters),a=t.useEditorStore(d=>d.frame),{setFrame:n}=t.useEditorActions(),{dashboardFilterableFields:r}=t.useFilterableFields(),{assignFilter:c}=t.useAssignFilter();function i(d){const o=c(d,"frame");n({...a,filterId:o})}const l=s==null?void 0:s.find(d=>d.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Card Filter"}),e.jsx(il,{onSelect:i,columns:r}),l&&e.jsx(t.FilterHeader,{filter:l})]})}function il({columns:s,onSelect:a}){var d;const[n,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:n,onOpenChange:r,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,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 m=o.id===c?"":o.id;i(m),r(!1),m&&a(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 cl=[{value:"difference",label:"Difference"},{value:"change",label:"Change (%)"},{value:"change_difference",label:"Change + Difference"},{value:"ratio",label:"Ratio"}],dl=[{value:"arrow_badge",label:"Arrow + Badge"},{value:"arrow",label:"Arrow Only"},{value:"badge",label:"Badge Only"},{value:"none",label:"None"}];function ul({cardType:s="table"}){var h,f,x,u,g;const a=t.useEditorStore(v=>v.card),n=t.useEditorStore(v=>{var b;return(b=v.card)==null?void 0:b.preferences}),r=t.useEditorStore(v=>v.actions.setCardPreferences),c=((h=a.config)==null?void 0:h.metricColumns)||[],i=c.some(v=>v.comparisonType&&v.comparisonType!=="none"),l=((f=n==null?void 0:n.tableVisualOptions)==null?void 0:f.metricComparison)||{},d=v=>{r({...n,tableVisualOptions:{...n==null?void 0:n.tableVisualOptions,metricComparison:{...l,...v}}})},o={increase:((x=l.colors)==null?void 0:x.increase)||"green",decrease:((u=l.colors)==null?void 0:u.decrease)||"red",neutral:((g=l.colors)==null?void 0:g.neutral)||"neutral"},m=v=>{r({...n,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(Mn,{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:cl.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(bt,{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:dl.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(at,{value:o.increase,onChange:v=>d({colors:{...o,increase:v}}),label:"Increase"}),e.jsx(at,{value:o.decrease,onChange:v=>d({colors:{...o,decrease:v}}),label:"Decrease"}),e.jsx(at,{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(ps,{value:v.format,onChange:b=>{var I;const S=(((I=a.config)==null?void 0:I.metricColumns)||[]).map(P=>P.id===v.id?{...P,format:b}:P);t.useEditorStore.getState().actions.updateCardConfig(a.id,{metricColumns:S})},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(Un,{}),e.jsx(ol,{})]})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Checkbox,{onCheckedChange:m,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 ml(){var r;const s=t.useEditorStore(c=>c.card.preferences),{setCardPreferences:a}=t.useEditorStore(c=>c.actions);function n(c){a({...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:n,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 xl(){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(ml,{})]})]})}const hl=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function pl(){var A,y,T,E,D,p,R,w,M,F;const s=t.useEditorStore(j=>j.card),a=t.useEditorStore(j=>{var L;return(L=j.card)==null?void 0:L.preferences}),n=Ae.useEffectiveEditorCardType(),{setCardPreferences:r,updateCardInFrame:c}=t.useEditorActions(),i=N.useMemo(()=>n!==s.type?{...s,type:n}:s,[s,n]),{data:l}=t.useEditorCardQuery(i),[d,o]=N.useState({}),[m,h]=N.useState(null),[f,x]=N.useState(null),u=N.useMemo(()=>{var O,z,V,B,_,G,q;if(!(l!=null&&l.records)||l.records.length===0)return[];const j=n==="stackedBar"||n==="stackedLine",L=n==="bar"||n==="line"||n==="horizontalBar"||n==="bullet"||n==="combo"||n==="area"||n==="stackedArea",k=((O=s==null?void 0:s.config)==null?void 0:O.pivotByColumns)&&s.config.pivotByColumns.length>0;if((j||L)&&k){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const H=new Set;return l.pivotSchema.forEach(te=>{te.alias&&H.add(te.alias)}),Array.from(H)}if(l.records.length>0){const H=l.records[0],te=Object.keys(H),ie=new Set;(z=s==null?void 0:s.config)!=null&&z.groupByColumns&&s.config.groupByColumns.forEach(he=>{ie.add(he.label||he.name),ie.add(he.alias||he.name)});const oe=new Set;return(V=s==null?void 0:s.config)!=null&&V.metricColumns&&s.config.metricColumns.forEach(he=>{const me=he.alias||he.name;oe.add(me),oe.add(`${me}_count`),oe.add(`${me}_sum`),oe.add(`${me}_avg`),oe.add(`${me}_min`),oe.add(`${me}_max`);const se=he.entityName||he.qualifiedEntityName;se&&(oe.add(`${se}_${me}`),oe.add(`${se}_${me}_count`))}),te.filter(he=>!ie.has(he)&&!oe.has(he))}}if((L||j)&&!k&&((_=(B=s==null?void 0:s.config)==null?void 0:B.metricColumns)!=null&&_.length))return s.config.metricColumns.map(H=>H.alias||H.label||H.name);if((q=(G=s==null?void 0:s.config)==null?void 0:G.groupByColumns)!=null&&q.length){const H=s.config.groupByColumns[0],te=H.label||H.name,ie=new Set;return l.records.forEach(oe=>{const de=oe[te];de!=null&&ie.add(String(de))}),Array.from(ie)}return[]},[l,(A=s==null?void 0:s.config)==null?void 0:A.groupByColumns,(y=s==null?void 0:s.config)==null?void 0:y.pivotByColumns,(T=s==null?void 0:s.config)==null?void 0:T.metricColumns,n]),g=N.useMemo(()=>t.getDefaultChartColors(),[]);N.useEffect(()=>{const j={};u.forEach((L,k)=>{j[L]=t.getColorForValue(L,k,a==null?void 0:a.colorConfig)}),o(j)},[u,a==null?void 0:a.colorConfig,g]);const v=(j,L)=>{const k={...d,[j]:L};o(k);const O={...a||{},colorConfig:{segments:k}};r(O);const z={...s,preferences:O};c(z)},b=(j,L)=>{var _;const k=g[L%g.length],{[j]:O,...z}=((_=a==null?void 0:a.colorConfig)==null?void 0:_.segments)||{},V={...a||{},colorConfig:{segments:z}};r(V);const B={...s,preferences:V};c(B),o(G=>({...G,[j]:k}))};if(!u.length||!((s==null?void 0:s.type)==="stackedBar"||(s==null?void 0:s.type)==="stackedLine"?((D=(E=s==null?void 0:s.config)==null?void 0:E.groupByColumns)==null?void 0:D.length)||((R=(p=s==null?void 0:s.config)==null?void 0:p.pivotByColumns)==null?void 0:R.length):(M=(w=s==null?void 0:s.config)==null?void 0:w.groupByColumns)==null?void 0:M.length)||["table","kpi","text","custom","heatmap"].includes(n))return null;const P=()=>{const j={...a||{},colorConfig:{segments:{}}};r(j);const L={...s,preferences:j};c(L);const k={};u.forEach((O,z)=>{k[O]=t.getColorForValue(O,z,void 0)}),o(k)},C=Object.keys(((F=a==null?void 0:a.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-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ta,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Colors"})]})}),e.jsx(t.AccordionContent,{className:"",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("div",{className:"flex items-center justify-between",children:C&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:P,children:[e.jsx(is,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:u.map((j,L)=>{const k=t.isDefaultColor(d[j],L),O=!k;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Popover,{open:m===j,onOpenChange:z=>h(z?j: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[j]}})}),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((z,V)=>e.jsxs("button",{className:t.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",d[j]===z?"border-gray-900":"border-transparent"),style:{backgroundColor:z},onClick:()=>{v(j,z),h(null)},children:[V===L%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:z})]},`default-${V}`))})]}),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:hl.map((z,V)=>e.jsx("button",{className:t.cn("h-5 w-5 rounded border transition-all hover:scale-110",d[j]===z?"border-2 border-gray-900":z==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:z},onClick:()=>{v(j,z),h(null)},children:e.jsx("span",{className:"sr-only",children:z})},`preset-${V}`))})]}),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:()=>{x({value:j,color:d[j]}),h(null)},children:"Custom color"}),!k&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{b(j,L),h(null)},children:[e.jsx(is,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:j}),O&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},j)})}),f&&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:()=>x(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Hn,{color:f.color,onColorChange:j=>{v(f.value,j),x(null)},onClose:()=>x(null)})})]})]})})]})}function He({value:s,onSave:a,placeholder:n="",type:r="text",className:c=""}){const[i,l]=N.useState(s??""),[d,o]=N.useState(!1);N.useEffect(()=>{l(s??"")},[s]);const m=()=>{a(i),o(!1)},h=()=>{l(s??""),o(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${c}`,children:[e.jsx(t.Input,{placeholder:n,type:r,value:d?i:s??"",onChange:f=>{l(f.target.value),o(!0)},onFocus:()=>o(!0),onClick:f=>f.stopPropagation(),className:"h-8 text-xs",onPointerDown:f=>f.stopPropagation(),onKeyDown:f=>{f.stopPropagation(),f.key==="Enter"&&d&&i!==s?m():f.key==="Escape"&&h()},"aria-label":n||"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:m,children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:h,children:e.jsx(t.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function ns({axis:s,label:a,type:n,config:r,onChange:c,defaultTitle:i,hidePosition:l}){var g,v,b,S,I,P,C,A,y,T,E,D,p,R;const d=t.normalizeContextFormatMode({formatMode:r==null?void 0:r.formatMode,formatOptions:r==null?void 0:r.formatOptions}),o=(w,M)=>{c({...r??{},[w]:M})},m=(w,M)=>{var k,O,z,V;const F=w==="enabled"&&M===!0,j=(k=r==null?void 0:r.name)==null?void 0:k.text,L=F&&!j&&i;c({...r??{},name:{...r==null?void 0:r.name,enabled:w==="enabled"?M:((O=r==null?void 0:r.name)==null?void 0:O.enabled)??!1,text:w==="text"?M:L?i:j,fontSize:w==="fontSize"?M:(z=r==null?void 0:r.name)==null?void 0:z.fontSize,fontWeight:w==="fontWeight"?M:(V=r==null?void 0:r.name)==null?void 0:V.fontWeight}})},h=(w,M)=>{var F,j;c({...r??{},labels:{enabled:w==="enabled"?M:((F=r==null?void 0:r.labels)==null?void 0:F.enabled)??!0,rotation:w==="rotation"?M:(j=r==null?void 0:r.labels)==null?void 0:j.rotation}})},f=(w,M)=>{c({...r??{},scale:{...r==null?void 0:r.scale,[w]:M===""?"auto":Number(M)}})},x=s==="x"?["auto","top","bottom"]:["auto","left","right"],u=["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-[12px] font-medium hover:no-underline",children:e.jsx("div",{className:"flex grow items-center justify-between gap-2",children:e.jsx("span",{children:a})})}),e.jsx(t.Switch,{size:"sm",checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:w=>o("enabled",w),onClick:w=>w.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:w=>m("enabled",w===!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:`${a} title`,value:((b=r==null?void 0:r.name)==null?void 0:b.text)||"",onSave:w=>m("text",w),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(((S=r==null?void 0:r.name)==null?void 0:S.fontSize)||12),onSave:w=>m("fontSize",Number(w)||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:((I=r==null?void 0:r.name)==null?void 0:I.fontWeight)||"normal",onValueChange:w=>m("fontWeight",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:"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:w=>o("position",w),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:x.map(w=>e.jsx(t.SelectItem,{value:w,className:"text-xs",children:w==="auto"?"Auto (Default)":t.titleCase(w)},w))})]})]}),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:((P=r==null?void 0:r.labels)==null?void 0:P.enabled)!==!1,onCheckedChange:w=>h("enabled",w)})]}),((C=r==null?void 0:r.labels)==null?void 0:C.enabled)!==!1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Rotation"}),e.jsxs(t.Select,{value:String(((A=r==null?void 0:r.labels)==null?void 0:A.rotation)||"auto"),onValueChange:w=>h("rotation",w==="auto"?"auto":Number(w)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:u.map(w=>e.jsx(t.SelectItem,{value:w,className:"text-xs",children:w==="auto"?"Auto (Default)":`${w}°`},w))})]})]})]}),n==="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:w=>c({...r,formatMode:w?"override":"inherit"})})]}),d==="override"&&e.jsx(bt,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:w=>c({...r,formatMode:"override",formatOptions:w}),showTitle:!1})]}),n==="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:((y=r==null?void 0:r.scale)==null?void 0:y.min)==="auto"||((T=r==null?void 0:r.scale)==null?void 0:T.min)===void 0?"":String(r.scale.min),onSave:w=>f("min",w),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:((E=r==null?void 0:r.scale)==null?void 0:E.max)==="auto"||((D=r==null?void 0:r.scale)==null?void 0:D.max)===void 0?"":String(r.scale.max),onSave:w=>f("max",w),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:((p=r==null?void 0:r.scale)==null?void 0:p.stepSize)==="auto"||((R=r==null?void 0:r.scale)==null?void 0:R.stepSize)===void 0?"":String(r.scale.stepSize),onSave:w=>f("stepSize",w),className:""})})]})]})]})]})]})}function as(s,a,n){var i,l,d;if(s==="x"){const o=(l=(i=a==null?void 0:a.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=a==null?void 0:a.config)==null?void 0:d.metricColumns)||[],c=(n==null?void 0:n.datasetOptions)||[];if(s==="y"){const o=r.filter((m,h)=>{const f=c.find(x=>x.idx===h);return!f||f.yAxisId!=="y2"});return o.length===1&&(o[0].label||o[0].name)||""}if(s==="y2"){const o=r.filter((m,h)=>{const f=c.find(x=>x.idx===h);return(f==null?void 0:f.yAxisId)==="y2"});return o.length===1&&(o[0].label||o[0].name)||""}return""}function fl(){const s=t.useEditorStore(o=>o.card),a=t.useEditorStore(o=>{var m;return(m=o.card)==null?void 0:m.preferences}),{setCardPreferences:n,updateCardInFrame:r}=t.useEditorActions(),c=Ae.useEffectiveEditorCardType();if(!s||["tornado","pyramid","kpi","treemap"].includes(c))return null;const i=t.AxisConfigurator.getAxisInfo(c,a);if(!i.hasXAxis&&!i.hasYAxis)return null;const l=(o,m)=>{let h;o==="x"?h="xAxisConfig":o==="y"?h="yAxisConfig":h="secondaryYAxisConfig";const f={...a||{},[h]:m};n(f);const x={...s,preferences:f};r(x)},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-[12px] 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(ns,{axis:"x",label:"X-Axis",type:i.xAxisType,config:t.mergeAxisConfig(t.getDefaultAxisConfig(c,"x"),a==null?void 0:a.xAxisConfig),onChange:o=>l("x",o),defaultTitle:as("x",s,a)}),i.hasYAxis&&e.jsx(ns,{axis:"y",label:d?"Y-Axis (Left)":"Y-Axis",type:i.yAxisType,config:t.mergeAxisConfig(t.getDefaultAxisConfig(c,"y"),a==null?void 0:a.yAxisConfig),onChange:o=>l("y",o),defaultTitle:as("y",s,a)}),d&&e.jsx(ns,{axis:"y2",label:"Y2-Axis (Right)",type:"value",config:t.mergeAxisConfig({enabled:!0,position:"right"},a==null?void 0:a.secondaryYAxisConfig),onChange:o=>l("y2",o),defaultTitle:as("y2",s,a),hidePosition:!0})]})})]})}function gl(){const s=t.useEditorStore(f=>f.card),a=Ae.useEffectiveEditorCardType(),n=t.useEditorStore(f=>{var x,u,g,v;return(v=(g=(u=(x=f.card)==null?void 0:x.preferences)==null?void 0:u.chartOptions)==null?void 0:g.plugins)==null?void 0:v.legend}),{setLegendOptions:r}=t.useEditorActions();if(!s||!t.chartSupportsLegend(a))return null;const c=t.getDefaultLegendConfig(a),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=(f,x)=>{const u={...n,[f]:x};r(u)},m=["top","bottom","left","right"],h=["start","center","end"];return e.jsxs(t.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Na,{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:(n==null?void 0:n.display)??i,onCheckedChange:f=>o("display",f)})]}),((n==null?void 0:n.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:(n==null?void 0:n.position)||l,onValueChange:f=>o("position",f),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:m.map(f=>e.jsx(t.SelectItem,{value:f,className:"text-xs",children:t.titleCase(f)},f))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(t.Select,{value:(n==null?void 0:n.align)||d,onValueChange:f=>o("align",f),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:h.map(f=>e.jsx(t.SelectItem,{value:f,className:"text-xs",children:t.titleCase(f)},f))})]})]})]})]})})]})}function bl(){var M,F,j,L,k,O,z;const s=t.useEditorStore(V=>V.card),a=Ae.useEffectiveEditorCardType(),n=t.useEditorStore(V=>{var B,_;return(_=(B=V.card)==null?void 0:B.preferences)==null?void 0:_.dataLabelsConfig}),r=t.useEditorStore(V=>{var B;return(B=V.card)==null?void 0:B.preferences}),{setCardPreferences:c,updateCardInFrame:i}=t.useEditorActions();if(!s||!t.chartSupportsDataLabels(a))return null;const l=a==="bullet"?((M=r==null?void 0:r.bulletConfig)==null?void 0:M.orientation)??(((F=r==null?void 0:r.chartOptions)==null?void 0:F.indexAxis)==="x"?"vertical":"horizontal"):void 0,d=l!=null?l==="horizontal":((j=r==null?void 0:r.chartOptions)==null?void 0:j.indexAxis)==="y",o=a==="stackedBar"||a==="stackedLine",m=a==="pie"||a==="doughnut"||a==="polarArea"||a==="funnel",h=a==="bubble"||a==="scatter",f=(k=(L=r==null?void 0:r.chartOptions)==null?void 0:L.plugins)==null?void 0:k.datalabels,x=(f==null?void 0:f.display)!==!1&&((f==null?void 0:f.anchor)||(f==null?void 0:f.align)),u=t.getDefaultDataLabelsConfig(a,s.preferences),g=n??u,v=(u==null?void 0:u.enabled)??x??!1,b=(n==null?void 0:n.enabled)!==void 0?n.enabled:v,S=(V,B)=>{const q={...u??{},...n??{},[V]:B};V==="enabled"&&(q.display=B,B&&h&&!q.position&&(q.position="bottom")),V==="position"&&h&&(q.position="bottom"),V==="formatMode"&&B==="inherit"&&(q.format=void 0,q.formatOptions=void 0);const H={...s.preferences||{},dataLabelsConfig:q};c(H);const te={...s,preferences:H};i(te)},I=(V,B)=>{const _=n??{},q={...u??{},..._,font:{..._.font||{},[V]:B}},H={...s.preferences||{},dataLabelsConfig:q};c(H);const te={...s,preferences:H};i(te)},P=()=>{const V=a;return V==="stackedBar"||V==="stackedLine"||V==="pie"||V==="doughnut"?"center":d?"right":"top"},C=a!=="treemap"&&a!=="heatmap",A=a!=="treemap",y=P();let T=[];if(C)if(h)T=["bottom"];else if(o||m)T=["center"];else{const V=d?["center","left","right"]:["center","top","bottom"];T=["auto",...a==="bullet"?V:V.filter(_=>_!==y),"custom"]}const E=()=>t.titleCase(y),D=["center","start","end"],p=["center","start","end","top","bottom"],R=(g==null?void 0:g.formatMode)||(g!=null&&g.format&&!["auto"].includes(g.format)?"override":"inherit"),w=(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-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"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:V=>S("enabled",V)})]}),b&&e.jsxs(e.Fragment,{children:[C&&!o&&!m&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(t.Select,{value:h?(g==null?void 0:g.position)||"bottom":(g==null?void 0:g.position)||"auto",onValueChange:V=>S("position",V),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:T.map(V=>e.jsx(t.SelectItem,{value:V,className:"text-xs",children:V==="auto"?E():V==="custom"?"Custom (Advanced)":t.titleCase(V)},V))})]})]}),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:(n==null?void 0:n.showTotal)??!1,onCheckedChange:V=>S("showTotal",V)})]}),(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:V=>S("anchor",V),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:D.map(V=>e.jsx(t.SelectItem,{value:V,className:"text-xs",children:t.titleCase(V)},V))})]})]}),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:V=>S("align",V),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:p.map(V=>e.jsx(t.SelectItem,{value:V,className:"text-xs",children:t.titleCase(V)},V))})]})]})]}),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:V=>S("formatMode",V?"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:w,onCheckedChange:V=>{const B=n??{},G={...u??{},...B,formatMode:"override",format:V?"none":void 0,formatOptions:V?void 0:B.formatOptions},q={...s.preferences||{},dataLabelsConfig:G};c(q),i({...s,preferences:q})}})]}),!w&&e.jsx(bt,{formatOptions:(g==null?void 0:g.formatOptions)||{},onFormatOptionsChange:V=>{const G={...u??{},...n??{},formatMode:"override",format:V.type&&V.type!=="auto"?V.type:void 0,formatOptions:V},q={...s.preferences||{},dataLabelsConfig:G};c(q),i({...s,preferences:q})},showTitle:!1})]})]}),A&&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(((O=g==null?void 0:g.font)==null?void 0:O.size)||12),onSave:V=>I("size",Number(V)),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:((z=g==null?void 0:g.font)==null?void 0:z.weight)||"normal",onValueChange:V=>I("weight",V),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:V=>{V==="auto"&&S("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:V=>S("rotation",Number(V)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}const vn={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 jl(){var x,u,g,v,b,S,I,P,C,A;const s=t.useEditorStore(y=>y.card),{setCardPreferences:a}=t.useEditorActions(),n=Ae.useEffectiveEditorCardType(),r=((x=s.config)==null?void 0:x.metricColumns)||[],c=((u=s.config)==null?void 0:u.groupByColumns)||[],i=r.length===2&&c.length===0,l=r.some(y=>y.comparisonType&&y.comparisonType!=="none");if(!(n==="kpi"&&(i||l)))return null;const o=((v=(g=s.preferences)==null?void 0:g.kpiVisualOptions)==null?void 0:v.metricComparison)||{},m=y=>{var E;const T={...s.preferences,kpiVisualOptions:{...(E=s.preferences)==null?void 0:E.kpiVisualOptions,metricComparison:{...o,...y}}};a(T)},h=l||o.enabled,f=r.some(y=>y.comparisonType==="previous_period"||y.comparisonType==="same_period_last_year"||y.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-[12px] hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mn,{className:"h-3.5 w-3.5 text-foreground/60"}),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:y=>m({enabled:y,...y&&!o.calculationType?{calculationType:"difference"}:{}})})]}),h&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(t.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.Info,{className:"h-3 w-3 cursor-help text-muted-foreground"})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:(()=>{const y=o.calculationType||"difference",T=vn[y];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:T==null?void 0:T.label}),e.jsx("p",{children:T==null?void 0:T.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:T==null?void 0:T.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",T==null?void 0:T.example]})]})})()})]})]}),e.jsxs(t.Select,{value:o.calculationType||"difference",onValueChange:y=>m({calculationType:y}),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(vn).map(([y,T])=>e.jsx(t.SelectItem,{value:y,className:"text-xs",children:T.label},y))})]})]}),e.jsx(bt,{formatOptions:o.formatOptions||{},onFormatOptionsChange:y=>m({formatOptions:y}),showTitle:!0,title:"COMPARISON FORMAT"}),(f||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:y=>m({position:y}),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"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:y=>m({showArrow:y})}),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:y=>m({showColor:y})}),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(at,{value:((b=o.colorConfig)==null?void 0:b.increase)||"green",onChange:y=>m({colorConfig:{...o.colorConfig,increase:y}}),label:"Primary > Secondary"}),e.jsx(at,{value:((S=o.colorConfig)==null?void 0:S.decrease)||"red",onChange:y=>m({colorConfig:{...o.colorConfig,decrease:y}}),label:"Primary < Secondary"}),e.jsx(at,{value:((I=o.colorConfig)==null?void 0:I.noChange)||"neutral",onChange:y=>m({colorConfig:{...o.colorConfig,noChange:y}}),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:y=>m({conditionalLabel:y})}),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:((P=o.conditionalLabels)==null?void 0:P.increase)??"Increase",onChange:y=>m({conditionalLabels:{...o.conditionalLabels,increase:y.target.value}}),placeholder:"Increase",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(t.Label,{htmlFor:"label-decrease",className:"text-xs text-muted-foreground",children:["Primary ","<"," Secondary"]}),e.jsx(t.Input,{id:"label-decrease",type:"text",value:((C=o.conditionalLabels)==null?void 0:C.decrease)??"Decrease",onChange:y=>m({conditionalLabels:{...o.conditionalLabels,decrease:y.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:((A=o.conditionalLabels)==null?void 0:A.noChange)??"No change",onChange:y=>m({conditionalLabels:{...o.conditionalLabels,noChange:y.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:y=>m({labelName:y.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function vl(){var i;const s=t.useEditorStore(l=>{var d;return(d=l.card)==null?void 0:d.type}),a=t.useEditorStore(l=>{var d;return(d=l.card)==null?void 0:d.preferences}),{setCardPreferences:n}=t.useEditorActions();if(s!=="treemap")return null;const r=((i=a==null?void 0:a.chartOptions)==null?void 0:i.treemapColorMode)??"branch",c=l=>{const d={...a||{},chartOptions:{...a==null?void 0:a.chartOptions,treemapColorMode:l}};n(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-[12px] 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 yl=Object.keys(t.HEATMAP_PRESET_PALETTES);function Nl(){const s=t.useEditorStore(x=>x.card),a=t.useEditorStore(x=>{var u;return(u=x.card)==null?void 0:u.preferences}),{setCardPreferences:n}=t.useEditorActions(),r=(s==null?void 0:s.type)==="heatmap",c=(a==null?void 0:a.heatmapConfig)||{},i=c.colorPalette??"green",l=c.legendPosition??"bottom",d=N.useMemo(()=>c.colorRange&&c.colorRange[0]&&c.colorRange[1]?[c.colorRange[0],c.colorRange[1]]:[...t.DEFAULT_HEATMAP_CUSTOM_RANGE],[c.colorRange]),o=x=>{const u={...c,...x};u.colorPalette!=="custom"?delete u.colorRange:(!u.colorRange||!u.colorRange[0]||!u.colorRange[1])&&(u.colorRange=[...t.DEFAULT_HEATMAP_CUSTOM_RANGE]),n({...a||{},heatmapConfig:u})},m=x=>{o({colorPalette:x,colorRange:x==="custom"?c.colorRange??[...t.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},h=(x,u)=>{const g=[...d];g[x]=u,o({colorPalette:"custom",colorRange:g})},f=x=>{o({legendPosition:x})};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-[12px] 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:x=>m(x??"blue"),className:"space-y-3",children:[yl.map(x=>{const u=t.HEATMAP_PRESET_PALETTES[x];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-${x}`,value:x}),e.jsxs(t.Label,{htmlFor:`heatmap-${x}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:u.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${u.start}, ${u.end})`}})]})]},x)}),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(at,{value:d[0],onChange:x=>h(0,x),label:"Start color"}),e.jsx(at,{value:d[1],onChange:x=>h(1,x),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:x=>f(x??"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(x=>e.jsx(t.SelectItem,{value:x,className:"text-xs",children:x[0].toUpperCase()+x.slice(1)},x))})]})]})]})]}):null}const yn=["poor","satisfactory","good"];function Nn(s){if(!s)return;const a={...s};return a.targetMetricKey||delete a.targetMetricKey,a.comparativeMetricKey||delete a.comparativeMetricKey,!a.targetValue&&a.targetValue!==0&&delete a.targetValue,(!a.rangeKeys||Object.keys(a.rangeKeys).length===0)&&delete a.rangeKeys,(!a.ranges||Object.keys(a.ranges).length===0)&&delete a.ranges,(!a.rangeLabels||Object.keys(a.rangeLabels).length===0)&&delete a.rangeLabels,a}function Cl(){var M,F;const s=t.useEditorStore(j=>j.card.preferences),a=t.useEditorStore(j=>j.card),n=t.useEditorStore(j=>j.isDevMode),{setCardPreferences:r,setChartOrientation:c}=t.useEditorActions(),i=N.useMemo(()=>(s==null?void 0:s.bulletConfig)||{},[s==null?void 0:s.bulletConfig]),d=t.hasValidCardConfig(a==null?void 0:a.config)&&!n,[o,m]=N.useState(i.showRanges??!1),[h,f]=N.useState(i.rangesArePercentages??!1),x=i.disableAutoComparative?!1:i.comparativeMetricKey!==void 0||!d,[u,g]=N.useState(x);N.useEffect(()=>{m(i.showRanges??!1)},[i.showRanges]),N.useEffect(()=>{f(i.rangesArePercentages??!1)},[i.rangesArePercentages]);const v=i.targetValue===void 0?"":String(i.targetValue);N.useEffect(()=>{const j=i.disableAutoComparative?!1:i.comparativeMetricKey!==void 0||!d;g(j)},[i.disableAutoComparative,i.comparativeMetricKey,d]);const b=N.useMemo(()=>{var j,L;return((L=(j=a==null?void 0:a.config)==null?void 0:j.metricColumns)==null?void 0:L.map(k=>{const O=k.label||k.name||k.alias||"";return{value:O,label:O}}))||[]},[(M=a==null?void 0:a.config)==null?void 0:M.metricColumns]);N.useEffect(()=>{var _,G;if(!s||b.length===0)return;const j={};let L=!1;const k=(_=b[1])==null?void 0:_.value;!i.targetMetricKey&&k&&(j.targetMetricKey=k,L=!0);const O=(G=b[2])==null?void 0:G.value;!i.comparativeMetricKey&&!i.disableAutoComparative&&O&&(j.comparativeMetricKey=O,L=!0);const z=b.slice(3),V={...i.rangeKeys||{}};let B=!1;if(yn.forEach((q,H)=>{!V[q]&&z[H]&&(V[q]=z[H].value,B=!0)}),B&&(j.rangeKeys=V,L=!0,i.showRanges===void 0&&(j.showRanges=!0)),L){const q=Nn({...i,...j});r({...s,bulletConfig:q})}},[b,i,s,r]);const S=j=>{const L=Nn({...i,...j});r({...s,bulletConfig:L})},I=(j,L)=>{const k={...i.rangeKeys||{},[j]:L.trim()};L.trim()||delete k[j],S({rangeKeys:Object.keys(k).length>0?k:void 0})},P=(j,L)=>{const k=L===""?void 0:Number(L),O={...i.ranges||{}};k===void 0||Number.isNaN(k)?delete O[j]:O[j]=k,S({ranges:Object.keys(O).length?O:void 0})},C=j=>{if(j===""){S({targetValue:void 0});return}const L=Number(j);S({targetValue:Number.isNaN(L)?void 0:L})},A=(j,L)=>{const k=L.trim(),O={...i.rangeLabels||{}};k?O[j]=k:delete O[j],S({rangeLabels:Object.keys(O).length>0?O:void 0})},y=j=>{m(j),S({showRanges:j})},T=j=>{f(j),S({rangesArePercentages:j})},E=i.orientation||(((F=s==null?void 0:s.chartOptions)==null?void 0:F.indexAxis)==="y"?"horizontal":"vertical"),D=j=>{S({orientation:j}),c(j==="horizontal"?"y":"x")},p=[{value:"__none",label:"None"},...b.map(j=>({value:j.value,label:j.label}))],R=p,w=j=>{if(g(j),!j){S({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!d){S({disableAutoComparative:!1});return}if(i.comparativeMetricKey)S({disableAutoComparative:!1});else{const L=b.find(k=>k.value!==i.targetMetricKey);S({comparativeMetricKey:L==null?void 0:L.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-[12px] 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:E,onValueChange:j=>D(j),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:j=>S({targetMetricKey:j==="__none"?void 0:j}),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(j=>e.jsx(t.SelectItem,{value:j.value,className:"text-xs",children:j.label},j.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:j=>S({comparativeMetricKey:j==="__none"?void 0:j,disableAutoComparative:j==="__none"}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select metric"})}),e.jsx(t.SelectContent,{children:p.map(j=>e.jsx(t.SelectItem,{value:j.value,className:"text-xs",children:j.label},j.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:u,onCheckedChange:j=>w(j)})]}),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:C,placeholder:"Optional numeric fallback"})]})]}),e.jsxs("section",{className:"space-y-4 rounded-md border border-border/60 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"QUALITATIVE RANGES"}),e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:200,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"text-muted-foreground transition-colors hover:text-foreground",children:e.jsx(t.Info,{className:"h-3.5 w-3.5"})})}),e.jsx(t.TooltipContent,{side:"top",children:"Use columns or static values for Poor / Average / Good."})]})})]}),e.jsx("div",{className:"flex items-center gap-2 text-xs font-medium",children:e.jsx(t.Switch,{size:"sm",checked:o,onCheckedChange:y})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:h,disabled:!o,onChange:j=>T(j.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:yn.map(j=>{var L,k,O,z,V;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:[j," LABEL"]}),e.jsx(qe,{placeholder:`Display label (${j})`,value:((L=i.rangeLabels)==null?void 0:L[j])||"",onCommit:B=>A(j,B),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:[j," COLUMN"]}),e.jsxs(t.Select,{value:((k=i.rangeKeys)==null?void 0:k[j])||"__none",onValueChange:B=>{B==="__none"?I(j,""):I(j,B)},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(B=>e.jsx(t.SelectItem,{value:B.value,className:"text-xs",children:B.label},B.value))})]})]}):e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[j," COLUMN KEY"]}),e.jsx(qe,{placeholder:"Column key",value:((O=i.rangeKeys)==null?void 0:O[j])||"",onCommit:B=>I(j,B),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:[j," VALUE"]}),e.jsx(qe,{type:"number",placeholder:h?"0.80":"Static value",value:((z=i.ranges)==null?void 0:z[j])===void 0?"":String((V=i.ranges)==null?void 0:V[j]),onCommit:B=>P(j,B),className:"h-8 text-xs"})]})]},j)})})]})]})]})}function Cn(s){if(!s)return;const a={...s};if(a.xMetricKey||delete a.xMetricKey,a.yMetricKey||delete a.yMetricKey,a.radiusMetricKey||delete a.radiusMetricKey,a.labelKey||delete a.labelKey,a.groupKey||delete a.groupKey,a.enableGrouping===void 0&&delete a.enableGrouping,a.radiusScale||delete a.radiusScale,a.fixedRadius===void 0&&delete a.fixedRadius,a.minRadius===void 0&&delete a.minRadius,a.maxRadius===void 0&&delete a.maxRadius,Object.keys(a).length!==0)return a}function Sl(){var A,y,T,E,D,p,R,w,M,F,j,L;const s=t.useEditorStore(k=>k.card.preferences),a=t.useEditorStore(k=>k.card),n=Ae.useEffectiveEditorCardType(),r=t.useEditorStore(k=>k.isDevMode),{setCardPreferences:c,updateCardInFrame:i}=t.useEditorActions(),l=n==="bubble",d=n==="scatter",o=N.useMemo(()=>(s==null?void 0:s.bubbleScatterConfig)||{},[s==null?void 0:s.bubbleScatterConfig]),h=t.hasValidCardConfig(a==null?void 0:a.config)&&!r,f=N.useMemo(()=>{var k,O;return((O=(k=a==null?void 0:a.config)==null?void 0:k.metricColumns)==null?void 0:O.map(z=>{const V=z.label||z.name||z.alias||"";return{value:V,label:V}}))||[]},[(A=a==null?void 0:a.config)==null?void 0:A.metricColumns]),x=N.useMemo(()=>{var k,O;return((O=(k=a==null?void 0:a.config)==null?void 0:k.groupByColumns)==null?void 0:O.map(z=>{const V=z.label||z.name||z.alias||"";return{value:V,label:V}}))||[]},[(y=a==null?void 0:a.config)==null?void 0:y.groupByColumns]),u=N.useMemo(()=>o.enableGrouping!==void 0?o.enableGrouping:!r&&x.length>=2,[o.enableGrouping,r,x.length]),[g,v]=N.useState(u);N.useEffect(()=>{v(u)},[u]);const b=k=>{const O={...s||{},bubbleScatterConfig:k};c(O),a&&i({...a,preferences:O})},S=k=>{c(k),a&&i({...a,preferences:k})};N.useEffect(()=>{if(!s||f.length===0)return;const k={};let O=!1;if(!o.xMetricKey&&f[0]&&(k.xMetricKey=f[0].value,O=!0),!o.yMetricKey&&f[1]&&(k.yMetricKey=f[1].value,O=!0),l&&!o.radiusMetricKey&&f[2]&&(k.radiusMetricKey=f[2].value,O=!0),!o.labelKey&&x[0]&&(k.labelKey=x[0].value,O=!0),u&&!o.groupKey&&x[1]&&(k.groupKey=x[1].value,k.enableGrouping=!0,O=!0),O){const z=Cn({...o,...k});b(z)}},[f,x,o,s,c,l,u]);const I=k=>{const O=Cn({...o,...k});b(O)},P=k=>{v(k),I({enableGrouping:k,groupKey:k?o.groupKey:void 0})};if(!l&&!d)return null;const C=l?t.Circle:t.ChartScatter;return e.jsxs(t.AccordionItem,{value:"bubble-scatter-config",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(C,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsxs("span",{children:[l?"Bubble":"Scatter"," Configuration"]})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-1 pb-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-1 text-xs font-medium text-muted-foreground",children:["Dimensions",e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{children:e.jsx(t.Info,{className:"h-3 w-3"})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{children:"Label identifies each point. Group creates separate series in the legend."})})]})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Label Column"}),h?e.jsxs(t.Select,{value:o.labelKey||"",onValueChange:k=>I({labelKey:k}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select label column"})}),e.jsx(t.SelectContent,{children:x.map(k=>e.jsx(t.SelectItem,{value:k.value,children:k.label},k.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for labels",value:o.labelKey||"",onCommit:k=>I({labelKey:k})})]}),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:P})]}),g&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Group By"}),h?e.jsxs(t.Select,{value:o.groupKey||"",onValueChange:k=>I({groupKey:k}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select group column"})}),e.jsx(t.SelectContent,{children:x.map(k=>e.jsx(t.SelectItem,{value:k.value,children:k.label},k.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:o.groupKey||"",onCommit:k=>I({groupKey:k})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Metrics"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"X Axis"}),h?e.jsxs(t.Select,{value:o.xMetricKey||"",onValueChange:k=>I({xMetricKey:k}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select X metric"})}),e.jsx(t.SelectContent,{children:f.map(k=>e.jsx(t.SelectItem,{value:k.value,children:k.label},k.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:o.xMetricKey||"",onCommit:k=>I({xMetricKey:k})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Axis"}),h?e.jsxs(t.Select,{value:o.yMetricKey||"",onValueChange:k=>I({yMetricKey:k}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select Y metric"})}),e.jsx(t.SelectContent,{children:f.map(k=>e.jsx(t.SelectItem,{value:k.value,children:k.label},k.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:o.yMetricKey||"",onCommit:k=>I({yMetricKey:k})})]}),l&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Radius"}),h?e.jsxs(t.Select,{value:o.radiusMetricKey||"",onValueChange:k=>I({radiusMetricKey:k}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select radius metric"})}),e.jsx(t.SelectContent,{children:f.map(k=>e.jsx(t.SelectItem,{value:k.value,children:k.label},k.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for radius",value:o.radiusMetricKey||"",onCommit:k=>I({radiusMetricKey:k})})]})]}),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:k=>I({radiusScale:k}),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:((T=o.minRadius)==null?void 0:T.toString())||"",onCommit:k=>I({minRadius:k?Number(k):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:((E=o.maxRadius)==null?void 0:E.toString())||"",onCommit:k=>I({maxRadius:k?Number(k):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:([k])=>I({fixedRadius:k}),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:([k])=>I({fixedRadius:k}),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:((p=(D=s==null?void 0:s.xAxisConfig)==null?void 0:D.name)==null?void 0:p.enabled)??!1,onCheckedChange:k=>{var V,B,_,G;const O=o.xMetricKey||"X Axis",z=o.yMetricKey||"Y Axis";S({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{enabled:k,text:((B=(V=s==null?void 0:s.xAxisConfig)==null?void 0:V.name)==null?void 0:B.text)||O}},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{enabled:k,text:((G=(_=s==null?void 0:s.yAxisConfig)==null?void 0:_.name)==null?void 0:G.text)||z}}})}})]}),((w=(R=s==null?void 0:s.xAxisConfig)==null?void 0:R.name)==null?void 0:w.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=(M=s==null?void 0:s.xAxisConfig)==null?void 0:M.name)==null?void 0:F.text)||"",onCommit:k=>{var O;S({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{...(O=s==null?void 0:s.xAxisConfig)==null?void 0:O.name,enabled:!0,text:k||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:((L=(j=s==null?void 0:s.yAxisConfig)==null?void 0:j.name)==null?void 0:L.text)||"",onCommit:k=>{var O;S({...s??{},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{...(O=s==null?void 0:s.yAxisConfig)==null?void 0:O.name,enabled:!0,text:k||o.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const wl=[{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 Tl(){const s=t.useEditorStore(x=>x.card),a=t.useEditorStore(x=>{var u;return(u=x.card)==null?void 0:u.preferences}),{setCardPreferences:n}=t.useEditorActions(),r=(s==null?void 0:s.type)==="funnel",c=(a==null?void 0:a.funnelConfig)||{},i=c.percentMode??"percentOfTotal",l=c.shrinkFraction??1,d=c.labelThreshold??0,o=x=>{const u={...c,...x};n({...a||{},funnelConfig:u})},m=x=>{o({percentMode:x})},h=x=>{o({shrinkFraction:x[0]})},f=x=>{o({labelThreshold:x[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-[12px] 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:x=>m(x),className:"space-y-2",children:wl.map(x=>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-${x.value}`,value:x.value,className:"mt-0.5"}),e.jsxs(t.Label,{htmlFor:`funnel-${x.value}`,className:"flex flex-col gap-0.5 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:x.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:x.description})]})]},x.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"SEGMENT SHRINK"}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Same Width"}),e.jsx(t.Slider,{value:[l],onValueChange:h,min:0,max:1,step:.1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Full Shrink"})]}),e.jsxs("p",{className:"text-center text-xs text-muted-foreground",children:["Current: ",Math.round(l*100),"%"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"LABEL VISIBILITY THRESHOLD"}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Show All"}),e.jsx(t.Slider,{value:[d],onValueChange:f,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:a}=t.useEditorCardQuery(s),{keys:n}=t.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(i=>!t.METADATA_KEYS.includes(i));let c=r;if(["stackedBar","stackedLine"].includes(s.type)){const i=t.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:l}=t.getKeys(i);c=l.slice(1)}return{transformedMetricKeys:c,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}const El=[{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"}],Il=[{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)"}],kl=["center","start","end"],Dl=["center","start","end","top","bottom"];function $t({config:s,onChange:a,isHorizontal:n=!1,showAutoFormat:r=!0,positionOptions:c,showAppearance:i=!0}){var g,v,b,S,I,P;const l=c??(n?["auto","center","left","right","custom"]:["auto","center","top","bottom","custom"]),d=r?["auto","number","currency","percent","none"]:["number","currency","percent","none"],o=(C,A)=>{const y={...s,[C]:A};a(y)},m=(C,A)=>{const y={...s,font:{...(s==null?void 0:s.font)||{},[C]:A}};a(y)},h=(C,A)=>{const y={...s,formatOptions:{...(s==null?void 0:s.formatOptions)||{},[C]:A}};a(y)},f=()=>n?"Right":"Top",x=s||{},u=x.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:x.position||"auto",onValueChange:C=>o("position",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:l.map(C=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:C==="auto"?f():C==="custom"?"Custom (Advanced)":t.titleCase(C)},C))})]})]}),x.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:x.anchor||"center",onValueChange:C=>o("anchor",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:kl.map(C=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:t.titleCase(C)},C))})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Align"}),e.jsxs(t.Select,{value:String(x.align||"center"),onValueChange:C=>o("align",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Dl.map(C=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:t.titleCase(C)},C))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Format"}),e.jsxs(t.Select,{value:u,onValueChange:C=>o("format",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:d.map(C=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:C==="auto"&&r?"Auto (Use Axis)":C==="none"?"None (Raw Value)":t.titleCase(C)},C))})]})]}),!["auto","none"].includes(u)&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[["number","currency","percent"].includes(u)&&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=x.formatOptions)==null?void 0:g.decimalPlaces)??(u==="currency"?2:u==="percent"?1:0)),onSave:C=>h("decimalPlaces",Number(C)),className:""})})]}),u==="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=x.formatOptions)==null?void 0:v.currency)||"USD",onValueChange:C=>h("currency",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:El.map(C=>e.jsx(t.SelectItem,{value:C.value,className:"text-xs",children:C.label},C.value))})]})]}),["number","currency"].includes(u)&&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=x.formatOptions)==null?void 0:b.useSuffix)??!1,onCheckedChange:C=>h("useSuffix",C)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Locale"}),e.jsxs(t.Select,{value:((S=x.formatOptions)==null?void 0:S.locale)||"en-US",onValueChange:C=>h("locale",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Il.map(C=>e.jsx(t.SelectItem,{value:C.value,className:"text-xs",children:C.label},C.value))})]})]})]}),i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Appearance"}),e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Size"}),e.jsx("div",{className:"w-16",children:e.jsx(He,{type:"number",placeholder:"12",value:String(((I=x.font)==null?void 0:I.size)||12),onSave:C=>m("size",Number(C)),className:""})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Weight"}),e.jsxs(t.Select,{value:((P=x.font)==null?void 0:P.weight)||"normal",onValueChange:C=>m("weight",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(t.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Color"}),e.jsxs(t.Select,{value:x.color==="auto"||!x.color?"auto":"custom",onValueChange:C=>{C==="auto"&&o("color","auto")},children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Contrast)"}),e.jsx(t.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Rotation"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-12",children:e.jsx(He,{type:"number",placeholder:"0",value:String(x.rotation||0),onSave:C=>o("rotation",Number(C)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"°"})]})]})]})]})]})}const Al=[{type:"bar",icon:t.ChartColumnIncreasing,label:"Bar"},{type:"line",icon:t.ChartLine,label:"Line"}],Ml=[0,1,2,3,4,5,6,8,10],Ll=[{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 │"}],Fl=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Rl(){return t.useEditorStore(a=>{var n;return(n=a.card)==null?void 0:n.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-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsx(Ol,{})})]})}function Ol(){const{transformedMetricKeys:s}=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((a,n)=>e.jsx(Pl,{metricKey:a,idx:n},a))})}function Pl({metricKey:s,idx:a}){var S;const[n,r]=N.useState(!1),c=t.useEditorStore(I=>{var P;return(P=I.card)==null?void 0:P.preferences}),i=t.useEditorStore(I=>{var P,C;return(C=(P=I.card)==null?void 0:P.preferences)==null?void 0:C.datasetOptions}),l=i==null?void 0:i.find(I=>I.idx===a),{setCardPreferences:d}=t.useEditorStore(I=>I.actions),o=(l==null?void 0:l.type)||"bar",m=(l==null?void 0:l.yAxisId)||"y",h=((S=l==null?void 0:l.dataLabels)==null?void 0:S.enabled)??!1,f=o==="line"?t.ChartLine:t.ChartColumnIncreasing;function x(I){const P={idx:a,type:o,yAxisId:m,dataLabels:l==null?void 0:l.dataLabels,...I};if(!l)d({...c||{},datasetOptions:[...i||[],P]});else{const C=i==null?void 0:i.map(A=>A.idx===a?{...A,...P}:A);d({...c||{},datasetOptions:C})}}function u(I){x({type:I})}function g(I){x({yAxisId:I})}function v(I){x({dataLabels:{...l==null?void 0:l.dataLabels,enabled:I}})}function b(I){x({dataLabels:I})}return e.jsx(t.Collapsible,{open:n,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",n&&"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(f,{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:m==="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:Al.map(({type:I,icon:P,label:C})=>{const A=o===I;return e.jsxs("button",{onClick:()=>u(I),className:t.cn("flex items-center gap-2 rounded-md border px-3 py-1.5 text-xs transition-colors",A?"border-primary bg-primary/10 text-primary":"border-border bg-background text-muted-foreground hover:bg-muted"),children:[e.jsx(P,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:C})]},I)})})]}),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:m,onValueChange:I=>g(I),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:I=>x({lineStyle:I}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Fl.map(({value:I,label:P})=>e.jsx(t.SelectItem,{value:I,className:"text-xs",children:P},I))})]})]}),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:I=>x({pointRadius:Number(I)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ml.map(I=>e.jsx(t.SelectItem,{value:String(I),className:"text-xs",children:I===0?"None":I},I))})]})]}),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:I=>x({pointStyle:I}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ll.map(({value:I,label:P})=>e.jsx(t.SelectItem,{value:I,className:"text-xs",children:P},I))})]})]})]})]}),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:h,onCheckedChange:v})]}),h&&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 rs=[{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"}],Bl=[0,1,2,3,4,5,6,8,10],Vl=[{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 │"}],zl=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function _l(s){return s==null?"origin":s===!1?"false":s}function ql(){const s=t.useEditorStore(a=>{var n;return(n=a.card)==null?void 0:n.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-[12px] 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((a,n)=>e.jsx(Kl,{metricKey:a,idx:n},a))})}function Kl({metricKey:s,idx:a}){var v;const[n,r]=N.useState(!1),c=t.useEditorStore(b=>{var S;return(S=b.card)==null?void 0:S.preferences}),i=t.useEditorStore(b=>{var S,I;return(I=(S=b.card)==null?void 0:S.preferences)==null?void 0:I.datasetOptions}),l=i==null?void 0:i.find(b=>b.idx===a),{setCardPreferences:d}=t.useEditorStore(b=>b.actions),o=_l(l==null?void 0:l.fill),m=((v=l==null?void 0:l.dataLabels)==null?void 0:v.enabled)??!1,h=rs.find(b=>b.value===o)||rs[0];function f(b){const S={idx:a,fill:o,dataLabels:l==null?void 0:l.dataLabels,...b};if(!l)d({...c||{},datasetOptions:[...i||[],S]});else{const I=i==null?void 0:i.map(P=>P.idx===a?{...P,...S}:P);d({...c||{},datasetOptions:I})}}function x(b){f({fill:b==="false"?!1:b})}function u(b){f({dataLabels:{...l==null?void 0:l.dataLabels,enabled:b}})}function g(b){f({dataLabels:b})}return e.jsx(t.Collapsible,{open:n,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",n&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:s,children:s})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:e.jsxs("span",{className:t.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(t.ChartArea,{className:"h-3 w-3"}),h.label.split(" ")[0]]})})]})}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Fill Target"}),e.jsxs(t.Select,{value:o,onValueChange:b=>x(b),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:rs.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=>f({lineStyle:b}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:zl.map(({value:b,label:S})=>e.jsx(t.SelectItem,{value:b,className:"text-xs",children:S},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=>f({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:Bl.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=>f({pointStyle:b}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Vl.map(({value:b,label:S})=>e.jsx(t.SelectItem,{value:b,className:"text-xs",children:S},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:m,onCheckedChange:u})]}),m&&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 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 │"}],ls=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Hl(){return t.useEditorStore(a=>{var n;return(n=a.card)==null?void 0:n.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-[12px] 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(Ql,{})})]})}function Ql(){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((a,n)=>e.jsx(Jl,{metricKey:a,idx:n},a))})}function Jl({metricKey:s,idx:a}){var b;const[n,r]=N.useState(!1),c=t.useEditorStore(S=>{var I;return(I=S.card)==null?void 0:I.preferences}),i=t.useEditorStore(S=>{var I,P;return(P=(I=S.card)==null?void 0:I.preferences)==null?void 0:P.datasetOptions}),l=i==null?void 0:i.find(S=>S.idx===a),{setCardPreferences:d}=t.useEditorStore(S=>S.actions),o=(l==null?void 0:l.lineStyle)||"solid",m=(l==null?void 0:l.pointRadius)??3,h=(l==null?void 0:l.pointStyle)||"circle",f=((b=l==null?void 0:l.dataLabels)==null?void 0:b.enabled)??!1,x=ls.find(S=>S.value===o)||ls[0];function u(S){const I={idx:a,lineStyle:o,pointRadius:m,pointStyle:h,dataLabels:l==null?void 0:l.dataLabels,...S};if(!l)d({...c||{},datasetOptions:[...i||[],I]});else{const P=i==null?void 0:i.map(C=>C.idx===a?{...C,...I}:C);d({...c||{},datasetOptions:P})}}function g(S){u({dataLabels:{...l==null?void 0:l.dataLabels,enabled:S}})}function v(S){u({dataLabels:S})}return e.jsx(t.Collapsible,{open:n,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",n&&"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"}),x.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:S=>u({lineStyle:S}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ls.map(({value:S,label:I})=>e.jsx(t.SelectItem,{value:S,className:"text-xs",children:I},S))})]})]}),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(m),onValueChange:S=>u({pointRadius:Number(S)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Gl.map(S=>e.jsx(t.SelectItem,{value:String(S),className:"text-xs",children:S===0?"None":S},S))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(t.Select,{value:h,onValueChange:S=>u({pointStyle:S}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ul.map(({value:S,label:I})=>e.jsx(t.SelectItem,{value:S,className:"text-xs",children:I},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 text-muted-foreground",children:"Data Labels"}),e.jsx(t.Switch,{size:"sm",checked:f,onCheckedChange:g})]}),f&&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 Wl=[0,2,4,6,8,10,12,16,20];function Yl(){const s=t.useEditorStore(a=>{var n;return(n=a.card)==null?void 0:n.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-[12px] 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(Xl,{})})]})}function Xl(){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((a,n)=>e.jsx(Zl,{metricKey:a,idx:n},a))})}function Zl({metricKey:s,idx:a}){var g;const[n,r]=N.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,S;return(S=(b=v.card)==null?void 0:b.preferences)==null?void 0:S.datasetOptions}),d=l==null?void 0:l.find(v=>v.idx===a),{setCardPreferences:o}=t.useEditorStore(v=>v.actions),m=(d==null?void 0:d.borderRadius)??0,h=((g=d==null?void 0:d.dataLabels)==null?void 0:g.enabled)??!1;function f(v){const b={idx:a,borderRadius:m,dataLabels:d==null?void 0:d.dataLabels,...v};if(!d)o({...i||{},datasetOptions:[...l||[],b]});else{const S=l==null?void 0:l.map(I=>I.idx===a?{...I,...b}:I);o({...i||{},datasetOptions:S})}}function x(v){f({dataLabels:{...d==null?void 0:d.dataLabels,enabled:v}})}function u(v){f({dataLabels:v})}return e.jsx(t.Collapsible,{open:n,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",n&&"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:m>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:",m]})})]})}),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(m),onValueChange:v=>f({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:Wl.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:h,onCheckedChange:x})]}),h&&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:u,isHorizontal:c==="horizontalBar",showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const eo=[0,1,2,3,4,5,6,8,10],to=[{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 │"}],so=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function no(){const s=t.useEditorStore(d=>d.card),a=t.useEditorStore(d=>{var o;return(o=d.card)==null?void 0:o.preferences}),n=Ae.useEffectiveEditorCardType(),r=a==null?void 0:a.lineStyleConfig,{setCardPreferences:c,updateCardInFrame:i}=t.useEditorActions();if(!s||!["line","area","stackedArea"].includes(n))return null;const l=(d,o)=>{const m={...a||{},lineStyleConfig:{...r,[d]:o}};c(m),i({...s,preferences:m})};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-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ma,{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:so.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:eo.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:to.map(({value:d,label:o})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:o},d))})]})]})]})})]})}const ao=[0,2,4,6,8,10,12,16,20],ro=[{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%"}],lo=[{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 oo(){const s=t.useEditorStore(d=>d.card),a=t.useEditorStore(d=>{var o;return(o=d.card)==null?void 0:o.preferences}),n=Ae.useEffectiveEditorCardType(),r=a==null?void 0:a.barStyleConfig,{setCardPreferences:c,updateCardInFrame:i}=t.useEditorActions();if(!s||!["bar","horizontalBar","stackedBar"].includes(n))return null;const l=(d,o)=>{const m={...a||{},barStyleConfig:{...r,[d]:o}};c(m),i({...s,preferences:m})};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-[12px] 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:ao.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:ro.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:lo.map(({value:d,label:o})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:o},d))})]})]})]})})]})}function io(){const s=t.useEditorStore(n=>{var r,c;return(c=(r=n==null?void 0:n.card)==null?void 0:r.preferences)==null?void 0:c.sortChart}),{setSortChart:a}=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-3.5 w-3.5 text-foreground/60"}),"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(nt,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"Ascending",value:"asc"},{label:"Descending",value:"desc"}],value:s||"none",onValueChange:n=>{a(n)}})]})})]})}const co=["kpi"],Sn={none:"None",previous_period:"Previous Period",same_period_last_year:"Same Period Last Year",start_vs_end:"Start vs End",target:"Target"},os=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 uo(s){if(!(s!=null&&s.name)||!(s!=null&&s.dataType)||s.role==="metric")return!1;const a=t.getDataType(s.dataType);return["date","string","boolean"].includes(a)}function mo(s){return{...s,role:"groupby"}}function xo(){var I,P;const s=t.useEditorStore(C=>C.card),a=t.useEditorStore(C=>C.actions.updateCardConfig),n=Ae.useEffectiveEditorCardType(),{scopedFields:r}=t.useScopedFields(),c=((I=s.config)==null?void 0:I.metricColumns)||[],i=((P=s.config)==null?void 0:P.summary)||{},l=i.breakdownDimensions||[],d=co.includes(n),o=c.length>0,m=i.enabled===!0,h=d&&o,{comparisonType:f}=t.getEffectiveComparisonSettings(s.config,n),x=Sn[f]||Sn.none,u=Array.from(new Map(r.filter(uo).map(C=>[lt(C),mo(C)])).values()),g=new Set(u.map(C=>lt(C))),v=new Set(l.map(C=>lt(C)).filter(C=>C&&g.has(C)));if(!d)return null;const b=C=>{a(s.id,{summary:{...i,...C}})},S=(C,A)=>{const y=lt(C),T=u.filter(D=>v.has(lt(D))),E=A?v.has(y)?T:[...T,C].slice(0,os):T.filter(D=>lt(D)!==y);b({breakdownDimensions:E})};return e.jsxs(t.AccordionItem,{value:"summary",className:"border-none",children:[e.jsx(t.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-[12px] hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.FileText,{className:"h-3.5 w-3.5 text-foreground/60"}),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:m,disabled:!h,onCheckedChange:C=>{if(!C){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: ",x]}),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:!m,onCheckedChange:C=>b({showOnCard:C})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"summary-include-rollup",className:"text-xs",children:"Include in dashboard summary"}),e.jsx(t.Switch,{size:"sm",id:"summary-include-rollup",checked:i.includeInDashboardSummary===!0,disabled:!m,onCheckedChange:C=>b({includeInDashboardSummary:C})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Breakdown Dimensions"}),e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[l.length,"/",os]})]}),u.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:u.map(C=>{const A=lt(C),y=v.has(A),T=v.size>=os,E=!m||!y&&T;return e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx(t.Checkbox,{id:`summary-breakdown-${A}`,checked:y,disabled:E,onCheckedChange:D=>S(C,D===!0)}),e.jsx(t.Label,{htmlFor:`summary-breakdown-${A}`,className:"cursor-pointer text-xs",children:C.label||C.name})]},A)})})]}),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:!m,onCheckedChange:C=>b({anomalyEnabled:C})})]})]})]})}const ho=[];function po(){var c;const s=t.useEditorStore(i=>i.card),a=((c=s==null?void 0:s.config)==null?void 0:c.metricColumns)??ho,{updateMetricColumn:n,updateCardInFrame:r}=t.useEditorActions();return!s||s.type==="kpi"||a.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-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ha.Braces,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:"Metric Formats"})]})}),e.jsx(t.AccordionContent,{className:"space-y-4 pt-2",children:a.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(ps,{value:i.format,onChange:l=>{var d;n(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 fo=new Set(["area","bar","bubble","bullet","combo","doughnut","funnel","horizontalBar","line","pie","polarArea","radar","scatter","stackedArea","stackedBar","stackedLine","tornado"]);function go(){const s=t.useEditorStore(o=>o.card),a=t.useEditorStore(o=>{var m;return(m=o.card)==null?void 0:m.preferences}),n=Ae.useEffectiveEditorCardType(),{setCardPreferences:r,updateCardInFrame:c}=t.useEditorActions();if(!s||!fo.has(n||""))return null;const i=a==null?void 0:a.tooltipConfig,l=(i==null?void 0:i.formatMode)||(i==null?void 0:i.mode)||"inherit",d=o=>{const m={...a||{},tooltipConfig:{...i||{},...o}};r(m),c({...s,preferences:m})};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-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Info,{className:"h-3.5 w-3.5 text-foreground/60"}),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(bt,{formatOptions:(i==null?void 0:i.formatOptions)||{},onFormatOptionsChange:o=>d({formatMode:"override",mode:"override",formatOptions:o}),showTitle:!1})]})]})}function Qn({mode:s}){const a=t.useEditorStore(n=>{var r;return(r=n.card)==null?void 0:r.type});return e.jsxs(e.Fragment,{children:[a==="combo"&&e.jsx(Rl,{}),(a==="area"||a==="stackedArea")&&e.jsx(ql,{}),a==="line"&&e.jsx(Hl,{}),(a==="bar"||a==="horizontalBar"||a==="stackedBar")&&e.jsx(Yl,{}),e.jsx(no,{}),e.jsx(oo,{}),e.jsx(vl,{}),s==="config"&&e.jsx(jl,{}),s==="config"&&e.jsx(xo,{}),e.jsx(Nl,{}),a==="bullet"&&e.jsx(Cl,{}),a==="funnel"&&e.jsx(Tl,{}),(a==="bubble"||a==="scatter")&&e.jsx(Sl,{}),(a==="stackedBar"||a==="stackedLine")&&e.jsx(io,{}),e.jsx(po,{}),e.jsx(pl,{}),e.jsx(fl,{}),e.jsx(gl,{}),e.jsx(bl,{}),e.jsx(go,{})]})}function bo(){const s=t.useEditorStore(n=>n.card),a=s==null?void 0:s.type;return a?e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(_t,{chartType:a}),e.jsx(t.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:e.jsx(Qn,{mode:"dev"})})]}):null}function jo(){const s=t.useEditorStore(c=>c.card),a=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(a){case"kpi":return e.jsx(Jr,{});case"table":return e.jsx(ul,{});case"map":return e.jsx(Zr,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(Kn,{})});case"text":return e.jsx(xl,{});default:return e.jsx(bo,{})}}return e.jsxs(t.ScrollArea,{className:"h-full w-full text-sm",children:[r(),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}function vo(){const s=N.useRef(null),a=N.useRef(null),n=t.useEditorStore(f=>f.isShowingVisual),r=t.useEditorStore(f=>f.isDevMode),c=t.useEditorStore(f=>f.showAIDialog),[i,l]=N.useState(!1),d=n&&!c,o=d&&(!r||i),m=r&&d,h=()=>l(f=>!f);return N.useEffect(()=>{var f,x,u,g;c?((f=s.current)==null||f.resize(0),(x=a.current)==null||x.resize(0)):((u=s.current)==null||u.resize(25),(g=a.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(ur,{})}),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(jo,{})})}),!c&&e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(hn,{visualAsideControl:m?{show:!0,isOpen:i,onToggle:h}:void 0})})]}):e.jsx(hn,{visualAsideControl:m?{show:!0,isOpen:i,onToggle:h}:void 0})})]})}function yo(s){var Ie;t.useAIInteractionStore(K=>K.currentAIContext);const[a,n]=N.useState(""),[r,c]=N.useState(null),{authToken:i,tokenProps:l}=t.useSemaphorContext(),d=t.useEditorStore(K=>K.card.id),o=t.useEditorStore(K=>{var re;return(re=K==null?void 0:K.card)==null?void 0:re.sql}),m=t.useEditorStore(K=>K.isDevMode),h=t.useEditorStore(K=>{var re;return(re=K==null?void 0:K.card)==null?void 0:re.python}),{setCardPython:f,setCardSql:x,setRunSql:u,switchCardType:g,setQueryConfig:v}=t.useEditorActions(),b=t.useEditorStore(K=>K.currentAssitantScope)||[],S=t.useEditorStore(K=>K.userInputForAI),I=t.useEditorStore(K=>K.triggerAIRun),P=t.useEditorStore(K=>K.card),C=t.useEditorStore(K=>K.selectedDatabaseName),A=t.useEditorStore(K=>K.selectedTableName),y=t.useEditorStore(K=>K.selectedConnectionId),T=t.useEditorStore(K=>K.selectedSchemaName),E=t.useDashboardStore(K=>K.dashboard.aiScopeTables),{errorMessage:D,refetch:p,data:R}=t.useEditorCardQuery(P),{setTriggerAIRun:w,setCurrentAssitantScope:M,setCardConfig:F}=t.useEditorActions(),{selectedDatamodelName:j,connectionType:L,selectedDatamodelId:k}=t.useEditorAside(),O=(Ie=t.useDashboardQuery().data)==null?void 0:Ie.assistantProfileId,z=N.useRef(t.createAssistantConversationId()),V=N.useRef(null),B=N.useRef(d),_=N.useRef(!1),G=()=>{const K=V.current;K&&(V.current=null,z.current=t.createAssistantConversationId(),K==="clear"&&H([]))},{messages:q,setMessages:H,regenerate:te,error:ie,sendMessage:oe,status:de,addToolResult:he,stop:me,clearError:se}=t.useChat({transport:new t.DefaultChatTransport({api:`${l.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${i==null?void 0:i.accessToken}`}),body:()=>{const K=t.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:O,conversationId:z.current,assistantRequestId:t.createAssistantRequestId(),isDevMode:m,aiContext:K.currentAIContext,reasoningEffort:K.reasoningEffort,showReasoning:K.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:K,body:re})=>({body:{...re,messages:t.cleanupIncompleteMessages(K)}})}),onError:K=>{var re;if(_.current=!1,K.name==="AbortError"||(re=K.message)!=null&&re.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)"),G();return}console.error("[Editor Assistant] Stream error:",K),G()},onToolCall:X,onFinish({isAbort:K,isDisconnect:re,isError:ve}){_.current=!1,n(""),console.log(K?"[Editor Assistant] Stream aborted by user":re?"[Editor Assistant] Stream disconnected (network error)":ve?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully"),G()}}),je=N.useCallback(K=>{_.current=!0;try{const re=oe(K);return t.isPromiseLike(re)?re.catch(ve=>{throw _.current=!1,ve}):re}catch(re){throw _.current=!1,re}},[oe]),be=N.useCallback(()=>{_.current=!0;try{const K=te();return t.isPromiseLike(K)?K.catch(re=>{throw _.current=!1,re}):K}catch(K){throw _.current=!1,K}},[te]),ye=K=>{let re=!1;H(ve=>{const ee=typeof K=="function"?K(ve):K;if(ee.length===0){if(_.current)return V.current="clear",re=!0,ve;V.current=null,z.current=t.createAssistantConversationId()}return ee}),re&&me()};N.useEffect(()=>{if(B.current!==d){if(B.current=d,_.current){V.current!=="clear"&&(V.current="rotate"),me();return}V.current=null,z.current=t.createAssistantConversationId()}},[d,me]),N.useEffect(()=>{I&&S&&(je({role:"user",parts:[{type:"text",text:S}]}),w(!1))},[I,S,je,w]);async function X({toolCall:K}){var re,ve,ee,Q,ae,ue,Se,Ne,Oe,Ve,Ye,Je,We,ne,ke,Be;if(["createChartFromSql","createForecast"].includes(K.toolName)){const Ce=((re=K.input)==null?void 0:re.sql)??((ve=K.args)==null?void 0:ve.sql),Ge=((ee=K.input)==null?void 0:ee.python)??((Q=K.args)==null?void 0:Q.python),we=((ae=K.input)==null?void 0:ae.chartType)??((ue=K.args)==null?void 0:ue.chartType);g(we),x(Ce),f(Ge),u(!0),he({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(K.toolName==="getUserSql"){if(!o){he({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"error",message:"No SQL found"}});return}he({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",sql:o,python:h||""}})}else if(K.toolName==="generateQueryConfig"){n("Generating query config...");const Ce=((Se=K.input)==null?void 0:Se.chartType)??((Ne=K.args)==null?void 0:Ne.chartType),Ge=((Oe=K.input)==null?void 0:Oe.queryConfig)??((Ve=K.args)==null?void 0:Ve.queryConfig);((Ye=K.input)==null?void 0:Ye.cardConfig)??((Je=K.args)==null||Je.cardConfig),g(Ce),F(Ge),x(void 0),f(void 0);const we=await p();if((We=we==null?void 0:we.data)!=null&&We.error){he({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"error",queryConfig:Ge,message:(ne=we==null?void 0:we.data)==null?void 0:ne.error.message}});return}if((ke=we==null?void 0:we.data)!=null&&ke.records){he({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",queryConfig:Ge,message:"The data has been visualized"}});return}he({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",queryConfig:Ge,message:"The data has been visualized",records:(Be=we==null?void 0:we.data)==null?void 0:Be.records}})}else n("Analyzing...")}function ge(K){const re=t.removeFromScopeArray(b,K);Z(re)}function Z(K){const re=t.sanitizeAIScope(K);M(re),H(ve=>[...ve,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(re)}`}]}])}function Te(){const K={databaseName:C||"",schemaName:T||"",tableName:A||"",datamodelId:k||"",datamodelName:t.resolveDatamodelName(j),connectionId:y||"",connectionType:L||""},re=t.dedup([...b,K]);Z(re)}function Le(){const K={databaseName:C||"",schemaName:T||"",tableName:A||"",datamodelName:t.resolveDatamodelName(j),connectionId:y||"",connectionType:L||"",datamodelId:k||""};if(!t.isInAiScopeArray([...E||[],...b],K)||b.length===0){const ve=t.dedup([...E||[],...b,K]).filter(ee=>ee.connectionId===K.connectionId);Z(ve)}}const De=!["ready","error"].includes(de),Ee=t.getErrorMessage(ie);return{messages:q,setMessages:ye,sendMessage:je,regenerate:be,isLoading:De,handleSetAIScope:Le,handleAddCurrentTableToScope:Te,removeFromCurrentSelections:ge,currentAssitantScope:b,setCurrentAssitantScope:M,stop:me,status:de,toolStatus:a,llmUsage:r,onFinish:s,errorMessage:Ee,clearError:se}}const No=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function wn({isFullscreen:s,onFullscreenChange:a,fullscreenContainer:n}){const r=N.useRef(null),c=N.useRef(!1),[i,l]=N.useState(!1),[d,o]=N.useState(t.isDevEnv),[m,h]=N.useState(!1),[f,x]=N.useState(!1),[u,g]=N.useState(!1),v=s??u,b=t.useCurrentAIContext(),{setCurrentAIContext:S,setHasEditorEntitySelectionOverride:I}=t.useAIActions(),{clearQueue:P}=t.useQueueActions(),{clearFileAttachments:C}=t.useFileActions(),A=t.useFileAttachments("editor"),{selectedEntities:y}=t.useAssistantContextEntities("editor"),T=t.useEditorStore(ne=>ne.card.id),E=t.useEditorStore(ne=>ne.card.dataSource),D=t.useEditorStore(ne=>{var ke;return(ke=ne.card.dataSource)==null?void 0:ke.selectedEntities}),p=t.useEditorStore(ne=>ne.actions.setCardSql),R=t.useEditorStore(ne=>ne.actions.setRunSql),w=t.useEditorStore(ne=>ne.showAIDialog),M=t.useDashboardStore(ne=>ne.handleOpenAssistantProfile),{setShowAIDialog:F,setCardPython:j}=t.useEditorActions(),{setDataSource:L}=t.useEditorActions(),{assistantProfile:k}=t.useAssistantProfile(),{messages:O,setMessages:z,sendMessage:V,isLoading:B,stop:_,status:G,llmUsage:q,errorMessage:H,clearError:te}=yo(),[ie,oe]=N.useState(""),de=ne=>{oe(ne.target.value)},he=ne=>{ne.preventDefault();const ke=ie.trim();if(!ke&&A.length===0)return;const Be=[];ke&&Be.push({type:"text",text:ke}),A.forEach(Ce=>{Ce.data&&Be.push({type:"file",mediaType:Ce.type,filename:Ce.name,url:`data:${Ce.type};base64,${Ce.data}`})}),V({role:"user",parts:Be}),oe(""),C("editor"),De({force:!0})},{visibleMessages:me,hasMoreMessages:se,totalMessageCount:je,loadMoreMessages:be,resetMessageWindow:ye}=t.useMessageWindow(O,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:X,contentRef:ge,isAtBottom:Z,hasNewMessages:Te,newMessageCount:Le,scrollToBottom:De,handleScroll:Ee,resetNewMessageCount:Ie}=t.useAutoScroll(me,{threshold:40,behavior:"smooth",isStreaming:B});N.useEffect(()=>{var ne;w&&!c.current&&((ne=r.current)==null||ne.focus()),c.current=w},[w]),N.useEffect(()=>{w&&(I(!1),S({selectedEntities:D||[]}))},[T,D,S,I,w]),t.useAutoSubmitQueue({assistantType:"editor",status:G,isLoading:B,sendMessage:V});const{hasActiveTools:K,activeToolText:re}=t.useActiveToolStatus(O),ve=N.useCallback(ne=>{a==null||a(ne),s===void 0&&g(ne)},[s,a]);N.useEffect(()=>{if(!v)return;function ne(ke){ke.key==="Escape"&&ve(!1)}return window.addEventListener("keydown",ne),()=>{window.removeEventListener("keydown",ne)}},[v,ve]);const ee=N.useCallback(ne=>{V({role:"user",parts:[{type:"text",text:ne}]}),De({force:!0})},[V,De]),Q=N.useCallback(async()=>{const ne=JSON.stringify(O??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(ne),t.ue.success("Conversation copied")}catch(ke){console.error("Failed to copy conversation",ke),t.ue.error("Unable to copy conversation")}},[O]),ae=N.useCallback(()=>{ve(!v)},[v,ve]);function ue(ne,ke){ke==="sql"?(p(ne),R(!0)):ke==="python"&&(j(ne),R(!0))}function Se(){b.selectedEntities.length===0&&S({selectedEntities:y})}function Ne(ne){Se();const ke={role:"user",parts:[{type:"text",text:ne.title+" "+ne.subtitle}]};V(ke)}function Oe(ne){Se(),V({role:"user",parts:[{type:"text",text:ne}]})}function Ve(){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:m,onCheckedChange:h,children:"System Message"})]})]})}function Ye(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const Je=(ie==null?void 0:ie.length)===0&&(O==null?void 0:O.filter(ne=>ne.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:[Ye(),M&&e.jsx(t.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:M,children:(k==null?void 0:k.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[Ve(),d&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Q,children:"Copy Conversation"}),e.jsx(t.IconButton,{tooltip:v?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:ae,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:()=>{z([]),P("editor"),te(),ye()},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:Ee,children:e.jsxs("div",{ref:ge,className:"min-w-0 space-y-4 py-2 pr-3","data-role":"messages",children:[se&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:be,className:"text-xs",children:["Load ",Math.min(5,je-me.length)," ","more messages (",je-me.length," ","hidden)"]})}),e.jsx(t.PrintMessages,{messages:me,showTools:d,handleRun:ue,showSystemMessage:m,onQuickReply:ee,disableQuickReplies:B}),e.jsx(t.AssistantStatus,{status:G,errorMessage:H,activeToolText:B&&K?re:void 0})]})}),w&&!Z&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(t.Button,{onClick:()=>{De({force:!0}),Ie()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(t.ChevronDown,{className:"h-4 w-4"}),Te&&Le>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:Le>9?"9+":Le})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[Je&&!k&&e.jsx(t.Placeholders,{onClick:Ne,placeholders:No}),e.jsx("div",{children:Je&&k&&e.jsx(t.SeedQuestions,{seedQuestions:k.seedQuestions||[],handleSeedQuestionClick:Oe})})]}),e.jsx(t.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(t.ChatInputWithContext,{ref:r,setInput:oe,stop:_,input:ie,handleInputChange:de,handleSubmit:ne=>{Se(),he(ne),De({force:!0})},isLoading:B,status:G,assistantType:"editor",onFocus:()=>{}})]}),q&&i&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",q.inputTokens," prompt tokens, ",q.outputTokens," ","completion tokens, ",q.totalTokens," total tokens"]})}),e.jsx(t.AddDataPicker,{incomingSelectedEntities:y,open:f,onOpenChange:x,dataSource:E||t.EMPTY_DATA_SOURCE,dialogMode:"aiContext",onSaveSelectedEntities:ne=>{I(!0),S({...b,selectedEntities:ne})}})]});return v&&n?xa.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})}),n):We}const Tn={table:t.Table2,bar:t.ChartColumnIncreasing,line:t.ChartLine,stackedBar:t.ChartColumnStacked,stackedLine:t.MdStackedLineChart,scatter:t.ChartScatter,bubble:t.TbChartBubble,pie:t.ChartPie,doughnut:t.Donut,kpi:t.TiSortNumerically,treemap:t.TbChartTreemap,bullet:t.BulletChartIcon,funnel:t.TbChartFunnel,tornado:t.Tornado,heatmap:t.Grid3x3,range:t.ChartNoAxesGantt,radar:t.Radar,polarArea:t.PiChartPolar,text:t.BookType,map:t.Map},En={table:"Table",bar:"Bar Chart",line:"Line Chart",stackedBar:"Stacked Bar",stackedLine:"Stacked Line",scatter:"Scatter",bubble:"Bubble",pie:"Pie Chart",doughnut:"Donut",kpi:"KPI",treemap:"Treemap",bullet:"Bullet",funnel:"Funnel",tornado:"Tornado",heatmap:"Heatmap",range:"Range",radar:"Radar",polarArea:"Polar Area",text:"Text",map:"Map"},Co=[{id:"table"},{id:"bar"},{id:"line"},{id:"pie"},{id:"kpi"},{id:"doughnut"}],So=6;function wo({selectedChart:s,onChartChange:a}){var C,A;const[n,r]=N.useState(!1),c=t.useEditorStore(y=>y.card),{setCardType:i,setCardPreferences:l}=t.useEditorStore(y=>y.actions),{setCardCustomCfg:d,setCustomCardPreferences:o,setQueryConfig:m,replaceFrameCards:h,clearModeDrafts:f,initializeModeDrafts:x}=t.useEditorActions(),{starredCharts:u}=t.useStarredChartsStore(),{data:g=[]}=t.useCustomVisualsQuery(),v=N.useMemo(()=>{const y=u.filter(p=>p.type==="default"?!0:g.some(R=>R.name===p.id)),T=new Set(y.map(p=>p.id)),E=Co.filter(p=>!T.has(p.id));return[...y.map(p=>({id:p.id,label:p.name,icon:p.type==="default"?Tn[p.id]:void 0,isCustom:p.type==="custom",url:p.url})),...E.map(p=>({id:p.id,label:En[p.id]??p.id,icon:Tn[p.id],isCustom:!1}))].slice(0,So)},[u,g]),b=s==="custom"&&((C=c==null?void 0:c.customCardPreferences)==null?void 0:C.componentName),S=y=>{if(y.isCustom){const T=g.find(p=>p.name===y.id);if(!T)return;d(null),l({}),m(void 0);const E=t.resolveMultiInputTypeFromVisual(T);if(E==="multiple"&&T.slots&&T.slots.length>0){f();const p=t.createCardsFromSlots(T.slots,T,c);h(p),p[0]&&x(p[0]);return}i("custom"),o({type:"component",visualType:E,url:T.url,componentName:T.name,icon:T.icon,pluginChartType:T.chartType,minInputs:T.minInputs,maxInputs:T.maxInputs}),a("custom");return}a(y.id)},I=v.some(y=>{var T;return y.isCustom?b&&((T=c==null?void 0:c.customCardPreferences)==null?void 0:T.componentName)===y.id:s===y.id}),P=I?"More":s==="custom"?((A=c==null?void 0:c.customCardPreferences)==null?void 0:A.componentName)||"Custom":En[s]||"More";return e.jsxs("div",{className:"px-4 pb-3 pt-4",children:[e.jsx("p",{className:"pb-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Chart type"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"inline-flex h-7 items-center overflow-hidden rounded-[5px] border border-border bg-background",children:v.map(y=>{var D;const T=y.icon,E=y.isCustom?b&&((D=c==null?void 0:c.customCardPreferences)==null?void 0:D.componentName)===y.id:s===y.id;return e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>S(y),"aria-label":y.label,"aria-pressed":!!E,className:t.cn("flex h-full w-7 items-center justify-center text-foreground/65 transition-colors hover:bg-muted/50 hover:text-foreground",E&&"bg-muted/70 text-foreground"),children:[T?e.jsx(T,{className:"h-3.5 w-3.5"}):e.jsx(ms,{chartName:y.label,isCustom:!0,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"sr-only",children:y.label})]})}),e.jsx(t.TooltipContent,{side:"bottom",children:y.label})]},`${y.isCustom?"custom":"default"}-${y.id}`)})}),e.jsxs(t.Popover,{open:n,onOpenChange:r,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",className:t.cn("inline-flex h-7 items-center gap-1 rounded-[5px] px-2 text-[12px] transition-colors hover:bg-muted/50",I?"text-muted-foreground":"text-foreground"),children:[e.jsx("span",{className:"truncate",children:P}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform",n&&"rotate-180"),strokeWidth:1.75})]})}),e.jsx(t.PopoverContent,{className:"w-[360px] p-3",align:"end",onOpenAutoFocus:y=>y.preventDefault(),children:e.jsx(Vn,{onChartSelect:y=>{a(y),r(!1)},onClose:()=>r(!1)})})]})]})]})}function To(s,a,n){if(!a)return!1;const r=a.qualifiedFieldName,c=a.qualifiedEntityName,i=c&&a.name?`${c}.${a.name}`:r;return s.some(l=>{if(!(t.getDataType(l.dataType||"")==="date"))return!1;const o=t.getSelectedDateFilterColumn(l,n),m=o.split("."),h=m[m.length-1]||o,f=m.length>1?m.slice(0,-1).join("."):void 0,x=l.qualifiedTableName||f,u=x?`${x}.${h}`:void 0;return r?u?u===i||u.endsWith(`.${r}`):h===a.name:u?u===i:h===a.name})}function Eo({aliasTemplate:s,onAliasTemplateChange:a}){var o;const[n,r]=N.useState(s),[c,i]=N.useState(!1),l=(o=t.useEditorStore(m=>{var h;return(h=m.card.config)==null?void 0:h.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?n:s,onChange:m=>{r(m.target.value),i(!0)},onFocus:()=>i(!0),onPointerDown:m=>m.stopPropagation(),className:"h-8 text-xs",onKeyDown:m=>{m.key==="Enter"&&c&&n!==s?(a(n),i(!1)):m.key==="Escape"&&(r(s),i(!1))},"aria-label":"Edit alias template"}),c&&n!==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:()=>{a(n),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 Io({valueAliases:s,onValueAliasesChange:a}){const[n,r]=N.useState(null),[c,i]=N.useState(""),[l,d]=N.useState(""),o=()=>{a({...s,"":""})},m=f=>{const x={...s};delete x[f],a(x)},h=f=>{const x={...s};delete x[f],x[c]=l,a(x),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(([f,x],u)=>e.jsx("div",{className:"flex items-center gap-2",children:n===f?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"?h(f):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"?h(f):g.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>h(f),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:f,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(f),i(f),d(x)},"aria-label":"Edit value alias key"}),e.jsx(t.Input,{placeholder:"Alias label",value:x,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(f),i(f),d(x)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>m(f),"aria-label":"Remove value alias",children:e.jsx(t.X,{className:"h-3 w-3"})})]})},f+u)),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 ko({idx:s}){var d;const a=t.useEditorStore(o=>{var m;return(m=o.card)==null?void 0:m.preferences}),n=t.useEditorStore(o=>{var m;return(m=o.card.preferences)==null?void 0:m.datasetOptions}),r=t.useEditorStore(o=>o.actions.setCardPreferences),c=(d=a==null?void 0:a.chartOptions)==null?void 0:d.indexAxis,i=n==null?void 0:n.find(o=>o.idx===s);function l(o,m){(o==="end"||o==="start")&&t.getContrastColor(t.getCanvasBackgroundColor());const h={display:o!=="none",align:o,anchor:o,clamp:!0};if(!i)r({...a,datasetOptions:[...n||[],{idx:m,datalabels:h}]});else{const f={...i};f.datalabels=h;const x=n==null?void 0:n.map(u=>u.idx===m?f:u);r({...a,datasetOptions:x})}}return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{children:e.jsx(Ra,{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(Ca,{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(wa,{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(Sa,{className:t.cn("h-4 w-4",{"rotate-90":c==="y"})})})]})})]})}function fs({children:s,className:a,delayDuration:n}){return e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:n,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:t.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:s})}),e.jsx(t.TooltipContent,{children:s})]})})}function Do(s,a=30){return s.length>a?s.slice(0,a)+"...":s}function Ao({col:s,idx:a,className:n,iconClassName:r,children:c}){const i=t.useEditorStore(h=>{var f;return(f=h.card)==null?void 0:f.preferences}),l=t.useEditorStore(h=>{var f,x;return(x=(f=h.card)==null?void 0:f.preferences)==null?void 0:x.datasetOptions}),d=l==null?void 0:l.find(h=>h.idx===a),{setCardPreferences:o}=t.useEditorStore(h=>h.actions);function m(h){if(!d)o({...i,datasetOptions:[...l||[],{idx:a,type:h==="area"?"line":h,fill:h==="area"?"origin":""}]});else{const f={...d};f.type=h==="area"?"line":h,f.fill=h==="area"?"origin":"";const x=l==null?void 0:l.map(u=>u.idx===a?f:u);o({...i,datasetOptions:x})}}return e.jsxs("div",{className:t.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[c||e.jsx(fs,{className:"max-w-[100px]",title:s,children:Do(s)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(t.ChartColumnIncreasing,{onClick:()=>m("bar"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(t.ChartLine,{onClick:()=>m("line"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(t.ChartArea,{onClick:()=>m("area"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(ko,{idx:a})]})]})}function Mo(){const s=t.useEditorStore(d=>d.card.type),a=t.useEditorStore(d=>d.isDevMode),n=t.useEditorStore(d=>d.card.preferences),{setCardPreferences:r}=t.useEditorStore(d=>d.actions);function c(d){var h;const o={datalabels:{display:d!=="none",align:d,anchor:d,clamp:!0}},m={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(h=n==null?void 0:n.chartOptions)==null?void 0:h.plugins,...o}}};r(m)}function i(){var d,o,m;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(t.Select,{value:((m=(o=(d=n==null?void 0:n.chartOptions)==null?void 0:d.plugins)==null?void 0:o.datalabels)==null?void 0:m.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,m;return e.jsx("div",{children:e.jsxs(t.Select,{value:((m=(o=(d=n==null?void 0:n.chartOptions)==null?void 0:d.plugins)==null?void 0:o.datalabels)==null?void 0:m.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:a?i():l()})}function Lo({column:s}){const a=t.useEditorStore(o=>o.card.type),n=t.useEditorStore(o=>{var m,h;return(h=(m=o.card)==null?void 0:m.config)==null?void 0:h.metricColumns}),r=(n==null?void 0:n.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(Ao,{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(Mo,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&l(),["pie","doughnut"].includes(a)&&d()]})}function Fo({field:s,searchQuery:a="",limit:n=500}){const{authToken:r,tokenProps:c}=t.useSemaphorContext(),i=t.useEditorStore(m=>m.card),l=i==null?void 0:i.dataSource,d=["attribute-values",s.entityName,s.name,a,n],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 m={groupByColumns:[{...s,role:"groupby"}],metricColumns:[],filters:a?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:s,operator:"contains",value:a}],groups:[]}:void 0,rowLimit:n},h={connection_id:l.connectionId,cardConfig:m,cardDataSource:l,cache_config:t.getCacheConfig({card:i})};console.log("requestBody",h);const f=await t.postRequestRegular(`${c.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",h);if(f!=null&&f.error)return console.error("Error fetching attribute values:",f.error),[];const x=s.name;return((f==null?void 0:f.records)||[]).map(g=>{const v=g[x]||g[s.alias||x]||g[s.label];return{id:v||"",value:v||"",label:String(v||"(empty)")}})}catch(m){return console.error("Error fetching attribute values:",m),[]}},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 Jn({open:s,onOpenChange:a,availableFields:n,existingFilters:r,editingCondition:c,onSave:i}){var P,C;const l=!!c,[d,o]=N.useState(l?"values":"fields"),[m,h]=N.useState(""),[f,x]=N.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]:[]}),u=n.filter(A=>{var T;return l?!1:!((T=r==null?void 0:r.conditions)==null?void 0:T.some(E=>E.field.id===A.id))&&A.label.toLowerCase().includes(m.toLowerCase())}),g=A=>{x({...f,field:A}),o("values")},v=()=>{if(f.field&&f.selectedValues.length>0){const A={id:f.id,field:f.field,operator:"in",value:f.selectedValues};let y;if(l){const T=((r==null?void 0:r.conditions)||[]).map(E=>E.id===c.id?A:E);y={...r,conditions:T}}else{const T=(r==null?void 0:r.conditions)||[];y={id:(r==null?void 0:r.id)||t.v4(),logicalOperator:"AND",negate:!1,conditions:[...T,A],groups:[]}}i(y),a(!1)}},b=()=>{if(!l||!c)return;const A=((r==null?void 0:r.conditions)||[]).filter(y=>y.id!==c.id);if(A.length>0){const y={...r,conditions:A};i(y)}else i(void 0);a(!1)},S=A=>{x({...f,selectedValues:A})},I=()=>{l&&c?(x({id:c.id,field:c.field,selectedValues:Array.isArray(c.value)?c.value:[c.value]}),o("values")):(x({id:t.v4(),field:null,selectedValues:[]}),o("fields")),h("")};return N.useEffect(()=>{s&&I()},[s,l,c]),e.jsx(t.Dialog,{open:s,onOpenChange:a,children:e.jsxs(t.DialogContent,{className:"max-w-2xl",children:[e.jsx(t.DialogHeader,{children:e.jsx(t.DialogTitle,{children:l?`Edit Filter: ${(P=f.field)==null?void 0:P.label}`:d==="fields"?"Select Field to Filter":`Select Values for ${(C=f.field)==null?void 0:C.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!l&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&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(A=>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:[A.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(A.value)?`${A.value.length} values`:String(A.value)})]},A.id))})]}),d==="fields"&&!l?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex h-7 items-center gap-1.5 rounded-[5px] border border-border bg-background px-2 focus-within:border-ring",children:[e.jsx(t.Search,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx("input",{type:"text",placeholder:"Search fields",value:m,onChange:A=>h(A.target.value),className:"h-full w-full bg-transparent text-[12px] text-foreground placeholder:text-muted-foreground focus:outline-none"}),m&&e.jsx("button",{type:"button","aria-label":"Clear search",onClick:()=>h(""),className:"inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground hover:bg-muted hover:text-foreground",children:e.jsx(t.X,{className:"h-3 w-3"})})]}),e.jsx("div",{className:"grid max-h-[400px] grid-cols-2 gap-1 overflow-y-auto",children:u.map(A=>e.jsxs("button",{type:"button",onClick:()=>g(A),className:"group flex items-center gap-2 rounded-[5px] border border-border px-2 py-1.5 text-left transition-colors hover:bg-muted focus-visible:border-ring focus-visible:outline-none",children:[e.jsx(t.IconForFieldType,{dataType:t.getDataType(A.dataType)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-[13px] text-foreground",children:A.label}),e.jsxs("div",{className:"truncate font-mono text-[10px] text-muted-foreground",children:[A.entityName,".",A.name]})]})]},A.id))}),u.length===0&&m&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',m,'"']}),u.length===0&&!m&&n.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(Ro,{field:f.field,selectedValues:f.selectedValues,onValuesChange:S,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:I,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(t.Button,{onClick:v,disabled:!f.field||f.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function Ro({field:s,selectedValues:a,onValuesChange:n,onBack:r}){const[c,i]=N.useState(""),{values:l,isLoading:d,isFetching:o}=Fo({field:s,searchQuery:c,limit:500}),m=c?l.filter(x=>String(x.value).toLowerCase().includes(c.toLowerCase())):l,h=x=>{const u=a.includes(x);n(u?a.filter(g=>g!==x):[...a,x])},f=()=>{a.length===m.length&&m.length>0?n([]):n(m.map(x=>x.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(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:x=>i(x.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:a.length===m.length&&m.length>0,onCheckedChange:f}),e.jsxs(t.Label,{className:"text-sm",children:["Select All (",m.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:m.map(x=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>h(x.value),children:[e.jsx(t.Checkbox,{checked:a.includes(x.value),onCheckedChange:()=>h(x.value)}),e.jsx(fs,{className:"text-sm",children:x.label})]},x.id))})]})]})}function Oo({field:s,zone:a,index:n,sortDirection:r,onSortDirectionChange:c,hasPivotColumns:i=!1,cardType:l}){var Cs,Ss,ws,Ts,Es,Is,ks,Ds,As,Ms,Ls,Fs,Rs,Os,Ps,Bs,Vs,zs,_s,qs,$s,Ks,Gs,Us,Hs,Qs,Js,Ws,Ys,Xs,Zs,en,tn;const{attributes:d,listeners:o,setNodeRef:m,transform:h,transition:f,isDragging:x}=t.useSortable({id:s.id}),u=t.useEditorStore(U=>U.card),g=t.useEditorStore(U=>U.frame),v=t.useDashboardStore(U=>U.isVisualEditing),b=t.useDashboardStore(U=>U.selectedSheetId),S=t.useDashboardStore(U=>U.actions.updateSheetCalculatedFields),{scopedFields:I,valuePickFilterableFields:P,isLoading:C}=t.useFilterableFields(),{userContext:A}=t.useCurrentUserInfo(),y=(A==null?void 0:A.type)==="organization",{updateLabel:T,handleAggregationChange:E,handleDateFormatChange:D,handleGranularityChange:p,handleAliasTemplateChange:R,handleValueAliasesChange:w,handleMetricFormatChange:M,removeField:F,handleMetricComparisonChange:j,handleMetricWindowTransformChange:L,handleMetricWindowOrderByChange:k,handleMetricWindowDirectionChange:O,handleMetricWindowPartitionToggle:z,handleMetricMovingAverageWindowSizeChange:V,handleMetricMovingAverageMinPeriodsChange:B,handleMetricPreviousPeriodDeltaModeChange:_,handleMetricPercentOfTotalScopeChange:G,handleMetricPercentOfTotalOutputChange:q,handleKpiShowTrendlineChange:H,handleKpiTrendlineWindowChange:te,handleKpiTrendlineGranularityChange:ie,handleMetricTargetValueChange:oe}=t.useFieldManagement(u),[de,he]=N.useState(!1),[me,se]=N.useState(()=>{var U;return!!((U=s.parameters)!=null&&U.windowTransform)}),[je,be]=N.useState(!1),[ye,X]=N.useState(!1),[ge,Z]=N.useState(null),Te=N.useMemo(()=>{const U=le=>le!=null&&le.startsWith("card-source-")?le.replace("card-source-",""):le,W=U(s.id),xe=I.find(le=>{if(s.qualifiedFieldName&&le.qualifiedFieldName&&le.qualifiedFieldName===s.qualifiedFieldName||s.qualifiedEntityName&&le.qualifiedEntityName&&le.qualifiedEntityName===s.qualifiedEntityName&&le.name===s.name)return!0;const Me=U(le.id);return!!(W&&Me&&W===Me)});return{dataType:(xe==null?void 0:xe.dataType)||s.dataType,resolvedFromScopedField:!!xe}},[s.dataType,s.id,s.name,s.qualifiedEntityName,s.qualifiedFieldName,I]),Le=t.getGranularityOptionsForFieldType(Te.dataType),[De,Ee]=N.useState(s.dateFormat||"YYYY-MM-DD"),[Ie,K]=N.useState(s.customFormat||""),[re,ve]=N.useState(!!s.customFormat),ee=N.useRef(null),[Q,ae]=N.useState(s.aliasTemplate||""),[ue,Se]=N.useState(s.valueAliases||{}),[Ne,Oe]=N.useState((Cs=s.parameters)==null?void 0:Cs.filters),Ve=U=>{U==="custom"?ve(!0):(ve(!1),Ee(U),(a==="groupBy"||mt)&&D(n,U,"",a))},Ye=U=>{K(U),(a==="groupBy"||mt)&&D(n,"custom",U,a)},Je=U=>{var le;const xe=(le=t.getDateFormatOptionsForGranularity(U)[0])==null?void 0:le.value;xe&&!re&&(Ee(xe),a==="groupBy"&&D(n,xe,"",a)),a==="groupBy"&&p(n,U)},We=U=>{ae(U),a==="metrics"&&R(n,U)},ne=U=>{Se(U),a==="metrics"&&w(n,U)},ke=U=>{T(a,n,U)},Be=t.getExpressionFieldKind(s),Ce=t.getFieldExpressionAnnotation(s),Ge=t.isManagedCalculatedExpressionField(s),we=s.role==="metric"&&Ge,jt=Ge&&(Be==="user_calculated"||Be==="inline_expression"&&s.fieldScope!=="domain"),Xe=jt?(Ss=g==null?void 0:g.calculatedFields)==null?void 0:Ss.find(U=>t.matchesCalculatedField(U,s,{allowComparableFallback:!0})):void 0,Tt=jt&&(s.fieldScope==="dashboard"||s.fieldScope===void 0&&!!Xe),Ue=Be==="domain_calculated"||s.fieldScope==="domain",Et=Ue?t.resolveDomainCalculatedFieldForEdit(s,I):void 0,ct=Ue?"domain":Tt?"dashboard":"card",Ze=Ue?Et||s:Tt&&Xe?Xe:s,It=U=>{var W;if(Oe(U),a==="metrics"){const xe={...s,parameters:{...s.parameters,filters:U}},le=[...((W=u.config)==null?void 0:W.metricColumns)||[]];le[n]=xe,t.useEditorStore.getState().actions.updateCardConfig(u.id,{metricColumns:le})}be(!1)},vt=()=>{F(a,n)},Kt={transform:t.CSS.Transform.toString(h),transition:f},kt=t.getDataType(Te.dataType||s.dataType),dt=kt==="date",ut=l==="kpi",mt=a==="detailColumns",xt=(ws=u.config)==null?void 0:ws.metricColumns,$e=(Ts=u.config)==null?void 0:Ts.groupByColumns,et=t.useDashboardStore(U=>{var W;return(W=U.dashboard)==null?void 0:W.filters}),Gt=t.useDashboardStore(U=>U.filterValues),tt=s.granularity||"day",Dt=Le.includes(tt)?tt:"day",yt=a==="groupBy"&&!Le.includes(tt),ht=t.getDateFormatOptionsForGranularity(Dt),Ut=re?"custom":ht.some(U=>U.value===De)?De:((Es=ht[0])==null?void 0:Es.value)??"YYYY-MM-DD";N.useEffect(()=>{var xe;if(C||!yt){ee.current=null;return}const U=`${s.id}:${tt}:${Te.dataType||s.dataType||""}:${n}`;if(ee.current===U)return;ee.current=U;const W="day";if(p(n,W),!re){const le=(xe=t.getDateFormatOptionsForGranularity(W)[0])==null?void 0:xe.value;le&&(Ee(le),D(n,le,"",a))}},[s.dataType,s.id,D,p,yt,n,re,C,tt,Te.dataType,a]);const Ht=!!l&&t.COMPARISON_SUPPORTED_CHART_TYPES.includes(l),Qt=l==="kpi"||l==="table",Ke=N.useMemo(()=>$e==null?void 0:$e.find(U=>t.getDataType(U.dataType||"")==="date"),[$e]),At=N.useMemo(()=>($e||[]).some(U=>t.getDataType(U.dataType||"")==="date"),[$e]),pt=N.useMemo(()=>{var le;if(!Ke)return!1;const U=(le=u.config)==null?void 0:le.filters;if(!U)return!1;const W=Me=>{const Re=Me.field;return Re?Ke.id&&Re.id===Ke.id||Ke.qualifiedFieldName&&Re.qualifiedFieldName===Ke.qualifiedFieldName?!0:Re.name===Ke.name:!1},xe=Me=>Me.conditions.some(_e=>t.getDataType(_e.field.dataType||"")==="date"&&W(_e))?!0:Me.groups.some(_e=>xe(_e));return xe(U)},[(Is=u.config)==null?void 0:Is.filters,Ke]),Mt=N.useMemo(()=>To(et||[],Ke,Gt),[et,Gt,Ke]),Nt=pt||Mt,$=s,Y=((Ds=(ks=$.parameters)==null?void 0:ks.windowTransform)==null?void 0:Ds.function)||"none",J=t.isMetricTransformEnabled($),ce=J?Y:null,pe=t.supportsMetricTransformForMetric({cardType:l||"table",cardConfig:u.config||{},metric:$,transformMode:ce||"running_total"}),fe=!!$.comparisonType&&$.comparisonType!=="none",Fe=t.getRunningTotalOrderByCandidates($e||[]),Pe=((Ls=(Ms=(As=$.parameters)==null?void 0:As.windowTransform)==null?void 0:Ms.orderBy)==null?void 0:Ls.fieldId)||"",Qe=((Os=(Rs=(Fs=$.parameters)==null?void 0:Fs.windowTransform)==null?void 0:Rs.orderBy)==null?void 0:Os.direction)||"asc",rt=Fe.find(U=>U.id===Pe),st=ce==="running_total"||ce==="moving_average"||ce==="previous_period_delta",ze=J&&st&&!!rt&&t.getDataType(rt.dataType||"")!=="date",ft=t.getDefaultRunningTotalPartitionByFieldIds({cardType:l||"table",cardConfig:u.config||{},orderByFieldId:Pe||void 0}),Jt=new Set(((Bs=(Ps=$.parameters)==null?void 0:Ps.windowTransform)==null?void 0:Bs.partitionByFieldIds)||ft),Wt=l==="pivotTable"||t.isSubtotalEnabledAggregateTable(l||"table",u.config||{}),bs=[...($e||[]).filter(U=>U.id&&(!st||U.id!==Pe)),...Wt?(((Vs=u.config)==null?void 0:Vs.pivotByColumns)||[]).filter(U=>U.id):[]],js=((qs=(_s=(zs=$.parameters)==null?void 0:zs.windowTransform)==null?void 0:_s.movingAverage)==null?void 0:qs.windowSize)||7,Yn=((Gs=(Ks=($s=$.parameters)==null?void 0:$s.windowTransform)==null?void 0:Ks.movingAverage)==null?void 0:Gs.minPeriods)||1,Xn=((Qs=(Hs=(Us=$.parameters)==null?void 0:Us.windowTransform)==null?void 0:Hs.previousPeriodDelta)==null?void 0:Qs.mode)||"absolute",vs=((Ys=(Ws=(Js=$.parameters)==null?void 0:Js.windowTransform)==null?void 0:Ws.percentOfTotal)==null?void 0:Ys.scope)||"grand_total",Zn=((en=(Zs=(Xs=$.parameters)==null?void 0:Xs.windowTransform)==null?void 0:Zs.percentOfTotal)==null?void 0:en.output)||"percent",ea=N.useMemo(()=>(xt||[]).some(U=>U.comparisonType==="start_vs_end"),[xt]);N.useEffect(()=>{J&&se(!0)},[J]);const ta=a!=="pivotBy"&&a!=="sortBy",sa=dt&&a==="groupBy"&&(!ut||ea),na=!ut&&dt&&(a==="groupBy"||mt),aa=l==="kpi"&&dt&&a==="groupBy",ra=a==="metrics",ys=Ht&&a==="metrics",la=()=>{const U=s,W=a==="metrics"&&we;return e.jsxs("div",{className:"space-y-1",children:[!W&&e.jsx("div",{title:`${s.entityName}.${s.name}`,onPointerDown:xe=>{xe.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}`}),W&&U.calculatedFormula&&e.jsxs("div",{title:t.formatDisplayFormula(U.calculatedFormula),onPointerDown:xe=>{xe.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(U.calculatedFormula)]})]})},oa=()=>ta?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:ke,placeholder:"Display label...",type:"text"})]}):null,ia=()=>a!=="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:U=>c(U),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"})]})]})]}),Ns=()=>sa?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:Dt,onValueChange:Je,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:Le.map(U=>e.jsx(t.SelectItem,{className:"text-xs",value:U,children:t.toTitleCase(U)},U))})]})]}):null,ca=()=>na?e.jsxs(e.Fragment,{children:[Ns(),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:Ve,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(U=>e.jsx(t.SelectItem,{className:"text-xs",value:U.value,children:U.label},U.value))})]}),re&&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:Ie,onChange:U=>{U.stopPropagation(),Ye(U.target.value)},onClick:U=>U.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,da=()=>{var W,xe,le,Me;const U=aa;return U?e.jsx(e.Fragment,{children:U&&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:((W=u.config)==null?void 0:W.showTrendline)||!1,onCheckedChange:H})]})}),((xe=u.config)==null?void 0:xe.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:((le=u.config)==null?void 0:le.trendlineWindow)||30,onChange:Re=>{const _e=parseInt(Re.target.value)||30;te(_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:((Me=u.config)==null?void 0:Me.trendlineGranularity)||"day",onValueChange:ie,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},ua=()=>{if(!ra)return null;const U=we;return e.jsxs(e.Fragment,{children:[U&&y&&!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:W=>{E(n,W)},disabled:U,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(ps,{value:$.format,onChange:W=>M(n,W),showTitle:!1})]}),e.jsx(t.Collapsible,{open:me,onOpenChange:se,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:[!me&&e.jsx("span",{className:"mr-2",children:J?t.toTitleCase(Y.replace(/_/g," ")):"None"}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 transition-transform",me?"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:J?Y:"none",onValueChange:W=>L(n,W),disabled:!pe.supported&&!J,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:fe,children:"Running Total"}),e.jsx(t.SelectItem,{value:"moving_average",disabled:fe,children:"Moving Average"}),e.jsx(t.SelectItem,{value:"previous_period_delta",disabled:fe,children:"Previous Period Delta"}),e.jsx(t.SelectItem,{value:"percent_of_total",disabled:fe,children:"Percent of Total"})]})]}),!pe.supported&&!J&&e.jsx("div",{className:"text-xs text-muted-foreground",children:pe.reason}),fe&&!J&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"Disable comparison to enable metric transforms."})]}),J&&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:Pe,onValueChange:W=>k(n,W),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:Fe.filter(W=>!!W.id).map(W=>e.jsx(t.SelectItem,{value:W.id,className:"text-xs",children:W.label||W.name},W.id))})]}),!Pe&&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:Qe,onValueChange:W=>O(n,W),disabled:!Pe,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:W=>V(n,Number(W.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:Yn,onChange:W=>B(n,Number(W.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:Xn,onValueChange:W=>_(n,W),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:vs,onValueChange:W=>G(n,W),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:Zn,onValueChange:W=>q(n,W),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"&&vs==="partition_total")&&bs.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:bs.map(W=>{const xe=!!W.id&&Jt.has(W.id);return e.jsxs("button",{type:"button",onClick:()=>W.id&&z(n,W.id),className:t.cn("flex h-7 w-full items-center justify-between rounded border px-2 text-xs",xe?"border-primary bg-primary/5 text-primary":"border-border text-muted-foreground"),children:[e.jsx("span",{children:W.label||W.name}),xe?e.jsx(t.Check,{className:"h-3 w-3"}):null]},W.id)})})]})]})]})]})}),ys&&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:$.comparisonType||"none",disabled:J,onValueChange:W=>j(n,W),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 W=!At||!Nt,xe=At?Nt?void 0:"Add a date filter to enable":"Add a date groupBy to enable",le=(Me,Re)=>e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.SelectItem,{value:Me,disabled:W,title:xe,children:Re})}),W&&xe&&e.jsx(t.TooltipContent,{side:"right",children:xe})]})});return e.jsxs(e.Fragment,{children:[le("previous_period","Previous Period"),le("same_period_last_year","Same Period Last Year"),le("start_vs_end","Start vs End")]})})(),Qt&&e.jsx(t.SelectItem,{value:"target",children:"Target"})]})]})]}),ys&&$.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:$.targetValue!==void 0&&$.targetValue!==null?String($.targetValue):"",onChange:W=>{const xe=W.target.value;if(xe===""){oe(n,void 0);return}const le=Number(xe);oe(n,Number.isFinite(le)?le: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"}),(Ne==null?void 0:Ne.conditions)&&Ne.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:Ne.conditions.map(W=>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:()=>{Z(W),be(!0)},children:[e.jsxs("span",{className:"font-medium",children:[W.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(W.value)?W.value.length===1?String(W.value[0]):W.value.length<=2?W.value.join(", "):`${W.value.slice(0,2).join(", ")} +${W.value.length-2}`:String(W.value)})}),Array.isArray(W.value)&&W.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 (",W.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:W.value.map((xe,le)=>e.jsx("div",{children:String(xe)},le))})]})})]})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:xe=>{var Me;xe.stopPropagation();const le=Ne.conditions.filter(Re=>Re.id!==W.id);if(le.length>0){const Re={...Ne,conditions:le};It(Re)}else if(Oe(void 0),a==="metrics"){const Re={...s,parameters:{...s.parameters,filters:void 0}},_e=[...((Me=u.config)==null?void 0:Me.metricColumns)||[]];_e[n]=Re,t.useEditorStore.getState().actions.updateCardConfig(u.id,{metricColumns:_e})}},children:e.jsx(t.X,{className:"h-3 w-3"})})]},W.id))}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{Z(null),be(!0)},children:[e.jsx(t.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(Lo,{column:s}),i&&e.jsxs(e.Fragment,{children:[e.jsx(Eo,{aliasTemplate:Q,onAliasTemplateChange:We}),e.jsx(Io,{valueAliases:ue,onValueAliasesChange:ne})]})]})};Ne!=null&&Ne.conditions&&Ne.conditions.length>0;const ma=a!=="sortBy";return e.jsxs(e.Fragment,{children:[e.jsxs(t.Popover,{open:de,onOpenChange:he,children:[e.jsxs("div",{ref:m,style:Kt,className:t.cn("group flex h-7 w-full items-center gap-1.5 rounded-[5px] border bg-background px-1.5 transition-colors",de?"border-foreground/30 bg-muted/40":"border-border hover:bg-muted/40",x&&"z-50 scale-95 opacity-50"),children:[e.jsx("button",{type:"button",...d,...o,className:"inline-flex shrink-0 cursor-grab items-center text-muted-foreground transition-colors hover:text-foreground active:cursor-grabbing","aria-label":`Drag ${t.getMetricDisplayLabel(s)}`,onClick:U=>{U.stopPropagation()},children:e.jsx(t.GripVertical,{className:"h-3 w-3"})}),e.jsx(t.TypeGlyph,{dataType:kt,calculated:!!Ce}),e.jsx(fs,{className:"block w-0 min-w-0 flex-1 text-[12px] text-foreground",children:t.getMetricDisplayLabel(s)}),a==="metrics"&&((tn=Ne==null?void 0:Ne.conditions)==null?void 0:tn.length)&&!de&&e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex shrink-0 items-center gap-1 rounded-[3px] bg-primary/10 px-1 text-[10px] tabular-nums text-primary/90",children:[e.jsx(t.Filter,{className:"h-2.5 w-2.5"}),e.jsx("span",{children:Ne.conditions.length})]})}),e.jsx(t.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:Ne.conditions.map(U=>e.jsxs("div",{children:[U.field.label,":"," ",Array.isArray(U.value)?`${U.value.length} values`:String(U.value)]},U.id))})})]})}),a==="sortBy"&&e.jsx("button",{type:"button","aria-label":r==="asc"?"Switch to descending":"Switch to ascending",className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",onClick:U=>{U.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"})}),ma&&e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":"Field configuration",className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground data-[state=open]:bg-muted data-[state=open]:text-foreground",onClick:U=>U.stopPropagation(),children:e.jsx(t.Ellipsis,{className:"h-3 w-3"})})}),e.jsx("button",{type:"button","aria-label":"Remove",className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground opacity-0 transition-opacity hover:bg-muted hover:text-foreground group-hover:opacity-100 group-focus-within:opacity-100 [@media(hover:none)]:opacity-100",onClick:U=>{U.stopPropagation(),vt()},children:e.jsx(t.X,{className:"h-3 w-3"})})]}),e.jsx(t.PopoverContent,{align:"start",sideOffset:6,className:"w-[320px] p-0",children:e.jsxs("div",{className:"max-h-[480px] space-y-3 overflow-y-auto p-3",children:[la(),ia(),oa(),l==="kpi"&&Ns(),ca(),da(),ua()]})})]}),je&&e.jsx(Jn,{open:je,onOpenChange:U=>{be(U),U||Z(null)},availableFields:P,existingFilters:Ne,editingCondition:ge,onSave:U=>{var W;if(U)It(U);else if(Oe(void 0),a==="metrics"){const xe={...s,parameters:{...s.parameters,filters:void 0}},le=[...((W=u.config)==null?void 0:W.metricColumns)||[]];le[n]=xe,t.useEditorStore.getState().actions.updateCardConfig(u.id,{metricColumns:le})}Z(null)}}),ye&&a==="metrics"&&we&&e.jsx(t.CalculatedFieldEditor,{open:ye,onOpenChange:X,availableFields:I,existingField:Ze,existingFieldScope:ct,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:U=>{var Ft;if(U.role!=="metric")return;const{card:W,frame:xe,actions:le}=t.useEditorStore.getState(),Me=((Ft=W.config)==null?void 0:Ft.metricColumns)||[],Re=xe.calculatedFields||[],{nextActiveFields:_e,nextStoredFields:Ct,nextSharedFields:Lt}=t.saveCalculatedFieldToCardScope({activeFields:Me,storedFields:W.calculatedFields||[],sharedFields:Re,updatedField:U,editingField:Ze,previousScope:ct});_e&&le.updateCardConfig(u.id,{metricColumns:_e}),le.updateCard(u.id,{calculatedFields:Ct}),Lt!==Re&&t.commitSharedCalculatedFields({nextSharedFields:Lt,currentSharedFields:Re,isVisualEditing:v,selectedSheetId:b,updateFrame:le.updateFrame,updateSheetCalculatedFields:S})},onSaveToDashboard:U=>{var sn;if(U.role!=="metric")return;const{card:W,frame:xe,actions:le}=t.useEditorStore.getState(),Me=s,Re=((sn=W.config)==null?void 0:sn.metricColumns)||[],_e=xe.calculatedFields||[],{nextActiveFields:Ct,nextStoredFields:Lt,nextSharedFields:Ft}=t.saveCalculatedFieldToSharedScope({activeFields:Re,storedFields:W.calculatedFields||[],sharedFields:_e,updatedField:{...U,id:Me.id,aliasTemplate:Me.aliasTemplate,valueAliases:Me.valueAliases,parameters:Me.parameters,customFormat:Me.customFormat},editingField:Ze,previousScope:ct});t.commitSharedCalculatedFields({nextSharedFields:Ft,currentSharedFields:_e,isVisualEditing:v,selectedSheetId:b,updateFrame:le.updateFrame,updateSheetCalculatedFields:S}),Ct&&le.updateCardConfig(u.id,{metricColumns:Ct}),le.updateCard(u.id,{calculatedFields:Lt})},cardId:u.id})]})}function Po({concept:s}){const{title:a,description:n}=Bo[s];return e.jsxs(t.HoverCard,{openDelay:150,closeDelay:50,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":`What does ${a} mean?`,className:"inline-flex h-3 w-3 shrink-0 items-center justify-center text-muted-foreground/70 transition-colors hover:text-foreground",children:e.jsx(t.CircleHelp,{className:"h-3 w-3"})})}),e.jsxs(t.HoverCardContent,{side:"right",align:"start",sideOffset:8,className:"w-[260px] space-y-2 rounded-[6px] border border-border bg-popover p-3 shadow-[0_4px_16px_rgba(0,0,0,0.08)]",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-[12px] font-semibold text-foreground",children:a}),e.jsx("p",{className:"text-[11px] leading-[1.45] text-muted-foreground",children:n})]}),s!=="detailColumns"&&e.jsx(Vo,{highlight:s})]})]})}const Bo={groupBy:{title:"Rows",description:"Each unique value becomes a row. Use for the dimensions you want stacked vertically."},pivotBy:{title:"Pivot Columns",description:"Each unique value spreads across as a column, splitting your metrics horizontally."},metrics:{title:"Metrics",description:"The aggregated numbers (sum, count, avg…) that fill the cells of your chart or table."},detailColumns:{title:"Columns",description:"Raw column values with no aggregation — the underlying detail rows from the database."}};function Vo({highlight:s}){const a=s==="pivotBy",n=s==="groupBy",r=s==="metrics",c="bg-foreground/[0.06] font-medium text-foreground dark:bg-foreground/[0.12]";return e.jsx("div",{className:"overflow-hidden rounded-[5px] border border-border",children:e.jsxs("table",{className:"w-full text-[10px]",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border bg-muted/40",children:[e.jsx("th",{className:"px-1.5 py-1 text-left font-normal text-muted-foreground"}),["North","South","East"].map(i=>e.jsx("th",{className:t.cn("px-1.5 py-1 text-center font-normal text-muted-foreground",a&&c),children:i},i))]})}),e.jsx("tbody",{children:In.map((i,l)=>e.jsxs("tr",{className:t.cn(l!==In.length-1&&"border-b border-border/60"),children:[e.jsx("td",{className:t.cn("px-1.5 py-1 text-left text-muted-foreground",n&&c),children:i.label}),i.values.map((d,o)=>e.jsx("td",{className:t.cn("px-1.5 py-1 text-right font-mono tabular-nums text-muted-foreground",r&&c),children:d},o))]},i.label))})]})})}const In=[{label:"Electronics",values:["2,300","1,800","3,400"]},{label:"Clothing",values:["1,300","620","480"]}],zo={groupBy:zt,pivotBy:ds,metrics:Aa,detailColumns:t.Table2,sortBy:t.ArrowUpDown};function wt({zone:s,fields:a,label:n,placeholder:r,shouldShow:c,hasPivotColumns:i=!1,activeField:l=null}){const{isOver:d,setNodeRef:o}=t.useDroppable({id:s}),{updateSortByColumn:m}=t.useEditorActions(),h=t.useEditorStore(S=>S.card),f=t.useEditorStore(S=>S.card.type),x=a.length>0,u=N.useMemo(()=>!l||!d?!0:t.validateFieldForChartType(l,s,f).isValid,[l,d,s,f]),g=(S,I)=>{var C;!((C=h.config)!=null&&C.sortByColumns)||h.config.sortByColumns.findIndex(A=>A.id===S)===-1||m(h.id,S,{direction:I})};if(s==="sortBy"&&c===!1)return null;const v=s!=="sortBy"&&f!=="kpi",b=zo[s]||t.Plus;return e.jsxs("div",{className:"w-full",children:[e.jsx(t.Label,{className:"mb-1 block text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:n}),e.jsx("div",{ref:o,className:t.cn("rounded-[5px] transition-colors",{"border border-foreground/40 bg-muted/50":d&&u,"border border-destructive/40 bg-destructive/5":d&&!u,"border border-dashed border-border/50 bg-background":!d&&!x}),children:a.length===0?e.jsxs("div",{className:"flex h-9 items-center justify-center gap-1.5 text-[11px] text-muted-foreground/80",children:[e.jsx(b,{className:"h-3 w-3 shrink-0 text-muted-foreground/60"}),e.jsx("span",{children:r}),v&&e.jsx(Po,{concept:s})]}):e.jsx(t.SortableContext,{id:s,items:a.map(S=>S.id),strategy:t.verticalListSortingStrategy,children:e.jsx("div",{className:"space-y-1",children:a.map((S,I)=>{const C=S.direction;return e.jsx(Oo,{field:S,zone:s,index:I,sortDirection:C,onSortDirectionChange:A=>g(S.id,A),hasPivotColumns:i,cardType:f},S.id)})})})})]})}function _o({groupByFields:s,pivotByFields:a,metricsFields:n,sortByFields:r,detailFields:c,activeField:i}){var B,_,G;const[l,d]=N.useState(!1);t.useEditorStore(q=>{var H;return!!((H=q.card.customCardPreferences)!=null&&H.url)});const o=t.useEditorStore(q=>q.card),m=t.useEditorStore(q=>q.frame),h=t.findCustomVisualConfigCard(m,o),{manifest:f}=t.useCustomVisual(((B=h==null?void 0:h.customCardPreferences)==null?void 0:B.url)||""),x=(_=f==null?void 0:f.visuals)==null?void 0:_.find(q=>{var H;return q.name===((H=h==null?void 0:h.customCardPreferences)==null?void 0:H.componentName)}),u=t.resolveMultiInputType(h,x)==="multiple";u&&((G=h==null?void 0:h.customCardPreferences)!=null&&G.url);const g=t.getConfigSlotExpectedType(x==null?void 0:x.slots),v=t.useEditorStore(q=>q.actions.updateCardConfig),b=t.useEditorStore(q=>q.actions.updateCard),S=t.useEditorStore(q=>q.actions.updateFrame),I=t.useDashboardStore(q=>q.isVisualEditing),P=t.useDashboardStore(q=>q.selectedSheetId),C=t.useDashboardStore(q=>q.actions.updateSheetCalculatedFields),{scopedFields:A}=t.useScopedFields(),{userContext:y}=t.useCurrentUserInfo(),T=u&&(h==null?void 0:h.id)===o.id&&g?g:o==null?void 0:o.type,E=T==="detailTable",D=s.length>0||n.length>0||c.length>0,p=!E&&(T!=="kpi"||n.length<=2),R=!E,w=!E&&T!=="kpi",M=T!=="kpi"&&D,F=E,j="Drop sort fields here",L=(y==null?void 0:y.type)==="organization",k=["pie","doughnut","polar","funnel","aggregateTable","bubble","scatter"].includes(T),O=w&&!k,z=()=>T==="kpi"?{label:"Trend By",placeholder:"Drop trend field here"}:{label:"Rows",placeholder:"Drop dimensions here"},V=()=>T==="kpi"?{label:"Metric",placeholder:"Drop metric here"}:{label:"Metrics",placeholder:"Drop metrics here"};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between bg-background px-4 py-2",children:[e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-foreground/70",children:"Fields"}),D&&e.jsx("button",{type:"button","aria-label":"Reset all field selections",onClick:()=>{v(o.id,{groupByColumns:[],pivotByColumns:[],metricColumns:[],sortByColumns:[],detailColumns:[]})},className:"text-[11px] text-muted-foreground transition-colors hover:text-foreground",children:"Reset"})]}),e.jsxs("div",{className:"space-y-3 px-4 pb-6 pt-3",children:[p&&e.jsx(wt,{zone:"groupBy",fields:s,label:z().label,placeholder:z().placeholder,activeField:i}),O&&e.jsx(wt,{zone:"pivotBy",fields:a,label:"Pivot Columns",placeholder:"Drop pivot fields here",activeField:i}),R&&e.jsx(wt,{zone:"metrics",fields:n,label:V().label,placeholder:V().placeholder,hasPivotColumns:a.length>0,activeField:i}),F&&e.jsx(wt,{zone:"detailColumns",fields:c,label:"Columns",placeholder:"Drop columns here"}),n.length>=1&&L&&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"]}),M&&e.jsx(wt,{zone:"sortBy",fields:r,label:"Sort By",placeholder:j,activeField:i})]}),e.jsx(t.CalculatedFieldEditor,{open:l,onOpenChange:d,availableFields:A,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:q=>{if(q.role!=="metric")return;const{nextStoredFields:H}=t.saveCalculatedFieldToCardScope({activeFields:n,storedFields:o.calculatedFields||[],sharedFields:m.calculatedFields||[],updatedField:q,previousScope:"card"});b(o.id,{calculatedFields:H})},onSaveToDashboard:q=>{if(q.role!=="metric")return;const H=m.calculatedFields||[],{nextSharedFields:te}=t.saveCalculatedFieldToSharedScope({activeFields:n,storedFields:o.calculatedFields||[],sharedFields:H,updatedField:q,previousScope:"dashboard"});t.commitSharedCalculatedFields({nextSharedFields:te,currentSharedFields:H,isVisualEditing:I,selectedSheetId:P,updateFrame:S,updateSheetCalculatedFields:C})},cardId:o.id})]})}function qo(){var g,v,b;const[s,a]=N.useState(!1),[n,r]=N.useState(!1),c=t.useEditorStore(S=>{var I;return!!((I=S.card.customCardPreferences)!=null&&I.url)}),i=t.useEditorStore(S=>S.card),l=t.useEditorStore(S=>S.frame),d=t.findCustomVisualConfigCard(l,i),{manifest:o}=t.useCustomVisual(((g=d==null?void 0:d.customCardPreferences)==null?void 0:g.url)||""),m=(v=o==null?void 0:o.visuals)==null?void 0:v.find(S=>{var I;return S.name===((I=d==null?void 0:d.customCardPreferences)==null?void 0:I.componentName)}),f=t.resolveMultiInputType(d,m)==="multiple"&&!!((b=d==null?void 0:d.customCardPreferences)!=null&&b.url),x=!c||f,u=c||f;return!x&&!u?null:e.jsxs("div",{className:"shrink-0 border-t border-border bg-background",children:[x&&s&&e.jsx("div",{className:"max-h-[40vh] overflow-y-auto border-b border-border px-4",children:e.jsx(t.Accordion,{type:"single",collapsible:!0,className:"w-full divide-y divide-border/60",children:e.jsx(Qn,{mode:"config"})})}),x&&e.jsxs("button",{type:"button",onClick:()=>a(S=>!S),className:"flex w-full items-center justify-between px-4 py-2.5 text-left transition-colors hover:bg-muted/50",children:[e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(t.Settings2,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-foreground/70",children:"Chart settings"})]}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 text-muted-foreground transition-transform",s&&"rotate-180"),strokeWidth:1.75})]}),u&&n&&e.jsx("div",{className:"max-h-[40vh] overflow-y-auto border-b border-t border-border px-4",children:e.jsx(Kn,{})}),u&&e.jsxs("button",{type:"button",onClick:()=>r(S=>!S),className:t.cn("flex w-full items-center justify-between px-4 py-2.5 text-left transition-colors hover:bg-muted/50",x&&"border-t border-border"),children:[e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Dn,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-foreground/70",children:"Component settings"})]}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 text-muted-foreground transition-transform",n&&"rotate-180"),strokeWidth:1.75})]})]})}function $o({onEditJoins:s}){const a=t.useEditorStore(d=>d.card),{autoJoinMetadata:n}=t.useEditorCardQuery(a);if(!(n!=null&&n.autoResolved))return null;const{resolvedJoinPlan:r}=n,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 x,u,g,v;const m=`${(x=o.source)==null?void 0:x.entityName}.${(u=o.source)==null?void 0:u.name}`,h=`${(g=o.target)==null?void 0:g.entityName}.${(v=o.target)==null?void 0:v.name}`,f=o.operator||"=";return`${m} ${f} ${h}`}).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,m)=>({id:m,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(Pa,{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 m=l(d),h=Array.isArray(m);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:h?m.map(f=>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:f.condition}),f.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",f.operator,")"]})]},f.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:m})})})]},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"})})]})})}function Ko({selectedChart:s,onChartChange:a,isVisible:n=!0,onToggleVisibility:r,groupByFields:c,pivotByFields:i,metricsFields:l,sortByFields:d,detailFields:o,activeField:m}){var T,E;const[h,f]=N.useState(!1),x=t.useEditorStore(D=>D.card),u=t.useEditorStore(D=>D.editorContext),g=t.useEditorStore(D=>D.actions.updateCardConfig),v=(u==null?void 0:u.type)==="documentSection",{autoJoinMetadata:b}=t.useEditorCardQuery(x),S=((T=x==null?void 0:x.config)==null?void 0:T.joinPlan)||(b!=null&&b.autoResolved?b.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),I=((E=x==null?void 0:x.dataSource)==null?void 0:E.selectedEntities)||[],P=D=>{g(x.id,{...x==null?void 0:x.config,joinPlan:D}),f(!1)},C=()=>{g(x.id,{...x==null?void 0:x.config,joinPlan:void 0}),f(!1)},A=()=>{f(!1)},y=()=>{f(!0)};return n?e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[325px] min-w-[325px] shrink-0 flex-col overflow-hidden border-r border-border bg-background transition-all duration-300 ease-in-out",children:[!v&&e.jsxs("div",{className:"flex items-start",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(wo,{selectedChart:s,onChartChange:a})}),r&&e.jsx("div",{className:"px-2 pt-4",children:e.jsx(t.IconButton,{tooltip:"Hide chart configuration","aria-label":"Hide chart configuration",onClick:r,className:"h-7 w-7 rounded-[5px] p-0 text-muted-foreground hover:text-foreground",children:e.jsx(t.ChevronLeft,{className:"h-4 w-4",strokeWidth:1.75})})})]}),e.jsxs(t.ScrollArea,{className:"min-h-0 w-full flex-1 basis-0 border-t border-border [&>[data-radix-scroll-area-viewport]]:overscroll-none [&>[data-radix-scroll-area-viewport]>div]:!block [&>[data-radix-scroll-area-viewport]>div]:w-full",children:[e.jsx("div",{className:"px-4 pt-4 empty:hidden",children:e.jsx($o,{onEditJoins:y})}),e.jsx(_o,{groupByFields:c,pivotByFields:i,metricsFields:l,sortByFields:d,detailFields:o,activeField:m})]}),e.jsx(qo,{}),e.jsx(Fn,{open:h,onOpenChange:f,joinPlan:S,availableDataSources:I,onSave:P,onCancel:A,onRemove:C,children:e.jsx("div",{})})]}):e.jsx("div",{"data-content":"Chart Configuration Panel (collapsed)",className:"flex w-9 shrink-0 flex-col items-center border-r border-border bg-background transition-all duration-300 ease-in-out",children:r&&e.jsx(t.IconButton,{tooltip:"Show chart configuration","aria-label":"Show chart configuration",onClick:r,className:"mt-3 h-7 w-7 rounded-[5px] p-0 text-muted-foreground hover:text-foreground",children:e.jsx(t.ChevronRight,{className:"h-4 w-4",strokeWidth:1.75})})})}function Go({initialFilters:s,availableFields:a}={}){const[n,r]=N.useState(s||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});t.useEditorStore(C=>C.card.dataSource);const{filterableFields:c,isLoading:i}=t.useFilterableFields(),l=a||c||[],d={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},o=C=>{const A=y=>{if(y.id===C){const T=l[0]||d,E=t.getDataType(T.dataType)==="date";return{...y,conditions:[...y.conditions,{id:`condition-${Date.now()}`,field:T,operator:E?"between":"=",value:E?[]:""}]}}return{...y,groups:y.groups.map(A)}};r(A(n))},m=C=>{const A=y=>{if(y.id===C){const T=l[0]||d,E=t.getDataType(T.dataType)==="date";return{...y,groups:[...y.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:T,operator:E?"between":"=",value:E?[]:""}],groups:[]}]}}return{...y,groups:y.groups.map(A)}};r(A(n))},h=(C,A)=>{const y=T=>T.id===C?{...T,conditions:T.conditions.filter(E=>E.id!==A)}:{...T,groups:T.groups.map(y)};r(y(n))},f=(C,A)=>{const y=T=>T.id===C?{...T,groups:T.groups.filter(E=>E.id!==A)}:{...T,groups:T.groups.map(y)};r(y(n))},x=(C,A,y,T)=>{if(y==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const E=D=>D.id===C?{...D,conditions:D.conditions.map(p=>p.id===A?{...p,[y]:T}:p)}:{...D,groups:D.groups.map(E)};r(E(n))},u=(C,A,y)=>{const T=E=>E.id===C?{...E,conditions:E.conditions.map(D=>D.id===A?{...D,...y}:D)}:{...E,groups:E.groups.map(T)};r(T(n))},g=(C,A)=>{const y=T=>T.id===C?{...T,logicalOperator:A}:{...T,groups:T.groups.map(y)};r(y(n))},v=(C,A)=>{const y=T=>T.id===C?{...T,negate:A}:{...T,groups:T.groups.map(y)};r(y(n))},b=(C,A,y)=>{const T=E=>E.id===C?{...E,conditions:t.arrayMove(E.conditions,A,y)}:{...E,groups:E.groups.map(T)};r(T(n))},S=(C,A,y)=>{const T=E=>E.id===C?{...E,groups:t.arrayMove(E.groups,A,y)}:{...E,groups:E.groups.map(T)};r(T(n))},I=C=>{if(!C||C.conditions.length===0&&C.groups.length===0)return"-- No filters defined";const A=T=>{let E="";typeof T.field=="object"?E=T.field.entityName?`${T.field.entityName}.${T.field.name}`:T.field.name:E=String(T.field);const D=T.operator;let p=T.value;if(T.field.dataType==="string"&&!["in","not in"].includes(T.operator))typeof p=="string"?p=`'${p}'`:Array.isArray(p)&&(p=`'${p.join(", ")}'`);else if(T.field.dataType==="date"||T.field.dataType==="datetime"||T.field.dataType==="timestamp")if(T.operator==="between"&&Array.isArray(p)&&p.length===2){const R=p[0]?`'${p[0]}'`:"NULL",w=p[1]?`'${p[1]}'`:"NULL";return`${E} BETWEEN ${R} AND ${w}`}else if((T.operator==="in"||T.operator==="not in")&&Array.isArray(p)){const R=p.map(w=>w?`'${w}'`:"NULL").join(", ");return`${E} ${D} (${R})`}else typeof p=="string"||p instanceof Date?p=`'${p}'`:Array.isArray(p)&&p.length>0&&(p=`'${p[0]}'`);else if(["in","not in"].includes(T.operator)){let R=[];Array.isArray(p)?R=p.map(w=>typeof w=="string"?`'${w}'`:String(w)):typeof p=="string"?R=p.split(",").map(w=>{const M=w.trim();return T.field.dataType==="string"?`'${M}'`:M}):typeof p=="number"&&(R=[String(p)]),p=`(${R.join(", ")})`}switch(D){case"contains":return typeof p=="string"?`${E} LIKE '%${p.replace(/'/g,"")}'`:`${E} LIKE '%${String(p)}'`;case"startsWith":return typeof p=="string"?`${E} LIKE '${p.replace(/'/g,"")}%'`:`${E} LIKE '${String(p)}%'`;case"endsWith":return typeof p=="string"?`${E} LIKE '%${p.replace(/'/g,"")}'`:`${E} LIKE '%${String(p)}'`;case"isNull":return`${E} IS NULL`;case"isNotNull":return`${E} IS NOT NULL`;default:return`${E} ${D} ${p}`}},y=T=>{const E=T.conditions.map(A),D=T.groups.map(M=>y(M)),p=[...E,...D].filter(Boolean);if(p.length===0)return"";const R=p.join(` ${T.logicalOperator} `),w=p.length>1?`(${R})`:R;return T.negate?`NOT ${w}`:w};return y(C)},P=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:l,isLoading:i,addCondition:o,addGroup:m,removeCondition:h,removeGroup:f,updateCondition:x,updateConditionFields:u,updateGroupOperator:g,updateGroupNegate:v,reorderConditions:b,reorderGroups:S,generateSQLPreview:I,hasAnyFilters:P}}function Uo({children:s,className:a,delayDuration:n}){return e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:n,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:t.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:s})}),e.jsx(t.TooltipContent,{children:s})]})})}const Ho=s=>{if(s.qualifiedEntityName){const a=s.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function Qo({value:s,onValueChange:a,availableFields:n,placeholder:r="Select field",className:c="w-64"}){const[i,l]=N.useState(!1),d=N.useMemo(()=>{const o={};return n.forEach(m=>{const h=Ho(m);o[h]||(o[h]={}),o[h][m.entityId]||(o[h][m.entityId]=[]),o[h][m.entityId].push(m)}),o},[n]);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(Uo,{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,m])=>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(m).map(([h,f])=>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(f[0].entityType,{size:"h-3 w-3"}),e.jsx("span",{children:f[0].entityName})]}),f.map((x,u)=>e.jsxs(t.CommandItem,{value:x.id,onSelect:()=>{a(x),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)===x.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:x.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:x.description&&e.jsx("span",{children:x.description})})]})]},x.id+u))]},`${o}-${h}`))},o))})]})})]})}function gs(s){var v;const a=t.useEditorStore(b=>b.card),{authToken:n,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"},m={joinPlan:i,groupByColumns:[l],metricColumns:[d],sortByColumns:[o]},h=((v=a.dataSource)==null?void 0:v.connectionId)||a.connectionId,{data:f,isPending:x,error:u}=t.useQuery({queryKey:["filterValues",s.entityId,s.name,s.qualifiedEntityName],queryFn:async()=>{try{return await t.postRequestRegular(`${r.apiServiceUrl}/v1/query`,(n==null?void 0:n.accessToken)||"",{connection_id:h,cardConfig:m,cardDataSource:a.dataSource})}catch(b){console.log(s),console.error("error",b)}},enabled:!!h,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((f==null?void 0:f.records)||[]).map(b=>({label:b.value||"BLANK",value:b.value||"BLANK",count:(b==null?void 0:b.count)||0})),isPending:x,error:u}}function Jo({field:s,selected:a,onChange:n,placeholder:r="Select items...",className:c}){const[i,l]=Pt.useState(!1),{filterValues:d}=gs(s),o=h=>{n(a.filter(f=>f!==h))},m=h=>{a.includes(h)?n(a.filter(f=>f!==h)):n([...a,h])};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:a.length>0?a.map(h=>{const f=d.find(x=>x.value===h);return e.jsxs(t.Badge,{variant:"secondary",className:"text-xs",children:[f==null?void 0:f.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:x=>{x.key==="Enter"&&o(h)},onMouseDown:x=>{x.preventDefault(),x.stopPropagation()},onClick:x=>{x.stopPropagation(),o(h)},children:e.jsx(t.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},h)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(t.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No results found."}),e.jsx(t.CommandGroup,{children:d.map((h,f)=>e.jsxs(t.CommandItem,{onSelect:()=>m(h.value),children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",a.includes(h.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:h.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:h.count})]})]},h.value+f))})]})]})})]})})}function Wo({field:s,value:a,onChange:n,placeholder:r="Select value...",className:c}){const{filterValues:i,isPending:l,error:d}=gs(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:a,onValueChange:n,children:[e.jsx(t.SelectTrigger,{className:c||"flex-1",children:e.jsx(t.SelectValue,{placeholder:r,children:a})}),e.jsx(t.SelectContent,{children:i.map((o,m)=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:o.value,children:o.label},o.value+m))})]})}function Yo({value:s,operator:a,onChange:n,className:r}){var u,g,v;const{tokenProps:c}=t.useSemaphorContext(),i=((g=(u=c==null?void 0:c.params)==null?void 0:u.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=a==="between"||a==="not between",o=N.useMemo(()=>{if(!(!s||!d)&&Array.isArray(s)&&s.length===2){const b=s[0]?new Date(s[0]):void 0,S=s[1]?new Date(s[1]):void 0;if(b&&S)return{from:b,to:S}}},[s,d]),m=N.useMemo(()=>{if(!s||d)return;const b=Array.isArray(s)?s[0]:s;if(!b)return;const S=new Date(b);if(!isNaN(S.getTime()))return S},[s,d]),h=b=>a==="<="||a===">"?t.endOfDayInTimezone(b,l):t.startOfDayInTimezone(b,l),f=b=>{if(!b){n([]);return}if(b.from&&b.to){n([b.from.toISOString(),b.to.toISOString()]);return}n([])},x=b=>{if(!b){n("");return}const S=h(b);n(S.toISOString())};return e.jsx(t.DateRangePicker,{value:d?o:void 0,selectionMode:d?"range":"single",singleValue:d?void 0:m,onChange:f,onSingleChange:x,timezone:i,showRelativeTab:d,className:r,placeholder:"Select date..."})}const Xo=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Zo=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],ei=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],ti=["=","!=","isNull","isNotNull"],si=["between","=","!=","<","<=",">",">=","isNull","isNotNull"],ni={"=":"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 kn(s){return ni[s]||t.titleCase(s)}function ai(s){switch(s){case"string":return Zo;case"number":return ei;case"boolean":return ti;case"date":return si;default:return Xo}}function Wn({condition:s,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:c,onRemoveCondition:i,onUpdateGroupOperator:l,availableFields:d,updateConditionFields:o}){const{attributes:m,listeners:h,setNodeRef:f,transform:x,transition:u,isDragging:g}=t.useSortable({id:s.id}),{isPending:v,error:b}=gs(s.field),S={transform:t.CSS.Transform.toString(x),transition:u};return e.jsxs("div",{ref:f,style:S,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${g?"z-50 opacity-50":""}`,children:[e.jsx("div",{...m,...h,className:"cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(t.Select,{value:r,onValueChange:I=>l(n,I),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"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(Qo,{value:s.field,onValueChange:I=>{const P=I,C=t.getDataType(P.dataType)==="date";o(n,s.id,{field:P,value:"",operator:C?"between":"="})},availableFields:d,placeholder:"Select field",className:"w-64"}),e.jsxs(t.Select,{value:s.operator,onValueChange:I=>{I==="in"||I==="not in"?o(n,s.id,{operator:I,value:[]}):I==="isNull"||I==="isNotNull"?o(n,s.id,{operator:I,value:null}):I==="between"||I==="not between"?o(n,s.id,{operator:I,value:[]}):o(n,s.id,{operator:I,value:""})},children:[e.jsx(t.SelectTrigger,{className:"w-32",children:e.jsx(t.SelectValue,{children:s.operator?kn(s.operator):""})}),e.jsx(t.SelectContent,{children:ai(t.getDataType(s.field.dataType)).map(I=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:I,children:kn(I)},I))})]}),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(Jo,{field:s.field,selected:Array.isArray(s.value)&&s.value.every(I=>typeof I=="string")?s.value:[],onChange:I=>o(n,s.id,{value:I}),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:I=>o(n,s.id,{value:I.target.value}),className:"flex-1",placeholder:s.operator.charAt(0).toUpperCase()+s.operator.slice(1)+"..."}):e.jsx(Wo,{field:s.field,value:typeof s.value=="string"?s.value:"",onChange:I=>o(n,s.id,{value:I}),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:I=>o(n,s.id,{value:I==="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(Yo,{value:s.value,operator:s.operator,onChange:I=>o(n,s.id,{value:I}),className:"flex-1"}):e.jsx(t.Input,{value:typeof s.value=="string"||typeof s.value=="number"?s.value:"",onChange:I=>c(n,s.id,"value",I.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(n,s.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]})}function ri({group:s,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:c,onRemoveGroup:i,onUpdateCondition:l,onUpdateField:d,onRemoveCondition:o,onReorderConditions:m,onReorderGroups:h,onAddCondition:f,onAddGroup:x,availableFields:u,renderFilterGroup:g,updateConditionFields:v}){const{attributes:b,listeners:S,setNodeRef:I,transform:P,transition:C,isDragging:A}=t.useSortable({id:s.id}),y={transform:t.CSS.Transform.toString(P),transition:C},T=D=>{const{active:p,over:R}=D;if(R&&p.id!==R.id){const w=s.conditions.findIndex(F=>F.id===p.id),M=s.conditions.findIndex(F=>F.id===R.id);w!==-1&&M!==-1&&m(s.id,w,M)}},E=D=>{const{active:p,over:R}=D;if(R&&p.id!==R.id&&n){const w=s.groups.findIndex(F=>F.id===p.id),M=s.groups.findIndex(F=>F.id===R.id);w!==-1&&M!==-1&&h(n,w,M)}};return e.jsxs("div",{ref:I,style:y,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${A?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...b,...S,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:D=>r(s.id,D),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:()=>n&&i(n,s.id),children:e.jsx(t.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>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:T,children:e.jsx(t.SortableContext,{items:s.conditions.map(D=>D.id),strategy:t.verticalListSortingStrategy,children:s.conditions.map((D,p)=>e.jsx(Wn,{condition:D,index:p,groupId:s.id,groupLogicalOperator:s.logicalOperator,onUpdateCondition:l,onUpdateField:d,onRemoveCondition:o,onUpdateGroupOperator:r,availableFields:u,updateConditionFields:v},D.id))})}),e.jsx(t.DndContext,{sensors:t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),collisionDetection:t.closestCenter,onDragEnd:E,children:e.jsx(t.SortableContext,{items:s.groups.map(D=>D.id),strategy:t.verticalListSortingStrategy,children:s.groups.map(D=>g(D,a+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:()=>f(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:()=>x(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function li({filters:s,availableFields:a,onSave:n,onClearAll:r,onCancel:c}){const{currentFilters:i,availableFields:l,isLoading:d,addCondition:o,addGroup:m,removeCondition:h,removeGroup:f,updateCondition:x,updateConditionFields:u,updateGroupOperator:g,updateGroupNegate:v,reorderConditions:b,reorderGroups:S,generateSQLPreview:I,hasAnyFilters:P,setCurrentFilters:C}=Go({initialFilters:s,availableFields:a}),A=t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),[y,T]=N.useState(!1),E=(R,w,M)=>{const F=j=>j.id===R?{...j,conditions:j.conditions.map(L=>L.id===w?{...L,field:M,dataType:M.dataType}:L)}:{...j,groups:j.groups.map(F)};C(F(i))},D=(R,w=0,M)=>w===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(t.DndContext,{sensors:A,collisionDetection:t.closestCenter,onDragEnd:F=>{const{active:j,over:L}=F;if(L&&j.id!==L.id){const k=R.conditions.findIndex(z=>z.id===j.id),O=R.conditions.findIndex(z=>z.id===L.id);k!==-1&&O!==-1&&b(R.id,k,O)}},children:e.jsx(t.SortableContext,{items:R.conditions.map(F=>F.id),strategy:t.verticalListSortingStrategy,children:R.conditions.map((F,j)=>e.jsx(Wn,{condition:F,index:j,groupId:R.id,groupLogicalOperator:R.logicalOperator,onUpdateCondition:x,onUpdateField:E,onRemoveCondition:h,onUpdateGroupOperator:g,availableFields:l,updateConditionFields:u},F.id))})}),e.jsx(t.DndContext,{sensors:A,collisionDetection:t.closestCenter,onDragEnd:F=>{const{active:j,over:L}=F;if(L&&j.id!==L.id){const k=R.groups.findIndex(z=>z.id===j.id),O=R.groups.findIndex(z=>z.id===L.id);k!==-1&&O!==-1&&S(R.id,k,O)}},children:e.jsx(t.SortableContext,{items:R.groups.map(F=>F.id),strategy:t.verticalListSortingStrategy,children:R.groups.map(F=>D(F,w+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"]}),y&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>m(R.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},R.id):e.jsx(ri,{group:R,depth:w,parentGroupId:M,onUpdateGroupOperator:g,onUpdateGroupNegate:v,onRemoveGroup:f,onUpdateCondition:x,onUpdateField:E,onRemoveCondition:h,onReorderConditions:b,onReorderGroups:S,onAddCondition:o,onAddGroup:m,availableFields:l,renderFilterGroup:D,updateConditionFields:u},R.id),p=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..."})]}):D(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:y,onCheckedChange:R=>T(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)"})]})}),P&&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:I(i)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(t.Button,{size:"sm",variant:"outline",onClick:c,children:"Cancel"}),p>0&&e.jsx(t.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(t.Button,{size:"sm",onClick:()=>n(P?i:null),children:"Apply Filters"})]})]})}function oi({cardId:s,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:c,isOpen:i,onOpenChange:l}){const d=m=>{n(s,m),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:m=>{m.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(li,{filters:a,availableFields:c,onSave:d,onCancel:()=>l(!1),onClearAll:o})]})]})}function ii({activeCardId:s,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var I,P;const[c,i]=N.useState(null),l=t.useEditorStore(C=>C.card),d=t.useEditorStore(C=>C.actions.updateCardConfig),o=t.useEditorStore(C=>C.actions.setCardPreferences),m=(I=l==null?void 0:l.config)==null?void 0:I.joinPlan,h=N.useCallback(C=>C.entityName===t.CALCULATED_FIELD_ENTITY_MARKER||C.entityName==="calculated_fields"||C.qualifiedEntityName==="calculated_fields",[]),f=(P=l==null?void 0:l.dataSource)==null?void 0:P.semanticDomainId,{data:x}=t.useJoinabilityMap(f),u=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy"),...n("detailColumns")],g=N.useCallback(C=>C.startsWith("card-source-")?"source":C.startsWith("card-")?null:C.startsWith("source-")||a.find(A=>A.id===C)?"source":n("groupBy").find(A=>A.id===C)?"groupBy":n("metrics").find(A=>A.id===C)?"metrics":n("pivotBy").find(A=>A.id===C)?"pivotBy":n("sortBy").find(A=>A.id===C)?"sortBy":n("detailColumns").find(A=>A.id===C)?"detailColumns":null,[a,n]),v=N.useCallback(C=>{i(C.active.id)},[]),b=N.useCallback(C=>{var R;const{active:A,over:y}=C;if(!y||!s){i(null);return}const T=A.id,E=y.id,D=g(T),p=g(E)||E;if(p==="sortBy"){if(D==="source"){const w=a.find(F=>F.id===T);if(!w){i(null);return}if(!(n("groupBy").some(F=>F.name===w.name&&F.qualifiedEntityName===w.qualifiedEntityName)||n("metrics").some(F=>F.name===w.name&&F.qualifiedEntityName===w.qualifiedEntityName)||n("detailColumns").some(F=>F.name===w.name&&F.qualifiedEntityName===w.qualifiedEntityName))){i(null);return}}else if(D==="pivotBy"){i(null);return}else if(D!=="groupBy"&&D!=="metrics"&&D!=="sortBy"&&D!=="detailColumns"){i(null);return}}if(D==="source"&&p==="sortBy"){const w=[...a].find(L=>L.id===T);if(!w){i(null);return}const M=n("sortBy");if(t.fieldAlreadyExists(w,M)){i(null);return}const F=t.validateFieldForChartType(w,"sortBy",l.type);if(!F.isValid){t.ue.error("Invalid Field Type",{description:F.reason,position:"top-center",duration:3e3}),i(null);return}const j=t.getNewField(w,"sortBy",M);i(null),r("sortBy",[...M,j]);return}if(D==="source"&&p!=="source"&&p!=="sortBy"){const w=[...a].find(z=>z.id===T);if(!w){i(null);return}const M=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy"),...n("detailColumns")],F=M.filter(z=>!h(z));if(F.length>0){const z=F[0].qualifiedEntityName;if(!z){i(null);return}if(z!==w.qualifiedEntityName&&!h(w)&&w.qualifiedEntityName)if(f&&(x!=null&&x.joinabilityMap)){if(t.calculateFieldState(w,{joinabilityMap:x.joinabilityMap,selectedFields:M,baseEntityName:(R=m==null?void 0:m.baseEntity)==null?void 0:R.name}).state==="unreachable"){t.showJoinRequiredNotification(),i(null);return}}else{if(!m){t.showJoinRequiredNotification(),i(null);return}if(!t.areEntitiesJoined(z,w.qualifiedEntityName,m)){t.showJoinRequiredNotification(),i(null);return}}}const j=n(p);if(t.fieldAlreadyExists(w,j)){i(null);return}const L=t.validateFieldForChartType(w,p,l.type);if(!L.isValid){t.ue.error("Invalid Field Type",{description:L.reason,position:"top-center",duration:3e3}),i(null);return}const k=t.getNewField(w,p,j),O=[...j,k];if(i(null),r(p,O),p==="metrics"&&s){const z=t.seedSemanticMetricFormatDefaults(l,k,l.preferences);z&&o(z),t.cleanupKpiMetricComparisonMode(l.type,l.config,d,s,O)}return}if(D&&p&&D!=="source"&&p!=="source"&&D!==p){const w=n(D),M=n(p),F=w.find(z=>z.id===T);if(!F){i(null);return}const j=t.validateFieldForChartType(F,p,l.type);if(!j.isValid){t.ue.error("Invalid Field Type",{description:j.reason,position:"top-center",duration:3e3}),i(null);return}const L=t.getNewField(F,p,M);if(i(null),p==="sortBy"){t.fieldAlreadyExists(F,M)||r(p,[...M,L]);return}const k=w.filter(z=>z.id!==T),O=[...M,L];if(r(D,k),r(p,O),p==="metrics"&&s){const z=t.seedSemanticMetricFormatDefaults(l,L,l.preferences);z&&o(z),t.cleanupKpiMetricComparisonMode(l.type,l.config,d,s,O)}return}if(D&&p&&D===p&&D!=="source"){const w=n(D),M=w.findIndex(j=>j.id===T),F=w.findIndex(j=>j.id===E);if(M!==F){const j=t.arrayMove(w,M,F);r(D,j)}}i(null)},[s,a,n,r,g,m,f,x,h,l,d,o]),S=c?u.find(C=>C.id===c):null;return{activeId:c,activeField:S,handleDragStart:v,handleDragEnd:b}}function ci({activeView:s,onViewChange:a,splitViewEnabled:n}){const r=t.useEditorStore(o=>o.card),{config:c}=N.useContext(t.SemaphorContext).tokenProps,i=(c==null?void 0:c.showInfoTab)!==!1,l=()=>n?!1:t.getVisualizationMode(r)==="dynamic"?!0:!["table","pivotTable","aggregateTable","detailTable"].includes(r.type),d=[{id:"chart",label:"Chart"}];return l()&&d.push({id:"table",label:"Results"}),r.type!=="kpi"&&i&&d.push({id:"info",label:"Info",icon:t.Info}),e.jsx(t.Tabs,{value:s,onValueChange:o=>a(o),children:e.jsx(t.TabsList,{variant:"underline",className:"gap-5 border-b-0",children:d.map(o=>{const m=o.icon;return e.jsxs(t.TabsTrigger,{value:o.id,className:"gap-1.5 px-0 text-[13px]",children:[m&&e.jsx(m,{className:"h-3 w-3",strokeWidth:1.75}),o.label]},o.id)})})})}const di=[{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 ui(){var o,m;const s=t.useEditorStore(h=>h.card),{updateRowLimit:a}=t.useEditorActions(),[n,r]=N.useState(!1),[c,i]=N.useState(""),l=h=>{if(h==="custom"){r(!0);return}r(!1),a(s.id,parseInt(h))},d=h=>{const f=h.target.value;i(f),f&&!isNaN(parseInt(f))&&a(s.id,parseInt(f))};return e.jsx("div",{className:"flex items-center gap-2",children:n?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:((m=(o=s.config)==null?void 0:o.rowLimit)==null?void 0:m.toString())||"100",onValueChange:l,children:[e.jsxs(t.SelectTrigger,{className:"mb-0.5 h-auto w-auto gap-1.5 border-none bg-transparent px-0.5 pb-2.5 pt-0 text-[13px] font-normal text-muted-foreground shadow-none transition-colors hover:text-foreground focus:ring-0 focus:ring-offset-0 [&>svg]:hidden",children:[e.jsx(t.Filter,{className:"h-3 w-3",strokeWidth:1.75}),e.jsx(t.SelectValue,{placeholder:"Select limit"})]}),e.jsx(t.SelectContent,{children:di.map(h=>e.jsx(t.SelectItem,{value:h.value,children:h.label},h.value))})]})})}function mi({card:s,queryData:a,isLoading:n,isFetching:r,pagination:c,onPaginationChange:i,onSortChange:l,sortState:d,splitViewEnabled:o,isDynamicInspectorOpen:m,onDynamicInspectorOpenChange:h}){const f=N.useMemo(()=>(a==null?void 0:a.records)||[],[a==null?void 0:a.records]),x=t.getVisualizationMode(s)==="dynamic",u=e.jsx(ot,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(qn,{fallbackPreview:e.jsx(ot,{}),records:f,title:s.title,isInspectorOpen:m,onInspectorOpenChange:h})});return x?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:u}),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 px-4 py-4",children:[(n||r)&&(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"})}),(a==null?void 0:a.records)&&e.jsx(t.TableVisual,{card:s,data:f,paginationMetadata:c,onPaginationChange:i,isLoading:n||r,onSortChange:l,sortState:d})]})})]}):u:!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:[(n||r)&&(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"})}),(a==null?void 0:a.records)&&e.jsx(t.TableVisual,{card:s,data:f,paginationMetadata:c,onPaginationChange:i,isLoading:n||r,onSortChange:l,sortState:d})]})})]})}function xi(s,a){const[n,r]=N.useState(()=>{const c=localStorage.getItem(s);return c?JSON.parse(c):a});return N.useEffect(()=>{localStorage.setItem(s,JSON.stringify(n))},[n,s]),[n,r]}const hi="semaphor-split-view-enabled";function pi(){return xi(hi,!0)}function fi({activeView:s,onViewChange:a,onFiltersClick:n,activeCard:r,columns:c}){var ye,X,ge;const i=t.useEditorStore(Z=>Z.card),l=t.useEditorStore(Z=>Z.editorContext),d=t.useEditorStore(Z=>Z.inlineFilterValuesMap[(r==null?void 0:r.id)||""]),o=t.useEditorStore(Z=>Z.actions.removeCardInlineFilterValue),m=t.useDashboardStore(Z=>Z.filterValues),h=t.useDashboardStore(Z=>Z.selectedSheetId),{updateCardConfig:f,setCard:x,updateCardInFrame:u,setShowAIDialog:g}=t.useEditorActions(),v=t.useEditorStore(Z=>Z.showAIDialog),b=t.useEditorStore(Z=>Z.isDevMode),S=t.useDashboardStore(Z=>Z.isVisualEditing),[I,P]=N.useState(!1),[C,A]=N.useState(!1),[y,T]=N.useState(!1),[E,D]=N.useState(null),{config:p}=N.useContext(t.SemaphorContext).tokenProps,R=(p==null?void 0:p.showInfoTab)!==!1,w=(p==null?void 0:p.showQueryDebugTools)!==!1,[M,F]=pi();t.useEditorStore(Z=>{var Te;return!!((Te=Z.card.customCardPreferences)!=null&&Te.url)});const L=t.getVisualizationMode(i)==="dynamic",k=(l==null?void 0:l.type)==="documentSection",{data:O,errorMessage:z,isLoading:V,isFetching:B,errorSql:_,pagination:G,refetch:q,comparisonMetadata:H,queryRequestPayload:te,resolvedPrimaryDateField:ie}=t.useEditorCardQuery(r),oe=N.useMemo(()=>(O==null?void 0:O.records)||[],[O==null?void 0:O.records]),[de,he]=N.useState(!1);N.useEffect(()=>{B||he(!1)},[B]);const me=()=>{const Z=!M;Z&&s==="table"&&a("chart"),F(Z)},se=(Z,Te)=>{const Le={...r,paginationConfig:{page:Z+1,pageSize:Te}};x(Le),u(Le)},je=Z=>{if(!i.config)return;const Te=t.sortStateToSortByColumns(Z,i.config.metricColumns,i.config.groupByColumns,i.config.detailColumns);f(i.id,{...i.config,sortByColumns:Te})},be=N.useMemo(()=>{var Z;return t.sortByColumnsToSortState((Z=i.config)==null?void 0:Z.sortByColumns)},[(ye=i.config)==null?void 0:ye.sortByColumns]);return e.jsx("div",{className:t.cn("relative flex w-0 grow flex-col",{"border-l":v&&S}),children:e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col",children:[e.jsxs("div",{className:"flex h-11 items-center gap-3 border-b border-border px-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[s==="chart"&&v&&!k&&!L&&e.jsx("div",{className:"w-[200px]",children:e.jsx(zn,{variant:b?"secondary":"ghost"})}),e.jsxs("div",{className:"flex h-11 items-end gap-5 self-stretch",children:[e.jsx(ci,{activeView:s,onViewChange:a,splitViewEnabled:M}),e.jsx(ui,{})]}),H&&i.type!=="table"&&e.jsx(t.ComparisonMetadataBadge,{metadata:H,variant:"compact"}),v&&e.jsx(Ae.EditorClearButton,{})]}),e.jsxs("div",{className:"flex grow items-center justify-end gap-1",children:[e.jsx(t.FilterInfo,{cardId:r.id,cardFilters:(X=r.config)==null?void 0:X.filters,cardFilterCount:t.getFilterCount(((ge=r.config)==null?void 0:ge.filters)||null),onFiltersClick:n,inlineFilters:r.inlineFilters,inlineFilterValues:d,sheetId:h||"",removeInlineFilterValue:Z=>o(r.id,Z),resolvedPrimaryDateField:ie}),e.jsx(t.IconButton,{tooltip:"Refresh",className:"h-7 w-7 rounded-[5px] p-0",disabled:V||B,onClick:()=>{he(!0),q()},children:e.jsx(t.RefreshCcw,{className:t.cn("h-3.5 w-3.5",{"animate-spin":de})})}),s==="chart"&&!L&&e.jsx(_n,{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-7 w-7 rounded-[5px] p-0","aria-label":"More options",children:e.jsx(t.EllipsisVertical,{className:"h-3.5 w-3.5"})})}),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:me,children:[M?e.jsx(va,{className:"mr-2 h-4 w-4"}):e.jsx(Fa,{className:"mr-2 h-4 w-4"}),M?"Hide Results Table":"Show Results Table"]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs("div",{className:"px-1 py-1",children:[e.jsx(hs,{triggerVariant:"menu",className:"w-full"}),e.jsx(xs,{triggerVariant:"menu",className:"w-full"})]}),e.jsx($n,{onCustomize:()=>T(!0)})]})]})]})]}),e.jsxs("div",{className:"flex min-h-0 grow flex-col",children:[s==="chart"&&e.jsx("div",{className:t.cn("flex grow flex-col pb-4",{"pb-0":M&&!["table","pivotTable","aggregateTable","detailTable"].includes(r.type)}),children:e.jsx(mi,{card:r,queryData:O,isLoading:V,isFetching:B,pagination:G,onPaginationChange:se,onSortChange:je,sortState:be,splitViewEnabled:M,isDynamicInspectorOpen:y,onDynamicInspectorOpenChange:T})}),s==="table"&&(O==null?void 0:O.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 px-4 py-4",children:[(V||B)&&(O==null?void 0:O.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:oe,comparisonMetadata:H,paginationMetadata:G,onPaginationChange:se,isLoading:V||B,onSortChange:je,sortState:be})]}),s==="info"&&R&&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 px-4",children:z?e.jsx(us,{error:z,errorSql:_,onSendFeedback:()=>{const Z=t.prepareFeedbackData(t.FeedbackCategory.QUERY_GENERATION,{cardConfig:i.config,dataSource:r.dataSource,dashboardFilters:m,errorMessage:z,errorSql:_,generatedSql:O==null?void 0:O.sql});D(Z),A(!0)},onOpenInEditor:()=>{g(!0),setTimeout(()=>{const Z=t.useEditorStore.getState().actions;Z.setIsDevMode(!0),Z.setCardSql(_||""),setTimeout(()=>{Z.setRunSql(!0)},100)},100)}}):(O==null?void 0:O.sql)&&e.jsx(On,{sql:O.sql,showCardDetails:!0,debugPayloads:w?{queryRequest:te,queryResponse:O,columns:c,dashboardFilters:m}:void 0})})})]}),E&&e.jsx(t.FeedbackDialog,{open:C,onOpenChange:A,feedbackData:E})]})})}function gi({activeField:s}){const[a,n]=N.useState(!0);if(N.useEffect(()=>{s&&n(!0)},[s]),!s)return null;const r=!!t.getFieldExpressionAnnotation(s);return e.jsxs("div",{className:`flex h-7 max-w-[300px] items-center gap-2 rounded-[5px] border border-border bg-popover px-3 text-[13px] text-foreground/90 shadow-[0_4px_12px_rgba(0,0,0,0.08)] transition-all duration-150 ${a?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(t.TypeGlyph,{dataType:s.dataType,calculated:r}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap",children:s.label||s.name})]})}const bi=()=>{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 a=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},n=r=>{var 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",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=s,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function ji({column:s,isSelected:a,onSelect:n,availableFields:r,width:c,onWidthChange:i}){var z,V,B;const l=t.useEditorStore(_=>_.card),{updateCardConfig:d,removeGroupByColumn:o,removeMetricColumn:m,updateFilters:h}=t.useEditorActions(),[f,x]=N.useState(!1),[u,g]=N.useState(!1),v=N.useRef(null),b=N.useCallback(_=>{_.preventDefault(),_.stopPropagation(),g(!0),v.current={startX:_.clientX,startWidth:c||150};const G=H=>{if(!v.current)return;const te=H.clientX-v.current.startX,ie=Math.max(80,v.current.startWidth+te);i==null||i(s.id,ie)},q=()=>{g(!1),v.current=null,document.removeEventListener("mousemove",G),document.removeEventListener("mouseup",q)};document.addEventListener("mousemove",G),document.addEventListener("mouseup",q)},[c,s.id,i]),S=(z=l==null?void 0:l.config)==null?void 0:z.filters,I=(V=S==null?void 0:S.conditions)==null?void 0:V.some(_=>_.field.name===s.name&&_.field.qualifiedEntityName===s.qualifiedEntityName),P=_=>{_?h(l.id,_):d(l.id,{filters:void 0})},{attributes:C,listeners:A,setNodeRef:y,transform:T,transition:E,isDragging:D}=t.useSortable({id:s.id}),p={transform:t.CSS.Transform.toString(T),transition:E},R=t.getDataType(s.dataType),w=vi(R),M=()=>{var q;const _=((q=l==null?void 0:l.config)==null?void 0:q.sortByColumns)||[],G=_.findIndex(H=>H.name===s.name);if(G!==-1){const H=[..._];H[G]={...H[G],direction:"asc"},d(l.id,{sortByColumns:H})}else d(l.id,{sortByColumns:[..._,{...s,id:`sort-${s.id}`,role:"sortby",direction:"asc"}]})},F=()=>{var q;const _=((q=l==null?void 0:l.config)==null?void 0:q.sortByColumns)||[],G=_.findIndex(H=>H.name===s.name);if(G!==-1){const H=[..._];H[G]={...H[G],direction:"desc"},d(l.id,{sortByColumns:H})}else d(l.id,{sortByColumns:[..._,{...s,id:`sort-${s.id}`,role:"sortby",direction:"desc"}]})},j=()=>{var q;const _=((q=l==null?void 0:l.config)==null?void 0:q.groupByColumns)||[];if(!_.some(H=>H.name===s.name)){const H={...s,id:`groupby-${s.id}-${Date.now()}`,role:"groupby"};d(l.id,{groupByColumns:[..._,H]})}},L=_=>{var H;const G=((H=l==null?void 0:l.config)==null?void 0:H.metricColumns)||[];if(!G.some(te=>te.name===s.name&&te.aggregate===_)){const te={...s,id:`metric-${s.id}-${_}-${Date.now()}`,label:`${_} of ${s.label||s.name}`,role:"metric",aggregate:_};d(l.id,{metricColumns:[...G,te]})}},k=()=>{s.role==="groupby"?o(l.id,s.id):s.role==="metric"&&m(l.id,s.id)},O={...p,width:c?`${c}px`:void 0,minWidth:c?`${c}px`:"120px"};return e.jsxs("th",{ref:y,style:O,className:t.cn("group relative border-r border-border bg-background px-1 py-0",D&&"opacity-50",a&&"bg-primary/10",u&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...C,...A,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:n,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",a&&"bg-primary/10"),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(w,{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,")"]}),I&&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:()=>x(!0),children:[e.jsx(t.Filter,{className:t.cn("mr-2 h-4 w-4",I&&"text-primary")}),I?"Edit Filter":"Filter"]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{onClick:M,children:[e.jsx(ga,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(t.DropdownMenuItem,{onClick:F,children:[e.jsx(fa,{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:()=>L("SUM"),children:"Sum"}),e.jsx(t.DropdownMenuItem,{onClick:()=>L("AVG"),children:"Average"}),e.jsx(t.DropdownMenuItem,{onClick:()=>L("COUNT"),children:"Count"}),e.jsx(t.DropdownMenuItem,{onClick:()=>L("DISTINCT"),children:"Count Distinct"}),e.jsx(t.DropdownMenuItem,{onClick:()=>L("MIN"),children:"Min"}),e.jsx(t.DropdownMenuItem,{onClick:()=>L("MAX"),children:"Max"})]})]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{onClick:j,children:[e.jsx(zt,{className:"mr-2 h-4 w-4"}),"Group by this column"]}),e.jsxs(t.DropdownMenuItem,{disabled:!0,children:[e.jsx(ds,{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:k,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",u&&"bg-primary")}),e.jsx(Jn,{open:f,onOpenChange:x,availableFields:r.length>0?r:[s],existingFilters:S,editingCondition:I?(B=S==null?void 0:S.conditions)==null?void 0:B.find(_=>_.field.name===s.name&&_.field.qualifiedEntityName===s.qualifiedEntityName):void 0,onSave:P})]})}function vi(s){switch(s){case"number":return t.Hash;case"date":return t.Calendar;case"string":default:return t.Type}}function yi({selectedColumn:s,onColumnSelect:a,isLoading:n=!1,sourceFields:r=[],filterableFields:c=r}){var D,p,R,w;const i=t.useEditorStore(M=>M.card),{updateCardConfig:l}=t.useEditorActions(),[d,o]=N.useState(null),[m,h]=N.useState({}),[f,x]=N.useState(!1),u=N.useMemo(()=>{var j,L;const M=((j=i==null?void 0:i.config)==null?void 0:j.groupByColumns)||[],F=((L=i==null?void 0:i.config)==null?void 0:L.metricColumns)||[];return[...M,...F]},[(D=i==null?void 0:i.config)==null?void 0:D.groupByColumns,(p=i==null?void 0:i.config)==null?void 0:p.metricColumns]),g=N.useMemo(()=>{const M=new Set(u.map(F=>`${F.qualifiedEntityName}.${F.name}`));return r.filter(F=>!M.has(`${F.qualifiedEntityName}.${F.name}`))},[r,u]),{data:v,isLoading:b}=t.useEditorCardQuery(i),S=(v==null?void 0:v.records)||[],I=N.useCallback((M,F)=>{h(j=>({...j,[M]:F}))},[]),P=N.useCallback(M=>{var k,O;const F=t.getDataType(M.dataType),j=((k=i==null?void 0:i.config)==null?void 0:k.groupByColumns)||[],L=((O=i==null?void 0:i.config)==null?void 0:O.metricColumns)||[];if(F==="number"){const z={...M,id:`metric-${M.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};l(i.id,{metricColumns:[...L,z]})}else{const z={...M,id:`groupby-${M.id}-${Date.now()}`,role:"groupby"};l(i.id,{groupByColumns:[...j,z]})}x(!1)},[(R=i==null?void 0:i.config)==null?void 0:R.groupByColumns,(w=i==null?void 0:i.config)==null?void 0:w.metricColumns,i.id,l]),C=t.useSensors(t.useSensor(t.PointerSensor,{activationConstraint:{distance:8}})),A=M=>{o(M.active.id)},y=M=>{const{active:F,over:j}=M;if(o(null),!j||F.id===j.id)return;const L=u.findIndex(O=>O.id===F.id),k=u.findIndex(O=>O.id===j.id);if(L!==-1&&k!==-1){const O=t.arrayMove(u,L,k),z=O.filter(B=>B.role==="groupby"),V=O.filter(B=>B.role==="metric");l(i.id,{groupByColumns:z,metricColumns:V})}},T=d?u.find(M=>M.id===d):null,E=M=>{let F="";for(;M>=0;)F=String.fromCharCode(M%26+65)+F,M=Math.floor(M/26)-1;return F};return n?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"})}):u.length===0?e.jsx("div",{className:"flex h-full flex-col items-center justify-center gap-4 p-8 text-center",children:e.jsxs("div",{className:"rounded-lg border-2 border-dashed border-muted-foreground/25 p-12",children:[e.jsx("h3",{className:"text-lg font-medium text-muted-foreground",children:"No columns selected"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground/75",children:"Select columns from the panel on the right to build your table"})]})}):e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsxs(t.DndContext,{sensors:C,collisionDetection:t.closestCenter,onDragStart:A,onDragEnd:y,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:u.map(M=>M.id),strategy:t.horizontalListSortingStrategy,children:u.map((M,F)=>e.jsx("th",{style:{width:m[M.id]?`${m[M.id]}px`:void 0,minWidth:m[M.id]?`${m[M.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:E(F)},`letter-${M.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:u.map(M=>M.id),strategy:t.horizontalListSortingStrategy,children:u.map(M=>e.jsx(ji,{column:M,isSelected:(s==null?void 0:s.id)===M.id,onSelect:()=>a(M),availableFields:c,width:m[M.id],onWidthChange:I},M.id))}),e.jsx("th",{className:"w-10 border-r border-border bg-background px-1 py-2",children:e.jsxs(t.Popover,{open:f,onOpenChange:x,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(M=>{const F=t.getDataType(M.dataType),j=F==="number"?t.Hash:F==="date"?t.Calendar:t.Type;return e.jsxs(t.CommandItem,{value:M.label||M.name,onSelect:()=>P(M),children:[e.jsx(j,{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:M.label||M.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:M.entityName})]})]},M.id)})})]})]})})]})})]})]}),e.jsx("tbody",{children:b?e.jsx("tr",{children:e.jsx("td",{colSpan:u.length+2,className:"h-32 text-center",children:e.jsx(t.LoaderCircle,{className:"mx-auto h-6 w-6 animate-spin text-muted-foreground"})})}):S.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:u.length+2,className:"h-32 text-center text-muted-foreground",children:"No data available"})}):S.slice(0,100).map((M,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}),u.map(j=>{const L=M[j.name]??M[j.label??""];return e.jsx("td",{style:{width:m[j.id]?`${m[j.id]}px`:void 0,minWidth:m[j.id]?`${m[j.id]}px`:"120px"},className:t.cn("border-r border-border px-3 py-2 text-sm",(s==null?void 0:s.id)===j.id&&"bg-primary/5"),children:e.jsx("span",{className:"block truncate",children:Ni(L,j)})},`${F}-${j.id}`)}),e.jsx("td",{className:"w-10 border-r border-border"})]},F))})]}),e.jsx(t.DragOverlay,{children:T&&e.jsx("div",{className:"rounded border border-primary bg-background px-3 py-2 text-sm font-medium shadow-lg",children:T.label||T.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(S.length,100)," of ",S.length," rows"]}),e.jsxs("span",{children:[u.length," columns"]})]})]})}function Ni(s,a){if(s==null)return"—";if(typeof s=="number")return a.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 n=new Date(s);if(!isNaN(n.getTime()))return n.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}return String(s)}function Ci({entityGroups:s,isLoading:a=!1}){var P,C;const n=t.useEditorStore(A=>A.card),{updateCardConfig:r,removeGroupByColumn:c,removeMetricColumn:i}=t.useEditorActions(),[l,d]=N.useState(!0),[o,m]=N.useState(""),[h,f]=N.useState(new Set),x=((P=n==null?void 0:n.config)==null?void 0:P.groupByColumns)||[],u=((C=n==null?void 0:n.config)==null?void 0:C.metricColumns)||[],g=A=>{const y=new Set(h);y.has(A)?y.delete(A):y.add(A),f(y)},v=A=>x.some(y=>y.name===A.name&&y.qualifiedEntityName===A.qualifiedEntityName)||u.some(y=>y.name===A.name&&y.qualifiedEntityName===A.qualifiedEntityName),b=(A,y)=>{if(y)if(t.getDataType(A.dataType)==="number"){const E={...A,id:`metric-${A.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};r(n.id,{metricColumns:[...u,E]})}else{const E={...A,id:`groupby-${A.id}-${Date.now()}`,role:"groupby"};r(n.id,{groupByColumns:[...x,E]})}else{const T=x.findIndex(D=>D.name===A.name&&D.qualifiedEntityName===A.qualifiedEntityName),E=u.findIndex(D=>D.name===A.name&&D.qualifiedEntityName===A.qualifiedEntityName);T!==-1&&c(n.id,x[T].id),E!==-1&&i(n.id,u[E].id)}},S=A=>{if(!o)return A;const y=o.toLowerCase();return A.filter(T=>T.name.toLowerCase().includes(y)||T.label&&T.label.toLowerCase().includes(y))},I=A=>{switch(t.getDataType(A)){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(Ea,{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:A=>m(A.target.value),className:"h-8 pl-8 text-sm"})]})}),(x.length>0||u.length>0)&&e.jsxs("div",{className:"border-b border-border",children:[x.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:x.length})]}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:x.map(A=>{const y=I(A.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(y,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:A.label||A.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(n.id,A.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]},A.id)})})})]}),u.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:u.length})]}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:u.map(A=>{const y=I(A.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(y,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:A.label||A.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:A.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(n.id,A.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]},A.id)})})})]})]}),e.jsx(t.ScrollArea,{className:"flex-1",children:e.jsx("div",{className:"p-2",children:a?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(A=>{const y=S(A.columns);if(y.length===0)return null;const T=h.has(A.entityId)||o.length>0;return e.jsxs(t.Collapsible,{open:T,onOpenChange:()=>g(A.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",T&&"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:A.label||A.entityName}),e.jsx("span",{className:"text-xs text-muted-foreground",children:y.length})]}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:y.map(E=>{const D=I(E.dataType),p=v(E);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",p&&"bg-primary/5"),children:[e.jsx(t.Checkbox,{checked:p,onCheckedChange:R=>b(E,R),className:"h-3.5 w-3.5"}),e.jsx(D,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:E.label||E.name})]},E.id)})})})]},A.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(Ia,{className:"h-4 w-4"})})})}const Si=[{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 wi({value:s,onChange:a,onSubmit:n,onCancel:r,selectedColumn:c,availableColumns:i}){const[l,d]=N.useState(!1),[o,m]=N.useState("column"),h=N.useRef(null);N.useEffect(()=>{const g=v=>{v.key==="Escape"&&s?r():v.key==="Enter"&&s&&!l&&n(s)};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[s,r,n,l]);const f=g=>{const v=`[${g.label||g.name}]`,b=h.current;if(b){const S=b.selectionStart||0,I=b.selectionEnd||0,P=s.slice(0,S)+v+s.slice(I);a(P),setTimeout(()=>{b.setSelectionRange(S+v.length,S+v.length),b.focus()},0)}else a(s+v);d(!1)},x=g=>{const v=h.current;if(v){const b=v.selectionStart||0,S=v.selectionEnd||0,I=s.slice(0,b)+g.syntax+s.slice(S);a(I),setTimeout(()=>{v.setSelectionRange(b+g.name.length+1,b+g.syntax.length-1),v.focus()},0)}else a(s+g.syntax);d(!1)},u=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&&m("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(La,{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:Si.map(g=>e.jsx(t.CommandItem,{value:g.name,onSelect:()=>x(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&&m("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=u(g.dataType);return e.jsxs(t.CommandItem,{value:g.label||g.name,onSelect:()=>f(g),children:[e.jsx(v,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:g.label||g.name})]},g.id)})})]})]})})]}),e.jsx("div",{className:"relative flex-1",children:e.jsx(t.Input,{ref:h,value:s,onChange:g=>a(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:()=>n(s),title:"Apply (Enter)",children:e.jsx(t.Check,{className:"h-4 w-4"})})]})]})}function Ti({className:s}){var u,g,v,b;const a=t.useEditorStore(S=>S.card),[n,r]=N.useState(null),[c,i]=N.useState(""),{columns:l=[],columnGroups:d=[],isLoading:o}=t.useColumns(),{valuePickFilterableFields:m=[]}=t.useFilterableFields();(u=a==null?void 0:a.config)!=null&&u.groupByColumns,(g=a==null?void 0:a.config)!=null&&g.metricColumns,(v=a==null?void 0:a.config)!=null&&v.groupByColumns,(b=a==null?void 0:a.config)!=null&&b.pivotByColumns;const h=S=>{r(S),i(S?`[${S.label||S.name}]`:"")},f=S=>{console.log("Formula submitted:",S),i(""),r(null)},x=()=>{i(""),r(null)};return e.jsxs("div",{className:t.cn("flex h-full w-full flex-col",s),children:[e.jsx(wi,{value:c,onChange:i,onSubmit:f,onCancel:x,selectedColumn:n,availableColumns:l}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(yi,{selectedColumn:n,onColumnSelect:h,isLoading:o,sourceFields:l,filterableFields:m})}),e.jsx(Ci,{entityGroups:d,isLoading:o})]})]})}function Ei(){var z,V;const[s,a]=N.useState("chart"),[n,r]=N.useState(!1),[c,i]=N.useState(!0),[l,d]=N.useState(!0),o=t.useEditorStore(B=>B.showAIDialog),m=t.useDashboardStore(B=>B.isVisualEditing),{setCardType:h}=t.useEditorActions(),f=t.useEditorStore(B=>B.card.type);N.useEffect(()=>bi(),[]);const x=B=>{h(B)},u=t.useEditorStore(B=>B.frame),g=t.useEditorStore(B=>B.card);t.useEditorStore(B=>B.activeTabCardId),t.useEditorStore(B=>B.actions.getAvailableFields);const{addCard:v,removeCard:b,updateCard:S,setActiveCard:I,updateFilters:P}=t.useEditorActions(),{columnFields:C=[],scopedFields:A=[],filterableFields:y=[]}=t.useFilterableFields(),T=t.useSensors(t.useSensor(t.PointerSensor,{activationConstraint:{distance:8}})),E=g,{getFieldsForContainer:D,setFieldsForContainer:p}=t.useFieldManagement(E),{activeField:R,handleDragStart:w,handleDragEnd:M}=ii({activeCardId:u.activeCardId,sourceFields:A,getFieldsForContainer:D,setFieldsForContainer:p}),F=(B,_)=>{_&&P(B,_)},j=B=>{var _;S(B,{config:{...(_=u.cards.find(G=>G.id===B))==null?void 0:_.config,filters:void 0}})},L=y,k=B=>{if(!B)return 0;let _=B.conditions.length;return B.groups.forEach(G=>{_+=k(G)}),_},O=k(((z=E==null?void 0:E.config)==null?void 0:z.filters)||null);return e.jsxs(t.DndContext,{sensors:T,collisionDetection:t.closestCenter,onDragStart:w,onDragEnd:M,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Rn,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:f==="tableBuilder"?e.jsx(Ti,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!o&&e.jsx(Ko,{selectedChart:f,onChartChange:x,groupByFields:D("groupBy"),pivotByFields:D("pivotBy"),metricsFields:D("metrics"),sortByFields:D("sortBy"),detailFields:D("detailColumns"),activeField:R,isVisible:l,onToggleVisibility:()=>d(!l)}),e.jsx(fi,{selectedChart:f,activeView:s,onViewChange:a,onFiltersClick:()=>r(!0),filterCount:O,activeCard:E,columns:C,getFieldsForContainer:D,cards:u.cards,activeCardId:u.activeCardId,addCard:v,setActiveCard:I})]})}),!c&&m&&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"})})})]}),E&&e.jsx(oi,{cardId:E.id,filters:((V=E.config)==null?void 0:V.filters)||null,onFiltersChange:F,onClearFilters:j,availableFields:L,isOpen:n,onOpenChange:r}),e.jsx(t.DragOverlay,{dropAnimation:null,children:e.jsx(gi,{activeField:R||null})})]})}function Ii({authToken:s,onSave:a,onClose:n}){const r=N.useRef(null),c=t.useEditorStore(y=>y.showAIDialog),i=t.useEditorStore(y=>y.isDevMode),l=t.useAssistantLayoutStore(y=>y.setFullscreen),d=t.useAssistantLayoutStore(y=>y.setPanelOpen),o=t.useAssistantLayoutStore(y=>y.setContainer),m=t.useAssistantPanel("editor"),h=t.useFullscreenAssistant(),f=t.useAssistantContainer("editor"),x=h==="editor",u=N.useCallback(y=>{o("editor",y)},[o]),{setAuthToken:g}=t.useDashboardActions(),{setShowAIDialog:v,setOnSave:b,setOnClose:S}=t.useEditorActions(),{setActiveAssistantType:I}=t.useAIActions();N.useEffect(()=>{a&&b(a),n&&S(n)},[a,b,n,S]),N.useEffect(()=>{s&&s.accessToken&&g(s)},[s,g]),N.useEffect(()=>{var y,T;c?((y=r.current)==null||y.resize(40),d("editor",!0),I("editor")):((T=r.current)==null||T.resize(0),d("editor",!1),h==="editor"&&l(null),I(null))},[c,d,I,l,h]);function P(y){var T;y<1?(v(!1),d("editor",!1),h==="editor"&&l(null),I(null),(T=r.current)==null||T.resize(0)):(c||(v(!0),I("editor")),m.isOpen||d("editor",!0))}function C(){return e.jsxs(e.Fragment,{children:[e.jsx(Rn,{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",x&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(vo,{})}),e.jsx(t.ResizableHandle,{disabled:!c}),e.jsx(t.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:P,defaultSize:m.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(wn,{isFullscreen:x,onFullscreenChange:y=>l(y?"editor":null),fullscreenContainer:f})})})]}),e.jsx("div",{ref:u,className:t.cn("absolute inset-0",!x&&"pointer-events-none")})]})]})}function A(){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",x&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Ei,{})}),e.jsx(t.ResizableHandle,{disabled:!c}),e.jsx(t.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:P,defaultSize:m.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(wn,{isFullscreen:x,onFullscreenChange:y=>l(y?"editor":null),fullscreenContainer:f})})})]}),e.jsx("div",{ref:u,className:t.cn("absolute inset-0",!x&&"pointer-events-none")})]})}return e.jsx(t.ErrorBoundary,{FallbackComponent:t.Fallback,children:i?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:C()}):A()})}function ki(){t.useDashboardStore(x=>x.selectedCardId);const s=t.useDashboardStore(x=>x.selectedSheetId),a=t.useDashboardStore(x=>x.dashboard),{setIsVisualEditing:n,setSelectedSheetId:r}=t.useDashboardStore(x=>x.actions),c=t.useEditorStore(x=>x.editorContext),{clearEditorContext:i}=t.useEditorStore(x=>x.actions),l=t.useDashboardStore(x=>x.isVisualEditing),d=t.useDashboardStore(x=>x.actions.updateFrame),o=t.useDashboardStore(x=>x.actions.updateDocumentSectionCard),m=t.useResolveExistingFrameSemanticExecutionPayload();async function h(x){var S,I,P;if((c==null?void 0:c.type)==="documentSection"){const C=t.getDocumentSectionEditorCard(x,c.cardId);if(!C){t.ue.error("No document section card found");return}if(!t.isSupportedDocumentTableCardType(C)){t.ue.error("Document table sections support Table and Pivot Table");return}o(c.sheetId,c.sectionId,C,{calculatedFields:x.calculatedFields}),i(),n(!1);return}const u=s?(S=a==null?void 0:a.sheets)==null?void 0:S.some(C=>{var A;return C.id===s&&((A=C.frames)==null?void 0:A.some(y=>y.id===x.id))}):!1,g=(P=(I=a==null?void 0:a.sheets)==null?void 0:I.find(C=>{var A;return(A=C.frames)==null?void 0:A.some(y=>y.id===x.id)}))==null?void 0:P.id,v=u?s:g||null;if(!v)return;const b=t.findDashboardFrameById(a,x.id);try{const C=await m(x,{previousFrame:b});d(v,x,{semanticExecutionPayload:C}),s!==v&&r(v),n(!1)}catch(C){console.error("Failed to resolve semantic metadata on save:",C),t.ue.error(C instanceof Error?C.message:"Failed to resolve semantic metadata for this visual")}}function f(){i(),n(!1)}return e.jsx("div",{role:"editor-container",className:t.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!l}),children:e.jsx(Ii,{onSave:h,onClose:f})})}exports.default=ki;
|