react-semaphor 0.1.300 → 0.1.301
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-C0YourPb.js → braces-Bhqo4iW1.js} +1 -1
- package/dist/chunks/{braces-BAdE5PE0.js → braces-BwK7fWd_.js} +1 -1
- package/dist/chunks/{dashboard-controls-CfQ3VOdS.js → dashboard-controls-BIRiWCUK.js} +1 -1
- package/dist/chunks/{dashboard-controls-M1pEBMUQ.js → dashboard-controls-DIlnYo96.js} +5 -5
- package/dist/chunks/{dashboard-filter-controls-button-Dy_rukRc.js → dashboard-filter-controls-button-CK1-mKQh.js} +1 -1
- package/dist/chunks/{dashboard-filter-controls-button-K4hL7KCc.js → dashboard-filter-controls-button-DjALRkvg.js} +3 -3
- package/dist/chunks/{dashboard-json-CDj4ps7k.js → dashboard-json-D-zIG46N.js} +1 -1
- package/dist/chunks/{dashboard-json-Dux0R9T3.js → dashboard-json-DK4mQ1gS.js} +1 -1
- package/dist/chunks/{dashboard-summary-settings-dialog-Ci9neBCE.js → dashboard-summary-settings-dialog-D-F1eEJI.js} +1 -1
- package/dist/chunks/{dashboard-summary-settings-dialog-FCGGq0QT.js → dashboard-summary-settings-dialog-DSxNqxFI.js} +1 -1
- package/dist/chunks/{edit-dashboard-visual-Baklmbnn.js → edit-dashboard-visual-BjflrL8w.js} +4195 -4215
- package/dist/chunks/edit-dashboard-visual-DCsrtJr_.js +193 -0
- package/dist/chunks/{index-u9HF3DLf.js → index-8GnvL1_L.js} +266 -271
- package/dist/chunks/{index-k2nUr51g.js → index-DDA12yqV.js} +30549 -30668
- package/dist/chunks/{resource-management-panel-CzAaiI_M.js → resource-management-panel-B2558XA1.js} +2 -2
- package/dist/chunks/{resource-management-panel-Sb9b4R-f.js → resource-management-panel-CKp4_aem.js} +1 -1
- package/dist/chunks/{use-create-flow-overlay-state-CJo92SfT.js → use-create-flow-overlay-state-BUw_JtLs.js} +2 -2
- package/dist/chunks/{use-create-flow-overlay-state-nT9AdiH1.js → use-create-flow-overlay-state-CWcCdPbC.js} +1 -1
- package/dist/chunks/{use-visual-utils-BVz7bp1V.js → use-visual-utils-C45OxsOf.js} +1 -1
- package/dist/chunks/{use-visual-utils-BlLzFtMt.js → use-visual-utils-DyaThRzf.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-B0nk13zW.js +0 -193
|
@@ -1,193 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),N=require("react"),t=require("./index-u9HF3DLf.js"),it=require("./use-visual-utils-BlLzFtMt.js"),Ae=require("./use-create-flow-overlay-state-nT9AdiH1.js"),pa=require("react-dom"),fa=require("./braces-BAdE5PE0.js");function ga(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 Vt=ga(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 ba=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 ja=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 xs=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 va=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 ya=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 Na=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 Ca=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 Sa=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 wa=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 ln=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 Ta=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 Ea=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 Zt=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 es=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 Ia=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 ka=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 Da=t.createLucideIcon("PanelRightOpen",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m10 15-3-3 3-3",key:"1pgupc"}]]);/**
|
|
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 Aa=t.createLucideIcon("PanelRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
|
|
107
|
-
* @license lucide-react v0.453.0 - ISC
|
|
108
|
-
*
|
|
109
|
-
* This source code is licensed under the ISC license.
|
|
110
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
111
|
-
*/const us=t.createLucideIcon("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/**
|
|
112
|
-
* @license lucide-react v0.453.0 - ISC
|
|
113
|
-
*
|
|
114
|
-
* This source code is licensed under the ISC license.
|
|
115
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
116
|
-
*/const qt=t.createLucideIcon("Rows3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M21 9H3",key:"1338ky"}],["path",{d:"M21 15H3",key:"9uk58r"}]]);/**
|
|
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 Ma=t.createLucideIcon("SendHorizontal",[["path",{d:"M3.714 3.048a.498.498 0 0 0-.683.627l2.843 7.627a2 2 0 0 1 0 1.396l-2.842 7.627a.498.498 0 0 0 .682.627l18-8.5a.5.5 0 0 0 0-.904z",key:"117uat"}],["path",{d:"M6 12h16",key:"s4cdu5"}]]);/**
|
|
122
|
-
* @license lucide-react v0.453.0 - ISC
|
|
123
|
-
*
|
|
124
|
-
* This source code is licensed under the ISC license.
|
|
125
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
126
|
-
*/const La=t.createLucideIcon("Shapes",[["path",{d:"M8.3 10a.7.7 0 0 1-.626-1.079L11.4 3a.7.7 0 0 1 1.198-.043L16.3 8.9a.7.7 0 0 1-.572 1.1Z",key:"1bo67w"}],["rect",{x:"3",y:"14",width:"7",height:"7",rx:"1",key:"1bkyp8"}],["circle",{cx:"17.5",cy:"17.5",r:"3.5",key:"w3z12y"}]]);/**
|
|
127
|
-
* @license lucide-react v0.453.0 - ISC
|
|
128
|
-
*
|
|
129
|
-
* This source code is licensed under the ISC license.
|
|
130
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
131
|
-
*/const Fa=t.createLucideIcon("Sigma",[["path",{d:"M18 7V5a1 1 0 0 0-1-1H6.5a.5.5 0 0 0-.4.8l4.5 6a2 2 0 0 1 0 2.4l-4.5 6a.5.5 0 0 0 .4.8H17a1 1 0 0 0 1-1v-2",key:"wuwx1p"}]]);/**
|
|
132
|
-
* @license lucide-react v0.453.0 - ISC
|
|
133
|
-
*
|
|
134
|
-
* This source code is licensed under the ISC license.
|
|
135
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
136
|
-
*/const Ra=t.createLucideIcon("Spline",[["circle",{cx:"19",cy:"5",r:"2",key:"mhkx31"}],["circle",{cx:"5",cy:"19",r:"2",key:"v8kfzx"}],["path",{d:"M5 17A12 12 0 0 1 17 5",key:"1okkup"}]]);/**
|
|
137
|
-
* @license lucide-react v0.453.0 - ISC
|
|
138
|
-
*
|
|
139
|
-
* This source code is licensed under the ISC license.
|
|
140
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
141
|
-
*/const Oa=t.createLucideIcon("SquareFunction",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["path",{d:"M9 17c2 0 2.8-1 2.8-2.8V10c0-2 1-3.3 3.2-3",key:"m1af9g"}],["path",{d:"M9 11.2h5.7",key:"3zgcl2"}]]);/**
|
|
142
|
-
* @license lucide-react v0.453.0 - ISC
|
|
143
|
-
*
|
|
144
|
-
* This source code is licensed under the ISC license.
|
|
145
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
146
|
-
*/const Pa=t.createLucideIcon("SquareSplitVertical",[["path",{d:"M5 8V5c0-1 1-2 2-2h10c1 0 2 1 2 2v3",key:"1pi83i"}],["path",{d:"M19 16v3c0 1-1 2-2 2H7c-1 0-2-1-2-2v-3",key:"ido5k7"}],["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}]]);/**
|
|
147
|
-
* @license lucide-react v0.453.0 - ISC
|
|
148
|
-
*
|
|
149
|
-
* This source code is licensed under the ISC license.
|
|
150
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
151
|
-
*/const Ba=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"}]]);/**
|
|
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 Va=t.createLucideIcon("Tags",[["path",{d:"m15 5 6.3 6.3a2.4 2.4 0 0 1 0 3.4L17 19",key:"1cbfv1"}],["path",{d:"M9.586 5.586A2 2 0 0 0 8.172 5H3a1 1 0 0 0-1 1v5.172a2 2 0 0 0 .586 1.414L8.29 18.29a2.426 2.426 0 0 0 3.42 0l3.58-3.58a2.426 2.426 0 0 0 0-3.42z",key:"135mg7"}],["circle",{cx:"6.5",cy:"9.5",r:".5",fill:"currentColor",key:"5pm5xn"}]]);/**
|
|
157
|
-
* @license lucide-react v0.453.0 - ISC
|
|
158
|
-
*
|
|
159
|
-
* This source code is licensed under the ISC license.
|
|
160
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
161
|
-
*/const za=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[d,i]=N.useState(s??a),l=N.useRef(null),c=N.useRef(d),o=N.useRef(s),m=N.useRef(!1),x=N.useCallback(()=>{l.current&&(clearTimeout(l.current),l.current=null),m.current&&c.current!==(o.current??a)&&(n(c.current),o.current=c.current)},[a,n]);N.useEffect(()=>{if(s!==o.current){l.current&&(clearTimeout(l.current),l.current=null);const h=s??a;i(h),c.current=h,o.current=s,m.current=!1}},[s,a]),N.useEffect(()=>{if(m.current)return l.current=setTimeout(()=>{x()},r),()=>{l.current&&(clearTimeout(l.current),l.current=null)}},[r,x,d]),N.useEffect(()=>()=>{l.current&&clearTimeout(l.current)},[]);const b=N.useCallback(h=>{const u=h??a;m.current=!0,c.current=u,i(u)},[a]);return{value:d,onChange:b,flush:x}}function _a({open:s,onOpenChange:a}){const[n,r]=N.useState([]),{updateDataSource:d}=t.useEditorActions(),{selectedEntities:i}=t.useAssistantContextEntities("dashboard");N.useEffect(()=>{s&&r([])},[s]);const l=u=>{r(p=>p.some(f=>t.areContextEntitiesEqual(f,u))?p.filter(f=>!t.areContextEntitiesEqual(f,u)):[...p,u])},c=()=>{r([...i])},o=()=>{r([])},m=()=>{if(n.length===0)return;const u=n[0],p=u.connectionId||"",j=u.connectionType||"",T=n.some(O=>O.type==="dataset")?"semanticDomain":"database";d({connectionId:p,connectionType:j,mode:T,selectedEntities:n}),a(!1)},x=u=>"label"in u&&u.label?u.label:u.name,b=u=>{if("description"in u&&u.description)return u.description;const p=[];return u.database&&p.push(u.database),u.schema&&p.push(u.schema),u.name&&p.push(u.name),p.join(".")},h=u=>n.some(p=>t.areContextEntitiesEqual(p,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:c,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,p)=>e.jsxs("div",{className:t.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",h(u)&&"border-primary bg-primary/5"),children:[e.jsx(t.Checkbox,{checked:h(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:x(u)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:b(u)})]}),e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:u.type})]},`${u.type}-${u.name}-${p}`))})})]}),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 qa({initialJoinPlan:s,availableDataSources:a}){const[n,r]=N.useState(s),[d,i]=N.useState(new Set),l=()=>{const w=n.joins.length>0?Math.max(...n.joins.map(y=>y.sequence))+1:1,D={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:w,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...n,joins:[...n.joins,D]}),i(new Set([...d,D.id]))},c=w=>{r({...n,joins:n.joins.filter(D=>D.id!==w)}),i(new Set([...d].filter(D=>D!==w)))},o=(w,D)=>{var M,S,F,v,L;const y=n.joins.find(I=>I.id===w);if(!y)return;const A={...y,...D};if((M=A.source)!=null&&M.name&&((S=A.target)!=null&&S.name)&&A.source.name===A.target.name){t.ue.error("Self-joins are not yet supported",{description:`Joining ${A.source.name} to itself is not currently supported. Please select a different target table.`});return}const g=n.joins.filter(I=>{var P;return I.id!==w&&I.target.name===((P=A.target)==null?void 0:P.name)});if((F=A.target)!=null&&F.name&&g.length>0){t.ue.error("Duplicate join targets are not supported",{description:`The table ${A.target.name} is already used as a target in another join. Each table can only be joined once.`});return}const R=n.joins.map(I=>I.id===w?A:I);if((v=A.source)!=null&&v.name&&((L=A.target)!=null&&L.name)&&A.joinKeyGroups[0].keys.length===0){const I=a.find(B=>{var _;return B.name===((_=A.source)==null?void 0:_.name)}),P=a.find(B=>{var _;return B.name===((_=A.target)==null?void 0:_.name)}),V={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(I==null?void 0:I.name)||"",entityName:(I==null?void 0:I.name)||"",entityType:(I==null?void 0:I.type)||"table"},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:"="},z=[...A.joinKeyGroups];z[0]={...z[0],keys:[V]},A.joinKeyGroups=z,R[R.findIndex(B=>B.id===w)]=A}r({...n,joins:R})};return{joinPlan:n,expandedJoins:d,setJoinPlan:r,addJoin:l,removeJoin:c,updateJoin:o,moveJoinUp:w=>{const D=n.joins.findIndex(y=>y.id===w);if(D>0){const y=[...n.joins],A={...y[D]},g={...y[D-1]};y[D]=g,y[D-1]=A,y.forEach((M,S)=>{M.sequence=S+1});const R={...n,joins:y};r(R)}},moveJoinDown:w=>{const D=n.joins.findIndex(y=>y.id===w);if(D<n.joins.length-1){const y=[...n.joins],A={...y[D]},g={...y[D+1]};y[D]=g,y[D+1]=A,y.forEach((M,S)=>{M.sequence=S+1});const R={...n,joins:y};r(R)}},toggleJoinExpansion:w=>{const D=new Set(d);D.has(w)?D.delete(w):D.add(w),i(D)},getAvailableSourceEntities:w=>{if(n.joins.length===0)return a;const D=n.joins.findIndex(A=>A.id===w);if(D===0)return a.filter(A=>A.name===n.baseEntity.name);const y=new Set;return n.baseEntity.name&&y.add(n.baseEntity.name),n.joins.slice(0,D).forEach(A=>{y.add(A.source.name),y.add(A.target.name)}),a.filter(A=>y.has(A.name))},getAvailableTargetEntities:w=>a.filter(D=>D.name!==w),addJoinKeyGroup:w=>{const D=n.joins.find(A=>A.id===w);if(!D)return;const y=[...D.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];o(w,{joinKeyGroups:y})},updateGroupOperator:(w,D,y)=>{const A=n.joins.find(R=>R.id===w);if(!A)return;const g=[...A.joinKeyGroups];g[D]={...g[D],operator:y},o(w,{joinKeyGroups:g})},removeJoinKeyGroup:(w,D)=>{const y=n.joins.find(g=>g.id===w);if(!y)return;const A=[...y.joinKeyGroups];A.splice(D,1),o(w,{joinKeyGroups:A})},addJoinKey:(w,D)=>{const y=n.joins.find(S=>S.id===w);if(!y)return;const A=a.find(S=>S.name===y.source.name),g=a.find(S=>S.name===y.target.name),R=[...y.joinKeyGroups],M={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(A==null?void 0:A.name)||"",entityName:(A==null?void 0:A.name)||"",entityType:(A==null?void 0:A.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(g==null?void 0:g.name)||"",entityName:(g==null?void 0:g.name)||"",entityType:(g==null?void 0:g.type)||"table"},operator:"="};R[D]={...R[D],keys:[...R[D].keys,M]},o(w,{joinKeyGroups:R})},updateJoinKey:(w,D,y,A,g)=>{const R=n.joins.find(L=>L.id===w);if(!R)return;const M=a.find(L=>L.name===R.source.name),S=a.find(L=>L.name===R.target.name),F=[...R.joinKeyGroups],v=F[D].keys[y];A==="sourceColumnName"&&M?F[D].keys[y]={...v,source:{...v.source,name:g}}:A==="targetColumnName"&&S?F[D].keys[y]={...v,target:{...v.target,name:g}}:A==="operator"&&(F[D].keys[y]={...v,operator:g}),o(w,{joinKeyGroups:F})},removeJoinKey:(w,D,y)=>{const A=n.joins.find(R=>R.id===w);if(!A)return;const g=[...A.joinKeyGroups];g[D].keys.splice(y,1),o(w,{joinKeyGroups:g})},generateSQLPreview:()=>{const w=[...n.joins].sort((A,g)=>A.sequence-g.sequence),D=n.baseEntity;if(!D.name)return"SELECT * FROM table -- Please select a base entity";let y=`SELECT *
|
|
162
|
-
FROM ${D.name}`;return w.forEach(A=>{const g=a.find(S=>S.name===A.target.name);if(!g)return;const R=A.joinKeyGroups.filter(S=>S.keys&&S.keys.length>0).map(S=>{const F=S.keys.filter(v=>{var L,I,P,V;return((L=v.source)==null?void 0:L.name)&&((I=v.target)==null?void 0:I.name)&&((P=v.source)==null?void 0:P.entityName)&&((V=v.target)==null?void 0:V.entityName)}).map(v=>`${v.source.entityName}.${v.source.name} ${v.operator} ${v.target.entityName}.${v.target.name}`);return F.length>1?`(${F.join(` ${S.operator} `)})`:F[0]}).filter(Boolean),M=R.length>1?R.join(" OR "):R[0]||"condition_here";y+=`
|
|
163
|
-
${A.joinType} JOIN ${g.name}
|
|
164
|
-
ON ${M}`}),y},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(A=>!A.source.name||!A.target.name)||n.joins.some(A=>A.joinKeyGroups.some(g=>g.keys.length===0))||n.joins.some(A=>A.joinKeyGroups.some(g=>g.keys.some(R=>!R.source.name||!R.target.name||!R.operator))))}}function $a({joinPlan:s,availableDataSources:a,onSave:n,onRemove:r,onCancel:d}){const{setCardConfig:i}=t.useEditorActions();t.useEditorStore(M=>M.card.config);const{columnGroups:l}=t.useColumns(),c=l.filter(M=>M.entityName!==t.CALCULATED_FIELDS_GROUP_NAME),{joinPlan:o,expandedJoins:m,setJoinPlan:x,addJoin:b,removeJoin:h,updateJoin:u,moveJoinUp:p,moveJoinDown:j,toggleJoinExpansion:f,getAvailableSourceEntities:T,getAvailableTargetEntities:E,addJoinKeyGroup:O,updateGroupOperator:C,removeJoinKeyGroup:k,addJoinKey:w,updateJoinKey:D,removeJoinKey:y,generateSQLPreview:A,isValidConfiguration:g}=qa({initialJoinPlan:s,availableDataSources:a}),R=M=>{const S=c.find(F=>F.entityName===M);return(S==null?void 0:S.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:M=>{const S=a.find(F=>F.name===M);x({...o,baseEntity:{connectionId:(S==null?void 0:S.connectionId)||"",connectionType:(S==null?void 0:S.connectionType)||"none",type:(S==null?void 0:S.type)||"table",name:M,database:S==null?void 0:S.database,schema:S==null?void 0:S.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(t.SelectContent,{children:a.map(M=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:M.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:M.type}),M.name,e.jsx(t.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},M.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:A()})]}),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:b,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(M=>{const S=a.find(L=>L.name===M.source.name),F=a.find(L=>L.name===M.target.name),v=m.has(M.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:M.sequence}),e.jsxs(t.CardTitle,{className:"text-sm",children:["Join ",M.sequence,S&&F&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",S.name," → ",F.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>p(M.id),disabled:M.sequence===1,children:e.jsx(t.ArrowUp,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>j(M.id),disabled:M.sequence===o.joins.length,children:e.jsx(t.ArrowDown,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>f(M.id),children:v?e.jsx(t.ChevronUp,{className:"h-4 w-4"}):e.jsx(t.ChevronDown,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>h(M.id),children:e.jsx(t.X,{className:"h-4 w-4"})})]})]})}),v&&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:M.source.name,onValueChange:L=>{const I=a.find(P=>P.name===L);u(M.id,{source:{connectionId:(I==null?void 0:I.connectionId)||"",connectionType:(I==null?void 0:I.connectionType)||"none",type:(I==null?void 0:I.type)||"table",name:L,database:I==null?void 0:I.database,schema:I==null?void 0:I.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select source..."})}),e.jsx(t.SelectContent,{children:T(M.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:M.joinType,onValueChange:L=>u(M.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:M.target.name,onValueChange:L=>{const I=a.find(P=>P.name===L);u(M.id,{target:{connectionId:(I==null?void 0:I.connectionId)||"",connectionType:(I==null?void 0:I.connectionType)||"none",type:(I==null?void 0:I.type)||"table",name:L,database:I==null?void 0:I.database,schema:I==null?void 0:I.schema}})},disabled:!M.source.name,children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select target..."})}),e.jsx(t.SelectContent,{children:M.source.name?E(M.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===M.source.name&&e.jsx(t.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},L.name)):[]})]})]})]}),M.source.name&&M.target.name&&S&&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:()=>O(M.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),M.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:M.joinKeyGroups.map((L,I)=>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 ",I+1]}),I>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:P=>C(M.id,I,P),children:[e.jsx(t.SelectTrigger,{className:"w-[100px]",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>k(M.id,I),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((P,V)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[V>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:P.source.name,onValueChange:z=>D(M.id,I,V,"sourceColumnName",z),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Source column"})}),e.jsx(t.SelectContent,{children:R(M.source.name).map(z=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:z.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:z.name}),e.jsx(t.Badge,{variant:"outline",className:"ml-2 text-xs",children:z.dataType})]})},z.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(t.Select,{value:P.operator,onValueChange:z=>D(M.id,I,V,"operator",z),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:P.target.name,onValueChange:z=>D(M.id,I,V,"targetColumnName",z),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Target column"})}),e.jsx(t.SelectContent,{children:R(M.target.name).map(z=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:z.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:z.name}),e.jsx(t.Badge,{variant:"outline",className:"ml-2 text-xs",children:z.dataType})]})},z.name))})]})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>y(M.id,I,V),children:e.jsx(t.X,{className:"size-3.5"})})]},P.id||V))}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>w(M.id,I),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},L.id))})]})]})]},M.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>{r(),d()},children:"Remove All"}),e.jsx(t.Button,{variant:"outline",onClick:d,children:"Cancel"}),e.jsx(t.Button,{onClick:()=>n(o),disabled:!g(),children:"Save"})]})]})}function Fn({children:s,open:a,onOpenChange:n,joinPlan:r,availableDataSources:d,onRemove:i,onSave:l,onCancel:c}){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($a,{joinPlan:r,availableDataSources:d,onSave:l,onCancel:c,onRemove:i})]}),s]})}function Ka({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 d=[...s].sort((l,c)=>l.sequence-c.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"})]}),d.map(l=>{const c=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:c==null?void 0:c.type}),e.jsx("span",{className:"text-xs font-medium",children:c==null?void 0:c.name})]})]},l.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",s.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...s].sort((d,i)=>d.sequence-i.sequence).map((d,i)=>{const l=n.find(m=>m.name===d.source.name),c=n.find(m=>m.name===d.target.name),o=d.joinKeyGroups.reduce((m,x)=>m+x.keys.length,0);return e.jsxs("div",{className:"rounded-md bg-muted p-2 text-left",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:i+1}),e.jsx(t.Badge,{variant:"outline",className:"shrink-0 text-xs",children:d.joinType}),e.jsxs(t.Badge,{variant:"outline",className:"ml-auto shrink-0 text-xs",children:[o," condition",o>1?"s":""]})]}),e.jsxs("div",{className:"mt-1 truncate pl-1 text-xs text-muted-foreground",children:[l==null?void 0:l.name," → ",c==null?void 0:c.name]})]},d.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function Ga({open:s,onOpenChange:a,variant:n="button"}={}){var E,O;const r=t.useEditorStore(C=>C.card),{autoJoinMetadata:d}=t.useEditorCardQuery(r),i=t.useEditorStore(C=>C.actions.updateCardConfig),l=((E=r==null?void 0:r.config)==null?void 0:E.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[c,o]=N.useState(!1),m=s!==void 0,x=m?s:c,b=m?a:o,h=((O=r==null?void 0:r.dataSource)==null?void 0:O.selectedEntities)||[],u=C=>{i(r.id,{...r==null?void 0:r.config,joinPlan:C}),b(!1)},p=()=>{i(r.id,{...r==null?void 0:r.config,joinPlan:void 0})},j=()=>{b(!1)},f=()=>{const C=[...l.joins].sort((D,y)=>D.sequence-y.sequence),k=l.baseEntity;if(!k.name)return"SELECT * FROM table -- Please select a base entity";let w=`SELECT *
|
|
165
|
-
FROM ${k.name}`;return C.forEach(D=>{const y=h.find(R=>R.name===D.target.name);if(!y)return;const A=D.joinKeyGroups.filter(R=>R.keys&&R.keys.length>0).map(R=>{const M=R.keys.filter(S=>{var F,v,L,I;return((F=S.source)==null?void 0:F.name)&&((v=S.target)==null?void 0:v.name)&&((L=S.source)==null?void 0:L.entityName)&&((I=S.target)==null?void 0:I.entityName)}).map(S=>`${S.source.entityName}.${S.source.name} ${S.operator} ${S.target.entityName}.${S.target.name}`);return M.length>1?`(${M.join(` ${R.operator} `)})`:M[0]}).filter(Boolean),g=A.length>1?A.join(" OR "):A[0]||"condition_here";w+=`
|
|
166
|
-
${D.joinType} JOIN ${y.name}
|
|
167
|
-
ON ${g}`}),w};if(h.length<2)return null;const T=l.joins.length>0&&e.jsx(t.TooltipContent,{side:"bottom",className:"ml-4 max-w-md overflow-hidden p-0",children:e.jsx(Ka,{joins:l.joins,baseEntityId:l.baseEntity.name,availableDataSources:h,generateSQLPreview:f})});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(),b(!0)},children:[e.jsx(t.Link,{className:"h-3 w-3"}),l.joins.length]}):e.jsxs("button",{type:"button",onClick:()=>b(!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"}`}),(d==null?void 0:d.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"]})]})}),T]})}),e.jsx(Fn,{open:x,onOpenChange:b,joinPlan:l,availableDataSources:h,onSave:u,onCancel:j,onRemove:p,children:e.jsx("div",{})})]})}function Ua(){var C,k,w,D,y,A;const[s,a]=N.useState(!1),[n,r]=N.useState(!1),[d,i]=N.useState(!1),l=t.useEditorStore(g=>g.card.dataSource),c=t.useEditorStore(g=>g.card),o=t.useEditorStore(g=>g.isDevMode),{updateDataSource:m}=t.useEditorActions(),{autoJoinMetadata:x}=t.useEditorCardQuery(c),h={...{connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},...l,selectedEntities:(l==null?void 0:l.selectedEntities)||[]},u=t.toEntityArray(h.selectedEntities),p=u.length,j=p===0?"Choose dataset":p===1?ts(u[0]):`${p} datasets`,f=((w=(k=(C=c==null?void 0:c.config)==null?void 0:C.joinPlan)==null?void 0:k.joins)==null?void 0:w.length)??0,T=!!(x!=null&&x.autoResolved);((y=(D=x==null?void 0:x.resolvedJoinPlan)==null?void 0:D.joins)==null?void 0:y.length)??((A=x==null?void 0:x.relationshipsUsed)==null||A.length);const E=p<2?null:f>0?`${f} join${f===1?"":"s"}`:T?"auto":null,O=g=>{const R=u.filter(M=>!t.areContextEntitiesEqual(M,g));m({...h,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:j}),E&&e.jsxs("span",{className:"shrink-0 text-[11px] text-muted-foreground",children:["· ",E]}),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:p})]}),p===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((g,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:ts(g)}),e.jsx("p",{className:"truncate text-[11px] text-muted-foreground",children:Ha(g)})]}),e.jsx("button",{type:"button",onClick:()=>O(g),"aria-label":`Remove ${ts(g)}`,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"})})]},`${g.connectionId}-${g.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"]})]}),p>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:f>0?`${f} ${f===1?"join":"joins"}`:"Configure joins"}),T&&f===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:h}),p>1&&!o&&e.jsx("div",{className:"hidden",children:e.jsx(Ga,{open:d,onOpenChange:i})})]})}function ts(s){return"label"in s&&s.label?s.label:s.name||"Dataset"}function Ha(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(Ua,{})}),e.jsx("div",{className:"min-h-0 flex-1",children:e.jsx(t.FieldsSection,{})}),e.jsx(_a,{open:a,onOpenChange:n})]})}const Qa=300;function Wa(){const s=t.useEditorStore(T=>T.card.sql),a=t.useEditorStore(T=>T.sqlGen),n=t.useEditorStore(T=>T.card),r=Ae.useEffectiveEditorCardType(),{setCardSql:d,setSqlGen:i,setRunSql:l}=t.useEditorActions(),c=N.useMemo(()=>r!==n.type?{...n,type:r}:n,[n,r]),{queryKey:o}=t.useEditorCardQuery(c),m=t.useQueryClient(),x=N.useRef(o);x.current=o;const b=N.useRef(a);b.current=a;const h=N.useCallback(T=>{d(T)},[d]),{value:u,onChange:p,flush:j}=Ln({storeValue:s,defaultValue:"",onStoreUpdate:h,delay:Qa});N.useEffect(()=>it.registerPendingEditorDraftFlusher(j),[j]);function f(T){p(T),t.isObjectEmpty(b.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:f,language:"sql-jinja",embedded:!0,flushGutter:!0,onKeyDown:T=>{T.key==="Enter"&&T.shiftKey&&(T.preventDefault(),it.flushPendingEditorDrafts(),setTimeout(()=>{m.removeQueries({queryKey:x.current,exact:!0}),l(!0)},0))}})]})}const Ja=300;function Ya(){const s=t.useEditorStore(h=>h.card.python),a=t.useEditorStore(h=>h.card),n=Ae.useEffectiveEditorCardType(),{setCardPython:r,setRunSql:d}=t.useEditorActions(),i=N.useMemo(()=>n!==a.type?{...a,type:n}:a,[a,n]),{queryKey:l}=t.useEditorCardQuery(i),c=t.useQueryClient(),o=N.useRef(l);o.current=l;const{value:m,onChange:x,flush:b}=Ln({storeValue:s,defaultValue:t.PYTHON_DEFAULT_CODE,onStoreUpdate:r,delay:Ja});return N.useEffect(()=>it.registerPendingEditorDraftFlusher(b),[b]),e.jsx(t.CodeEditor,{value:m??"",onValueChange:x,language:"python",embedded:!0,flushGutter:!0,onKeyDown:h=>{h.key==="Enter"&&h.shiftKey&&(h.preventDefault(),it.flushPendingEditorDrafts(),setTimeout(()=>{c.removeQueries({queryKey:o.current,exact:!0}),d(!0)},0))}})}const Xa=/\{\{-?\s*filters\s*\|\s*where\s*-?\}\}/i,Za=/\{\{-?\s*filters\s*\|\s*and\s*-?\}\}/i,er=/\bwhere\b/i;function tr(s){return s!=null&&s.trim()?Xa.test(s)||Za.test(s):!1}function sr(s){return!(s!=null&&s.trim())||tr(s)?null:er.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 nr(s){const{request:a,mode:n="draft",currentSql:r,selectedTableName:d,selectedSchemaName:i,selectedDatabaseName:l}=s,c=[l?`Database: ${l}`:"",i?`Schema: ${i}`:"",d?`Table: ${d}`:""].filter(Boolean);return["You are an expert SQL writing assistant embedded in a query editor.",`Write SQL only. You may call only read-only tools when needed: ${t.INLINE_ALLOWED_TOOL_LIST}.`,"Do not call mutation tools or chart-creation tools; those require Full Assistant.","Return exactly one SQL statement inside a single ```sql fenced block.","After the code block, optionally include one short sentence.",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.",c.length>0?`Context:
|
|
168
|
-
${c.join(`
|
|
169
|
-
`)}`:"",r?n==="refine"?`Current SQL (must refine):
|
|
170
|
-
${r}`:`Current SQL (revise if useful):
|
|
171
|
-
${r}`:"",`User request:
|
|
172
|
-
${a}`].filter(Boolean).join(`
|
|
173
|
-
|
|
174
|
-
`)}function ar(s){const{request:a,failedSql:n,errorMessage:r,errorCode:d,selectedDatabaseName:i,selectedSchemaName:l,selectedTableName:c,contextEntityLabels:o}=s,m=[i?`Database: ${i}`:"",l?`Schema: ${l}`:"",c?`Table: ${c}`:"",o.length>0?`Selected context entities: ${o.join(", ")}`:""].filter(Boolean);return["You are fixing SQL after validation failed.","Return one read-only SQL statement in a single ```sql fenced block.","Do not call mutation tools.",m.length>0?`Context:
|
|
175
|
-
${m.join(`
|
|
176
|
-
`)}`:"",`Original user request:
|
|
177
|
-
${a}`,`Previous SQL draft:
|
|
178
|
-
${n}`,`Validation failure${d?` (${d})`:""}:
|
|
179
|
-
${r}`].filter(Boolean).join(`
|
|
180
|
-
|
|
181
|
-
`)}function rr(s,a){typeof window>"u"||window.dispatchEvent(new CustomEvent("semaphor:inline-query-writer",{detail:{event:s,...a,timestamp:Date.now()}}))}const ss={runId:0,phase:"idle",attempt:0,activeStep:"",timelineSteps:[],lastValidation:null,finalOutcome:"idle",hasTools:!1};function lr(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 on(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 cn(s){return s==="getTableColumns"?"Discovering columns":s==="getDomainRelationships"?"Resolving relationships":s==="getChartSQLSyntax"?"Reviewing SQL syntax":s==="getUserSql"?"Inspecting current query":"Analyzing context"}function or(s,a){return s===t.SELF_HEAL_TIMELINE_STEP&&a>0?`${t.SELF_HEAL_TIMELINE_STEP} ${a}/${t.MAX_SELF_HEAL_ATTEMPTS}`:s}function Pt(s){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`${s}-${crypto.randomUUID()}`:`${s}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function dn(s){var a;for(let n=s.length-1;n>=0;n-=1){const r=s[n];if(r.role!=="user")continue;const d=(a=r.metadata)==null?void 0:a.inlineRunToken;if(typeof d=="string"&&d.length>0)return d}}function ir(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 un(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 d=n.parts[r];if((d==null?void 0:d.type)!=="text"||typeof(d==null?void 0:d.text)!="string")continue;const i=ir(d.text);if(i)return i}}return""}function cr({currentSql:s,currentPython:a,selectedDatabaseName:n,selectedSchemaName:r,selectedTableName:d,onApplySql:i,onOpenFullAssistant:l}){var Ft,Ct;const{authToken:c,tokenProps:o}=t.useSemaphorContext(),m=(Ft=t.useDashboardQuery().data)==null?void 0:Ft.assistantProfileId,x=t.useEditorStore(G=>G.isDevMode),b=t.useEditorStore(G=>G.selectedConnectionId),h=t.useEditorStore(G=>{var Y;return(Y=G.card.dataSource)==null?void 0:Y.selectedEntities}),u=t.useAIInteractionStore(G=>G.currentAIContext.selectedEntities),p=u.length,{setCurrentAIContext:j}=t.useAIActions(),[f,T]=N.useState(""),[E,O]=N.useState(""),[C,k]=N.useState(""),[w,D]=N.useState("draft"),[y,A]=N.useState("draft"),[g,R]=N.useState(""),[M,S]=N.useState(!1),[F,v]=N.useState({status:"idle"}),[L,I]=N.useState(ss),[P,V]=N.useState(!1),[z,B]=N.useState(()=>Pt("inline-query-session")),_=N.useRef(null),U=N.useRef(null),K=N.useRef(null),H=N.useRef(0),Z=N.useRef(0),de=N.useRef(Pt("inline-run-token")),ae=N.useRef(z),ce=N.useRef(new Set),me=N.useRef(new Map),he=N.useRef(0),Ne=N.useRef(""),we=N.useRef(!1),Ie=N.useRef(!1),X=N.useRef(ss),je=N.useRef(!1),ke=N.useRef(null),te=N.useRef(()=>{}),De=(Ct=o.apiServiceUrl)==null?void 0:Ct.replace(/\/$/,""),Me=De?`${De}/v1/sql/validate`:"/v1/sql/validate",le=N.useCallback(G=>{I(Y=>{const W=G(Y);return X.current=W,W})},[]),ve=N.useCallback((G,Y)=>{le(W=>W.runId===G?Y(W):W)},[le]),ge=N.useCallback(G=>Z.current===G&&!ce.current.has(G),[]),$=N.useCallback((G,Y,W)=>{ve(G,ie=>{const pe=ie.timelineSteps.includes(Y)?ie.timelineSteps:[...ie.timelineSteps,Y];return{...ie,phase:(W==null?void 0:W.phase)||ie.phase,attempt:typeof(W==null?void 0:W.attempt)=="number"?W.attempt:ie.attempt,activeStep:Y,timelineSteps:pe,finalOutcome:(W==null?void 0:W.finalOutcome)||ie.finalOutcome,hasTools:W!=null&&W.hasTools?!0:ie.hasTools}})},[ve]),ee=N.useCallback(()=>{const G=Z.current+1,Y=Pt("inline-run-token"),W=Pt("inline-query-session");return Z.current=G,de.current=Y,ae.current=W,B(W),ce.current=new Set,me.current=new Map,he.current=0,Ne.current="",je.current=!1,le(()=>({runId:G,phase:"drafting",attempt:0,activeStep:"Drafting SQL",timelineSteps:["Drafting SQL"],lastValidation:null,finalOutcome:"drafting",hasTools:!1})),{runId:G,runToken:Y,chatSessionId:W}},[le]),ue=N.useCallback(()=>{if(we.current||Ie.current||p>0)return;const G=h||[];if(G.length===0)return;const Y=t.useAIInteractionStore.getState().currentAIContext;j({...Y,selectedEntities:G}),Ie.current=!0},[p,h,j]),Se=N.useCallback(()=>{we.current=!0},[]),q=N.useCallback((G,Y,W)=>{rr(G,{runId:Y,attemptCount:typeof(W==null?void 0:W.attemptCount)=="number"?W.attemptCount:he.current,errorCode:W==null?void 0:W.errorCode,hasTools:typeof(W==null?void 0:W.hasTools)=="boolean"?W.hasTools:L.hasTools,entityCount:p,finalOutcome:(W==null?void 0:W.finalOutcome)||L.finalOutcome})},[p,L.finalOutcome,L.hasTools]),se=N.useCallback((G,Y)=>{const W=K.current;if(!W)return;const ie={inlineRunToken:Y};W({role:"user",parts:[{type:"text",text:G}],metadata:ie},{metadata:ie})},[]);N.useEffect(()=>{const G=ke.current;!G||G.sessionId!==z||(ke.current=null,se(G.message,G.runToken))},[z,se]);const oe=z,be=N.useCallback(async({toolCall:G})=>{var Pe,We,rt,st,ze,ft;if(oe!==ae.current)return;const Y=String(G.toolName||"").trim();if(!Y)return;const W=Z.current;if(!ge(W)){(Pe=U.current)==null||Pe.call(U,{tool:Y,toolCallId:G.toolCallId,output:{status:"error",message:"Inline run is no longer active; ignoring tool output."}});return}if(Y==="getUserSql"){$(W,cn(Y),{hasTools:!0}),q("inline_tool_step",W,{hasTools:!0}),(We=U.current)==null||We.call(U,{tool:Y,toolCallId:G.toolCallId,output:{status:"success",sql:s||"",python:a||""}});return}const ie=t.INLINE_BLOCKED_MUTATING_TOOLS.has(Y),pe=t.INLINE_ALLOWED_READ_ONLY_TOOLS.has(Y);if(ie||!pe){(rt=U.current)==null||rt.call(U,{tool:Y,toolCallId:G.toolCallId,output:{status:"error",message:"This action is unavailable in inline draft mode. Open Full Assistant for this action."}});return}const fe=cn(Y);$(W,fe,{phase:L.phase==="self-healing"?"self-healing":"drafting",hasTools:!0}),q("inline_tool_step",W,{hasTools:!0});const Fe=((st=G.input)==null?void 0:st.sql)??((ze=G.args)==null?void 0:ze.sql);typeof Fe=="string"&&Fe.trim().length>0&&(je.current=!1,k(Fe.trim())),(ft=U.current)==null||ft.call(U,{tool:Y,toolCallId:G.toolCallId,output:{status:"success",message:"Read-only tool result received."}})},[a,s,q,L.phase,ge,oe,$]),ye=N.useCallback(({message:G,messages:Y})=>{if(oe!==ae.current)return;const W=dn(Y);if(!W||W!==de.current)return;const ie=Z.current;if(!ge(ie))return;const pe=un([G])||un(Y);if(pe){je.current=!1,k(pe.trim());return}je.current&&X.current.phase==="self-healing"&&te.current(ie)},[ge,oe]),Oe=N.useCallback(G=>{if(oe!==ae.current)return;const Y=Z.current;ge(Y)&&je.current&&X.current.phase==="self-healing"&&te.current(Y)},[ge,oe]),{setMessages:Ve,sendMessage:Ge,addToolResult:Je,status:Ye,stop:ne,error:Ee,clearError:Be}=t.useChat({id:z,transport:new t.DefaultChatTransport({api:`${o.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${c==null?void 0:c.accessToken}`}),body:()=>{const G=t.useAIInteractionStore.getState();return{assistantId:"editor-assistant",assistantProfileId:m,isDevMode:x,aiContext:G.currentAIContext,reasoningEffort:G.reasoningEffort,showReasoning:!1}},credentials:"omit",prepareSendMessagesRequest:({messages:G,body:Y,requestMetadata:W})=>{const ie=W==null?void 0:W.inlineRunToken,pe=dn(G);return{body:{...Y,inlineRunToken:ie||pe,messages:t.cleanupIncompleteMessages(G)}}}}),onToolCall:be,onFinish:ye,onError:Oe,sendAutomaticallyWhen:t.lastAssistantMessageIsCompleteWithToolCalls});U.current=Je,K.current=Ge;const Ce=!["ready","error"].includes(Ye),Ue=(Ee==null?void 0:Ee.message)||"Unable to generate a SQL draft right now. Try again.",Te=N.useCallback(G=>{const Y=Z.current,W=X.current.phase;if(!(W==="drafting"||W==="self-healing"||W==="validating")){G==="stopped"&&Ce&&ne();return}ce.current.add(Y),je.current=!1,H.current+=1,Ne.current="",v({status:"idle"}),k(""),Be(),Ve([]),ve(Y,pe=>({...pe,phase:"idle",activeStep:"",finalOutcome:"cancelled"})),q("inline_self_heal_stopped",Y,{finalOutcome:"cancelled"}),(Ce||G==="stopped")&&ne()},[Be,q,Ce,Ve,ne,ve]),vt=N.useCallback(async(G,Y)=>{var ie;if(!ge(Y))return null;const W=H.current+1;H.current=W,$(Y,"Validating SQL",{phase:"validating"}),v({status:"validating"});try{const pe=await t.postRequestRegular(Me,(c==null?void 0:c.accessToken)||"",{sql:G,connectionId:b||void 0});if(H.current!==W||!ge(Y))return null;if((pe==null?void 0:pe.valid)===!0)return v({status:"valid",message:"SQL validation passed."}),ve(Y,Pe=>({...Pe,phase:"ready",finalOutcome:"validated",lastValidation:{valid:!0}})),q("inline_draft_validated",Y,{finalOutcome:"validated"}),{status:"valid"};const fe=lr(pe==null?void 0:pe.errorCode)||"UNKNOWN",Fe=typeof(pe==null?void 0:pe.error)=="string"&&pe.error||typeof((ie=pe==null?void 0:pe.details)==null?void 0:ie.error)=="string"&&pe.details.error||"SQL validation failed. Please revise the query draft.";return v({status:"invalid",message:Fe,errorCode:fe}),ve(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!==W||!ge(Y))return null;const fe=t.getRequestErrorMessage(pe,"Validation service unavailable. You can still replace and run.");return v({status:"error",message:fe,errorCode:"SQL_CONNECTION_ERROR"}),ve(Y,Fe=>({...Fe,phase:"error",finalOutcome:"error",lastValidation:{valid:!1,error:fe,errorCode:"SQL_CONNECTION_ERROR"}})),{status:"error",error:fe,errorCode:"SQL_CONNECTION_ERROR"}}},[c==null?void 0:c.accessToken,q,ge,b,Me,ve,$]),Xe=N.useCallback((G,Y,W,ie)=>{let pe=W,fe="validation_failed",Fe="Validating SQL";Y==="attempt_limit"?(pe=`Couldn't auto-fix after ${t.MAX_SELF_HEAL_ATTEMPTS} attempts. ${W}`,fe="self_heal_exhausted",Fe=`Auto-fix stopped (${t.MAX_SELF_HEAL_ATTEMPTS} attempts)`):Y==="duplicate"&&(pe=`Auto-fix stopped (repeated validation failure). ${W}`,fe="self_heal_duplicate_stopped",Fe="Auto-fix stopped (repeated failure)"),v({status:"invalid",message:pe,errorCode:ie}),$(G,Fe,{phase:"error",finalOutcome:fe}),ve(G,Pe=>({...Pe,phase:"error",finalOutcome:fe,lastValidation:{valid:!1,error:pe,errorCode:ie}})),Y!=="terminal"&&q("inline_self_heal_stopped",G,{errorCode:ie,finalOutcome:fe}),je.current=!1},[q,ve,$]),It=N.useCallback(G=>{const Y="Auto-fix stopped (no SQL returned). Open Full Assistant to continue.",W="self_heal_no_draft";v({status:"invalid",message:Y,errorCode:"UNKNOWN"}),$(G,"Auto-fix stopped (no SQL returned)",{phase:"error",finalOutcome:W}),ve(G,ie=>({...ie,phase:"error",finalOutcome:W,lastValidation:{valid:!1,error:Y,errorCode:"UNKNOWN"}})),q("inline_self_heal_stopped",G,{errorCode:"UNKNOWN",finalOutcome:W}),je.current=!1},[q,ve,$]);te.current=It,N.useEffect(()=>{const G=C.trim(),Y=Z.current;if(!G){if(H.current+=1,Ne.current="",X.current.phase==="error")return;v({status:"idle"});return}if(!ge(Y)||Ce)return;const W=`${Y}:${he.current}:${on(G)}`;if(Ne.current===W)return;Ne.current=W;let ie=!1;return(async()=>{const fe=await vt(G,Y);if(!fe||ie||!ge(Y)||fe.status!=="invalid")return;if(!t.RECOVERABLE_SQL_ERROR_CODES.has(fe.errorCode)){Xe(Y,"terminal",fe.error,fe.errorCode);return}const Fe=`${on(G)}::${fe.errorCode}`,Pe=(me.current.get(Fe)||0)+1;if(me.current.set(Fe,Pe),Pe>=2){Xe(Y,"duplicate",fe.error,fe.errorCode);return}if(he.current>=t.MAX_SELF_HEAL_ATTEMPTS){Xe(Y,"attempt_limit",fe.error,fe.errorCode);return}const We=he.current+1;he.current=We,$(Y,t.SELF_HEAL_TIMELINE_STEP,{phase:"self-healing",attempt:We}),q("inline_self_heal_attempt",Y,{attemptCount:We,errorCode:fe.errorCode}),je.current=!0,Be(),Ve([]),k("");const rt=u.map(ze=>{const ft=ze!=null&&ze.database?`${ze.database}.`:"",Yt=ze!=null&&ze.schema?`${ze.schema}.`:"",Xt=(ze==null?void 0:ze.name)||"unknown";return`${ft}${Yt}${Xt}`}),st=ar({request:E,failedSql:G,errorMessage:fe.error,errorCode:fe.errorCode,selectedDatabaseName:n||"",selectedSchemaName:r||"",selectedTableName:d||"",contextEntityLabels:rt});se(st,de.current)})(),()=>{ie=!0}},[Be,u,q,Ce,ge,E,C,n,r,d,se,Ve,Xe,$,vt]);const He=(s==null?void 0:s.trim())||"",kt=N.useCallback((G="draft")=>{if(Ce)return;const Y=f.trim();if(!Y)return;const W=G==="refine"&&He?"refine":"draft",ie=W==="refine"?He:"",pe=He,{runId:fe,runToken:Fe,chatSessionId:Pe}=ee();q("inline_draft_started",fe,{attemptCount:0,hasTools:!1,finalOutcome:"drafting"}),ue(),Be(),O(Y),k(""),D(W),R(ie),S(!1),v({status:"idle"}),H.current+=1,Ve([]),V(!0);const We=nr({request:Y,mode:W,currentSql:pe,selectedTableName:d||"",selectedSchemaName:r||"",selectedDatabaseName:n||""});ke.current={sessionId:Pe,message:We,runToken:Fe}},[ee,Be,He,q,Ce,f,ue,n,r,d,Ve]),ct=N.useCallback(G=>{const Y=C.trim();Y&&(i(Y,G),G||V(!1))},[i,C]),Ze=C.trim().length>0,Dt=["valid","invalid","error"].includes(F.status),yt=Ze&&Dt,Ut=F.status==="invalid",At=F.status==="validating",dt=Ze&&E.length>0&&E===f.trim(),ut=He.length>0,mt=f.length>0,xt=dt&&w==="draft",$e=dt&&w==="refine"&&g===He,et=y==="refine"&&!ut?"draft":y,tt=(et==="refine"?$e:xt)?"Open composer preview":"Generate composer SQL",Mt=f.trim().length>0||E.trim().length>0||Ze||F.status!=="idle"||L.timelineSteps.length>0,Nt=N.useCallback((G="draft")=>{if(Ce)return;if((G==="refine"?$e:xt)&&!P){ue(),V(!0);return}kt(G)},[xt,$e,kt,Ce,P,ue]),ht=N.useCallback(()=>{ue(),V(!0)},[ue]),Qt=N.useCallback(G=>{Te("cancelled"),T(G)},[Te]),Wt=N.useCallback(()=>{Ce||(Te("cancelled"),je.current=!1,H.current+=1,Ne.current="",he.current=0,T(""),O(""),k(""),D("draft"),A("draft"),R(""),S(!1),v({status:"idle"}),Be(),Ve([]),le(G=>({...ss,runId:G.runId})))},[Te,Be,Ce,Ve,le]),Jt=N.useCallback(G=>{G||Te("cancelled"),V(G)},[Te]),Ke=L.timelineSteps.findIndex(G=>G===L.activeStep),Lt=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.Sparkles,{className:"pointer-events-none absolute left-2.5 top-1/2 h-3 w-3 -translate-y-1/2 text-muted-foreground",strokeWidth:1.75}),e.jsx(t.Input,{value:f,onChange:G=>Qt(G.target.value),onFocus:ht,onClick:ht,onKeyDown:G=>{G.key==="Enter"&&(G.preventDefault(),Nt(et))},placeholder:"Ask in plain English — e.g. top 10 customers by profit last quarter",className:["h-7 rounded-[5px] border border-border/60 bg-background pl-7 text-[12px] shadow-none placeholder:text-muted-foreground/70 focus-visible:border-ring focus-visible:ring-0",mt?"pr-[56px]":"pr-9"].join(" ")}),e.jsxs(t.Popover,{open:P,onOpenChange:Jt,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:G=>{G.preventDefault(),Te("cancelled"),T("")},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:G=>{G.preventDefault(),Nt(et)},disabled:Ce,"aria-label":tt,title:tt,children:e.jsx(Ma,{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:G=>{G.preventDefault()},onInteractOutside:G=>{var W;const Y=G.target;Y&&((W=_.current)!=null&&W.contains(Y))&&G.preventDefault()},children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[13px] font-medium",children:"Composer"}),E&&e.jsx("p",{className:"line-clamp-2 text-[11px] text-muted-foreground",children:E})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"inline-flex h-7 items-center rounded-[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:()=>{A("draft"),S(!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:()=>A("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:()=>{Te("stopped")},children:"Stop"}),!Ce&&e.jsx(t.Button,{variant:"ghost",size:"xs",onClick:Wt,disabled:!Mt,children:"Clear"})]})]}),L.timelineSteps.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[L.timelineSteps.map((G,Y)=>{const W=G===L.activeStep&&["drafting","validating","self-healing"].includes(L.phase),ie=!W&&Ke>=0&&Y<Ke;return e.jsx("span",{className:["rounded-full border px-2 py-0.5 text-[11px]",W?"border-foreground/30 bg-foreground/10 text-foreground":ie?"border-border/60 bg-muted/20 text-muted-foreground":"border-border/50 bg-background text-muted-foreground/80"].join(" "),children:or(G,L.attempt)},`${G}-${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:Se})}),(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"}),Lt]}),Ee&&e.jsx("div",{className:"rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-xs text-destructive",children:Ue}),w==="refine"&&g&&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:()=>S(G=>!G),children:M?"Hide base SQL":"View base SQL"})]}),M&&e.jsx("div",{className:"max-h-[120px] overflow-auto rounded-[5px] border border-border/60",children:e.jsx(t.CodeHighlighter,{code:g,language:"sql"})})]}),yt?e.jsxs("div",{className:"space-y-1",children:[w==="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||!yt,onClick:()=>ct(!1),children:"Replace SQL"}),e.jsx(t.Button,{size:"xs",disabled:Ce||!yt||At||Ut,onClick:()=>ct(!0),children:"Replace & Run"})]})]})})]})]})}function dr(){var we,Ie;const s=t.useQueryClient(),[a,n]=N.useState(!1),r=t.useEditorStore(X=>X.frame),d=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 c=t.useEditorStore(X=>X.selectedTableName),o=t.useDashboardStore(X=>{var je,ke;return((ke=(je=X.dashboard)==null?void 0:je.filters)==null?void 0:ke.length)??0}),m=t.useEditorStore(X=>X.inlineFilterValuesMap[(d==null?void 0:d.id)??""]),x=N.useMemo(()=>t.findCustomVisualConfigCard(r,d),[r,d]),{manifest:b}=t.useCustomVisual(((we=x==null?void 0:x.customCardPreferences)==null?void 0:we.url)||""),h=N.useMemo(()=>{var X;return(X=b==null?void 0:b.visuals)==null?void 0:X.find(je=>{var ke;return je.name===((ke=x==null?void 0:x.customCardPreferences)==null?void 0:ke.componentName)})},[b,(Ie=x==null?void 0:x.customCardPreferences)==null?void 0:Ie.componentName]),u=t.resolveMultiInputType(x,h),p=N.useMemo(()=>t.getCustomVisualInputCards({frame:r,configCard:x,isMultiInputVisual:u==="multiple"}),[r,x,u]),j=N.useMemo(()=>{const X=p.findIndex(je=>(je==null?void 0:je.id)===(d==null?void 0:d.id));return X<0?-1:t.getSlotIndexForCard(d,X)},[p,d]),f=N.useMemo(()=>!x||u!=="multiple"||j<0?d.type:t.getEffectiveCardTypeForSlot(d,j,h==null?void 0:h.slots)??d.type,[x,u,j,d,h==null?void 0:h.slots]),T=N.useMemo(()=>f!==d.type?{...d,type:f}:d,[d,f]),E=N.useMemo(()=>o===0?null:sr(d==null?void 0:d.sql),[d==null?void 0:d.sql,o]),O=N.useRef(!0),{setCardCustomCfg:C,setQueryResultColumns:k,setCardSql:w,setTempQueryData:D,setPythonStdOut:y,setCardPreferences:A,setCardType:g,setCardPython:R,setShowAIDialog:M,setCard:S,updateCardInFrame:F}=t.useEditorActions();t.useEditorStore(X=>X.onSave),t.useEditorStore(X=>X.onClose),t.useEditorStore(X=>X.actions.setSqlGen);const v=t.useEditorStore(X=>X.runSql),L=t.useEditorStore(X=>X.actions.setRunSql),I=t.useEditorStore(X=>X.actions.setIsSqlRunning),{data:P,isLoading:V,isFetching:z,isSuccess:B,isError:_,error:U,errorSql:K,queryKey:H,refetch:Z,errorMessage:de}=t.useEditorCardQuery(T),ae=N.useRef(H);ae.current=H,N.useEffect(()=>{if(P&&(P.rowLimitExceeded&&t.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),y((P==null?void 0:P.output)||""),P.records.length>0)){const{dimensionKeys:X}=t.getKeys(P.records);k(X)}},[P,k,y]),N.useEffect(()=>{(V||z)&&I(!0),(_||B)&&I(!1),_&&(k([]),y(""))},[V,z,P,y,_,B,I,k,U]),N.useEffect(()=>{v&&(s.getQueryData(H)||Z(),L(!1))},[v,Z,L,H,s]);const ce=N.useRef(Z);ce.current=Z,N.useEffect(()=>{if(O.current){O.current=!1;return}ce.current()},[m]);function me(X,je){w(X),je&&L(!0)}function he(){return e.jsxs(t.ResizablePanelGroup,{className:"flex grow gap-2 px-4",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-full overflow-hidden rounded-[6px] border border-border bg-background",children:e.jsx(Wa,{})}),a&&e.jsx("code",{className:"absolute right-3 top-2 text-[10px] uppercase tracking-[0.08em] text-muted-foreground/70",children:"sql"})]}),a&&e.jsxs(e.Fragment,{children:[e.jsxs(t.PanelResizeHandle,{className:"group/divider relative my-1 flex h-6 w-full shrink-0 cursor-row-resize items-center gap-3 px-1 outline-none",children:[e.jsx("span",{className:"h-px flex-1 bg-border transition-colors group-hover/divider:bg-foreground/30"}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:[e.jsx(t.ArrowDown,{className:"h-3 w-3",strokeWidth:1.75}),"Post-process with Python"]}),e.jsx("span",{className:"h-px flex-1 bg-border transition-colors group-hover/divider:bg-foreground/30"}),e.jsx("button",{type:"button","aria-label":"Close Python editor",onClick:X=>{X.stopPropagation(),n(!1)},onPointerDown:X=>X.stopPropagation(),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",strokeWidth:1.75})})]}),e.jsx(t.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:e.jsxs("div",{id:"python-container",className:"relative flex w-full flex-col overflow-hidden rounded-[6px] border border-border bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border bg-muted/30 px-3 py-1.5 text-[11px] text-muted-foreground",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"rounded-[3px] bg-background px-1.5 py-0.5 font-mono text-[10px] text-foreground/80",children:"Py"}),e.jsx("code",{className:"truncate font-mono text-[11px] text-foreground/80",children:"def process(df) → df"}),e.jsx("span",{className:"hidden truncate text-muted-foreground/80 sm:inline",children:"Runs after SQL · receives a DataFrame"})]}),e.jsx("span",{className:"shrink-0 font-mono text-[10px] uppercase tracking-[0.08em] text-muted-foreground/70",children:"Python 3.11"})]}),e.jsx("div",{className:"relative flex flex-1",children:e.jsx(Ya,{})})]})})]})]})}function Ne(){return e.jsxs("div",{role:"editor-controls",className:"flex w-full flex-wrap items-center gap-2 px-4 pb-2 pt-3",children:[E&&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("button",{type:"button",title:"Click to copy",onClick:()=>{var X;typeof navigator>"u"||!((X=navigator.clipboard)!=null&&X.writeText)||navigator.clipboard.writeText(E.helper).then(()=>t.ue.success("Copied to clipboard")).catch(()=>t.ue.error("Failed to copy"))},className:"cursor-pointer rounded-[4px] bg-muted px-1 py-0.5 font-mono text-[10px] text-foreground transition-colors hover:bg-muted-foreground/20",children:E.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||z,onClick:()=>{it.flushPendingEditorDrafts(),setTimeout(()=>{s.removeQueries({queryKey:ae.current,exact:!0}),L(!0)},0)},className:"shrink-0",size:"xs",children:[V||z?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"]}),e.jsx(Ae.EditorClearButton,{}),e.jsxs(t.Toggle,{pressed:a,onPressedChange:X=>n(X),title:a?"Remove Python post-processor":"Add a Python step to post-process the SQL result",className:"h-7 gap-1.5 rounded-[5px] px-2.5 text-[12px]",size:"sm",variant:"outline",children:[e.jsx("span",{className:"inline-flex h-3 w-3 items-center justify-center rounded-[2px] bg-muted font-mono text-[8px] font-bold text-muted-foreground",children:"Py"}),"Python",a?e.jsx(t.Check,{className:"h-3 w-3",strokeWidth:1.75}):e.jsx(t.Plus,{className:"h-3 w-3 text-muted-foreground",strokeWidth:1.75})]}),e.jsx(cr,{currentSql:d==null?void 0:d.sql,currentPython:d==null?void 0:d.python,selectedDatabaseName:i,selectedSchemaName:l,selectedTableName:c,onApplySql:me,onOpenFullAssistant:()=>M(!0)})]})]})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsxs("div",{className:"flex shrink-0 flex-col gap-1.5 px-4 pb-3 pt-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(t.EditableText,{value:d.title,onSave:X=>S({...d,title:X}),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:d})]}),e.jsx(t.EditableText,{value:(d.description||"").trim(),onSave:X=>S({...d,description:X.trim()}),isEditable:!0,placeholder:"Add description",displayClassName:"text-[12px] leading-snug text-muted-foreground",inputClassName:"text-[12px] leading-snug"})]}),e.jsx("div",{className:"relative flex grow overflow-y-scroll",children:he()}),Ne()]})}function ur(s,a){var i;let n=0,r=0;const d=Math.min(s.length,50);for(let l=0;l<d;l++){const c=(i=s[l])==null?void 0:i[a];if(!(c==null||c==="")){if(r++,typeof c=="number"||typeof c=="bigint")n++;else if(typeof c=="boolean")return"boolean"}}return r===0?"null":n/r>.7?"number":"text"}function mr(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 xr({data:s,card:a,paginationMetadata:n,onPaginationChange:r,onPageSizePreferenceChange:d,onSortChange:i,isLoading:l}){var y,A,g,R,M,S;const c=N.useMemo(()=>Object.keys(s[0]??{}),[s]),o=a.sql&&!((A=(y=a.preferences)==null?void 0:y.tablePrefs)!=null&&A.enableDevModePagination)?(R=(g=a.preferences)==null?void 0:g.tablePrefs)==null?void 0:R.pageSize:void 0,m=N.useMemo(()=>{var F;return t.sortByColumnsToSortState((F=a.config)==null?void 0:F.sortByColumns)},[(M=a.config)==null?void 0:M.sortByColumns]),{canSort:x,canUseLocalSorting:b,handlePaginationChange:h,handleSortChange:u,pagination:p,paginationMode:j,sorting:f}=t.useTableQueryState({card:a,dataLength:s.length,onPaginationChange:r,onSortChange:i,pageSize:o,paginationMetadata:n,sortState:m}),T=N.useMemo(()=>f.filter(F=>c.includes(F.id)),[f,c]),E=N.useMemo(()=>{const F={};for(const v of c)F[v]=ur(s,v);return F},[c,s]),O=N.useMemo(()=>c.map(F=>{const L=E[F]==="number";return{accessorKey:F,enableSorting:x,header:({column:I})=>{const P=I.getIsSorted();return e.jsxs("div",{className:t.cn("flex select-none items-center gap-1.5 transition-colors",I.getCanSort()&&"cursor-pointer hover:text-foreground",L&&"justify-end"),onClick:()=>I.getCanSort()&&I.toggleSorting(I.getIsSorted()==="asc"),children:[e.jsx("span",{children:F}),P==="asc"?e.jsx(t.ArrowUpIcon,{className:"h-3.5 w-3.5 shrink-0 text-foreground"}):P==="desc"?e.jsx(t.ArrowDownIcon,{className:"h-3.5 w-3.5 shrink-0 text-foreground"}):I.getCanSort()?e.jsx(t.ChevronsUpDown,{className:"h-3 w-3 shrink-0 opacity-0 transition-opacity group-hover/header:opacity-50"}):null]})},cell:({getValue:I})=>{const P=I(),V=P===null;return e.jsx("div",{className:t.cn("whitespace-pre-wrap break-all",L&&"text-right tabular-nums",V&&"text-muted-foreground/50 italic"),children:mr(P)})}}}),[x,E,c]),C=Math.max(O.length,1),k=t.useReactTable({data:s,columns:O,getCoreRowModel:t.getCoreRowModel(),getPaginationRowModel:j==="client"?t.getPaginationRowModel():void 0,onSortingChange:u,getSortedRowModel:b?t.getSortedRowModel():void 0,onPaginationChange:j==="disabled"?void 0:h,manualPagination:j==="server"||j==="disabled",manualSorting:!b,pageCount:j==="server"&&n?n.pageCount:void 0,state:{sorting:T,pagination:p}}),w=j==="server"&&n?n.totalCount:s.length,D=j!=="disabled"&&(j==="server"||w>10);return e.jsxs("div",{className:"relative flex h-full w-full min-h-0 flex-col",children:[l&&e.jsx("div",{className:"absolute inset-0 z-20 flex items-center justify-center bg-background/50",children:e.jsx(t.LoaderCircle,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),e.jsxs(t.CustomScrollArea,{className:"min-h-0 grow overflow-auto text-foreground",children:[e.jsxs("table",{className:"w-full",children:[e.jsx(t.TableHeader,{className:"sticky top-0 z-10",children:k.getHeaderGroups().map(F=>e.jsx(t.TableRow,{className:"border-b-0 hover:bg-transparent",children:F.headers.map(v=>{const I=E[v.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",I&&"text-right"),children:v.isPlaceholder?null:t.flexRender(v.column.columnDef.header,v.getContext())},v.id)})},F.id))}),e.jsx(t.TableBody,{className:"font-mono",children:(S=k.getRowModel().rows)!=null&&S.length?k.getRowModel().rows.map((F,v)=>e.jsx(t.TableRow,{className:t.cn("h-[34px] border-b border-border/40 transition-colors",v%2===1&&"bg-muted/20"),"data-state":F.getIsSelected()&&"selected",children:F.getVisibleCells().map(L=>{const P=E[L.column.id]==="number";return e.jsx(t.TableCell,{className:t.cn("px-3 py-1.5 text-xs",P&&"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:D?e.jsx(t.DataTablePagination,{totalColumns:c.length,pageCount:j==="server"&&n?n.pageCount:k.getPageCount(),pageIndex:k.getState().pagination.pageIndex,pageSize:k.getState().pagination.pageSize,rowCount:w,selectedRowCount:0,setPageIndex:k.setPageIndex,setPageSize:k.setPageSize,canPreviousPage:j==="server"&&n?n.hasPrevPage:k.getCanPreviousPage(),canNextPage:j==="server"&&n?n.hasNextPage:k.getCanNextPage(),previousPage:k.previousPage,nextPage:k.nextPage,onPageSizePreferenceChange:d,onClearSelection:()=>{},paginationMode:j,showExport:!1}):e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-[11px] tabular-nums text-muted-foreground",children:[w.toLocaleString()," ",w===1?"row":"rows"," · ",c.length," ",c.length===1?"column":"columns"]}),T.length>0&&e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["Sorted by"," ",e.jsx("span",{className:"font-medium text-foreground/70",children:T[0].id})," ",T[0].desc?"↓":"↑"]})]})})]})}const mn=[{value:"table",label:"Table"},{value:"aggregateTable",label:"Aggregate"},{value:"pivotTable",label:"Pivot"},{value:"detailTable",label:"Detail"}];function hr({className:s}){const a=t.useEditorStore(u=>u.card),n=t.useEditorStore(u=>u.frame),r=t.useEditorStore(u=>u.editorContext),d=Ae.useEffectiveEditorCardType(),{setCard:i,updateCardInFrame:l}=t.useEditorActions(),c=(r==null?void 0:r.type)==="documentSection"?mn.filter(u=>["table","pivotTable"].includes(u.value)):mn,o=["table","aggregateTable","pivotTable","detailTable"].includes(d),m=t.hasValidCardConfig(a.config),x=t.isCustomVisualConfigCard(a,n.cards);if(!o||!m||x)return null;const b=u=>{if(u===d||x)return;const p=u,j=a.config??{},f=h(d,p,j),T={...a,type:p,config:f};i(T),l(T)},h=(u,p,j)=>{var T;if(u===p)return j;if(p==="detailTable"){const E=w=>w==null?void 0:w.toLowerCase().replace(/\s+/g,"").trim(),O=(w,D)=>{const y=[E(w.label),E(w.qualifiedFieldName),E(w.name)].filter(Boolean),A=[E(D.label),E(D.qualifiedFieldName),E(D.name)].filter(Boolean);return y.some(g=>A.includes(g))},C=(j.groupByColumns||[]).map(w=>({...w,role:"detail"})),k=((T=j.sortByColumns)==null?void 0:T.filter(w=>C.some(D=>O(w,D))))??[];return{...j,detailTableBackup:{groupByColumns:j.groupByColumns,metricColumns:j.metricColumns,pivotByColumns:j.pivotByColumns,sortByColumns:j.sortByColumns,rowAggregates:j.rowAggregates,columnAggregates:j.columnAggregates,comparisonType:j.comparisonType},detailColumns:C,groupByColumns:[],metricColumns:[],pivotByColumns:[],sortByColumns:k,rowAggregates:[],columnAggregates:[],comparisonType:"none"}}let f=j;if(u==="detailTable")if(j.detailTableBackup)f={...j,...j.detailTableBackup,detailColumns:[],detailTableBackup:void 0};else{const E=(j.detailColumns||[]).map(O=>({...O,role:"groupby"}));f={...j,groupByColumns:E,detailColumns:[]}}return p==="aggregateTable"?{...f,pivotByColumns:[]}:f};return e.jsx("div",{role:"tablist",className:t.cn("flex items-center gap-5",s),children:c.map(u=>{const p=d===u.value;return e.jsx("button",{type:"button",role:"tab","aria-selected":p,onClick:()=>b(u.value),className:t.cn("-mb-px flex h-9 items-center border-b-2 text-[12px] transition-colors",p?"border-foreground font-medium text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),children:u.label},u.value)})})}const xn="text-[11px] text-muted-foreground underline-offset-2 hover:text-foreground hover:underline";function hs({error:s,errorSql:a,errorTitle:n="Unable to load data",onOpenInEditor:r,onDebugWithAssistant:d,onSendFeedback:i,showFeedbackButton:l=!0,className:c}){const[o,m]=N.useState(!1),h=!!d||!!(r&&a);return e.jsxs("div",{className:t.cn("w-full space-y-3 rounded-[6px] border border-border/60 bg-card p-4",c),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})})]}),h&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[d&&e.jsxs(t.Button,{variant:"outline",size:"xs",onClick:d,children:[e.jsx(Ca,{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:xn,children:o?"Hide query details":"Show query details"}),l&&i&&e.jsx("button",{type:"button",onClick:i,className:xn,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 On(s,a){const n=t.useEditorStore(m=>m.card),r=t.useEditorStore(m=>m.isDevMode),{switchEditorMode:d,setRunSql:i,runAssistant:l}=t.useEditorActions();return{isDevMode:r,handleOpenInEditor:r?void 0:()=>{const m=a||n.sql||n.python||"";d("dev",{sqlToLoad:m}),setTimeout(()=>{i(!0)},100)},handleDebugWithAssistant:r?()=>{const m=`Can you help me debug this query?
|
|
182
|
-
|
|
183
|
-
Error:
|
|
184
|
-
|
|
185
|
-
${s}
|
|
186
|
-
|
|
187
|
-
Error SQL:
|
|
188
|
-
|
|
189
|
-
${a||n.sql||n.python}
|
|
190
|
-
|
|
191
|
-
`;l(m)}:void 0}}function Pn({className:s,...a}){var ge,$,ee,ue,Se;const n=t.useEditorStore(q=>q.card),d=t.useEditorStore(q=>q.isDevMode)?!1:((ge=n.customCardPreferences)==null?void 0:ge.showCardHeader)??!0,i=((ee=($=n.preferences)==null?void 0:$.displayOptions)==null?void 0:ee.showInlineFilterBar)??!0,l=t.useEditorStore(q=>q.frame),c=t.useEditorStore(q=>q.inlineFilterValuesMap[n.id]),o=t.useDashboardStore(q=>q.dashboard.filters),m=t.useDashboardStore(q=>q.selectedSheetId),[x,b]=N.useState(!1),{currentUser:h}=t.useCurrentUserInfo(),{tokenProps:u}=N.useContext(t.SemaphorContext),p=t.useEditorStore(q=>q.actions.setRunSql),j=t.useEditorStore(q=>q.actions.setCardInlineFilterValue),f=t.useEditorStore(q=>q.actions.removeCardInlineFilterValue),{updateFilter:T}=t.useDashboardActions(),E=o==null?void 0:o.find(q=>q.id===l.filterId),O=N.useMemo(()=>t.findCustomVisualConfigCard(l,n),[l,n]),{manifest:C}=t.useCustomVisual(((ue=O==null?void 0:O.customCardPreferences)==null?void 0:ue.url)||""),k=N.useMemo(()=>{var q;return(q=C==null?void 0:C.visuals)==null?void 0:q.find(se=>{var oe;return se.name===((oe=O==null?void 0:O.customCardPreferences)==null?void 0:oe.componentName)})},[C,(Se=O==null?void 0:O.customCardPreferences)==null?void 0:Se.componentName]),w=t.resolveMultiInputType(O,k),D=N.useMemo(()=>t.getCustomVisualInputCards({frame:l,configCard:O,isMultiInputVisual:w==="multiple"}),[l,O,w]),y=N.useMemo(()=>{const q=D.findIndex(se=>(se==null?void 0:se.id)===(n==null?void 0:n.id));return q<0?-1:t.getSlotIndexForCard(n,q)},[D,n]),A=N.useMemo(()=>!O||w!=="multiple"||y<0?n.type:t.getEffectiveCardTypeForSlot(n,y,k==null?void 0:k.slots)??n.type,[O,w,y,n,k==null?void 0:k.slots]),g=A??n.type,R=N.useMemo(()=>g===n.type?n:{...n,type:g},[n,g]),M=N.useMemo(()=>A!==n.type?{...n,type:A}:n,[n,A]),{data:S,isLoading:F,isFetching:v,errorMessage:L,errorSql:I,pagination:P}=t.useEditorCardQuery(M),{handleOpenInEditor:V,handleDebugWithAssistant:z}=On(L,I||n.sql||n.python),B=N.useMemo(()=>(S==null?void 0:S.records)||[],[S==null?void 0:S.records]),{setCard:_,updateCardInFrame:U}=t.useEditorActions(),{data:K}=t.useTopoJson(R),H=R.id,Z=R.config,de=R.interactionConfig,ae=R.customCfg,ce=R.preferences,me=R.queryConfig,he=!!R.sql,Ne=S==null?void 0:S.records,we=N.useMemo(()=>({id:H,type:g,config:Z,interactionConfig:de,sql:he?"__editor_sql__":""}),[H,g,Z,de,he]),Ie=N.useMemo(()=>{var q;return g!=="pivotTable"||!((q=S==null?void 0:S.records)!=null&&q.length)?null:{records:S.records,columnSubtotalMeta:S.columnSubtotalMeta,subtotalColumns:S.subtotalColumns||[],pivotSchema:S.pivotSchema||[],groupByColumns:S.groupByColumns}},[g,S==null?void 0:S.records,S==null?void 0:S.columnSubtotalMeta,S==null?void 0:S.subtotalColumns,S==null?void 0:S.pivotSchema,S==null?void 0:S.groupByColumns]),X=t.usePivotTableConfig(R,Ie),je=()=>{b(!0)},ke=N.useMemo(()=>{const q=typeof window<"u"?window.location.href:"",se=typeof navigator<"u"?navigator.userAgent:"",oe=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:t.FeedbackCategory.QUERY_GENERATION,user:h,tokenContext:u,systemState:{cardConfig:n.config,dataSource:n.dataSource,dashboardFilters:o,errorMessage:L||void 0,errorSql:I||n.sql||n.python,generatedSql:I||n.sql},metadata:{url:q,userAgent:se,timestamp:new Date().toISOString(),viewport:oe}}},[h,u,n,o,L,I]),te=(q,se)=>{var be,ye;const oe={...n,paginationConfig:{page:q+1,pageSize:se}};_(oe),U(oe),n.sql&&((ye=(be=n.preferences)==null?void 0:be.tablePrefs)!=null&&ye.enableDevModePagination)&&p(!0)},De=q=>{var be,ye,Oe,Ve,Ge;const se=t.sortStateToSortByColumns(q,(be=n.config)==null?void 0:be.metricColumns,(ye=n.config)==null?void 0:ye.groupByColumns,(Oe=n.config)==null?void 0:Oe.detailColumns),oe={...n,config:{...n.config||{},sortByColumns:se}};_(oe),U(oe),n.sql&&((Ge=(Ve=n.preferences)==null?void 0:Ve.tablePrefs)!=null&&Ge.enableDevModePagination)&&p(!0)},Me=N.useMemo(()=>!H||!Ne?null:t.createChartConfig({card:we,data:Ne,cardType:g,queryConfig:me,customCfg:ae,preferences:ce,topoJson:K}),[we,H,ae,ce,me,Ne,g,K]);function le(q){return e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackVisual,children:e.jsx(t.EditorCustomVisual,{card:q})})}function ve(){var q;if(S!=null&&S.records&&(S==null?void 0:S.records.length)===0&&!F&&!v)return L?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(hs,{error:L,errorSql:I||n.sql||n.python,onOpenInEditor:V,onDebugWithAssistant:z,onSendFeedback:je,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((F||v)&&(!(S!=null&&S.records)||S.records.length===0))return g==="table"||g==="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(!R.id)return null;if(g==="custom")return le(n);if(!["table","pivotTable","aggregateTable","detailTable","custom"].includes(g)&&Me)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:F||v?e.jsx(e.Fragment,{}):e.jsx(t.ChartJsVisual,{cfg:Me})});if(g==="table"||g==="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:R,data:B,comparisonMetadata:(q=S==null?void 0:S.metadata)==null?void 0:q.comparisonMetadata,paginationMetadata:P,onPaginationChange:te,onSortChange:De,isLoading:F||v})});if(g==="pivotTable"&&X)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:R,data:X.data,options:X.options,onAggregationChange:se=>{const oe=t.handleAggregationChange(se,n.config),be={...n,config:oe};_(be),U(be)},onAggregationLabelChange:se=>{const oe=t.handleAggregationLabelChange(se,n.config),be={...n,config:oe};_(be),U(be)}})});if(g==="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:R,data:(S==null?void 0:S.records)||[],groupByColumns:S==null?void 0:S.groupByColumns,pivotSchema:S==null?void 0:S.pivotSchema,paginationMetadata:P,onPaginationChange:te,onAggregationChange:se=>{const oe=t.handleAggregationChange(se,n.config),be={...n,config:oe};_(be),U(be)},isLoading:F||v})})}return e.jsxs(t.Card,{role:"editor-visual-card",className:t.cn("relative flex h-full flex-col rounded-none",s),...a,children:[(F||v)&&(S==null?void 0:S.records)&&S.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"})}),d&&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:q=>_({...n,title:q}),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(hr,{})})]}),e.jsx("div",{className:"min-w-0",children:e.jsx(t.EditableText,{value:(n.description||"").trim(),onSave:q=>_({...n,description:q.trim()}),isEditable:!0,placeholder:"Add description",displayClassName:"text-[12px] leading-snug text-muted-foreground",inputClassName:"text-[12px] leading-snug"})})]}),E&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Label,{className:"my-1",children:e.jsx(t.EditableText,{value:E.title||E.column,onSave:q=>T({...E,title:q}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(t.FilterComponent,{filter:E})]})]}),i&&n.inlineFilters&&n.inlineFilters.length>0&&e.jsx("div",{className:"px-4 pb-2",children:e.jsx(t.InlineFilterBar,{card:n,sheetId:m||"",inlineFilterValues:c,setInlineFilterValue:q=>j(n.id,q),removeInlineFilterValue:q=>f(n.id,q)})}),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:ve()}),t.isCardSummaryVisibleOnCard(R)&&e.jsx("div",{className:"pt-3",children:e.jsx(t.CardSummary,{card:R,mode:"editor"})})]}),e.jsx(t.FeedbackDialog,{open:x,onOpenChange:b,feedbackData:ke,showDebugInfo:!0})]})}const ns=({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}),pr=()=>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."})]})]}),fr=({customCode:s,cardCustomCfgString:a,mergedConfig:n,onConfigChange:r,onCodeChange:d})=>e.jsxs(t.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(t.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(t.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(t.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(t.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(t.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ns,{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(ns,{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(ns,{language:"javascript",value:s,onChange:d})})]}),gr=({error:s,hasCardCustomConfig:a,onReset:n,onApply:r,onClose:d})=>e.jsxs(t.DialogFooter,{className:"flex items-center",children:[e.jsx(t.Label,{className:"mr-2 text-red-500",children:s}),e.jsx(t.Button,{disabled:!a,onClick:n,variant:"outline",children:"Reset"}),e.jsx(t.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(t.Button,{onClick:d,variant:"outline",children:"Close"})]});function br({triggerVariant:s="icon",className:a,label:n="Customize Visual"}={}){const[r,d]=N.useState(!1),[i,l]=N.useState(""),[c,o]=N.useState(""),[m,x]=N.useState(""),[b,h]=N.useState(""),u=t.useEditorStore(g=>g.card),p=Ae.useEffectiveEditorCardType(),j=t.useEditorStore(g=>g.card.customCfg),f=j?JSON.stringify(j,null,2):"",T=N.useMemo(()=>p!==u.type?{...u,type:p}:u,[u,p]),{data:E}=t.useEditorCardQuery(T),{data:O}=t.useTopoJson(u),{setCardCustomCfg:C,setCustomVisualCode:k}=t.useEditorActions(),w=g=>{var R,M;return JSON.stringify({...g,data:{...g.data,datasets:(M=(R=g.data)==null?void 0:R.datasets)==null?void 0:M.map(S=>({...S,data:[]}))}},null,2)},D=()=>{var R,M;if(!((R=E==null?void 0:E.records)!=null&&R.length))return;const g=t.createChartConfig({card:u,data:E.records,cardType:u.type,queryConfig:u.queryConfig,preferences:u.preferences,topoJson:O});if(g){l(w(g)),x(((M=u.preferences)==null?void 0:M.customVisualCode)||"");const S=t.merge(g,j);o(w(S))}},y=()=>{try{if(m&&k(m),c){const g=JSON.parse(c),R=t.getObjectDiff(JSON.parse(i),g);C(R),h("")}}catch{h("Invalid JSON configuration")}},A=Object.keys(j||{}).length===0;return e.jsxs(t.Dialog,{open:r,onOpenChange:d,children:[e.jsx(t.DialogTrigger,{asChild:!0,children:s==="menu"?e.jsxs(t.Button,{variant:"ghost",onClick:D,className:t.cn("h-8 w-full justify-start gap-2 px-2 text-sm",A?"":"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:D,className:t.cn(A?"":"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(pr,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackVisual,children:e.jsx(Pn,{className:"w-1/2 rounded shadow-none"})}),e.jsx(fr,{customCode:m,cardCustomCfgString:f,mergedConfig:c,onConfigChange:g=>o(g??""),onCodeChange:g=>x(g??"")})]}),e.jsx(gr,{error:b,hasCardCustomConfig:!!j,onReset:()=>{o(i),C(null)},onApply:y,onClose:()=>d(!1)})]})]})}function jr(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 vr(s){const a=s.trim().split(/\s+/);return a.length>1?(a[0][0]+a[1][0]).toUpperCase():s.slice(0,2).toUpperCase()}function ps({chartType:s,chartName:a,isCustom:n=!1,className:r="h-6 w-6"}){if(!n&&s)return t.getChartIconByType(s,r);const d=t.getAutoDetectedChartIcon(a);if(d)return N.cloneElement(d,{className:r});const i=vr(a),l=jr(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 yr({isStarred:s,onClick:a,className:n}){const r=d=>{d.stopPropagation(),d.preventDefault(),a(d)};return e.jsx("button",{type:"button",onClick:r,className:t.cn("flex items-center justify-center rounded-sm p-0.5 transition-all","hover:bg-muted/80",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 hn({chartType:s,chartName:a,isCustom:n=!1,pluginName:r,isStarred:d,showStar:i=!0,isSelected:l=!1,onSelect:c,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",d?"opacity-100":"opacity-0 group-hover:opacity-100 group-focus-within:opacity-100"),children:e.jsx(yr,{isStarred:d,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:c,"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(ps,{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 pn=[{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 Bn({onChartSelect:s,onClose:a}){const[n,r]=N.useState(""),{starredCharts:d,isStarred:i,toggleStar:l}=t.useStarredChartsStore(),{data:c=[],isLoading:o}=t.useCustomVisualsQuery(),{setCardType:m,setCardPreferences:x,setIsDevMode:b}=t.useEditorStore(g=>g.actions),h=t.useEditorStore(g=>g.card),{setCardCustomCfg:u,setCustomCardPreferences:p,setVisualizationMode:j,setQueryConfig:f,replaceFrameCards:T,clearModeDrafts:E,initializeModeDrafts:O}=t.useEditorActions(),C=N.useMemo(()=>{if(!n)return pn;const g=n.toLowerCase();return pn.filter(R=>R.name.toLowerCase().includes(g))},[n]),k=N.useMemo(()=>{const g=c.filter(M=>M.componentType==="chart"&&M.pluginType!=="standard");if(!n)return g;const R=n.toLowerCase();return g.filter(M=>M.name.toLowerCase().includes(R))},[c,n]),w=g=>{u(null),x({}),j("builtin"),m(g),["custom","text","map"].includes(g)&&(b(!0),f(void 0)),s==null||s(g),a==null||a()},D=g=>{u(null),x({}),j("builtin"),f(void 0);const R=t.resolveMultiInputTypeFromVisual(g);if(R==="multiple"&&g.slots&&g.slots.length>0){E();const S=t.createCardsFromSlots(g.slots,g,h);T(S),S[0]&&O(S[0]),a==null||a();return}else m("custom"),p({type:"component",visualType:R,url:g.url,componentName:g.name,icon:g.icon,pluginChartType:g.chartType,minInputs:g.minInputs,maxInputs:g.maxInputs});s==null||s("custom",g),a==null||a()},y=g=>{const R={type:"default",id:g.id,name:g.name};l(R)},A=g=>{const R={type:"custom",id:g.name,url:g.url,icon:g.icon,name:g.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:g=>r(g.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(g=>e.jsx(hn,{chartType:g.id,chartName:g.name,isCustom:!1,isStarred:i("default",g.id),onSelect:()=>w(g.id),onToggleStar:()=>y(g)},g.id))}),k.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:k.length})]}),e.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:k.map((g,R)=>e.jsx(hn,{chartName:g.name,isCustom:!0,pluginName:g.pluginName,isStarred:i("custom",g.name),onSelect:()=>D(g),onToggleStar:()=>A(g)},`${g.url}-${g.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&&k.length===0&&!o&&e.jsx("div",{className:"py-8 text-center text-[11px] text-muted-foreground",children:"No charts found"})]})]})}function Nr({selectedChart:s,onChartChange:a}){var w,D,y,A;const n=t.useEditorStore(g=>g.card),r=t.useEditorStore(g=>g.frame),d=t.useEditorStore(g=>g.isDevMode),{replaceFrameCards:i,clearModeDrafts:l,initializeModeDrafts:c,setIsDevMode:o}=t.useEditorActions(),m=N.useMemo(()=>t.findCustomVisualConfigCard(r,n),[r,n]),{manifest:x}=t.useCustomVisual(((w=m==null?void 0:m.customCardPreferences)==null?void 0:w.url)||""),b=N.useMemo(()=>{var g;return(g=x==null?void 0:x.visuals)==null?void 0:g.find(R=>{var M;return R.name===((M=m==null?void 0:m.customCardPreferences)==null?void 0:M.componentName)})},[x,(D=m==null?void 0:m.customCardPreferences)==null?void 0:D.componentName]),h=t.resolveMultiInputType(m,b)==="multiple",u=Ae.useEffectiveEditorCardType(),p=h?u:s??n.type,j=(y=n==null?void 0:n.customCardPreferences)==null?void 0:y.componentName,f=(A=m==null?void 0:m.customCardPreferences)==null?void 0:A.componentName,T=h&&!!f,E=N.useMemo(()=>{const g=t.chartTypes.find(R=>R.id===p);return g?g.label:p==="custom"?j||"Custom Visual":"Select chart type"},[p,j]),O=N.useMemo(()=>{const g=t.chartTypes.find(R=>R.id===p);if(g){const R=g.icon;return e.jsx(R,{className:"h-4 w-4"})}if(p==="custom"&&j){const R=t.getAutoDetectedChartIcon(j);return R||e.jsx(ps,{chartName:j,isCustom:!0,className:"h-4 w-4"})}return e.jsx(La,{className:"h-4 w-4"})},[p,j]);return{displayChartType:p,displayLabel:E,displayIcon:O,showBadge:T,badgeLabel:f,isMultiInputContext:h,handleChartSelect:g=>{a==null||a(g)},handleClearCustomVisual:g=>{g.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(),c(R),d&&o(!0),a==null||a("bar")}}}function Cr({selectedChart:s,onChartChange:a,variant:n="ghost",className:r}){const[d,i]=N.useState(!1),{displayLabel:l,displayIcon:c,showBadge:o,badgeLabel:m,handleChartSelect:x,handleClearCustomVisual:b}=Nr({selectedChart:s,onChartChange:a}),h=n==="header";return e.jsxs("div",{className:t.cn("relative w-full",r),children:[e.jsxs(t.Popover,{open:d,onOpenChange:i,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:h?e.jsxs("button",{type:"button",role:"combobox","aria-expanded":d,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:[c,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",d&&"rotate-180")})]}):e.jsxs(t.Button,{size:"xs",variant:n,role:"combobox","aria-expanded":d,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:[c,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(Bn,{onChartSelect:u=>x(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:b,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"})})]})]})}const bt={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},Et={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"},Vn=[{id:"table"},{id:"bar"},{id:"line"},{id:"pie"},{id:"kpi"},{id:"doughnut"}],zn=6;function Sr({selectedChart:s,onChartChange:a}){var E,O;const[n,r]=N.useState(!1),d=t.useEditorStore(C=>C.card),{setCardType:i,setCardPreferences:l}=t.useEditorStore(C=>C.actions),{setCardCustomCfg:c,setCustomCardPreferences:o,setQueryConfig:m,replaceFrameCards:x,clearModeDrafts:b,initializeModeDrafts:h}=t.useEditorActions(),{starredCharts:u}=t.useStarredChartsStore(),{data:p=[]}=t.useCustomVisualsQuery(),j=N.useMemo(()=>{const C=u.filter(y=>y.type==="default"?!0:p.some(A=>A.name===y.id)),k=new Set(C.map(y=>y.id)),w=Vn.filter(y=>!k.has(y.id));return[...C.map(y=>({id:y.id,label:y.name,icon:y.type==="default"?bt[y.id]:void 0,isCustom:y.type==="custom",url:y.url})),...w.map(y=>({id:y.id,label:Et[y.id]??y.id,icon:bt[y.id],isCustom:!1}))].slice(0,zn)},[u,p]),f=s==="custom"&&((E=d==null?void 0:d.customCardPreferences)==null?void 0:E.componentName);return j.some(C=>{var k;return C.isCustom?f&&((k=d==null?void 0:d.customCardPreferences)==null?void 0:k.componentName)===C.id:s===C.id})||(s==="custom"?(O=d==null?void 0:d.customCardPreferences)!=null&&O.componentName:Et[s]),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.jsx(_n,{selectedChart:s,onChartChange:a,compactMore:!0})]})}function _n({selectedChart:s,onChartChange:a,compactMore:n=!1}){var w,D;const[r,d]=N.useState(!1),i=t.useEditorStore(y=>y.card),{setCardType:l,setCardPreferences:c}=t.useEditorStore(y=>y.actions),{setCardCustomCfg:o,setCustomCardPreferences:m,setQueryConfig:x,replaceFrameCards:b,clearModeDrafts:h,initializeModeDrafts:u}=t.useEditorActions(),{starredCharts:p}=t.useStarredChartsStore(),{data:j=[]}=t.useCustomVisualsQuery(),f=((w=i==null?void 0:i.customCardPreferences)==null?void 0:w.componentName)??null,T=N.useMemo(()=>{const y=p.filter(S=>S.type==="default"?!0:j.some(F=>F.name===S.id)),A=new Set(y.map(S=>S.id)),g=Vn.filter(S=>!A.has(S.id)),R=[...y.map(S=>({id:S.id,label:S.name,icon:S.type==="default"?bt[S.id]:void 0,isCustom:S.type==="custom",url:S.url})),...g.map(S=>({id:S.id,label:Et[S.id]??S.id,icon:bt[S.id],isCustom:!1}))];if(!R.some(S=>S.isCustom?s==="custom"&&S.id===f:S.id===s))if(s==="custom"&&f){const S=j.find(F=>F.name===f);S&&R.unshift({id:S.name,label:S.name,icon:void 0,isCustom:!0,url:S.url})}else s&&bt[s]&&R.unshift({id:s,label:Et[s]??s,icon:bt[s],isCustom:!1});return R.slice(0,zn)},[p,j,s,f]),E=s==="custom"&&f,O=y=>{if(y.isCustom){const A=j.find(M=>M.name===y.id);if(!A)return;o(null),c({}),x(void 0);const g=t.resolveMultiInputTypeFromVisual(A);if(g==="multiple"&&A.slots&&A.slots.length>0){h();const M=t.createCardsFromSlots(A.slots,A,i);b(M),M[0]&&u(M[0]);return}l("custom"),m({type:"component",visualType:g,url:A.url,componentName:A.name,icon:A.icon,pluginChartType:A.chartType,minInputs:A.minInputs,maxInputs:A.maxInputs}),a("custom");return}a(y.id)},C=T.some(y=>{var A;return y.isCustom?E&&((A=i==null?void 0:i.customCardPreferences)==null?void 0:A.componentName)===y.id:s===y.id}),k=C?"More":s==="custom"?((D=i==null?void 0:i.customCardPreferences)==null?void 0:D.componentName)||"Custom":Et[s]||"More";return 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:T.map(y=>{var R;const A=y.icon,g=y.isCustom?E&&((R=i==null?void 0:i.customCardPreferences)==null?void 0:R.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:()=>O(y),"aria-label":y.label,"aria-pressed":!!g,className:t.cn("flex h-full w-7 items-center justify-center text-foreground/65 transition-colors hover:bg-muted/50 hover:text-foreground",g&&"bg-foreground/[0.08] font-medium text-foreground"),children:[A?e.jsx(A,{className:"h-3.5 w-3.5"}):e.jsx(ps,{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:r,onOpenChange:d,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs("button",{type:"button","aria-label":n?"More chart types":k,className:t.cn("inline-flex h-7 items-center gap-1 rounded-[5px] transition-colors hover:bg-muted/50",n?"w-7 justify-center":"px-2 text-[12px]",!n&&(C?"text-muted-foreground":"text-foreground")),children:[!n&&e.jsx("span",{className:"truncate",children:k}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform",r&&"rotate-180"),strokeWidth:1.75})]})}),e.jsx(t.PopoverContent,{className:"w-[360px] p-3",align:"end",onOpenAutoFocus:y=>y.preventDefault(),children:e.jsx(Bn,{onChartSelect:y=>{a(y),d(!1)},onClose:()=>d(!1)})})]})]})}function wr(){const s=t.useEditorStore(o=>{var m,x;return(x=(m=o.card.preferences)==null?void 0:m.chartOptions)==null?void 0:x.indexAxis}),a=t.useEditorStore(o=>o.card.type),{setChartOrientation:n,setCardPreferences:r}=t.useEditorStore(o=>o.actions),d=o=>{if(n(o),a!=="bullet")return;const m=o==="y"?"horizontal":"vertical",x=t.useEditorStore.getState().card.preferences,b={...x||{},bulletConfig:{...(x==null?void 0:x.bulletConfig)||{},orientation:m}};r(b)};function i(){const o=s??"x",m=()=>{d(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(es,{className:"h-3.5 w-3.5"}):e.jsx(Zt,{className:"h-3.5 w-3.5"})})}function l(){const o=()=>{d(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(es,{className:"h-3.5 w-3.5"}):e.jsx(Zt,{className:"h-3.5 w-3.5"})})}function c(){const o=s??"y",m=()=>{d(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(Zt,{className:"h-3.5 w-3.5"}):e.jsx(es,{className:"h-3.5 w-3.5"})})}return e.jsx(e.Fragment,{children:a==="funnel"?l():a==="bullet"?c():i()})}function fs({className:s,triggerVariant:a="icon",label:n="Display Options"}){var j,f,T,E,O,C,k,w,D,y;const r=t.useEditorStore(A=>A.card),{setCardPreferences:d,updateCardInFrame:i,setCard:l}=t.useEditorActions(),[c,o]=N.useState(!1),m=((f=(j=r.preferences)==null?void 0:j.displayOptions)==null?void 0:f.showFilterInfo)??!0,x=((E=(T=r.preferences)==null?void 0:T.displayOptions)==null?void 0:E.showCardToolbar)??!0,b=((C=(O=r.preferences)==null?void 0:O.displayOptions)==null?void 0:C.showChrome)??!0,h=((w=(k=r.preferences)==null?void 0:k.displayOptions)==null?void 0:w.allowScroll)??!0,u=((y=(D=r.preferences)==null?void 0:D.displayOptions)==null?void 0:y.showInlineFilterBar)??!0,p=(A,g)=>{var S;const R={...r.preferences,displayOptions:{...(S=r.preferences)==null?void 0:S.displayOptions,[A]:g}};d(R);const M={...r,preferences:R};l(M),i(M)};return e.jsx("div",{className:t.cn("flex items-center",s),children:e.jsxs(t.DropdownMenu,{modal:!1,open:c,onOpenChange:o,children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children: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:A=>{p("showFilterInfo",A)},onSelect:A=>A.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:x,onCheckedChange:A=>{p("showCardToolbar",A)},onSelect:A=>A.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:b,onCheckedChange:A=>{p("showChrome",A)},onSelect:A=>A.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Chrome"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Frame & padding"})]}),e.jsxs(t.DropdownMenuCheckboxItem,{checked:h,onCheckedChange:A=>{p("allowScroll",A)},onSelect:A=>A.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:A=>{p("showInlineFilterBar",A)},onSelect:A=>A.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 gs({className:s,triggerVariant:a="icon",label:n="Inline Filters"}){var k,w,D;const[r,d]=N.useState(!1),i=t.useEditorStore(y=>y.card),l=t.useEditorStore(y=>y.selectedConnectionId),{tokenProps:c}=t.useSemaphorContext(),{setCard:o}=t.useEditorActions(),m=t.useDashboardStore(y=>y.actions.removeCardInlineFilterValue),x=t.useDashboardStore(y=>y.actions.setCardInlineFilterValue),b=t.useEditorStore(y=>y.actions.removeCardInlineFilterValue),h=t.useEditorStore(y=>y.actions.setCardInlineFilterValue),u=t.useDashboardStore(y=>y.isVisualEditing),p=(i==null?void 0:i.inlineFilters)||[],j=((w=(k=c==null?void 0:c.params)==null?void 0:k.calendarContext)==null?void 0:w.tz)||((D=c==null?void 0:c.params)==null?void 0:D.timezone)||Intl.DateTimeFormat().resolvedOptions().timeZone;function f(y){var z,B,_,U,K,H,Z;const A=((_=(B=(z=i==null?void 0:i.dataSource)==null?void 0:z.selectedEntities)==null?void 0:B[0])==null?void 0:_.database)||"",g=y.qualifiedFieldName||y.name;if(p.find(de=>t.doesStoredFilterMatchField(de,y)))return;const M=y.qualifiedFieldName?y.qualifiedFieldName.split(".").slice(0,-1).join("."):y.qualifiedEntityName||y.entityName,F=t.fmt(y.name),v=t.buildFilterFieldMeta(y),L=t.buildFilterSemanticContext(i==null?void 0:i.dataSource,{connectionId:l||((U=i==null?void 0:i.dataSource)==null?void 0:U.connectionId),connectionType:(K=i==null?void 0:i.dataSource)==null?void 0:K.connectionType}),I=t.isCalculatedFilterField(v),P=!!(((H=i==null?void 0:i.dataSource)==null?void 0:H.mode)==="semanticDomain"&&((Z=L==null?void 0:L.selectedEntities)!=null&&Z.length||L!=null&&L.semanticDomainId)),V={id:t.v4(),column:g,title:y.label||y.name,dataType:y.dataType,table:y.entityName||"",database:A,qualifiedTableName:M,connectionId:l||"",operation:"in",sql:I||P?"":t.getDefaultFilterSql(y.dataType,M,F),fieldMeta:v,semanticContext:L,width:250};o({...i,inlineFilters:[...p,V]})}function T(y){const A=p.filter(g=>g.id!==y);o({...i,inlineFilters:A}),u?b(i.id,y):m(i.id,y)}function E(y,A){const g=p.map(F=>F.id===y?{...F,...A}:F);if(o({...i,inlineFilters:g}),!(Object.prototype.hasOwnProperty.call(A,"defaultValues")||Object.prototype.hasOwnProperty.call(A,"defaultDateFilter")))return;const M=g.find(F=>F.id===y);if(!M)return;const S=t.buildFilterValueFromDefaults(M,j);S?u?h(i.id,S):x(i.id,S):u?b(i.id,y):m(i.id,y)}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:d,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]",p.length>0&&"text-primary"),children:[e.jsx(ln,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:n}),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:p.length})]}):e.jsxs(t.IconButton,{tooltip:"Add Inline Filter",className:t.cn("relative h-7 w-7 px-0",{"text-primary":p.length>0}),children:[e.jsx(ln,{className:"h-3.5 w-3.5"}),p.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:p.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:f,inlineFilters:p})})})}),p.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:p.map(y=>e.jsx(Tr,{filter:y,onUpdate:A=>E(y.id,A),onRemove:()=>T(y.id)},y.id))})]})]})})]})})}function Tr({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 Er={metric_selector:"Displayed metric",field_selector:"Group by field",aggregation_selector:"Aggregation",grain_selector:"Time grain"};function Ir(s,a){return s&&typeof s=="object"&&"label"in s&&typeof s.label=="string"&&s.label.trim().length>0?s.label:a||null}const kr={metric_selector:"config_metric_selector",field_selector:"config_field_selector",aggregation_selector:"config_aggregation",grain_selector:"config_grain"};function _t(s,a){return`${s}:${a}`}function Dr(s,a,n){const r=new Set(n.filter(i=>i.target!=="sql_param").map(i=>_t(i.controlId,i.target))),d=a.map(i=>{const l=t.getCompatibleBindingTargetOptions({card:s,control:i}).map(x=>x.value),c=kr[i.type],m=[...c?[c]:[],...l.filter(x=>x!==c)].find(x=>!r.has(_t(i.id,x)));return m?{controlId:i.id,target:m}:null}).find(Boolean);return d?{controlId:d.controlId,target:d.target,mapping:{}}:null}function Ar({card:s,dashboardControls:a,bindings:n,onChange:r,availableFieldChoices:d,availableMetricChoices:i,suppressTransientStaleState:l=!1}){const c=[...a,...s.controls||[]],[o,m]=N.useState({}),x=t.extractSqlParamReferences({sql:s.sql,controlBindings:s.controlBindings}),b=t.getBindingTargetSuggestions(s),h=new Set(n.map(O=>_t(O.controlId,O.target))),u=c.some(O=>t.getCompatibleBindingTargetOptions({card:s,control:O}).some(C=>!h.has(_t(O.id,C.value)))),p=l?0:n.reduce((O,C)=>{const k=j(C.target),w=Object.values(C.mapping).filter(D=>{const y=C.target==="config_metric_selector"||C.target==="config_field_selector"?typeof D=="string"?D:D==null?void 0:D.id:typeof D=="string"?D:void 0;return typeof y=="string"&&!k.some(A=>A.value===y)}).length;return O+w},0);function j(O){var C,k,w,D;switch(O){case"config_metric_selector":return i?i.filter(y=>!!y.target).map(y=>({value:y.target.id,label:y.target.label||y.option.label,target:y.target})):((k=(C=s.config)==null?void 0:C.metricColumns)==null?void 0:k.map(y=>({value:y.id,label:y.label||y.id,target:y})))||[];case"config_field_selector":return d?d.filter(y=>!!y.target).map(y=>({value:y.target.id,label:y.target.label||y.option.label,target:y.target})):((D=(w=s.config)==null?void 0:w.groupByColumns)==null?void 0:D.map(y=>({value:y.id,label:y.label||y.id,target:y})))||[];case"config_aggregation":return(b.config_aggregation||[]).map(y=>({value:y,label:y}));case"config_grain":return(b.config_grain||[]).map(y=>({value:y,label:y.charAt(0).toUpperCase()+y.slice(1)}));default:return[]}}const f=(O,C)=>{r(n.map((k,w)=>w!==O?k:C(k)))},T=O=>{r(n.filter((C,k)=>k!==O))},E=()=>{const O=Dr(s,c,n);O&&r([...n,O])};if(typeof s.sql=="string"&&s.sql.trim().length>0){const O=x.map(({controlId:C,paramId:k})=>{const w=c.find(D=>D.id===C);return w?{id:C,paramId:k,label:w.label,reference:`[[param.${k}]]`}:{id:C,paramId:k,label:C,reference:`[[param.${k}]]`}});return e.jsx("div",{className:"space-y-2",children:O.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]]`."}):O.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:[p>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:[p," ",p===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((O,C)=>{const k=b[O.target]||[],w=c.find(v=>v.id===O.controlId),D=w?t.ensureManualSource(w):null,y=(D==null?void 0:D.source.kind)==="manual"?D.source.options:[],A=j(O.target),g=Array.from(new Set([...y.map(v=>v.value),...Object.keys(O.mapping)])).map(v=>{const L=y.find(I=>I.value===v);return{value:v,label:(L==null?void 0:L.label)||v}}),R=`${O.controlId}-${O.target}-${C}`,M=o[R]??C===0,S=Object.keys(O.mapping).length,F=w!=null&&w.type?Er[w.type]||w.type:null;return e.jsxs(t.Collapsible,{open:M,onOpenChange:v=>m(L=>({...L,[R]:v})),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:[M?e.jsx(t.ChevronDown,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}):e.jsx(t.ChevronRight,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:(w==null?void 0:w.label)||"Control"}),F?e.jsx(t.Badge,{variant:"secondary",className:"shrink-0 text-[11px] font-normal text-muted-foreground",children:F}):null]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:S>0?`${S} mapped`:"No mappings yet"})]})]})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>T(C),children:e.jsx(t.Trash2,{className:"h-4 w-4"})})]}),e.jsx(t.CollapsibleContent,{className:"space-y-3 border-t px-3 pb-3 pt-2",children:g.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."}):A.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:g.map(v=>{const L=O.mapping[v.value],I=O.target==="config_metric_selector"||O.target==="config_field_selector"?typeof L=="string"?L:L==null?void 0:L.id:typeof L=="string"?L:void 0,P=!l&&typeof I=="string"&&!A.some(B=>B.value===I),V=Ir(L,I),z=I&&P?[...A,{value:I,label:"Needs remap",target:L}]:A;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:v.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:I||"__none__",onValueChange:B=>f(C,_=>{if(_.target==="config_metric_selector"){const K={..._.mapping};if(B==="__none__")delete K[v.value];else{const H=z.find(Z=>Z.value===B);H!=null&&H.target?K[v.value]=H.target:delete K[v.value]}return{..._,mapping:K}}if(_.target==="config_field_selector"){const K={..._.mapping};if(B==="__none__")delete K[v.value];else{const H=z.find(Z=>Z.value===B);H!=null&&H.target?K[v.value]=H.target:delete K[v.value]}return{..._,mapping:K}}const U={..._.mapping};return B==="__none__"?delete U[v.value]:U[v.value]=B,{..._,mapping:U}}),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Choose what this should use"})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"__none__",children:"Not mapped"}),z.map(B=>e.jsx(t.SelectItem,{value:B.value,children:B.label},B.value))]})]}),P?e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-amber-700",children:[e.jsx(t.CircleAlert,{className:"h-3 w-3 shrink-0"}),e.jsxs("span",{children:["Needs remap",V?` · Previously: ${V}`:""]})]}):null]})]},`${O.controlId}-${O.target}-${v.value}`)})}),k.length>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Available choices for this card: ",k.join(", ")]})]})})]},R)}),u?e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",onClick:E,children:[e.jsx(t.Plus,{className:"mr-2 h-4 w-4"}),"Add another control response"]}):null]})}const Mr=[];function Lr({className:s,triggerVariant:a="icon",label:n="Controls"}){var M,S;const{handleOpenChange:r,preventPassiveDismissDuringCreate:d,resolvedOpen:i,setIsCreateFlowActive:l}=Ae.useCreateFlowOverlayState({}),c=t.useEditorStore(F=>F.card),o=t.useEditorStore(F=>F.frame),m=t.useDashboardStore(F=>F.dashboard),b=t.useDashboardStore(F=>F.dashboard.controls)||Mr,{setCard:h,updateCardInFrame:u}=t.useEditorActions(),[p,j]=N.useState(null);N.useEffect(()=>{i&&!p&&(c!=null&&c.id)&&j(c.id)},[c==null?void 0:c.id,i,p]),N.useEffect(()=>{!i&&p!==null&&j(null)},[i,p]);const f=N.useMemo(()=>p?(o==null?void 0:o.cards.find(F=>F.id===p))||((c==null?void 0:c.id)===p?c:void 0):c,[c,o==null?void 0:o.cards,p]),T=(f==null?void 0:f.controls)||[],E=f?t.collectDashboardControlIds(m,{excludeCardId:f.id}):b.map(F=>F.id),O=((f==null?void 0:f.controlBindings)||[]).filter(F=>F.target!=="sql_param"),C=t.buildCardControlUsageById({card:f,controls:T}),k={choices:t.getFieldSelectorChoicesForCard(f),targetMap:Object.fromEntries((((M=f==null?void 0:f.config)==null?void 0:M.groupByColumns)||[]).map(F=>[F.id,F]))},w={choices:t.getMetricSelectorChoicesForCard(f),targetMap:Object.fromEntries((((S=f==null?void 0:f.config)==null?void 0:S.metricColumns)||[]).map(F=>[F.id,F]))},D=k.choices.map(F=>({option:F,target:k.targetMap[F.value]})),y=w.choices.map(F=>({option:F,target:w.targetMap[F.value]})),A=(F,v)=>{if(!f)return;const L=(v==null?void 0:v.type)==="rename"?t.applyControlMutationToCard(f,{type:"rename",oldId:v.oldId,newId:v.newId}):(v==null?void 0:v.type)==="remove"?t.applyControlMutationToCard(f,{type:"remove",controlId:v.controlId}):f,I={...L,controls:F,controlBindings:t.syncStructuralBindingsWithControls(L.controlBindings,F)};u(I),(c==null?void 0:c.id)===I.id&&h(I)},g=F=>{if(!f)return;const v={...f,controlBindings:t.mergeConfigBindingsWithSqlParamBindings(F,f.controlBindings)};u(v),(c==null?void 0:c.id)===v.id&&h(v)},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]",(T.length>0||O.length>0)&&"text-primary"),children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:n}),T.length+O.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:T.length+O.length})]}):e.jsxs(t.IconButton,{tooltip:"Configure Controls",className:t.cn("relative h-7 w-7 px-0",{"text-primary":T.length>0||O.length>0}),children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"}),T.length+O.length>0&&e.jsx("span",{className:"absolute -right-1 -top-1 inline-flex h-4 min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[10px] font-medium text-primary-foreground",children:T.length+O.length})]})}),e.jsxs(t.PopoverContent,{className:"flex max-h-[85vh] w-[560px] max-w-[95vw] flex-col",align:"end",onEscapeKeyDown:d,onPointerDownOutside:d,children:[e.jsxs("div",{className:"space-y-1 border-b pb-4",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Card-only controls"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add controls that belong only to this card, or decide how this card should respond to shared dashboard controls."}),f!=null&&f.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:f,controls:T,reservedControlIds:E,usageByControlId:C,availableFieldChoices:D,availableMetricChoices:y,onCreateFlowActiveChange:l,onChange:(F,v,L)=>A(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."})]}),f?e.jsx(Ar,{card:f,dashboardControls:b,bindings:O,onChange:g,availableFieldChoices:D,availableMetricChoices:y}):null]})})]})]})})}function qn({showOrientation:s=!0,showGridStyle:a=!0,showInlineFilters:n=!0,showControls:r=!0,showDisplayOptions:d=!0}={}){const i=t.useEditorStore(u=>u.card),l=t.useEditorStore(u=>{var p,j;return(j=(p=u.card)==null?void 0:p.preferences)==null?void 0:j.chartOptions}),c=t.getChartGridStyle(l),{setChartGrid:o}=t.useEditorActions();function m(){const u=["xy","none","x","y"],j=(u.indexOf(c)+1)%u.length;o(u[j])}const x=s&&["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel","bullet"].includes(i.type),b=a&&!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(i.type);return x||b||n||r||d?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[x&&e.jsx(e.Fragment,{children:e.jsx(wr,{})}),b&&e.jsxs(t.IconButton,{tooltip:"Grid Style",onClick:m,className:"h-7 w-7 px-0",children:[(c==="xy"||!c)&&e.jsx(t.Grid3x3,{className:"h-3.5 w-3.5"}),c==="x"&&e.jsx(xs,{className:"h-3.5 w-3.5"}),c==="y"&&e.jsx(qt,{className:"h-3.5 w-3.5"}),c==="none"&&e.jsx(t.Square,{className:"h-3.5 w-3.5"})]}),n&&e.jsx(gs,{}),r&&e.jsx(Lr,{}),d&&e.jsx(fs,{})]}):null}function Fr({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 Rr({isPreviewMode:s,onPreviewToggle:a,configCard:n}){var L,I,P,V,z;const r=t.useEditorStore(B=>B.frame),d=t.useEditorStore(B=>B.card),i=t.useEditorStore(B=>B.editorContext),l=(i==null?void 0:i.type)==="documentSection",{setFrame:c,setActiveTabCardId:o,setCard:m,updateCardInFrame:x,clearModeDrafts:b,initializeModeDrafts:h}=t.useEditorActions(),{manifest:u}=t.useCustomVisual(((L=n==null?void 0:n.customCardPreferences)==null?void 0:L.url)||""),p=(I=u==null?void 0:u.visuals)==null?void 0:I.find(B=>{var _;return B.name===((_=n==null?void 0:n.customCardPreferences)==null?void 0:_.componentName)}),f=t.resolveMultiInputType(n,p)==="multiple",T=(p==null?void 0:p.minInputs)??((P=n==null?void 0:n.customCardPreferences)==null?void 0:P.minInputs)??1,E=(p==null?void 0:p.maxInputs)??((V=n==null?void 0:n.customCardPreferences)==null?void 0:V.maxInputs),O=N.useMemo(()=>t.getCustomVisualInputCards({frame:r,configCard:n,isMultiInputVisual:f}),[r,n,f]),C=f?O.filter(Boolean).length:r.cards.length,k=l?!1:E?C<E:!0,w=C>Math.max(T||1,1),D=!!((z=n==null?void 0:n.customCardPreferences)!=null&&z.dataInputCardIds),y=(B,_)=>{B.dataTransfer.setData("tabIndex",_.toString())},A=B=>{B.preventDefault()},g=(B,_)=>{const U=B.dataTransfer.getData("tabIndex");if(U===_.toString())return;const K=Array.from(r.cards),[H]=K.splice(parseInt(U),1);K.splice(_,0,H),c({...r,cards:K})};function R(B){const _=(n==null?void 0:n.id)===B;if(!(D&&_?r.cards.length>1:w))return;let K=r.cards.filter(ae=>ae.id!==B);f&&!D&&(K=t.reindexSlotCards(K));const H=K[0],Z={...r,cards:K,activeCardId:H.id},de=B===d.id;de&&b(),c(Z),o(H.id),m(H),de&&h(H)}function M(B,_){if(!k)return;const U={...r,cards:[...r.cards,_],activeCardId:B.id};c(U),o(_.id)}function S(){if(l)return;if(f&&(n==null?void 0:n.id)===d.id){F(d);return}const B={...d,id:t.v4(),title:`${d.title} Copy`,tabTitle:`${d.tabTitle||d.title} Copy`,customCardPreferences:d.customCardPreferences?{...d.customCardPreferences,slotIndex:f?Math.max(-1,...O.map((_,U)=>t.getSlotIndexForCard(_,U)))+1:d.customCardPreferences.slotIndex}:void 0};M(d,B)}function F(B){var de;if(l||!k)return;let _=f?"table":"bar",U="Title",K="";const H=f?Math.max(-1,...O.map((ae,ce)=>t.getSlotIndexForCard(ae,ce)))+1:C;if(f&&((de=p==null?void 0:p.slots)!=null&&de.length)){const ae=t.getSlotDefinitionForIndex(p.slots,H);ae&&(_=t.getSlotExpectedChartType(ae),U=ae.label||`Tab ${H+1}`,K=ae.description||"")}const Z={dataSource:B.dataSource,connectionId:B.connectionId,lastSelectedDatabase:B.lastSelectedDatabase,lastSelectedSchema:B.lastSelectedSchema,lastSelectedTable:B.lastSelectedTable,lastSelectedDatamodelId:B.lastSelectedDatamodelId,id:t.v4(),title:U,tabTitle:U,description:K,preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:_,sql:"",data:[],mode:"explorer",...f&&{customCardPreferences:{slotIndex:H}}};M(B,Z)}function v(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 U=_.displayTab===void 0?!1:!_.displayTab;m({..._,displayTab:U}),x({..._,displayTab:U})},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 de,ae;const U=f?t.getSlotIndexForCard(B,_):-1,K=f&&((de=p==null?void 0:p.slots)!=null&&de.length)&&U>=0?t.getSlotDefinitionForIndex(p.slots,U):null,H=K?(Array.isArray(K.expectedType)?K.expectedType[0]:K.expectedType)||"table":B.type,Z=f&&((ae=p==null?void 0:p.slots)==null?void 0:ae.length)&&p.slots.every(ce=>typeof ce.position=="number"||typeof ce.position=="string"&&!ce.position.includes("+"));return e.jsxs(t.TabsTrigger,{draggable:!f&&!l,onDragStart:f||l?void 0:ce=>y(ce,_),onDragOver:f||l?void 0:A,onDrop:f||l?void 0:ce=>g(ce,_),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:[f&&K?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:K.label||`Tab ${U+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:K.label}),K.description&&e.jsx("p",{className:"whitespace-normal break-words text-xs text-muted-foreground",children:K.description}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[K.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(K.expectedType)?K.expectedType.join(" / "):K.expectedType}),K.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:[v(r,B),e.jsx(t.Editable,{enabled:r.activeCardId===B.id,text:B.tabTitle||B.title,onSave:ce=>{m({...d,tabTitle:ce}),x({...d,tabTitle:ce})},children:B.tabTitle||B.title},B.id)]}),!l&&r.activeCardId===B.id&&!Z&&e.jsx(t.CopyPlus,{className:"h-3 w-3 text-muted-foreground hover:text-foreground",onClick:ce=>{ce.stopPropagation(),S()}}),!l&&r.activeCardId===B.id&&(D&&(n==null?void 0:n.id)===B.id?r.cards.length>1:w)&&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(d),disabled:!k,children:e.jsx(t.Plus,{className:"h-3 w-3"})}),f&&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 ge,$,ee,ue,Se;const n=t.useEditorStore(q=>q.frame),r=t.useEditorStore(q=>q.card),[d,i]=N.useState(!1),l=N.useMemo(()=>t.findCustomVisualConfigCard(n,r),[n,r]),c=t.useEditorStore(q=>q.isSqlRunning);t.useEditorStore(q=>q.isDevMode);const{setFrame:o,setActiveTabCardId:m,setCard:x,setRunSql:b,mergeDraftsIntoCard:h,clearModeDrafts:u,initializeModeDrafts:p}=t.useEditorActions(),[j,f]=N.useState({}),[T,E]=N.useState(()=>new Set),{theme:O}=t.useTheme(),C=t.useDashboardStore(q=>q.themeStyle),{authToken:k}=t.useSemaphorContext(),w=t.getTokenParams(k==null?void 0:k.accessToken),D={mode:O||"system",colors:(($=(ge=C==null?void 0:C.chart)==null?void 0:ge.dataset)==null?void 0:$.backgroundColor)||[]},{getCard:y,manifest:A,isLoading:g}=t.useCustomVisual(((ee=l==null?void 0:l.customCardPreferences)==null?void 0:ee.url)||""),R=(ue=l==null?void 0:l.customCardPreferences)==null?void 0:ue.componentName,M=R?y(R):null,S=(Se=A==null?void 0:A.visuals)==null?void 0:Se.find(q=>q.name===R),F=t.resolveMultiInputType(l,S),v=d&&F==="multiple"&&!!l,L=N.useMemo(()=>t.getCustomVisualInputCards({frame:n,configCard:l,isMultiInputVisual:!0}).map(se=>(se==null?void 0:se.id)===r.id?r:se),[n,l,r]),I=N.useMemo(()=>t.buildSlotOrderedCards(L),[L]),P=N.useMemo(()=>{const q=L.findIndex(se=>(se==null?void 0:se.id)===r.id);return q<0?-1:t.getSlotIndexForCard(r,q)},[L,r]),V=N.useMemo(()=>!l||F!=="multiple"||P<0?r.type:t.getEffectiveCardTypeForSlot(r,P,S==null?void 0:S.slots)??r.type,[l,F,P,r,S==null?void 0:S.slots]),z=N.useMemo(()=>v?{...r,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:V!==r.type?{...r,type:V}:r,[r,V,v]),{data:B,isLoading:_,isFetching:U,isError:K}=t.useEditorCardQuery(z),H=N.useCallback((q,se)=>{const oe=t.normalizeMultiInputPayload(se);f(be=>({...be,[q]:oe}))},[]),Z=N.useCallback((q,se)=>{E(oe=>{const be=new Set(oe);return se?be.add(q):be.delete(q),be})},[]),de=T.size>0,ae=t.useInteractionStore(q=>q.interactionStates),ce=t.useDashboardStore(q=>{var se;return(se=q.dashboard)==null?void 0:se.id}),me=t.useDashboardStore(q=>q.dashboard.filters),he=t.useDashboardStore(q=>q.filterValues),Ne=t.useDashboardStore(q=>q.selectedSheetId),we=t.useEditorStore(q=>q.inlineFilterValuesMap[(l==null?void 0:l.id)||""]),Ie=t.useEditorStore(q=>q.actions.setCardInlineFilterValue),X=t.useEditorStore(q=>q.actions.removeCardInlineFilterValue),je=N.useMemo(()=>l?t.buildInlineFilterNodes({card:l,sheetId:Ne||"",inlineFilterValues:we,setInlineFilterValue:q=>Ie(l.id,q),removeInlineFilterValue:q=>X(l.id,q)}):[],[l,Ne,we,Ie,X]),{cardFilters:ke,cardFilterValues:te}=N.useMemo(()=>l?t.calculateContextAwareFilters({card:l,interactionStates:ae,currentDashboardId:ce,filters:me,filterValues:he,selectedSheetId:Ne}):{cardFilters:[],cardFilterValues:[]},[l,ae,ce,me,he,Ne]);function De(q){const se=n.cards.find(oe=>oe.id===q);se&&(it.flushPendingEditorDrafts(),h(),Me(q),m(q),u(),p(se))}function Me(q){const se=t.useEditorStore.getState().card,oe=t.useEditorStore.getState().frame,be={...oe,cards:oe.cards.map(Oe=>Oe.id===se.id?se:Oe),activeCardId:q};o(be);const ye=be.cards.find(Oe=>Oe.id===q);ye.sql&&b(!0),x(ye)}function le(){if(g)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(!M)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 se=I.map((oe,be)=>t.getEffectiveCardTypeForSlot(oe,be,S==null?void 0:S.slots));return e.jsxs("div",{className:"relative flex h-full flex-col pl-2 pr-4",children:[L.map((oe,be)=>{if(!oe)return null;const ye=t.getSlotIndexForCard(oe,be),Oe=t.getEffectiveCardTypeForSlot(oe,ye,S==null?void 0:S.slots);return e.jsx(t.MultiInputEmptyRenderer,{onLoadingStatus:Z,onDataChange:H,card:oe,effectiveCardType:Oe},`${oe.id}-${ye}`)}),de&&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",de&&"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(M,{editing:!0,...t.buildMultiInputCustomVisualProps({configCard:l,slotOrderedCards:I,slotTypes:se,multiInputData:j,params:w,theme:D,filters:ke,filterValues:[...te||[],...we||[]],inlineFilters:je})})})})]})}function ve(){var q;return v?le():s&&(a||!_&&!U&&!K)?s({card:r,data:B,isLoading:_,isFetching:U,isError:K}):r.type==="kpi"?_||U?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"w-1/2 space-y-3",children:[e.jsx(Fr,{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:_||U,isError:K,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"?_||U?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(t.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(t.TextCard,{isLoading:c,card:r,data:B==null?void 0:B.records})})})}):e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackVisual,children:e.jsx(Pn,{className:"grow border-none shadow-none"})})}return e.jsxs(t.Tabs,{onValueChange:De,value:n.activeCardId,className:"flex grow flex-col gap-2",children:[v?e.jsx("div",{className:"mt-0 grow",children:ve()}):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:ve()},q.id)),e.jsx(Rr,{isPreviewMode:v,onPreviewToggle:i,configCard:l})]})}function Or({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 $n({fallbackPreview:s,records:a,title:n,isInspectorOpen:r,onInspectorOpenChange:d}){var S;const i=t.useEditorStore(F=>F.card),l=t.useEditorStore(F=>F.actions.setCard),c=t.useEditorStore(F=>F.actions.updateCardInFrame),o=t.normalizeDynamicRendererSource((S=i.dynamicCardPreferences)==null?void 0:S.rendererCode),[m,x]=N.useState(o),[b,h]=N.useState(o);N.useEffect(()=>{x(o),h(o)},[o,i.id]);const u=N.useMemo(()=>t.normalizeDynamicRendererSource(m),[m]),p=N.useMemo(()=>t.validateDynamicRendererSource(u),[u]),j=!!o,f=N.useMemo(()=>{var F;return t.buildCardWithVisualizationMode(i,b?"dynamic":"builtin",{rendererCode:b||void 0,artifactId:((F=i.dynamicCardPreferences)==null?void 0:F.artifactId)||i.id,title:n||i.title})},[i,b,n]),T=!!b,E=u!==b,O=b!==o,C=!u||!p.valid||E||O,k=u?p.valid?E?"Unapplied changes":"Pending save":"Needs attention":"Draft",w=!u||E||O?"outline":"destructive",D=u?p.valid?E?"The preview still reflects the last applied code until you apply this draft.":O?"Preview reflects pending changes. Accept changes to save them.":"":p.error||"Visual code is invalid.":"Paste visual code or generate one before saving this card.";function y(){if(!p.valid){t.ue.error(p.error||"Visual code is invalid.");return}h(u),t.ue.success("Dynamic preview updated.")}function A(){x(b)}function g(){var v;const F=t.buildCardWithVisualizationMode(i,b?"dynamic":"builtin",{rendererCode:b||void 0,artifactId:((v=i.dynamicCardPreferences)==null?void 0:v.artifactId)||t.v4(),title:n||i.title});l(F),c(F),d(!1),t.ue.success(b?"Dynamic visual changes saved.":"Dynamic visual cleared.")}function R(){x(o),h(o),d(!1)}function M(){x(""),h("")}return e.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[e.jsx("div",{className:"min-h-0 flex-1 bg-background px-2",children:j?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(Or,{onClick:()=>d(!0)})]})}),e.jsx(t.Dialog,{open:r,onOpenChange:F=>{if(!F){R();return}d(!0)},children:e.jsxs(t.DialogContent,{className:"flex h-[min(88vh,860px)] max-w-[min(1280px,calc(100vw-2rem))] flex-col gap-0 overflow-hidden p-0",children:[e.jsx(t.DialogHeader,{className:"border-b px-6 py-4 pr-20 text-left",children:e.jsxs("div",{className:"flex items-start justify-between gap-4 pr-4",children:[e.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[e.jsx(t.DialogTitle,{children:"Dynamic Visual Editor"}),e.jsx(t.DialogDescription,{children:"Adjust the preview and visual code here. Query editing stays in the normal editor controls."})]}),C&&e.jsx(t.Badge,{className:"mr-4 shrink-0",variant:w,children:k})]})}),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:T?e.jsx(t.PersistedDynamicVisual,{card:f,records:a,title:n,layoutMode:"fill",fallback:s},b||"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:!j&&!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:M,children:"Clear"})]})]})]}),e.jsxs(t.Button,{type:"button",size:"sm",variant:"outline",className:"h-8 gap-1.5 px-2.5 text-xs",onClick:A,disabled:!E,children:[e.jsx(us,{className:"h-3.5 w-3.5 shrink-0"}),"Reset"]}),e.jsxs(t.Button,{type:"button",size:"sm",className:"h-8 gap-1.5 px-3 text-xs",onClick:y,disabled:!E||!p.valid,children:[e.jsx(t.Play,{className:"h-3.5 w-3.5 shrink-0"}),"Apply to Preview"]})]})]}),e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3 p-4",children:[D&&e.jsx("p",{className:t.cn("text-xs",p.valid?"text-muted-foreground":"text-destructive"),children:D}),e.jsx("div",{className:t.cn("min-h-0 flex-1 overflow-hidden rounded-md border",!p.valid&&u&&"border-destructive"),children:e.jsx(t.CodeEditor,{value:m,onValueChange:F=>x(F||""),language:"javascript",embedded:!0})})]})]})})]})}),e.jsxs(t.DialogFooter,{className:"border-t px-6 py-4 sm:justify-between",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:D||"Preview changes here before saving them."}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{type:"button",variant:"outline",size:"sm",className:"h-8 px-3 text-xs",onClick:R,children:"Cancel"}),e.jsx(t.Button,{type:"button",size:"sm",className:"h-8 px-3 text-xs",onClick:g,disabled:!O,children:"Accept changes"})]})]})]})})]})}function Kn({onCustomize:s}){const a=t.useEditorStore(m=>m.card),n=t.useEditorStore(m=>m.frame),r=t.useEditorStore(m=>m.actions.setIsShowingVisual),{setVisualizationMode:d,setDynamicCardPreferences:i}=t.useEditorActions(),c=t.getVisualizationMode(a)==="dynamic";if(n.cards.length!==1||t.isCustomVisualizationCard(a))return null;const o=m=>{var x;m==="dynamic"&&!a.dynamicCardPreferences&&i(t.createEmptyDynamicCardPreferences(a.type,(x=a.preferences)==null?void 0:x.displayOptions)),d(m),r(!0)};return e.jsxs(e.Fragment,{children:[e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{onSelect:m=>{m.preventDefault(),o(c?"builtin":"dynamic")},className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx(t.CodeXml,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Dynamic"})]}),e.jsx(t.Switch,{checked:c,onCheckedChange:m=>o(m?"dynamic":"builtin"),onClick:m=>m.stopPropagation()})]}),c&&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]})}const Pr={async writeTextToClipboard(s){return typeof navigator>"u"||!navigator.clipboard?!1:(await navigator.clipboard.writeText(s),!0)}},Bt=50,Br=[{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 fn(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 Vr(s){if(!s||typeof s!="object")return{value:s};const a=s.records;return!Array.isArray(a)||a.length<=Bt?{value:s}:{value:{...s,records:a.slice(0,Bt),previewMeta:{truncatedRecords:!0,displayedRecords:Bt,totalRecords:a.length}},truncationMessage:`Preview showing first ${Bt} records of ${a.length}. Copy actions include full payload.`}}function Gn({sql:s,showCardDetails:a=!1,debugPayloads:n,className:r}){const[d,i]=N.useState(!1),[l,c]=N.useState(null),o=t.useEditorStore(g=>g.card),m=t.useEditorStore(g=>g.frame),x=t.useEditorStore(g=>g.isDevMode),b=t.useDashboardStore(g=>g.selectedSheetId),h=t.useDashboardStore(g=>{var R;return(R=g.dashboard)==null?void 0:R.id}),{switchEditorMode:u,setRunSql:p}=t.useEditorActions(),j=N.useMemo(()=>({cardId:o.id||null,frameId:m.id||null,sheetId:b||null,dashboardId:h||null}),[o.id,m.id,b,h]),f=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:j}),[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,j]),T=a&&d&&!!n,E=N.useMemo(()=>[{label:"Card ID",value:o.id||""},{label:"Frame ID",value:m.id||""},{label:"Sheet ID",value:b||""},{label:"Dashboard ID",value:h||""}],[o.id,m.id,b,h]),O=()=>{u("dev",{sqlToLoad:s}),setTimeout(()=>{p(!0)},100)},C=g=>f[g]!==void 0,k=N.useMemo(()=>{if(!l)return null;const g=f[l];if(g===void 0)return null;const R=l==="queryResponse"?Vr(g):{value:g},M=fn(R.value);return M?{target:l,title:gt(l),json:M,truncationMessage:R.truncationMessage}:null},[l,f]),w=k?k.title:"Preview Payload",D=async g=>{const R=f[g];if(R===void 0)return t.ue.error(`No ${gt(g).toLowerCase()} available`),!1;const M=fn(R);if(!M)return t.ue.error(`Unable to serialize ${gt(g).toLowerCase()}`),!1;try{return await Pr.writeTextToClipboard(M)?(t.ue.success(`${gt(g)} copied`),!0):(t.ue.error("Clipboard is not available"),!1)}catch(S){return console.error("Failed to copy debug payload",S),t.ue.error(`Unable to copy ${gt(g).toLowerCase()}`),!1}},y=async()=>k?D(k.target):!1,A=g=>{if(f[g]===void 0){t.ue.error(`No ${gt(g).toLowerCase()} available`);return}c(g)};return e.jsxs("div",{className:t.cn("flex min-h-0 flex-1 flex-col pt-3",r),children:[!x&&e.jsxs("div",{className:"mb-3 flex items-center gap-1.5",children:[e.jsxs(t.Button,{onClick:O,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(!d),variant:"outline",size:"xs",children:[e.jsx(t.Info,{className:"mr-1.5 h-3 w-3"}),"Card Details"]})]}),d&&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:E.map(g=>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:g.label}),e.jsx(t.CopyButton,{text:g.value,className:"h-6 w-6 shrink-0"})]}),e.jsx("code",{title:g.value||"N/A",className:"mt-1 block whitespace-normal break-all font-mono text-xs",children:g.value||"N/A"})]},g.label))}),T&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-background/70 p-3",children:[e.jsx("p",{className:"text-xs font-semibold text-muted-foreground",children:"Debug Tools"}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(t.DropdownMenu,{children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8","aria-label":"Preview Payload Menu",children:[e.jsx(t.Eye,{className:"mr-1.5 h-3.5 w-3.5"}),w,e.jsx(t.ChevronDown,{className:"ml-1.5 h-3.5 w-3.5"})]})}),e.jsx(t.DropdownMenuContent,{align:"start",className:"w-56",children:Br.map(g=>e.jsx(t.DropdownMenuItem,{disabled:!C(g.target),onSelect:()=>A(g.target),className:t.cn(l===g.target&&"bg-accent"),children:g.label},`preview-${g.target}`))})]})}),k&&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:[k.title," Preview"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(t.CopyButton,{text:k.json,className:"h-6 w-6",ariaLabel:"Copy Payload",onCopy:y}),e.jsxs(t.Button,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>c(null),children:[e.jsx(Ae.CircleX,{className:"mr-1 h-3.5 w-3.5"}),"Hide"]})]})]}),k.truncationMessage&&e.jsx("p",{className:"text-xs text-muted-foreground",children:k.truncationMessage}),e.jsx("div",{className:"max-h-80 overflow-auto",children:e.jsx(t.CodeHighlighter,{code:k.json,language:"json"})})]})]})]})}),e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden",children:[e.jsxs("div",{className:"flex h-7 shrink-0 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-5 w-5 rounded-[3px] px-0 text-muted-foreground hover:bg-muted hover:text-foreground"})]}),e.jsx("div",{className:"min-h-[80px] flex-1 px-3 py-2",children:e.jsx(t.CodeEditor,{value:s,onValueChange:()=>{},language:"sql",readOnly:!0,embedded:!0,wrapLines:!0,dense:!0,hideLineNumbers:!0,ariaLabel:"Executed SQL"})})]})]})}function as({children:s,visualAsideControl:a,mode:n="both",isDynamicInspectorOpen:r,onDynamicInspectorOpenChange:d}){var Me;const i=t.useQueryClient(),l=t.useEditorStore(le=>le.frame),c=t.useEditorStore(le=>le.card),o=c.type==="table"||c.type==="detailTable",m=t.useEditorStore(le=>le.isDevMode),x=t.useEditorStore(le=>le.editorContext),b=(x==null?void 0:x.type)==="documentSection",h=t.useEditorStore(le=>le.isShowingVisual),u=t.useEditorStore(le=>le.actions.setIsShowingVisual),p=t.useDashboardStore(le=>le.isVisualEditing),{isConsoleMode:j}=t.useDashboardPreferences(),f=t.useEditorStore(le=>le.pythonStdOut),T=t.useEditorStore(le=>le.actions.setRunSql),E=Ae.useEffectiveEditorCardType(),C=t.getVisualizationMode(c)==="dynamic",[k,w]=N.useState(!1),D=r??k,y=d??w,{setFrame:A,setCard:g,setActiveTabCardId:R,setCardPreferences:M,mergeDraftsIntoCard:S,clearModeDrafts:F,initializeModeDrafts:v,updatePageSize:L,setCardType:I}=t.useEditorActions(),P=N.useMemo(()=>E!==c.type?{...c,type:E}:c,[c,E]),{data:V,isLoading:z,isFetching:B,errorMessage:_,errorSql:U,refetch:K,queryKey:H,pagination:Z}=t.useEditorCardQuery(P),de=N.useRef(H);de.current=H;const{handleDebugWithAssistant:ae}=On(_,U),ce=N.useMemo(()=>(V==null?void 0:V.records)||[],[V==null?void 0:V.records]),{cardFilterValues:me}=t.useCardFilterValues((c==null?void 0:c.id)??""),[he,Ne]=N.useState(!1);N.useEffect(()=>{B||Ne(!1)},[B]),N.useEffect(()=>{o&&!h&&!m&&!j&&u(!0)},[j,m,o,h,u]);function we(le,ve){var ee,ue;const ge={...c,paginationConfig:{page:le+1,pageSize:ve}};g(ge);const $={...l,cards:l.cards.map(Se=>Se.id===c.id?ge:Se)};A($),c.sql&&((ue=(ee=c.preferences)==null?void 0:ee.tablePrefs)!=null&&ue.enableDevModePagination)&&T(!0)}function Ie(le){var ee,ue,Se,q,se;const ve=t.sortStateToSortByColumns(le,(ee=c.config)==null?void 0:ee.metricColumns,(ue=c.config)==null?void 0:ue.groupByColumns,(Se=c.config)==null?void 0:Se.detailColumns),ge={...c,config:{...c.config||{},sortByColumns:ve}};g(ge);const $={...l,cards:l.cards.map(oe=>oe.id===c.id?ge:oe)};A($),c.sql&&((se=(q=c.preferences)==null?void 0:q.tablePrefs)!=null&&se.enableDevModePagination)&&T(!0)}function X(){var ve;const le=JSON.stringify(V==null?void 0:V.records,null,2);typeof navigator>"u"||!((ve=navigator.clipboard)!=null&&ve.writeText)||navigator.clipboard.writeText(le).catch(ge=>{console.error("Failed to copy JSON",ge)})}function je(){const le=JSON.stringify(V==null?void 0:V.records,null,2),ve=new Blob([le],{type:"application/json"}),ge=URL.createObjectURL(ve),$=document.createElement("a");$.href=ge,$.download=`${c.title}.json`,$.click()}function ke(){const ve=[Object.keys(V==null?void 0:V.records.reduce((ue,Se)=>({...ue,...Se}),{})).join(","),...((V==null?void 0:V.records)||[]).map(ue=>Object.values(ue).join(","))].join(`
|
|
192
|
-
`),ge=new Blob([ve],{type:"text/csv"}),$=URL.createObjectURL(ge),ee=document.createElement("a");ee.href=$,ee.download=`${c.title}.csv`,ee.click()}if(!c)return e.jsx(e.Fragment,{children:"No Active Card"});const te=n==="both"||n==="toolbar",De=n==="both"||n==="canvas";return e.jsxs("div",{className:t.cn("relative isolate flex flex-col",n==="toolbar"?"h-auto pb-1":"h-full py-2"),children:[te&&e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center gap-2 px-4",children:[h&&e.jsx("div",{className:"flex grow items-center gap-4",children:e.jsx("div",{className:"flex items-center gap-3",children:!b&&!C&&e.jsx(_n,{selectedChart:c.type,onChartChange:le=>I(le),compactMore:!0})})}),!z&&!B&&!_&&(V==null?void 0:V.sql)&&e.jsx("div",{className:"inline-flex shrink-0 items-center text-[11px] text-muted-foreground",children:e.jsxs(t.HoverCard,{openDelay:200,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"cursor-pointer text-[11px] underline-offset-4 hover:text-foreground hover:underline",children:"View executed SQL"})}),e.jsx(t.HoverCardContent,{align:"end",className:"w-[500px] p-0",children:e.jsx(Gn,{sql:V.sql})})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[s,me&&me.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:"h-7 gap-1.5 px-2",children:[e.jsx(t.Filter,{className:"h-3.5 w-3.5",strokeWidth:1.75}),e.jsx(t.Badge,{variant:"secondary",className:"h-4 min-w-4 rounded-[4px] px-1 text-[10px] font-medium",children:me.length})]})}),e.jsx(t.HoverCardContent,{align:"end",className:"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(me,null,2),language:"json"})]})})]}),e.jsx(t.IconButton,{tooltip:"Refresh",disabled:z||B,className:"h-7 w-7 px-0",onClick:()=>{if(Ne(!0),m){it.flushPendingEditorDrafts(),setTimeout(()=>{i.removeQueries({queryKey:de.current,exact:!0}),T(!0)},0);return}K()},children:e.jsx(t.RefreshCcw,{className:t.cn("h-3.5 w-3.5",{"animate-spin":he})})}),!C&&e.jsx(qn,{showInlineFilters:!1,showDisplayOptions:!1}),(a==null?void 0:a.show)&&e.jsxs(t.Button,{type:"button",variant:"outline",size:"xs","aria-pressed":a.isOpen,onClick:a.onToggle,className:t.cn("h-7 gap-1.5 px-2 text-[12px]",a.isOpen&&"bg-muted/40 text-foreground"),children:[e.jsx(Da,{className:"h-3.5 w-3.5",strokeWidth:1.75}),"Chart settings"]}),(m||j)&&e.jsxs(e.Fragment,{children:[e.jsx($r,{}),o&&e.jsxs(e.Fragment,{children:[e.jsx(_r,{}),e.jsx(qr,{})]})]}),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:[!C&&!["table","detailTable","custom"].includes(c.type)&&p&&e.jsx(br,{triggerVariant:"menu",className:"w-full"}),e.jsx(gs,{triggerVariant:"menu",className:"w-full"}),e.jsx(fs,{triggerVariant:"menu",className:"w-full"}),e.jsx(Kn,{onCustomize:()=>y(!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:ke,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:je,children:[e.jsx(ya,{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:X,children:[e.jsx(t.Copy,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Copy JSON"})]})]})]})]})]})]}),De&&(h?C?e.jsx(ot,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx($n,{fallbackPreview:e.jsx(ot,{}),records:ce,title:c.title,isInspectorOpen:D,onInspectorOpenChange:y})}):e.jsx(ot,{}):e.jsxs(t.ResizablePanelGroup,{className:"py-2 pl-2 pr-6",direction:"horizontal",children:[f&&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:f&&e.jsx(zr,{})}),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":f}),children:[Array.isArray(V==null?void 0:V.records)&&!_&&(m?e.jsx(xr,{data:V.records,card:P,paginationMetadata:Z,onPaginationChange:we,onPageSizePreferenceChange:L,onSortChange:Ie,isLoading:z||B}):V.records.length>0?e.jsx(t.TableVisual,{card:c,data:ce,comparisonMetadata:(Me=V==null?void 0:V.metadata)==null?void 0:Me.comparisonMetadata,paginationMetadata:Z,onPaginationChange:we,onSortChange:Ie,isLoading:z||B}):null),_&&e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(hs,{error:_,errorSql:U||c.sql||c.python,onDebugWithAssistant:ae,showFeedbackButton:!1})})]})]}))]})}function zr(){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 _r(){var n,r;const s=t.useEditorStore(d=>d.card),a=t.useEditorStore(d=>d.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:d=>{var i;a({...s.preferences,tablePrefs:{...(i=s.preferences)==null?void 0:i.tablePrefs,density:d}})},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 qr(){var c,o,m,x,b,h,u,p;const s=t.useEditorStore(j=>j.card),a=t.useEditorStore(j=>j.actions.setCard),n=t.useEditorStore(j=>j.actions.setRunSql),r=t.useEditorStore(j=>j.actions.setCardPreferences),d=t.useEditorStore(j=>j.actions.updateCardInFrame),i=N.useMemo(()=>{var j,f;return t.getTablePageSizeOptions((f=(j=s.preferences)==null?void 0:j.tablePrefs)==null?void 0:f.pageSize)},[(o=(c=s.preferences)==null?void 0:c.tablePrefs)==null?void 0:o.pageSize]),l=t.resolveTablePageSize((x=(m=s.preferences)==null?void 0:m.tablePrefs)==null?void 0:x.pageSize);return s.type!=="table"&&s.type!=="detailTable"?null:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Checkbox,{id:"dev-pagination",checked:((h=(b=s.preferences)==null?void 0:b.tablePrefs)==null?void 0:h.enableDevModePagination)??!1,onCheckedChange:j=>{var f;r({...s.preferences,tablePrefs:{...(f=s.preferences)==null?void 0:f.tablePrefs,enableDevModePagination:j}})}}),e.jsx(t.Label,{htmlFor:"dev-pagination",className:"cursor-pointer text-[13px]",children:"Paginate"}),((p=(u=s.preferences)==null?void 0:u.tablePrefs)==null?void 0:p.enableDevModePagination)&&e.jsxs(t.Select,{value:String(l),onValueChange:j=>{var E,O,C;const f=Number(j),T={...s,preferences:{...s.preferences,tablePrefs:{...(E=s.preferences)==null?void 0:E.tablePrefs,pageSize:f}},paginationConfig:{page:1,pageSize:f}};a(T),d(T),s.sql&&((C=(O=s.preferences)==null?void 0:O.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(j=>e.jsx(t.SelectItem,{value:String(j),children:j},j))})]})]})}function $r(){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:d}){const[i,l]=N.useState(s),c=N.useRef(!1);N.useEffect(()=>{l(s)},[s]);const o=()=>{if(c.current){c.current=!1;return}i!==s&&a(i)},m=x=>{if(x.key==="Enter"){x.currentTarget.blur();return}x.key==="Escape"&&(c.current=!0,l(s),x.currentTarget.blur())};return e.jsx(t.Input,{type:n,placeholder:r,value:i,onChange:x=>l(x.target.value),onBlur:o,onKeyDown:m,className:d})}function nt({defaultValue:s,label:a,options:n,value:r,onValueChange:d,className:i,icon:l,showPlaceholderLabel:c=!0}){return e.jsxs(t.Select,{defaultValue:s,value:r,onValueChange:d,children:[e.jsx(t.SelectTrigger,{className:t.cn("w-full focus:ring-0 focus:ring-offset-0",i),children:e.jsxs("div",{className:"flex items-center gap-2",children:[l&&e.jsx("span",{children:l}),c&&e.jsx(t.SelectValue,{placeholder: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 Kr(s,a){return t.getSlotDefinitionForIndex(s,a)||null}function wt(s){if(typeof s=="number")return`Tab ${s+1}`;const a=s.match(/^(\d+)-(\d+)$/);if(a){const[,r,d]=a;return`Tabs ${Number(r)+1}-${Number(d)+1}`}const n=s.match(/^(\d+)\+$/);return n?`Tabs ${Number(n[1])+1}+`:`Tab ${s}`}function Gr(s){return s?Array.isArray(s)?s:[s]:[]}function rs(s){var r,d;if(!s)return!1;if(s.type==="text")return!!((r=s.description)!=null&&r.trim());const a=!!((d=s.sql)!=null&&d.trim()),n=t.hasValidCardConfig(s.config);return a||n}function Ur({slots:s,cards:a,minInputs:n}){const r=[],d=a.filter(Boolean).length;return n&&d<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];rs(o)||r.push({type:"missing-required",message:`${wt(i.position)} ("${i.label}") is required but has no data configured.`});return}const l=i.position.match(/^(\d+)-(\d+)$/);if(l){const[,o,m]=l.map(Number);for(let x=o;x<=m;x+=1){const b=a[x];if(!rs(b)){r.push({type:"missing-required",message:`${wt(x)} ("${i.label}") is required but has no data configured.`});break}}return}const c=i.position.match(/^(\d+)\+$/);if(c){const o=Number(c[1]);if(a.length<=o){r.push({type:"missing-required",message:`${wt(o)} ("${i.label}") is required but has no data configured.`});return}for(let m=o;m<a.length;m+=1){const x=a[m];if(!rs(x)){r.push({type:"missing-required",message:`${wt(m)} ("${i.label}") is required but has no data configured.`});break}}}}),a.forEach((i,l)=>{if(!i)return;const c=Kr(s,l);if(!c||!c.expectedType)return;const o=Gr(c.expectedType);o.length!==0&&(o.includes(i.type)||r.push({type:"wrong-type",message:`${wt(l)} ("${c.label}") expects ${o.join(", ")}, but is configured as ${i.type}.`}))})),r}const Hr={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 Un(){var M,S,F;const s=t.useEditorStore(v=>v.card.customCardPreferences),{data:a}=t.usePluginQuery(),n=(a==null?void 0:a.plugins)||[],r=t.useEditorStore(v=>v.card),d=t.useEditorStore(v=>v.frame),{setCustomCardPreferences:i}=t.useEditorActions(),l=N.useMemo(()=>t.findCustomVisualConfigCard(d,r),[d,r]),c=l==null?void 0:l.customCardPreferences,{components:o,manifest:m}=t.useCustomVisual((c==null?void 0:c.url)||(s==null?void 0:s.url)||""),x=(M=m==null?void 0:m.visuals)==null?void 0:M.find(v=>v.name===((c==null?void 0:c.componentName)||(s==null?void 0:s.componentName))),h=t.resolveMultiInputType(l||r,x)==="multiple",u=!!l&&l.id===r.id,p=(x==null?void 0:x.minInputs)??((S=l==null?void 0:l.customCardPreferences)==null?void 0:S.minInputs),j=(x==null?void 0:x.maxInputs)??((F=l==null?void 0:l.customCardPreferences)==null?void 0:F.maxInputs),f=N.useMemo(()=>t.getCustomVisualInputCards({frame:d,configCard:l||r,isMultiInputVisual:h}),[d,l,r,h]),T=N.useMemo(()=>t.buildSlotOrderedCards(f),[f]),E=N.useMemo(()=>T.map((v,L)=>{if(!v)return null;const I=t.getSlotIndexForCard(v,L),P=t.getEffectiveCardTypeForSlot(v,I,x==null?void 0:x.slots);return{...v,type:P??v.type}}),[T,x==null?void 0:x.slots]),O=N.useMemo(()=>Ur({slots:x==null?void 0:x.slots,cards:E,minInputs:p}),[x==null?void 0:x.slots,E,p]),C=N.useMemo(()=>{const v=f.findIndex(L=>(L==null?void 0:L.id)===r.id);return v<0?-1:t.getSlotIndexForCard(r,v)},[f,r]);function k(v){if(typeof v=="number")return`Tab ${v+1}`;const L=v.match(/^(\d+)-(\d+)$/);if(L){const[,P,V]=L;return`Tabs ${Number(P)+1}-${Number(V)+1}`}const I=v.match(/^(\d+)\+$/);return I?`Tabs ${Number(I[1])+1}+`:`Tab ${v}`}function w(v){return v?(Array.isArray(v)?v:[v]).join(", "):null}function D(v,L,I=[],P="",V,z,B){const _=y({key:L,defaultValue:P,settingsValue:z,sourceCard:B});return v==="input"?e.jsx(qe,{className:`h-8 w-full ${t.removeRing}`,value:String(_??""),onCommit:U=>{A({key:L,value:U,settingsField:V,settingsValue:z,sourceCard:B})}},L):v==="select"?e.jsx(nt,{className:"h-8 w-full",label:"",options:I,value:String(_!==void 0?_:P??""),onValueChange:U=>{A({key:L,value:U,settingsField:V,settingsValue:z,sourceCard:B})}}):null}function y({key:v,defaultValue:L,settingsValue:I,sourceCard:P}){const V=I==null?void 0:I[v];return V!==void 0?V:v==="title"&&(P==null?void 0:P.title)!==void 0?P.title:v==="description"&&(P==null?void 0:P.description)!==void 0?P.description:L}function A({key:v,value:L,settingsField:I,settingsValue:P,sourceCard:V}){const z={...P||{}},B=v==="title"&&(V==null?void 0:V.title)!==void 0,_=v==="description"&&(V==null?void 0:V.description)!==void 0;B&&L===String((V==null?void 0:V.title)??"")||_&&L===String((V==null?void 0:V.description)??"")?delete z[v]:z[v]=L,i({...s||{},[I]:z})}function g({settingsSchema:v,settingsField:L,settingsValue:I,sourceCard:P,headerLabel:V}){const z=Object.entries(v||{});return e.jsxs("div",{className:"space-y-3",children:[V&&e.jsx(t.Label,{children:V}),z.map(([B,_])=>{var U;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{children:_.title}),((U=_.docs)==null?void 0:U.description)&&e.jsx(t.TooltipProvider,{delayDuration:0,children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{className:"text-xs",children:_.docs.description})})]})})]}),D(_.ui,B,_.options,_.defaultValue,L,I,P)]},B)})]})}function R(){return e.jsxs(e.Fragment,{children:[h&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Slot Guide"}),e.jsx("div",{className:"space-y-3 rounded-md border border-border bg-muted/40 px-3 py-2 text-xs",children:x!=null&&x.slots&&x.slots.length>0?e.jsx("div",{className:"space-y-3",children:x.slots.map((v,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:k(v.position)}),e.jsx("span",{className:"text-muted-foreground",children:"•"}),e.jsx("span",{className:"font-medium",children:v.label})]}),v.description&&e.jsx("p",{className:"text-muted-foreground",children:v.description}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-muted-foreground",children:[w(v.expectedType)&&e.jsxs("span",{children:["Expected: ",w(v.expectedType)]}),v.required&&e.jsx("span",{children:"Required"})]})]},`${v.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."}),(p||j)&&e.jsxs("p",{children:[p?`Min ${p} tabs`:"",p&&j?" • ":"",j?`Max ${j} tabs`:""]})]})})]}),h&&O.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:O.map((v,L)=>e.jsx("li",{children:v.message},`${v.type}-${L}`))})})}),x&&!h&&x.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:g({settingsSchema:x.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:r})})}),x&&h&&(x.settings||x.slotSettings)&&e.jsxs("div",{className:"mt-4 space-y-4",children:[u&&x.settings&&e.jsx("div",{className:"px-2",children:g({settingsSchema:x.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:l||r,headerLabel:"Global Settings"})}),x.slotSettings&&e.jsx("div",{className:"px-2",children:g({settingsSchema:x.slotSettings,settingsField:"slotSettings",settingsValue:s==null?void 0:s.slotSettings,sourceCard:r,headerLabel:(()=>{const v=r.tabTitle||r.title,L=C>=0?C:0,I=u?"Slot 0":`Slot ${L}`;return v?`${I}: ${v} Settings`:`${I} Settings`})()})})]})]})}return e.jsxs(t.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"",children:[e.jsxs(t.AccordionItem,{value:"plugin-settings",children:[e.jsx(t.AccordionTrigger,{children:"Plugin"}),e.jsx(t.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[(!h||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:(c==null?void 0:c.url)||"",onValueChange:v=>i({...s||{url:"",componentName:""},url:v})}),h&&!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&&(!h||u)&&e.jsx(e.Fragment,{children:o&&e.jsx(nt,{icon:e.jsx(va,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(o==null?void 0:o.map(v=>({value:v.name,label:v.name})))||[],value:s.componentName||"",onValueChange:v=>{var P;const L=(P=m==null?void 0:m.visuals)==null?void 0:P.find(V=>V.name===v),I=o==null?void 0:o.find(V=>V.name===v);i({...s,componentName:v,visualType:(L==null?void 0:L.visualType)||(I==null?void 0:I.type)||"single",minInputs:L==null?void 0:L.minInputs,maxInputs:L==null?void 0:L.maxInputs,pluginChartType:L==null?void 0:L.chartType})}})})]})})]}),((c==null?void 0:c.componentName)||(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:(x==null?void 0:x.name)||"Settings"}),(x==null?void 0:x.docs)&&e.jsxs(t.HoverCard,{openDelay:0,closeDelay:100,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,onClick:v=>v.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:[x.docs.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:x.docs.description}),x.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:Hr,children:x.docs.dataSchema})})]}),(()=>{var L;const v=(L=x.docs)==null?void 0:L.useCases;return!v||v.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:v.map((I,P)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1 text-primary",children:"•"}),e.jsx("span",{children:I})]},P))})]})})()]})})]})]})}),e.jsx(t.AccordionContent,{children:R()})]})]})}function Qr({colorRanges:s,setColorRanges:a}){const n={start:-1/0,end:100,color:""};function r(l,c,o){const m=[...s];m[l]={...m[l],[c]:o},a(m)}function d(l){const c=[...s];c.splice(l,1),a(c)}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,c)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(t.Input,{onChange:o=>r(c,"start",o.target.value),value:l.start,className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(t.Input,{value:l.end,onChange:o=>r(c,"end",o.target.value),className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx(t.Input,{onChange:o=>r(c,"color",o.target.value),value:l.color,className:t.cn(`h-7 min-w-14 p-0 ${t.removeRing}`),type:"color",list:"presetColors"}),e.jsxs("datalist",{id:"presetColors",children:[e.jsx("option",{children:t.colors.green[600]}),e.jsx("option",{children:t.colors.red[500]}),e.jsx("option",{children:t.colors.yellow[400]}),e.jsx("option",{children:t.colors.orange[500]})]}),e.jsx(t.Button,{onClick:()=>d(c),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(t.X,{className:"size-3"})})]},c))]})}function Wr(){var x,b,h,u,p;const s=t.useEditorStore(j=>j.card.preferences),a=t.useEditorStore(j=>j.actions.setCardPreferences),n=t.useEditorStore(j=>j.card),r=t.hasValidCardConfig(n.config),d=t.useEditorStore(j=>j.actions.setNumberFormat);t.useEditorStore(j=>{var f,T;return(T=(f=j.card.preferences)==null?void 0:f.formatNumber)==null?void 0:T.decimalPlaces});const i=t.useEditorStore(j=>{var f,T;return(T=(f=j.card.preferences)==null?void 0:f.formatNumber)==null?void 0:T.locale}),l=t.useEditorStore(j=>{var f,T;return(T=(f=j.card.preferences)==null?void 0:f.formatNumber)==null?void 0:T.currency});t.useEditorStore(j=>j.actions.setFilterOnClickField);const c=t.useEditorStore(j=>{var f,T;return(T=(f=j.card.preferences)==null?void 0:f.formatNumber)==null?void 0:T.colorRanges})||[],o=t.useEditorStore(j=>j.actions.setColorRanges),m=[...new Set(t.LOCALE_CURRENCY_PAIRS.map(j=>j.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(t.Checkbox,{checked:!!((x=s==null?void 0:s.formatNumber)!=null&&x.enabled),onCheckedChange:j=>{a({...s,formatNumber:{...s==null?void 0:s.formatNumber,enabled:j}})}}),e.jsx(t.Label,{children:"Format Number"})]}),(((b=s==null?void 0:s.formatNumber)==null?void 0:b.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:j=>{var f,T,E;return d(((f=s==null?void 0:s.formatNumber)==null?void 0:f.decimalPlaces)||0,((T=s==null?void 0:s.formatNumber)==null?void 0:T.currency)||"",j,((E=s==null?void 0:s.formatNumber)==null?void 0:E.suffix)||"")},children:[e.jsx(t.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Format"}),e.jsx(t.SelectItem,{value:"none",children:"Auto"},"none"),t.LOCALE_CURRENCY_PAIRS.map(j=>e.jsx(t.SelectItem,{value:j.locale,children:j.locale},j.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:j=>{var f,T,E;console.log("currency",j),d(((f=s==null?void 0:s.formatNumber)==null?void 0:f.decimalPlaces)||0,j==="none"?"":j,((T=s==null?void 0:s.formatNumber)==null?void 0:T.locale)||"",((E=s==null?void 0:s.formatNumber)==null?void 0:E.suffix)||"")},children:[e.jsx(t.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Currency"}),e.jsx(t.SelectItem,{value:"none",children:"None"},"none"),m.map(j=>e.jsx(t.SelectItem,{value:j,children:j},j))]})})]})]})]}),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=(h=s==null?void 0:s.formatNumber)==null?void 0:h.decimalPlaces)==null?void 0:u.toString())||"0",onValueChange:j=>{var f,T,E;return d(Number(j),((f=s==null?void 0:s.formatNumber)==null?void 0:f.currency)||"",((T=s==null?void 0:s.formatNumber)==null?void 0:T.locale)||"",((E=s==null?void 0:s.formatNumber)==null?void 0:E.suffix)||"")},children:[e.jsx(t.SelectTrigger,{className:"col-span-3 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:["0","1","2","3","4"].map(j=>e.jsx(t.SelectItem,{value:j,children:j},j))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Suffix"}),e.jsx(t.Input,{value:((p=s==null?void 0:s.formatNumber)==null?void 0:p.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:j=>{var f,T,E;return d(((f=s==null?void 0:s.formatNumber)==null?void 0:f.decimalPlaces)||0,((T=s==null?void 0:s.formatNumber)==null?void 0:T.currency)||"",((E=s==null?void 0:s.formatNumber)==null?void 0:E.locale)||"",j.target.value)}})]})]})]})}),e.jsx(t.Separator,{className:"my-3"}),e.jsx(Qr,{colorRanges:c,setColorRanges:o})]})]})}const Jr={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 Hn(s){return Jr[s]}function Yr({chartType:s,showDocsLink:a=!0}){const n=Hn(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,d)=>e.jsxs("tr",{className:d<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 Xr({chartType:s}){return Hn(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(Yr,{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(Xr,{chartType:s})]})}function Zr(){return e.jsxs("div",{className:"space-y-6 px-6 py-4",children:[e.jsx($t,{chartType:"kpi"}),e.jsx("section",{children:e.jsx(Wr,{})})]})}function gn({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 Qn(){const[s,a]=N.useState([]),n=t.useEditorStore(m=>m.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:d}=t.useEditorStore(m=>m.actions),i=t.useEditorStore(m=>m.queryResultColumns);t.useEditorStore(m=>{var x;return(x=m.card.preferences)==null?void 0:x.filterOnClickColumnIndex}),N.useEffect(()=>{i&&a(new Array(i.length).fill(!1))},[i]);function l(m,x){var b,h;x?n!=null&&n.onClickFilter&&((b=n==null?void 0:n.onClickFilter)==null?void 0:b.length)>0?d({...n,onClickFilter:[...n.onClickFilter,{columnIndex:m,expression:""}]}):d({...n,onClickFilter:[{columnIndex:m,expression:""}]}):(d({...n,onClickFilter:(h=n==null?void 0:n.onClickFilter)==null?void 0:h.filter(u=>u.columnIndex!==m)}),a(u=>{const p=[...u];return p[m]=!1,p}))}function c(m,x){var h;const b=(h=n==null?void 0:n.onClickFilter)==null?void 0:h.map(u=>u.columnIndex===m?{...u,expression:x.target.value}:u);d({...n,onClickFilter:b})}function o(m){var x,b,h,u;if(s!=null&&s[m]||(b=(x=n==null?void 0:n.onClickFilter)==null?void 0:x.find(p=>p.columnIndex===m))!=null&&b.expression)return e.jsx(t.Input,{value:(u=(h=n==null?void 0:n.onClickFilter)==null?void 0:h.find(p=>p.columnIndex===m))==null?void 0:u.expression,onChange:p=>c(m,p),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,x)=>{var b,h;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(t.Checkbox,{checked:!!((b=n==null?void 0:n.onClickFilter)!=null&&b.find(u=>u.columnIndex===x)),onCheckedChange:u=>l(x,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:((h=n==null?void 0:n.onClickFilter)==null?void 0:h.find(u=>u.columnIndex===x))&&e.jsx(t.Pencil,{onClick:()=>{a(u=>{const p=[...u];return p[x]=!u[x],p})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),o(x)]})},m)})})}const el=[{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"}],tl=["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"],sl=tl.map(s=>({label:s,value:s}));function nl(){var o,m,x,b,h,u,p,j,f,T,E,O,C,k,w,D,y,A;const s=t.useEditorStore(g=>g.card),a=(m=(o=s==null?void 0:s.preferences)==null?void 0:o.mapVisualOptions)==null?void 0:m.topoJsonUrl,[n,r]=N.useState(((b=(x=s==null?void 0:s.preferences)==null?void 0:x.mapVisualOptions)==null?void 0:b.customTopoJsonUrl)||""),{setCardPreferences:d}=t.useEditorActions(),{data:i}=t.useTopoJson(s),l=Object.keys((i==null?void 0:i.objects)||{}).map(g=>({label:g,value:g}))||[],c=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx($t,{chartType:"map"}),e.jsx(gn,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(nt,{className:"h-9",options:c,onValueChange:g=>{console.log("value",g),d({...s.preferences,mapVisualOptions:{topoJsonUrl:g}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(t.Input,{onChange:g=>{r(g.target.value)},onBlur:()=>{var g;console.log("onBlur",n),d({...s.preferences,mapVisualOptions:{...(g=s.preferences)==null?void 0:g.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=(h=s.preferences)==null?void 0:h.mapVisualOptions)==null?void 0:u.objectKey)||"",label:"Map Object",onValueChange:g=>{var R;d({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,objectKey:g}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Projection"}),e.jsx(nt,{className:"h-9",options:el,value:((j=(p=s.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:j.projection)||"",label:"Projection",onValueChange:g=>{var R;d({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,projection:g}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Colors"}),e.jsx(nt,{className:"h-9",options:sl,value:((T=(f=s.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:T.colorScale)||"",label:"Select Color Scale",onValueChange:g=>{var R;d({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,colorScale:g}})}})]})]})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(gn,{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:((O=(E=s.preferences)==null?void 0:E.mapVisualOptions)==null?void 0:O.projectionScale)||1,onChange:g=>{var R;d({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,projectionScale:Number(g.target.value)}})}}),e.jsx(t.Label,{children:"X"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((w=(k=(C=s.preferences)==null?void 0:C.mapVisualOptions)==null?void 0:k.projectionOffset)==null?void 0:w[0])||0,onChange:g=>{var R,M,S,F;d({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,projectionOffset:[Number(g.target.value),((F=(S=(M=s.preferences)==null?void 0:M.mapVisualOptions)==null?void 0:S.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:((A=(y=(D=s.preferences)==null?void 0:D.mapVisualOptions)==null?void 0:y.projectionOffset)==null?void 0:A[1])||0,onChange:g=>{var R,M,S,F;d({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,projectionOffset:[((F=(S=(M=s.preferences)==null?void 0:M.mapVisualOptions)==null?void 0:S.projectionOffset)==null?void 0:F[0])||0,Number(g.target.value)]}})}})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(Qn,{})]})}function Wn({color:s,onColorChange:a,onClose:n}){const[r,d]=N.useState(0),[i,l]=N.useState(100),[c,o]=N.useState(50),[m,x]=N.useState(s);N.useEffect(()=>{const f=bn(s);if(f){const T=jn(f.r,f.g,f.b);d(T.h),l(T.s),o(T.l),x(s)}},[s]);const b=f=>{d(f),u(f,i,c)},h=f=>{const T=f.currentTarget.getBoundingClientRect(),E=Math.max(0,Math.min(1,(f.clientX-T.left)/T.width)),O=Math.max(0,Math.min(1,(f.clientY-T.top)/T.height)),C=E*100,k=(1-O)*100;l(C),o(k),u(r,C,k)},u=(f,T,E)=>{const O=rl(f,T,E),C=al(O.r,O.g,O.b);x(C)},p=f=>{if(x(f),/^#[0-9A-Fa-f]{6}$/.test(f)){const T=bn(f);if(T){const E=jn(T.r,T.g,T.b);d(E.h),l(E.s),o(E.l)}}},j=()=>{/^#[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:h,onMouseMove:f=>{f.buttons===1&&h(f)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${i}%`,top:`${100-c}%`,backgroundColor:m}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:f=>b(Number(f.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:f=>p(f.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:j,children:"OK"})]})]})}function bn(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 al(s,a,n){return"#"+((1<<24)+(s<<16)+(a<<8)+n).toString(16).slice(1)}function jn(s,a,n){s/=255,a/=255,n/=255;const r=Math.max(s,a,n),d=Math.min(s,a,n);let i=0,l=0;const c=(r+d)/2;if(r!==d){const o=r-d;switch(l=c>.5?o/(2-r-d):o/(r+d),r){case s:i=((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(c*100)}}function rl(s,a,n){s/=360,a/=100,n/=100;let r,d,i;if(a===0)r=d=i=n;else{const l=(m,x,b)=>(b<0&&(b+=1),b>1&&(b-=1),b<.16666666666666666?m+(x-m)*6*b:b<.5?x:b<.6666666666666666?m+(x-m)*(.6666666666666666-b)*6:m),c=n<.5?n*(1+a):n+a-n*a,o=2*n-c;r=l(o,c,s+1/3),d=l(o,c,s),i=l(o,c,s-1/3)}return{r:Math.round(r*255),g:Math.round(d*255),b:Math.round(i*255)}}const vn=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],ll=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function at({value:s,onChange:a,label:n}){const[r,d]=N.useState(!1),[i,l]=N.useState(!1),c=()=>{const o=vn.find(m=>m.value===s);return o?o.color:s.startsWith("#")?s:vn[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Popover,{open:r,onOpenChange:d,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"size-5 rounded border-2 border-input shadow-sm transition-all hover:scale-110 hover:border-gray-400",style:{backgroundColor:c()},"aria-label":`Change color for ${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:ll.map(o=>e.jsx("button",{className:t.cn("h-5 w-5 rounded border-2 transition-all",c()===o?"border-gray-900":"border-transparent"),style:{backgroundColor:o},onClick:()=>{a(o),d(!1)},children:e.jsx("span",{className:"sr-only",children:o})},o))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{l(!0),d(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children: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(Wn,{color:c(),onColorChange:o=>{a(o),l(!1)},onClose:()=>l(!1)})})]})]})}function zt(s){return s==="currency"?2:s==="percent"?1:s==="scientific"?2:0}function yn(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?ms(n,zt(a)):n}function ms(s,a){return{...s,decimalPlaces:a,minimumFractionDigits:a,maximumFractionDigits:a}}const ol=["auto","number","currency","percent","scientific","date"],il=[{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"}],cl=[{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"}],dl=s=>s.charAt(0).toUpperCase()+s.slice(1);function jt({formatOptions:s={},onFormatOptionsChange:a,showTitle:n=!0,title:r="NUMBER FORMAT"}){const d=s.type||"auto",i=d==="auto"?s:yn(s,d),l=u=>{u.stopPropagation()},c=(u,p)=>{a({...i,[u]:p})},[o,m]=N.useState(()=>String(i.decimalPlaces??zt(d))),[x,b]=N.useState(()=>i.multiplyBy!==void 0?String(i.multiplyBy):""),h=u=>{a(yn(s,u))};return N.useEffect(()=>{m(String(i.decimalPlaces??zt(d)))},[i.decimalPlaces,d]),N.useEffect(()=>{b(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:d,onValueChange:u=>h(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:ol.map(u=>e.jsx(t.SelectItem,{value:u,className:"text-xs",children:u==="auto"?"Auto (Default)":dl(u)},u))})]})]}),d!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent","scientific"].includes(d)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{type:"text",inputMode:"numeric",min:"0",max:"10",placeholder:"0",value:o,onClick:l,onPointerDown:l,onKeyDown:l,onChange:u=>{const p=u.target.value.replace(/[^\d]/g,"");m(p),p!==""&&a(ms(i,Math.max(0,Math.min(10,parseInt(p,10)))))},onBlur:()=>{if(o!=="")return;const u=zt(d);m(String(u)),a(ms(i,u))},className:"h-8 text-xs"})})]}),d==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(t.Select,{value:s.currency||"USD",onValueChange:u=>c("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:il.map(u=>e.jsx(t.SelectItem,{value:u.value,className:"text-xs",children:u.label},u.value))})]})]}),["number","currency"].includes(d)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(t.Switch,{size:"sm",checked:s.useSuffix??!1,onClick:u=>u.stopPropagation(),onCheckedChange:u=>c("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=>c("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:cl.map(u=>e.jsx(t.SelectItem,{value:u.value,className:"text-xs",children:u.label},u.value))})]})]}),d==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{placeholder:"e.g., $",value:s.prefix||"",onClick:l,onPointerDown:l,onKeyDown:l,onChange:u=>c("prefix",u.target.value),className:"h-8 text-xs"})})]}),d==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{placeholder:"e.g., units",value:s.suffix||"",onClick:l,onPointerDown:l,onKeyDown:l,onChange:u=>c("suffix",u.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(d)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Negative in ()"}),e.jsx(t.Switch,{size:"sm",checked:s.negativeInParentheses??!1,onClick:u=>u.stopPropagation(),onCheckedChange:u=>c("negativeInParentheses",u)})]}),d==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{type:"text",inputMode:"decimal",placeholder:"100",value:x,onClick:l,onPointerDown:l,onKeyDown:l,onChange:u=>{const p=u.target.value.replace(/[^0-9.]/g,"");b(p),c("multiplyBy",p?parseFloat(p):void 0)},className:"h-8 text-xs"})})]}),d==="date"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Format"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{type:"text",placeholder:"MM/DD/YYYY",value:s.dateFormat||"",onClick:l,onPointerDown:l,onKeyDown:l,onChange:u=>c("dateFormat",u.target.value),className:"h-8 text-xs"})})]})]})]})}function bs({value:s,onChange:a,showTitle:n=!0,title:r="NUMBER FORMAT"}){const d=t.toTFormatOptions(t.fromSemanticFormat(s))||{},i=l=>{a(t.fromTFormatOptions(l))};return e.jsx(jt,{formatOptions:d,onFormatOptionsChange:i,showTitle:n,title:r})}function ul(){const s=t.useDashboardStore(c=>c.dashboard.filters),a=t.useEditorStore(c=>c.frame),{setFrame:n}=t.useEditorActions(),{dashboardFilterableFields:r}=t.useFilterableFields(),{assignFilter:d}=t.useAssignFilter();function i(c){const o=d(c,"frame");n({...a,filterId:o})}const l=s==null?void 0:s.find(c=>c.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Card Filter"}),e.jsx(ml,{onSelect:i,columns:r}),l&&e.jsx(t.FilterHeader,{filter:l})]})}function ml({columns:s,onSelect:a}){var c;const[n,r]=Vt.useState(!1),[d,i]=Vt.useState(""),l=Vt.useCallback(o=>[o.label,o.name,o.qualifiedEntityName].filter(Boolean).join(" "),[]);return e.jsxs(t.Popover,{open: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:[d?((c=s.find(o=>o.id===d))==null?void 0:c.label)||d:"Select Column...",e.jsx(t.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No column found."}),e.jsx(t.CommandGroup,{children:s==null?void 0:s.map(o=>e.jsxs(t.CommandItem,{value:l(o),onSelect:()=>{const m=o.id===d?"":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",d===o.id?"opacity-100":"opacity-0")})]},o.id))})]})]})})]})}const xl=[{value:"difference",label:"Difference"},{value:"change",label:"Change (%)"},{value:"change_difference",label:"Change + Difference"},{value:"ratio",label:"Ratio"}],hl=[{value:"arrow_badge",label:"Arrow + Badge"},{value:"arrow",label:"Arrow Only"},{value:"badge",label:"Badge Only"},{value:"none",label:"None"}];function pl({cardType:s="table"}){var x,b,h,u,p;const a=t.useEditorStore(j=>j.card),n=t.useEditorStore(j=>{var f;return(f=j.card)==null?void 0:f.preferences}),r=t.useEditorStore(j=>j.actions.setCardPreferences),d=((x=a.config)==null?void 0:x.metricColumns)||[],i=d.some(j=>j.comparisonType&&j.comparisonType!=="none"),l=((b=n==null?void 0:n.tableVisualOptions)==null?void 0:b.metricComparison)||{},c=j=>{r({...n,tableVisualOptions:{...n==null?void 0:n.tableVisualOptions,metricComparison:{...l,...j}}})},o={increase:((h=l.colors)==null?void 0:h.increase)||"green",decrease:((u=l.colors)==null?void 0:u.decrease)||"red",neutral:((p=l.colors)==null?void 0:p.neutral)||"neutral"},m=j=>{r({...n,allowDownload:j})};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:j=>c({calculatedAs:j}),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:xl.map(j=>e.jsx(t.SelectItem,{value:j.value,className:"text-xs",children:j.label},j.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Number Format"}),e.jsx(jt,{formatOptions:l.formatOptions||{},onFormatOptionsChange:j=>c({formatOptions:j}),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:j=>c({indicatorStyle:j}),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:hl.map(j=>e.jsx(t.SelectItem,{value:j.value,className:"text-xs",children:j.label},j.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:j=>c({colors:{...o,increase:j}}),label:"Increase"}),e.jsx(at,{value:o.decrease,onChange:j=>c({colors:{...o,decrease:j}}),label:"Decrease"}),e.jsx(at,{value:o.neutral,onChange:j=>c({colors:{...o,neutral:j}}),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:j=>c({lowerIsBetter:!!j})})]})]})]}),d.length>0&&e.jsxs(t.AccordionItem,{value:"metric-formats",className:"border-none",children:[e.jsx(t.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsx("span",{children:"Metric Formats"})}),e.jsx(t.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:d.map(j=>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:j.label||j.name}),e.jsx(bs,{value:j.format,onChange:f=>{var E;const T=(((E=a.config)==null?void 0:E.metricColumns)||[]).map(O=>O.id===j.id?{...O,format:f}:O);t.useEditorStore.getState().actions.updateCardConfig(a.id,{metricColumns:T})},showTitle:!1})]},j.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(Qn,{}),e.jsx(ul,{})]})]})]}),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 fl(){var r;const s=t.useEditorStore(d=>d.card.preferences),{setCardPreferences:a}=t.useEditorStore(d=>d.actions);function n(d){a({...s,textVisualOptions:{...s==null?void 0:s.textVisualOptions,isDynamicText:d==="dynamic"}})}return e.jsxs(t.RadioGroup,{value:(r=s==null?void 0:s.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange: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 gl(){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(fl,{})]})]})}const bl=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function jl(){var k,w,D,y,A,g,R,M,S,F;const s=t.useEditorStore(v=>v.card),a=t.useEditorStore(v=>{var L;return(L=v.card)==null?void 0:L.preferences}),n=Ae.useEffectiveEditorCardType(),{setCardPreferences:r,updateCardInFrame:d}=t.useEditorActions(),i=N.useMemo(()=>n!==s.type?{...s,type:n}:s,[s,n]),{data:l}=t.useEditorCardQuery(i),[c,o]=N.useState({}),[m,x]=N.useState(null),[b,h]=N.useState(null),u=N.useMemo(()=>{var P,V,z,B,_,U,K;if(!(l!=null&&l.records)||l.records.length===0)return[];const v=n==="stackedBar"||n==="stackedLine",L=n==="bar"||n==="line"||n==="horizontalBar"||n==="bullet"||n==="combo"||n==="area"||n==="stackedArea",I=((P=s==null?void 0:s.config)==null?void 0:P.pivotByColumns)&&s.config.pivotByColumns.length>0;if((v||L)&&I){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const H=new Set;return l.pivotSchema.forEach(Z=>{Z.alias&&H.add(Z.alias)}),Array.from(H)}if(l.records.length>0){const H=l.records[0],Z=Object.keys(H),de=new Set;(V=s==null?void 0:s.config)!=null&&V.groupByColumns&&s.config.groupByColumns.forEach(me=>{de.add(me.label||me.name),de.add(me.alias||me.name)});const ae=new Set;return(z=s==null?void 0:s.config)!=null&&z.metricColumns&&s.config.metricColumns.forEach(me=>{const he=me.alias||me.name;ae.add(he),ae.add(`${he}_count`),ae.add(`${he}_sum`),ae.add(`${he}_avg`),ae.add(`${he}_min`),ae.add(`${he}_max`);const Ne=me.entityName||me.qualifiedEntityName;Ne&&(ae.add(`${Ne}_${he}`),ae.add(`${Ne}_${he}_count`))}),Z.filter(me=>!de.has(me)&&!ae.has(me))}}if((L||v)&&!I&&((_=(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((K=(U=s==null?void 0:s.config)==null?void 0:U.groupByColumns)!=null&&K.length){const H=s.config.groupByColumns[0],Z=H.label||H.name,de=new Set;return l.records.forEach(ae=>{const ce=ae[Z];ce!=null&&de.add(String(ce))}),Array.from(de)}return[]},[l,(k=s==null?void 0:s.config)==null?void 0:k.groupByColumns,(w=s==null?void 0:s.config)==null?void 0:w.pivotByColumns,(D=s==null?void 0:s.config)==null?void 0:D.metricColumns,n]),p=N.useMemo(()=>t.getDefaultChartColors(),[]);N.useEffect(()=>{const v={};u.forEach((L,I)=>{v[L]=t.getColorForValue(L,I,a==null?void 0:a.colorConfig)}),o(v)},[u,a==null?void 0:a.colorConfig,p]);const j=(v,L)=>{const I={...c,[v]:L};o(I);const P={...a||{},colorConfig:{segments:I}};r(P);const V={...s,preferences:P};d(V)},f=(v,L)=>{var _;const I=p[L%p.length],{[v]:P,...V}=((_=a==null?void 0:a.colorConfig)==null?void 0:_.segments)||{},z={...a||{},colorConfig:{segments:V}};r(z);const B={...s,preferences:z};d(B),o(U=>({...U,[v]:I}))};if(!u.length||!((s==null?void 0:s.type)==="stackedBar"||(s==null?void 0:s.type)==="stackedLine"?((A=(y=s==null?void 0:s.config)==null?void 0:y.groupByColumns)==null?void 0:A.length)||((R=(g=s==null?void 0:s.config)==null?void 0:g.pivotByColumns)==null?void 0:R.length):(S=(M=s==null?void 0:s.config)==null?void 0:M.groupByColumns)==null?void 0:S.length)||["table","kpi","text","custom","heatmap"].includes(n))return null;const O=()=>{const v={...a||{},colorConfig:{segments:{}}};r(v);const L={...s,preferences:v};d(L);const I={};u.forEach((P,V)=>{I[P]=t.getColorForValue(P,V,void 0)}),o(I)},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(Ia,{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:O,children:[e.jsx(us,{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((v,L)=>{const I=t.isDefaultColor(c[v],L),P=!I;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Popover,{open:m===v,onOpenChange:V=>x(V?v:null),children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"h-5 w-5 shrink-0 rounded border border-input shadow-sm transition-colors hover:border-gray-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",style:{backgroundColor:c[v]}})}),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:p.slice(0,10).map((V,z)=>e.jsxs("button",{className:t.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",c[v]===V?"border-gray-900":"border-transparent"),style:{backgroundColor:V},onClick:()=>{j(v,V),x(null)},children:[z===L%p.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:V})]},`default-${z}`))})]}),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:bl.map((V,z)=>e.jsx("button",{className:t.cn("h-5 w-5 rounded border transition-all hover:scale-110",c[v]===V?"border-2 border-gray-900":V==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:V},onClick:()=>{j(v,V),x(null)},children:e.jsx("span",{className:"sr-only",children:V})},`preset-${z}`))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsx("button",{className:"text-sm font-medium text-blue-600 hover:text-blue-700",onClick:()=>{h({value:v,color:c[v]}),x(null)},children:"Custom color"}),!I&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{f(v,L),x(null)},children:[e.jsx(us,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:v}),P&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},v)})}),b&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>h(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Wn,{color:b.color,onColorChange:v=>{j(b.value,v),h(null)},onClose:()=>h(null)})})]})]})})]})}function Qe({value:s,onSave:a,placeholder:n="",type:r="text",className:d=""}){const[i,l]=N.useState(s??""),[c,o]=N.useState(!1);N.useEffect(()=>{l(s??"")},[s]);const m=()=>{a(i),o(!1)},x=()=>{l(s??""),o(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${d}`,children:[e.jsx(t.Input,{placeholder:n,type:r,value:c?i:s??"",onChange:b=>{l(b.target.value),o(!0)},onFocus:()=>o(!0),onClick:b=>b.stopPropagation(),className:"h-8 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.stopPropagation(),b.key==="Enter"&&c&&i!==s?m():b.key==="Escape"&&x()},"aria-label":n||"Edit field"}),c&&i!==s&&e.jsxs(e.Fragment,{children:[e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick: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:x,children:e.jsx(t.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function ls({axis:s,label:a,type:n,config:r,onChange:d,defaultTitle:i,hidePosition:l}){var p,j,f,T,E,O,C,k,w,D,y,A,g,R;const c=t.normalizeContextFormatMode({formatMode:r==null?void 0:r.formatMode,formatOptions:r==null?void 0:r.formatOptions}),o=(M,S)=>{d({...r??{},[M]:S})},m=(M,S)=>{var I,P,V,z;const F=M==="enabled"&&S===!0,v=(I=r==null?void 0:r.name)==null?void 0:I.text,L=F&&!v&&i;d({...r??{},name:{...r==null?void 0:r.name,enabled:M==="enabled"?S:((P=r==null?void 0:r.name)==null?void 0:P.enabled)??!1,text:M==="text"?S:L?i:v,fontSize:M==="fontSize"?S:(V=r==null?void 0:r.name)==null?void 0:V.fontSize,fontWeight:M==="fontWeight"?S:(z=r==null?void 0:r.name)==null?void 0:z.fontWeight}})},x=(M,S)=>{var F,v;d({...r??{},labels:{enabled:M==="enabled"?S:((F=r==null?void 0:r.labels)==null?void 0:F.enabled)??!0,rotation:M==="rotation"?S:(v=r==null?void 0:r.labels)==null?void 0:v.rotation}})},b=(M,S)=>{d({...r??{},scale:{...r==null?void 0:r.scale,[M]:S===""?"auto":Number(S)}})},h=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:M=>o("enabled",M),onClick:M=>M.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:((p=r==null?void 0:r.name)==null?void 0:p.enabled)??!1,onCheckedChange:M=>m("enabled",M===!0)}),e.jsx(t.Label,{htmlFor:`${s}-title-enabled`,className:"text-xs font-medium cursor-pointer",children:"TITLE"})]}),((j=r==null?void 0:r.name)==null?void 0:j.enabled)&&e.jsxs("div",{className:"space-y-2 pl-6",children:[e.jsx(Qe,{placeholder:`${a} title`,value:((f=r==null?void 0:r.name)==null?void 0:f.text)||"",onSave:M=>m("text",M),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(Qe,{type:"number",placeholder:"12",value:String(((T=r==null?void 0:r.name)==null?void 0:T.fontSize)||12),onSave:M=>m("fontSize",Number(M)||12),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Weight"}),e.jsxs(t.Select,{value:((E=r==null?void 0:r.name)==null?void 0:E.fontWeight)||"normal",onValueChange:M=>m("fontWeight",M),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:M=>o("position",M),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:h.map(M=>e.jsx(t.SelectItem,{value:M,className:"text-xs",children:M==="auto"?"Auto (Default)":t.titleCase(M)},M))})]})]}),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:((O=r==null?void 0:r.labels)==null?void 0:O.enabled)!==!1,onCheckedChange:M=>x("enabled",M)})]}),((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(((k=r==null?void 0:r.labels)==null?void 0:k.rotation)||"auto"),onValueChange:M=>x("rotation",M==="auto"?"auto":Number(M)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:u.map(M=>e.jsx(t.SelectItem,{value:M,className:"text-xs",children:M==="auto"?"Auto (Default)":`${M}°`},M))})]})]})]}),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:c==="override",onCheckedChange:M=>d({...r,formatMode:M?"override":"inherit"})})]}),c==="override"&&e.jsx(jt,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:M=>d({...r,formatMode:"override",formatOptions:M}),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(Qe,{type:"number",placeholder:"auto",value:((w=r==null?void 0:r.scale)==null?void 0:w.min)==="auto"||((D=r==null?void 0:r.scale)==null?void 0:D.min)===void 0?"":String(r.scale.min),onSave:M=>b("min",M),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(Qe,{type:"number",placeholder:"auto",value:((y=r==null?void 0:r.scale)==null?void 0:y.max)==="auto"||((A=r==null?void 0:r.scale)==null?void 0:A.max)===void 0?"":String(r.scale.max),onSave:M=>b("max",M),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(Qe,{type:"number",placeholder:"auto",value:((g=r==null?void 0:r.scale)==null?void 0:g.stepSize)==="auto"||((R=r==null?void 0:r.scale)==null?void 0:R.stepSize)===void 0?"":String(r.scale.stepSize),onSave:M=>b("stepSize",M),className:""})})]})]})]})]})]})}function os(s,a,n){var i,l,c;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=((c=a==null?void 0:a.config)==null?void 0:c.metricColumns)||[],d=(n==null?void 0:n.datasetOptions)||[];if(s==="y"){const o=r.filter((m,x)=>{const b=d.find(h=>h.idx===x);return!b||b.yAxisId!=="y2"});return o.length===1&&(o[0].label||o[0].name)||""}if(s==="y2"){const o=r.filter((m,x)=>{const b=d.find(h=>h.idx===x);return(b==null?void 0:b.yAxisId)==="y2"});return o.length===1&&(o[0].label||o[0].name)||""}return""}function vl(){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(),d=Ae.useEffectiveEditorCardType();if(!s||["tornado","pyramid","kpi","treemap"].includes(d))return null;const i=t.AxisConfigurator.getAxisInfo(d,a);if(!i.hasXAxis&&!i.hasYAxis)return null;const l=(o,m)=>{let x;o==="x"?x="xAxisConfig":o==="y"?x="yAxisConfig":x="secondaryYAxisConfig";const b={...a||{},[x]:m};n(b);const h={...s,preferences:b};r(h)},c=i.hasY2Axis&&d==="combo";return e.jsxs(t.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[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(ls,{axis:"x",label:"X-Axis",type:i.xAxisType,config:t.mergeAxisConfig(t.getDefaultAxisConfig(d,"x"),a==null?void 0:a.xAxisConfig),onChange:o=>l("x",o),defaultTitle:os("x",s,a)}),i.hasYAxis&&e.jsx(ls,{axis:"y",label:c?"Y-Axis (Left)":"Y-Axis",type:i.yAxisType,config:t.mergeAxisConfig(t.getDefaultAxisConfig(d,"y"),a==null?void 0:a.yAxisConfig),onChange:o=>l("y",o),defaultTitle:os("y",s,a)}),c&&e.jsx(ls,{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:os("y2",s,a),hidePosition:!0})]})})]})}function yl(){const s=t.useEditorStore(b=>b.card),a=Ae.useEffectiveEditorCardType(),n=t.useEditorStore(b=>{var h,u,p,j;return(j=(p=(u=(h=b.card)==null?void 0:h.preferences)==null?void 0:u.chartOptions)==null?void 0:p.plugins)==null?void 0:j.legend}),{setLegendOptions:r}=t.useEditorActions();if(!s||!t.chartSupportsLegend(a))return null;const d=t.getDefaultLegendConfig(a),i=(d==null?void 0:d.display)??!0,l=(d==null?void 0:d.position)??"top",c=(d==null?void 0:d.align)??"center",o=(b,h)=>{const u={...n,[b]:h};r(u)},m=["top","bottom","left","right"],x=["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(Sa,{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:b=>o("display",b)})]}),((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:b=>o("position",b),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:m.map(b=>e.jsx(t.SelectItem,{value:b,className:"text-xs",children:t.titleCase(b)},b))})]})]}),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)||c,onValueChange:b=>o("align",b),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:x.map(b=>e.jsx(t.SelectItem,{value:b,className:"text-xs",children:t.titleCase(b)},b))})]})]})]})]})})]})}function Nl(){var S,F,v,L,I,P,V;const s=t.useEditorStore(z=>z.card),a=Ae.useEffectiveEditorCardType(),n=t.useEditorStore(z=>{var B,_;return(_=(B=z.card)==null?void 0:B.preferences)==null?void 0:_.dataLabelsConfig}),r=t.useEditorStore(z=>{var B;return(B=z.card)==null?void 0:B.preferences}),{setCardPreferences:d,updateCardInFrame:i}=t.useEditorActions();if(!s||!t.chartSupportsDataLabels(a))return null;const l=a==="bullet"?((S=r==null?void 0:r.bulletConfig)==null?void 0:S.orientation)??(((F=r==null?void 0:r.chartOptions)==null?void 0:F.indexAxis)==="x"?"vertical":"horizontal"):void 0,c=l!=null?l==="horizontal":((v=r==null?void 0:r.chartOptions)==null?void 0:v.indexAxis)==="y",o=a==="stackedBar"||a==="stackedLine",m=a==="pie"||a==="doughnut"||a==="polarArea"||a==="funnel",x=a==="bubble"||a==="scatter",b=(I=(L=r==null?void 0:r.chartOptions)==null?void 0:L.plugins)==null?void 0:I.datalabels,h=(b==null?void 0:b.display)!==!1&&((b==null?void 0:b.anchor)||(b==null?void 0:b.align)),u=t.getDefaultDataLabelsConfig(a,s.preferences),p=n??u,j=(u==null?void 0:u.enabled)??h??!1,f=(n==null?void 0:n.enabled)!==void 0?n.enabled:j,T=(z,B)=>{const K={...u??{},...n??{},[z]:B};z==="enabled"&&(K.display=B,B&&x&&!K.position&&(K.position="bottom")),z==="position"&&x&&(K.position="bottom"),z==="formatMode"&&B==="inherit"&&(K.format=void 0,K.formatOptions=void 0);const H={...s.preferences||{},dataLabelsConfig:K};d(H);const Z={...s,preferences:H};i(Z)},E=(z,B)=>{const _=n??{},K={...u??{},..._,font:{..._.font||{},[z]:B}},H={...s.preferences||{},dataLabelsConfig:K};d(H);const Z={...s,preferences:H};i(Z)},O=()=>{const z=a;return z==="stackedBar"||z==="stackedLine"||z==="pie"||z==="doughnut"?"center":c?"right":"top"},C=a!=="treemap"&&a!=="heatmap",k=a!=="treemap",w=O();let D=[];if(C)if(x)D=["bottom"];else if(o||m)D=["center"];else{const z=c?["center","left","right"]:["center","top","bottom"];D=["auto",...a==="bullet"?z:z.filter(_=>_!==w),"custom"]}const y=()=>t.titleCase(w),A=["center","start","end"],g=["center","start","end","top","bottom"],R=(p==null?void 0:p.formatMode)||(p!=null&&p.format&&!["auto"].includes(p.format)?"override":"inherit"),M=(p==null?void 0:p.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(Va,{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:f,onCheckedChange:z=>T("enabled",z)})]}),f&&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:x?(p==null?void 0:p.position)||"bottom":(p==null?void 0:p.position)||"auto",onValueChange:z=>T("position",z),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:D.map(z=>e.jsx(t.SelectItem,{value:z,className:"text-xs",children:z==="auto"?y():z==="custom"?"Custom (Advanced)":t.titleCase(z)},z))})]})]}),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:z=>T("showTotal",z)})]}),(p==null?void 0:p.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:(p==null?void 0:p.anchor)||"center",onValueChange:z=>T("anchor",z),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:A.map(z=>e.jsx(t.SelectItem,{value:z,className:"text-xs",children:t.titleCase(z)},z))})]})]}),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((p==null?void 0:p.align)||"center"),onValueChange:z=>T("align",z),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:g.map(z=>e.jsx(t.SelectItem,{value:z,className:"text-xs",children:t.titleCase(z)},z))})]})]})]}),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:z=>T("formatMode",z?"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:M,onCheckedChange:z=>{const B=n??{},U={...u??{},...B,formatMode:"override",format:z?"none":void 0,formatOptions:z?void 0:B.formatOptions},K={...s.preferences||{},dataLabelsConfig:U};d(K),i({...s,preferences:K})}})]}),!M&&e.jsx(jt,{formatOptions:(p==null?void 0:p.formatOptions)||{},onFormatOptionsChange:z=>{const U={...u??{},...n??{},formatMode:"override",format:z.type&&z.type!=="auto"?z.type:void 0,formatOptions:z},K={...s.preferences||{},dataLabelsConfig:U};d(K),i({...s,preferences:K})},showTitle:!1})]})]}),k&&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(Qe,{type:"number",placeholder:"12",value:String(((P=p==null?void 0:p.font)==null?void 0:P.size)||12),onSave:z=>E("size",Number(z)),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:((V=p==null?void 0:p.font)==null?void 0:V.weight)||"normal",onValueChange:z=>E("weight",z),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:(p==null?void 0:p.color)==="auto"||!(p!=null&&p.color)?"auto":"custom",onValueChange:z=>{z==="auto"&&T("color","auto")},children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Smart Contrast)"}),e.jsx(t.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom (Coming Soon)"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground w-20",children:"Rotation"}),e.jsx("div",{className:"flex-1",children:e.jsx(Qe,{type:"number",placeholder:"0",value:String((p==null?void 0:p.rotation)||0),onSave:z=>T("rotation",Number(z)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}const Nn={difference:{label:"Difference",description:"Shows the exact difference between two values.",formula:"Primary - Secondary",example:"Sales increased by $5,000 compared to last year."},change:{label:"Change",description:"Shows the percentage increase or decrease between two values.",formula:"(Primary - Secondary) / Secondary × 100%",example:"Year-over-year sales change of 25%."},change_difference:{label:"Change (difference)",description:"Shows both the percentage change and the exact difference between two values.",formula:`% Change: (Primary - Secondary) / Secondary × 100%
|
|
193
|
-
Difference: Primary - Secondary`,example:"Sales grew by 25% ($5,000) compared to last year."},ratio:{label:"Ratio",description:"Shows how much of one value is covered by another — useful for quotas and benchmarks.",formula:"Primary / Secondary × 100%",example:"You've achieved 80% of your sales quota."}};function Cl(){var h,u,p,j,f,T,E,O,C,k;const s=t.useEditorStore(w=>w.card),{setCardPreferences:a}=t.useEditorActions(),n=Ae.useEffectiveEditorCardType(),r=((h=s.config)==null?void 0:h.metricColumns)||[],d=((u=s.config)==null?void 0:u.groupByColumns)||[],i=r.length===2&&d.length===0,l=r.some(w=>w.comparisonType&&w.comparisonType!=="none");if(!(n==="kpi"&&(i||l)))return null;const o=((j=(p=s.preferences)==null?void 0:p.kpiVisualOptions)==null?void 0:j.metricComparison)||{},m=w=>{var y;const D={...s.preferences,kpiVisualOptions:{...(y=s.preferences)==null?void 0:y.kpiVisualOptions,metricComparison:{...o,...w}}};a(D)},x=l||o.enabled,b=r.some(w=>w.comparisonType==="previous_period"||w.comparisonType==="same_period_last_year"||w.comparisonType==="start_vs_end");return e.jsxs(t.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(t.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-[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:w=>m({enabled:w,...w&&!o.calculationType?{calculationType:"difference"}:{}})})]}),x&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(t.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.Info,{className:"h-3 w-3 cursor-help text-muted-foreground"})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:(()=>{const w=o.calculationType||"difference",D=Nn[w];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:D==null?void 0:D.label}),e.jsx("p",{children:D==null?void 0:D.description}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Formula:"})," ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-[10px]",children:D==null?void 0:D.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",D==null?void 0:D.example]})]})})()})]})]}),e.jsxs(t.Select,{value:o.calculationType||"difference",onValueChange:w=>m({calculationType:w}),children:[e.jsx(t.SelectTrigger,{id:"calculation-type",className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Object.entries(Nn).map(([w,D])=>e.jsx(t.SelectItem,{value:w,className:"text-xs",children:D.label},w))})]})]}),e.jsx(jt,{formatOptions:o.formatOptions||{},onFormatOptionsChange:w=>m({formatOptions:w}),showTitle:!0,title:"COMPARISON FORMAT"}),(b||i)&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator"}),i&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(t.Select,{value:o.position||"right",onValueChange:w=>m({position:w}),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"right",className:"text-xs",children:"Right"}),e.jsx(t.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(t.SelectItem,{value:"top",className:"text-xs",children:"Top"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Checkbox,{id:"show-arrow",checked:o.showArrow!==!1,onCheckedChange:w=>m({showArrow:w})}),e.jsx(t.Label,{htmlFor:"show-arrow",className:"cursor-pointer text-xs text-muted-foreground",children:"Arrow"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Checkbox,{id:"show-color",checked:o.showColor!==!1,onCheckedChange:w=>m({showColor:w})}),e.jsx(t.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),o.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(at,{value:((f=o.colorConfig)==null?void 0:f.increase)||"green",onChange:w=>m({colorConfig:{...o.colorConfig,increase:w}}),label:"Primary > Secondary"}),e.jsx(at,{value:((T=o.colorConfig)==null?void 0:T.decrease)||"red",onChange:w=>m({colorConfig:{...o.colorConfig,decrease:w}}),label:"Primary < Secondary"}),e.jsx(at,{value:((E=o.colorConfig)==null?void 0:E.noChange)||"neutral",onChange:w=>m({colorConfig:{...o.colorConfig,noChange:w}}),label:"Primary = Secondary"})]})]}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Checkbox,{id:"conditional-label",checked:o.conditionalLabel||!1,onCheckedChange:w=>m({conditionalLabel:w})}),e.jsx(t.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),o.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(t.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(t.Input,{id:"label-increase",type:"text",value:((O=o.conditionalLabels)==null?void 0:O.increase)??"Increase",onChange:w=>m({conditionalLabels:{...o.conditionalLabels,increase:w.target.value}}),placeholder:"Increase",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(t.Label,{htmlFor:"label-decrease",className:"text-xs text-muted-foreground",children:["Primary ","<"," Secondary"]}),e.jsx(t.Input,{id:"label-decrease",type:"text",value:((C=o.conditionalLabels)==null?void 0:C.decrease)??"Decrease",onChange:w=>m({conditionalLabels:{...o.conditionalLabels,decrease:w.target.value}}),placeholder:"Decrease",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{htmlFor:"label-no-change",className:"text-xs text-muted-foreground",children:"Primary = Secondary"}),e.jsx(t.Input,{id:"label-no-change",type:"text",value:((k=o.conditionalLabels)==null?void 0:k.noChange)??"No change",onChange:w=>m({conditionalLabels:{...o.conditionalLabels,noChange:w.target.value}}),placeholder:"No change",className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{htmlFor:"label-name",className:"text-xs text-muted-foreground",children:"Previous Label"}),e.jsx(t.Input,{id:"label-name",type:"text",value:o.labelName??"",onChange:w=>m({labelName:w.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function Sl(){var i;const s=t.useEditorStore(l=>{var c;return(c=l.card)==null?void 0:c.type}),a=t.useEditorStore(l=>{var c;return(c=l.card)==null?void 0:c.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",d=l=>{const c={...a||{},chartOptions:{...a==null?void 0:a.chartOptions,treemapColorMode:l}};n(c)};return e.jsxs(t.AccordionItem,{value:"treemap-color-mode",className:"border-none",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-[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=>d(l??"branch"),className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(t.RadioGroupItem,{id:"treemap-color-branch",value:"branch"}),e.jsxs(t.Label,{htmlFor:"treemap-color-branch",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Shade by value (default)"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Keeps parent hue and adjusts lightness based on the node's share within the branch."})]})]}),e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(t.RadioGroupItem,{id:"treemap-color-category",value:"category"}),e.jsxs(t.Label,{htmlFor:"treemap-color-category",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Single color per category"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Applies the top-level color to all descendants without lightening/darkening."})]})]})]})})]})}const wl=Object.keys(t.HEATMAP_PRESET_PALETTES);function Tl(){const s=t.useEditorStore(h=>h.card),a=t.useEditorStore(h=>{var u;return(u=h.card)==null?void 0:u.preferences}),{setCardPreferences:n}=t.useEditorActions(),r=(s==null?void 0:s.type)==="heatmap",d=(a==null?void 0:a.heatmapConfig)||{},i=d.colorPalette??"green",l=d.legendPosition??"bottom",c=N.useMemo(()=>d.colorRange&&d.colorRange[0]&&d.colorRange[1]?[d.colorRange[0],d.colorRange[1]]:[...t.DEFAULT_HEATMAP_CUSTOM_RANGE],[d.colorRange]),o=h=>{const u={...d,...h};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=h=>{o({colorPalette:h,colorRange:h==="custom"?d.colorRange??[...t.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},x=(h,u)=>{const p=[...c];p[h]=u,o({colorPalette:"custom",colorRange:p})},b=h=>{o({legendPosition:h})};return r?e.jsxs(t.AccordionItem,{value:"heatmap-color-config",className:"border-none",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-[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:h=>m(h??"blue"),className:"space-y-3",children:[wl.map(h=>{const u=t.HEATMAP_PRESET_PALETTES[h];return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(t.RadioGroupItem,{id:`heatmap-${h}`,value:h}),e.jsxs(t.Label,{htmlFor:`heatmap-${h}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:u.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${u.start}, ${u.end})`}})]})]},h)}),e.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.RadioGroupItem,{id:"heatmap-custom",value:"custom"}),e.jsx(t.Label,{htmlFor:"heatmap-custom",className:"text-sm font-medium",children:"Custom colors"})]}),i==="custom"&&e.jsxs("div",{className:"flex flex-col gap-3 pl-6",children:[e.jsx(at,{value:c[0],onChange:h=>x(0,h),label:"Start color"}),e.jsx(at,{value:c[1],onChange:h=>x(1,h),label:"End color"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Color scale position"}),e.jsxs(t.Select,{value:l,onValueChange:h=>b(h??"bottom"),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:["top","bottom","left","right"].map(h=>e.jsx(t.SelectItem,{value:h,className:"text-xs",children:h[0].toUpperCase()+h.slice(1)},h))})]})]})]})]}):null}const Cn=["poor","satisfactory","good"];function Sn(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 El(){var S,F;const s=t.useEditorStore(v=>v.card.preferences),a=t.useEditorStore(v=>v.card),n=t.useEditorStore(v=>v.isDevMode),{setCardPreferences:r,setChartOrientation:d}=t.useEditorActions(),i=N.useMemo(()=>(s==null?void 0:s.bulletConfig)||{},[s==null?void 0:s.bulletConfig]),c=t.hasValidCardConfig(a==null?void 0:a.config)&&!n,[o,m]=N.useState(i.showRanges??!1),[x,b]=N.useState(i.rangesArePercentages??!1),h=i.disableAutoComparative?!1:i.comparativeMetricKey!==void 0||!c,[u,p]=N.useState(h);N.useEffect(()=>{m(i.showRanges??!1)},[i.showRanges]),N.useEffect(()=>{b(i.rangesArePercentages??!1)},[i.rangesArePercentages]);const j=i.targetValue===void 0?"":String(i.targetValue);N.useEffect(()=>{const v=i.disableAutoComparative?!1:i.comparativeMetricKey!==void 0||!c;p(v)},[i.disableAutoComparative,i.comparativeMetricKey,c]);const f=N.useMemo(()=>{var v,L;return((L=(v=a==null?void 0:a.config)==null?void 0:v.metricColumns)==null?void 0:L.map(I=>{const P=I.label||I.name||I.alias||"";return{value:P,label:P}}))||[]},[(S=a==null?void 0:a.config)==null?void 0:S.metricColumns]);N.useEffect(()=>{var _,U;if(!s||f.length===0)return;const v={};let L=!1;const I=(_=f[1])==null?void 0:_.value;!i.targetMetricKey&&I&&(v.targetMetricKey=I,L=!0);const P=(U=f[2])==null?void 0:U.value;!i.comparativeMetricKey&&!i.disableAutoComparative&&P&&(v.comparativeMetricKey=P,L=!0);const V=f.slice(3),z={...i.rangeKeys||{}};let B=!1;if(Cn.forEach((K,H)=>{!z[K]&&V[H]&&(z[K]=V[H].value,B=!0)}),B&&(v.rangeKeys=z,L=!0,i.showRanges===void 0&&(v.showRanges=!0)),L){const K=Sn({...i,...v});r({...s,bulletConfig:K})}},[f,i,s,r]);const T=v=>{const L=Sn({...i,...v});r({...s,bulletConfig:L})},E=(v,L)=>{const I={...i.rangeKeys||{},[v]:L.trim()};L.trim()||delete I[v],T({rangeKeys:Object.keys(I).length>0?I:void 0})},O=(v,L)=>{const I=L===""?void 0:Number(L),P={...i.ranges||{}};I===void 0||Number.isNaN(I)?delete P[v]:P[v]=I,T({ranges:Object.keys(P).length?P:void 0})},C=v=>{if(v===""){T({targetValue:void 0});return}const L=Number(v);T({targetValue:Number.isNaN(L)?void 0:L})},k=(v,L)=>{const I=L.trim(),P={...i.rangeLabels||{}};I?P[v]=I:delete P[v],T({rangeLabels:Object.keys(P).length>0?P:void 0})},w=v=>{m(v),T({showRanges:v})},D=v=>{b(v),T({rangesArePercentages:v})},y=i.orientation||(((F=s==null?void 0:s.chartOptions)==null?void 0:F.indexAxis)==="y"?"horizontal":"vertical"),A=v=>{T({orientation:v}),d(v==="horizontal"?"y":"x")},g=[{value:"__none",label:"None"},...f.map(v=>({value:v.value,label:v.label}))],R=g,M=v=>{if(p(v),!v){T({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!c){T({disableAutoComparative:!1});return}if(i.comparativeMetricKey)T({disableAutoComparative:!1});else{const L=f.find(I=>I.value!==i.targetMetricKey);T({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:y,onValueChange:v=>A(v),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"horizontal",className:"text-xs",children:"Horizontal"}),e.jsx(t.SelectItem,{value:"vertical",className:"text-xs",children:"Vertical"})]})]})]}),c&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"TARGET METRIC"}),e.jsxs(t.Select,{value:i.targetMetricKey||"__none",onValueChange:v=>T({targetMetricKey:v==="__none"?void 0:v}),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"}),f.map(v=>e.jsx(t.SelectItem,{value:v.value,className:"text-xs",children:v.label},v.value))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"COMPARATIVE METRIC"}),c?e.jsxs(t.Select,{value:i.comparativeMetricKey||"__none",onValueChange:v=>T({comparativeMetricKey:v==="__none"?void 0:v,disableAutoComparative:v==="__none"}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select metric"})}),e.jsx(t.SelectContent,{children:g.map(v=>e.jsx(t.SelectItem,{value:v.value,className:"text-xs",children:v.label},v.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:v=>M(v)})]}),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:j,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:w})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:x,disabled:!o,onChange:v=>D(v.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:Cn.map(v=>{var L,I,P,V,z;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:[v," LABEL"]}),e.jsx(qe,{placeholder:`Display label (${v})`,value:((L=i.rangeLabels)==null?void 0:L[v])||"",onCommit:B=>k(v,B),className:"h-8 text-xs"})]}),c?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[v," COLUMN"]}),e.jsxs(t.Select,{value:((I=i.rangeKeys)==null?void 0:I[v])||"__none",onValueChange:B=>{B==="__none"?E(v,""):E(v,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:[v," COLUMN KEY"]}),e.jsx(qe,{placeholder:"Column key",value:((P=i.rangeKeys)==null?void 0:P[v])||"",onCommit:B=>E(v,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:[v," VALUE"]}),e.jsx(qe,{type:"number",placeholder:x?"0.80":"Static value",value:((V=i.ranges)==null?void 0:V[v])===void 0?"":String((z=i.ranges)==null?void 0:z[v]),onCommit:B=>O(v,B),className:"h-8 text-xs"})]})]},v)})})]})]})]})}function wn(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 Il(){var k,w,D,y,A,g,R,M,S,F,v,L;const s=t.useEditorStore(I=>I.card.preferences),a=t.useEditorStore(I=>I.card),n=Ae.useEffectiveEditorCardType(),r=t.useEditorStore(I=>I.isDevMode),{setCardPreferences:d,updateCardInFrame:i}=t.useEditorActions(),l=n==="bubble",c=n==="scatter",o=N.useMemo(()=>(s==null?void 0:s.bubbleScatterConfig)||{},[s==null?void 0:s.bubbleScatterConfig]),x=t.hasValidCardConfig(a==null?void 0:a.config)&&!r,b=N.useMemo(()=>{var I,P;return((P=(I=a==null?void 0:a.config)==null?void 0:I.metricColumns)==null?void 0:P.map(V=>{const z=V.label||V.name||V.alias||"";return{value:z,label:z}}))||[]},[(k=a==null?void 0:a.config)==null?void 0:k.metricColumns]),h=N.useMemo(()=>{var I,P;return((P=(I=a==null?void 0:a.config)==null?void 0:I.groupByColumns)==null?void 0:P.map(V=>{const z=V.label||V.name||V.alias||"";return{value:z,label:z}}))||[]},[(w=a==null?void 0:a.config)==null?void 0:w.groupByColumns]),u=N.useMemo(()=>o.enableGrouping!==void 0?o.enableGrouping:!r&&h.length>=2,[o.enableGrouping,r,h.length]),[p,j]=N.useState(u);N.useEffect(()=>{j(u)},[u]);const f=I=>{const P={...s||{},bubbleScatterConfig:I};d(P),a&&i({...a,preferences:P})},T=I=>{d(I),a&&i({...a,preferences:I})};N.useEffect(()=>{if(!s||b.length===0)return;const I={};let P=!1;if(!o.xMetricKey&&b[0]&&(I.xMetricKey=b[0].value,P=!0),!o.yMetricKey&&b[1]&&(I.yMetricKey=b[1].value,P=!0),l&&!o.radiusMetricKey&&b[2]&&(I.radiusMetricKey=b[2].value,P=!0),!o.labelKey&&h[0]&&(I.labelKey=h[0].value,P=!0),u&&!o.groupKey&&h[1]&&(I.groupKey=h[1].value,I.enableGrouping=!0,P=!0),P){const V=wn({...o,...I});f(V)}},[b,h,o,s,d,l,u]);const E=I=>{const P=wn({...o,...I});f(P)},O=I=>{j(I),E({enableGrouping:I,groupKey:I?o.groupKey:void 0})};if(!l&&!c)return null;const C=l?t.Circle:t.ChartScatter;return e.jsxs(t.AccordionItem,{value:"bubble-scatter-config",children:[e.jsx(t.AccordionTrigger,{className:"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"}),x?e.jsxs(t.Select,{value:o.labelKey||"",onValueChange:I=>E({labelKey:I}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select label column"})}),e.jsx(t.SelectContent,{children:h.map(I=>e.jsx(t.SelectItem,{value:I.value,children:I.label},I.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for labels",value:o.labelKey||"",onCommit:I=>E({labelKey:I})})]}),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:p,onCheckedChange:O})]}),p&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Group By"}),x?e.jsxs(t.Select,{value:o.groupKey||"",onValueChange:I=>E({groupKey:I}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select group column"})}),e.jsx(t.SelectContent,{children:h.map(I=>e.jsx(t.SelectItem,{value:I.value,children:I.label},I.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:o.groupKey||"",onCommit:I=>E({groupKey:I})})]})]}),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"}),x?e.jsxs(t.Select,{value:o.xMetricKey||"",onValueChange:I=>E({xMetricKey:I}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select X metric"})}),e.jsx(t.SelectContent,{children:b.map(I=>e.jsx(t.SelectItem,{value:I.value,children:I.label},I.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:o.xMetricKey||"",onCommit:I=>E({xMetricKey:I})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Axis"}),x?e.jsxs(t.Select,{value:o.yMetricKey||"",onValueChange:I=>E({yMetricKey:I}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select Y metric"})}),e.jsx(t.SelectContent,{children:b.map(I=>e.jsx(t.SelectItem,{value:I.value,children:I.label},I.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:o.yMetricKey||"",onCommit:I=>E({yMetricKey:I})})]}),l&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Radius"}),x?e.jsxs(t.Select,{value:o.radiusMetricKey||"",onValueChange:I=>E({radiusMetricKey:I}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select radius metric"})}),e.jsx(t.SelectContent,{children:b.map(I=>e.jsx(t.SelectItem,{value:I.value,children:I.label},I.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for radius",value:o.radiusMetricKey||"",onCommit:I=>E({radiusMetricKey:I})})]})]}),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:I=>E({radiusScale:I}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"sqrt",children:"Square Root (area-proportional)"}),e.jsx(t.SelectItem,{value:"linear",children:"Linear"}),e.jsx(t.SelectItem,{value:"fixed",children:"Fixed Size"})]})]})]}),o.radiusScale!=="fixed"&&e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Min Radius"}),e.jsx(qe,{className:"h-8 text-xs",type:"number",placeholder:"5",value:((D=o.minRadius)==null?void 0:D.toString())||"",onCommit:I=>E({minRadius:I?Number(I):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:((y=o.maxRadius)==null?void 0:y.toString())||"",onCommit:I=>E({maxRadius:I?Number(I):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:([I])=>E({fixedRadius:I}),min:3,max:30,step:1,className:"py-2"})]})]}),c&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Point Settings"}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(t.Label,{className:"text-xs",children:["Point Size: ",o.fixedRadius||5]}),e.jsx(t.Slider,{value:[o.fixedRadius||5],onValueChange:([I])=>E({fixedRadius:I}),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:((g=(A=s==null?void 0:s.xAxisConfig)==null?void 0:A.name)==null?void 0:g.enabled)??!1,onCheckedChange:I=>{var z,B,_,U;const P=o.xMetricKey||"X Axis",V=o.yMetricKey||"Y Axis";T({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{enabled:I,text:((B=(z=s==null?void 0:s.xAxisConfig)==null?void 0:z.name)==null?void 0:B.text)||P}},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{enabled:I,text:((U=(_=s==null?void 0:s.yAxisConfig)==null?void 0:_.name)==null?void 0:U.text)||V}}})}})]}),((M=(R=s==null?void 0:s.xAxisConfig)==null?void 0:R.name)==null?void 0:M.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=(S=s==null?void 0:s.xAxisConfig)==null?void 0:S.name)==null?void 0:F.text)||"",onCommit:I=>{var P;T({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{...(P=s==null?void 0:s.xAxisConfig)==null?void 0:P.name,enabled:!0,text:I||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=(v=s==null?void 0:s.yAxisConfig)==null?void 0:v.name)==null?void 0:L.text)||"",onCommit:I=>{var P;T({...s??{},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{...(P=s==null?void 0:s.yAxisConfig)==null?void 0:P.name,enabled:!0,text:I||o.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const kl=[{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 Dl(){const s=t.useEditorStore(h=>h.card),a=t.useEditorStore(h=>{var u;return(u=h.card)==null?void 0:u.preferences}),{setCardPreferences:n}=t.useEditorActions(),r=(s==null?void 0:s.type)==="funnel",d=(a==null?void 0:a.funnelConfig)||{},i=d.percentMode??"percentOfTotal",l=d.shrinkFraction??1,c=d.labelThreshold??0,o=h=>{const u={...d,...h};n({...a||{},funnelConfig:u})},m=h=>{o({percentMode:h})},x=h=>{o({shrinkFraction:h[0]})},b=h=>{o({labelThreshold:h[0]})};return r?e.jsxs(t.AccordionItem,{value:"funnel-config",className:"border-none",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-[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:h=>m(h),className:"space-y-2",children:kl.map(h=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(t.RadioGroupItem,{id:`funnel-${h.value}`,value:h.value,className:"mt-0.5"}),e.jsxs(t.Label,{htmlFor:`funnel-${h.value}`,className:"flex flex-col gap-0.5 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:h.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:h.description})]})]},h.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"SEGMENT SHRINK"}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Same Width"}),e.jsx(t.Slider,{value:[l],onValueChange:x,min:0,max:1,step:.1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Full Shrink"})]}),e.jsxs("p",{className:"text-center text-xs text-muted-foreground",children:["Current: ",Math.round(l*100),"%"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"LABEL VISIBILITY THRESHOLD"}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Show All"}),e.jsx(t.Slider,{value:[c],onValueChange:b,min:0,max:25,step:1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Hide Small"})]}),e.jsx("p",{className:"text-center text-xs text-muted-foreground",children:c===0?"Showing all labels":`Hide labels below ${c}%`})]})]})]}):null}function Kt(){const s=t.useEditorStore(i=>i.card),{data: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 d=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);d=l.slice(1)}return{transformedMetricKeys:d,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}const Al=[{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"}],Ml=[{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)"}],Ll=["center","start","end"],Fl=["center","start","end","top","bottom"];function Gt({config:s,onChange:a,isHorizontal:n=!1,showAutoFormat:r=!0,positionOptions:d,showAppearance:i=!0}){var p,j,f,T,E,O;const l=d??(n?["auto","center","left","right","custom"]:["auto","center","top","bottom","custom"]),c=r?["auto","number","currency","percent","none"]:["number","currency","percent","none"],o=(C,k)=>{const w={...s,[C]:k};a(w)},m=(C,k)=>{const w={...s,font:{...(s==null?void 0:s.font)||{},[C]:k}};a(w)},x=(C,k)=>{const w={...s,formatOptions:{...(s==null?void 0:s.formatOptions)||{},[C]:k}};a(w)},b=()=>n?"Right":"Top",h=s||{},u=h.format||(r?"auto":"number");return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(t.Select,{value:h.position||"auto",onValueChange: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"?b():C==="custom"?"Custom (Advanced)":t.titleCase(C)},C))})]})]}),h.position==="custom"&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Anchor"}),e.jsxs(t.Select,{value:h.anchor||"center",onValueChange: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:Ll.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(h.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:Fl.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:c.map(C=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:C==="auto"&&r?"Auto (Use Axis)":C==="none"?"None (Raw Value)":t.titleCase(C)},C))})]})]}),!["auto","none"].includes(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(Qe,{type:"number",placeholder:"0",value:String(((p=h.formatOptions)==null?void 0:p.decimalPlaces)??(u==="currency"?2:u==="percent"?1:0)),onSave:C=>x("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:((j=h.formatOptions)==null?void 0:j.currency)||"USD",onValueChange:C=>x("currency",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Al.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:((f=h.formatOptions)==null?void 0:f.useSuffix)??!1,onCheckedChange:C=>x("useSuffix",C)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Locale"}),e.jsxs(t.Select,{value:((T=h.formatOptions)==null?void 0:T.locale)||"en-US",onValueChange:C=>x("locale",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ml.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(Qe,{type:"number",placeholder:"12",value:String(((E=h.font)==null?void 0:E.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:((O=h.font)==null?void 0:O.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:h.color==="auto"||!h.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(Qe,{type:"number",placeholder:"0",value:String(h.rotation||0),onSave:C=>o("rotation",Number(C)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"°"})]})]})]})]})]})}const Rl=[{type:"bar",icon:t.ChartColumnIncreasing,label:"Bar"},{type:"line",icon:t.ChartLine,label:"Line"}],Ol=[0,1,2,3,4,5,6,8,10],Pl=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],Bl=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Vl(){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(zl,{})})]})}function zl(){const{transformedMetricKeys:s}=Kt();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((a,n)=>e.jsx(_l,{metricKey:a,idx:n},a))})}function _l({metricKey:s,idx:a}){var T;const[n,r]=N.useState(!1),d=t.useEditorStore(E=>{var O;return(O=E.card)==null?void 0:O.preferences}),i=t.useEditorStore(E=>{var O,C;return(C=(O=E.card)==null?void 0:O.preferences)==null?void 0:C.datasetOptions}),l=i==null?void 0:i.find(E=>E.idx===a),{setCardPreferences:c}=t.useEditorStore(E=>E.actions),o=(l==null?void 0:l.type)||"bar",m=(l==null?void 0:l.yAxisId)||"y",x=((T=l==null?void 0:l.dataLabels)==null?void 0:T.enabled)??!1,b=o==="line"?t.ChartLine:t.ChartColumnIncreasing;function h(E){const O={idx:a,type:o,yAxisId:m,dataLabels:l==null?void 0:l.dataLabels,...E};if(!l)c({...d||{},datasetOptions:[...i||[],O]});else{const C=i==null?void 0:i.map(k=>k.idx===a?{...k,...O}:k);c({...d||{},datasetOptions:C})}}function u(E){h({type:E})}function p(E){h({yAxisId:E})}function j(E){h({dataLabels:{...l==null?void 0:l.dataLabels,enabled:E}})}function f(E){h({dataLabels:E})}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(b,{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:Rl.map(({type:E,icon:O,label:C})=>{const k=o===E;return e.jsxs("button",{onClick:()=>u(E),className:t.cn("flex items-center gap-2 rounded-md border px-3 py-1.5 text-xs transition-colors",k?"border-primary bg-primary/10 text-primary":"border-border bg-background text-muted-foreground hover:bg-muted"),children:[e.jsx(O,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:C})]},E)})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Axis"}),e.jsxs(t.Select,{value:m,onValueChange:E=>p(E),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-20 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"y",className:"text-xs",children:"Y1 (Left)"}),e.jsx(t.SelectItem,{value:"y2",className:"text-xs",children:"Y2 (Right)"})]})]})]})]}),o==="line"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(t.Select,{value:(l==null?void 0:l.lineStyle)||"solid",onValueChange:E=>h({lineStyle:E}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Bl.map(({value:E,label:O})=>e.jsx(t.SelectItem,{value:E,className:"text-xs",children:O},E))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(t.Select,{value:String((l==null?void 0:l.pointRadius)??3),onValueChange:E=>h({pointRadius:Number(E)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ol.map(E=>e.jsx(t.SelectItem,{value:String(E),className:"text-xs",children:E===0?"None":E},E))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(t.Select,{value:(l==null?void 0:l.pointStyle)||"circle",onValueChange:E=>h({pointStyle:E}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Pl.map(({value:E,label:O})=>e.jsx(t.SelectItem,{value:E,className:"text-xs",children:O},E))})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(t.Switch,{size:"sm",checked:x,onCheckedChange:j})]}),x&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Gt,{config:l==null?void 0:l.dataLabels,onChange:f,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const is=[{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"}],ql=[0,1,2,3,4,5,6,8,10],$l=[{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 │"}],Kl=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Gl(s){return s==null?"origin":s===!1?"false":s}function Ul(){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(Hl,{})})]})}function Hl(){const{transformedMetricKeys:s}=Kt();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((a,n)=>e.jsx(Ql,{metricKey:a,idx:n},a))})}function Ql({metricKey:s,idx:a}){var j;const[n,r]=N.useState(!1),d=t.useEditorStore(f=>{var T;return(T=f.card)==null?void 0:T.preferences}),i=t.useEditorStore(f=>{var T,E;return(E=(T=f.card)==null?void 0:T.preferences)==null?void 0:E.datasetOptions}),l=i==null?void 0:i.find(f=>f.idx===a),{setCardPreferences:c}=t.useEditorStore(f=>f.actions),o=Gl(l==null?void 0:l.fill),m=((j=l==null?void 0:l.dataLabels)==null?void 0:j.enabled)??!1,x=is.find(f=>f.value===o)||is[0];function b(f){const T={idx:a,fill:o,dataLabels:l==null?void 0:l.dataLabels,...f};if(!l)c({...d||{},datasetOptions:[...i||[],T]});else{const E=i==null?void 0:i.map(O=>O.idx===a?{...O,...T}:O);c({...d||{},datasetOptions:E})}}function h(f){b({fill:f==="false"?!1:f})}function u(f){b({dataLabels:{...l==null?void 0:l.dataLabels,enabled:f}})}function p(f){b({dataLabels:f})}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"}),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-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Fill Target"}),e.jsxs(t.Select,{value:o,onValueChange:f=>h(f),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:is.map(f=>e.jsx(t.SelectItem,{value:f.value,className:"text-xs",children:e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{children:f.label})})},f.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:f=>b({lineStyle:f}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Kl.map(({value:f,label:T})=>e.jsx(t.SelectItem,{value:f,className:"text-xs",children:T},f))})]})]}),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:f=>b({pointRadius:Number(f)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ql.map(f=>e.jsx(t.SelectItem,{value:String(f),className:"text-xs",children:f===0?"None":f},f))})]})]}),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:f=>b({pointStyle:f}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:$l.map(({value:f,label:T})=>e.jsx(t.SelectItem,{value:f,className:"text-xs",children:T},f))})]})]})]})]}),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(Gt,{config:l==null?void 0:l.dataLabels,onChange:p,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Wl=[0,1,2,3,4,5,6,8,10],Jl=[{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 │"}],cs=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Yl(){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(Xl,{})})]})}function Xl(){const{transformedMetricKeys:s}=Kt();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((a,n)=>e.jsx(Zl,{metricKey:a,idx:n},a))})}function Zl({metricKey:s,idx:a}){var f;const[n,r]=N.useState(!1),d=t.useEditorStore(T=>{var E;return(E=T.card)==null?void 0:E.preferences}),i=t.useEditorStore(T=>{var E,O;return(O=(E=T.card)==null?void 0:E.preferences)==null?void 0:O.datasetOptions}),l=i==null?void 0:i.find(T=>T.idx===a),{setCardPreferences:c}=t.useEditorStore(T=>T.actions),o=(l==null?void 0:l.lineStyle)||"solid",m=(l==null?void 0:l.pointRadius)??3,x=(l==null?void 0:l.pointStyle)||"circle",b=((f=l==null?void 0:l.dataLabels)==null?void 0:f.enabled)??!1,h=cs.find(T=>T.value===o)||cs[0];function u(T){const E={idx:a,lineStyle:o,pointRadius:m,pointStyle:x,dataLabels:l==null?void 0:l.dataLabels,...T};if(!l)c({...d||{},datasetOptions:[...i||[],E]});else{const O=i==null?void 0:i.map(C=>C.idx===a?{...C,...E}:C);c({...d||{},datasetOptions:O})}}function p(T){u({dataLabels:{...l==null?void 0:l.dataLabels,enabled:T}})}function j(T){u({dataLabels:T})}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"}),h.label.split(" ")[0]]})})]})}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(t.Select,{value:o,onValueChange:T=>u({lineStyle:T}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:cs.map(({value:T,label:E})=>e.jsx(t.SelectItem,{value:T,className:"text-xs",children:E},T))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(t.Select,{value:String(m),onValueChange:T=>u({pointRadius:Number(T)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Wl.map(T=>e.jsx(t.SelectItem,{value:String(T),className:"text-xs",children:T===0?"None":T},T))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(t.Select,{value:x,onValueChange:T=>u({pointStyle:T}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Jl.map(({value:T,label:E})=>e.jsx(t.SelectItem,{value:T,className:"text-xs",children:E},T))})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(t.Switch,{size:"sm",checked:b,onCheckedChange:p})]}),b&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Gt,{config:l==null?void 0:l.dataLabels,onChange:j,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const eo=[0,2,4,6,8,10,12,16,20];function to(){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(so,{})})]})}function so(){const{transformedMetricKeys:s}=Kt();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((a,n)=>e.jsx(no,{metricKey:a,idx:n},a))})}function no({metricKey:s,idx:a}){var p;const[n,r]=N.useState(!1),d=t.useEditorStore(j=>{var f;return(f=j.card)==null?void 0:f.type}),i=t.useEditorStore(j=>{var f;return(f=j.card)==null?void 0:f.preferences}),l=t.useEditorStore(j=>{var f,T;return(T=(f=j.card)==null?void 0:f.preferences)==null?void 0:T.datasetOptions}),c=l==null?void 0:l.find(j=>j.idx===a),{setCardPreferences:o}=t.useEditorStore(j=>j.actions),m=(c==null?void 0:c.borderRadius)??0,x=((p=c==null?void 0:c.dataLabels)==null?void 0:p.enabled)??!1;function b(j){const f={idx:a,borderRadius:m,dataLabels:c==null?void 0:c.dataLabels,...j};if(!c)o({...i||{},datasetOptions:[...l||[],f]});else{const T=l==null?void 0:l.map(E=>E.idx===a?{...E,...f}:E);o({...i||{},datasetOptions:T})}}function h(j){b({dataLabels:{...c==null?void 0:c.dataLabels,enabled:j}})}function u(j){b({dataLabels:j})}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:j=>b({borderRadius:Number(j)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:eo.map(j=>e.jsx(t.SelectItem,{value:String(j),className:"text-xs",children:j===0?"None":`${j}px`},j))})]})]})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(t.Switch,{size:"sm",checked:x,onCheckedChange:h})]}),x&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Gt,{config:c==null?void 0:c.dataLabels,onChange:u,isHorizontal:d==="horizontalBar",showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const ao=[0,1,2,3,4,5,6,8,10],ro=[{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 │"}],lo=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function oo(){const s=t.useEditorStore(c=>c.card),a=t.useEditorStore(c=>{var o;return(o=c.card)==null?void 0:o.preferences}),n=Ae.useEffectiveEditorCardType(),r=a==null?void 0:a.lineStyleConfig,{setCardPreferences:d,updateCardInFrame:i}=t.useEditorActions();if(!s||!["line","area","stackedArea"].includes(n))return null;const l=(c,o)=>{const m={...a||{},lineStyleConfig:{...r,[c]:o}};d(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(Ra,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Line Style"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Default styles for all series. Override per-series in the Series section."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Line Pattern"}),e.jsxs(t.Select,{value:(r==null?void 0:r.lineStyle)||"solid",onValueChange:c=>l("lineStyle",c),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:lo.map(({value:c,label:o})=>e.jsx(t.SelectItem,{value:c,className:"text-xs",children:o},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Point Size"}),e.jsxs(t.Select,{value:String((r==null?void 0:r.pointRadius)??3),onValueChange:c=>l("pointRadius",Number(c)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ao.map(c=>e.jsx(t.SelectItem,{value:String(c),className:"text-xs",children:c===0?"None":c},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Point Shape"}),e.jsxs(t.Select,{value:(r==null?void 0:r.pointStyle)||"circle",onValueChange:c=>l("pointStyle",c),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ro.map(({value:c,label:o})=>e.jsx(t.SelectItem,{value:c,className:"text-xs",children:o},c))})]})]})]})})]})}const io=[0,2,4,6,8,10,12,16,20],co=[{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%"}],uo=[{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 mo(){const s=t.useEditorStore(c=>c.card),a=t.useEditorStore(c=>{var o;return(o=c.card)==null?void 0:o.preferences}),n=Ae.useEffectiveEditorCardType(),r=a==null?void 0:a.barStyleConfig,{setCardPreferences:d,updateCardInFrame:i}=t.useEditorActions();if(!s||!["bar","horizontalBar","stackedBar"].includes(n))return null;const l=(c,o)=>{const m={...a||{},barStyleConfig:{...r,[c]:o}};d(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:c=>l("borderRadius",Number(c)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:io.map(c=>e.jsx(t.SelectItem,{value:String(c),className:"text-xs",children:c===0?"None":`${c}px`},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Bar Width"}),e.jsxs(t.Select,{value:String((r==null?void 0:r.barPercentage)??.9),onValueChange:c=>l("barPercentage",Number(c)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:co.map(({value:c,label:o})=>e.jsx(t.SelectItem,{value:c,className:"text-xs",children:o},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Category Width"}),e.jsxs(t.Select,{value:String((r==null?void 0:r.categoryPercentage)??.8),onValueChange:c=>l("categoryPercentage",Number(c)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:uo.map(({value:c,label:o})=>e.jsx(t.SelectItem,{value:c,className:"text-xs",children:o},c))})]})]})]})})]})}function xo(){const s=t.useEditorStore(n=>{var r,d;return(d=(r=n==null?void 0:n.card)==null?void 0:r.preferences)==null?void 0:d.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 ho=["kpi"],Tn={none:"None",previous_period:"Previous Period",same_period_last_year:"Same Period Last Year",start_vs_end:"Start vs End",target:"Target"},ds=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 po(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 fo(s){return{...s,role:"groupby"}}function go(){var E,O;const s=t.useEditorStore(C=>C.card),a=t.useEditorStore(C=>C.actions.updateCardConfig),n=Ae.useEffectiveEditorCardType(),{scopedFields:r}=t.useScopedFields(),d=((E=s.config)==null?void 0:E.metricColumns)||[],i=((O=s.config)==null?void 0:O.summary)||{},l=i.breakdownDimensions||[],c=ho.includes(n),o=d.length>0,m=i.enabled===!0,x=c&&o,{comparisonType:b}=t.getEffectiveComparisonSettings(s.config,n),h=Tn[b]||Tn.none,u=Array.from(new Map(r.filter(po).map(C=>[lt(C),fo(C)])).values()),p=new Set(u.map(C=>lt(C))),j=new Set(l.map(C=>lt(C)).filter(C=>C&&p.has(C)));if(!c)return null;const f=C=>{a(s.id,{summary:{...i,...C}})},T=(C,k)=>{const w=lt(C),D=u.filter(A=>j.has(lt(A))),y=k?j.has(w)?D:[...D,C].slice(0,ds):D.filter(A=>lt(A)!==w);f({breakdownDimensions:y})};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:!x,onCheckedChange:C=>{if(!C){f({enabled:!1,showOnCard:!1,includeInDashboardSummary:!1});return}f({enabled:!0,showOnCard:i.showOnCard??!0,includeInDashboardSummary:i.includeInDashboardSummary??!0,anomalyEnabled:i.anomalyEnabled??!0})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Comparison"}),e.jsxs("p",{className:"rounded-md border border-border bg-muted/40 px-2 py-1.5 text-xs",children:["Using: ",h]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Comparison is configured from card/metric comparison settings."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"summary-show-on-card",className:"text-xs",children:"Show summary on card"}),e.jsx(t.Switch,{size:"sm",id:"summary-show-on-card",checked:i.showOnCard===!0,disabled:!m,onCheckedChange:C=>f({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=>f({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,"/",ds]})]}),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 k=lt(C),w=j.has(k),D=j.size>=ds,y=!m||!w&&D;return e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx(t.Checkbox,{id:`summary-breakdown-${k}`,checked:w,disabled:y,onCheckedChange:A=>T(C,A===!0)}),e.jsx(t.Label,{htmlFor:`summary-breakdown-${k}`,className:"cursor-pointer text-xs",children:C.label||C.name})]},k)})})]}),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=>f({anomalyEnabled:C})})]})]})]})}const bo=[];function jo(){var d;const s=t.useEditorStore(i=>i.card),a=((d=s==null?void 0:s.config)==null?void 0:d.metricColumns)??bo,{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(fa.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(bs,{value:i.format,onChange:l=>{var c;n(s.id,i.id,{format:l}),r({...s,config:{...s.config,metricColumns:(((c=s.config)==null?void 0:c.metricColumns)||[]).map(o=>o.id===i.id?{...o,format:l}:o)}})}})]},i.id))})]})}const vo=new Set(["area","bar","bubble","bullet","combo","doughnut","funnel","horizontalBar","line","pie","polarArea","radar","scatter","stackedArea","stackedBar","stackedLine","tornado"]);function yo(){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:d}=t.useEditorActions();if(!s||!vo.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",c=o=>{const m={...a||{},tooltipConfig:{...i||{},...o}};r(m),d({...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=>c({formatMode:o?"override":"inherit",mode:o?"override":"inherit"})})]}),l==="override"&&e.jsx(jt,{formatOptions:(i==null?void 0:i.formatOptions)||{},onFormatOptionsChange:o=>c({formatMode:"override",mode:"override",formatOptions:o}),showTitle:!1})]})]})}function Jn({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(Vl,{}),(a==="area"||a==="stackedArea")&&e.jsx(Ul,{}),a==="line"&&e.jsx(Yl,{}),(a==="bar"||a==="horizontalBar"||a==="stackedBar")&&e.jsx(to,{}),e.jsx(oo,{}),e.jsx(mo,{}),e.jsx(Sl,{}),s==="config"&&e.jsx(Cl,{}),s==="config"&&e.jsx(go,{}),e.jsx(Tl,{}),a==="bullet"&&e.jsx(El,{}),a==="funnel"&&e.jsx(Dl,{}),(a==="bubble"||a==="scatter")&&e.jsx(Il,{}),(a==="stackedBar"||a==="stackedLine")&&e.jsx(xo,{}),e.jsx(jo,{}),e.jsx(jl,{}),e.jsx(vl,{}),e.jsx(yl,{}),e.jsx(Nl,{}),e.jsx(yo,{})]})}function No(){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(Jn,{mode:"dev"})})]}):null}function Co(){const s=t.useEditorStore(d=>d.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(Zr,{});case"table":return e.jsx(pl,{});case"map":return e.jsx(nl,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(Un,{})});case"text":return e.jsx(gl,{});default:return e.jsx(No,{})}}return e.jsxs(t.ScrollArea,{className:"h-full w-full text-sm",children:[r(),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}function So(){const s=N.useRef(null),a=N.useRef(null),n=t.useEditorStore(p=>p.isShowingVisual),r=t.useEditorStore(p=>p.isDevMode),d=t.useEditorStore(p=>p.showAIDialog),[i,l]=N.useState(!1),c=n&&!d,o=c&&(!r||i),m=r&&c,x=()=>l(p=>!p);N.useEffect(()=>{var p,j,f,T;d?((p=s.current)==null||p.resize(0),(j=a.current)==null||j.resize(0)):((f=s.current)==null||f.resize(25),(T=a.current)==null||T.resize(25))},[d]);const[b,h]=N.useState(!1),u=m?{show:!0,isOpen:i,onToggle:x}:void 0;return 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:50,children:e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex min-h-0 flex-1 flex-col",children:e.jsx(dr,{})}),e.jsx(as,{mode:"toolbar",visualAsideControl:u,isDynamicInspectorOpen:b,onDynamicInspectorOpenChange:h})]})}),e.jsx(t.ResizableHandle,{withHandle:!0}),e.jsx(t.ResizablePanel,{role:"visual-section",minSize:0,defaultSize:50,children:o?e.jsxs(t.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(t.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(as,{mode:"canvas",visualAsideControl:u,isDynamicInspectorOpen:b,onDynamicInspectorOpenChange:h})}),!d&&e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{ref:s,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(Co,{})})]}):e.jsx(as,{mode:"canvas",visualAsideControl:u,isDynamicInspectorOpen:b,onDynamicInspectorOpenChange:h})})]})}function wo(s){var ge;t.useAIInteractionStore($=>$.currentAIContext);const[a,n]=N.useState(""),[r,d]=N.useState(null),{authToken:i,tokenProps:l}=t.useSemaphorContext(),c=t.useEditorStore($=>$.card.id),o=t.useEditorStore($=>{var ee;return(ee=$==null?void 0:$.card)==null?void 0:ee.sql}),m=t.useEditorStore($=>$.isDevMode),x=t.useEditorStore($=>{var ee;return(ee=$==null?void 0:$.card)==null?void 0:ee.python}),{setCardPython:b,setCardSql:h,setRunSql:u,switchCardType:p,setQueryConfig:j}=t.useEditorActions(),f=t.useEditorStore($=>$.currentAssitantScope)||[],T=t.useEditorStore($=>$.userInputForAI),E=t.useEditorStore($=>$.triggerAIRun),O=t.useEditorStore($=>$.card),C=t.useEditorStore($=>$.selectedDatabaseName),k=t.useEditorStore($=>$.selectedTableName),w=t.useEditorStore($=>$.selectedConnectionId),D=t.useEditorStore($=>$.selectedSchemaName),y=t.useDashboardStore($=>$.dashboard.aiScopeTables),{errorMessage:A,refetch:g,data:R}=t.useEditorCardQuery(O),{setTriggerAIRun:M,setCurrentAssitantScope:S,setCardConfig:F}=t.useEditorActions(),{selectedDatamodelName:v,connectionType:L,selectedDatamodelId:I}=t.useEditorAside(),P=(ge=t.useDashboardQuery().data)==null?void 0:ge.assistantProfileId,V=N.useRef(t.createAssistantConversationId()),z=N.useRef(null),B=N.useRef(c),_=N.useRef(!1),U=()=>{const $=z.current;$&&(z.current=null,V.current=t.createAssistantConversationId(),$==="clear"&&H([]))},{messages:K,setMessages:H,regenerate:Z,error:de,sendMessage:ae,status:ce,addToolResult:me,stop:he,clearError:Ne}=t.useChat({transport:new t.DefaultChatTransport({api:`${l.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${i==null?void 0:i.accessToken}`}),body:()=>{const $=t.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:P,conversationId:V.current,assistantRequestId:t.createAssistantRequestId(),isDevMode:m,aiContext:$.currentAIContext,reasoningEffort:$.reasoningEffort,showReasoning:$.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:$,body:ee})=>({body:{...ee,messages:t.cleanupIncompleteMessages($)}})}),onError:$=>{var ee;if(_.current=!1,$.name==="AbortError"||(ee=$.message)!=null&&ee.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)"),U();return}console.error("[Editor Assistant] Stream error:",$),U()},onToolCall:je,onFinish({isAbort:$,isDisconnect:ee,isError:ue}){_.current=!1,n(""),console.log($?"[Editor Assistant] Stream aborted by user":ee?"[Editor Assistant] Stream disconnected (network error)":ue?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully"),U()}}),we=N.useCallback($=>{_.current=!0;try{const ee=ae($);return t.isPromiseLike(ee)?ee.catch(ue=>{throw _.current=!1,ue}):ee}catch(ee){throw _.current=!1,ee}},[ae]),Ie=N.useCallback(()=>{_.current=!0;try{const $=Z();return t.isPromiseLike($)?$.catch(ee=>{throw _.current=!1,ee}):$}catch($){throw _.current=!1,$}},[Z]),X=$=>{let ee=!1;H(ue=>{const Se=typeof $=="function"?$(ue):$;if(Se.length===0){if(_.current)return z.current="clear",ee=!0,ue;z.current=null,V.current=t.createAssistantConversationId()}return Se}),ee&&he()};N.useEffect(()=>{if(B.current!==c){if(B.current=c,_.current){z.current!=="clear"&&(z.current="rotate"),he();return}z.current=null,V.current=t.createAssistantConversationId()}},[c,he]),N.useEffect(()=>{E&&T&&(we({role:"user",parts:[{type:"text",text:T}]}),M(!1))},[E,T,we,M]);async function je({toolCall:$}){var ee,ue,Se,q,se,oe,be,ye,Oe,Ve,Ge,Je,Ye,ne,Ee,Be;if(["createChartFromSql","createForecast"].includes($.toolName)){const Ce=((ee=$.input)==null?void 0:ee.sql)??((ue=$.args)==null?void 0:ue.sql),Ue=((Se=$.input)==null?void 0:Se.python)??((q=$.args)==null?void 0:q.python),Te=((se=$.input)==null?void 0:se.chartType)??((oe=$.args)==null?void 0:oe.chartType);p(Te),h(Ce),b(Ue),u(!0),me({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if($.toolName==="getUserSql"){if(!o){me({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",message:"No SQL found"}});return}me({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",sql:o,python:x||""}})}else if($.toolName==="generateQueryConfig"){n("Generating query config...");const Ce=((be=$.input)==null?void 0:be.chartType)??((ye=$.args)==null?void 0:ye.chartType),Ue=((Oe=$.input)==null?void 0:Oe.queryConfig)??((Ve=$.args)==null?void 0:Ve.queryConfig);((Ge=$.input)==null?void 0:Ge.cardConfig)??((Je=$.args)==null||Je.cardConfig),p(Ce),F(Ue),h(void 0),b(void 0);const Te=await g();if((Ye=Te==null?void 0:Te.data)!=null&&Ye.error){me({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",queryConfig:Ue,message:(ne=Te==null?void 0:Te.data)==null?void 0:ne.error.message}});return}if((Ee=Te==null?void 0:Te.data)!=null&&Ee.records){me({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:Ue,message:"The data has been visualized"}});return}me({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:Ue,message:"The data has been visualized",records:(Be=Te==null?void 0:Te.data)==null?void 0:Be.records}})}else n("Analyzing...")}function ke($){const ee=t.removeFromScopeArray(f,$);te(ee)}function te($){const ee=t.sanitizeAIScope($);S(ee),H(ue=>[...ue,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(ee)}`}]}])}function De(){const $={databaseName:C||"",schemaName:D||"",tableName:k||"",datamodelId:I||"",datamodelName:t.resolveDatamodelName(v),connectionId:w||"",connectionType:L||""},ee=t.dedup([...f,$]);te(ee)}function Me(){const $={databaseName:C||"",schemaName:D||"",tableName:k||"",datamodelName:t.resolveDatamodelName(v),connectionId:w||"",connectionType:L||"",datamodelId:I||""};if(!t.isInAiScopeArray([...y||[],...f],$)||f.length===0){const ue=t.dedup([...y||[],...f,$]).filter(Se=>Se.connectionId===$.connectionId);te(ue)}}const le=!["ready","error"].includes(ce),ve=t.getErrorMessage(de);return{messages:K,setMessages:X,sendMessage:we,regenerate:Ie,isLoading:le,handleSetAIScope:Me,handleAddCurrentTableToScope:De,removeFromCurrentSelections:ke,currentAssitantScope:f,setCurrentAssitantScope:S,stop:he,status:ce,toolStatus:a,llmUsage:r,onFinish:s,errorMessage:ve,clearError:Ne}}const To=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function En({isFullscreen:s,onFullscreenChange:a,fullscreenContainer:n}){const r=N.useRef(null),d=N.useRef(!1),[i,l]=N.useState(!1),[c,o]=N.useState(t.isDevEnv),[m,x]=N.useState(!1),[b,h]=N.useState(!1),[u,p]=N.useState(!1),j=s??u,f=t.useCurrentAIContext(),{setCurrentAIContext:T,setHasEditorEntitySelectionOverride:E}=t.useAIActions(),{clearQueue:O}=t.useQueueActions(),{clearFileAttachments:C}=t.useFileActions(),k=t.useFileAttachments("editor"),{selectedEntities:w}=t.useAssistantContextEntities("editor"),D=t.useEditorStore(ne=>ne.card.id),y=t.useEditorStore(ne=>ne.card.dataSource),A=t.useEditorStore(ne=>{var Ee;return(Ee=ne.card.dataSource)==null?void 0:Ee.selectedEntities}),g=t.useEditorStore(ne=>ne.actions.setCardSql),R=t.useEditorStore(ne=>ne.actions.setRunSql),M=t.useEditorStore(ne=>ne.showAIDialog),S=t.useDashboardStore(ne=>ne.handleOpenAssistantProfile),{setShowAIDialog:F,setCardPython:v}=t.useEditorActions(),{setDataSource:L}=t.useEditorActions(),{assistantProfile:I}=t.useAssistantProfile(),{messages:P,setMessages:V,sendMessage:z,isLoading:B,stop:_,status:U,llmUsage:K,errorMessage:H,clearError:Z}=wo(),[de,ae]=N.useState(""),ce=ne=>{ae(ne.target.value)},me=ne=>{ne.preventDefault();const Ee=de.trim();if(!Ee&&k.length===0)return;const Be=[];Ee&&Be.push({type:"text",text:Ee}),k.forEach(Ce=>{Ce.data&&Be.push({type:"file",mediaType:Ce.type,filename:Ce.name,url:`data:${Ce.type};base64,${Ce.data}`})}),z({role:"user",parts:Be}),ae(""),C("editor"),le({force:!0})},{visibleMessages:he,hasMoreMessages:Ne,totalMessageCount:we,loadMoreMessages:Ie,resetMessageWindow:X}=t.useMessageWindow(P,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:je,contentRef:ke,isAtBottom:te,hasNewMessages:De,newMessageCount:Me,scrollToBottom:le,handleScroll:ve,resetNewMessageCount:ge}=t.useAutoScroll(he,{threshold:40,behavior:"smooth",isStreaming:B});N.useEffect(()=>{var ne;M&&!d.current&&((ne=r.current)==null||ne.focus()),d.current=M},[M]),N.useEffect(()=>{M&&(E(!1),T({selectedEntities:A||[]}))},[D,A,T,E,M]),t.useAutoSubmitQueue({assistantType:"editor",status:U,isLoading:B,sendMessage:z});const{hasActiveTools:$,activeToolText:ee}=t.useActiveToolStatus(P),ue=N.useCallback(ne=>{a==null||a(ne),s===void 0&&p(ne)},[s,a]);N.useEffect(()=>{if(!j)return;function ne(Ee){Ee.key==="Escape"&&ue(!1)}return window.addEventListener("keydown",ne),()=>{window.removeEventListener("keydown",ne)}},[j,ue]);const Se=N.useCallback(ne=>{z({role:"user",parts:[{type:"text",text:ne}]}),le({force:!0})},[z,le]),q=N.useCallback(async()=>{const ne=JSON.stringify(P??[],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(Ee){console.error("Failed to copy conversation",Ee),t.ue.error("Unable to copy conversation")}},[P]),se=N.useCallback(()=>{ue(!j)},[j,ue]);function oe(ne,Ee){Ee==="sql"?(g(ne),R(!0)):Ee==="python"&&(v(ne),R(!0))}function be(){f.selectedEntities.length===0&&T({selectedEntities:w})}function ye(ne){be();const Ee={role:"user",parts:[{type:"text",text:ne.title+" "+ne.subtitle}]};z(Ee)}function Oe(ne){be(),z({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:c,onCheckedChange:o,children:"Tool Invocations"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:m,onCheckedChange:x,children:"System Message"})]})]})}function Ge(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const Je=(de==null?void 0:de.length)===0&&(P==null?void 0:P.filter(ne=>ne.role==="user").length)===0,Ye=e.jsxs("div",{"data-role":"editor-assistant",className:t.cn("flex h-full w-full flex-col justify-between px-6 py-4",j&&"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:[Ge(),S&&e.jsx(t.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:S,children:(I==null?void 0:I.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[Ve(),c&&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:j?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:se,children:j?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:()=>{V([]),O("editor"),Z(),X()},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:je,className:"mt-2 flex min-w-0 w-full grow basis-0",onScroll:ve,children:e.jsxs("div",{ref:ke,className:"min-w-0 space-y-4 py-2 pr-3","data-role":"messages",children:[Ne&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:Ie,className:"text-xs",children:["Load ",Math.min(5,we-he.length)," ","more messages (",we-he.length," ","hidden)"]})}),e.jsx(t.PrintMessages,{messages:he,showTools:c,handleRun:oe,showSystemMessage:m,onQuickReply:Se,disableQuickReplies:B}),e.jsx(t.AssistantStatus,{status:U,errorMessage:H,activeToolText:B&&$?ee:void 0})]})}),M&&!te&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(t.Button,{onClick:()=>{le({force:!0}),ge()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(t.ChevronDown,{className:"h-4 w-4"}),De&&Me>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:Me>9?"9+":Me})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[Je&&!I&&e.jsx(t.Placeholders,{onClick:ye,placeholders:To}),e.jsx("div",{children:Je&&I&&e.jsx(t.SeedQuestions,{seedQuestions:I.seedQuestions||[],handleSeedQuestionClick:Oe})})]}),e.jsx(t.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(t.ChatInputWithContext,{ref:r,setInput:ae,stop:_,input:de,handleInputChange:ce,handleSubmit:ne=>{be(),me(ne),le({force:!0})},isLoading:B,status:U,assistantType:"editor",onFocus:()=>{}})]}),K&&i&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",K.inputTokens," prompt tokens, ",K.outputTokens," ","completion tokens, ",K.totalTokens," total tokens"]})}),e.jsx(t.AddDataPicker,{incomingSelectedEntities:w,open:b,onOpenChange:h,dataSource:y||t.EMPTY_DATA_SOURCE,dialogMode:"aiContext",onSaveSelectedEntities:ne=>{E(!0),T({...f,selectedEntities:ne})}})]});return j&&n?pa.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:Ye})}),n):Ye}function Eo(s,a,n){if(!a)return!1;const r=a.qualifiedFieldName,d=a.qualifiedEntityName,i=d&&a.name?`${d}.${a.name}`:r;return s.some(l=>{if(!(t.getDataType(l.dataType||"")==="date"))return!1;const o=t.getSelectedDateFilterColumn(l,n),m=o.split("."),x=m[m.length-1]||o,b=m.length>1?m.slice(0,-1).join("."):void 0,h=l.qualifiedTableName||b,u=h?`${h}.${x}`:void 0;return r?u?u===i||u.endsWith(`.${r}`):x===a.name:u?u===i:x===a.name})}function Io({aliasTemplate:s,onAliasTemplateChange:a}){var o;const[n,r]=N.useState(s),[d,i]=N.useState(!1),l=(o=t.useEditorStore(m=>{var x;return(x=m.card.config)==null?void 0:x.pivotByColumns}))==null?void 0:o[0],c=l?`e.g. Min Sales in {{${l.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Input,{placeholder:c,value:d?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"&&d&&n!==s?(a(n),i(!1)):m.key==="Escape"&&(r(s),i(!1))},"aria-label":"Edit alias template"}),d&&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 ko({valueAliases:s,onValueAliasesChange:a}){const[n,r]=N.useState(null),[d,i]=N.useState(""),[l,c]=N.useState(""),o=()=>{a({...s,"":""})},m=b=>{const h={...s};delete h[b],a(h)},x=b=>{const h={...s};delete h[b],h[d]=l,a(h),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(s).map(([b,h],u)=>e.jsx("div",{className:"flex items-center gap-2",children:n===b?e.jsxs(e.Fragment,{children:[e.jsx(t.Input,{placeholder:"Value key",value:d,onChange:p=>i(p.target.value),className:"h-8 w-24 text-xs",onPointerDown:p=>p.stopPropagation(),onKeyDown:p=>{p.key==="Enter"?x(b):p.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(t.Input,{placeholder:"Alias label",value:l,onChange:p=>c(p.target.value),className:"h-8 w-24 text-xs",onPointerDown:p=>p.stopPropagation(),onKeyDown:p=>{p.key==="Enter"?x(b):p.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:()=>x(b),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:b,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(b),i(b),c(h)},"aria-label":"Edit value alias key"}),e.jsx(t.Input,{placeholder:"Alias label",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(b),i(b),c(h)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>m(b),"aria-label":"Remove value alias",children:e.jsx(t.X,{className:"h-3 w-3"})})]})},b+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 Do({idx:s}){var c;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),d=(c=a==null?void 0:a.chartOptions)==null?void 0:c.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 x={display:o!=="none",align:o,anchor:o,clamp:!0};if(!i)r({...a,datasetOptions:[...n||[],{idx:m,datalabels:x}]});else{const b={...i};b.datalabels=x;const h=n==null?void 0:n.map(u=>u.idx===m?b:u);r({...a,datasetOptions:h})}}return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{children:e.jsx(Ba,{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(wa,{className:t.cn("h-4 w-4",{"rotate-90":d==="y"})})}),e.jsx("button",{onClick:()=>l("center",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Ea,{className:t.cn("h-4 w-4",{"rotate-90":d==="y"})})}),e.jsx("button",{onClick:()=>l("end",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Ta,{className:t.cn("h-4 w-4",{"rotate-90":d==="y"})})})]})})]})}function js({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 Ao(s,a=30){return s.length>a?s.slice(0,a)+"...":s}function Mo({col:s,idx:a,className:n,iconClassName:r,children:d}){const i=t.useEditorStore(x=>{var b;return(b=x.card)==null?void 0:b.preferences}),l=t.useEditorStore(x=>{var b,h;return(h=(b=x.card)==null?void 0:b.preferences)==null?void 0:h.datasetOptions}),c=l==null?void 0:l.find(x=>x.idx===a),{setCardPreferences:o}=t.useEditorStore(x=>x.actions);function m(x){if(!c)o({...i,datasetOptions:[...l||[],{idx:a,type:x==="area"?"line":x,fill:x==="area"?"origin":""}]});else{const b={...c};b.type=x==="area"?"line":x,b.fill=x==="area"?"origin":"";const h=l==null?void 0:l.map(u=>u.idx===a?b:u);o({...i,datasetOptions:h})}}return e.jsxs("div",{className:t.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[d||e.jsx(js,{className:"max-w-[100px]",title:s,children:Ao(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(Do,{idx:a})]})]})}function Lo(){const s=t.useEditorStore(c=>c.card.type),a=t.useEditorStore(c=>c.isDevMode),n=t.useEditorStore(c=>c.card.preferences),{setCardPreferences:r}=t.useEditorStore(c=>c.actions);function d(c){var x;const o={datalabels:{display:c!=="none",align:c,anchor:c,clamp:!0}},m={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(x=n==null?void 0:n.chartOptions)==null?void 0:x.plugins,...o}}};r(m)}function i(){var c,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=(c=n==null?void 0:n.chartOptions)==null?void 0:c.plugins)==null?void 0:o.datalabels)==null?void 0:m.anchor)||"none",onValueChange:d,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Data Labels"}),e.jsx(t.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"start",children:"Start"}),e.jsx(t.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"end",children:"End"})]})})]})]})}function l(){var c,o,m;return e.jsx("div",{children:e.jsxs(t.Select,{value:((m=(o=(c=n==null?void 0:n.chartOptions)==null?void 0:c.plugins)==null?void 0:o.datalabels)==null?void 0:m.anchor)||"none",onValueChange:d,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(t.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:a?i():l()})}function Fo({column:s}){const a=t.useEditorStore(o=>o.card.type),n=t.useEditorStore(o=>{var m,x;return(x=(m=o.card)==null?void 0:m.config)==null?void 0:x.metricColumns}),r=(n==null?void 0:n.map(o=>o.label))||[],d=r==null?void 0:r.find(o=>o===s.label||o===s.name),i=d?r.indexOf(d):-1;function l(){return e.jsx("div",{className:"pr-1",children:d&&e.jsx(Mo,{idx:i,col:d,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function c(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(Lo,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&l(),["pie","doughnut"].includes(a)&&c()]})}function Ro({field:s,searchQuery:a="",limit:n=500}){const{authToken:r,tokenProps:d}=t.useSemaphorContext(),i=t.useEditorStore(m=>m.card),l=i==null?void 0:i.dataSource,c=["attribute-values",s.entityName,s.name,a,n],o=t.useQuery({queryKey:c,queryFn:async()=>{if(!(l!=null&&l.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const 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},x={connection_id:l.connectionId,cardConfig:m,cardDataSource:l,cache_config:t.getCacheConfig({card:i})};console.log("requestBody",x);const b=await t.postRequestRegular(`${d.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",x);if(b!=null&&b.error)return console.error("Error fetching attribute values:",b.error),[];const h=s.name;return((b==null?void 0:b.records)||[]).map(p=>{const j=p[h]||p[s.alias||h]||p[s.label];return{id:j||"",value:j||"",label:String(j||"(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 Yn({open:s,onOpenChange:a,availableFields:n,existingFilters:r,editingCondition:d,onSave:i}){var O,C;const l=!!d,[c,o]=N.useState(l?"values":"fields"),[m,x]=N.useState(""),[b,h]=N.useState({id:(d==null?void 0:d.id)||t.v4(),field:(d==null?void 0:d.field)||null,selectedValues:d?Array.isArray(d.value)?d.value:[d.value]:[]}),u=n.filter(k=>{var D;return l?!1:!((D=r==null?void 0:r.conditions)==null?void 0:D.some(y=>y.field.id===k.id))&&k.label.toLowerCase().includes(m.toLowerCase())}),p=k=>{h({...b,field:k}),o("values")},j=()=>{if(b.field&&b.selectedValues.length>0){const k={id:b.id,field:b.field,operator:"in",value:b.selectedValues};let w;if(l){const D=((r==null?void 0:r.conditions)||[]).map(y=>y.id===d.id?k:y);w={...r,conditions:D}}else{const D=(r==null?void 0:r.conditions)||[];w={id:(r==null?void 0:r.id)||t.v4(),logicalOperator:"AND",negate:!1,conditions:[...D,k],groups:[]}}i(w),a(!1)}},f=()=>{if(!l||!d)return;const k=((r==null?void 0:r.conditions)||[]).filter(w=>w.id!==d.id);if(k.length>0){const w={...r,conditions:k};i(w)}else i(void 0);a(!1)},T=k=>{h({...b,selectedValues:k})},E=()=>{l&&d?(h({id:d.id,field:d.field,selectedValues:Array.isArray(d.value)?d.value:[d.value]}),o("values")):(h({id:t.v4(),field:null,selectedValues:[]}),o("fields")),x("")};return N.useEffect(()=>{s&&E()},[s,l,d]),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: ${(O=b.field)==null?void 0:O.label}`:c==="fields"?"Select Field to Filter":`Select Values for ${(C=b.field)==null?void 0:C.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!l&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&c==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Current Filters:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.conditions.map(k=>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:[k.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(k.value)?`${k.value.length} values`:String(k.value)})]},k.id))})]}),c==="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:k=>x(k.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:()=>x(""),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(k=>e.jsxs("button",{type:"button",onClick:()=>p(k),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(k.dataType)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-[13px] text-foreground",children:k.label}),e.jsxs("div",{className:"truncate font-mono text-[10px] text-muted-foreground",children:[k.entityName,".",k.name]})]})]},k.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(Oo,{field:b.field,selectedValues:b.selectedValues,onValuesChange:T,onBack:l?void 0:()=>o("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:l?e.jsx(t.Button,{variant:"destructive",onClick:f,children:"Delete Filter"}):e.jsx(t.Button,{variant:"outline",onClick:E,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(t.Button,{onClick:j,disabled:!b.field||b.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function Oo({field:s,selectedValues:a,onValuesChange:n,onBack:r}){const[d,i]=N.useState(""),{values:l,isLoading:c,isFetching:o}=Ro({field:s,searchQuery:d,limit:500}),m=d?l.filter(h=>String(h.value).toLowerCase().includes(d.toLowerCase())):l,x=h=>{const u=a.includes(h);n(u?a.filter(p=>p!==h):[...a,h])},b=()=>{a.length===m.length&&m.length>0?n([]):n(m.map(h=>h.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:r,children:"← Back"}),e.jsxs(t.Label,{className:"text-sm font-medium",children:["Select values for ",s.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(t.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(t.Input,{placeholder:"Search values...",value:d,onChange:h=>i(h.target.value),className:"pl-10"})]}),c||o?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(t.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx(t.Checkbox,{checked:a.length===m.length&&m.length>0,onCheckedChange:b}),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(h=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>x(h.value),children:[e.jsx(t.Checkbox,{checked:a.includes(h.value),onCheckedChange:()=>x(h.value)}),e.jsx(js,{className:"text-sm",children:h.label})]},h.id))})]})]})}function Po({field:s,zone:a,index:n,sortDirection:r,onSortDirectionChange:d,hasPivotColumns:i=!1,cardType:l}){var Ts,Es,Is,ks,Ds,As,Ms,Ls,Fs,Rs,Os,Ps,Bs,Vs,zs,_s,qs,$s,Ks,Gs,Us,Hs,Qs,Ws,Js,Ys,Xs,Zs,en,tn,sn,nn,an;const{attributes:c,listeners:o,setNodeRef:m,transform:x,transition:b,isDragging:h}=t.useSortable({id:s.id}),u=t.useEditorStore(Q=>Q.card),p=t.useEditorStore(Q=>Q.frame),j=t.useDashboardStore(Q=>Q.isVisualEditing),f=t.useDashboardStore(Q=>Q.selectedSheetId),T=t.useDashboardStore(Q=>Q.actions.updateSheetCalculatedFields),{scopedFields:E,valuePickFilterableFields:O,isLoading:C}=t.useFilterableFields(),{userContext:k}=t.useCurrentUserInfo(),w=(k==null?void 0:k.type)==="organization",{updateLabel:D,handleAggregationChange:y,handleDateFormatChange:A,handleGranularityChange:g,handleAliasTemplateChange:R,handleValueAliasesChange:M,handleMetricFormatChange:S,removeField:F,handleMetricComparisonChange:v,handleMetricWindowTransformChange:L,handleMetricWindowOrderByChange:I,handleMetricWindowDirectionChange:P,handleMetricWindowPartitionToggle:V,handleMetricMovingAverageWindowSizeChange:z,handleMetricMovingAverageMinPeriodsChange:B,handleMetricPreviousPeriodDeltaModeChange:_,handleMetricPercentOfTotalScopeChange:U,handleMetricPercentOfTotalOutputChange:K,handleKpiShowTrendlineChange:H,handleKpiTrendlineWindowChange:Z,handleKpiTrendlineGranularityChange:de,handleMetricTargetValueChange:ae}=t.useFieldManagement(u),[ce,me]=N.useState(!1),[he,Ne]=N.useState(()=>{var Q;return!!((Q=s.parameters)!=null&&Q.windowTransform)}),[we,Ie]=N.useState(!1),[X,je]=N.useState(!1),[ke,te]=N.useState(null),De=N.useMemo(()=>{const Q=re=>re!=null&&re.startsWith("card-source-")?re.replace("card-source-",""):re,J=Q(s.id),xe=E.find(re=>{if(s.qualifiedFieldName&&re.qualifiedFieldName&&re.qualifiedFieldName===s.qualifiedFieldName||s.qualifiedEntityName&&re.qualifiedEntityName&&re.qualifiedEntityName===s.qualifiedEntityName&&re.name===s.name)return!0;const Le=Q(re.id);return!!(J&&Le&&J===Le)});return{dataType:(xe==null?void 0:xe.dataType)||s.dataType,resolvedFromScopedField:!!xe}},[s.dataType,s.id,s.name,s.qualifiedEntityName,s.qualifiedFieldName,E]),Me=t.getGranularityOptionsForFieldType(De.dataType),[le,ve]=N.useState(s.dateFormat||"YYYY-MM-DD"),[ge,$]=N.useState(s.customFormat||""),[ee,ue]=N.useState(!!s.customFormat),Se=N.useRef(null),[q,se]=N.useState(s.aliasTemplate||""),[oe,be]=N.useState(s.valueAliases||{}),[ye,Oe]=N.useState((Ts=s.parameters)==null?void 0:Ts.filters),Ve=Q=>{Q==="custom"?ue(!0):(ue(!1),ve(Q),(a==="groupBy"||mt)&&A(n,Q,"",a))},Ge=Q=>{$(Q),(a==="groupBy"||mt)&&A(n,"custom",Q,a)},Je=Q=>{var re;const xe=(re=t.getDateFormatOptionsForGranularity(Q)[0])==null?void 0:re.value;xe&&!ee&&(ve(xe),a==="groupBy"&&A(n,xe,"",a)),a==="groupBy"&&g(n,Q)},Ye=Q=>{se(Q),a==="metrics"&&R(n,Q)},ne=Q=>{be(Q),a==="metrics"&&M(n,Q)},Ee=Q=>{D(a,n,Q)},Be=t.getExpressionFieldKind(s),Ce=t.getFieldExpressionAnnotation(s),Ue=t.isManagedCalculatedExpressionField(s),Te=s.role==="metric"&&Ue,vt=Ue&&(Be==="user_calculated"||Be==="inline_expression"&&s.fieldScope!=="domain"),Xe=vt?(Es=p==null?void 0:p.calculatedFields)==null?void 0:Es.find(Q=>t.matchesCalculatedField(Q,s,{allowComparableFallback:!0})):void 0,It=vt&&(s.fieldScope==="dashboard"||s.fieldScope===void 0&&!!Xe),He=Be==="domain_calculated"||s.fieldScope==="domain",kt=He?t.resolveDomainCalculatedFieldForEdit(s,E):void 0,ct=He?"domain":It?"dashboard":"card",Ze=He?kt||s:It&&Xe?Xe:s,Dt=Q=>{var J;if(Oe(Q),a==="metrics"){const xe={...s,parameters:{...s.parameters,filters:Q}},re=[...((J=u.config)==null?void 0:J.metricColumns)||[]];re[n]=xe,t.useEditorStore.getState().actions.updateCardConfig(u.id,{metricColumns:re})}Ie(!1)},yt=()=>{F(a,n)},Ut={transform:t.CSS.Transform.toString(x),transition:b},At=t.getDataType(De.dataType||s.dataType),dt=At==="date",ut=l==="kpi",mt=a==="detailColumns",xt=(Is=u.config)==null?void 0:Is.metricColumns,$e=(ks=u.config)==null?void 0:ks.groupByColumns,et=t.useDashboardStore(Q=>{var J;return(J=Q.dashboard)==null?void 0:J.filters}),Ht=t.useDashboardStore(Q=>Q.filterValues),tt=s.granularity||"day",Mt=Me.includes(tt)?tt:"day",Nt=a==="groupBy"&&!Me.includes(tt),ht=t.getDateFormatOptionsForGranularity(Mt),Qt=ee?"custom":ht.some(Q=>Q.value===le)?le:((Ds=ht[0])==null?void 0:Ds.value)??"YYYY-MM-DD";N.useEffect(()=>{var xe;if(C||!Nt){Se.current=null;return}const Q=`${s.id}:${tt}:${De.dataType||s.dataType||""}:${n}`;if(Se.current===Q)return;Se.current=Q;const J="day";if(g(n,J),!ee){const re=(xe=t.getDateFormatOptionsForGranularity(J)[0])==null?void 0:xe.value;re&&(ve(re),A(n,re,"",a))}},[s.dataType,s.id,A,g,Nt,n,ee,C,tt,De.dataType,a]);const Wt=!!l&&t.COMPARISON_SUPPORTED_CHART_TYPES.includes(l),Jt=l==="kpi"||l==="table",Ke=N.useMemo(()=>$e==null?void 0:$e.find(Q=>t.getDataType(Q.dataType||"")==="date"),[$e]),Lt=N.useMemo(()=>($e||[]).some(Q=>t.getDataType(Q.dataType||"")==="date"),[$e]),pt=N.useMemo(()=>{var re;if(!Ke)return!1;const Q=(re=u.config)==null?void 0:re.filters;if(!Q)return!1;const J=Le=>{const Re=Le.field;return Re?Ke.id&&Re.id===Ke.id||Ke.qualifiedFieldName&&Re.qualifiedFieldName===Ke.qualifiedFieldName?!0:Re.name===Ke.name:!1},xe=Le=>Le.conditions.some(_e=>t.getDataType(_e.field.dataType||"")==="date"&&J(_e))?!0:Le.groups.some(_e=>xe(_e));return xe(Q)},[(As=u.config)==null?void 0:As.filters,Ke]),Ft=N.useMemo(()=>Eo(et||[],Ke,Ht),[et,Ht,Ke]),Ct=pt||Ft,G=s,Y=((Ls=(Ms=G.parameters)==null?void 0:Ms.windowTransform)==null?void 0:Ls.function)||"none",W=t.isMetricTransformEnabled(G),ie=W?Y:null,pe=t.supportsMetricTransformForMetric({cardType:l||"table",cardConfig:u.config||{},metric:G,transformMode:ie||"running_total"}),fe=!!G.comparisonType&&G.comparisonType!=="none",Fe=t.getRunningTotalOrderByCandidates($e||[]),Pe=((Os=(Rs=(Fs=G.parameters)==null?void 0:Fs.windowTransform)==null?void 0:Rs.orderBy)==null?void 0:Os.fieldId)||"",We=((Vs=(Bs=(Ps=G.parameters)==null?void 0:Ps.windowTransform)==null?void 0:Bs.orderBy)==null?void 0:Vs.direction)||"asc",rt=Fe.find(Q=>Q.id===Pe),st=ie==="running_total"||ie==="moving_average"||ie==="previous_period_delta",ze=W&&st&&!!rt&&t.getDataType(rt.dataType||"")!=="date",ft=t.getDefaultRunningTotalPartitionByFieldIds({cardType:l||"table",cardConfig:u.config||{},orderByFieldId:Pe||void 0}),Yt=new Set(((_s=(zs=G.parameters)==null?void 0:zs.windowTransform)==null?void 0:_s.partitionByFieldIds)||ft),Xt=l==="pivotTable"||t.isSubtotalEnabledAggregateTable(l||"table",u.config||{}),ys=[...($e||[]).filter(Q=>Q.id&&(!st||Q.id!==Pe)),...Xt?(((qs=u.config)==null?void 0:qs.pivotByColumns)||[]).filter(Q=>Q.id):[]],Ns=((Gs=(Ks=($s=G.parameters)==null?void 0:$s.windowTransform)==null?void 0:Ks.movingAverage)==null?void 0:Gs.windowSize)||7,Zn=((Qs=(Hs=(Us=G.parameters)==null?void 0:Us.windowTransform)==null?void 0:Hs.movingAverage)==null?void 0:Qs.minPeriods)||1,ea=((Ys=(Js=(Ws=G.parameters)==null?void 0:Ws.windowTransform)==null?void 0:Js.previousPeriodDelta)==null?void 0:Ys.mode)||"absolute",Cs=((en=(Zs=(Xs=G.parameters)==null?void 0:Xs.windowTransform)==null?void 0:Zs.percentOfTotal)==null?void 0:en.scope)||"grand_total",ta=((nn=(sn=(tn=G.parameters)==null?void 0:tn.windowTransform)==null?void 0:sn.percentOfTotal)==null?void 0:nn.output)||"percent",sa=N.useMemo(()=>(xt||[]).some(Q=>Q.comparisonType==="start_vs_end"),[xt]);N.useEffect(()=>{W&&Ne(!0)},[W]);const na=a!=="pivotBy"&&a!=="sortBy",aa=dt&&a==="groupBy"&&(!ut||sa),ra=!ut&&dt&&(a==="groupBy"||mt),la=l==="kpi"&&dt&&a==="groupBy",oa=a==="metrics",Ss=Wt&&a==="metrics",ia=()=>{const Q=s,J=a==="metrics"&&Te;return e.jsxs("div",{className:"space-y-1",children:[!J&&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}`}),J&&Q.calculatedFormula&&e.jsxs("div",{title:t.formatDisplayFormula(Q.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(Q.calculatedFormula)]})]})},ca=()=>na?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(Qe,{value:s.label??"",onSave:Ee,placeholder:"Display label...",type:"text"})]}):null,da=()=>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:Q=>d(Q),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"})]})]})]}),ws=()=>aa?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:Mt,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:Me.map(Q=>e.jsx(t.SelectItem,{className:"text-xs",value:Q,children:t.toTitleCase(Q)},Q))})]})]}):null,ua=()=>ra?e.jsxs(e.Fragment,{children:[ws(),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:Qt,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(Q=>e.jsx(t.SelectItem,{className:"text-xs",value:Q.value,children:Q.label},Q.value))})]}),ee&&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:ge,onChange:Q=>{Q.stopPropagation(),Ge(Q.target.value)},onClick:Q=>Q.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,ma=()=>{var J,xe,re,Le;const Q=la;return Q?e.jsx(e.Fragment,{children:Q&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(t.Switch,{size:"sm",checked:((J=u.config)==null?void 0:J.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:((re=u.config)==null?void 0:re.trendlineWindow)||30,onChange:Re=>{const _e=parseInt(Re.target.value)||30;Z(_e)},className:"h-8 text-xs",placeholder:"30"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Granularity"}),e.jsxs(t.Select,{value:((Le=u.config)==null?void 0:Le.trendlineGranularity)||"day",onValueChange:de,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},xa=()=>{if(!oa)return null;const Q=Te;return e.jsxs(e.Fragment,{children:[Q&&w&&!He&&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:()=>je(!0),children:[e.jsx(t.Pencil,{className:"mr-2 h-3 w-3"}),"Edit Formula"]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(t.Select,{value:s.aggregate,onValueChange:J=>{y(n,J)},disabled:Q,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(bs,{value:G.format,onChange:J=>S(n,J),showTitle:!1})]}),e.jsx(t.Collapsible,{open:he,onOpenChange:Ne,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:[!he&&e.jsx("span",{className:"mr-2",children:W?t.toTitleCase(Y.replace(/_/g," ")):"None"}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 transition-transform",he?"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:W?Y:"none",onValueChange:J=>L(n,J),disabled:!pe.supported&&!W,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&&!W&&e.jsx("div",{className:"text-xs text-muted-foreground",children:pe.reason}),fe&&!W&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"Disable comparison to enable metric transforms."})]}),W&&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:J=>I(n,J),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select order field..."})}),e.jsx(t.SelectContent,{children:Fe.filter(J=>!!J.id).map(J=>e.jsx(t.SelectItem,{value:J.id,className:"text-xs",children:J.label||J.name},J.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:We,onValueChange:J=>P(n,J),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"})]})]})]})]}),ie==="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:Ns,onChange:J=>z(n,Number(J.target.value))}),e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Min Periods"}),e.jsx(t.Input,{type:"number",min:1,max:Ns,className:"h-8 text-xs",value:Zn,onChange:J=>B(n,Number(J.target.value))})]}),ie==="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:ea,onValueChange:J=>_(n,J),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select output..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"absolute",children:"Absolute Delta"}),e.jsx(t.SelectItem,{value:"percent",children:"Percent Delta"})]})]})]}),ie==="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:Cs,onValueChange:J=>U(n,J),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select scope..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"grand_total",children:"Grand Total"}),e.jsx(t.SelectItem,{value:"partition_total",children:"Partition Total"})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Output"}),e.jsxs(t.Select,{value:ta,onValueChange:J=>K(n,J),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select output..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"percent",children:"Percent"}),e.jsx(t.SelectItem,{value:"fraction",children:"Fraction"})]})]})]})]}),(ie==="running_total"||ie==="moving_average"||ie==="previous_period_delta"||ie==="percent_of_total"&&Cs==="partition_total")&&ys.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:ys.map(J=>{const xe=!!J.id&&Yt.has(J.id);return e.jsxs("button",{type:"button",onClick:()=>J.id&&V(n,J.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:J.label||J.name}),xe?e.jsx(t.Check,{className:"h-3 w-3"}):null]},J.id)})})]})]})]})]})}),Ss&&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:G.comparisonType||"none",disabled:W,onValueChange:J=>v(n,J),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"none",children:"No Comparison"}),(()=>{const J=!Lt||!Ct,xe=Lt?Ct?void 0:"Add a date filter to enable":"Add a date groupBy to enable",re=(Le,Re)=>e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.SelectItem,{value:Le,disabled:J,title:xe,children:Re})}),J&&xe&&e.jsx(t.TooltipContent,{side:"right",children:xe})]})});return e.jsxs(e.Fragment,{children:[re("previous_period","Previous Period"),re("same_period_last_year","Same Period Last Year"),re("start_vs_end","Start vs End")]})})(),Jt&&e.jsx(t.SelectItem,{value:"target",children:"Target"})]})]})]}),Ss&&G.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:G.targetValue!==void 0&&G.targetValue!==null?String(G.targetValue):"",onChange:J=>{const xe=J.target.value;if(xe===""){ae(n,void 0);return}const re=Number(xe);ae(n,Number.isFinite(re)?re:void 0)},className:"h-8 text-xs",placeholder:"Enter target value..."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(ye==null?void 0:ye.conditions)&&ye.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:ye.conditions.map(J=>e.jsxs("div",{className:"flex cursor-pointer items-center gap-2 rounded bg-muted/50 p-2 text-xs transition-colors hover:bg-muted/70",onClick:()=>{te(J),Ie(!0)},children:[e.jsxs("span",{className:"font-medium",children:[J.field.label,":"]}),e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"cursor-help text-muted-foreground",children:Array.isArray(J.value)?J.value.length===1?String(J.value[0]):J.value.length<=2?J.value.join(", "):`${J.value.slice(0,2).join(", ")} +${J.value.length-2}`:String(J.value)})}),Array.isArray(J.value)&&J.value.length>1&&e.jsx(t.TooltipContent,{side:"top",className:"max-w-[300px]",children:e.jsxs("div",{className:"text-xs",children:[e.jsxs("div",{className:"mb-1 font-medium",children:["Selected values (",J.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:J.value.map((xe,re)=>e.jsx("div",{children:String(xe)},re))})]})})]})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:xe=>{var Le;xe.stopPropagation();const re=ye.conditions.filter(Re=>Re.id!==J.id);if(re.length>0){const Re={...ye,conditions:re};Dt(Re)}else if(Oe(void 0),a==="metrics"){const Re={...s,parameters:{...s.parameters,filters:void 0}},_e=[...((Le=u.config)==null?void 0:Le.metricColumns)||[]];_e[n]=Re,t.useEditorStore.getState().actions.updateCardConfig(u.id,{metricColumns:_e})}},children:e.jsx(t.X,{className:"h-3 w-3"})})]},J.id))}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{te(null),Ie(!0)},children:[e.jsx(t.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(Fo,{column:s}),i&&e.jsxs(e.Fragment,{children:[e.jsx(Io,{aliasTemplate:q,onAliasTemplateChange:Ye}),e.jsx(ko,{valueAliases:oe,onValueAliasesChange:ne})]})]})};ye!=null&&ye.conditions&&ye.conditions.length>0;const ha=a!=="sortBy";return e.jsxs(e.Fragment,{children:[e.jsxs(t.Popover,{open:ce,onOpenChange:me,children:[e.jsxs("div",{ref:m,style:Ut,className:t.cn("group flex h-7 w-full items-center gap-1.5 rounded-[5px] border bg-background px-1.5 transition-colors",ce?"border-foreground/30 bg-muted/40":"border-border hover:bg-muted/40",h&&"z-50 scale-95 opacity-50"),children:[e.jsx("button",{type:"button",...c,...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:Q=>{Q.stopPropagation()},children:e.jsx(t.GripVertical,{className:"h-3 w-3"})}),e.jsx(t.TypeGlyph,{dataType:At,calculated:!!Ce}),e.jsx(js,{className:"block w-0 min-w-0 flex-1 text-[12px] text-foreground",children:t.getMetricDisplayLabel(s)}),a==="metrics"&&((an=ye==null?void 0:ye.conditions)==null?void 0:an.length)&&!ce&&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:ye.conditions.length})]})}),e.jsx(t.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:ye.conditions.map(Q=>e.jsxs("div",{children:[Q.field.label,":"," ",Array.isArray(Q.value)?`${Q.value.length} values`:String(Q.value)]},Q.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:Q=>{Q.stopPropagation(),d(r==="asc"?"desc":"asc")},children:r==="asc"?e.jsx(t.ArrowUp,{className:"h-3 w-3"}):e.jsx(t.ArrowDown,{className:"h-3 w-3"})}),ha&&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:Q=>Q.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:Q=>{Q.stopPropagation(),yt()},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:[ia(),da(),ca(),l==="kpi"&&ws(),ua(),ma(),xa()]})})]}),we&&e.jsx(Yn,{open:we,onOpenChange:Q=>{Ie(Q),Q||te(null)},availableFields:O,existingFilters:ye,editingCondition:ke,onSave:Q=>{var J;if(Q)Dt(Q);else if(Oe(void 0),a==="metrics"){const xe={...s,parameters:{...s.parameters,filters:void 0}},re=[...((J=u.config)==null?void 0:J.metricColumns)||[]];re[n]=xe,t.useEditorStore.getState().actions.updateCardConfig(u.id,{metricColumns:re})}te(null)}}),X&&a==="metrics"&&Te&&e.jsx(t.CalculatedFieldEditor,{open:X,onOpenChange:je,availableFields:E,existingField:Ze,existingFieldScope:ct,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:Q=>{var Ot;if(Q.role!=="metric")return;const{card:J,frame:xe,actions:re}=t.useEditorStore.getState(),Le=((Ot=J.config)==null?void 0:Ot.metricColumns)||[],Re=xe.calculatedFields||[],{nextActiveFields:_e,nextStoredFields:St,nextSharedFields:Rt}=t.saveCalculatedFieldToCardScope({activeFields:Le,storedFields:J.calculatedFields||[],sharedFields:Re,updatedField:Q,editingField:Ze,previousScope:ct});_e&&re.updateCardConfig(u.id,{metricColumns:_e}),re.updateCard(u.id,{calculatedFields:St}),Rt!==Re&&t.commitSharedCalculatedFields({nextSharedFields:Rt,currentSharedFields:Re,isVisualEditing:j,selectedSheetId:f,updateFrame:re.updateFrame,updateSheetCalculatedFields:T})},onSaveToDashboard:Q=>{var rn;if(Q.role!=="metric")return;const{card:J,frame:xe,actions:re}=t.useEditorStore.getState(),Le=s,Re=((rn=J.config)==null?void 0:rn.metricColumns)||[],_e=xe.calculatedFields||[],{nextActiveFields:St,nextStoredFields:Rt,nextSharedFields:Ot}=t.saveCalculatedFieldToSharedScope({activeFields:Re,storedFields:J.calculatedFields||[],sharedFields:_e,updatedField:{...Q,id:Le.id,aliasTemplate:Le.aliasTemplate,valueAliases:Le.valueAliases,parameters:Le.parameters,customFormat:Le.customFormat},editingField:Ze,previousScope:ct});t.commitSharedCalculatedFields({nextSharedFields:Ot,currentSharedFields:_e,isVisualEditing:j,selectedSheetId:f,updateFrame:re.updateFrame,updateSheetCalculatedFields:T}),St&&re.updateCardConfig(u.id,{metricColumns:St}),re.updateCard(u.id,{calculatedFields:Rt})},cardId:u.id})]})}function Bo({concept:s}){const{title:a,description:n}=Vo[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(zo,{highlight:s})]})]})}const Vo={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 zo({highlight:s}){const a=s==="pivotBy",n=s==="groupBy",r=s==="metrics",d="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&&d),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&&d),children:i.label}),i.values.map((c,o)=>e.jsx("td",{className:t.cn("px-1.5 py-1 text-right font-mono tabular-nums text-muted-foreground",r&&d),children:c},o))]},i.label))})]})})}const In=[{label:"Electronics",values:["2,300","1,800","3,400"]},{label:"Clothing",values:["1,300","620","480"]}],_o={groupBy:qt,pivotBy:xs,metrics:Fa,detailColumns:t.Table2,sortBy:t.ArrowUpDown};function Tt({zone:s,fields:a,label:n,placeholder:r,shouldShow:d,hasPivotColumns:i=!1,activeField:l=null}){const{isOver:c,setNodeRef:o}=t.useDroppable({id:s}),{updateSortByColumn:m}=t.useEditorActions(),x=t.useEditorStore(T=>T.card),b=t.useEditorStore(T=>T.card.type),h=a.length>0,u=N.useMemo(()=>!l||!c?!0:t.validateFieldForChartType(l,s,b).isValid,[l,c,s,b]),p=(T,E)=>{var C;!((C=x.config)!=null&&C.sortByColumns)||x.config.sortByColumns.findIndex(k=>k.id===T)===-1||m(x.id,T,{direction:E})};if(s==="sortBy"&&d===!1)return null;const j=s!=="sortBy"&&b!=="kpi",f=_o[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":c&&u,"border border-destructive/40 bg-destructive/5":c&&!u,"border border-dashed border-border/50 bg-background":!c&&!h}),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(f,{className:"h-3 w-3 shrink-0 text-muted-foreground/60"}),e.jsx("span",{children:r}),j&&e.jsx(Bo,{concept:s})]}):e.jsx(t.SortableContext,{id:s,items:a.map(T=>T.id),strategy:t.verticalListSortingStrategy,children:e.jsx("div",{className:"space-y-1",children:a.map((T,E)=>{const C=T.direction;return e.jsx(Po,{field:T,zone:s,index:E,sortDirection:C,onSortDirectionChange:k=>p(T.id,k),hasPivotColumns:i,cardType:b},T.id)})})})})]})}function qo({groupByFields:s,pivotByFields:a,metricsFields:n,sortByFields:r,detailFields:d,activeField:i}){var B,_,U;const[l,c]=N.useState(!1);t.useEditorStore(K=>{var H;return!!((H=K.card.customCardPreferences)!=null&&H.url)});const o=t.useEditorStore(K=>K.card),m=t.useEditorStore(K=>K.frame),x=t.findCustomVisualConfigCard(m,o),{manifest:b}=t.useCustomVisual(((B=x==null?void 0:x.customCardPreferences)==null?void 0:B.url)||""),h=(_=b==null?void 0:b.visuals)==null?void 0:_.find(K=>{var H;return K.name===((H=x==null?void 0:x.customCardPreferences)==null?void 0:H.componentName)}),u=t.resolveMultiInputType(x,h)==="multiple";u&&((U=x==null?void 0:x.customCardPreferences)!=null&&U.url);const p=t.getConfigSlotExpectedType(h==null?void 0:h.slots),j=t.useEditorStore(K=>K.actions.updateCardConfig),f=t.useEditorStore(K=>K.actions.updateCard),T=t.useEditorStore(K=>K.actions.updateFrame),E=t.useDashboardStore(K=>K.isVisualEditing),O=t.useDashboardStore(K=>K.selectedSheetId),C=t.useDashboardStore(K=>K.actions.updateSheetCalculatedFields),{scopedFields:k}=t.useScopedFields(),{userContext:w}=t.useCurrentUserInfo(),D=u&&(x==null?void 0:x.id)===o.id&&p?p:o==null?void 0:o.type,y=D==="detailTable",A=s.length>0||n.length>0||d.length>0,g=!y&&(D!=="kpi"||n.length<=2),R=!y,M=!y&&D!=="kpi",S=D!=="kpi"&&A,F=y,v="Drop sort fields here",L=(w==null?void 0:w.type)==="organization",I=["pie","doughnut","polar","funnel","aggregateTable","bubble","scatter"].includes(D),P=M&&!I,V=()=>D==="kpi"?{label:"Trend By",placeholder:"Drop trend field here"}:{label:"Rows",placeholder:"Drop dimensions here"},z=()=>D==="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"}),A&&e.jsx("button",{type:"button","aria-label":"Reset all field selections",onClick:()=>{j(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:[g&&e.jsx(Tt,{zone:"groupBy",fields:s,label:V().label,placeholder:V().placeholder,activeField:i}),P&&e.jsx(Tt,{zone:"pivotBy",fields:a,label:"Pivot Columns",placeholder:"Drop pivot fields here",activeField:i}),R&&e.jsx(Tt,{zone:"metrics",fields:n,label:z().label,placeholder:z().placeholder,hasPivotColumns:a.length>0,activeField:i}),F&&e.jsx(Tt,{zone:"detailColumns",fields:d,label:"Columns",placeholder:"Drop columns here"}),n.length>=1&&L&&e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:()=>c(!0),className:"mt-1.5 w-full justify-start border-border/60 border-dashed bg-background text-xs text-foreground/70 hover:bg-muted/40 hover:text-foreground",children:[e.jsx(t.Calculator,{className:"mr-2 h-4 w-4"}),"Create Metric"]}),S&&e.jsx(Tt,{zone:"sortBy",fields:r,label:"Sort By",placeholder:v,activeField:i})]}),e.jsx(t.CalculatedFieldEditor,{open:l,onOpenChange:c,availableFields:k,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:K=>{if(K.role!=="metric")return;const{nextStoredFields:H}=t.saveCalculatedFieldToCardScope({activeFields:n,storedFields:o.calculatedFields||[],sharedFields:m.calculatedFields||[],updatedField:K,previousScope:"card"});f(o.id,{calculatedFields:H})},onSaveToDashboard:K=>{if(K.role!=="metric")return;const H=m.calculatedFields||[],{nextSharedFields:Z}=t.saveCalculatedFieldToSharedScope({activeFields:n,storedFields:o.calculatedFields||[],sharedFields:H,updatedField:K,previousScope:"dashboard"});t.commitSharedCalculatedFields({nextSharedFields:Z,currentSharedFields:H,isVisualEditing:E,selectedSheetId:O,updateFrame:T,updateSheetCalculatedFields:C})},cardId:o.id})]})}function $o(){var p,j,f;const[s,a]=N.useState(!1),[n,r]=N.useState(!1),d=t.useEditorStore(T=>{var E;return!!((E=T.card.customCardPreferences)!=null&&E.url)}),i=t.useEditorStore(T=>T.card),l=t.useEditorStore(T=>T.frame),c=t.findCustomVisualConfigCard(l,i),{manifest:o}=t.useCustomVisual(((p=c==null?void 0:c.customCardPreferences)==null?void 0:p.url)||""),m=(j=o==null?void 0:o.visuals)==null?void 0:j.find(T=>{var E;return T.name===((E=c==null?void 0:c.customCardPreferences)==null?void 0:E.componentName)}),b=t.resolveMultiInputType(c,m)==="multiple"&&!!((f=c==null?void 0:c.customCardPreferences)!=null&&f.url),h=!d||b,u=d||b;return!h&&!u?null:e.jsxs("div",{className:"shrink-0 border-t border-border bg-background",children:[h&&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(Jn,{mode:"config"})})}),h&&e.jsxs("button",{type:"button",onClick:()=>a(T=>!T),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(Un,{})}),u&&e.jsxs("button",{type:"button",onClick:()=>r(T=>!T),className:t.cn("flex w-full items-center justify-between px-4 py-2.5 text-left transition-colors hover:bg-muted/50",h&&"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 Ko({onEditJoins:s}){const a=t.useEditorStore(c=>c.card),{autoJoinMetadata:n}=t.useEditorCardQuery(a);if(!(n!=null&&n.autoResolved))return null;const{resolvedJoinPlan:r}=n,d=(r==null?void 0:r.joins)||[];if(d.length===0)return null;const i=c=>!c||c.length===0?"No conditions":c.map(o=>{var h,u,p,j;const m=`${(h=o.source)==null?void 0:h.entityName}.${(u=o.source)==null?void 0:u.name}`,x=`${(p=o.target)==null?void 0:p.entityName}.${(j=o.target)==null?void 0:j.name}`,b=o.operator||"=";return`${m} ${b} ${x}`}).join(" AND "),l=c=>!c.joinKeyGroups||c.joinKeyGroups.length===0?"No conditions defined":c.joinKeyGroups.length===1?i(c.joinKeyGroups[0].keys):c.joinKeyGroups.map((o,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(za,{className:"size-4 text-blue-600/90 dark:text-blue-400"}),e.jsx("h3",{className:"text-xs font-semibold tracking-wide text-blue-900/90 dark:text-blue-100",children:"Resolved Joins"}),e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.Badge,{variant:"secondary",className:"cursor-help bg-blue-100/80 text-xs text-blue-700 dark:bg-blue-900/70 dark:text-blue-300",children:d.length})}),e.jsx(t.TooltipContent,{side:"bottom",align:"start",className:"max-w-md p-3",children:e.jsx("div",{className:"space-y-2",children:d.map((c,o)=>{const m=l(c),x=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:c.source.name}),e.jsx(t.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:c.target.name})]}),e.jsx(t.Badge,{variant:"outline",className:"border-green-500/40 bg-green-50/30 text-xs text-green-700 dark:bg-green-950/30 dark:text-green-300",children:c.joinType})]}),e.jsx("div",{className:"mt-1 space-y-1",children:x?m.map(b=>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:b.condition}),b.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",b.operator,")"]})]},b.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})})})]},c.id||o)})})})]})})]}),s&&e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:s,className:"h-7 gap-1 p-2 text-xs text-blue-700/80 hover:text-blue-900 dark:text-blue-300 dark:hover:text-blue-100",children:e.jsx(t.SquarePen,{className:"size-3.5"})})]})})}function Go({selectedChart:s,onChartChange:a,isVisible:n=!0,onToggleVisibility:r,groupByFields:d,pivotByFields:i,metricsFields:l,sortByFields:c,detailFields:o,activeField:m}){var D,y;const[x,b]=N.useState(!1),h=t.useEditorStore(A=>A.card),u=t.useEditorStore(A=>A.editorContext),p=t.useEditorStore(A=>A.actions.updateCardConfig),j=(u==null?void 0:u.type)==="documentSection",{autoJoinMetadata:f}=t.useEditorCardQuery(h),T=((D=h==null?void 0:h.config)==null?void 0:D.joinPlan)||(f!=null&&f.autoResolved?f.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),E=((y=h==null?void 0:h.dataSource)==null?void 0:y.selectedEntities)||[],O=A=>{p(h.id,{...h==null?void 0:h.config,joinPlan:A}),b(!1)},C=()=>{p(h.id,{...h==null?void 0:h.config,joinPlan:void 0}),b(!1)},k=()=>{b(!1)},w=()=>{b(!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:[!j&&e.jsxs("div",{className:"flex items-start",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(Sr,{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(Ko,{onEditJoins:w})}),e.jsx(qo,{groupByFields:d,pivotByFields:i,metricsFields:l,sortByFields:c,detailFields:o,activeField:m})]}),e.jsx($o,{}),e.jsx(Fn,{open:x,onOpenChange:b,joinPlan:T,availableDataSources:E,onSave:O,onCancel:k,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 Uo({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:d,isLoading:i}=t.useFilterableFields(),l=a||d||[],c={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},o=C=>{const k=w=>{if(w.id===C){const D=l[0]||c,y=t.getDataType(D.dataType)==="date";return{...w,conditions:[...w.conditions,{id:`condition-${Date.now()}`,field:D,operator:y?"between":"=",value:y?[]:""}]}}return{...w,groups:w.groups.map(k)}};r(k(n))},m=C=>{const k=w=>{if(w.id===C){const D=l[0]||c,y=t.getDataType(D.dataType)==="date";return{...w,groups:[...w.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:D,operator:y?"between":"=",value:y?[]:""}],groups:[]}]}}return{...w,groups:w.groups.map(k)}};r(k(n))},x=(C,k)=>{const w=D=>D.id===C?{...D,conditions:D.conditions.filter(y=>y.id!==k)}:{...D,groups:D.groups.map(w)};r(w(n))},b=(C,k)=>{const w=D=>D.id===C?{...D,groups:D.groups.filter(y=>y.id!==k)}:{...D,groups:D.groups.map(w)};r(w(n))},h=(C,k,w,D)=>{if(w==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const y=A=>A.id===C?{...A,conditions:A.conditions.map(g=>g.id===k?{...g,[w]:D}:g)}:{...A,groups:A.groups.map(y)};r(y(n))},u=(C,k,w)=>{const D=y=>y.id===C?{...y,conditions:y.conditions.map(A=>A.id===k?{...A,...w}:A)}:{...y,groups:y.groups.map(D)};r(D(n))},p=(C,k)=>{const w=D=>D.id===C?{...D,logicalOperator:k}:{...D,groups:D.groups.map(w)};r(w(n))},j=(C,k)=>{const w=D=>D.id===C?{...D,negate:k}:{...D,groups:D.groups.map(w)};r(w(n))},f=(C,k,w)=>{const D=y=>y.id===C?{...y,conditions:t.arrayMove(y.conditions,k,w)}:{...y,groups:y.groups.map(D)};r(D(n))},T=(C,k,w)=>{const D=y=>y.id===C?{...y,groups:t.arrayMove(y.groups,k,w)}:{...y,groups:y.groups.map(D)};r(D(n))},E=C=>{if(!C||C.conditions.length===0&&C.groups.length===0)return"-- No filters defined";const k=D=>{let y="";typeof D.field=="object"?y=D.field.entityName?`${D.field.entityName}.${D.field.name}`:D.field.name:y=String(D.field);const A=D.operator;let g=D.value;if(D.field.dataType==="string"&&!["in","not in"].includes(D.operator))typeof g=="string"?g=`'${g}'`:Array.isArray(g)&&(g=`'${g.join(", ")}'`);else if(D.field.dataType==="date"||D.field.dataType==="datetime"||D.field.dataType==="timestamp")if(D.operator==="between"&&Array.isArray(g)&&g.length===2){const R=g[0]?`'${g[0]}'`:"NULL",M=g[1]?`'${g[1]}'`:"NULL";return`${y} BETWEEN ${R} AND ${M}`}else if((D.operator==="in"||D.operator==="not in")&&Array.isArray(g)){const R=g.map(M=>M?`'${M}'`:"NULL").join(", ");return`${y} ${A} (${R})`}else typeof g=="string"||g instanceof Date?g=`'${g}'`:Array.isArray(g)&&g.length>0&&(g=`'${g[0]}'`);else if(["in","not in"].includes(D.operator)){let R=[];Array.isArray(g)?R=g.map(M=>typeof M=="string"?`'${M}'`:String(M)):typeof g=="string"?R=g.split(",").map(M=>{const S=M.trim();return D.field.dataType==="string"?`'${S}'`:S}):typeof g=="number"&&(R=[String(g)]),g=`(${R.join(", ")})`}switch(A){case"contains":return typeof g=="string"?`${y} LIKE '%${g.replace(/'/g,"")}'`:`${y} LIKE '%${String(g)}'`;case"startsWith":return typeof g=="string"?`${y} LIKE '${g.replace(/'/g,"")}%'`:`${y} LIKE '${String(g)}%'`;case"endsWith":return typeof g=="string"?`${y} LIKE '%${g.replace(/'/g,"")}'`:`${y} LIKE '%${String(g)}'`;case"isNull":return`${y} IS NULL`;case"isNotNull":return`${y} IS NOT NULL`;default:return`${y} ${A} ${g}`}},w=D=>{const y=D.conditions.map(k),A=D.groups.map(S=>w(S)),g=[...y,...A].filter(Boolean);if(g.length===0)return"";const R=g.join(` ${D.logicalOperator} `),M=g.length>1?`(${R})`:R;return D.negate?`NOT ${M}`:M};return w(C)},O=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:l,isLoading:i,addCondition:o,addGroup:m,removeCondition:x,removeGroup:b,updateCondition:h,updateConditionFields:u,updateGroupOperator:p,updateGroupNegate:j,reorderConditions:f,reorderGroups:T,generateSQLPreview:E,hasAnyFilters:O}}function Ho({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 Qo=s=>{if(s.qualifiedEntityName){const a=s.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function Wo({value:s,onValueChange:a,availableFields:n,placeholder:r="Select field",className:d="w-64"}){const[i,l]=N.useState(!1),c=N.useMemo(()=>{const o={};return n.forEach(m=>{const x=Qo(m);o[x]||(o[x]={}),o[x][m.entityId]||(o[x][m.entityId]=[]),o[x][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",d),children:[s?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Ho,{children:[s.entityName,".",s.name]})}):r,e.jsx(t.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(t.CommandEmpty,{children:"No fields found."}),e.jsx(t.CommandList,{className:"max-h-80",children:Object.entries(c).map(([o,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(([x,b])=>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(b[0].entityType,{size:"h-3 w-3"}),e.jsx("span",{children:b[0].entityName})]}),b.map((h,u)=>e.jsxs(t.CommandItem,{value:h.id,onSelect:()=>{a(h),l(!1)},className:"overflow-x-auto",children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",(s==null?void 0:s.id)===h.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:h.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:h.description&&e.jsx("span",{children:h.description})})]})]},h.id+u))]},`${o}-${x}`))},o))})]})})]})}function vs(s){var j;const a=t.useEditorStore(f=>f.card),{authToken:n,tokenProps:r}=t.useSemaphorContext(),d=t.useEditorStore(f=>f.card.config),i=d==null?void 0:d.joinPlan,l={...s,alias:s.name,label:"value",role:"groupby"},c={...s,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},o={...l,role:"sortby",direction:"asc"},m={joinPlan:i,groupByColumns:[l],metricColumns:[c],sortByColumns:[o]},x=((j=a.dataSource)==null?void 0:j.connectionId)||a.connectionId,{data:b,isPending:h,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:x,cardConfig:m,cardDataSource:a.dataSource})}catch(f){console.log(s),console.error("error",f)}},enabled:!!x,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((b==null?void 0:b.records)||[]).map(f=>({label:f.value||"BLANK",value:f.value||"BLANK",count:(f==null?void 0:f.count)||0})),isPending:h,error:u}}function Jo({field:s,selected:a,onChange:n,placeholder:r="Select items...",className:d}){const[i,l]=Vt.useState(!1),{filterValues:c}=vs(s),o=x=>{n(a.filter(b=>b!==x))},m=x=>{a.includes(x)?n(a.filter(b=>b!==x)):n([...a,x])};return e.jsx("div",{className:t.cn("w-full",d),children:e.jsxs(t.Popover,{open:i,onOpenChange:l,modal:!0,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(x=>{const b=c.find(h=>h.value===x);return e.jsxs(t.Badge,{variant:"secondary",className:"text-xs",children:[b==null?void 0:b.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:h=>{h.key==="Enter"&&o(x)},onMouseDown:h=>{h.preventDefault(),h.stopPropagation()},onClick:h=>{h.stopPropagation(),o(x)},children:e.jsx(t.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},x)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(t.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No results found."}),e.jsx(t.CommandGroup,{children:c.map((x,b)=>e.jsxs(t.CommandItem,{onSelect:()=>m(x.value),children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",a.includes(x.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:x.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:x.count})]})]},x.value+b))})]})]})})]})})}function Yo({field:s,value:a,onChange:n,placeholder:r="Select value...",className:d}){const{filterValues:i,isPending:l,error:c}=vs(s);return l?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(t.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):c?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(t.Select,{value:a,onValueChange:n,children:[e.jsx(t.SelectTrigger,{className:d||"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 Xo({value:s,operator:a,onChange:n,className:r}){var u,p,j;const{tokenProps:d}=t.useSemaphorContext(),i=((p=(u=d==null?void 0:d.params)==null?void 0:u.calendarContext)==null?void 0:p.tz)||((j=d==null?void 0:d.params)==null?void 0:j.timezone),l=i||Intl.DateTimeFormat().resolvedOptions().timeZone,c=a==="between"||a==="not between",o=N.useMemo(()=>{if(!(!s||!c)&&Array.isArray(s)&&s.length===2){const f=s[0]?new Date(s[0]):void 0,T=s[1]?new Date(s[1]):void 0;if(f&&T)return{from:f,to:T}}},[s,c]),m=N.useMemo(()=>{if(!s||c)return;const f=Array.isArray(s)?s[0]:s;if(!f)return;const T=new Date(f);if(!isNaN(T.getTime()))return T},[s,c]),x=f=>a==="<="||a===">"?t.endOfDayInTimezone(f,l):t.startOfDayInTimezone(f,l),b=f=>{if(!f){n([]);return}if(f.from&&f.to){n([f.from.toISOString(),f.to.toISOString()]);return}n([])},h=f=>{if(!f){n("");return}const T=x(f);n(T.toISOString())};return e.jsx(t.DateRangePicker,{value:c?o:void 0,selectionMode:c?"range":"single",singleValue:c?void 0:m,onChange:b,onSingleChange:h,timezone:i,showRelativeTab:c,className:r,placeholder:"Select date..."})}const Zo=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],ei=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],ti=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],si=["=","!=","isNull","isNotNull"],ni=["between","=","!=","<","<=",">",">=","isNull","isNotNull"],ai={"=":"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 ai[s]||t.titleCase(s)}function ri(s){switch(s){case"string":return ei;case"number":return ti;case"boolean":return si;case"date":return ni;default:return Zo}}function Xn({condition:s,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:d,onRemoveCondition:i,onUpdateGroupOperator:l,availableFields:c,updateConditionFields:o}){const{attributes:m,listeners:x,setNodeRef:b,transform:h,transition:u,isDragging:p}=t.useSortable({id:s.id}),{isPending:j,error:f}=vs(s.field),T={transform:t.CSS.Transform.toString(h),transition:u};return e.jsxs("div",{ref:b,style:T,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${p?"z-50 opacity-50":""}`,children:[e.jsx("div",{...m,...x,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:E=>l(n,E),children:[e.jsx(t.SelectTrigger,{className:"w-24",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(Wo,{value:s.field,onValueChange:E=>{const O=E,C=t.getDataType(O.dataType)==="date";o(n,s.id,{field:O,value:"",operator:C?"between":"="})},availableFields:c,placeholder:"Select field",className:"w-64"}),e.jsxs(t.Select,{value:s.operator,onValueChange:E=>{E==="in"||E==="not in"?o(n,s.id,{operator:E,value:[]}):E==="isNull"||E==="isNotNull"?o(n,s.id,{operator:E,value:null}):E==="between"||E==="not between"?o(n,s.id,{operator:E,value:[]}):o(n,s.id,{operator:E,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:ri(t.getDataType(s.field.dataType)).map(E=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:E,children:kn(E)},E))})]}),s.operator==="isNull"||s.operator==="isNotNull"?e.jsx("div",{className:"flex-1"}):t.getDataType(s.field.dataType)==="string"?s.operator==="in"||s.operator==="not in"?j?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..."]}):f?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(E=>typeof E=="string")?s.value:[],onChange:E=>o(n,s.id,{value:E}),placeholder:`Select values for ${s.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(s.operator)?e.jsx(t.Input,{value:typeof s.value=="string"?s.value:"",onChange:E=>o(n,s.id,{value:E.target.value}),className:"flex-1",placeholder:s.operator.charAt(0).toUpperCase()+s.operator.slice(1)+"..."}):e.jsx(Yo,{field:s.field,value:typeof s.value=="string"?s.value:"",onChange:E=>o(n,s.id,{value:E}),placeholder:"Select value...",className:"flex-1"}):t.getDataType(s.field.dataType)==="boolean"?e.jsxs(t.Select,{value:typeof s.value=="boolean"?String(s.value):"",onValueChange:E=>o(n,s.id,{value:E==="true"}),children:[e.jsx(t.SelectTrigger,{className:"flex-1",children:e.jsx(t.SelectValue,{placeholder:"Select value..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"true",children:"True"}),e.jsx(t.SelectItem,{value:"false",children:"False"})]})]}):t.getDataType(s.field.dataType)==="date"?e.jsx(Xo,{value:s.value,operator:s.operator,onChange:E=>o(n,s.id,{value:E}),className:"flex-1"}):e.jsx(t.Input,{value:typeof s.value=="string"||typeof s.value=="number"?s.value:"",onChange:E=>d(n,s.id,"value",E.target.value),className:"flex-1",placeholder:s.operator==="in"||s.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>i(n,s.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]})}function li({group:s,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:d,onRemoveGroup:i,onUpdateCondition:l,onUpdateField:c,onRemoveCondition:o,onReorderConditions:m,onReorderGroups:x,onAddCondition:b,onAddGroup:h,availableFields:u,renderFilterGroup:p,updateConditionFields:j}){const{attributes:f,listeners:T,setNodeRef:E,transform:O,transition:C,isDragging:k}=t.useSortable({id:s.id}),w={transform:t.CSS.Transform.toString(O),transition:C},D=A=>{const{active:g,over:R}=A;if(R&&g.id!==R.id){const M=s.conditions.findIndex(F=>F.id===g.id),S=s.conditions.findIndex(F=>F.id===R.id);M!==-1&&S!==-1&&m(s.id,M,S)}},y=A=>{const{active:g,over:R}=A;if(R&&g.id!==R.id&&n){const M=s.groups.findIndex(F=>F.id===g.id),S=s.groups.findIndex(F=>F.id===R.id);M!==-1&&S!==-1&&x(n,M,S)}};return e.jsxs("div",{ref:E,style:w,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${k?"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",{...f,...T,className:"cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(t.Button,{variant:s.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>d(s.id,!s.negate),children:"NOT"}),e.jsxs(t.Select,{value:s.logicalOperator,onValueChange:A=>r(s.id,A),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:D,children:e.jsx(t.SortableContext,{items:s.conditions.map(A=>A.id),strategy:t.verticalListSortingStrategy,children:s.conditions.map((A,g)=>e.jsx(Xn,{condition:A,index:g,groupId:s.id,groupLogicalOperator:s.logicalOperator,onUpdateCondition:l,onUpdateField:c,onRemoveCondition:o,onUpdateGroupOperator:r,availableFields:u,updateConditionFields:j},A.id))})}),e.jsx(t.DndContext,{sensors:t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),collisionDetection:t.closestCenter,onDragEnd:y,children:e.jsx(t.SortableContext,{items:s.groups.map(A=>A.id),strategy:t.verticalListSortingStrategy,children:s.groups.map(A=>p(A,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:()=>b(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>h(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function oi({filters:s,availableFields:a,onSave:n,onClearAll:r,onCancel:d}){const{currentFilters:i,availableFields:l,isLoading:c,addCondition:o,addGroup:m,removeCondition:x,removeGroup:b,updateCondition:h,updateConditionFields:u,updateGroupOperator:p,updateGroupNegate:j,reorderConditions:f,reorderGroups:T,generateSQLPreview:E,hasAnyFilters:O,setCurrentFilters:C}=Uo({initialFilters:s,availableFields:a}),k=t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),[w,D]=N.useState(!1),y=(R,M,S)=>{const F=v=>v.id===R?{...v,conditions:v.conditions.map(L=>L.id===M?{...L,field:S,dataType:S.dataType}:L)}:{...v,groups:v.groups.map(F)};C(F(i))},A=(R,M=0,S)=>M===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(t.DndContext,{sensors:k,collisionDetection:t.closestCenter,onDragEnd:F=>{const{active:v,over:L}=F;if(L&&v.id!==L.id){const I=R.conditions.findIndex(V=>V.id===v.id),P=R.conditions.findIndex(V=>V.id===L.id);I!==-1&&P!==-1&&f(R.id,I,P)}},children:e.jsx(t.SortableContext,{items:R.conditions.map(F=>F.id),strategy:t.verticalListSortingStrategy,children:R.conditions.map((F,v)=>e.jsx(Xn,{condition:F,index:v,groupId:R.id,groupLogicalOperator:R.logicalOperator,onUpdateCondition:h,onUpdateField:y,onRemoveCondition:x,onUpdateGroupOperator:p,availableFields:l,updateConditionFields:u},F.id))})}),e.jsx(t.DndContext,{sensors:k,collisionDetection:t.closestCenter,onDragEnd:F=>{const{active:v,over:L}=F;if(L&&v.id!==L.id){const I=R.groups.findIndex(V=>V.id===v.id),P=R.groups.findIndex(V=>V.id===L.id);I!==-1&&P!==-1&&T(R.id,I,P)}},children:e.jsx(t.SortableContext,{items:R.groups.map(F=>F.id),strategy:t.verticalListSortingStrategy,children:R.groups.map(F=>A(F,M+1,R.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(t.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>o(R.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),w&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>m(R.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},R.id):e.jsx(li,{group:R,depth:M,parentGroupId:S,onUpdateGroupOperator:p,onUpdateGroupNegate:j,onRemoveGroup:b,onUpdateCondition:h,onUpdateField:y,onRemoveCondition:x,onReorderConditions:f,onReorderGroups:T,onAddCondition:o,onAddGroup:m,availableFields:l,renderFilterGroup:A,updateConditionFields:u},R.id),g=t.getFilterCount(s);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(t.Card,{children:e.jsx(t.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[c?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):A(i),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Switch,{size:"sm",id:"advanced-mode",checked:w,onCheckedChange:R=>D(R)}),e.jsx(t.Label,{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),O&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:E(i)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(t.Button,{size:"sm",variant:"outline",onClick:d,children:"Cancel"}),g>0&&e.jsx(t.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(t.Button,{size:"sm",onClick:()=>n(O?i:null),children:"Apply Filters"})]})]})}function ii({cardId:s,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:d,isOpen:i,onOpenChange:l}){const c=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(oi,{filters:a,availableFields:d,onSave:c,onCancel:()=>l(!1),onClearAll:o})]})]})}function ci({activeCardId:s,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var E,O;const[d,i]=N.useState(null),l=t.useEditorStore(C=>C.card),c=t.useEditorStore(C=>C.actions.updateCardConfig),o=t.useEditorStore(C=>C.actions.setCardPreferences),m=(E=l==null?void 0:l.config)==null?void 0:E.joinPlan,x=N.useCallback(C=>C.entityName===t.CALCULATED_FIELD_ENTITY_MARKER||C.entityName==="calculated_fields"||C.qualifiedEntityName==="calculated_fields",[]),b=(O=l==null?void 0:l.dataSource)==null?void 0:O.semanticDomainId,{data:h}=t.useJoinabilityMap(b),u=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy"),...n("detailColumns")],p=N.useCallback(C=>C.startsWith("card-source-")?"source":C.startsWith("card-")?null:C.startsWith("source-")||a.find(k=>k.id===C)?"source":n("groupBy").find(k=>k.id===C)?"groupBy":n("metrics").find(k=>k.id===C)?"metrics":n("pivotBy").find(k=>k.id===C)?"pivotBy":n("sortBy").find(k=>k.id===C)?"sortBy":n("detailColumns").find(k=>k.id===C)?"detailColumns":null,[a,n]),j=N.useCallback(C=>{i(C.active.id)},[]),f=N.useCallback(C=>{var R;const{active:k,over:w}=C;if(!w||!s){i(null);return}const D=k.id,y=w.id,A=p(D),g=p(y)||y;if(g==="sortBy"){if(A==="source"){const M=a.find(F=>F.id===D);if(!M){i(null);return}if(!(n("groupBy").some(F=>F.name===M.name&&F.qualifiedEntityName===M.qualifiedEntityName)||n("metrics").some(F=>F.name===M.name&&F.qualifiedEntityName===M.qualifiedEntityName)||n("detailColumns").some(F=>F.name===M.name&&F.qualifiedEntityName===M.qualifiedEntityName))){i(null);return}}else if(A==="pivotBy"){i(null);return}else if(A!=="groupBy"&&A!=="metrics"&&A!=="sortBy"&&A!=="detailColumns"){i(null);return}}if(A==="source"&&g==="sortBy"){const M=[...a].find(L=>L.id===D);if(!M){i(null);return}const S=n("sortBy");if(t.fieldAlreadyExists(M,S)){i(null);return}const F=t.validateFieldForChartType(M,"sortBy",l.type);if(!F.isValid){t.ue.error("Invalid Field Type",{description:F.reason,position:"top-center",duration:3e3}),i(null);return}const v=t.getNewField(M,"sortBy",S);i(null),r("sortBy",[...S,v]);return}if(A==="source"&&g!=="source"&&g!=="sortBy"){const M=[...a].find(V=>V.id===D);if(!M){i(null);return}const S=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy"),...n("detailColumns")],F=S.filter(V=>!x(V));if(F.length>0){const V=F[0].qualifiedEntityName;if(!V){i(null);return}if(V!==M.qualifiedEntityName&&!x(M)&&M.qualifiedEntityName)if(b&&(h!=null&&h.joinabilityMap)){if(t.calculateFieldState(M,{joinabilityMap:h.joinabilityMap,selectedFields:S,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(V,M.qualifiedEntityName,m)){t.showJoinRequiredNotification(),i(null);return}}}const v=n(g);if(t.fieldAlreadyExists(M,v)){i(null);return}const L=t.validateFieldForChartType(M,g,l.type);if(!L.isValid){t.ue.error("Invalid Field Type",{description:L.reason,position:"top-center",duration:3e3}),i(null);return}const I=t.getNewField(M,g,v),P=[...v,I];if(i(null),r(g,P),g==="metrics"&&s){const V=t.seedSemanticMetricFormatDefaults(l,I,l.preferences);V&&o(V),t.cleanupKpiMetricComparisonMode(l.type,l.config,c,s,P)}return}if(A&&g&&A!=="source"&&g!=="source"&&A!==g){const M=n(A),S=n(g),F=M.find(V=>V.id===D);if(!F){i(null);return}const v=t.validateFieldForChartType(F,g,l.type);if(!v.isValid){t.ue.error("Invalid Field Type",{description:v.reason,position:"top-center",duration:3e3}),i(null);return}const L=t.getNewField(F,g,S);if(i(null),g==="sortBy"){t.fieldAlreadyExists(F,S)||r(g,[...S,L]);return}const I=M.filter(V=>V.id!==D),P=[...S,L];if(r(A,I),r(g,P),g==="metrics"&&s){const V=t.seedSemanticMetricFormatDefaults(l,L,l.preferences);V&&o(V),t.cleanupKpiMetricComparisonMode(l.type,l.config,c,s,P)}return}if(A&&g&&A===g&&A!=="source"){const M=n(A),S=M.findIndex(v=>v.id===D),F=M.findIndex(v=>v.id===y);if(S!==F){const v=t.arrayMove(M,S,F);r(A,v)}}i(null)},[s,a,n,r,p,m,b,h,x,l,c,o]),T=d?u.find(C=>C.id===d):null;return{activeId:d,activeField:T,handleDragStart:j,handleDragEnd:f}}function di({activeView:s,onViewChange:a,splitViewEnabled:n}){const r=t.useEditorStore(o=>o.card),{config:d}=N.useContext(t.SemaphorContext).tokenProps,i=(d==null?void 0:d.showInfoTab)!==!1,l=()=>n?!1:t.getVisualizationMode(r)==="dynamic"?!0:!["table","pivotTable","aggregateTable","detailTable"].includes(r.type),c=[{id:"chart",label:"Chart"}];return l()&&c.push({id:"table",label:"Results"}),r.type!=="kpi"&&i&&c.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:c.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 ui=[{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 mi(){var o,m;const s=t.useEditorStore(x=>x.card),{updateRowLimit:a}=t.useEditorActions(),[n,r]=N.useState(!1),[d,i]=N.useState(""),l=x=>{if(x==="custom"){r(!0);return}r(!1),a(s.id,parseInt(x))},c=x=>{const b=x.target.value;i(b),b&&!isNaN(parseInt(b))&&a(s.id,parseInt(b))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(t.Input,{type:"number",value:d,onChange:c,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(t.Select,{value:((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:ui.map(x=>e.jsx(t.SelectItem,{value:x.value,children:x.label},x.value))})]})})}function xi({card:s,queryData:a,isLoading:n,isFetching:r,pagination:d,onPaginationChange:i,onSortChange:l,sortState:c,splitViewEnabled:o,isDynamicInspectorOpen:m,onDynamicInspectorOpenChange:x}){const b=N.useMemo(()=>(a==null?void 0:a.records)||[],[a==null?void 0:a.records]),h=t.getVisualizationMode(s)==="dynamic",u=e.jsx(ot,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx($n,{fallbackPreview:e.jsx(ot,{}),records:b,title:s.title,isInspectorOpen:m,onInspectorOpenChange:x})});return h?o?e.jsxs(t.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(t.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children: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:b,paginationMetadata:d,onPaginationChange:i,isLoading:n||r,onSortChange:l,sortState:c})]})})]}):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:b,paginationMetadata:d,onPaginationChange:i,isLoading:n||r,onSortChange:l,sortState:c})]})})]})}function hi(s,a){const[n,r]=N.useState(()=>{const d=localStorage.getItem(s);return d?JSON.parse(d):a});return N.useEffect(()=>{localStorage.setItem(s,JSON.stringify(n))},[n,s]),[n,r]}const pi="semaphor-split-view-enabled";function fi(){return hi(pi,!0)}function gi({activeView:s,onViewChange:a,onFiltersClick:n,activeCard:r,columns:d}){var X,je,ke;const i=t.useEditorStore(te=>te.card),l=t.useEditorStore(te=>te.editorContext),c=t.useEditorStore(te=>te.inlineFilterValuesMap[(r==null?void 0:r.id)||""]),o=t.useEditorStore(te=>te.actions.removeCardInlineFilterValue),m=t.useDashboardStore(te=>te.filterValues),x=t.useDashboardStore(te=>te.selectedSheetId),{updateCardConfig:b,setCard:h,updateCardInFrame:u,setShowAIDialog:p}=t.useEditorActions(),j=t.useEditorStore(te=>te.showAIDialog),f=t.useEditorStore(te=>te.isDevMode),T=t.useDashboardStore(te=>te.isVisualEditing),[E,O]=N.useState(!1),[C,k]=N.useState(!1),[w,D]=N.useState(!1),[y,A]=N.useState(null),{config:g}=N.useContext(t.SemaphorContext).tokenProps,R=(g==null?void 0:g.showInfoTab)!==!1,M=(g==null?void 0:g.showQueryDebugTools)!==!1,[S,F]=fi();t.useEditorStore(te=>{var De;return!!((De=te.card.customCardPreferences)!=null&&De.url)});const L=t.getVisualizationMode(i)==="dynamic",I=(l==null?void 0:l.type)==="documentSection",{data:P,errorMessage:V,isLoading:z,isFetching:B,errorSql:_,pagination:U,refetch:K,comparisonMetadata:H,queryRequestPayload:Z,resolvedPrimaryDateField:de}=t.useEditorCardQuery(r),ae=N.useMemo(()=>(P==null?void 0:P.records)||[],[P==null?void 0:P.records]),[ce,me]=N.useState(!1);N.useEffect(()=>{B||me(!1)},[B]);const he=()=>{const te=!S;te&&s==="table"&&a("chart"),F(te)},Ne=(te,De)=>{const Me={...r,paginationConfig:{page:te+1,pageSize:De}};h(Me),u(Me)},we=te=>{if(!i.config)return;const De=t.sortStateToSortByColumns(te,i.config.metricColumns,i.config.groupByColumns,i.config.detailColumns);b(i.id,{...i.config,sortByColumns:De})},Ie=N.useMemo(()=>{var te;return t.sortByColumnsToSortState((te=i.config)==null?void 0:te.sortByColumns)},[(X=i.config)==null?void 0:X.sortByColumns]);return e.jsx("div",{className:t.cn("relative flex w-0 grow flex-col",{"border-l":j&&T}),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"&&j&&!I&&!L&&e.jsx("div",{className:"w-[200px]",children:e.jsx(Cr,{variant:f?"secondary":"ghost"})}),e.jsxs("div",{className:"flex h-11 items-end gap-5 self-stretch",children:[e.jsx(di,{activeView:s,onViewChange:a,splitViewEnabled:S}),e.jsx(mi,{})]}),H&&i.type!=="table"&&e.jsx(t.ComparisonMetadataBadge,{metadata:H,variant:"compact"}),j&&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:(je=r.config)==null?void 0:je.filters,cardFilterCount:t.getFilterCount(((ke=r.config)==null?void 0:ke.filters)||null),onFiltersClick:n,inlineFilters:r.inlineFilters,inlineFilterValues:c,sheetId:x||"",removeInlineFilterValue:te=>o(r.id,te),resolvedPrimaryDateField:de}),e.jsx(t.IconButton,{tooltip:"Refresh",className:"h-7 w-7 rounded-[5px] p-0",disabled:z||B,onClick:()=>{me(!0),K()},children:e.jsx(t.RefreshCcw,{className:t.cn("h-3.5 w-3.5",{"animate-spin":ce})})}),s==="chart"&&!L&&e.jsx(qn,{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:he,children:[S?e.jsx(Na,{className:"mr-2 h-4 w-4"}):e.jsx(Pa,{className:"mr-2 h-4 w-4"}),S?"Hide Results Table":"Show Results Table"]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs("div",{className:"px-1 py-1",children:[e.jsx(gs,{triggerVariant:"menu",className:"w-full"}),e.jsx(fs,{triggerVariant:"menu",className:"w-full"})]}),e.jsx(Kn,{onCustomize:()=>D(!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-2",{"pb-0":S&&!["table","pivotTable","aggregateTable","detailTable"].includes(r.type)}),children:e.jsx(xi,{card:r,queryData:P,isLoading:z,isFetching:B,pagination:U,onPaginationChange:Ne,onSortChange:we,sortState:Ie,splitViewEnabled:S,isDynamicInspectorOpen:w,onDynamicInspectorOpenChange:D})}),s==="table"&&(P==null?void 0:P.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:[(z||B)&&(P==null?void 0:P.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:ae,comparisonMetadata:H,paginationMetadata:U,onPaginationChange:Ne,isLoading:z||B,onSortChange:we,sortState:Ie})]}),s==="info"&&R&&e.jsx("div",{className:"flex min-h-0 flex-1 flex-col pb-2",children:e.jsx("div",{className:"flex min-h-0 flex-1 flex-col rounded-md bg-background px-4",children:V?e.jsx(hs,{error:V,errorSql:_,onSendFeedback:()=>{const te=t.prepareFeedbackData(t.FeedbackCategory.QUERY_GENERATION,{cardConfig:i.config,dataSource:r.dataSource,dashboardFilters:m,errorMessage:V,errorSql:_,generatedSql:P==null?void 0:P.sql});A(te),k(!0)},onOpenInEditor:()=>{p(!0),setTimeout(()=>{const te=t.useEditorStore.getState().actions;te.setIsDevMode(!0),te.setCardSql(_||""),setTimeout(()=>{te.setRunSql(!0)},100)},100)}}):(P==null?void 0:P.sql)&&e.jsx(Gn,{sql:P.sql,showCardDetails:!0,debugPayloads:M?{queryRequest:Z,queryResponse:P,columns:d,dashboardFilters:m}:void 0})})})]}),y&&e.jsx(t.FeedbackDialog,{open:C,onOpenChange:k,feedbackData:y})]})})}function bi({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 ji=()=>{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 d;if((d=r.reason)!=null&&d.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=s,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function vi({column:s,isSelected:a,onSelect:n,availableFields:r,width:d,onWidthChange:i}){var V,z,B;const l=t.useEditorStore(_=>_.card),{updateCardConfig:c,removeGroupByColumn:o,removeMetricColumn:m,updateFilters:x}=t.useEditorActions(),[b,h]=N.useState(!1),[u,p]=N.useState(!1),j=N.useRef(null),f=N.useCallback(_=>{_.preventDefault(),_.stopPropagation(),p(!0),j.current={startX:_.clientX,startWidth:d||150};const U=H=>{if(!j.current)return;const Z=H.clientX-j.current.startX,de=Math.max(80,j.current.startWidth+Z);i==null||i(s.id,de)},K=()=>{p(!1),j.current=null,document.removeEventListener("mousemove",U),document.removeEventListener("mouseup",K)};document.addEventListener("mousemove",U),document.addEventListener("mouseup",K)},[d,s.id,i]),T=(V=l==null?void 0:l.config)==null?void 0:V.filters,E=(z=T==null?void 0:T.conditions)==null?void 0:z.some(_=>_.field.name===s.name&&_.field.qualifiedEntityName===s.qualifiedEntityName),O=_=>{_?x(l.id,_):c(l.id,{filters:void 0})},{attributes:C,listeners:k,setNodeRef:w,transform:D,transition:y,isDragging:A}=t.useSortable({id:s.id}),g={transform:t.CSS.Transform.toString(D),transition:y},R=t.getDataType(s.dataType),M=yi(R),S=()=>{var K;const _=((K=l==null?void 0:l.config)==null?void 0:K.sortByColumns)||[],U=_.findIndex(H=>H.name===s.name);if(U!==-1){const H=[..._];H[U]={...H[U],direction:"asc"},c(l.id,{sortByColumns:H})}else c(l.id,{sortByColumns:[..._,{...s,id:`sort-${s.id}`,role:"sortby",direction:"asc"}]})},F=()=>{var K;const _=((K=l==null?void 0:l.config)==null?void 0:K.sortByColumns)||[],U=_.findIndex(H=>H.name===s.name);if(U!==-1){const H=[..._];H[U]={...H[U],direction:"desc"},c(l.id,{sortByColumns:H})}else c(l.id,{sortByColumns:[..._,{...s,id:`sort-${s.id}`,role:"sortby",direction:"desc"}]})},v=()=>{var K;const _=((K=l==null?void 0:l.config)==null?void 0:K.groupByColumns)||[];if(!_.some(H=>H.name===s.name)){const H={...s,id:`groupby-${s.id}-${Date.now()}`,role:"groupby"};c(l.id,{groupByColumns:[..._,H]})}},L=_=>{var H;const U=((H=l==null?void 0:l.config)==null?void 0:H.metricColumns)||[];if(!U.some(Z=>Z.name===s.name&&Z.aggregate===_)){const Z={...s,id:`metric-${s.id}-${_}-${Date.now()}`,label:`${_} of ${s.label||s.name}`,role:"metric",aggregate:_};c(l.id,{metricColumns:[...U,Z]})}},I=()=>{s.role==="groupby"?o(l.id,s.id):s.role==="metric"&&m(l.id,s.id)},P={...g,width:d?`${d}px`:void 0,minWidth:d?`${d}px`:"120px"};return e.jsxs("th",{ref:w,style:P,className:t.cn("group relative border-r border-border bg-background px-1 py-0",A&&"opacity-50",a&&"bg-primary/10",u&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...C,...k,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(M,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:s.label||s.name}),s.role==="metric"&&s.aggregate&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",s.aggregate,")"]}),E&&e.jsx(t.Filter,{className:"h-3 w-3 text-primary"})]}),e.jsx(t.ChevronDown,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsxs(t.DropdownMenuContent,{align:"start",className:"w-48",children:[e.jsxs(t.DropdownMenuItem,{onClick:()=>h(!0),children:[e.jsx(t.Filter,{className:t.cn("mr-2 h-4 w-4",E&&"text-primary")}),E?"Edit Filter":"Filter"]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{onClick:S,children:[e.jsx(ja,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(t.DropdownMenuItem,{onClick:F,children:[e.jsx(ba,{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:v,children:[e.jsx(qt,{className:"mr-2 h-4 w-4"}),"Group by this column"]}),e.jsxs(t.DropdownMenuItem,{disabled:!0,children:[e.jsx(xs,{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:I,className:"text-destructive focus:text-destructive",children:[e.jsx(t.Trash2,{className:"mr-2 h-4 w-4"}),"Remove column"]})]})]})]}),e.jsx("div",{onMouseDown:f,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(Yn,{open:b,onOpenChange:h,availableFields:r.length>0?r:[s],existingFilters:T,editingCondition:E?(B=T==null?void 0:T.conditions)==null?void 0:B.find(_=>_.field.name===s.name&&_.field.qualifiedEntityName===s.qualifiedEntityName):void 0,onSave:O})]})}function yi(s){switch(s){case"number":return t.Hash;case"date":return t.Calendar;case"string":default:return t.Type}}function Ni({selectedColumn:s,onColumnSelect:a,isLoading:n=!1,sourceFields:r=[],filterableFields:d=r}){var A,g,R,M;const i=t.useEditorStore(S=>S.card),{updateCardConfig:l}=t.useEditorActions(),[c,o]=N.useState(null),[m,x]=N.useState({}),[b,h]=N.useState(!1),u=N.useMemo(()=>{var v,L;const S=((v=i==null?void 0:i.config)==null?void 0:v.groupByColumns)||[],F=((L=i==null?void 0:i.config)==null?void 0:L.metricColumns)||[];return[...S,...F]},[(A=i==null?void 0:i.config)==null?void 0:A.groupByColumns,(g=i==null?void 0:i.config)==null?void 0:g.metricColumns]),p=N.useMemo(()=>{const S=new Set(u.map(F=>`${F.qualifiedEntityName}.${F.name}`));return r.filter(F=>!S.has(`${F.qualifiedEntityName}.${F.name}`))},[r,u]),{data:j,isLoading:f}=t.useEditorCardQuery(i),T=(j==null?void 0:j.records)||[],E=N.useCallback((S,F)=>{x(v=>({...v,[S]:F}))},[]),O=N.useCallback(S=>{var I,P;const F=t.getDataType(S.dataType),v=((I=i==null?void 0:i.config)==null?void 0:I.groupByColumns)||[],L=((P=i==null?void 0:i.config)==null?void 0:P.metricColumns)||[];if(F==="number"){const V={...S,id:`metric-${S.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};l(i.id,{metricColumns:[...L,V]})}else{const V={...S,id:`groupby-${S.id}-${Date.now()}`,role:"groupby"};l(i.id,{groupByColumns:[...v,V]})}h(!1)},[(R=i==null?void 0:i.config)==null?void 0:R.groupByColumns,(M=i==null?void 0:i.config)==null?void 0:M.metricColumns,i.id,l]),C=t.useSensors(t.useSensor(t.PointerSensor,{activationConstraint:{distance:8}})),k=S=>{o(S.active.id)},w=S=>{const{active:F,over:v}=S;if(o(null),!v||F.id===v.id)return;const L=u.findIndex(P=>P.id===F.id),I=u.findIndex(P=>P.id===v.id);if(L!==-1&&I!==-1){const P=t.arrayMove(u,L,I),V=P.filter(B=>B.role==="groupby"),z=P.filter(B=>B.role==="metric");l(i.id,{groupByColumns:V,metricColumns:z})}},D=c?u.find(S=>S.id===c):null,y=S=>{let F="";for(;S>=0;)F=String.fromCharCode(S%26+65)+F,S=Math.floor(S/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:k,onDragEnd:w,children:[e.jsxs("table",{className:"w-full border-collapse",children:[e.jsxs("thead",{children:[e.jsxs("tr",{className:"border-b border-border bg-muted/30",children:[e.jsx("th",{className:"sticky left-0 z-20 w-12 border-r border-border bg-muted/50 px-2 py-1 text-center text-xs font-medium text-muted-foreground"}),e.jsx(t.SortableContext,{items:u.map(S=>S.id),strategy:t.horizontalListSortingStrategy,children:u.map((S,F)=>e.jsx("th",{style:{width:m[S.id]?`${m[S.id]}px`:void 0,minWidth:m[S.id]?`${m[S.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:y(F)},`letter-${S.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(S=>S.id),strategy:t.horizontalListSortingStrategy,children:u.map(S=>e.jsx(vi,{column:S,isSelected:(s==null?void 0:s.id)===S.id,onSelect:()=>a(S),availableFields:d,width:m[S.id],onWidthChange:E},S.id))}),e.jsx("th",{className:"w-10 border-r border-border bg-background px-1 py-2",children:e.jsxs(t.Popover,{open:b,onOpenChange:h,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Add column",children:e.jsx(t.Plus,{className:"h-4 w-4"})})}),e.jsx(t.PopoverContent,{className:"w-[280px] p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search columns..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No columns available."}),e.jsx(t.CommandGroup,{heading:"Available Columns",children:p.map(S=>{const F=t.getDataType(S.dataType),v=F==="number"?t.Hash:F==="date"?t.Calendar:t.Type;return e.jsxs(t.CommandItem,{value:S.label||S.name,onSelect:()=>O(S),children:[e.jsx(v,{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:S.label||S.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:S.entityName})]})]},S.id)})})]})]})})]})})]})]}),e.jsx("tbody",{children:f?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"})})}):T.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"})}):T.slice(0,100).map((S,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(v=>{const L=S[v.name]??S[v.label??""];return e.jsx("td",{style:{width:m[v.id]?`${m[v.id]}px`:void 0,minWidth:m[v.id]?`${m[v.id]}px`:"120px"},className:t.cn("border-r border-border px-3 py-2 text-sm",(s==null?void 0:s.id)===v.id&&"bg-primary/5"),children:e.jsx("span",{className:"block truncate",children:Ci(L,v)})},`${F}-${v.id}`)}),e.jsx("td",{className:"w-10 border-r border-border"})]},F))})]}),e.jsx(t.DragOverlay,{children:D&&e.jsx("div",{className:"rounded border border-primary bg-background px-3 py-2 text-sm font-medium shadow-lg",children:D.label||D.name})})]})}),e.jsxs("div",{className:"flex items-center justify-between border-t border-border bg-muted/30 px-4 py-2 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Showing ",Math.min(T.length,100)," of ",T.length," rows"]}),e.jsxs("span",{children:[u.length," columns"]})]})]})}function Ci(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 Si({entityGroups:s,isLoading:a=!1}){var O,C;const n=t.useEditorStore(k=>k.card),{updateCardConfig:r,removeGroupByColumn:d,removeMetricColumn:i}=t.useEditorActions(),[l,c]=N.useState(!0),[o,m]=N.useState(""),[x,b]=N.useState(new Set),h=((O=n==null?void 0:n.config)==null?void 0:O.groupByColumns)||[],u=((C=n==null?void 0:n.config)==null?void 0:C.metricColumns)||[],p=k=>{const w=new Set(x);w.has(k)?w.delete(k):w.add(k),b(w)},j=k=>h.some(w=>w.name===k.name&&w.qualifiedEntityName===k.qualifiedEntityName)||u.some(w=>w.name===k.name&&w.qualifiedEntityName===k.qualifiedEntityName),f=(k,w)=>{if(w)if(t.getDataType(k.dataType)==="number"){const y={...k,id:`metric-${k.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};r(n.id,{metricColumns:[...u,y]})}else{const y={...k,id:`groupby-${k.id}-${Date.now()}`,role:"groupby"};r(n.id,{groupByColumns:[...h,y]})}else{const D=h.findIndex(A=>A.name===k.name&&A.qualifiedEntityName===k.qualifiedEntityName),y=u.findIndex(A=>A.name===k.name&&A.qualifiedEntityName===k.qualifiedEntityName);D!==-1&&d(n.id,h[D].id),y!==-1&&i(n.id,u[y].id)}},T=k=>{if(!o)return k;const w=o.toLowerCase();return k.filter(D=>D.name.toLowerCase().includes(w)||D.label&&D.label.toLowerCase().includes(w))},E=k=>{switch(t.getDataType(k)){case"number":return t.Hash;case"date":return t.Calendar;default:return t.Type}};return l?e.jsxs("div",{className:"flex h-full w-72 flex-col border-l border-border bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border px-3 py-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Columns"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:()=>c(!1),title:"Close panel",children:e.jsx(ka,{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:k=>m(k.target.value),className:"h-8 pl-8 text-sm"})]})}),(h.length>0||u.length>0)&&e.jsxs("div",{className:"border-b border-border",children:[h.length>0&&e.jsxs(t.Collapsible,{defaultOpen:!0,children:[e.jsxs(t.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(t.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(qt,{className:"h-3.5 w-3.5 text-blue-500"}),e.jsx("span",{children:"Groupings"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:h.length})]}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:h.map(k=>{const w=E(k.dataType);return e.jsxs("div",{className:"group flex items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted/50",children:[e.jsx(t.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(w,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:k.label||k.name}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>d(n.id,k.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]},k.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(k=>{const w=E(k.dataType);return e.jsxs("div",{className:"group flex items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted/50",children:[e.jsx(t.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(w,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:k.label||k.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:k.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,k.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]},k.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(k=>{const w=T(k.columns);if(w.length===0)return null;const D=x.has(k.entityId)||o.length>0;return e.jsxs(t.Collapsible,{open:D,onOpenChange:()=>p(k.entityId),children:[e.jsxs(t.CollapsibleTrigger,{className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm font-medium hover:bg-muted/50",children:[e.jsx(t.ChevronRight,{className:t.cn("h-3.5 w-3.5 transition-transform duration-200",D&&"rotate-90")}),e.jsx(t.Table2,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate text-left",children:k.label||k.entityName}),e.jsx("span",{className:"text-xs text-muted-foreground",children:w.length})]}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:w.map(y=>{const A=E(y.dataType),g=j(y);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",g&&"bg-primary/5"),children:[e.jsx(t.Checkbox,{checked:g,onCheckedChange:R=>f(y,R),className:"h-3.5 w-3.5"}),e.jsx(A,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:y.label||y.name})]},y.id)})})})]},k.entityId)})})})]}):e.jsx("div",{className:"flex h-full items-start border-l border-border bg-muted/30 p-2",children:e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>c(!0),title:"Open panel",children:e.jsx(Aa,{className:"h-4 w-4"})})})}const wi=[{name:"SUM",description:"Sum of values",syntax:"SUM([column])"},{name:"AVG",description:"Average of values",syntax:"AVG([column])"},{name:"COUNT",description:"Count of rows",syntax:"COUNT([column])"},{name:"COUNTD",description:"Count distinct values",syntax:"COUNTD([column])"},{name:"MIN",description:"Minimum value",syntax:"MIN([column])"},{name:"MAX",description:"Maximum value",syntax:"MAX([column])"},{name:"IF",description:"Conditional logic",syntax:"IF(condition, then, else)"},{name:"CASE",description:"Multiple conditions",syntax:"CASE WHEN ... THEN ... END"},{name:"CONCAT",description:"Concatenate text",syntax:"CONCAT([col1], [col2])"},{name:"ROUND",description:"Round number",syntax:"ROUND([column], decimals)"},{name:"FLOOR",description:"Round down",syntax:"FLOOR([column])"},{name:"CEIL",description:"Round up",syntax:"CEIL([column])"},{name:"ABS",description:"Absolute value",syntax:"ABS([column])"},{name:"DATEPART",description:"Extract date part",syntax:"DATEPART(year, [date])"},{name:"DATEDIFF",description:"Difference between dates",syntax:"DATEDIFF(day, [date1], [date2])"}];function Ti({value:s,onChange:a,onSubmit:n,onCancel:r,selectedColumn:d,availableColumns:i}){const[l,c]=N.useState(!1),[o,m]=N.useState("column"),x=N.useRef(null);N.useEffect(()=>{const p=j=>{j.key==="Escape"&&s?r():j.key==="Enter"&&s&&!l&&n(s)};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[s,r,n,l]);const b=p=>{const j=`[${p.label||p.name}]`,f=x.current;if(f){const T=f.selectionStart||0,E=f.selectionEnd||0,O=s.slice(0,T)+j+s.slice(E);a(O),setTimeout(()=>{f.setSelectionRange(T+j.length,T+j.length),f.focus()},0)}else a(s+j);c(!1)},h=p=>{const j=x.current;if(j){const f=j.selectionStart||0,T=j.selectionEnd||0,E=s.slice(0,f)+p.syntax+s.slice(T);a(E),setTimeout(()=>{j.setSelectionRange(f+p.name.length+1,f+p.syntax.length-1),j.focus()},0)}else a(s+p.syntax);c(!1)},u=p=>{switch(t.getDataType(p)){case"number":return t.Hash;case"date":return t.Calendar;default:return t.Type}};return e.jsxs("div",{className:"flex items-center gap-2 border-b border-border bg-muted/30 px-3 py-1.5",children:[e.jsx("div",{className:"flex min-w-[100px] items-center justify-center rounded border border-border bg-background px-2 py-1 text-xs font-medium text-muted-foreground",children:d?e.jsx("span",{className:"truncate",children:d.label||d.name}):e.jsx("span",{children:"—"})}),e.jsxs(t.Popover,{open:l&&o==="function",onOpenChange:p=>{c(p),p&&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(Oa,{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:wi.map(p=>e.jsx(t.CommandItem,{value:p.name,onSelect:()=>h(p),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:p.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:p.description})]}),e.jsx("span",{className:"font-mono text-xs text-muted-foreground/75",children:p.syntax})]})},p.name))})]})]})})]}),e.jsxs(t.Popover,{open:l&&o==="column",onOpenChange:p=>{c(p),p&&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(p=>{const j=u(p.dataType);return e.jsxs(t.CommandItem,{value:p.label||p.name,onSelect:()=>b(p),children:[e.jsx(j,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:p.label||p.name})]},p.id)})})]})]})})]}),e.jsx("div",{className:"relative flex-1",children:e.jsx(t.Input,{ref:x,value:s,onChange:p=>a(p.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 Ei({className:s}){var u,p,j,f;const a=t.useEditorStore(T=>T.card),[n,r]=N.useState(null),[d,i]=N.useState(""),{columns:l=[],columnGroups:c=[],isLoading:o}=t.useColumns(),{valuePickFilterableFields:m=[]}=t.useFilterableFields();(u=a==null?void 0:a.config)!=null&&u.groupByColumns,(p=a==null?void 0:a.config)!=null&&p.metricColumns,(j=a==null?void 0:a.config)!=null&&j.groupByColumns,(f=a==null?void 0:a.config)!=null&&f.pivotByColumns;const x=T=>{r(T),i(T?`[${T.label||T.name}]`:"")},b=T=>{console.log("Formula submitted:",T),i(""),r(null)},h=()=>{i(""),r(null)};return e.jsxs("div",{className:t.cn("flex h-full w-full flex-col",s),children:[e.jsx(Ti,{value:d,onChange:i,onSubmit:b,onCancel:h,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(Ni,{selectedColumn:n,onColumnSelect:x,isLoading:o,sourceFields:l,filterableFields:m})}),e.jsx(Si,{entityGroups:c,isLoading:o})]})]})}function Ii(){var V,z;const[s,a]=N.useState("chart"),[n,r]=N.useState(!1),[d,i]=N.useState(!0),[l,c]=N.useState(!0),o=t.useEditorStore(B=>B.showAIDialog),m=t.useDashboardStore(B=>B.isVisualEditing),{setCardType:x}=t.useEditorActions(),b=t.useEditorStore(B=>B.card.type);N.useEffect(()=>ji(),[]);const h=B=>{x(B)},u=t.useEditorStore(B=>B.frame),p=t.useEditorStore(B=>B.card);t.useEditorStore(B=>B.activeTabCardId),t.useEditorStore(B=>B.actions.getAvailableFields);const{addCard:j,removeCard:f,updateCard:T,setActiveCard:E,updateFilters:O}=t.useEditorActions(),{columnFields:C=[],scopedFields:k=[],filterableFields:w=[]}=t.useFilterableFields(),D=t.useSensors(t.useSensor(t.PointerSensor,{activationConstraint:{distance:8}})),y=p,{getFieldsForContainer:A,setFieldsForContainer:g}=t.useFieldManagement(y),{activeField:R,handleDragStart:M,handleDragEnd:S}=ci({activeCardId:u.activeCardId,sourceFields:k,getFieldsForContainer:A,setFieldsForContainer:g}),F=(B,_)=>{_&&O(B,_)},v=B=>{var _;T(B,{config:{...(_=u.cards.find(U=>U.id===B))==null?void 0:_.config,filters:void 0}})},L=w,I=B=>{if(!B)return 0;let _=B.conditions.length;return B.groups.forEach(U=>{_+=I(U)}),_},P=I(((V=y==null?void 0:y.config)==null?void 0:V.filters)||null);return e.jsxs(t.DndContext,{sensors:D,collisionDetection:t.closestCenter,onDragStart:M,onDragEnd:S,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Rn,{isVisible:d,onToggleVisibility:()=>i(!d)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:b==="tableBuilder"?e.jsx(Ei,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!o&&e.jsx(Go,{selectedChart:b,onChartChange:h,groupByFields:A("groupBy"),pivotByFields:A("pivotBy"),metricsFields:A("metrics"),sortByFields:A("sortBy"),detailFields:A("detailColumns"),activeField:R,isVisible:l,onToggleVisibility:()=>c(!l)}),e.jsx(gi,{selectedChart:b,activeView:s,onViewChange:a,onFiltersClick:()=>r(!0),filterCount:P,activeCard:y,columns:C,getFieldsForContainer:A,cards:u.cards,activeCardId:u.activeCardId,addCard:j,setActiveCard:E})]})}),!d&&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"})})})]}),y&&e.jsx(ii,{cardId:y.id,filters:((z=y.config)==null?void 0:z.filters)||null,onFiltersChange:F,onClearFilters:v,availableFields:L,isOpen:n,onOpenChange:r}),e.jsx(t.DragOverlay,{dropAnimation:null,children:e.jsx(bi,{activeField:R||null})})]})}function ki({authToken:s,onSave:a,onClose:n}){const r=N.useRef(null),d=t.useEditorStore(w=>w.showAIDialog),i=t.useEditorStore(w=>w.isDevMode),l=t.useAssistantLayoutStore(w=>w.setFullscreen),c=t.useAssistantLayoutStore(w=>w.setPanelOpen),o=t.useAssistantLayoutStore(w=>w.setContainer),m=t.useAssistantPanel("editor"),x=t.useFullscreenAssistant(),b=t.useAssistantContainer("editor"),h=x==="editor",u=N.useCallback(w=>{o("editor",w)},[o]),{setAuthToken:p}=t.useDashboardActions(),{setShowAIDialog:j,setOnSave:f,setOnClose:T}=t.useEditorActions(),{setActiveAssistantType:E}=t.useAIActions();N.useEffect(()=>{a&&f(a),n&&T(n)},[a,f,n,T]),N.useEffect(()=>{s&&s.accessToken&&p(s)},[s,p]),N.useEffect(()=>{var w,D;d?((w=r.current)==null||w.resize(40),c("editor",!0),E("editor")):((D=r.current)==null||D.resize(0),c("editor",!1),x==="editor"&&l(null),E(null))},[d,c,E,l,x]);function O(w){var D;w<1?(j(!1),c("editor",!1),x==="editor"&&l(null),E(null),(D=r.current)==null||D.resize(0)):(d||(j(!0),E("editor")),m.isOpen||c("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",h&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(So,{})}),e.jsx(t.ResizableHandle,{disabled:!d}),e.jsx(t.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:O,defaultSize:m.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(En,{isFullscreen:h,onFullscreenChange:w=>l(w?"editor":null),fullscreenContainer:b})})})]}),e.jsx("div",{ref:u,className:t.cn("absolute inset-0",!h&&"pointer-events-none")})]})]})}function k(){return e.jsxs("div",{className:"relative flex h-full grow",children:[e.jsxs(t.ResizablePanelGroup,{"data-content":"explorer",className:t.cn("flex grow transition-opacity",h&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Ii,{})}),e.jsx(t.ResizableHandle,{disabled:!d}),e.jsx(t.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:O,defaultSize:m.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(En,{isFullscreen:h,onFullscreenChange:w=>l(w?"editor":null),fullscreenContainer:b})})})]}),e.jsx("div",{ref:u,className:t.cn("absolute inset-0",!h&&"pointer-events-none")})]})}return e.jsx(t.ErrorBoundary,{FallbackComponent:t.Fallback,children:i?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:C()}):k()})}function Di(){t.useDashboardStore(h=>h.selectedCardId);const s=t.useDashboardStore(h=>h.selectedSheetId),a=t.useDashboardStore(h=>h.dashboard),{setIsVisualEditing:n,setSelectedSheetId:r}=t.useDashboardStore(h=>h.actions),d=t.useEditorStore(h=>h.editorContext),{clearEditorContext:i}=t.useEditorStore(h=>h.actions),l=t.useDashboardStore(h=>h.isVisualEditing),c=t.useDashboardStore(h=>h.actions.updateFrame),o=t.useDashboardStore(h=>h.actions.updateDocumentSectionCard),m=t.useResolveExistingFrameSemanticExecutionPayload();async function x(h){var T,E,O;if((d==null?void 0:d.type)==="documentSection"){const C=t.getDocumentSectionEditorCard(h,d.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(d.sheetId,d.sectionId,C,{calculatedFields:h.calculatedFields}),i(),n(!1);return}const u=s?(T=a==null?void 0:a.sheets)==null?void 0:T.some(C=>{var k;return C.id===s&&((k=C.frames)==null?void 0:k.some(w=>w.id===h.id))}):!1,p=(O=(E=a==null?void 0:a.sheets)==null?void 0:E.find(C=>{var k;return(k=C.frames)==null?void 0:k.some(w=>w.id===h.id)}))==null?void 0:O.id,j=u?s:p||null;if(!j)return;const f=t.findDashboardFrameById(a,h.id);try{const C=await m(h,{previousFrame:f});c(j,h,{semanticExecutionPayload:C}),s!==j&&r(j),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 b(){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(ki,{onSave:x,onClose:b})})}exports.default=Di;
|