react-semaphor 0.1.295 → 0.1.296
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-BdoTYzuj.js → braces-BNXseceK.js} +1 -1
- package/dist/chunks/{braces-DWldEFn5.js → braces-DVrX_3Q_.js} +1 -1
- package/dist/chunks/dashboard-controls-CKKZcVA5.js +2219 -0
- package/dist/chunks/dashboard-controls-DS2xJxHU.js +47 -0
- package/dist/chunks/dashboard-filter-controls-button-nqfmscB7.js +11 -0
- package/dist/chunks/{dashboard-filter-controls-button-XwenlcXw.js → dashboard-filter-controls-button-xPaIlNHP.js} +501 -495
- package/dist/chunks/{dashboard-json-CU55qPXj.js → dashboard-json-cuj9vYY9.js} +1 -1
- package/dist/chunks/{dashboard-json-V6m6lJ_c.js → dashboard-json-ovQyHWw6.js} +1 -1
- package/dist/chunks/{dashboard-summary-settings-dialog-DRLPzp1P.js → dashboard-summary-settings-dialog-BUg3Qyhh.js} +1 -1
- package/dist/chunks/{dashboard-summary-settings-dialog-0CIiWsKc.js → dashboard-summary-settings-dialog-DF076HeJ.js} +1 -1
- package/dist/chunks/{edit-dashboard-visual-8ha6EM_g.js → edit-dashboard-visual-32TAM00c.js} +5331 -5303
- package/dist/chunks/edit-dashboard-visual-BtiMcO-L.js +183 -0
- package/dist/chunks/{index-14M0TnH6.js → index-BDeJH9hO.js} +103265 -88338
- package/dist/chunks/index-Dbrs96G8.js +1533 -0
- package/dist/chunks/{resource-management-panel-CcDAn86l.js → resource-management-panel-2qcXsKwg.js} +2 -2
- package/dist/chunks/{resource-management-panel-BL5-5ouC.js → resource-management-panel-C4qoxy_g.js} +31 -30
- package/dist/chunks/use-create-flow-overlay-state-BMD3YRzU.js +21 -0
- package/dist/chunks/{use-create-flow-overlay-state-D3PxfjYv.js → use-create-flow-overlay-state-CHeppRNE.js} +572 -568
- package/dist/chunks/{use-visual-utils-CdIOq4nt.js → use-visual-utils-BIHLaVwh.js} +70 -68
- package/dist/chunks/use-visual-utils-dOYWf6nM.js +1 -0
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +113 -112
- package/dist/style.css +1 -1
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +2 -2
- package/dist/types/dashboard.d.ts +235 -1
- package/dist/types/main.d.ts +288 -1
- package/dist/types/shared.d.ts +204 -1
- package/dist/types/surfboard.d.ts +235 -1
- package/dist/types/types.d.ts +235 -1
- package/package.json +7 -1
- package/dist/chunks/dashboard-controls-B3lrnI_r.js +0 -47
- package/dist/chunks/dashboard-controls-D7U6E1sB.js +0 -2014
- package/dist/chunks/dashboard-filter-controls-button-D0AsV28-.js +0 -11
- package/dist/chunks/edit-dashboard-visual-sSLAkmgf.js +0 -183
- package/dist/chunks/index-Ze8VskG1.js +0 -1435
- package/dist/chunks/use-create-flow-overlay-state-BbQVNDCj.js +0 -21
- package/dist/chunks/use-visual-utils-kh8p2QFm.js +0 -1
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),t=require("./index-Dbrs96G8.js"),y=require("react"),it=require("./use-visual-utils-dOYWf6nM.js"),ke=require("./use-create-flow-overlay-state-BMD3YRzU.js"),ua=require("react-dom"),ma=require("./braces-DVrX_3Q_.js");function xa(s){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const n in s)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(s,n);Object.defineProperty(a,n,r.get?r:{enumerable:!0,get:()=>s[n]})}}return a.default=s,Object.freeze(a)}const Pt=xa(y);/**
|
|
2
|
+
* @license lucide-react v0.453.0 - ISC
|
|
3
|
+
*
|
|
4
|
+
* This source code is licensed under the ISC license.
|
|
5
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
6
|
+
*/const ha=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 pa=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 cs=t.createLucideIcon("Columns3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
|
|
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 fa=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 kn=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 ga=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 ja=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 An=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 ba=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 va=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 ya=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 sn=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 Na=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 Ca=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 Wt=t.createLucideIcon("MoveHorizontal",[["path",{d:"m18 8 4 4-4 4",key:"1ak13k"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}]]);/**
|
|
82
|
+
* @license lucide-react v0.453.0 - ISC
|
|
83
|
+
*
|
|
84
|
+
* This source code is licensed under the ISC license.
|
|
85
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
86
|
+
*/const Xt=t.createLucideIcon("MoveVertical",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m8 18 4 4 4-4",key:"bh5tu3"}],["path",{d:"m8 6 4-4 4 4",key:"ybng9g"}]]);/**
|
|
87
|
+
* @license lucide-react v0.453.0 - ISC
|
|
88
|
+
*
|
|
89
|
+
* This source code is licensed under the ISC license.
|
|
90
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
91
|
+
*/const Sa=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 wa=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 Ta=t.createLucideIcon("PanelRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
|
|
102
|
+
* @license lucide-react v0.453.0 - ISC
|
|
103
|
+
*
|
|
104
|
+
* This source code is licensed under the ISC license.
|
|
105
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
106
|
+
*/const os=t.createLucideIcon("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/**
|
|
107
|
+
* @license lucide-react v0.453.0 - ISC
|
|
108
|
+
*
|
|
109
|
+
* This source code is licensed under the ISC license.
|
|
110
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
111
|
+
*/const zt=t.createLucideIcon("Rows3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M21 9H3",key:"1338ky"}],["path",{d:"M21 15H3",key:"9uk58r"}]]);/**
|
|
112
|
+
* @license lucide-react v0.453.0 - ISC
|
|
113
|
+
*
|
|
114
|
+
* This source code is licensed under the ISC license.
|
|
115
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
116
|
+
*/const Ea=t.createLucideIcon("SendHorizontal",[["path",{d:"M3.714 3.048a.498.498 0 0 0-.683.627l2.843 7.627a2 2 0 0 1 0 1.396l-2.842 7.627a.498.498 0 0 0 .682.627l18-8.5a.5.5 0 0 0 0-.904z",key:"117uat"}],["path",{d:"M6 12h16",key:"s4cdu5"}]]);/**
|
|
117
|
+
* @license lucide-react v0.453.0 - ISC
|
|
118
|
+
*
|
|
119
|
+
* This source code is licensed under the ISC license.
|
|
120
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
121
|
+
*/const Ia=t.createLucideIcon("Shapes",[["path",{d:"M8.3 10a.7.7 0 0 1-.626-1.079L11.4 3a.7.7 0 0 1 1.198-.043L16.3 8.9a.7.7 0 0 1-.572 1.1Z",key:"1bo67w"}],["rect",{x:"3",y:"14",width:"7",height:"7",rx:"1",key:"1bkyp8"}],["circle",{cx:"17.5",cy:"17.5",r:"3.5",key:"w3z12y"}]]);/**
|
|
122
|
+
* @license lucide-react v0.453.0 - ISC
|
|
123
|
+
*
|
|
124
|
+
* This source code is licensed under the ISC license.
|
|
125
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
126
|
+
*/const Da=t.createLucideIcon("Sigma",[["path",{d:"M18 7V5a1 1 0 0 0-1-1H6.5a.5.5 0 0 0-.4.8l4.5 6a2 2 0 0 1 0 2.4l-4.5 6a.5.5 0 0 0 .4.8H17a1 1 0 0 0 1-1v-2",key:"wuwx1p"}]]);/**
|
|
127
|
+
* @license lucide-react v0.453.0 - ISC
|
|
128
|
+
*
|
|
129
|
+
* This source code is licensed under the ISC license.
|
|
130
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
131
|
+
*/const ka=t.createLucideIcon("Spline",[["circle",{cx:"19",cy:"5",r:"2",key:"mhkx31"}],["circle",{cx:"5",cy:"19",r:"2",key:"v8kfzx"}],["path",{d:"M5 17A12 12 0 0 1 17 5",key:"1okkup"}]]);/**
|
|
132
|
+
* @license lucide-react v0.453.0 - ISC
|
|
133
|
+
*
|
|
134
|
+
* This source code is licensed under the ISC license.
|
|
135
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
136
|
+
*/const Aa=t.createLucideIcon("SquareFunction",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["path",{d:"M9 17c2 0 2.8-1 2.8-2.8V10c0-2 1-3.3 3.2-3",key:"m1af9g"}],["path",{d:"M9 11.2h5.7",key:"3zgcl2"}]]);/**
|
|
137
|
+
* @license lucide-react v0.453.0 - ISC
|
|
138
|
+
*
|
|
139
|
+
* This source code is licensed under the ISC license.
|
|
140
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
141
|
+
*/const Ma=t.createLucideIcon("SquareSplitVertical",[["path",{d:"M5 8V5c0-1 1-2 2-2h10c1 0 2 1 2 2v3",key:"1pi83i"}],["path",{d:"M19 16v3c0 1-1 2-2 2H7c-1 0-2-1-2-2v-3",key:"ido5k7"}],["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}]]);/**
|
|
142
|
+
* @license lucide-react v0.453.0 - ISC
|
|
143
|
+
*
|
|
144
|
+
* This source code is licensed under the ISC license.
|
|
145
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
146
|
+
*/const La=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"}]]);/**
|
|
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 Fa=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 Mn({storeValue:s,defaultValue:a="",onStoreUpdate:n,delay:r=300}){const[c,i]=y.useState(s??a),l=y.useRef(null),d=y.useRef(c),o=y.useRef(s),u=y.useRef(!1),p=y.useCallback(()=>{l.current&&(clearTimeout(l.current),l.current=null),u.current&&d.current!==(o.current??a)&&(n(d.current),o.current=d.current)},[a,n]);y.useEffect(()=>{if(s!==o.current){l.current&&(clearTimeout(l.current),l.current=null);const x=s??a;i(x),d.current=x,o.current=s,u.current=!1}},[s,a]),y.useEffect(()=>{if(u.current)return l.current=setTimeout(()=>{p()},r),()=>{l.current&&(clearTimeout(l.current),l.current=null)}},[r,p,c]),y.useEffect(()=>()=>{l.current&&clearTimeout(l.current)},[]);const h=y.useCallback(x=>{const m=x??a;u.current=!0,d.current=m,i(m)},[a]);return{value:c,onChange:h,flush:p}}function Ra({initialJoinPlan:s,availableDataSources:a}){const[n,r]=y.useState(s),[c,i]=y.useState(new Set),l=()=>{const S=n.joins.length>0?Math.max(...n.joins.map(D=>D.sequence))+1:1,I={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:S,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...n,joins:[...n.joins,I]}),i(new Set([...c,I.id]))},d=S=>{r({...n,joins:n.joins.filter(I=>I.id!==S)}),i(new Set([...c].filter(I=>I!==S)))},o=(S,I)=>{var C,k,F,f,L;const D=n.joins.find(E=>E.id===S);if(!D)return;const M={...D,...I};if((C=M.source)!=null&&C.name&&((k=M.target)!=null&&k.name)&&M.source.name===M.target.name){t.ue.error("Self-joins are not yet supported",{description:`Joining ${M.source.name} to itself is not currently supported. Please select a different target table.`});return}const v=n.joins.filter(E=>{var O;return E.id!==S&&E.target.name===((O=M.target)==null?void 0:O.name)});if((F=M.target)!=null&&F.name&&v.length>0){t.ue.error("Duplicate join targets are not supported",{description:`The table ${M.target.name} is already used as a target in another join. Each table can only be joined once.`});return}const R=n.joins.map(E=>E.id===S?M:E);if((f=M.source)!=null&&f.name&&((L=M.target)!=null&&L.name)&&M.joinKeyGroups[0].keys.length===0){const E=a.find(z=>{var _;return z.name===((_=M.source)==null?void 0:_.name)}),O=a.find(z=>{var _;return z.name===((_=M.target)==null?void 0:_.name)}),B={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(E==null?void 0:E.name)||"",entityName:(E==null?void 0:E.name)||"",entityType:(E==null?void 0:E.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(O==null?void 0:O.name)||"",entityName:(O==null?void 0:O.name)||"",entityType:(O==null?void 0:O.type)||"table"},operator:"="},V=[...M.joinKeyGroups];V[0]={...V[0],keys:[B]},M.joinKeyGroups=V,R[R.findIndex(z=>z.id===S)]=M}r({...n,joins:R})};return{joinPlan:n,expandedJoins:c,setJoinPlan:r,addJoin:l,removeJoin:d,updateJoin:o,moveJoinUp:S=>{const I=n.joins.findIndex(D=>D.id===S);if(I>0){const D=[...n.joins],M={...D[I]},v={...D[I-1]};D[I]=v,D[I-1]=M,D.forEach((C,k)=>{C.sequence=k+1});const R={...n,joins:D};r(R)}},moveJoinDown:S=>{const I=n.joins.findIndex(D=>D.id===S);if(I<n.joins.length-1){const D=[...n.joins],M={...D[I]},v={...D[I+1]};D[I]=v,D[I+1]=M,D.forEach((C,k)=>{C.sequence=k+1});const R={...n,joins:D};r(R)}},toggleJoinExpansion:S=>{const I=new Set(c);I.has(S)?I.delete(S):I.add(S),i(I)},getAvailableSourceEntities:S=>{if(n.joins.length===0)return a;const I=n.joins.findIndex(M=>M.id===S);if(I===0)return a.filter(M=>M.name===n.baseEntity.name);const D=new Set;return n.baseEntity.name&&D.add(n.baseEntity.name),n.joins.slice(0,I).forEach(M=>{D.add(M.source.name),D.add(M.target.name)}),a.filter(M=>D.has(M.name))},getAvailableTargetEntities:S=>a.filter(I=>I.name!==S),addJoinKeyGroup:S=>{const I=n.joins.find(M=>M.id===S);if(!I)return;const D=[...I.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];o(S,{joinKeyGroups:D})},updateGroupOperator:(S,I,D)=>{const M=n.joins.find(R=>R.id===S);if(!M)return;const v=[...M.joinKeyGroups];v[I]={...v[I],operator:D},o(S,{joinKeyGroups:v})},removeJoinKeyGroup:(S,I)=>{const D=n.joins.find(v=>v.id===S);if(!D)return;const M=[...D.joinKeyGroups];M.splice(I,1),o(S,{joinKeyGroups:M})},addJoinKey:(S,I)=>{const D=n.joins.find(k=>k.id===S);if(!D)return;const M=a.find(k=>k.name===D.source.name),v=a.find(k=>k.name===D.target.name),R=[...D.joinKeyGroups],C={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(M==null?void 0:M.name)||"",entityName:(M==null?void 0:M.name)||"",entityType:(M==null?void 0:M.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(v==null?void 0:v.name)||"",entityName:(v==null?void 0:v.name)||"",entityType:(v==null?void 0:v.type)||"table"},operator:"="};R[I]={...R[I],keys:[...R[I].keys,C]},o(S,{joinKeyGroups:R})},updateJoinKey:(S,I,D,M,v)=>{const R=n.joins.find(L=>L.id===S);if(!R)return;const C=a.find(L=>L.name===R.source.name),k=a.find(L=>L.name===R.target.name),F=[...R.joinKeyGroups],f=F[I].keys[D];M==="sourceColumnName"&&C?F[I].keys[D]={...f,source:{...f.source,name:v}}:M==="targetColumnName"&&k?F[I].keys[D]={...f,target:{...f.target,name:v}}:M==="operator"&&(F[I].keys[D]={...f,operator:v}),o(S,{joinKeyGroups:F})},removeJoinKey:(S,I,D)=>{const M=n.joins.find(R=>R.id===S);if(!M)return;const v=[...M.joinKeyGroups];v[I].keys.splice(D,1),o(S,{joinKeyGroups:v})},generateSQLPreview:()=>{const S=[...n.joins].sort((M,v)=>M.sequence-v.sequence),I=n.baseEntity;if(!I.name)return"SELECT * FROM table -- Please select a base entity";let D=`SELECT *
|
|
152
|
+
FROM ${I.name}`;return S.forEach(M=>{const v=a.find(k=>k.name===M.target.name);if(!v)return;const R=M.joinKeyGroups.filter(k=>k.keys&&k.keys.length>0).map(k=>{const F=k.keys.filter(f=>{var L,E,O,B;return((L=f.source)==null?void 0:L.name)&&((E=f.target)==null?void 0:E.name)&&((O=f.source)==null?void 0:O.entityName)&&((B=f.target)==null?void 0:B.entityName)}).map(f=>`${f.source.entityName}.${f.source.name} ${f.operator} ${f.target.entityName}.${f.target.name}`);return F.length>1?`(${F.join(` ${k.operator} `)})`:F[0]}).filter(Boolean),C=R.length>1?R.join(" OR "):R[0]||"condition_here";D+=`
|
|
153
|
+
${M.joinType} JOIN ${v.name}
|
|
154
|
+
ON ${C}`}),D},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(M=>!M.source.name||!M.target.name)||n.joins.some(M=>M.joinKeyGroups.some(v=>v.keys.length===0))||n.joins.some(M=>M.joinKeyGroups.some(v=>v.keys.some(R=>!R.source.name||!R.target.name||!R.operator))))}}function Oa({joinPlan:s,availableDataSources:a,onSave:n,onRemove:r,onCancel:c}){const{setCardConfig:i}=t.useEditorActions();t.useEditorStore(C=>C.card.config);const{columnGroups:l}=t.useColumns(),d=l.filter(C=>C.entityName!==t.CALCULATED_FIELDS_GROUP_NAME),{joinPlan:o,expandedJoins:u,setJoinPlan:p,addJoin:h,removeJoin:x,updateJoin:m,moveJoinUp:g,moveJoinDown:b,toggleJoinExpansion:j,getAvailableSourceEntities:w,getAvailableTargetEntities:T,addJoinKeyGroup:P,updateGroupOperator:N,removeJoinKeyGroup:A,addJoinKey:S,updateJoinKey:I,removeJoinKey:D,generateSQLPreview:M,isValidConfiguration:v}=Ra({initialJoinPlan:s,availableDataSources:a}),R=C=>{const k=d.find(F=>F.entityName===C);return(k==null?void 0:k.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:C=>{const k=a.find(F=>F.name===C);p({...o,baseEntity:{connectionId:(k==null?void 0:k.connectionId)||"",connectionType:(k==null?void 0:k.connectionType)||"none",type:(k==null?void 0:k.type)||"table",name:C,database:k==null?void 0:k.database,schema:k==null?void 0:k.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(t.SelectContent,{children:a.map(C=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:C.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:C.type}),C.name,e.jsx(t.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},C.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:M()})]}),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:h,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(C=>{const k=a.find(L=>L.name===C.source.name),F=a.find(L=>L.name===C.target.name),f=u.has(C.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:C.sequence}),e.jsxs(t.CardTitle,{className:"text-sm",children:["Join ",C.sequence,k&&F&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",k.name," → ",F.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>g(C.id),disabled:C.sequence===1,children:e.jsx(t.ArrowUp,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>b(C.id),disabled:C.sequence===o.joins.length,children:e.jsx(t.ArrowDown,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>j(C.id),children:f?e.jsx(t.ChevronUp,{className:"h-4 w-4"}):e.jsx(t.ChevronDown,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>x(C.id),children:e.jsx(t.X,{className:"h-4 w-4"})})]})]})}),f&&e.jsxs(t.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Source"}),e.jsxs(t.Select,{value:C.source.name,onValueChange:L=>{const E=a.find(O=>O.name===L);m(C.id,{source:{connectionId:(E==null?void 0:E.connectionId)||"",connectionType:(E==null?void 0:E.connectionType)||"none",type:(E==null?void 0:E.type)||"table",name:L,database:E==null?void 0:E.database,schema:E==null?void 0:E.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select source..."})}),e.jsx(t.SelectContent,{children:w(C.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:C.joinType,onValueChange:L=>m(C.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:C.target.name,onValueChange:L=>{const E=a.find(O=>O.name===L);m(C.id,{target:{connectionId:(E==null?void 0:E.connectionId)||"",connectionType:(E==null?void 0:E.connectionType)||"none",type:(E==null?void 0:E.type)||"table",name:L,database:E==null?void 0:E.database,schema:E==null?void 0:E.schema}})},disabled:!C.source.name,children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select target..."})}),e.jsx(t.SelectContent,{children:C.source.name?T(C.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===C.source.name&&e.jsx(t.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},L.name)):[]})]})]})]}),C.source.name&&C.target.name&&k&&F&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{children:"Join Conditions"}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>P(C.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),C.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:C.joinKeyGroups.map((L,E)=>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 ",E+1]}),E>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(t.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Select,{value:L.operator,onValueChange:O=>N(C.id,E,O),children:[e.jsx(t.SelectTrigger,{className:"w-[100px]",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>A(C.id,E),children:e.jsx(t.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[L.keys.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-sm text-gray-500",children:"No conditions in this group. Add conditions to specify join criteria."}):e.jsx("div",{className:"space-y-2",children:L.keys.map((O,B)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[B>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:L.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:O.source.name,onValueChange:V=>I(C.id,E,B,"sourceColumnName",V),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Source column"})}),e.jsx(t.SelectContent,{children:R(C.source.name).map(V=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:V.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:V.name}),e.jsx(t.Badge,{variant:"outline",className:"ml-2 text-xs",children:V.dataType})]})},V.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(t.Select,{value:O.operator,onValueChange:V=>I(C.id,E,B,"operator",V),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:O.target.name,onValueChange:V=>I(C.id,E,B,"targetColumnName",V),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Target column"})}),e.jsx(t.SelectContent,{children:R(C.target.name).map(V=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:V.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:V.name}),e.jsx(t.Badge,{variant:"outline",className:"ml-2 text-xs",children:V.dataType})]})},V.name))})]})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>D(C.id,E,B),children:e.jsx(t.X,{className:"size-3.5"})})]},O.id||B))}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>S(C.id,E),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},L.id))})]})]})]},C.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>{r(),c()},children:"Remove All"}),e.jsx(t.Button,{variant:"outline",onClick:c,children:"Cancel"}),e.jsx(t.Button,{onClick:()=>n(o),disabled:!v(),children:"Save"})]})]})}function Ln({children:s,open:a,onOpenChange:n,joinPlan:r,availableDataSources:c,onRemove:i,onSave:l,onCancel:d}){return e.jsxs(t.Dialog,{open:a,onOpenChange:n,children:[e.jsxs(t.DialogContent,{className:"max-w-4xl",children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Join Configuration"}),e.jsx(t.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(Oa,{joinPlan:r,availableDataSources:c,onSave:l,onCancel:d,onRemove:i})]}),s]})}function Pa({joins:s,baseEntityId:a,availableDataSources:n,generateSQLPreview:r}){return e.jsxs("div",{className:"my-2 max-h-[400px] divide-y divide-border overflow-y-auto",children:[s.length>0&&e.jsxs("div",{className:"px-4 py-2",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const c=[...s].sort((l,d)=>l.sequence-d.sequence),i=n.find(l=>l.name===a);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(t.Badge,{variant:"secondary",className:"text-xs",children:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name}),e.jsx(t.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),c.map(l=>{const d=n.find(o=>o.name===l.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:l.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(t.Badge,{variant:"secondary",className:"text-xs",children:d==null?void 0:d.type}),e.jsx("span",{className:"text-xs font-medium",children:d==null?void 0:d.name})]})]},l.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",s.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...s].sort((c,i)=>c.sequence-i.sequence).map((c,i)=>{const l=n.find(u=>u.name===c.source.name),d=n.find(u=>u.name===c.target.name),o=c.joinKeyGroups.reduce((u,p)=>u+p.keys.length,0);return e.jsxs("div",{className:"rounded-md bg-muted p-2 text-left",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:i+1}),e.jsx(t.Badge,{variant:"outline",className:"shrink-0 text-xs",children:c.joinType}),e.jsxs(t.Badge,{variant:"outline",className:"ml-auto shrink-0 text-xs",children:[o," condition",o>1?"s":""]})]}),e.jsxs("div",{className:"mt-1 truncate pl-1 text-xs text-muted-foreground",children:[l==null?void 0:l.name," → ",d==null?void 0:d.name]})]},c.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function nn({open:s,onOpenChange:a,variant:n="button"}={}){var T,P;const r=t.useEditorStore(N=>N.card),{autoJoinMetadata:c}=t.useEditorCardQuery(r),i=t.useEditorStore(N=>N.actions.updateCardConfig),l=((T=r==null?void 0:r.config)==null?void 0:T.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[d,o]=y.useState(!1),u=s!==void 0,p=u?s:d,h=u?a:o,x=((P=r==null?void 0:r.dataSource)==null?void 0:P.selectedEntities)||[],m=N=>{i(r.id,{...r==null?void 0:r.config,joinPlan:N}),h(!1)},g=()=>{i(r.id,{...r==null?void 0:r.config,joinPlan:void 0})},b=()=>{h(!1)},j=()=>{const N=[...l.joins].sort((I,D)=>I.sequence-D.sequence),A=l.baseEntity;if(!A.name)return"SELECT * FROM table -- Please select a base entity";let S=`SELECT *
|
|
155
|
+
FROM ${A.name}`;return N.forEach(I=>{const D=x.find(R=>R.name===I.target.name);if(!D)return;const M=I.joinKeyGroups.filter(R=>R.keys&&R.keys.length>0).map(R=>{const C=R.keys.filter(k=>{var F,f,L,E;return((F=k.source)==null?void 0:F.name)&&((f=k.target)==null?void 0:f.name)&&((L=k.source)==null?void 0:L.entityName)&&((E=k.target)==null?void 0:E.entityName)}).map(k=>`${k.source.entityName}.${k.source.name} ${k.operator} ${k.target.entityName}.${k.target.name}`);return C.length>1?`(${C.join(` ${R.operator} `)})`:C[0]}).filter(Boolean),v=M.length>1?M.join(" OR "):M[0]||"condition_here";S+=`
|
|
156
|
+
${I.joinType} JOIN ${D.name}
|
|
157
|
+
ON ${v}`}),S};if(x.length<2)return null;const w=l.joins.length>0&&e.jsx(t.TooltipContent,{side:"bottom",className:"ml-4 max-w-md overflow-hidden p-0",children:e.jsx(Pa,{joins:l.joins,baseEntityId:l.baseEntity.name,availableDataSources:x,generateSQLPreview:j})});return e.jsxs(e.Fragment,{children:[e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children: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:N=>{N.stopPropagation(),h(!0)},children:[e.jsx(t.Link,{className:"h-3 w-3"}),l.joins.length]}):e.jsxs(t.Button,{onClick:()=>h(!0),variant:"outline",className:"w-full bg-muted/50",children:[e.jsx(t.Link,{className:"mr-2 h-3.5 w-3.5"}),l.joins.length===0?"Configure Joins":l.joins.length===1?"Join":"Joins",l.joins.length>0&&e.jsx("span",{className:"ml-2 flex h-5 min-w-5 items-center justify-center rounded-full border bg-muted-foreground px-1.5 text-xs font-medium text-background",children:l.joins.length}),(c==null?void 0:c.autoResolved)&&e.jsxs(t.Badge,{variant:"secondary",className:"ml-2 h-5 gap-1 bg-blue-50 text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:[e.jsx(t.Sparkles,{className:"h-3 w-3"}),"Auto"]})]})}),w]})}),e.jsx(Ln,{open:p,onOpenChange:h,joinPlan:l,availableDataSources:x,onSave:m,onCancel:b,onRemove:g,children:e.jsx("div",{})})]})}function Ba({open:s,onOpenChange:a}){const[n,r]=y.useState([]),{updateDataSource:c}=t.useEditorActions(),{selectedEntities:i}=t.useAssistantContextEntities("dashboard");y.useEffect(()=>{s&&r([])},[s]);const l=m=>{r(g=>g.some(j=>t.areContextEntitiesEqual(j,m))?g.filter(j=>!t.areContextEntitiesEqual(j,m)):[...g,m])},d=()=>{r([...i])},o=()=>{r([])},u=()=>{if(n.length===0)return;const m=n[0],g=m.connectionId||"",b=m.connectionType||"",w=n.some(P=>P.type==="dataset")?"semanticDomain":"database";c({connectionId:g,connectionType:b,mode:w,selectedEntities:n}),a(!1)},p=m=>"label"in m&&m.label?m.label:m.name,h=m=>{if("description"in m&&m.description)return m.description;const g=[];return m.database&&g.push(m.database),m.schema&&g.push(m.schema),m.name&&g.push(m.name),g.join(".")},x=m=>n.some(g=>t.areContextEntitiesEqual(g,m));return i.length===0?e.jsx(t.Dialog,{open:s,onOpenChange:a,children:e.jsxs(t.DialogContent,{className:"max-w-md",children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"No Data Available"}),e.jsx(t.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(t.DialogFooter,{children:e.jsx(t.Button,{onClick:()=>a(!1),children:"Close"})})]})}):e.jsx(t.Dialog,{open:s,onOpenChange:a,children:e.jsxs(t.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(t.DialogDescription,{children:"Choose entities from the dashboard's context"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"outline",size:"sm",onClick:d,disabled:n.length===i.length,children:"Select All"}),e.jsx(t.Button,{variant:"outline",size:"sm",onClick:o,disabled:n.length===0,children:"Clear All"})]}),e.jsxs(t.Badge,{variant:"secondary",children:[n.length," of ",i.length," selected"]})]}),e.jsx(t.Separator,{}),e.jsx(t.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:i.map((m,g)=>e.jsxs("div",{className:t.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",x(m)&&"border-primary bg-primary/5"),children:[e.jsx(t.Checkbox,{checked:x(m),onCheckedChange:()=>l(m)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:t.getEntityIcon(m.type)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:p(m)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:h(m)})]}),e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:m.type})]},`${m.type}-${m.name}-${g}`))})})]}),e.jsx(t.DialogFooter,{children:e.jsx("div",{className:"flex w-full justify-between",children:e.jsxs("div",{className:"flex grow justify-end gap-2",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(t.Button,{onClick:u,disabled:n.length===0,children:["Select"," ",n.length>0?`(${n.length})`:""]})]})})})]})})}function an({entities:s,title:a}){const{isConsoleMode:n}=t.useDashboardPreferences();return e.jsx(t.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:a??`${s.length} more entities`}),e.jsx("div",{className:"space-y-1",children:s.map((r,c)=>{const i=t.getEntityDetails(r),l=i.find(o=>o.label==="Description"&&o.value),d=i.filter(o=>o.label==="Description"?!1:n?!0:!["Connection","Database","Schema"].includes(o.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:t.getDisplayName(r)}),l&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:l.value})]}),d.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:d.map((o,u)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[o.label,":"]}),e.jsx("span",{className:"font-mono",children:o.value})]},u))})]},`remaining-${r.type}-${r.name}-${c}`)})})]})})}function Fn(s,a){const[n,r]=y.useState(()=>{const c=localStorage.getItem(s);return c?JSON.parse(c):a});return y.useEffect(()=>{localStorage.setItem(s,JSON.stringify(n))},[n,s]),[n,r]}function Rn({isVisible:s}){var b,j;const a=t.useEditorStore(w=>w.isDevMode);t.useSyncLegacyEditorState();const[n,r]=y.useState(!1),[c,i]=y.useState(!1),[l,d]=Fn("semaphor:data-source-collapsed",!1),o=t.useEditorStore(w=>w.card.dataSource),u=t.useEditorStore(w=>{var T,P;return(P=(T=w.card)==null?void 0:T.config)==null?void 0:P.joinPlan}),{updateDataSource:p}=t.useEditorActions(),h=((b=o==null?void 0:o.selectedEntities)==null?void 0:b.length)||0,x=((j=u==null?void 0:u.joins)==null?void 0:j.length)||0,g={...{connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},...o,selectedEntities:(o==null?void 0:o.selectedEntities)||[]};return e.jsxs("div",{className:t.cn("flex shrink-0 flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":s,"min-w-[325px]":s,"w-0":!s,"min-w-0":!s}),children:[h===0&&x===0?e.jsx("div",{className:"px-4 pt-4",children:e.jsx("div",{className:"rounded-xl border border-border/55 bg-card p-3 shadow-[0_1px_2px_rgba(15,23,42,0.05)]",children:e.jsxs(t.Button,{className:"w-full bg-background",variant:"outline",onClick:()=>r(!0),children:[e.jsx(t.Database,{className:"mr-2 h-3.5 w-3.5"}),"Choose Dataset"]})})}):e.jsx("div",{className:"px-4 pt-4",children:e.jsxs("div",{className:"rounded-xl border border-border/55 bg-card p-3 shadow-[0_1px_2px_rgba(15,23,42,0.05)]",children:[e.jsxs("div",{className:t.cn("flex cursor-pointer items-center justify-between px-1",l?"pb-0":"pb-3"),onClick:()=>d(!l),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:"Data Source"}),l&&e.jsxs("div",{className:"flex items-center gap-1.5",onClick:w=>w.stopPropagation(),children:[h>0&&e.jsx(t.TooltipProvider,{delayDuration:100,children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs(t.Badge,{variant:"secondary",className:"h-5 cursor-pointer gap-1 px-1.5 text-xs transition-colors hover:bg-secondary/80",onClick:()=>r(!0),children:[e.jsx(t.Database,{className:"h-3 w-3"}),h]})}),e.jsx(an,{entities:g.selectedEntities,title:`${h} selected ${h===1?"entity":"entities"}`})]})}),x>0&&!a&&e.jsx(nn,{variant:"badge"})]})]}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:w=>{w.stopPropagation(),d(!l)},children:l?e.jsx(t.ChevronDown,{className:"h-4 w-4"}):e.jsx(t.ChevronUp,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:t.cn("flex flex-col overflow-hidden transition-all duration-200 ease-in-out",l?"max-h-0 opacity-0":"max-h-96 opacity-100"),children:[e.jsx("div",{className:"px-1",children:e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs(t.Button,{className:"w-full bg-background",variant:"outline",onClick:()=>r(!0),children:[e.jsx(t.Database,{className:"mr-2 h-3.5 w-3.5"}),h===1?"Dataset":"Datasets",e.jsx("span",{className:"ml-2 flex h-5 min-w-5 items-center justify-center rounded-full border bg-muted-foreground px-1.5 text-xs font-medium text-background",children:h})]})}),e.jsx(an,{entities:g.selectedEntities,title:`${h} selected ${h===1?"entity":"entities"}`})]})})}),!a&&h>1&&e.jsx("div",{className:"mt-3 px-1",children:e.jsx(nn,{})})]})]})}),e.jsx("div",{className:"min-h-0 flex-1 px-4 pb-4 pt-2",children:e.jsx("div",{className:"h-full overflow-hidden rounded-xl border border-border/55 bg-card shadow-[0_1px_2px_rgba(15,23,42,0.05)]",children:e.jsx(t.FieldsSection,{})})}),e.jsx(t.DataSourceDialog,{incomingSelectedEntities:(o==null?void 0:o.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:r,dataSource:g}),e.jsx(Ba,{open:c,onOpenChange:i})]})}function Va(s){return t.GenIcon({attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M439.8 200.5c-7.7-30.9-22.3-54.2-53.4-54.2h-40.1v47.4c0 36.8-31.2 67.8-66.8 67.8H172.7c-29.2 0-53.4 25-53.4 54.3v101.8c0 29 25.2 46 53.4 54.3 33.8 9.9 66.3 11.7 106.8 0 26.9-7.8 53.4-23.5 53.4-54.3v-40.7H226.2v-13.6h160.2c31.1 0 42.6-21.7 53.4-54.2 11.2-33.5 10.7-65.7 0-108.6zM286.2 404c11.1 0 20.1 9.1 20.1 20.3 0 11.3-9 20.4-20.1 20.4-11 0-20.1-9.2-20.1-20.4.1-11.3 9.1-20.3 20.1-20.3zM167.8 248.1h106.8c29.7 0 53.4-24.5 53.4-54.3V91.9c0-29-24.4-50.7-53.4-55.6-35.8-5.9-74.7-5.6-106.8.1-45.2 8-53.4 24.7-53.4 55.6v40.7h106.9v13.6h-147c-31.1 0-58.3 18.7-66.8 54.2-9.8 40.7-10.2 66.1 0 108.6 7.6 31.6 25.7 54.2 56.8 54.2H101v-48.8c0-35.3 30.5-66.4 66.8-66.4zm-6.7-142.6c-11.1 0-20.1-9.1-20.1-20.3.1-11.3 9-20.4 20.1-20.4 11 0 20.1 9.2 20.1 20.4s-9 20.3-20.1 20.3z"},child:[]}]})(s)}const za=300;function _a(){const s=t.useEditorStore(w=>w.card.sql),a=t.useEditorStore(w=>w.sqlGen),n=t.useEditorStore(w=>w.card),r=ke.useEffectiveEditorCardType(),{setCardSql:c,setSqlGen:i,setRunSql:l}=t.useEditorActions(),d=y.useMemo(()=>r!==n.type?{...n,type:r}:n,[n,r]),{queryKey:o}=t.useEditorCardQuery(d),u=t.useQueryClient(),p=y.useRef(o);p.current=o;const h=y.useRef(a);h.current=a;const x=y.useCallback(w=>{c(w)},[c]),{value:m,onChange:g,flush:b}=Mn({storeValue:s,defaultValue:"",onStoreUpdate:x,delay:za});y.useEffect(()=>it.registerPendingEditorDraftFlusher(b),[b]);function j(w){g(w),t.isObjectEmpty(h.current)||i({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!m&&e.jsx("div",{className:"pointer-events-none absolute left-[56px] top-4 z-10 font-mono text-[12px] leading-[1.55] text-muted-foreground",children:"Write your SQL here"}),e.jsx(t.CodeEditor,{value:m??"",onValueChange:j,language:"sql-jinja",embedded:!0,flushGutter:!0,onKeyDown:w=>{w.key==="Enter"&&w.shiftKey&&(w.preventDefault(),it.flushPendingEditorDrafts(),setTimeout(()=>{u.removeQueries({queryKey:p.current,exact:!0}),l(!0)},0))}})]})}const qa=300;function $a(){const s=t.useEditorStore(x=>x.card.python),a=t.useEditorStore(x=>x.card),n=ke.useEffectiveEditorCardType(),{setCardPython:r,setRunSql:c}=t.useEditorActions(),i=y.useMemo(()=>n!==a.type?{...a,type:n}:a,[a,n]),{queryKey:l}=t.useEditorCardQuery(i),d=t.useQueryClient(),o=y.useRef(l);o.current=l;const{value:u,onChange:p,flush:h}=Mn({storeValue:s,defaultValue:t.PYTHON_DEFAULT_CODE,onStoreUpdate:r,delay:qa});return y.useEffect(()=>it.registerPendingEditorDraftFlusher(h),[h]),e.jsx(t.CodeEditor,{value:u??"",onValueChange:p,language:"python",embedded:!0,flushGutter:!0,onKeyDown:x=>{x.key==="Enter"&&x.shiftKey&&(x.preventDefault(),it.flushPendingEditorDrafts(),setTimeout(()=>{d.removeQueries({queryKey:o.current,exact:!0}),c(!0)},0))}})}const Ka={async writeTextToClipboard(s){return typeof navigator>"u"||!navigator.clipboard?!1:(await navigator.clipboard.writeText(s),!0)}},Rt=50,Ga=[{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 rn(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 Ua(s){if(!s||typeof s!="object")return{value:s};const a=s.records;return!Array.isArray(a)||a.length<=Rt?{value:s}:{value:{...s,records:a.slice(0,Rt),previewMeta:{truncatedRecords:!0,displayedRecords:Rt,totalRecords:a.length}},truncationMessage:`Preview showing first ${Rt} records of ${a.length}. Copy actions include full payload.`}}function On({sql:s,showCardDetails:a=!1,debugPayloads:n,className:r}){const[c,i]=y.useState(!1),[l,d]=y.useState(null),o=t.useEditorStore(v=>v.card),u=t.useEditorStore(v=>v.frame),p=t.useEditorStore(v=>v.isDevMode),h=t.useDashboardStore(v=>v.selectedSheetId),x=t.useDashboardStore(v=>{var R;return(R=v.dashboard)==null?void 0:R.id}),{switchEditorMode:m,setRunSql:g}=t.useEditorActions(),b=y.useMemo(()=>({cardId:o.id||null,frameId:u.id||null,sheetId:h||null,dashboardId:x||null}),[o.id,u.id,h,x]),j=y.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:b}),[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,b]),w=a&&c&&!!n,T=y.useMemo(()=>[{label:"Card ID",value:o.id||""},{label:"Frame ID",value:u.id||""},{label:"Sheet ID",value:h||""},{label:"Dashboard ID",value:x||""}],[o.id,u.id,h,x]),P=()=>{m("dev",{sqlToLoad:s}),setTimeout(()=>{g(!0)},100)},N=v=>j[v]!==void 0,A=y.useMemo(()=>{if(!l)return null;const v=j[l];if(v===void 0)return null;const R=l==="queryResponse"?Ua(v):{value:v},C=rn(R.value);return C?{target:l,title:gt(l),json:C,truncationMessage:R.truncationMessage}:null},[l,j]),S=A?A.title:"Preview Payload",I=async v=>{const R=j[v];if(R===void 0)return t.ue.error(`No ${gt(v).toLowerCase()} available`),!1;const C=rn(R);if(!C)return t.ue.error(`Unable to serialize ${gt(v).toLowerCase()}`),!1;try{return await Ka.writeTextToClipboard(C)?(t.ue.success(`${gt(v)} copied`),!0):(t.ue.error("Clipboard is not available"),!1)}catch(k){return console.error("Failed to copy debug payload",k),t.ue.error(`Unable to copy ${gt(v).toLowerCase()}`),!1}},D=async()=>A?I(A.target):!1,M=v=>{if(j[v]===void 0){t.ue.error(`No ${gt(v).toLowerCase()} available`);return}d(v)};return e.jsxs("div",{className:t.cn("flex min-h-0 flex-1 flex-col",r),children:[!p&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsxs(t.Button,{onClick:P,variant:"secondary",size:"sm",children:[e.jsx(kn,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),a&&e.jsxs(t.Button,{onClick:()=>i(!c),variant:"outline",size:"sm",children:[e.jsx(t.Info,{className:"mr-2 h-4 w-4"}),"Card Details"]})]}),c&&a&&e.jsx("div",{className:"mb-3 rounded-lg border border-border bg-muted/30 p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Card Information"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>i(!1),children:e.jsx(ke.CircleX,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"grid grid-cols-1 gap-2 md:grid-cols-2",children:T.map(v=>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:v.label}),e.jsx(t.CopyButton,{text:v.value,className:"h-6 w-6 shrink-0"})]}),e.jsx("code",{title:v.value||"N/A",className:"mt-1 block whitespace-normal break-all font-mono text-xs",children:v.value||"N/A"})]},v.label))}),w&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-background/70 p-3",children:[e.jsx("p",{className:"text-xs font-semibold text-muted-foreground",children:"Debug Tools"}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(t.DropdownMenu,{children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8","aria-label":"Preview Payload Menu",children:[e.jsx(t.Eye,{className:"mr-1.5 h-3.5 w-3.5"}),S,e.jsx(t.ChevronDown,{className:"ml-1.5 h-3.5 w-3.5"})]})}),e.jsx(t.DropdownMenuContent,{align:"start",className:"w-56",children:Ga.map(v=>e.jsx(t.DropdownMenuItem,{disabled:!N(v.target),onSelect:()=>M(v.target),className:t.cn(l===v.target&&"bg-accent"),children:v.label},`preview-${v.target}`))})]})}),A&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs font-medium text-muted-foreground",children:[A.title," Preview"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(t.CopyButton,{text:A.json,className:"h-6 w-6",ariaLabel:"Copy Payload",onCopy:D}),e.jsxs(t.Button,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>d(null),children:[e.jsx(ke.CircleX,{className:"mr-1 h-3.5 w-3.5"}),"Hide"]})]})]}),A.truncationMessage&&e.jsx("p",{className:"text-xs text-muted-foreground",children:A.truncationMessage}),e.jsx("div",{className:"max-h-80 overflow-auto",children:e.jsx(t.CodeHighlighter,{code:A.json,language:"json"})})]})]})]})}),e.jsx("div",{className:"min-h-0 flex-1 overflow-auto",children:e.jsxs("div",{className:"overflow-hidden rounded-xl border border-border/60 bg-gradient-to-b from-background to-muted/[0.18] shadow-sm",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border/50 bg-background/80 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"rounded-md border border-border/60 bg-muted/60 px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.12em] text-muted-foreground",children:"SQL"}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Generated query"})]}),e.jsx("div",{className:"rounded-md border border-border/60 bg-background/85 p-0.5 shadow-sm backdrop-blur-sm",children:e.jsx(t.CopyButton,{text:s,className:"h-6 w-6 px-0 text-muted-foreground/80 hover:text-foreground"})})]}),e.jsx("div",{className:"group relative overflow-auto px-1 py-1 text-xs leading-relaxed text-foreground/80",children:e.jsx(t.CodeHighlighter,{code:s,language:"sql",wrapLongLines:!0})})]})})]})}const Ha=/\{\{-?\s*filters\s*\|\s*where\s*-?\}\}/i,Qa=/\{\{-?\s*filters\s*\|\s*and\s*-?\}\}/i,Ja=/\bwhere\b/i;function Ya(s){return s!=null&&s.trim()?Ha.test(s)||Qa.test(s):!1}function Wa(s){return!(s!=null&&s.trim())||Ya(s)?null:Ja.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 Xa(s){const{request:a,mode:n="draft",currentSql:r,selectedTableName:c,selectedSchemaName:i,selectedDatabaseName:l}=s,d=[l?`Database: ${l}`:"",i?`Schema: ${i}`:"",c?`Table: ${c}`:""].filter(Boolean);return["You are an expert SQL writing assistant embedded in a query editor.",`Write SQL only. You may call only read-only tools when needed: ${t.INLINE_ALLOWED_TOOL_LIST}.`,"Do not call mutation tools or chart-creation tools; those require Full Assistant.","Return exactly one SQL statement inside a single ```sql fenced block.","After the code block, optionally include one short sentence.",n==="refine"&&r?"Mode: Refine existing SQL. Keep the current query structure and only apply the requested changes unless the current query is invalid.":"Mode: Draft new SQL from the request.",d.length>0?`Context:
|
|
158
|
+
${d.join(`
|
|
159
|
+
`)}`:"",r?n==="refine"?`Current SQL (must refine):
|
|
160
|
+
${r}`:`Current SQL (revise if useful):
|
|
161
|
+
${r}`:"",`User request:
|
|
162
|
+
${a}`].filter(Boolean).join(`
|
|
163
|
+
|
|
164
|
+
`)}function Za(s){const{request:a,failedSql:n,errorMessage:r,errorCode:c,selectedDatabaseName:i,selectedSchemaName:l,selectedTableName:d,contextEntityLabels:o}=s,u=[i?`Database: ${i}`:"",l?`Schema: ${l}`:"",d?`Table: ${d}`:"",o.length>0?`Selected context entities: ${o.join(", ")}`:""].filter(Boolean);return["You are fixing SQL after validation failed.","Return one read-only SQL statement in a single ```sql fenced block.","Do not call mutation tools.",u.length>0?`Context:
|
|
165
|
+
${u.join(`
|
|
166
|
+
`)}`:"",`Original user request:
|
|
167
|
+
${a}`,`Previous SQL draft:
|
|
168
|
+
${n}`,`Validation failure${c?` (${c})`:""}:
|
|
169
|
+
${r}`].filter(Boolean).join(`
|
|
170
|
+
|
|
171
|
+
`)}function er(s,a){typeof window>"u"||window.dispatchEvent(new CustomEvent("semaphor:inline-query-writer",{detail:{event:s,...a,timestamp:Date.now()}}))}const Zt={runId:0,phase:"idle",attempt:0,activeStep:"",timelineSteps:[],lastValidation:null,finalOutcome:"idle",hasTools:!1};function tr(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 ln(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 on(s){return s==="getTableColumns"?"Discovering columns":s==="getDomainRelationships"?"Resolving relationships":s==="getChartSQLSyntax"?"Reviewing SQL syntax":s==="getUserSql"?"Inspecting current query":"Analyzing context"}function sr(s,a){return s===t.SELF_HEAL_TIMELINE_STEP&&a>0?`${t.SELF_HEAL_TIMELINE_STEP} ${a}/${t.MAX_SELF_HEAL_ATTEMPTS}`:s}function Ot(s){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`${s}-${crypto.randomUUID()}`:`${s}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function cn(s){var a;for(let n=s.length-1;n>=0;n-=1){const r=s[n];if(r.role!=="user")continue;const c=(a=r.metadata)==null?void 0:a.inlineRunToken;if(typeof c=="string"&&c.length>0)return c}}function nr(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 dn(s){for(let a=s.length-1;a>=0;a-=1){const n=s[a];if(!(n.role!=="assistant"||!Array.isArray(n.parts)))for(let r=n.parts.length-1;r>=0;r-=1){const c=n.parts[r];if((c==null?void 0:c.type)!=="text"||typeof(c==null?void 0:c.text)!="string")continue;const i=nr(c.text);if(i)return i}}return""}function ar({currentSql:s,currentPython:a,selectedDatabaseName:n,selectedSchemaName:r,selectedTableName:c,onApplySql:i,onOpenFullAssistant:l}){var Mt,Nt;const{authToken:d,tokenProps:o}=t.useSemaphorContext(),u=(Mt=t.useDashboardQuery().data)==null?void 0:Mt.assistantProfileId,p=t.useEditorStore(q=>q.isDevMode),h=t.useEditorStore(q=>q.selectedConnectionId),x=t.useEditorStore(q=>{var W;return(W=q.card.dataSource)==null?void 0:W.selectedEntities}),m=t.useAIInteractionStore(q=>q.currentAIContext.selectedEntities),g=m.length,{setCurrentAIContext:b}=t.useAIActions(),[j,w]=y.useState(""),[T,P]=y.useState(""),[N,A]=y.useState(""),[S,I]=y.useState("draft"),[D,M]=y.useState("draft"),[v,R]=y.useState(""),[C,k]=y.useState(!1),[F,f]=y.useState({status:"idle"}),[L,E]=y.useState(Zt),[O,B]=y.useState(!1),[V,z]=y.useState(()=>Ot("inline-query-session")),_=y.useRef(null),U=y.useRef(null),H=y.useRef(null),$=y.useRef(0),Z=y.useRef(0),re=y.useRef(Ot("inline-run-token")),ie=y.useRef(V),ce=y.useRef(new Set),he=y.useRef(new Map),me=y.useRef(0),se=y.useRef(""),be=y.useRef(!1),je=y.useRef(!1),ye=y.useRef(Zt),X=y.useRef(!1),ge=y.useRef(null),ee=y.useRef(()=>{}),Te=(Nt=o.apiServiceUrl)==null?void 0:Nt.replace(/\/$/,""),Le=Te?`${Te}/v1/sql/validate`:"/v1/sql/validate",Ae=y.useCallback(q=>{E(W=>{const J=q(W);return ye.current=J,J})},[]),Ee=y.useCallback((q,W)=>{Ae(J=>J.runId===q?W(J):J)},[Ae]),Ie=y.useCallback(q=>Z.current===q&&!ce.current.has(q),[]),K=y.useCallback((q,W,J)=>{Ee(q,de=>{const pe=de.timelineSteps.includes(W)?de.timelineSteps:[...de.timelineSteps,W];return{...de,phase:(J==null?void 0:J.phase)||de.phase,attempt:typeof(J==null?void 0:J.attempt)=="number"?J.attempt:de.attempt,activeStep:W,timelineSteps:pe,finalOutcome:(J==null?void 0:J.finalOutcome)||de.finalOutcome,hasTools:J!=null&&J.hasTools?!0:de.hasTools}})},[Ee]),le=y.useCallback(()=>{const q=Z.current+1,W=Ot("inline-run-token"),J=Ot("inline-query-session");return Z.current=q,re.current=W,ie.current=J,z(J),ce.current=new Set,he.current=new Map,me.current=0,se.current="",X.current=!1,Ae(()=>({runId:q,phase:"drafting",attempt:0,activeStep:"Drafting SQL",timelineSteps:["Drafting SQL"],lastValidation:null,finalOutcome:"drafting",hasTools:!1})),{runId:q,runToken:W,chatSessionId:J}},[Ae]),ve=y.useCallback(()=>{if(be.current||je.current||g>0)return;const q=x||[];if(q.length===0)return;const W=t.useAIInteractionStore.getState().currentAIContext;b({...W,selectedEntities:q}),je.current=!0},[g,x,b]),te=y.useCallback(()=>{be.current=!0},[]),Q=y.useCallback((q,W,J)=>{er(q,{runId:W,attemptCount:typeof(J==null?void 0:J.attemptCount)=="number"?J.attemptCount:me.current,errorCode:J==null?void 0:J.errorCode,hasTools:typeof(J==null?void 0:J.hasTools)=="boolean"?J.hasTools:L.hasTools,entityCount:g,finalOutcome:(J==null?void 0:J.finalOutcome)||L.finalOutcome})},[g,L.finalOutcome,L.hasTools]),ae=y.useCallback((q,W)=>{const J=H.current;if(!J)return;const de={inlineRunToken:W};J({role:"user",parts:[{type:"text",text:q}],metadata:de},{metadata:de})},[]);y.useEffect(()=>{const q=ge.current;!q||q.sessionId!==V||(ge.current=null,ae(q.message,q.runToken))},[V,ae]);const ue=V,Se=y.useCallback(async({toolCall:q})=>{var Pe,Qe,rt,st,ze,ft;if(ue!==ie.current)return;const W=String(q.toolName||"").trim();if(!W)return;const J=Z.current;if(!Ie(J)){(Pe=U.current)==null||Pe.call(U,{tool:W,toolCallId:q.toolCallId,output:{status:"error",message:"Inline run is no longer active; ignoring tool output."}});return}if(W==="getUserSql"){K(J,on(W),{hasTools:!0}),Q("inline_tool_step",J,{hasTools:!0}),(Qe=U.current)==null||Qe.call(U,{tool:W,toolCallId:q.toolCallId,output:{status:"success",sql:s||"",python:a||""}});return}const de=t.INLINE_BLOCKED_MUTATING_TOOLS.has(W),pe=t.INLINE_ALLOWED_READ_ONLY_TOOLS.has(W);if(de||!pe){(rt=U.current)==null||rt.call(U,{tool:W,toolCallId:q.toolCallId,output:{status:"error",message:"This action is unavailable in inline draft mode. Open Full Assistant for this action."}});return}const fe=on(W);K(J,fe,{phase:L.phase==="self-healing"?"self-healing":"drafting",hasTools:!0}),Q("inline_tool_step",J,{hasTools:!0});const Fe=((st=q.input)==null?void 0:st.sql)??((ze=q.args)==null?void 0:ze.sql);typeof Fe=="string"&&Fe.trim().length>0&&(X.current=!1,A(Fe.trim())),(ft=U.current)==null||ft.call(U,{tool:W,toolCallId:q.toolCallId,output:{status:"success",message:"Read-only tool result received."}})},[a,s,Q,L.phase,Ie,ue,K]),Ne=y.useCallback(({message:q,messages:W})=>{if(ue!==ie.current)return;const J=cn(W);if(!J||J!==re.current)return;const de=Z.current;if(!Ie(de))return;const pe=dn([q])||dn(W);if(pe){X.current=!1,A(pe.trim());return}X.current&&ye.current.phase==="self-healing"&&ee.current(de)},[Ie,ue]),Oe=y.useCallback(q=>{if(ue!==ie.current)return;const W=Z.current;Ie(W)&&X.current&&ye.current.phase==="self-healing"&&ee.current(W)},[Ie,ue]),{setMessages:Ve,sendMessage:We,addToolResult:Je,status:Ye,stop:ne,error:De,clearError:Be}=t.useChat({id:V,transport:new t.DefaultChatTransport({api:`${o.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${d==null?void 0:d.accessToken}`}),body:()=>{const q=t.useAIInteractionStore.getState();return{assistantId:"editor-assistant",assistantProfileId:u,isDevMode:p,aiContext:q.currentAIContext,reasoningEffort:q.reasoningEffort,showReasoning:!1}},credentials:"omit",prepareSendMessagesRequest:({messages:q,body:W,requestMetadata:J})=>{const de=J==null?void 0:J.inlineRunToken,pe=cn(q);return{body:{...W,inlineRunToken:de||pe,messages:t.cleanupIncompleteMessages(q)}}}}),onToolCall:Se,onFinish:Ne,onError:Oe,sendAutomaticallyWhen:t.lastAssistantMessageIsCompleteWithToolCalls});U.current=Je,H.current=We;const Ce=!["ready","error"].includes(Ye),Ge=(De==null?void 0:De.message)||"Unable to generate a SQL draft right now. Try again.",we=y.useCallback(q=>{const W=Z.current,J=ye.current.phase;if(!(J==="drafting"||J==="self-healing"||J==="validating")){q==="stopped"&&Ce&&ne();return}ce.current.add(W),X.current=!1,$.current+=1,se.current="",f({status:"idle"}),A(""),Be(),Ve([]),Ee(W,pe=>({...pe,phase:"idle",activeStep:"",finalOutcome:"cancelled"})),Q("inline_self_heal_stopped",W,{finalOutcome:"cancelled"}),(Ce||q==="stopped")&&ne()},[Be,Q,Ce,Ve,ne,Ee]),bt=y.useCallback(async(q,W)=>{var de;if(!Ie(W))return null;const J=$.current+1;$.current=J,K(W,"Validating SQL",{phase:"validating"}),f({status:"validating"});try{const pe=await t.postRequestRegular(Le,(d==null?void 0:d.accessToken)||"",{sql:q,connectionId:h||void 0});if($.current!==J||!Ie(W))return null;if((pe==null?void 0:pe.valid)===!0)return f({status:"valid",message:"SQL validation passed."}),Ee(W,Pe=>({...Pe,phase:"ready",finalOutcome:"validated",lastValidation:{valid:!0}})),Q("inline_draft_validated",W,{finalOutcome:"validated"}),{status:"valid"};const fe=tr(pe==null?void 0:pe.errorCode)||"UNKNOWN",Fe=typeof(pe==null?void 0:pe.error)=="string"&&pe.error||typeof((de=pe==null?void 0:pe.details)==null?void 0:de.error)=="string"&&pe.details.error||"SQL validation failed. Please revise the query draft.";return f({status:"invalid",message:Fe,errorCode:fe}),Ee(W,Pe=>({...Pe,lastValidation:{valid:!1,error:Fe,errorCode:fe}})),Q("inline_validation_failed",W,{errorCode:fe,finalOutcome:"validation_failed"}),{status:"invalid",error:Fe,errorCode:fe}}catch(pe){if($.current!==J||!Ie(W))return null;const fe=t.getRequestErrorMessage(pe,"Validation service unavailable. You can still replace and run.");return f({status:"error",message:fe,errorCode:"SQL_CONNECTION_ERROR"}),Ee(W,Fe=>({...Fe,phase:"error",finalOutcome:"error",lastValidation:{valid:!1,error:fe,errorCode:"SQL_CONNECTION_ERROR"}})),{status:"error",error:fe,errorCode:"SQL_CONNECTION_ERROR"}}},[d==null?void 0:d.accessToken,Q,Ie,h,Le,Ee,K]),Xe=y.useCallback((q,W,J,de)=>{let pe=J,fe="validation_failed",Fe="Validating SQL";W==="attempt_limit"?(pe=`Couldn't auto-fix after ${t.MAX_SELF_HEAL_ATTEMPTS} attempts. ${J}`,fe="self_heal_exhausted",Fe=`Auto-fix stopped (${t.MAX_SELF_HEAL_ATTEMPTS} attempts)`):W==="duplicate"&&(pe=`Auto-fix stopped (repeated validation failure). ${J}`,fe="self_heal_duplicate_stopped",Fe="Auto-fix stopped (repeated failure)"),f({status:"invalid",message:pe,errorCode:de}),K(q,Fe,{phase:"error",finalOutcome:fe}),Ee(q,Pe=>({...Pe,phase:"error",finalOutcome:fe,lastValidation:{valid:!1,error:pe,errorCode:de}})),W!=="terminal"&&Q("inline_self_heal_stopped",q,{errorCode:de,finalOutcome:fe}),X.current=!1},[Q,Ee,K]),Tt=y.useCallback(q=>{const W="Auto-fix stopped (no SQL returned). Open Full Assistant to continue.",J="self_heal_no_draft";f({status:"invalid",message:W,errorCode:"UNKNOWN"}),K(q,"Auto-fix stopped (no SQL returned)",{phase:"error",finalOutcome:J}),Ee(q,de=>({...de,phase:"error",finalOutcome:J,lastValidation:{valid:!1,error:W,errorCode:"UNKNOWN"}})),Q("inline_self_heal_stopped",q,{errorCode:"UNKNOWN",finalOutcome:J}),X.current=!1},[Q,Ee,K]);ee.current=Tt,y.useEffect(()=>{const q=N.trim(),W=Z.current;if(!q){if($.current+=1,se.current="",ye.current.phase==="error")return;f({status:"idle"});return}if(!Ie(W)||Ce)return;const J=`${W}:${me.current}:${ln(q)}`;if(se.current===J)return;se.current=J;let de=!1;return(async()=>{const fe=await bt(q,W);if(!fe||de||!Ie(W)||fe.status!=="invalid")return;if(!t.RECOVERABLE_SQL_ERROR_CODES.has(fe.errorCode)){Xe(W,"terminal",fe.error,fe.errorCode);return}const Fe=`${ln(q)}::${fe.errorCode}`,Pe=(he.current.get(Fe)||0)+1;if(he.current.set(Fe,Pe),Pe>=2){Xe(W,"duplicate",fe.error,fe.errorCode);return}if(me.current>=t.MAX_SELF_HEAL_ATTEMPTS){Xe(W,"attempt_limit",fe.error,fe.errorCode);return}const Qe=me.current+1;me.current=Qe,K(W,t.SELF_HEAL_TIMELINE_STEP,{phase:"self-healing",attempt:Qe}),Q("inline_self_heal_attempt",W,{attemptCount:Qe,errorCode:fe.errorCode}),X.current=!0,Be(),Ve([]),A("");const rt=m.map(ze=>{const ft=ze!=null&&ze.database?`${ze.database}.`:"",Jt=ze!=null&&ze.schema?`${ze.schema}.`:"",Yt=(ze==null?void 0:ze.name)||"unknown";return`${ft}${Jt}${Yt}`}),st=Za({request:T,failedSql:q,errorMessage:fe.error,errorCode:fe.errorCode,selectedDatabaseName:n||"",selectedSchemaName:r||"",selectedTableName:c||"",contextEntityLabels:rt});ae(st,re.current)})(),()=>{de=!0}},[Be,m,Q,Ce,Ie,T,N,n,r,c,ae,Ve,Xe,K,bt]);const Ue=(s==null?void 0:s.trim())||"",Et=y.useCallback((q="draft")=>{if(Ce)return;const W=j.trim();if(!W)return;const J=q==="refine"&&Ue?"refine":"draft",de=J==="refine"?Ue:"",pe=Ue,{runId:fe,runToken:Fe,chatSessionId:Pe}=le();Q("inline_draft_started",fe,{attemptCount:0,hasTools:!1,finalOutcome:"drafting"}),ve(),Be(),P(W),A(""),I(J),R(de),k(!1),f({status:"idle"}),$.current+=1,Ve([]),B(!0);const Qe=Xa({request:W,mode:J,currentSql:pe,selectedTableName:c||"",selectedSchemaName:r||"",selectedDatabaseName:n||""});ge.current={sessionId:Pe,message:Qe,runToken:Fe}},[le,Be,Ue,Q,Ce,j,ve,n,r,c,Ve]),ct=y.useCallback(q=>{const W=N.trim();W&&(i(W,q),q||B(!1))},[i,N]),Ze=N.trim().length>0,It=["valid","invalid","error"].includes(F.status),vt=Ze&&It,Kt=F.status==="invalid",Dt=F.status==="validating",dt=Ze&&T.length>0&&T===j.trim(),ut=Ue.length>0,mt=j.length>0,xt=dt&&S==="draft",$e=dt&&S==="refine"&&v===Ue,et=D==="refine"&&!ut?"draft":D,tt=(et==="refine"?$e:xt)?"Open composer preview":"Generate composer SQL",kt=j.trim().length>0||T.trim().length>0||Ze||F.status!=="idle"||L.timelineSteps.length>0,yt=y.useCallback((q="draft")=>{if(Ce)return;if((q==="refine"?$e:xt)&&!O){ve(),B(!0);return}Et(q)},[xt,$e,Et,Ce,O,ve]),ht=y.useCallback(()=>{ve(),B(!0)},[ve]),Ut=y.useCallback(q=>{we("cancelled"),w(q)},[we]),Ht=y.useCallback(()=>{Ce||(we("cancelled"),X.current=!1,$.current+=1,se.current="",me.current=0,w(""),P(""),A(""),I("draft"),M("draft"),R(""),k(!1),f({status:"idle"}),Be(),Ve([]),Ae(q=>({...Zt,runId:q.runId})))},[we,Be,Ce,Ve,Ae]),Qt=y.useCallback(q=>{q||we("cancelled"),B(q)},[we]),Ke=L.timelineSteps.findIndex(q=>q===L.activeStep),At=L.phase==="self-healing"?"Fixing validation issue":L.phase==="validating"?"Validating SQL":L.activeStep||"Drafting SQL",pt=F.status==="valid"?{label:"Validation passed",className:"border-emerald-500/30 bg-emerald-500/10 text-emerald-700",detail:F.message}:F.status==="invalid"?{label:"Validation failed",className:"border-destructive/40 bg-destructive/10 text-destructive",detail:F.message}:F.status==="error"?{label:"Validation unavailable",className:"border-border/60 bg-muted/20 text-muted-foreground",detail:F.message}:null;return e.jsxs("div",{ref:_,className:"relative flex h-7 min-w-[320px] flex-1 items-center",children:[e.jsx(t.Input,{value:j,onChange:q=>Ut(q.target.value),onFocus:ht,onClick:ht,onKeyDown:q=>{q.key==="Enter"&&(q.preventDefault(),yt(et))},placeholder:"Type your question...",className:["h-7 rounded-[5px] border border-border/60 bg-background text-[12px] shadow-none focus-visible:border-ring focus-visible:ring-0",mt?"pr-[56px]":"pr-9"].join(" ")}),e.jsxs(t.Popover,{open:O,onOpenChange:Qt,children:[e.jsx(t.PopoverAnchor,{asChild:!0,children:e.jsx("div",{className:"pointer-events-none absolute inset-0"})}),e.jsxs("div",{className:"absolute right-1 flex items-center gap-1",children:[mt&&e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"size-6 p-0",onClick:q=>{q.preventDefault(),we("cancelled"),w("")},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:q=>{q.preventDefault(),yt(et)},disabled:Ce,"aria-label":tt,title:tt,children:e.jsx(Ea,{className:"size-3.5"})})]}),e.jsx(t.PopoverContent,{align:"start",alignOffset:0,side:"bottom",sideOffset:8,className:"w-[min(92vw,var(--radix-popover-trigger-width))] max-w-[760px] p-2.5",onOpenAutoFocus:q=>{q.preventDefault()},onInteractOutside:q=>{var J;const W=q.target;W&&((J=_.current)!=null&&J.contains(W))&&q.preventDefault()},children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[13px] font-medium",children:"Composer"}),T&&e.jsx("p",{className:"line-clamp-2 text-[11px] text-muted-foreground",children:T})]}),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:()=>{M("draft"),k(!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:()=>M("refine"),disabled:!ut,children:"Refine Current"})]}),e.jsx("div",{className:"h-4 w-px bg-border/70"}),Ce&&e.jsx(t.Button,{variant:"ghost",size:"xs",onClick:()=>{we("stopped")},children:"Stop"}),!Ce&&e.jsx(t.Button,{variant:"ghost",size:"xs",onClick:Ht,disabled:!kt,children:"Clear"})]})]}),L.timelineSteps.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[L.timelineSteps.map((q,W)=>{const J=q===L.activeStep&&["drafting","validating","self-healing"].includes(L.phase),de=!J&&Ke>=0&&W<Ke;return e.jsx("span",{className:["rounded-full border px-2 py-0.5 text-[11px]",J?"border-foreground/30 bg-foreground/10 text-foreground":de?"border-border/60 bg-muted/20 text-muted-foreground":"border-border/50 bg-background text-muted-foreground/80"].join(" "),children:sr(q,L.attempt)},`${q}-${W}`)}),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:te})}),(Ce||L.phase==="self-healing"||F.status==="validating")&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border/60 bg-muted/20 px-3 py-2 text-xs text-muted-foreground",children:[e.jsx(t.LoaderCircle,{className:"size-3.5 animate-spin"}),At]}),De&&e.jsx("div",{className:"rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-xs text-destructive",children:Ge}),S==="refine"&&v&&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:()=>k(q=>!q),children:C?"Hide base SQL":"View base SQL"})]}),C&&e.jsx("div",{className:"max-h-[120px] overflow-auto rounded-[5px] border border-border/60",children:e.jsx(t.CodeHighlighter,{code:v,language:"sql"})})]}),vt?e.jsxs("div",{className:"space-y-1",children:[S==="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:N,language:"sql"})})]}):Ze?e.jsx("div",{className:"rounded-[5px] border border-dashed border-border/70 px-3 py-2 text-[11px] text-muted-foreground",children:"Validating SQL draft before preview."}):!Ce&&e.jsx("div",{className:"rounded-[5px] border border-dashed border-border/70 px-3 py-2 text-[11px] text-muted-foreground",children:ut?"Choose Draft New or Refine Current, then press Enter or click send.":"Describe what you want to query, then press Enter or click send to generate a SQL preview."}),e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-1.5",children:[e.jsx(t.Button,{variant:"outline",size:"xs",onClick:l,children:"Open Full Assistant"}),e.jsx(t.Button,{variant:"secondary",size:"xs",disabled:Ce||!vt,onClick:()=>ct(!1),children:"Replace SQL"}),e.jsx(t.Button,{size:"xs",disabled:Ce||!vt||Dt||Kt,onClick:()=>ct(!0),children:"Replace & Run"})]})]})})]})]})}function rr(){var je,ye;const s=t.useQueryClient(),[a,n]=y.useState(!1),r=t.useEditorStore(X=>X.frame),c=t.useEditorStore(X=>X.card);t.useEditorStore(X=>X.isShowingVisual),t.useEditorStore(X=>X.selectedConnectionId),t.useEditorStore(X=>X.tempQueryData);const i=t.useEditorStore(X=>X.selectedDatabaseName);t.useEditorStore(X=>X.selectedDatamodelId);const l=t.useEditorStore(X=>X.selectedSchemaName);t.useEditorStore(X=>X.showAIDialog);const d=t.useEditorStore(X=>X.selectedTableName),o=t.useDashboardStore(X=>{var ge,ee;return((ee=(ge=X.dashboard)==null?void 0:ge.filters)==null?void 0:ee.length)??0}),{cardFilterValues:u}=t.useCardFilterValues((c==null?void 0:c.id)??""),p=t.useEditorStore(X=>X.inlineFilterValuesMap[(c==null?void 0:c.id)??""]),h=y.useMemo(()=>t.findCustomVisualConfigCard(r,c),[r,c]),{manifest:x}=t.useCustomVisual(((je=h==null?void 0:h.customCardPreferences)==null?void 0:je.url)||""),m=y.useMemo(()=>{var X;return(X=x==null?void 0:x.visuals)==null?void 0:X.find(ge=>{var ee;return ge.name===((ee=h==null?void 0:h.customCardPreferences)==null?void 0:ee.componentName)})},[x,(ye=h==null?void 0:h.customCardPreferences)==null?void 0:ye.componentName]),g=t.resolveMultiInputType(h,m),b=y.useMemo(()=>t.getCustomVisualInputCards({frame:r,configCard:h,isMultiInputVisual:g==="multiple"}),[r,h,g]),j=y.useMemo(()=>{const X=b.findIndex(ge=>(ge==null?void 0:ge.id)===(c==null?void 0:c.id));return X<0?-1:t.getSlotIndexForCard(c,X)},[b,c]),w=y.useMemo(()=>!h||g!=="multiple"||j<0?c.type:t.getEffectiveCardTypeForSlot(c,j,m==null?void 0:m.slots)??c.type,[h,g,j,c,m==null?void 0:m.slots]),T=y.useMemo(()=>w!==c.type?{...c,type:w}:c,[c,w]),P=y.useMemo(()=>o===0?null:Wa(c==null?void 0:c.sql),[c==null?void 0:c.sql,o]),N=y.useRef(!0),{setCardCustomCfg:A,setQueryResultColumns:S,setCardSql:I,setTempQueryData:D,setPythonStdOut:M,setCardPreferences:v,setCardType:R,setCardPython:C,setShowAIDialog:k,setCard:F,updateCardInFrame:f}=t.useEditorActions();t.useEditorStore(X=>X.onSave),t.useEditorStore(X=>X.onClose),t.useEditorStore(X=>X.actions.setSqlGen);const L=t.useEditorStore(X=>X.runSql),E=t.useEditorStore(X=>X.actions.setRunSql),O=t.useEditorStore(X=>X.actions.setIsSqlRunning),{data:B,isLoading:V,isFetching:z,isSuccess:_,isError:U,error:H,errorSql:$,queryKey:Z,refetch:re,errorMessage:ie}=t.useEditorCardQuery(T),ce=y.useRef(Z);ce.current=Z,y.useEffect(()=>{if(B&&(B.rowLimitExceeded&&t.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),M((B==null?void 0:B.output)||""),B.records.length>0)){const{dimensionKeys:X}=t.getKeys(B.records);S(X)}},[B,S,M]),y.useEffect(()=>{(V||z)&&O(!0),(U||_)&&O(!1),U&&(S([]),M(""))},[V,z,B,M,U,_,O,S,H]),y.useEffect(()=>{L&&(s.getQueryData(Z)||re(),E(!1))},[L,re,E,Z,s]);const he=y.useRef(re);he.current=re,y.useEffect(()=>{if(N.current){N.current=!1;return}he.current()},[p]);function me(X,ge){I(X),ge&&E(!0)}function se(){return e.jsxs(t.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(t.ResizablePanel,{id:"1",order:1,defaultSize:a?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(_a,{})}),a&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),a&&e.jsxs(e.Fragment,{children:[e.jsx(t.ResizableHandle,{withHandle:!0,className:"data-[panel-group-direction=vertical]:ml-2 data-[panel-group-direction=vertical]:mr-6 data-[panel-group-direction=vertical]:w-auto"}),e.jsxs(t.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:[e.jsx("div",{id:"python-container",className:"relative flex w-[99%] pt-0",children:e.jsx($a,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function be(){return e.jsxs("div",{role:"editor-controls",className:"item-center flex w-full flex-wrap items-center gap-2 py-3 pl-2 pr-6",children:[P&&e.jsxs("div",{className:"mb-1.5 mr-6 flex w-full items-center gap-1.5 px-1 text-[11px] text-muted-foreground",children:[e.jsx(t.Filter,{className:"h-3 w-3 shrink-0"}),e.jsxs("span",{className:"min-w-0 truncate",children:["Not subscribed to dashboard filters. Add"," ",e.jsx("code",{className:"rounded-[4px] bg-muted px-1 py-0.5 font-mono text-[10px] text-foreground",children:P.helper})," ","to this query."," ",e.jsx("a",{href:"https://docs.semaphor.cloud/docs/concepts/filters",target:"_blank",rel:"noreferrer",className:"underline-offset-2 hover:text-foreground hover:underline",children:"Learn more ↗"})]})]}),e.jsxs("div",{className:"flex w-full items-center gap-3",children:[e.jsxs(t.Button,{title:"Shift + Enter",disabled:V||z,onClick:()=>{it.flushPendingEditorDrafts(),setTimeout(()=>{s.removeQueries({queryKey:ce.current,exact:!0}),E(!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"]}),(B==null?void 0:B.sql)&&!ie&&e.jsxs(t.HoverCard,{openDelay:300,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,children:e.jsx(t.Info,{className:"h-3.5 w-3.5 shrink-0 cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(t.HoverCardContent,{align:"start",className:"w-[500px] p-0",children:e.jsx(On,{sql:B.sql})})]}),e.jsx(ke.EditorClearButton,{}),e.jsxs(t.Toggle,{pressed:a,onPressedChange:X=>n(X),className:"h-7 gap-1.5 rounded-[5px] px-2.5 text-[12px]",size:"sm",variant:"outline",children:[e.jsx(Va,{className:"h-3.5 w-3.5 text-foreground/70"}),"Python"]}),e.jsx(ar,{currentSql:c==null?void 0:c.sql,currentPython:c==null?void 0:c.python,selectedDatabaseName:i,selectedSchemaName:l,selectedTableName:d,onApplySql:me,onOpenFullAssistant:()=>k(!0)}),e.jsx("div",{className:"ml-auto flex shrink-0 items-center gap-3",children:u&&u.length>0&&e.jsxs(t.HoverCard,{openDelay:200,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",size:"xs",className:"px-2",children:[e.jsx(t.Filter,{className:"h-3.5 w-3.5"}),e.jsx(t.Badge,{variant:"secondary",className:"h-4 min-w-4 rounded-[4px] px-1 text-[10px] font-medium",children:u.length})]})}),e.jsx(t.HoverCardContent,{className:"mr-4 max-h-[400px] w-[500px] overflow-auto p-0",children:e.jsxs("div",{className:"p-3",children:[e.jsx("div",{className:"mb-2 text-[13px] font-medium",children:"Active Dashboard Filters"}),e.jsx(t.CodeHighlighter,{code:JSON.stringify(u,null,2),language:"json"})]})})]})})]})]})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsx("div",{className:"relative flex grow overflow-y-scroll",children:se()}),be()]})}function lr(s,a){var i;let n=0,r=0;const c=Math.min(s.length,50);for(let l=0;l<c;l++){const d=(i=s[l])==null?void 0:i[a];if(!(d==null||d==="")){if(r++,typeof d=="number"||typeof d=="bigint")n++;else if(typeof d=="boolean")return"boolean"}}return r===0?"null":n/r>.7?"number":"text"}function or(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 ir({data:s,card:a,paginationMetadata:n,onPaginationChange:r,onPageSizePreferenceChange:c,onSortChange:i,isLoading:l}){var D,M,v,R,C,k;const d=y.useMemo(()=>Object.keys(s[0]??{}),[s]),o=a.sql&&!((M=(D=a.preferences)==null?void 0:D.tablePrefs)!=null&&M.enableDevModePagination)?(R=(v=a.preferences)==null?void 0:v.tablePrefs)==null?void 0:R.pageSize:void 0,u=y.useMemo(()=>{var F;return t.sortByColumnsToSortState((F=a.config)==null?void 0:F.sortByColumns)},[(C=a.config)==null?void 0:C.sortByColumns]),{canSort:p,canUseLocalSorting:h,handlePaginationChange:x,handleSortChange:m,pagination:g,paginationMode:b,sorting:j}=t.useTableQueryState({card:a,dataLength:s.length,onPaginationChange:r,onSortChange:i,pageSize:o,paginationMetadata:n,sortState:u}),w=y.useMemo(()=>j.filter(F=>d.includes(F.id)),[j,d]),T=y.useMemo(()=>{const F={};for(const f of d)F[f]=lr(s,f);return F},[d,s]),P=y.useMemo(()=>d.map(F=>{const L=T[F]==="number";return{accessorKey:F,enableSorting:p,header:({column:E})=>{const O=E.getIsSorted();return e.jsxs("div",{className:t.cn("flex select-none items-center gap-1.5 transition-colors",E.getCanSort()&&"cursor-pointer hover:text-foreground",L&&"justify-end"),onClick:()=>E.getCanSort()&&E.toggleSorting(E.getIsSorted()==="asc"),children:[e.jsx("span",{children:F}),O==="asc"?e.jsx(t.ArrowUpIcon,{className:"h-3.5 w-3.5 shrink-0 text-foreground"}):O==="desc"?e.jsx(t.ArrowDownIcon,{className:"h-3.5 w-3.5 shrink-0 text-foreground"}):E.getCanSort()?e.jsx(t.ChevronsUpDown,{className:"h-3 w-3 shrink-0 opacity-0 transition-opacity group-hover/header:opacity-50"}):null]})},cell:({getValue:E})=>{const O=E(),B=O===null;return e.jsx("div",{className:t.cn("whitespace-pre-wrap break-all",L&&"text-right tabular-nums",B&&"text-muted-foreground/50 italic"),children:or(O)})}}}),[p,T,d]),N=Math.max(P.length,1),A=t.useReactTable({data:s,columns:P,getCoreRowModel:t.getCoreRowModel(),getPaginationRowModel:b==="client"?t.getPaginationRowModel():void 0,onSortingChange:m,getSortedRowModel:h?t.getSortedRowModel():void 0,onPaginationChange:b==="disabled"?void 0:x,manualPagination:b==="server"||b==="disabled",manualSorting:!h,pageCount:b==="server"&&n?n.pageCount:void 0,state:{sorting:w,pagination:g}}),S=b==="server"&&n?n.totalCount:s.length,I=b!=="disabled"&&(b==="server"||S>10);return e.jsxs("div",{className:"relative flex h-full w-full min-h-0 flex-col",children:[l&&e.jsx("div",{className:"absolute inset-0 z-20 flex items-center justify-center bg-background/50",children:e.jsx(t.LoaderCircle,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),e.jsxs(t.CustomScrollArea,{className:"min-h-0 grow overflow-auto text-foreground",children:[e.jsxs("table",{className:"w-full",children:[e.jsx(t.TableHeader,{className:"sticky top-0 z-10",children:A.getHeaderGroups().map(F=>e.jsx(t.TableRow,{className:"border-b-0 hover:bg-transparent",children:F.headers.map(f=>{const E=T[f.id]==="number";return e.jsx(t.TableHead,{className:t.cn("group/header h-9 border-b bg-muted px-3 font-mono text-xs font-medium text-foreground",E&&"text-right"),children:f.isPlaceholder?null:t.flexRender(f.column.columnDef.header,f.getContext())},f.id)})},F.id))}),e.jsx(t.TableBody,{className:"font-mono",children:(k=A.getRowModel().rows)!=null&&k.length?A.getRowModel().rows.map((F,f)=>e.jsx(t.TableRow,{className:t.cn("h-[34px] border-b border-border/40 transition-colors",f%2===1&&"bg-muted/20"),"data-state":F.getIsSelected()&&"selected",children:F.getVisibleCells().map(L=>{const O=T[L.column.id]==="number";return e.jsx(t.TableCell,{className:t.cn("px-3 py-1.5 text-xs",O&&"text-right"),children:t.flexRender(L.column.columnDef.cell,L.getContext())},L.id)})},F.id)):e.jsx(t.TableRow,{children:e.jsx(t.TableCell,{colSpan:N,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:I?e.jsx(t.DataTablePagination,{totalColumns:d.length,pageCount:b==="server"&&n?n.pageCount:A.getPageCount(),pageIndex:A.getState().pagination.pageIndex,pageSize:A.getState().pagination.pageSize,rowCount:S,selectedRowCount:0,setPageIndex:A.setPageIndex,setPageSize:A.setPageSize,canPreviousPage:b==="server"&&n?n.hasPrevPage:A.getCanPreviousPage(),canNextPage:b==="server"&&n?n.hasNextPage:A.getCanNextPage(),previousPage:A.previousPage,nextPage:A.nextPage,onPageSizePreferenceChange:c,onClearSelection:()=>{},paginationMode:b,showExport:!1}):e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-[11px] tabular-nums text-muted-foreground",children:[S.toLocaleString()," ",S===1?"row":"rows"," · ",d.length," ",d.length===1?"column":"columns"]}),w.length>0&&e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["Sorted by"," ",e.jsx("span",{className:"font-medium text-foreground/70",children:w[0].id})," ",w[0].desc?"↓":"↑"]})]})})]})}const un=[{value:"table",label:"Table",icon:t.Table2},{value:"aggregateTable",label:"Aggregate",icon:t.Layers},{value:"pivotTable",label:"Pivot",icon:t.Grid3x3},{value:"detailTable",label:"Detail",icon:t.List}];function cr({className:s}){const a=t.useEditorStore(m=>m.card),n=t.useEditorStore(m=>m.frame),r=t.useEditorStore(m=>m.editorContext),c=ke.useEffectiveEditorCardType(),{setCard:i,updateCardInFrame:l}=t.useEditorActions(),d=(r==null?void 0:r.type)==="documentSection"?un.filter(m=>["table","pivotTable"].includes(m.value)):un,o=["table","aggregateTable","pivotTable","detailTable"].includes(c),u=t.hasValidCardConfig(a.config),p=t.isCustomVisualConfigCard(a,n.cards);if(!o||!u||p)return null;const h=m=>{if(p)return;const g=m,b=a.config??{},j=x(c,g,b),w={...a,type:g,config:j};i(w),l(w)},x=(m,g,b)=>{var w;if(g==="detailTable"){const T=S=>S==null?void 0:S.toLowerCase().replace(/\s+/g,"").trim(),P=(S,I)=>{const D=[T(S.label),T(S.qualifiedFieldName),T(S.name)].filter(Boolean),M=[T(I.label),T(I.qualifiedFieldName),T(I.name)].filter(Boolean);return D.some(v=>M.includes(v))},N=(b.groupByColumns||[]).map(S=>({...S,role:"detail"})),A=((w=b.sortByColumns)==null?void 0:w.filter(S=>N.some(I=>P(S,I))))??[];return{...b,detailTableBackup:{groupByColumns:b.groupByColumns,metricColumns:b.metricColumns,pivotByColumns:b.pivotByColumns,sortByColumns:b.sortByColumns,rowAggregates:b.rowAggregates,columnAggregates:b.columnAggregates,comparisonType:b.comparisonType},detailColumns:N,groupByColumns:[],metricColumns:[],pivotByColumns:[],sortByColumns:A,rowAggregates:[],columnAggregates:[],comparisonType:"none"}}let j=b;if(m==="detailTable")if(b.detailTableBackup)j={...b,...b.detailTableBackup,detailColumns:[],detailTableBackup:void 0};else{const T=(b.detailColumns||[]).map(P=>({...P,role:"groupby"}));j={...b,groupByColumns:T,detailColumns:[]}}return g==="aggregateTable"?{...j,pivotByColumns:[]}:j};return e.jsx("div",{className:t.cn("flex items-center",s),children:e.jsx(t.RadioGroup,{value:c,onValueChange:h,className:"flex flex-row items-center gap-1 border-b border-border/60",children:d.map(m=>{const g=m.icon,b=c===m.value;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(t.RadioGroupItem,{value:m.value,id:`table-type-${m.value}`,className:"peer sr-only"}),e.jsxs(t.Label,{htmlFor:`table-type-${m.value}`,className:t.cn("flex h-8 cursor-pointer items-center justify-center gap-1.5 whitespace-nowrap border-b-2 border-transparent px-2 pb-1 text-xs font-medium transition-colors",b?"border-foreground text-foreground":"text-muted-foreground hover:border-foreground/30 hover:text-foreground"),children:[e.jsx(g,{className:t.cn("h-3.5 w-3.5",b?"opacity-100":"opacity-75")}),m.label]})]},m.value)})})})}const mn="text-[11px] text-muted-foreground underline-offset-2 hover:text-foreground hover:underline";function ds({error:s,errorSql:a,errorTitle:n="Unable to load data",onOpenInEditor:r,onDebugWithAssistant:c,onSendFeedback:i,showFeedbackButton:l=!0,className:d}){const[o,u]=y.useState(!1),x=!!c||!!(r&&a);return e.jsxs("div",{className:t.cn("w-full space-y-3 rounded-[6px] border border-border/60 bg-card p-4",d),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.TriangleAlert,{"aria-hidden":!0,className:"h-3.5 w-3.5 shrink-0 text-amber-600 dark:text-amber-500"}),e.jsx("span",{className:"text-[13px] font-medium text-foreground",children:n})]}),e.jsxs("div",{className:"relative rounded-[5px] border border-border/60 bg-background",children:[e.jsx(t.CopyButton,{text:s,className:"absolute right-1.5 top-1.5 z-10 h-6 w-6"}),e.jsx("div",{className:"max-h-60 overflow-auto px-2.5 py-2 pr-9",children:e.jsx("p",{className:"whitespace-pre-wrap break-all font-mono text-[12px] leading-[1.55] text-muted-foreground",children:s})})]}),x&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[c&&e.jsxs(t.Button,{variant:"outline",size:"xs",onClick:c,children:[e.jsx(ba,{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(kn,{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:()=>u(m=>!m),className:mn,children:o?"Hide query details":"Show query details"}),l&&i&&e.jsx("button",{type:"button",onClick:i,className:mn,children:"Report this issue"})]}),a&&e.jsx(t.Collapsible,{open:o,onOpenChange:u,children:e.jsxs(t.CollapsibleContent,{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between pt-1",children:[e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Query"}),e.jsx(t.CopyButton,{text:a,className:"h-6 w-6"})]}),e.jsx("div",{className:"max-h-80 overflow-auto rounded-[5px] border border-border/60 bg-background p-2",children:e.jsx(t.CodeHighlighter,{code:a,language:"sql"})})]})})]})}function Pn(s,a){const n=t.useEditorStore(u=>u.card),r=t.useEditorStore(u=>u.isDevMode),{switchEditorMode:c,setRunSql:i,runAssistant:l}=t.useEditorActions();return{isDevMode:r,handleOpenInEditor:r?void 0:()=>{const u=a||n.sql||n.python||"";c("dev",{sqlToLoad:u}),setTimeout(()=>{i(!0)},100)},handleDebugWithAssistant:r?()=>{const u=`Can you help me debug this query?
|
|
172
|
+
|
|
173
|
+
Error:
|
|
174
|
+
|
|
175
|
+
${s}
|
|
176
|
+
|
|
177
|
+
Error SQL:
|
|
178
|
+
|
|
179
|
+
${a||n.sql||n.python}
|
|
180
|
+
|
|
181
|
+
`;l(u)}:void 0}}function Bn({className:s,...a}){var Ee,Ie,K,le,ve;const n=t.useEditorStore(te=>te.card);t.useEditorStore(te=>te.isDevMode);const r=((Ee=n.customCardPreferences)==null?void 0:Ee.showCardHeader)??!0,c=((K=(Ie=n.preferences)==null?void 0:Ie.displayOptions)==null?void 0:K.showInlineFilterBar)??!0,i=t.useEditorStore(te=>te.frame),l=t.useEditorStore(te=>te.inlineFilterValuesMap[n.id]),d=t.useDashboardStore(te=>te.dashboard.filters),o=t.useDashboardStore(te=>te.selectedSheetId),[u,p]=y.useState(!1),{currentUser:h}=t.useCurrentUserInfo(),{tokenProps:x}=y.useContext(t.SemaphorContext),m=t.useEditorStore(te=>te.actions.setRunSql),g=t.useEditorStore(te=>te.actions.setCardInlineFilterValue),b=t.useEditorStore(te=>te.actions.removeCardInlineFilterValue),{updateFilter:j}=t.useDashboardActions(),w=d==null?void 0:d.find(te=>te.id===i.filterId),T=y.useMemo(()=>t.findCustomVisualConfigCard(i,n),[i,n]),{manifest:P}=t.useCustomVisual(((le=T==null?void 0:T.customCardPreferences)==null?void 0:le.url)||""),N=y.useMemo(()=>{var te;return(te=P==null?void 0:P.visuals)==null?void 0:te.find(Q=>{var ae;return Q.name===((ae=T==null?void 0:T.customCardPreferences)==null?void 0:ae.componentName)})},[P,(ve=T==null?void 0:T.customCardPreferences)==null?void 0:ve.componentName]),A=t.resolveMultiInputType(T,N),S=y.useMemo(()=>t.getCustomVisualInputCards({frame:i,configCard:T,isMultiInputVisual:A==="multiple"}),[i,T,A]),I=y.useMemo(()=>{const te=S.findIndex(Q=>(Q==null?void 0:Q.id)===(n==null?void 0:n.id));return te<0?-1:t.getSlotIndexForCard(n,te)},[S,n]),D=y.useMemo(()=>!T||A!=="multiple"||I<0?n.type:t.getEffectiveCardTypeForSlot(n,I,N==null?void 0:N.slots)??n.type,[T,A,I,n,N==null?void 0:N.slots]),M=D??n.type,v=y.useMemo(()=>M===n.type?n:{...n,type:M},[n,M]),R=y.useMemo(()=>D!==n.type?{...n,type:D}:n,[n,D]),{data:C,isLoading:k,isFetching:F,errorMessage:f,errorSql:L,pagination:E}=t.useEditorCardQuery(R),{handleOpenInEditor:O,handleDebugWithAssistant:B}=Pn(f,L||n.sql||n.python),V=y.useMemo(()=>(C==null?void 0:C.records)||[],[C==null?void 0:C.records]),{setCard:z,updateCardInFrame:_}=t.useEditorActions(),{data:U}=t.useTopoJson(v),H=v.id,$=v.config,Z=v.interactionConfig,re=v.customCfg,ie=v.preferences,ce=v.queryConfig,he=!!v.sql,me=C==null?void 0:C.records,se=y.useMemo(()=>({id:H,type:M,config:$,interactionConfig:Z,sql:he?"__editor_sql__":""}),[H,M,$,Z,he]),be=y.useMemo(()=>{var te;return M!=="pivotTable"||!((te=C==null?void 0:C.records)!=null&&te.length)?null:{records:C.records,columnSubtotalMeta:C.columnSubtotalMeta,subtotalColumns:C.subtotalColumns||[],pivotSchema:C.pivotSchema||[],groupByColumns:C.groupByColumns}},[M,C==null?void 0:C.records,C==null?void 0:C.columnSubtotalMeta,C==null?void 0:C.subtotalColumns,C==null?void 0:C.pivotSchema,C==null?void 0:C.groupByColumns]),je=t.usePivotTableConfig(v,be),ye=()=>{p(!0)},X=y.useMemo(()=>{const te=typeof window<"u"?window.location.href:"",Q=typeof navigator<"u"?navigator.userAgent:"",ae=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:t.FeedbackCategory.QUERY_GENERATION,user:h,tokenContext:x,systemState:{cardConfig:n.config,dataSource:n.dataSource,dashboardFilters:d,errorMessage:f||void 0,errorSql:L||n.sql||n.python,generatedSql:L||n.sql},metadata:{url:te,userAgent:Q,timestamp:new Date().toISOString(),viewport:ae}}},[h,x,n,d,f,L]),ge=(te,Q)=>{var ue,Se;const ae={...n,paginationConfig:{page:te+1,pageSize:Q}};z(ae),_(ae),n.sql&&((Se=(ue=n.preferences)==null?void 0:ue.tablePrefs)!=null&&Se.enableDevModePagination)&&m(!0)},ee=te=>{var ue,Se,Ne,Oe,Ve;const Q=t.sortStateToSortByColumns(te,(ue=n.config)==null?void 0:ue.metricColumns,(Se=n.config)==null?void 0:Se.groupByColumns,(Ne=n.config)==null?void 0:Ne.detailColumns),ae={...n,config:{...n.config||{},sortByColumns:Q}};z(ae),_(ae),n.sql&&((Ve=(Oe=n.preferences)==null?void 0:Oe.tablePrefs)!=null&&Ve.enableDevModePagination)&&m(!0)},Te=y.useMemo(()=>!H||!me?null:t.createChartConfig({card:se,data:me,cardType:M,queryConfig:ce,customCfg:re,preferences:ie,topoJson:U}),[se,H,re,ie,ce,me,M,U]);function Le(te){return e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackVisual,children:e.jsx(t.EditorCustomVisual,{card:te})})}function Ae(){var te;if(C!=null&&C.records&&(C==null?void 0:C.records.length)===0&&!k&&!F)return f?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(ds,{error:f,errorSql:L||n.sql||n.python,onOpenInEditor:O,onDebugWithAssistant:B,onSendFeedback:ye,showFeedbackButton:!0})}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(t.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((k||F)&&(!(C!=null&&C.records)||C.records.length===0))return M==="table"||M==="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(!v.id)return null;if(M==="custom")return Le(n);if(!["table","pivotTable","aggregateTable","detailTable","custom"].includes(M)&&Te)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:k||F?e.jsx(e.Fragment,{}):e.jsx(t.ChartJsVisual,{cfg:Te})});if(M==="table"||M==="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:v,data:V,comparisonMetadata:(te=C==null?void 0:C.metadata)==null?void 0:te.comparisonMetadata,paginationMetadata:E,onPaginationChange:ge,onSortChange:ee,isLoading:k||F})});if(M==="pivotTable"&&je)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:v,data:je.data,options:je.options,onAggregationChange:Q=>{const ae=t.handleAggregationChange(Q,n.config),ue={...n,config:ae};z(ue),_(ue)},onAggregationLabelChange:Q=>{const ae=t.handleAggregationLabelChange(Q,n.config),ue={...n,config:ae};z(ue),_(ue)}})});if(M==="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:v,data:(C==null?void 0:C.records)||[],groupByColumns:C==null?void 0:C.groupByColumns,pivotSchema:C==null?void 0:C.pivotSchema,paginationMetadata:E,onPaginationChange:ge,onAggregationChange:Q=>{const ae=t.handleAggregationChange(Q,n.config),ue={...n,config:ae};z(ue),_(ue)},isLoading:k||F})})}return e.jsxs(t.Card,{role:"editor-visual-card",className:t.cn("relative flex h-full flex-col rounded-none",s),...a,children:[(k||F)&&(C==null?void 0:C.records)&&C.records.length>0&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),r&&e.jsxs(t.CardHeader,{className:t.cn("flex flex-row items-start justify-between py-4 pr-6","pl-2"),children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.CardTitle,{className:"text-base",children:e.jsx(t.EditableText,{value:n.title,onSave:te=>z({...n,title:te}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(t.InfoHover,{card:n}),e.jsx(ke.VisualBadge,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(cr,{})})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(t.EditableText,{value:(n.description||"").trim(),onSave:te=>z({...n,description:te.trim()}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),w&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Label,{className:"my-1",children:e.jsx(t.EditableText,{value:w.title||w.column,onSave:te=>j({...w,title:te}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(t.FilterComponent,{filter:w})]})]}),c&&n.inlineFilters&&n.inlineFilters.length>0&&e.jsx("div",{className:t.cn("pb-2 pr-6","pl-2"),children:e.jsx(t.InlineFilterBar,{card:n,sheetId:o||"",inlineFilterValues:l,setInlineFilterValue:te=>g(n.id,te),removeInlineFilterValue:te=>b(n.id,te)})}),e.jsxs(t.CardContent,{className:t.cn("flex min-h-0 grow flex-col pr-6","pl-2"),children:[e.jsx("div",{className:"min-h-0 flex-1 grow basis-0",children:Ae()}),t.isCardSummaryVisibleOnCard(v)&&e.jsx("div",{className:"pt-3",children:e.jsx(t.CardSummary,{card:v,mode:"editor"})})]}),e.jsx(t.FeedbackDialog,{open:u,onOpenChange:p,feedbackData:X,showDebugInfo:!0})]})}const es=({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}),dr=()=>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."})]})]}),ur=({customCode:s,cardCustomCfgString:a,mergedConfig:n,onConfigChange:r,onCodeChange:c})=>e.jsxs(t.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(t.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(t.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(t.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(t.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(t.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(es,{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(es,{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(es,{language:"javascript",value:s,onChange:c})})]}),mr=({error:s,hasCardCustomConfig:a,onReset:n,onApply:r,onClose:c})=>e.jsxs(t.DialogFooter,{className:"flex items-center",children:[e.jsx(t.Label,{className:"mr-2 text-red-500",children:s}),e.jsx(t.Button,{disabled:!a,onClick:n,variant:"outline",children:"Reset"}),e.jsx(t.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(t.Button,{onClick:c,variant:"outline",children:"Close"})]});function xr({triggerVariant:s="icon",className:a,label:n="Customize Visual"}={}){const[r,c]=y.useState(!1),[i,l]=y.useState(""),[d,o]=y.useState(""),[u,p]=y.useState(""),[h,x]=y.useState(""),m=t.useEditorStore(v=>v.card),g=ke.useEffectiveEditorCardType(),b=t.useEditorStore(v=>v.card.customCfg),j=b?JSON.stringify(b,null,2):"",w=y.useMemo(()=>g!==m.type?{...m,type:g}:m,[m,g]),{data:T}=t.useEditorCardQuery(w),{data:P}=t.useTopoJson(m),{setCardCustomCfg:N,setCustomVisualCode:A}=t.useEditorActions(),S=v=>{var R,C;return JSON.stringify({...v,data:{...v.data,datasets:(C=(R=v.data)==null?void 0:R.datasets)==null?void 0:C.map(k=>({...k,data:[]}))}},null,2)},I=()=>{var R,C;if(!((R=T==null?void 0:T.records)!=null&&R.length))return;const v=t.createChartConfig({card:m,data:T.records,cardType:m.type,queryConfig:m.queryConfig,preferences:m.preferences,topoJson:P});if(v){l(S(v)),p(((C=m.preferences)==null?void 0:C.customVisualCode)||"");const k=t.merge(v,b);o(S(k))}},D=()=>{try{if(u&&A(u),d){const v=JSON.parse(d),R=t.getObjectDiff(JSON.parse(i),v);N(R),x("")}}catch{x("Invalid JSON configuration")}},M=Object.keys(b||{}).length===0;return e.jsxs(t.Dialog,{open:r,onOpenChange:c,children:[e.jsx(t.DialogTrigger,{asChild:!0,children:s==="menu"?e.jsxs(t.Button,{variant:"ghost",onClick:I,className:t.cn("h-8 w-full justify-start gap-2 px-2 text-sm",M?"":"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:I,className:t.cn(M?"":"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(dr,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackVisual,children:e.jsx(Bn,{className:"w-1/2 rounded shadow-none"})}),e.jsx(ur,{customCode:u,cardCustomCfgString:j,mergedConfig:d,onConfigChange:v=>o(v??""),onCodeChange:v=>p(v??"")})]}),e.jsx(mr,{error:h,hasCardCustomConfig:!!b,onReset:()=>{o(i),N(null)},onApply:D,onClose:()=>c(!1)})]})]})}function hr({isStarred:s,onClick:a,className:n}){const r=c=>{c.stopPropagation(),c.preventDefault(),a(c)};return e.jsx("button",{type:"button",onClick:r,className:t.cn("flex items-center justify-center rounded-sm p-0.5 transition-all","hover:bg-muted/80",n),"aria-label":s?"Remove from favorites":"Add to favorites",children:e.jsx(t.Star,{className:t.cn("h-3.5 w-3.5 transition-colors",s?"fill-yellow-400 text-yellow-400":"text-muted-foreground hover:text-foreground")})})}function xn({chartType:s,chartName:a,isCustom:n=!1,pluginName:r,isStarred:c,showStar:i=!0,onSelect:l,onToggleStar:d}){return e.jsxs("div",{className:"group relative",children:[i&&e.jsx("div",{className:t.cn("absolute left-1 top-1 z-10 transition-opacity",c?"opacity-100":"opacity-0 group-hover:opacity-100 group-focus-within:opacity-100"),children:e.jsx(hr,{isStarred:c,onClick:()=>d()})}),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",className:"text-xs",children:r})]})}),e.jsxs("button",{type:"button",onClick:l,className:t.cn("flex w-full flex-col items-center gap-2 rounded-lg border border-border","bg-background p-3 transition-all","hover:border-primary/50 hover:bg-muted/50 hover:shadow-sm"),children:[e.jsx(t.ChartIcon,{chartType:s,chartName:a,isCustom:n,className:"h-6 w-6"}),e.jsx("span",{title:a,className:"line-clamp-2 text-center text-xs font-medium text-foreground",children:a})]})]})}const hn=[{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 pr({onChartSelect:s,onClose:a}){const[n,r]=y.useState(""),{starredCharts:c,isStarred:i,toggleStar:l}=t.useStarredChartsStore(),{data:d=[],isLoading:o}=t.useCustomVisualsQuery(),{setCardType:u,setCardPreferences:p,setIsDevMode:h}=t.useEditorStore(v=>v.actions),x=t.useEditorStore(v=>v.card),{setCardCustomCfg:m,setCustomCardPreferences:g,setVisualizationMode:b,setQueryConfig:j,replaceFrameCards:w,clearModeDrafts:T,initializeModeDrafts:P}=t.useEditorActions(),N=y.useMemo(()=>{if(!n)return hn;const v=n.toLowerCase();return hn.filter(R=>R.name.toLowerCase().includes(v))},[n]),A=y.useMemo(()=>{const v=d.filter(C=>C.componentType==="chart"&&C.pluginType!=="standard");if(!n)return v;const R=n.toLowerCase();return v.filter(C=>C.name.toLowerCase().includes(R))},[d,n]),S=v=>{m(null),p({}),b("builtin"),u(v),["custom","text","map"].includes(v)&&(h(!0),j(void 0)),s==null||s(v),a==null||a()},I=v=>{m(null),p({}),b("builtin"),j(void 0);const R=t.resolveMultiInputTypeFromVisual(v);if(R==="multiple"&&v.slots&&v.slots.length>0){T();const k=t.createCardsFromSlots(v.slots,v,x);w(k),k[0]&&P(k[0]),a==null||a();return}else u("custom"),g({type:"component",visualType:R,url:v.url,componentName:v.name,icon:v.icon,pluginChartType:v.chartType,minInputs:v.minInputs,maxInputs:v.maxInputs});s==null||s("custom",v),a==null||a()},D=v=>{const R={type:"default",id:v.id,name:v.name};l(R)},M=v=>{const R={type:"custom",id:v.name,url:v.url,icon:v.icon,name:v.name};l(R)};return e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2 rounded-sm border border-border bg-background px-3 py-2",children:[e.jsx(t.Search,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(t.Input,{placeholder:"Search charts...",value:n,onChange:v=>r(v.target.value),className:"h-auto border-0 p-0 text-sm focus-visible:ring-0 focus-visible:ring-offset-0"})]}),e.jsxs("div",{className:"max-h-[350px] overflow-y-auto",children:[N.length>0&&e.jsx("div",{className:"mb-3",children:e.jsx("div",{className:"grid grid-cols-3 gap-2",children:N.map(v=>e.jsx(xn,{chartType:v.id,chartName:v.name,isCustom:!1,isStarred:i("default",v.id),onSelect:()=>S(v.id),onToggleStar:()=>D(v)},v.id))})}),A.length>0&&e.jsxs(e.Fragment,{children:[N.length>0?e.jsx(t.Separator,{className:"my-3"}):null,e.jsxs("div",{children:[e.jsx("span",{className:"mb-2 block text-xs font-medium text-muted-foreground",children:"Custom Charts"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:A.map((v,R)=>e.jsx(xn,{chartName:v.name,isCustom:!0,pluginName:v.pluginName,isStarred:i("custom",v.name),onSelect:()=>I(v),onToggleStar:()=>M(v)},`${v.url}-${v.name}-${R}`))})]})]}),o&&e.jsxs(e.Fragment,{children:[e.jsx(t.Separator,{className:"my-3"}),e.jsx("div",{className:"py-4 text-center text-sm text-muted-foreground",children:"Loading custom charts..."})]}),N.length===0&&A.length===0&&!o&&e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No charts found"})]})]})}function fr({selectedChart:s,onChartChange:a}){var S,I,D,M;const n=t.useEditorStore(v=>v.card),r=t.useEditorStore(v=>v.frame),c=t.useEditorStore(v=>v.isDevMode),{replaceFrameCards:i,clearModeDrafts:l,initializeModeDrafts:d,setIsDevMode:o}=t.useEditorActions(),u=y.useMemo(()=>t.findCustomVisualConfigCard(r,n),[r,n]),{manifest:p}=t.useCustomVisual(((S=u==null?void 0:u.customCardPreferences)==null?void 0:S.url)||""),h=y.useMemo(()=>{var v;return(v=p==null?void 0:p.visuals)==null?void 0:v.find(R=>{var C;return R.name===((C=u==null?void 0:u.customCardPreferences)==null?void 0:C.componentName)})},[p,(I=u==null?void 0:u.customCardPreferences)==null?void 0:I.componentName]),x=t.resolveMultiInputType(u,h)==="multiple",m=ke.useEffectiveEditorCardType(),g=x?m:s??n.type,b=(D=n==null?void 0:n.customCardPreferences)==null?void 0:D.componentName,j=(M=u==null?void 0:u.customCardPreferences)==null?void 0:M.componentName,w=x&&!!j,T=y.useMemo(()=>{const v=t.chartTypes.find(R=>R.id===g);return v?v.label:g==="custom"?b||"Custom Visual":"Select chart type"},[g,b]),P=y.useMemo(()=>{const v=t.chartTypes.find(R=>R.id===g);if(v){const R=v.icon;return e.jsx(R,{className:"h-4 w-4"})}if(g==="custom"&&b){const R=t.getAutoDetectedChartIcon(b);return R||e.jsx(t.ChartIcon,{chartName:b,isCustom:!0,className:"h-4 w-4"})}return e.jsx(Ia,{className:"h-4 w-4"})},[g,b]);return{displayChartType:g,displayLabel:T,displayIcon:P,showBadge:w,badgeLabel:j,isMultiInputContext:x,handleChartSelect:v=>{a==null||a(v)},handleClearCustomVisual:v=>{v.stopPropagation();const R={...n,type:"bar",sql:"",python:"",config:void 0,queryConfig:void 0,customCfg:void 0,preferences:{},customCardPreferences:void 0,title:"Chart",tabTitle:"Chart",description:void 0,info:void 0};i([R]),l(),d(R),c&&o(!0),a==null||a("bar")}}}function us({selectedChart:s,onChartChange:a,variant:n="ghost",className:r}){const[c,i]=y.useState(!1),{displayLabel:l,displayIcon:d,showBadge:o,badgeLabel:u,handleChartSelect:p,handleClearCustomVisual:h}=fr({selectedChart:s,onChartChange:a});return e.jsxs("div",{className:t.cn("relative w-full",r),children:[e.jsxs(t.Popover,{open:c,onOpenChange:i,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{size:"xs",variant:n,role:"combobox","aria-expanded":c,className:t.cn("w-full justify-between gap-2",n==="ghost"&&"border border-border/70 bg-background text-foreground/90",n==="outline"&&"border-border/70 bg-background text-foreground/90",n==="secondary"&&"text-foreground"),children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[d,e.jsx("span",{className:"truncate",children:l})]}),e.jsx(t.ChevronDown,{className:"h-3.5 w-3.5 shrink-0 opacity-70"})]})}),e.jsx(t.PopoverContent,{className:"w-[360px] p-3",align:"start",onOpenAutoFocus:x=>x.preventDefault(),children:e.jsx(pr,{onChartSelect:x=>p(x),onClose:()=>i(!1)})})]}),o&&e.jsxs("div",{className:"absolute right-10 top-1/2 z-10 flex max-w-[140px] -translate-y-1/2 items-center gap-1 rounded-full border bg-background py-0.5 pl-2 pr-1 text-[10px] text-muted-foreground shadow-sm",title:u,children:[e.jsx(t.Layers,{className:"h-2.5 w-2.5 shrink-0"}),e.jsx("span",{className:"truncate",children:u}),e.jsx("button",{onClick:h,className:"rounded-full p-0.5 hover:bg-muted",title:"Clear custom visual",children:e.jsx(t.X,{className:"h-2.5 w-2.5"})})]})]})}function gr(){const s=t.useEditorStore(o=>{var u,p;return(p=(u=o.card.preferences)==null?void 0:u.chartOptions)==null?void 0:p.indexAxis}),a=t.useEditorStore(o=>o.card.type),{setChartOrientation:n,setCardPreferences:r}=t.useEditorStore(o=>o.actions),c=o=>{if(n(o),a!=="bullet")return;const u=o==="y"?"horizontal":"vertical",p=t.useEditorStore.getState().card.preferences,h={...p||{},bulletConfig:{...(p==null?void 0:p.bulletConfig)||{},orientation:u}};r(h)};function i(){const o=s??"x",u=()=>{c(o==="x"?"y":"x")};return e.jsx(t.IconButton,{onClick:u,tooltip:"Chart Orientation",className:"h-7 w-7 px-0",children:o==="x"?e.jsx(Xt,{className:"h-3.5 w-3.5"}):e.jsx(Wt,{className:"h-3.5 w-3.5"})})}function l(){const o=()=>{c(s==="y"||s===void 0?"x":"y")};return e.jsx(t.IconButton,{onClick:o,tooltip:"Chart Orientation",className:"h-7 w-7 px-0",children:s==="y"||s===void 0?e.jsx(Xt,{className:"h-3.5 w-3.5"}):e.jsx(Wt,{className:"h-3.5 w-3.5"})})}function d(){const o=s??"y",u=()=>{c(o==="y"?"x":"y")};return e.jsx(t.IconButton,{onClick:u,tooltip:"Chart Orientation",className:"h-7 w-7 px-0",children:o==="y"?e.jsx(Wt,{className:"h-3.5 w-3.5"}):e.jsx(Xt,{className:"h-3.5 w-3.5"})})}return e.jsx(e.Fragment,{children:a==="funnel"?l():a==="bullet"?d():i()})}function ms({className:s,triggerVariant:a="icon",label:n="Display Options"}){var b,j,w,T,P,N,A,S,I,D;const r=t.useEditorStore(M=>M.card),{setCardPreferences:c,updateCardInFrame:i,setCard:l}=t.useEditorActions(),[d,o]=y.useState(!1),u=((j=(b=r.preferences)==null?void 0:b.displayOptions)==null?void 0:j.showFilterInfo)??!0,p=((T=(w=r.preferences)==null?void 0:w.displayOptions)==null?void 0:T.showCardToolbar)??!0,h=((N=(P=r.preferences)==null?void 0:P.displayOptions)==null?void 0:N.showChrome)??!0,x=((S=(A=r.preferences)==null?void 0:A.displayOptions)==null?void 0:S.allowScroll)??!0,m=((D=(I=r.preferences)==null?void 0:I.displayOptions)==null?void 0:D.showInlineFilterBar)??!0,g=(M,v)=>{var k;const R={...r.preferences,displayOptions:{...(k=r.preferences)==null?void 0:k.displayOptions,[M]:v}};c(R);const C={...r,preferences:R};l(C),i(C)};return e.jsx("div",{className:t.cn("flex items-center",s),children:e.jsxs(t.DropdownMenu,{modal:!1,open:d,onOpenChange:o,children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:a==="menu"?e.jsxs(t.Button,{variant:"ghost",className:"h-7 w-full justify-start gap-2 px-2 text-[13px]",children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:n})]}):e.jsx(t.IconButton,{className:"h-7 w-7 p-0",tooltip:"Display Options",children:e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(t.DropdownMenuLabel,{children:"Display Options"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsx("div",{className:"px-2 py-1.5",children:e.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"Changes apply to dashboard view only"})}),e.jsxs(t.DropdownMenuCheckboxItem,{checked:u,onCheckedChange:M=>{g("showFilterInfo",M)},onSelect:M=>M.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Filter Info"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Badge"})]}),e.jsxs(t.DropdownMenuCheckboxItem,{checked:p,onCheckedChange:M=>{g("showCardToolbar",M)},onSelect:M=>M.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:h,onCheckedChange:M=>{g("showChrome",M)},onSelect:M=>M.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Chrome"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Frame & padding"})]}),e.jsxs(t.DropdownMenuCheckboxItem,{checked:x,onCheckedChange:M=>{g("allowScroll",M)},onSelect:M=>M.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Allow Scroll"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card content scroll"})]}),e.jsxs(t.DropdownMenuCheckboxItem,{checked:m,onCheckedChange:M=>{g("showInlineFilterBar",M)},onSelect:M=>M.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Inline Filter Bar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card filters"})]})]})]})})}function xs({className:s,triggerVariant:a="icon",label:n="Inline Filters"}){var A,S,I;const[r,c]=y.useState(!1),i=t.useEditorStore(D=>D.card),l=t.useEditorStore(D=>D.selectedConnectionId),{tokenProps:d}=t.useSemaphorContext(),{setCard:o}=t.useEditorActions(),u=t.useDashboardStore(D=>D.actions.removeCardInlineFilterValue),p=t.useDashboardStore(D=>D.actions.setCardInlineFilterValue),h=t.useEditorStore(D=>D.actions.removeCardInlineFilterValue),x=t.useEditorStore(D=>D.actions.setCardInlineFilterValue),m=t.useDashboardStore(D=>D.isVisualEditing),g=(i==null?void 0:i.inlineFilters)||[],b=((S=(A=d==null?void 0:d.params)==null?void 0:A.calendarContext)==null?void 0:S.tz)||((I=d==null?void 0:d.params)==null?void 0:I.timezone)||Intl.DateTimeFormat().resolvedOptions().timeZone;function j(D){var V,z,_,U,H,$,Z;const M=((_=(z=(V=i==null?void 0:i.dataSource)==null?void 0:V.selectedEntities)==null?void 0:z[0])==null?void 0:_.database)||"",v=D.qualifiedFieldName||D.name;if(g.find(re=>t.doesStoredFilterMatchField(re,D)))return;const C=D.qualifiedFieldName?D.qualifiedFieldName.split(".").slice(0,-1).join("."):D.qualifiedEntityName||D.entityName,F=t.fmt(D.name),f=t.buildFilterFieldMeta(D),L=t.buildFilterSemanticContext(i==null?void 0:i.dataSource,{connectionId:l||((U=i==null?void 0:i.dataSource)==null?void 0:U.connectionId),connectionType:(H=i==null?void 0:i.dataSource)==null?void 0:H.connectionType}),E=t.isCalculatedFilterField(f),O=!!((($=i==null?void 0:i.dataSource)==null?void 0:$.mode)==="semanticDomain"&&((Z=L==null?void 0:L.selectedEntities)!=null&&Z.length||L!=null&&L.semanticDomainId)),B={id:t.v4(),column:v,title:D.label||D.name,dataType:D.dataType,table:D.entityName||"",database:M,qualifiedTableName:C,connectionId:l||"",operation:"in",sql:E||O?"":t.getDefaultFilterSql(D.dataType,C,F),fieldMeta:f,semanticContext:L,width:250};o({...i,inlineFilters:[...g,B]})}function w(D){const M=g.filter(v=>v.id!==D);o({...i,inlineFilters:M}),m?h(i.id,D):u(i.id,D)}function T(D,M){const v=g.map(F=>F.id===D?{...F,...M}:F);if(o({...i,inlineFilters:v}),!(Object.prototype.hasOwnProperty.call(M,"defaultValues")||Object.prototype.hasOwnProperty.call(M,"defaultDateFilter")))return;const C=v.find(F=>F.id===D);if(!C)return;const k=t.buildFilterValueFromDefaults(C,b);k?m?x(i.id,k):p(i.id,k):m?h(i.id,D):u(i.id,D)}if(!["bar","line","pie","doughnut","table","detailTable","stackedBar","stackedLine","horizontalBar","radar","polarArea","scatter","bubble","funnel","aggregateTable","custom"].includes(i==null?void 0:i.type))return null;const N=a==="menu";return e.jsx("div",{className:t.cn("flex items-center gap-1",N&&"w-full",s),children:e.jsxs(t.Popover,{open:r,onOpenChange:c,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:N?e.jsxs(t.Button,{variant:"ghost",className:t.cn("h-7 w-full justify-start gap-2 px-2 text-[13px]",g.length>0&&"text-primary"),children:[e.jsx(sn,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:n}),g.length>0&&e.jsx("span",{className:"ml-auto inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-[4px] bg-primary text-[10px] font-medium leading-none text-primary-foreground",children:g.length})]}):e.jsxs(t.IconButton,{tooltip:"Add Inline Filter",className:t.cn("relative h-7 w-7 px-0",{"text-primary":g.length>0}),children:[e.jsx(sn,{className:"h-3.5 w-3.5"}),g.length>0&&e.jsx("span",{className:"absolute -right-1 -top-1 flex h-4 w-4 items-center justify-center rounded-full bg-primary text-[10px] font-medium text-primary-foreground",children:g.length})]})}),e.jsx(t.PopoverContent,{align:"end",className:t.cn("w-80 p-0",N&&"z-[60]"),children:e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"border-b px-4 py-3",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Inline Filters"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"On-card filters for fast, focused exploration."})]}),e.jsx("div",{className:"flex h-[320px] min-h-0 flex-col overflow-hidden",children:e.jsx(t.DndContext,{collisionDetection:t.closestCenter,children:e.jsx(t.SortableContext,{items:[],strategy:t.verticalListSortingStrategy,children:e.jsx(t.FieldsList,{context:"inline-filter",onFieldSelect:j,inlineFilters:g})})})}),g.length>0&&e.jsxs("div",{className:"border-t px-4 py-3",children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Active Filters"}),e.jsx("div",{className:"space-y-1",children:g.map(D=>e.jsx(jr,{filter:D,onUpdate:M=>T(D.id,M),onRemove:()=>w(D.id)},D.id))})]})]})})]})})}function jr({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 br={metric_selector:"Displayed metric",field_selector:"Group by field",aggregation_selector:"Aggregation",grain_selector:"Time grain"};function vr(s,a){return s&&typeof s=="object"&&"label"in s&&typeof s.label=="string"&&s.label.trim().length>0?s.label:a||null}const yr={metric_selector:"config_metric_selector",field_selector:"config_field_selector",aggregation_selector:"config_aggregation",grain_selector:"config_grain"};function Vt(s,a){return`${s}:${a}`}function Nr(s,a,n){const r=new Set(n.filter(i=>i.target!=="sql_param").map(i=>Vt(i.controlId,i.target))),c=a.map(i=>{const l=t.getCompatibleBindingTargetOptions({card:s,control:i}).map(p=>p.value),d=yr[i.type],u=[...d?[d]:[],...l.filter(p=>p!==d)].find(p=>!r.has(Vt(i.id,p)));return u?{controlId:i.id,target:u}:null}).find(Boolean);return c?{controlId:c.controlId,target:c.target,mapping:{}}:null}function Cr({card:s,dashboardControls:a,bindings:n,onChange:r,availableFieldChoices:c,availableMetricChoices:i,suppressTransientStaleState:l=!1}){const d=[...a,...s.controls||[]],[o,u]=y.useState({}),p=t.extractSqlParamReferences({sql:s.sql,controlBindings:s.controlBindings}),h=t.getBindingTargetSuggestions(s),x=new Set(n.map(P=>Vt(P.controlId,P.target))),m=d.some(P=>t.getCompatibleBindingTargetOptions({card:s,control:P}).some(N=>!x.has(Vt(P.id,N.value)))),g=l?0:n.reduce((P,N)=>{const A=b(N.target),S=Object.values(N.mapping).filter(I=>{const D=N.target==="config_metric_selector"||N.target==="config_field_selector"?typeof I=="string"?I:I==null?void 0:I.id:typeof I=="string"?I:void 0;return typeof D=="string"&&!A.some(M=>M.value===D)}).length;return P+S},0);function b(P){var N,A,S,I;switch(P){case"config_metric_selector":return i?i.filter(D=>!!D.target).map(D=>({value:D.target.id,label:D.target.label||D.option.label,target:D.target})):((A=(N=s.config)==null?void 0:N.metricColumns)==null?void 0:A.map(D=>({value:D.id,label:D.label||D.id,target:D})))||[];case"config_field_selector":return c?c.filter(D=>!!D.target).map(D=>({value:D.target.id,label:D.target.label||D.option.label,target:D.target})):((I=(S=s.config)==null?void 0:S.groupByColumns)==null?void 0:I.map(D=>({value:D.id,label:D.label||D.id,target:D})))||[];case"config_aggregation":return(h.config_aggregation||[]).map(D=>({value:D,label:D}));case"config_grain":return(h.config_grain||[]).map(D=>({value:D,label:D.charAt(0).toUpperCase()+D.slice(1)}));default:return[]}}const j=(P,N)=>{r(n.map((A,S)=>S!==P?A:N(A)))},w=P=>{r(n.filter((N,A)=>A!==P))},T=()=>{const P=Nr(s,d,n);P&&r([...n,P])};if(typeof s.sql=="string"&&s.sql.trim().length>0){const P=p.map(({controlId:N,paramId:A})=>{const S=d.find(I=>I.id===N);return S?{id:N,paramId:A,label:S.label,reference:`[[param.${A}]]`}:{id:N,paramId:A,label:N,reference:`[[param.${A}]]`}});return e.jsx("div",{className:"space-y-2",children:P.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-sm text-muted-foreground",children:"This card is currently using raw SQL. Reference a control directly in the SQL editor with syntax like `[[param.metric]]`."}):P.map(N=>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:N.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:N.reference}),e.jsx(t.CopyButton,{text:N.reference,ariaLabel:`Copy ${N.reference}`})]})]})},`${N.id}:${N.paramId}`))})}return e.jsxs("div",{className:"space-y-4",children:[g>0?e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-950",children:[e.jsx(t.CircleAlert,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{children:[g," ",g===1?"mapping needs":"mappings need"," attention before save. Replace each missing target or choose Not mapped."]})]}):null,n.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-sm text-muted-foreground",children:"This card is not using any controls yet."}):n.map((P,N)=>{const A=h[P.target]||[],S=d.find(f=>f.id===P.controlId),I=S?t.ensureManualSource(S):null,D=(I==null?void 0:I.source.kind)==="manual"?I.source.options:[],M=b(P.target),v=Array.from(new Set([...D.map(f=>f.value),...Object.keys(P.mapping)])).map(f=>{const L=D.find(E=>E.value===f);return{value:f,label:(L==null?void 0:L.label)||f}}),R=`${P.controlId}-${P.target}-${N}`,C=o[R]??N===0,k=Object.keys(P.mapping).length,F=S!=null&&S.type?br[S.type]||S.type:null;return e.jsxs(t.Collapsible,{open:C,onOpenChange:f=>u(L=>({...L,[R]:f})),className:"rounded-md border",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 p-3",children:[e.jsx(t.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-start gap-2 text-left",children:[C?e.jsx(t.ChevronDown,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}):e.jsx(t.ChevronRight,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:(S==null?void 0:S.label)||"Control"}),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:k>0?`${k} mapped`:"No mappings yet"})]})]})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>w(N),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:v.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."}):M.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:v.map(f=>{const L=P.mapping[f.value],E=P.target==="config_metric_selector"||P.target==="config_field_selector"?typeof L=="string"?L:L==null?void 0:L.id:typeof L=="string"?L:void 0,O=!l&&typeof E=="string"&&!M.some(z=>z.value===E),B=vr(L,E),V=E&&O?[...M,{value:E,label:"Needs remap",target:L}]:M;return e.jsxs("div",{className:"grid gap-2 rounded-md border p-2 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-[11px] text-muted-foreground",children:"Viewer picks"}),e.jsx("div",{className:"rounded-md bg-muted/50 px-3 py-2 text-sm",children:f.label})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-[11px] text-muted-foreground",children:"Switch to"}),e.jsxs(t.Select,{value:E||"__none__",onValueChange:z=>j(N,_=>{if(_.target==="config_metric_selector"){const H={..._.mapping};if(z==="__none__")delete H[f.value];else{const $=V.find(Z=>Z.value===z);$!=null&&$.target?H[f.value]=$.target:delete H[f.value]}return{..._,mapping:H}}if(_.target==="config_field_selector"){const H={..._.mapping};if(z==="__none__")delete H[f.value];else{const $=V.find(Z=>Z.value===z);$!=null&&$.target?H[f.value]=$.target:delete H[f.value]}return{..._,mapping:H}}const U={..._.mapping};return z==="__none__"?delete U[f.value]:U[f.value]=z,{..._,mapping:U}}),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Choose what this should use"})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"__none__",children:"Not mapped"}),V.map(z=>e.jsx(t.SelectItem,{value:z.value,children:z.label},z.value))]})]}),O?e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-amber-700",children:[e.jsx(t.CircleAlert,{className:"h-3 w-3 shrink-0"}),e.jsxs("span",{children:["Needs remap",B?` · Previously: ${B}`:""]})]}):null]})]},`${P.controlId}-${P.target}-${f.value}`)})}),A.length>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Available choices for this card: ",A.join(", ")]})]})})]},R)}),m?e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",onClick:T,children:[e.jsx(t.Plus,{className:"mr-2 h-4 w-4"}),"Add another control response"]}):null]})}const Sr=[];function wr({className:s,triggerVariant:a="icon",label:n="Controls"}){var C,k;const{handleOpenChange:r,preventPassiveDismissDuringCreate:c,resolvedOpen:i,setIsCreateFlowActive:l}=ke.useCreateFlowOverlayState({}),d=t.useEditorStore(F=>F.card),o=t.useEditorStore(F=>F.frame),u=t.useDashboardStore(F=>F.dashboard),h=t.useDashboardStore(F=>F.dashboard.controls)||Sr,{setCard:x,updateCardInFrame:m}=t.useEditorActions(),[g,b]=y.useState(null);y.useEffect(()=>{i&&!g&&(d!=null&&d.id)&&b(d.id)},[d==null?void 0:d.id,i,g]),y.useEffect(()=>{!i&&g!==null&&b(null)},[i,g]);const j=y.useMemo(()=>g?(o==null?void 0:o.cards.find(F=>F.id===g))||((d==null?void 0:d.id)===g?d:void 0):d,[d,o==null?void 0:o.cards,g]),w=(j==null?void 0:j.controls)||[],T=j?t.collectDashboardControlIds(u,{excludeCardId:j.id}):h.map(F=>F.id),P=((j==null?void 0:j.controlBindings)||[]).filter(F=>F.target!=="sql_param"),N=t.buildCardControlUsageById({card:j,controls:w}),A={choices:t.getFieldSelectorChoicesForCard(j),targetMap:Object.fromEntries((((C=j==null?void 0:j.config)==null?void 0:C.groupByColumns)||[]).map(F=>[F.id,F]))},S={choices:t.getMetricSelectorChoicesForCard(j),targetMap:Object.fromEntries((((k=j==null?void 0:j.config)==null?void 0:k.metricColumns)||[]).map(F=>[F.id,F]))},I=A.choices.map(F=>({option:F,target:A.targetMap[F.value]})),D=S.choices.map(F=>({option:F,target:S.targetMap[F.value]})),M=(F,f)=>{if(!j)return;const L=(f==null?void 0:f.type)==="rename"?t.applyControlMutationToCard(j,{type:"rename",oldId:f.oldId,newId:f.newId}):(f==null?void 0:f.type)==="remove"?t.applyControlMutationToCard(j,{type:"remove",controlId:f.controlId}):j,E={...L,controls:F,controlBindings:t.syncStructuralBindingsWithControls(L.controlBindings,F)};m(E),(d==null?void 0:d.id)===E.id&&x(E)},v=F=>{if(!j)return;const f={...j,controlBindings:t.mergeConfigBindingsWithSqlParamBindings(F,j.controlBindings)};m(f),(d==null?void 0:d.id)===f.id&&x(f)},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]",(w.length>0||P.length>0)&&"text-primary"),children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:n}),w.length+P.length>0&&e.jsx("span",{className:"ml-auto inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-[4px] bg-primary text-[10px] font-medium leading-none text-primary-foreground",children:w.length+P.length})]}):e.jsxs(t.IconButton,{tooltip:"Configure Controls",className:t.cn("relative h-7 w-7 px-0",{"text-primary":w.length>0||P.length>0}),children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"}),w.length+P.length>0&&e.jsx("span",{className:"absolute -right-1 -top-1 inline-flex h-4 min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[10px] font-medium text-primary-foreground",children:w.length+P.length})]})}),e.jsxs(t.PopoverContent,{className:"flex max-h-[85vh] w-[560px] max-w-[95vw] flex-col",align:"end",onEscapeKeyDown:c,onPointerDownOutside:c,children:[e.jsxs("div",{className:"space-y-1 border-b pb-4",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Card-only controls"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add controls that belong only to this card, or decide how this card should respond to shared dashboard controls."}),j!=null&&j.sql?e.jsx("p",{className:"text-xs text-muted-foreground",children:"SQL cards reference controls explicitly with syntax like `[[param.wac_type]]`."}):null]}),e.jsx("div",{className:"flex-1 overflow-y-auto pt-5",children:e.jsxs("div",{className:"space-y-5 pr-1",children:[e.jsx(ke.ControlDefinitionListEditor,{scope:"card",card:j,controls:w,reservedControlIds:T,usageByControlId:N,availableFieldChoices:I,availableMetricChoices:D,onCreateFlowActiveChange:l,onChange:(F,f,L)=>M(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."})]}),j?e.jsx(Cr,{card:j,dashboardControls:h,bindings:P,onChange:v,availableFieldChoices:I,availableMetricChoices:D}):null]})})]})]})})}function Vn({showOrientation:s=!0,showGridStyle:a=!0,showInlineFilters:n=!0,showControls:r=!0,showDisplayOptions:c=!0}={}){const i=t.useEditorStore(m=>m.card),l=t.useEditorStore(m=>{var g,b;return(b=(g=m.card)==null?void 0:g.preferences)==null?void 0:b.chartOptions}),d=t.getChartGridStyle(l),{setChartGrid:o}=t.useEditorActions();function u(){const m=["xy","none","x","y"],b=(m.indexOf(d)+1)%m.length;o(m[b])}const p=s&&["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel","bullet"].includes(i.type),h=a&&!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(i.type);return p||h||n||r||c?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[p&&e.jsx(e.Fragment,{children:e.jsx(gr,{})}),h&&e.jsxs(t.IconButton,{tooltip:"Grid Style",onClick:u,className:"h-7 w-7 px-0",children:[(d==="xy"||!d)&&e.jsx(t.Grid3x3,{className:"h-3.5 w-3.5"}),d==="x"&&e.jsx(cs,{className:"h-3.5 w-3.5"}),d==="y"&&e.jsx(zt,{className:"h-3.5 w-3.5"}),d==="none"&&e.jsx(t.Square,{className:"h-3.5 w-3.5"})]}),n&&e.jsx(xs,{}),r&&e.jsx(wr,{}),c&&e.jsx(ms,{})]}):null}function Tr({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(ke.VisualBadge,{showLabel:!0,className:"h-6 w-fit px-2 py-0.5 text-[11px]"})})}function Er({isPreviewMode:s,onPreviewToggle:a,configCard:n}){var L,E,O,B,V;const r=t.useEditorStore(z=>z.frame),c=t.useEditorStore(z=>z.card),i=t.useEditorStore(z=>z.editorContext),l=(i==null?void 0:i.type)==="documentSection",{setFrame:d,setActiveTabCardId:o,setCard:u,updateCardInFrame:p,clearModeDrafts:h,initializeModeDrafts:x}=t.useEditorActions(),{manifest:m}=t.useCustomVisual(((L=n==null?void 0:n.customCardPreferences)==null?void 0:L.url)||""),g=(E=m==null?void 0:m.visuals)==null?void 0:E.find(z=>{var _;return z.name===((_=n==null?void 0:n.customCardPreferences)==null?void 0:_.componentName)}),j=t.resolveMultiInputType(n,g)==="multiple",w=(g==null?void 0:g.minInputs)??((O=n==null?void 0:n.customCardPreferences)==null?void 0:O.minInputs)??1,T=(g==null?void 0:g.maxInputs)??((B=n==null?void 0:n.customCardPreferences)==null?void 0:B.maxInputs),P=y.useMemo(()=>t.getCustomVisualInputCards({frame:r,configCard:n,isMultiInputVisual:j}),[r,n,j]),N=j?P.filter(Boolean).length:r.cards.length,A=l?!1:T?N<T:!0,S=N>Math.max(w||1,1),I=!!((V=n==null?void 0:n.customCardPreferences)!=null&&V.dataInputCardIds),D=(z,_)=>{z.dataTransfer.setData("tabIndex",_.toString())},M=z=>{z.preventDefault()},v=(z,_)=>{const U=z.dataTransfer.getData("tabIndex");if(U===_.toString())return;const H=Array.from(r.cards),[$]=H.splice(parseInt(U),1);H.splice(_,0,$),d({...r,cards:H})};function R(z){const _=(n==null?void 0:n.id)===z;if(!(I&&_?r.cards.length>1:S))return;let H=r.cards.filter(ie=>ie.id!==z);j&&!I&&(H=t.reindexSlotCards(H));const $=H[0],Z={...r,cards:H,activeCardId:$.id},re=z===c.id;re&&h(),d(Z),o($.id),u($),re&&x($)}function C(z,_){if(!A)return;const U={...r,cards:[...r.cards,_],activeCardId:z.id};d(U),o(_.id)}function k(){if(l)return;if(j&&(n==null?void 0:n.id)===c.id){F(c);return}const z={...c,id:t.v4(),title:`${c.title} Copy`,tabTitle:`${c.tabTitle||c.title} Copy`,customCardPreferences:c.customCardPreferences?{...c.customCardPreferences,slotIndex:j?Math.max(-1,...P.map((_,U)=>t.getSlotIndexForCard(_,U)))+1:c.customCardPreferences.slotIndex}:void 0};C(c,z)}function F(z){var re;if(l||!A)return;let _=j?"table":"bar",U="Title",H="";const $=j?Math.max(-1,...P.map((ie,ce)=>t.getSlotIndexForCard(ie,ce)))+1:N;if(j&&((re=g==null?void 0:g.slots)!=null&&re.length)){const ie=t.getSlotDefinitionForIndex(g.slots,$);ie&&(_=t.getSlotExpectedChartType(ie),U=ie.label||`Tab ${$+1}`,H=ie.description||"")}const Z={dataSource:z.dataSource,connectionId:z.connectionId,lastSelectedDatabase:z.lastSelectedDatabase,lastSelectedSchema:z.lastSelectedSchema,lastSelectedTable:z.lastSelectedTable,lastSelectedDatamodelId:z.lastSelectedDatamodelId,id:t.v4(),title:U,tabTitle:U,description:H,preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:_,sql:"",data:[],mode:"explorer",...j&&{customCardPreferences:{slotIndex:$}}};C(z,Z)}function f(z,_){return z.cards.length===1&&(_.displayTab===!0||_.displayTab===void 0)||z.activeCardId!==_.id&&(_.displayTab===!0||_.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const U=_.displayTab===void 0?!1:!_.displayTab;u({..._,displayTab:U}),p({..._,displayTab:U})},children:_.displayTab===!0||_.displayTab===void 0?e.jsx(t.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(t.EyeOff,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(t.TabsList,{className:"group ml-2 mr-6 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[r.cards.map((z,_)=>{var re,ie;const U=j?t.getSlotIndexForCard(z,_):-1,H=j&&((re=g==null?void 0:g.slots)!=null&&re.length)&&U>=0?t.getSlotDefinitionForIndex(g.slots,U):null,$=H?(Array.isArray(H.expectedType)?H.expectedType[0]:H.expectedType)||"table":z.type,Z=j&&((ie=g==null?void 0:g.slots)==null?void 0:ie.length)&&g.slots.every(ce=>typeof ce.position=="number"||typeof ce.position=="string"&&!ce.position.includes("+"));return e.jsxs(t.TabsTrigger,{draggable:!j&&!l,onDragStart:j||l?void 0:ce=>D(ce,_),onDragOver:j||l?void 0:M,onDrop:j||l?void 0:ce=>v(ce,_),className:"",value:z.id,children:[j&&H?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($,"size-3.5")}),e.jsx("span",{children:H.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:H.label}),H.description&&e.jsx("p",{className:"whitespace-normal break-words text-xs text-muted-foreground",children:H.description}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[H.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(H.expectedType)?H.expectedType.join(" / "):H.expectedType}),H.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:[f(r,z),e.jsx(t.Editable,{enabled:r.activeCardId===z.id,text:z.tabTitle||z.title,onSave:ce=>{u({...c,tabTitle:ce}),p({...c,tabTitle:ce})},children:z.tabTitle||z.title},z.id)]}),!l&&r.activeCardId===z.id&&!Z&&e.jsx(t.CopyPlus,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:ce=>{ce.stopPropagation(),k()}}),!l&&r.activeCardId===z.id&&(I&&(n==null?void 0:n.id)===z.id?r.cards.length>1:S)&&e.jsx(t.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>R(z.id)})]},z.id)}),!l&&e.jsx(t.IconButton,{tooltip:"Add Card",className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",onClick:()=>F(c),disabled:!A,children:e.jsx(t.Plus,{className:"h-4 w-4"})}),j&&e.jsxs(t.Toggle,{pressed:s,onPressedChange:a,size:"sm",className:"ml-2 h-8 gap-1 px-2 data-[state=on]:bg-background data-[state=on]:text-foreground","aria-label":"Toggle preview",children:[s?e.jsx(t.EyeOff,{className:"h-4 w-4"}):e.jsx(t.Eye,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Preview"})]})]})})}function ot({renderCardOverride:s,alwaysRenderOverride:a=!1}={}){var Ie,K,le,ve,te;const n=t.useEditorStore(Q=>Q.frame),r=t.useEditorStore(Q=>Q.card),[c,i]=y.useState(!1),l=y.useMemo(()=>t.findCustomVisualConfigCard(n,r),[n,r]),d=t.useEditorStore(Q=>Q.isSqlRunning);t.useEditorStore(Q=>Q.isDevMode);const{setFrame:o,setActiveTabCardId:u,setCard:p,setRunSql:h,mergeDraftsIntoCard:x,clearModeDrafts:m,initializeModeDrafts:g}=t.useEditorActions(),[b,j]=y.useState({}),[w,T]=y.useState(()=>new Set),{theme:P}=t.useTheme(),N=t.useDashboardStore(Q=>Q.themeStyle),{authToken:A}=t.useSemaphorContext(),S=t.getTokenParams(A==null?void 0:A.accessToken),I={mode:P||"system",colors:((K=(Ie=N==null?void 0:N.chart)==null?void 0:Ie.dataset)==null?void 0:K.backgroundColor)||[]},{getCard:D,manifest:M,isLoading:v}=t.useCustomVisual(((le=l==null?void 0:l.customCardPreferences)==null?void 0:le.url)||""),R=(ve=l==null?void 0:l.customCardPreferences)==null?void 0:ve.componentName,C=R?D(R):null,k=(te=M==null?void 0:M.visuals)==null?void 0:te.find(Q=>Q.name===R),F=t.resolveMultiInputType(l,k),f=c&&F==="multiple"&&!!l,L=y.useMemo(()=>t.getCustomVisualInputCards({frame:n,configCard:l,isMultiInputVisual:!0}).map(ae=>(ae==null?void 0:ae.id)===r.id?r:ae),[n,l,r]),E=y.useMemo(()=>t.buildSlotOrderedCards(L),[L]),O=y.useMemo(()=>{const Q=L.findIndex(ae=>(ae==null?void 0:ae.id)===r.id);return Q<0?-1:t.getSlotIndexForCard(r,Q)},[L,r]),B=y.useMemo(()=>!l||F!=="multiple"||O<0?r.type:t.getEffectiveCardTypeForSlot(r,O,k==null?void 0:k.slots)??r.type,[l,F,O,r,k==null?void 0:k.slots]),V=y.useMemo(()=>f?{...r,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:B!==r.type?{...r,type:B}:r,[r,B,f]),{data:z,isLoading:_,isFetching:U,isError:H}=t.useEditorCardQuery(V),$=y.useCallback((Q,ae)=>{const ue=t.normalizeMultiInputPayload(ae);j(Se=>({...Se,[Q]:ue}))},[]),Z=y.useCallback((Q,ae)=>{T(ue=>{const Se=new Set(ue);return ae?Se.add(Q):Se.delete(Q),Se})},[]),re=w.size>0,ie=t.useInteractionStore(Q=>Q.interactionStates),ce=t.useDashboardStore(Q=>{var ae;return(ae=Q.dashboard)==null?void 0:ae.id}),he=t.useDashboardStore(Q=>Q.dashboard.filters),me=t.useDashboardStore(Q=>Q.filterValues),se=t.useDashboardStore(Q=>Q.selectedSheetId),be=t.useEditorStore(Q=>Q.inlineFilterValuesMap[(l==null?void 0:l.id)||""]),je=t.useEditorStore(Q=>Q.actions.setCardInlineFilterValue),ye=t.useEditorStore(Q=>Q.actions.removeCardInlineFilterValue),X=y.useMemo(()=>l?t.buildInlineFilterNodes({card:l,sheetId:se||"",inlineFilterValues:be,setInlineFilterValue:Q=>je(l.id,Q),removeInlineFilterValue:Q=>ye(l.id,Q)}):[],[l,se,be,je,ye]),{cardFilters:ge,cardFilterValues:ee}=y.useMemo(()=>l?t.calculateContextAwareFilters({card:l,interactionStates:ie,currentDashboardId:ce,filters:he,filterValues:me,selectedSheetId:se}):{cardFilters:[],cardFilterValues:[]},[l,ie,ce,he,me,se]);function Te(Q){const ae=n.cards.find(ue=>ue.id===Q);ae&&(it.flushPendingEditorDrafts(),x(),Le(Q),u(Q),m(),g(ae))}function Le(Q){const ae=t.useEditorStore.getState().card,ue=t.useEditorStore.getState().frame,Se={...ue,cards:ue.cards.map(Oe=>Oe.id===ae.id?ae:Oe),activeCardId:Q};o(Se);const Ne=Se.cards.find(Oe=>Oe.id===Q);Ne.sql&&h(!0),p(Ne)}function Ae(){if(v)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(!C)return e.jsx("div",{className:"flex h-full items-center justify-center text-sm text-muted-foreground",children:"Select a component to preview the multi-input visual."});const ae=E.map((ue,Se)=>t.getEffectiveCardTypeForSlot(ue,Se,k==null?void 0:k.slots));return e.jsxs("div",{className:"relative flex h-full flex-col pl-2 pr-4",children:[L.map((ue,Se)=>{if(!ue)return null;const Ne=t.getSlotIndexForCard(ue,Se),Oe=t.getEffectiveCardTypeForSlot(ue,Ne,k==null?void 0:k.slots);return e.jsx(t.MultiInputEmptyRenderer,{onLoadingStatus:Z,onDataChange:$,card:ue,effectiveCardType:Oe},`${ue.id}-${Ne}`)}),re&&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",re&&"opacity-50"),children:e.jsx(y.Suspense,{fallback:e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(t.LoadingDots,{size:"md",color:"muted"})}),children:e.jsx(C,{editing:!0,...t.buildMultiInputCustomVisualProps({configCard:l,slotOrderedCards:E,slotTypes:ae,multiInputData:b,params:S,theme:I,filters:ge,filterValues:[...ee||[],...be||[]],inlineFilters:X})})})})]})}function Ee(){var Q;return f?Ae():s&&(a||!_&&!U&&!H)?s({card:r,data:z,isLoading:_,isFetching:U,isError:H}):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(Tr,{visible:!0}),e.jsx("div",{className:"rounded-md border border-border",children:e.jsx(t.KPICard,{card:r,data:z==null?void 0:z.records,isPending:_||U,isError:H,comparisonMetadata:(Q=z==null?void 0:z.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:d,card:r,data:z==null?void 0:z.records})})})}):e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackVisual,children:e.jsx(Bn,{className:"grow border-none shadow-none"})})}return e.jsxs(t.Tabs,{onValueChange:Te,value:n.activeCardId,className:"flex grow flex-col gap-2",children:[f?e.jsx("div",{className:"mt-0 grow",children:Ee()}):n.cards.map(Q=>e.jsx(t.TabsContent,{className:"mt-0 grow focus-visible:ring-0 focus-visible:ring-offset-0",value:Q.id,children:Ee()},Q.id)),e.jsx(Er,{isPreviewMode:f,onPreviewToggle:i,configCard:l})]})}function Ir({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 zn({fallbackPreview:s,records:a,title:n,isInspectorOpen:r,onInspectorOpenChange:c}){var k;const i=t.useEditorStore(F=>F.card),l=t.useEditorStore(F=>F.actions.setCard),d=t.useEditorStore(F=>F.actions.updateCardInFrame),o=t.normalizeDynamicRendererSource((k=i.dynamicCardPreferences)==null?void 0:k.rendererCode),[u,p]=y.useState(o),[h,x]=y.useState(o);y.useEffect(()=>{p(o),x(o)},[o,i.id]);const m=y.useMemo(()=>t.normalizeDynamicRendererSource(u),[u]),g=y.useMemo(()=>t.validateDynamicRendererSource(m),[m]),b=!!o,j=y.useMemo(()=>{var F;return t.buildCardWithVisualizationMode(i,h?"dynamic":"builtin",{rendererCode:h||void 0,artifactId:((F=i.dynamicCardPreferences)==null?void 0:F.artifactId)||i.id,title:n||i.title})},[i,h,n]),w=!!h,T=m!==h,P=h!==o,N=!m||!g.valid||T||P,A=m?g.valid?T?"Unapplied changes":"Pending save":"Needs attention":"Draft",S=!m||T||P?"outline":"destructive",I=m?g.valid?T?"The preview still reflects the last applied code until you apply this draft.":P?"Preview reflects pending changes. Accept changes to save them.":"":g.error||"Visual code is invalid.":"Paste visual code or generate one before saving this card.";function D(){if(!g.valid){t.ue.error(g.error||"Visual code is invalid.");return}x(m),t.ue.success("Dynamic preview updated.")}function M(){p(h)}function v(){var f;const F=t.buildCardWithVisualizationMode(i,h?"dynamic":"builtin",{rendererCode:h||void 0,artifactId:((f=i.dynamicCardPreferences)==null?void 0:f.artifactId)||t.v4(),title:n||i.title});l(F),d(F),c(!1),t.ue.success(h?"Dynamic visual changes saved.":"Dynamic visual cleared.")}function R(){p(o),x(o),c(!1)}function C(){p(""),x("")}return e.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[e.jsx("div",{className:"min-h-0 flex-1 bg-background px-2",children:b?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(Ir,{onClick:()=>c(!0)})]})}),e.jsx(t.Dialog,{open:r,onOpenChange:F=>{if(!F){R();return}c(!0)},children:e.jsxs(t.DialogContent,{className:"flex h-[min(88vh,860px)] max-w-[min(1280px,calc(100vw-2rem))] flex-col gap-0 overflow-hidden p-0",children:[e.jsx(t.DialogHeader,{className:"border-b px-6 py-4 pr-20 text-left",children:e.jsxs("div",{className:"flex items-start justify-between gap-4 pr-4",children:[e.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[e.jsx(t.DialogTitle,{children:"Dynamic Visual Editor"}),e.jsx(t.DialogDescription,{children:"Adjust the preview and visual code here. Query editing stays in the normal editor controls."})]}),N&&e.jsx(t.Badge,{className:"mr-4 shrink-0",variant:S,children:A})]})}),e.jsx("div",{className:"min-h-0 flex-1",children:e.jsxs(t.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(t.ResizablePanel,{defaultSize:54,minSize:38,children:e.jsx("div",{className:"flex h-full min-h-0 flex-col",children:e.jsx("div",{className:"min-h-0 flex-1 bg-background p-4",children:w?e.jsx(t.PersistedDynamicVisual,{card:j,records:a,title:n,layoutMode:"fill",fallback:s},h||"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:!b&&!m,children:[e.jsx(t.X,{className:"h-3.5 w-3.5 shrink-0"}),"Clear"]})}),e.jsxs(t.AlertDialogContent,{children:[e.jsxs(t.AlertDialogHeader,{children:[e.jsx(t.AlertDialogTitle,{children:"Clear dynamic visual?"}),e.jsx(t.AlertDialogDescription,{children:"This removes the saved dynamic renderer and switches the card back to built-in mode. The underlying query and built-in chart type will remain."})]}),e.jsxs(t.AlertDialogFooter,{children:[e.jsx(t.AlertDialogCancel,{children:"Cancel"}),e.jsx(t.AlertDialogAction,{className:"bg-foreground text-background hover:bg-foreground/90",onClick:C,children:"Clear"})]})]})]}),e.jsxs(t.Button,{type:"button",size:"sm",variant:"outline",className:"h-8 gap-1.5 px-2.5 text-xs",onClick:M,disabled:!T,children:[e.jsx(os,{className:"h-3.5 w-3.5 shrink-0"}),"Reset"]}),e.jsxs(t.Button,{type:"button",size:"sm",className:"h-8 gap-1.5 px-3 text-xs",onClick:D,disabled:!T||!g.valid,children:[e.jsx(t.Play,{className:"h-3.5 w-3.5 shrink-0"}),"Apply to Preview"]})]})]}),e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3 p-4",children:[I&&e.jsx("p",{className:t.cn("text-xs",g.valid?"text-muted-foreground":"text-destructive"),children:I}),e.jsx("div",{className:t.cn("min-h-0 flex-1 overflow-hidden rounded-md border",!g.valid&&m&&"border-destructive"),children:e.jsx(t.CodeEditor,{value:u,onValueChange:F=>p(F||""),language:"javascript",embedded:!0})})]})]})})]})}),e.jsxs(t.DialogFooter,{className:"border-t px-6 py-4 sm:justify-between",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:I||"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:v,disabled:!P,children:"Accept changes"})]})]})]})})]})}function _n({onCustomize:s}){const a=t.useEditorStore(u=>u.card),n=t.useEditorStore(u=>u.frame),r=t.useEditorStore(u=>u.actions.setIsShowingVisual),{setVisualizationMode:c,setDynamicCardPreferences:i}=t.useEditorActions(),d=t.getVisualizationMode(a)==="dynamic";if(n.cards.length!==1||t.isCustomVisualizationCard(a))return null;const o=u=>{var p;u==="dynamic"&&!a.dynamicCardPreferences&&i(t.createEmptyDynamicCardPreferences(a.type,(p=a.preferences)==null?void 0:p.displayOptions)),c(u),r(!0)};return e.jsxs(e.Fragment,{children:[e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{onSelect:u=>{u.preventDefault(),o(d?"builtin":"dynamic")},className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx(t.CodeXml,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Dynamic"})]}),e.jsx(t.Switch,{checked:d,onCheckedChange:u=>o(u?"dynamic":"builtin"),onClick:u=>u.stopPropagation()})]}),d&&s?e.jsxs(t.DropdownMenuItem,{onSelect:u=>{u.preventDefault(),s()},children:[e.jsx(t.SlidersHorizontal,{className:"mr-2 h-4 w-4"}),"Customize Visual"]}):null]})}function pn({children:s,visualAsideControl:a}){var me;const n=t.useQueryClient(),r=t.useEditorStore(se=>se.frame),c=t.useEditorStore(se=>se.card),i=c.type==="table"||c.type==="detailTable",l=t.useEditorStore(se=>se.isDevMode),d=t.useEditorStore(se=>se.editorContext),o=(d==null?void 0:d.type)==="documentSection",u=t.useEditorStore(se=>se.isShowingVisual),p=t.useEditorStore(se=>se.actions.setIsShowingVisual),h=t.useDashboardStore(se=>se.isVisualEditing),{isConsoleMode:x}=t.useDashboardPreferences(),m=t.useEditorStore(se=>se.pythonStdOut),g=t.useEditorStore(se=>se.actions.setRunSql),b=ke.useEffectiveEditorCardType(),w=t.getVisualizationMode(c)==="dynamic",[T,P]=y.useState(!1),{setFrame:N,setCard:A,setActiveTabCardId:S,setCardPreferences:I,mergeDraftsIntoCard:D,clearModeDrafts:M,initializeModeDrafts:v,updatePageSize:R}=t.useEditorActions(),C=y.useMemo(()=>b!==c.type?{...c,type:b}:c,[c,b]),{data:k,isLoading:F,isFetching:f,errorMessage:L,errorSql:E,refetch:O,queryKey:B,pagination:V}=t.useEditorCardQuery(C),z=y.useRef(B);z.current=B;const{handleDebugWithAssistant:_}=Pn(L,E),U=y.useMemo(()=>(k==null?void 0:k.records)||[],[k==null?void 0:k.records]),[H,$]=y.useState(!1);y.useEffect(()=>{f||$(!1)},[f]),y.useEffect(()=>{i&&!u&&!l&&!x&&p(!0)},[x,l,i,u,p]);function Z(se,be){var X,ge;const je={...c,paginationConfig:{page:se+1,pageSize:be}};A(je);const ye={...r,cards:r.cards.map(ee=>ee.id===c.id?je:ee)};N(ye),c.sql&&((ge=(X=c.preferences)==null?void 0:X.tablePrefs)!=null&&ge.enableDevModePagination)&&g(!0)}function re(se){var X,ge,ee,Te,Le;const be=t.sortStateToSortByColumns(se,(X=c.config)==null?void 0:X.metricColumns,(ge=c.config)==null?void 0:ge.groupByColumns,(ee=c.config)==null?void 0:ee.detailColumns),je={...c,config:{...c.config||{},sortByColumns:be}};A(je);const ye={...r,cards:r.cards.map(Ae=>Ae.id===c.id?je:Ae)};N(ye),c.sql&&((Le=(Te=c.preferences)==null?void 0:Te.tablePrefs)!=null&&Le.enableDevModePagination)&&g(!0)}function ie(){var be;const se=JSON.stringify(k==null?void 0:k.records,null,2);typeof navigator>"u"||!((be=navigator.clipboard)!=null&&be.writeText)||navigator.clipboard.writeText(se).catch(je=>{console.error("Failed to copy JSON",je)})}function ce(){const se=JSON.stringify(k==null?void 0:k.records,null,2),be=new Blob([se],{type:"application/json"}),je=URL.createObjectURL(be),ye=document.createElement("a");ye.href=je,ye.download=`${c.title}.json`,ye.click()}function he(){const be=[Object.keys(k==null?void 0:k.records.reduce((ge,ee)=>({...ge,...ee}),{})).join(","),...((k==null?void 0:k.records)||[]).map(ge=>Object.values(ge).join(","))].join(`
|
|
182
|
+
`),je=new Blob([be],{type:"text/csv"}),ye=URL.createObjectURL(je),X=document.createElement("a");X.href=ye,X.download=`${c.title}.csv`,X.click()}return c?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 pl-2 pr-6",children:[u&&e.jsx("div",{className:"flex grow items-center",children:e.jsxs("div",{className:"flex items-center gap-3",children:[(a==null?void 0:a.show)&&e.jsx(t.IconButton,{tooltip:a.isOpen?"Hide Visual Aside":"Show Visual Aside",className:"h-7 w-7 px-0",buttonProps:{variant:"outline"},onClick:a.onToggle,children:a.isOpen?e.jsx(t.ChevronLeft,{className:"h-3.5 w-3.5"}):e.jsx(t.ChevronRight,{className:"h-3.5 w-3.5"})}),!o&&!w&&e.jsx("div",{className:"w-[200px]",children:e.jsx(us,{variant:l?"secondary":"ghost"})})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[s,e.jsx(t.IconButton,{tooltip:"Refresh",disabled:F||f,className:"h-7 w-7 px-0",onClick:()=>{if($(!0),l){it.flushPendingEditorDrafts(),setTimeout(()=>{n.removeQueries({queryKey:z.current,exact:!0}),g(!0)},0);return}O()},children:e.jsx(t.RefreshCcw,{className:t.cn("h-3.5 w-3.5",{"animate-spin":H})})}),!w&&e.jsx(Vn,{showInlineFilters:!1,showDisplayOptions:!1}),(l||x)&&e.jsxs(e.Fragment,{children:[e.jsx(Mr,{}),i&&e.jsxs(e.Fragment,{children:[e.jsx(kr,{}),e.jsx(Ar,{})]})]}),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:[!w&&!["table","detailTable","custom"].includes(c.type)&&h&&e.jsx(xr,{triggerVariant:"menu",className:"w-full"}),e.jsx(xs,{triggerVariant:"menu",className:"w-full"}),e.jsx(ms,{triggerVariant:"menu",className:"w-full"}),e.jsx(_n,{onCustomize:()=>P(!0)}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.Button,{variant:"ghost",className:"h-7 w-full justify-start gap-2 px-2 text-[13px]",onClick:he,children:[e.jsx(t.Download,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Download CSV"})]}),e.jsxs(t.Button,{variant:"ghost",className:"h-7 w-full justify-start gap-2 px-2 text-[13px]",onClick:ce,children:[e.jsx(ga,{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:ie,children:[e.jsx(t.Copy,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Copy JSON"})]})]})]})]})]})]}),u?w?e.jsx(ot,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(zn,{fallbackPreview:e.jsx(ot,{}),records:U,title:c.title,isInspectorOpen:T,onInspectorOpenChange:P})}):e.jsx(ot,{}):e.jsxs(t.ResizablePanelGroup,{className:"py-2 pl-2 pr-6",direction:"horizontal",children:[m&&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:m&&e.jsx(Dr,{})}),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":m}),children:[Array.isArray(k==null?void 0:k.records)&&!L&&(l?e.jsx(ir,{data:k.records,card:C,paginationMetadata:V,onPaginationChange:Z,onPageSizePreferenceChange:R,onSortChange:re,isLoading:F||f}):k.records.length>0?e.jsx(t.TableVisual,{card:c,data:U,comparisonMetadata:(me=k==null?void 0:k.metadata)==null?void 0:me.comparisonMetadata,paginationMetadata:V,onPaginationChange:Z,onSortChange:re,isLoading:F||f}):null),L&&e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(ds,{error:L,errorSql:E||c.sql||c.python,onDebugWithAssistant:_,showFeedbackButton:!1})})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function Dr(){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 kr(){var n,r;const s=t.useEditorStore(c=>c.card),a=t.useEditorStore(c=>c.actions.setCardPreferences);return s.type!=="table"&&s.type!=="detailTable"?null:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(t.Label,{htmlFor:"table-density",className:"text-[13px]",children:"Density"}),e.jsxs(t.Select,{value:((r=(n=s.preferences)==null?void 0:n.tablePrefs)==null?void 0:r.density)??"compact",onValueChange:c=>{var i;a({...s.preferences,tablePrefs:{...(i=s.preferences)==null?void 0:i.tablePrefs,density:c}})},children:[e.jsx(t.SelectTrigger,{id:"table-density",className:"h-7 w-[116px] rounded-[5px] px-2 text-[12px]",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"compact",children:"Compact"}),e.jsx(t.SelectItem,{value:"comfortable",children:"Comfortable"}),e.jsx(t.SelectItem,{value:"spacious",children:"Spacious"})]})]})]})}function Ar(){var d,o,u,p,h,x,m,g;const s=t.useEditorStore(b=>b.card),a=t.useEditorStore(b=>b.actions.setCard),n=t.useEditorStore(b=>b.actions.setRunSql),r=t.useEditorStore(b=>b.actions.setCardPreferences),c=t.useEditorStore(b=>b.actions.updateCardInFrame),i=y.useMemo(()=>{var b,j;return t.getTablePageSizeOptions((j=(b=s.preferences)==null?void 0:b.tablePrefs)==null?void 0:j.pageSize)},[(o=(d=s.preferences)==null?void 0:d.tablePrefs)==null?void 0:o.pageSize]),l=t.resolveTablePageSize((p=(u=s.preferences)==null?void 0:u.tablePrefs)==null?void 0:p.pageSize);return s.type!=="table"&&s.type!=="detailTable"?null:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Checkbox,{id:"dev-pagination",checked:((x=(h=s.preferences)==null?void 0:h.tablePrefs)==null?void 0:x.enableDevModePagination)??!1,onCheckedChange:b=>{var j;r({...s.preferences,tablePrefs:{...(j=s.preferences)==null?void 0:j.tablePrefs,enableDevModePagination:b}})}}),e.jsx(t.Label,{htmlFor:"dev-pagination",className:"cursor-pointer text-[13px]",children:"Paginate"}),((g=(m=s.preferences)==null?void 0:m.tablePrefs)==null?void 0:g.enableDevModePagination)&&e.jsxs(t.Select,{value:String(l),onValueChange:b=>{var T,P,N;const j=Number(b),w={...s,preferences:{...s.preferences,tablePrefs:{...(T=s.preferences)==null?void 0:T.tablePrefs,pageSize:j}},paginationConfig:{page:1,pageSize:j}};a(w),c(w),s.sql&&((N=(P=s.preferences)==null?void 0:P.tablePrefs)!=null&&N.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(b=>e.jsx(t.SelectItem,{value:String(b),children:b},b))})]})]})}function Mr(){const s=t.useEditorStore(n=>n.isShowingVisual),a=t.useEditorStore(n=>n.actions.setIsShowingVisual);return e.jsxs(t.Toggle,{pressed:!s,onPressedChange:n=>{a(!n)},variant:"default",size:"sm",className:"h-7 gap-1.5 rounded-[5px] border border-transparent px-2.5 text-[12px] text-foreground/80 hover:bg-accent hover:text-accent-foreground data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",children:[e.jsx(t.Table2,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Query Output"})]})}function qe({value:s,onCommit:a,type:n="text",placeholder:r,className:c}){const[i,l]=y.useState(s),d=y.useRef(!1);y.useEffect(()=>{l(s)},[s]);const o=()=>{if(d.current){d.current=!1;return}i!==s&&a(i)},u=p=>{if(p.key==="Enter"){p.currentTarget.blur();return}p.key==="Escape"&&(d.current=!0,l(s),p.currentTarget.blur())};return e.jsx(t.Input,{type:n,placeholder:r,value:i,onChange:p=>l(p.target.value),onBlur:o,onKeyDown:u,className:c})}function nt({defaultValue:s,label:a,options:n,value:r,onValueChange:c,className:i,icon:l,showPlaceholderLabel:d=!0}){return e.jsxs(t.Select,{defaultValue:s,value:r,onValueChange:c,children:[e.jsx(t.SelectTrigger,{className:t.cn("w-full focus:ring-0 focus:ring-offset-0",i),children:e.jsxs("div",{className:"flex items-center gap-2",children:[l&&e.jsx("span",{children:l}),d&&e.jsx(t.SelectValue,{placeholder:a})]})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:a}),n.map(o=>e.jsx(t.SelectItem,{value:o.value,children:o.label},o.value))]})})]})}function Lr(s,a){return t.getSlotDefinitionForIndex(s,a)||null}function St(s){if(typeof s=="number")return`Tab ${s+1}`;const a=s.match(/^(\d+)-(\d+)$/);if(a){const[,r,c]=a;return`Tabs ${Number(r)+1}-${Number(c)+1}`}const n=s.match(/^(\d+)\+$/);return n?`Tabs ${Number(n[1])+1}+`:`Tab ${s}`}function Fr(s){return s?Array.isArray(s)?s:[s]:[]}function ts(s){var r,c;if(!s)return!1;if(s.type==="text")return!!((r=s.description)!=null&&r.trim());const a=!!((c=s.sql)!=null&&c.trim()),n=t.hasValidCardConfig(s.config);return a||n}function Rr({slots:s,cards:a,minInputs:n}){const r=[],c=a.filter(Boolean).length;return n&&c<n&&r.push({type:"too-few-inputs",message:`This visual requires at least ${n} tab${n===1?"":"s"}.`}),!s||s.length===0||(s.forEach(i=>{if(!i.required)return;if(typeof i.position=="number"){const o=a[i.position];ts(o)||r.push({type:"missing-required",message:`${St(i.position)} ("${i.label}") is required but has no data configured.`});return}const l=i.position.match(/^(\d+)-(\d+)$/);if(l){const[,o,u]=l.map(Number);for(let p=o;p<=u;p+=1){const h=a[p];if(!ts(h)){r.push({type:"missing-required",message:`${St(p)} ("${i.label}") is required but has no data configured.`});break}}return}const d=i.position.match(/^(\d+)\+$/);if(d){const o=Number(d[1]);if(a.length<=o){r.push({type:"missing-required",message:`${St(o)} ("${i.label}") is required but has no data configured.`});return}for(let u=o;u<a.length;u+=1){const p=a[u];if(!ts(p)){r.push({type:"missing-required",message:`${St(u)} ("${i.label}") is required but has no data configured.`});break}}}}),a.forEach((i,l)=>{if(!i)return;const d=Lr(s,l);if(!d||!d.expectedType)return;const o=Fr(d.expectedType);o.length!==0&&(o.includes(i.type)||r.push({type:"wrong-type",message:`${St(l)} ("${d.label}") expects ${o.join(", ")}, but is configured as ${i.type}.`}))})),r}const Or={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 qn(){var C,k,F;const s=t.useEditorStore(f=>f.card.customCardPreferences),{data:a}=t.usePluginQuery(),n=(a==null?void 0:a.plugins)||[],r=t.useEditorStore(f=>f.card),c=t.useEditorStore(f=>f.frame),{setCustomCardPreferences:i}=t.useEditorActions(),l=y.useMemo(()=>t.findCustomVisualConfigCard(c,r),[c,r]),d=l==null?void 0:l.customCardPreferences,{components:o,manifest:u}=t.useCustomVisual((d==null?void 0:d.url)||(s==null?void 0:s.url)||""),p=(C=u==null?void 0:u.visuals)==null?void 0:C.find(f=>f.name===((d==null?void 0:d.componentName)||(s==null?void 0:s.componentName))),x=t.resolveMultiInputType(l||r,p)==="multiple",m=!!l&&l.id===r.id,g=(p==null?void 0:p.minInputs)??((k=l==null?void 0:l.customCardPreferences)==null?void 0:k.minInputs),b=(p==null?void 0:p.maxInputs)??((F=l==null?void 0:l.customCardPreferences)==null?void 0:F.maxInputs),j=y.useMemo(()=>t.getCustomVisualInputCards({frame:c,configCard:l||r,isMultiInputVisual:x}),[c,l,r,x]),w=y.useMemo(()=>t.buildSlotOrderedCards(j),[j]),T=y.useMemo(()=>w.map((f,L)=>{if(!f)return null;const E=t.getSlotIndexForCard(f,L),O=t.getEffectiveCardTypeForSlot(f,E,p==null?void 0:p.slots);return{...f,type:O??f.type}}),[w,p==null?void 0:p.slots]),P=y.useMemo(()=>Rr({slots:p==null?void 0:p.slots,cards:T,minInputs:g}),[p==null?void 0:p.slots,T,g]),N=y.useMemo(()=>{const f=j.findIndex(L=>(L==null?void 0:L.id)===r.id);return f<0?-1:t.getSlotIndexForCard(r,f)},[j,r]);function A(f){if(typeof f=="number")return`Tab ${f+1}`;const L=f.match(/^(\d+)-(\d+)$/);if(L){const[,O,B]=L;return`Tabs ${Number(O)+1}-${Number(B)+1}`}const E=f.match(/^(\d+)\+$/);return E?`Tabs ${Number(E[1])+1}+`:`Tab ${f}`}function S(f){return f?(Array.isArray(f)?f:[f]).join(", "):null}function I(f,L,E=[],O="",B,V,z){const _=D({key:L,defaultValue:O,settingsValue:V,sourceCard:z});return f==="input"?e.jsx(qe,{className:`h-8 w-full ${t.removeRing}`,value:String(_??""),onCommit:U=>{M({key:L,value:U,settingsField:B,settingsValue:V,sourceCard:z})}},L):f==="select"?e.jsx(nt,{className:"h-8 w-full",label:"",options:E,value:String(_!==void 0?_:O??""),onValueChange:U=>{M({key:L,value:U,settingsField:B,settingsValue:V,sourceCard:z})}}):null}function D({key:f,defaultValue:L,settingsValue:E,sourceCard:O}){const B=E==null?void 0:E[f];return B!==void 0?B:f==="title"&&(O==null?void 0:O.title)!==void 0?O.title:f==="description"&&(O==null?void 0:O.description)!==void 0?O.description:L}function M({key:f,value:L,settingsField:E,settingsValue:O,sourceCard:B}){const V={...O||{}},z=f==="title"&&(B==null?void 0:B.title)!==void 0,_=f==="description"&&(B==null?void 0:B.description)!==void 0;z&&L===String((B==null?void 0:B.title)??"")||_&&L===String((B==null?void 0:B.description)??"")?delete V[f]:V[f]=L,i({...s||{},[E]:V})}function v({settingsSchema:f,settingsField:L,settingsValue:E,sourceCard:O,headerLabel:B}){const V=Object.entries(f||{});return e.jsxs("div",{className:"space-y-3",children:[B&&e.jsx(t.Label,{children:B}),V.map(([z,_])=>{var U;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{children:_.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})})]})})]}),I(_.ui,z,_.options,_.defaultValue,L,E,O)]},z)})]})}function R(){return e.jsxs(e.Fragment,{children:[x&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Slot Guide"}),e.jsx("div",{className:"space-y-3 rounded-md border border-border bg-muted/40 px-3 py-2 text-xs",children:p!=null&&p.slots&&p.slots.length>0?e.jsx("div",{className:"space-y-3",children:p.slots.map((f,L)=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-foreground",children:[e.jsx("span",{className:"font-medium",children:A(f.position)}),e.jsx("span",{className:"text-muted-foreground",children:"•"}),e.jsx("span",{className:"font-medium",children:f.label})]}),f.description&&e.jsx("p",{className:"text-muted-foreground",children:f.description}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-muted-foreground",children:[S(f.expectedType)&&e.jsxs("span",{children:["Expected: ",S(f.expectedType)]}),f.required&&e.jsx("span",{children:"Required"})]})]},`${f.label}-${L}`))}):e.jsxs("div",{className:"space-y-1 text-muted-foreground",children:[e.jsx("p",{children:"This visual renders all tabs in a flexible layout. Add as many tabs as needed."}),(g||b)&&e.jsxs("p",{children:[g?`Min ${g} tabs`:"",g&&b?" • ":"",b?`Max ${b} tabs`:""]})]})})]}),x&&P.length>0&&e.jsx(t.Alert,{className:"mt-3 border-yellow-500/40 bg-yellow-500/10 text-yellow-900 dark:text-yellow-100",children:e.jsx(t.AlertDescription,{children:e.jsx("ul",{className:"list-disc space-y-1 pl-4 text-xs",children:P.map((f,L)=>e.jsx("li",{children:f.message},`${f.type}-${L}`))})})}),p&&!x&&p.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:v({settingsSchema:p.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:r})})}),p&&x&&(p.settings||p.slotSettings)&&e.jsxs("div",{className:"mt-4 space-y-4",children:[m&&p.settings&&e.jsx("div",{className:"px-2",children:v({settingsSchema:p.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:l||r,headerLabel:"Global Settings"})}),p.slotSettings&&e.jsx("div",{className:"px-2",children:v({settingsSchema:p.slotSettings,settingsField:"slotSettings",settingsValue:s==null?void 0:s.slotSettings,sourceCard:r,headerLabel:(()=>{const f=r.tabTitle||r.title,L=N>=0?N:0,E=m?"Slot 0":`Slot ${L}`;return f?`${E}: ${f} Settings`:`${E} Settings`})()})})]})]})}return e.jsxs(t.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"",children:[e.jsxs(t.AccordionItem,{value:"plugin-settings",children:[e.jsx(t.AccordionTrigger,{children:"Plugin"}),e.jsx(t.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[(!x||m)&&e.jsx(nt,{icon:e.jsx(Dn,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(d==null?void 0:d.url)||"",onValueChange:f=>i({...s||{url:"",componentName:""},url:f})}),x&&!m&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Switch to the config tab to change the plugin or component."})]})}),((s==null?void 0:s.type)==="component"||(s==null?void 0:s.type)===void 0)&&s&&(!x||m)&&e.jsx(e.Fragment,{children:o&&e.jsx(nt,{icon:e.jsx(fa,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(o==null?void 0:o.map(f=>({value:f.name,label:f.name})))||[],value:s.componentName||"",onValueChange:f=>{var O;const L=(O=u==null?void 0:u.visuals)==null?void 0:O.find(B=>B.name===f),E=o==null?void 0:o.find(B=>B.name===f);i({...s,componentName:f,visualType:(L==null?void 0:L.visualType)||(E==null?void 0:E.type)||"single",minInputs:L==null?void 0:L.minInputs,maxInputs:L==null?void 0:L.maxInputs,pluginChartType:L==null?void 0:L.chartType})}})})]})})]}),((d==null?void 0:d.componentName)||(s==null?void 0:s.componentName))&&e.jsxs(t.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(t.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:(p==null?void 0:p.name)||"Settings"}),(p==null?void 0:p.docs)&&e.jsxs(t.HoverCard,{openDelay:0,closeDelay:100,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,onClick:f=>f.stopPropagation(),children:e.jsx(t.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground transition-colors hover:text-foreground"})}),e.jsx(t.HoverCardContent,{side:"right",align:"start",className:"max-h-[40vh] w-[500px] overflow-y-auto text-left",children:e.jsxs("div",{className:"space-y-4 text-left",children:[p.docs.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:p.docs.description}),p.docs.dataSchema&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Data Schema"}),e.jsx("div",{className:"prose prose-sm dark:prose-invert prose-pre:bg-muted prose-pre:text-xs max-w-none",children:e.jsx(t.Markdown,{remarkPlugins:[t.remarkGfm],components:Or,children:p.docs.dataSchema})})]}),(()=>{var L;const f=(L=p.docs)==null?void 0:L.useCases;return!f||f.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Use Cases"}),e.jsx("ul",{className:"space-y-1 text-sm",children:f.map((E,O)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1 text-primary",children:"•"}),e.jsx("span",{children:E})]},O))})]})})()]})})]})]})}),e.jsx(t.AccordionContent,{children:R()})]})]})}function Pr({colorRanges:s,setColorRanges:a}){const n={start:-1/0,end:100,color:""};function r(l,d,o){const u=[...s];u[l]={...u[l],[d]:o},a(u)}function c(l){const d=[...s];d.splice(l,1),a(d)}function i(){a([...s,n])}return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{children:"Color Range"}),e.jsx(t.Button,{onClick:i,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(t.Plus,{className:"size-3"})})]}),s.map((l,d)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(t.Input,{onChange:o=>r(d,"start",o.target.value),value:l.start,className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(t.Input,{value:l.end,onChange:o=>r(d,"end",o.target.value),className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx(t.Input,{onChange:o=>r(d,"color",o.target.value),value:l.color,className:t.cn(`h-7 min-w-14 p-0 ${t.removeRing}`),type:"color",list:"presetColors"}),e.jsxs("datalist",{id:"presetColors",children:[e.jsx("option",{children:t.colors.green[600]}),e.jsx("option",{children:t.colors.red[500]}),e.jsx("option",{children:t.colors.yellow[400]}),e.jsx("option",{children:t.colors.orange[500]})]}),e.jsx(t.Button,{onClick:()=>c(d),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(t.X,{className:"size-3"})})]},d))]})}function Br(){var p,h,x,m,g;const s=t.useEditorStore(b=>b.card.preferences),a=t.useEditorStore(b=>b.actions.setCardPreferences),n=t.useEditorStore(b=>b.card),r=t.hasValidCardConfig(n.config),c=t.useEditorStore(b=>b.actions.setNumberFormat);t.useEditorStore(b=>{var j,w;return(w=(j=b.card.preferences)==null?void 0:j.formatNumber)==null?void 0:w.decimalPlaces});const i=t.useEditorStore(b=>{var j,w;return(w=(j=b.card.preferences)==null?void 0:j.formatNumber)==null?void 0:w.locale}),l=t.useEditorStore(b=>{var j,w;return(w=(j=b.card.preferences)==null?void 0:j.formatNumber)==null?void 0:w.currency});t.useEditorStore(b=>b.actions.setFilterOnClickField);const d=t.useEditorStore(b=>{var j,w;return(w=(j=b.card.preferences)==null?void 0:j.formatNumber)==null?void 0:w.colorRanges})||[],o=t.useEditorStore(b=>b.actions.setColorRanges),u=[...new Set(t.LOCALE_CURRENCY_PAIRS.map(b=>b.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(t.Checkbox,{checked:!!((p=s==null?void 0:s.formatNumber)!=null&&p.enabled),onCheckedChange:b=>{a({...s,formatNumber:{...s==null?void 0:s.formatNumber,enabled:b}})}}),e.jsx(t.Label,{children:"Format Number"})]}),(((h=s==null?void 0:s.formatNumber)==null?void 0:h.enabled)===!0||r)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Locale"}),e.jsxs(t.Select,{value:i||"none",onValueChange:b=>{var j,w,T;return c(((j=s==null?void 0:s.formatNumber)==null?void 0:j.decimalPlaces)||0,((w=s==null?void 0:s.formatNumber)==null?void 0:w.currency)||"",b,((T=s==null?void 0:s.formatNumber)==null?void 0:T.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(b=>e.jsx(t.SelectItem,{value:b.locale,children:b.locale},b.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:b=>{var j,w,T;console.log("currency",b),c(((j=s==null?void 0:s.formatNumber)==null?void 0:j.decimalPlaces)||0,b==="none"?"":b,((w=s==null?void 0:s.formatNumber)==null?void 0:w.locale)||"",((T=s==null?void 0:s.formatNumber)==null?void 0:T.suffix)||"")},children:[e.jsx(t.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Currency"}),e.jsx(t.SelectItem,{value:"none",children:"None"},"none"),u.map(b=>e.jsx(t.SelectItem,{value:b,children:b},b))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Decimals"}),e.jsxs(t.Select,{value:((m=(x=s==null?void 0:s.formatNumber)==null?void 0:x.decimalPlaces)==null?void 0:m.toString())||"0",onValueChange:b=>{var j,w,T;return c(Number(b),((j=s==null?void 0:s.formatNumber)==null?void 0:j.currency)||"",((w=s==null?void 0:s.formatNumber)==null?void 0:w.locale)||"",((T=s==null?void 0:s.formatNumber)==null?void 0:T.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(b=>e.jsx(t.SelectItem,{value:b,children:b},b))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Suffix"}),e.jsx(t.Input,{value:((g=s==null?void 0:s.formatNumber)==null?void 0:g.suffix)||"",className:"h-8 font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"K, M, B, %",onChange:b=>{var j,w,T;return c(((j=s==null?void 0:s.formatNumber)==null?void 0:j.decimalPlaces)||0,((w=s==null?void 0:s.formatNumber)==null?void 0:w.currency)||"",((T=s==null?void 0:s.formatNumber)==null?void 0:T.locale)||"",b.target.value)}})]})]})]})}),e.jsx(t.Separator,{className:"my-3"}),e.jsx(Pr,{colorRanges:d,setColorRanges:o})]})]})}const Vr={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 $n(s){return Vr[s]}function zr({chartType:s,showDocsLink:a=!0}){const n=$n(s);return n?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Query Format"}),e.jsx("code",{className:"block rounded-md bg-muted/50 px-3 py-2 font-mono text-xs text-foreground",children:n.query})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Fields"}),e.jsx("div",{className:"rounded-md border",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/50",children:[e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Field"}),e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Type"}),e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Description"})]})}),e.jsx("tbody",{children:n.fields.map((r,c)=>e.jsxs("tr",{className:c<n.fields.length-1?"border-b":"",children:[e.jsxs("td",{className:"px-2.5 py-1.5 font-medium text-foreground",children:[r.name,r.optional&&e.jsx("span",{className:"ml-1 text-muted-foreground",children:"?"})]}),e.jsx("td",{className:"px-2.5 py-1.5 font-mono text-muted-foreground",children:r.type}),e.jsx("td",{className:"px-2.5 py-1.5 text-muted-foreground",children:r.description||"—"})]},r.name))})]})})]}),e.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:n.description}),a&&n.docsUrl&&e.jsxs("a",{href:n.docsUrl,target:"_blank",rel:"noopener noreferrer",onClick:r=>r.stopPropagation(),className:"inline-flex items-center gap-1.5 text-xs font-medium text-primary hover:underline",children:["View documentation",e.jsx(t.ExternalLink,{className:"h-3 w-3"})]})]}):null}function _r({chartType:s}){return $n(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(zr,{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(_r,{chartType:s})]})}function qr(){return e.jsxs("div",{className:"space-y-6 px-6 py-4",children:[e.jsx(_t,{chartType:"kpi"}),e.jsx("section",{children:e.jsx(Br,{})})]})}function fn({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 Kn(){const[s,a]=y.useState([]),n=t.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:c}=t.useEditorStore(u=>u.actions),i=t.useEditorStore(u=>u.queryResultColumns);t.useEditorStore(u=>{var p;return(p=u.card.preferences)==null?void 0:p.filterOnClickColumnIndex}),y.useEffect(()=>{i&&a(new Array(i.length).fill(!1))},[i]);function l(u,p){var h,x;p?n!=null&&n.onClickFilter&&((h=n==null?void 0:n.onClickFilter)==null?void 0:h.length)>0?c({...n,onClickFilter:[...n.onClickFilter,{columnIndex:u,expression:""}]}):c({...n,onClickFilter:[{columnIndex:u,expression:""}]}):(c({...n,onClickFilter:(x=n==null?void 0:n.onClickFilter)==null?void 0:x.filter(m=>m.columnIndex!==u)}),a(m=>{const g=[...m];return g[u]=!1,g}))}function d(u,p){var x;const h=(x=n==null?void 0:n.onClickFilter)==null?void 0:x.map(m=>m.columnIndex===u?{...m,expression:p.target.value}:m);c({...n,onClickFilter:h})}function o(u){var p,h,x,m;if(s!=null&&s[u]||(h=(p=n==null?void 0:n.onClickFilter)==null?void 0:p.find(g=>g.columnIndex===u))!=null&&h.expression)return e.jsx(t.Input,{value:(m=(x=n==null?void 0:n.onClickFilter)==null?void 0:x.find(g=>g.columnIndex===u))==null?void 0:m.expression,onChange:g=>d(u,g),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsx("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:i==null?void 0:i.map((u,p)=>{var h,x;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(t.Checkbox,{checked:!!((h=n==null?void 0:n.onClickFilter)!=null&&h.find(m=>m.columnIndex===p)),onCheckedChange:m=>l(p,m)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:u}),e.jsx("div",{className:"flex items-center gap-2",children:((x=n==null?void 0:n.onClickFilter)==null?void 0:x.find(m=>m.columnIndex===p))&&e.jsx(t.Pencil,{onClick:()=>{a(m=>{const g=[...m];return g[p]=!m[p],g})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),o(p)]})},u)})})}const $r=[{label:"Mercator",value:"mercator"},{label:"Azimuthal Equidistant",value:"azimuthalEquidistant"},{label:"Gnomonic",value:"gnomonic"},{label:"Orthographic",value:"orthographic"},{label:"Stereographic",value:"stereographic"},{label:"Equal Earth",value:"equalEarth"},{label:"Albers",value:"albers"},{label:"Albers USA",value:"albersUsa"},{label:"Conic Conformal",value:"conicConformal"},{label:"Conic Equal Area",value:"conicEqualArea"},{label:"Conic Equidistant",value:"conicEquidistant"},{label:"Equirectangular",value:"equirectangular"},{label:"Transverse Mercator",value:"transverseMercator"},{label:"Natural Earth 1",value:"naturalEarth1"}],Kr=["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"],Gr=Kr.map(s=>({label:s,value:s}));function Ur(){var o,u,p,h,x,m,g,b,j,w,T,P,N,A,S,I,D,M;const s=t.useEditorStore(v=>v.card),a=(u=(o=s==null?void 0:s.preferences)==null?void 0:o.mapVisualOptions)==null?void 0:u.topoJsonUrl,[n,r]=y.useState(((h=(p=s==null?void 0:s.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:c}=t.useEditorActions(),{data:i}=t.useTopoJson(s),l=Object.keys((i==null?void 0:i.objects)||{}).map(v=>({label:v,value:v}))||[],d=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(_t,{chartType:"map"}),e.jsx(fn,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(nt,{className:"h-9",options:d,onValueChange:v=>{console.log("value",v),c({...s.preferences,mapVisualOptions:{topoJsonUrl:v}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(t.Input,{onChange:v=>{r(v.target.value)},onBlur:()=>{var v;console.log("onBlur",n),c({...s.preferences,mapVisualOptions:{...(v=s.preferences)==null?void 0:v.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:((m=(x=s.preferences)==null?void 0:x.mapVisualOptions)==null?void 0:m.objectKey)||"",label:"Map Object",onValueChange:v=>{var R;c({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,objectKey:v}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Projection"}),e.jsx(nt,{className:"h-9",options:$r,value:((b=(g=s.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:b.projection)||"",label:"Projection",onValueChange:v=>{var R;c({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,projection:v}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Colors"}),e.jsx(nt,{className:"h-9",options:Gr,value:((w=(j=s.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:w.colorScale)||"",label:"Select Color Scale",onValueChange:v=>{var R;c({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,colorScale:v}})}})]})]})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(fn,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:.1,value:((P=(T=s.preferences)==null?void 0:T.mapVisualOptions)==null?void 0:P.projectionScale)||1,onChange:v=>{var R;c({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,projectionScale:Number(v.target.value)}})}}),e.jsx(t.Label,{children:"X"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((S=(A=(N=s.preferences)==null?void 0:N.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:S[0])||0,onChange:v=>{var R,C,k,F;c({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,projectionOffset:[Number(v.target.value),((F=(k=(C=s.preferences)==null?void 0:C.mapVisualOptions)==null?void 0:k.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:((M=(D=(I=s.preferences)==null?void 0:I.mapVisualOptions)==null?void 0:D.projectionOffset)==null?void 0:M[1])||0,onChange:v=>{var R,C,k,F;c({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,projectionOffset:[((F=(k=(C=s.preferences)==null?void 0:C.mapVisualOptions)==null?void 0:k.projectionOffset)==null?void 0:F[0])||0,Number(v.target.value)]}})}})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(Kn,{})]})}function Gn({color:s,onColorChange:a,onClose:n}){const[r,c]=y.useState(0),[i,l]=y.useState(100),[d,o]=y.useState(50),[u,p]=y.useState(s);y.useEffect(()=>{const j=gn(s);if(j){const w=jn(j.r,j.g,j.b);c(w.h),l(w.s),o(w.l),p(s)}},[s]);const h=j=>{c(j),m(j,i,d)},x=j=>{const w=j.currentTarget.getBoundingClientRect(),T=Math.max(0,Math.min(1,(j.clientX-w.left)/w.width)),P=Math.max(0,Math.min(1,(j.clientY-w.top)/w.height)),N=T*100,A=(1-P)*100;l(N),o(A),m(r,N,A)},m=(j,w,T)=>{const P=Qr(j,w,T),N=Hr(P.r,P.g,P.b);p(N)},g=j=>{if(p(j),/^#[0-9A-Fa-f]{6}$/.test(j)){const w=gn(j);if(w){const T=jn(w.r,w.g,w.b);c(T.h),l(T.s),o(T.l)}}},b=()=>{/^#[0-9A-Fa-f]{6}$/.test(u)&&(a(u),n())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:x,onMouseMove:j=>{j.buttons===1&&x(j)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${i}%`,top:`${100-d}%`,backgroundColor:u}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:j=>h(Number(j.target.value)),className:"w-full h-4 rounded-lg appearance-none cursor-pointer",style:{background:"linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"}})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"HEX"}),e.jsx(t.Input,{value:u,onChange:j=>g(j.target.value),placeholder:"#000000",className:"font-mono"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:s}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:u}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(t.Button,{variant:"outline",onClick:n,children:"Cancel"}),e.jsx(t.Button,{onClick:b,children:"OK"})]})]})}function gn(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 Hr(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),c=Math.min(s,a,n);let i=0,l=0;const d=(r+c)/2;if(r!==c){const o=r-c;switch(l=d>.5?o/(2-r-c):o/(r+c),r){case s:i=((a-n)/o+(a<n?6:0))/6;break;case a:i=((n-s)/o+2)/6;break;case n:i=((s-a)/o+4)/6;break}}return{h:Math.round(i*360),s:Math.round(l*100),l:Math.round(d*100)}}function Qr(s,a,n){s/=360,a/=100,n/=100;let r,c,i;if(a===0)r=c=i=n;else{const l=(u,p,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?u+(p-u)*6*h:h<.5?p:h<.6666666666666666?u+(p-u)*(.6666666666666666-h)*6:u),d=n<.5?n*(1+a):n+a-n*a,o=2*n-d;r=l(o,d,s+1/3),c=l(o,d,s),i=l(o,d,s-1/3)}return{r:Math.round(r*255),g:Math.round(c*255),b:Math.round(i*255)}}const bn=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],Jr=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function at({value:s,onChange:a,label:n}){const[r,c]=y.useState(!1),[i,l]=y.useState(!1),d=()=>{const o=bn.find(u=>u.value===s);return o?o.color:s.startsWith("#")?s:bn[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Popover,{open:r,onOpenChange:c,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"size-5 rounded border-2 border-input shadow-sm transition-all hover:scale-110 hover:border-gray-400",style:{backgroundColor:d()},"aria-label":`Change color for ${n}`})}),e.jsx(t.PopoverContent,{align:"start",className:"w-auto p-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"grid grid-cols-3 items-center justify-items-center gap-1",children:Jr.map(o=>e.jsx("button",{className:t.cn("h-5 w-5 rounded border-2 transition-all",d()===o?"border-gray-900":"border-transparent"),style:{backgroundColor:o},onClick:()=>{a(o),c(!1)},children:e.jsx("span",{className:"sr-only",children:o})},o))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{l(!0),c(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:n})]}),i&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>l(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Gn,{color:d(),onColorChange:o=>{a(o),l(!1)},onClose:()=>l(!1)})})]})]})}function Bt(s){return s==="currency"?2:s==="percent"?1:s==="scientific"?2:0}function vn(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?is(n,Bt(a)):n}function is(s,a){return{...s,decimalPlaces:a,minimumFractionDigits:a,maximumFractionDigits:a}}const Yr=["auto","number","currency","percent","scientific","date"],Wr=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"GBP",label:"GBP - British Pound"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"CHF",label:"CHF - Swiss Franc"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"},{value:"HKD",label:"HKD - Hong Kong Dollar"},{value:"SGD",label:"SGD - Singapore Dollar"},{value:"NZD",label:"NZD - New Zealand Dollar"},{value:"SEK",label:"SEK - Swedish Krona"},{value:"NOK",label:"NOK - Norwegian Krone"},{value:"DKK",label:"DKK - Danish Krone"},{value:"KRW",label:"KRW - South Korean Won"},{value:"INR",label:"INR - Indian Rupee"},{value:"RUB",label:"RUB - Russian Ruble"},{value:"BRL",label:"BRL - Brazilian Real"},{value:"MXN",label:"MXN - Mexican Peso"},{value:"TRY",label:"TRY - Turkish Lira"},{value:"ZAR",label:"ZAR - South African Rand"},{value:"SAR",label:"SAR - Saudi Riyal"},{value:"AED",label:"AED - UAE Dirham"},{value:"ARS",label:"ARS - Argentine Peso"},{value:"CLP",label:"CLP - Chilean Peso"},{value:"COP",label:"COP - Colombian Peso"},{value:"THB",label:"THB - Thai Baht"},{value:"IDR",label:"IDR - Indonesian Rupiah"},{value:"MYR",label:"MYR - Malaysian Ringgit"},{value:"PHP",label:"PHP - Philippine Peso"},{value:"PLN",label:"PLN - Polish Zloty"},{value:"NGN",label:"NGN - Nigerian Naira"},{value:"KES",label:"KES - Kenyan Shilling"},{value:"GHS",label:"GHS - Ghanaian Cedi"},{value:"ZMW",label:"ZMW - Zambian Kwacha"},{value:"ZWL",label:"ZWL - Zimbabwean Dollar"},{value:"EGP",label:"EGP - Egyptian Pound"},{value:"MAD",label:"MAD - Moroccan Dirham"},{value:"UAH",label:"UAH - Ukrainian Hryvnia"},{value:"HUF",label:"HUF - Hungarian Forint"},{value:"CZK",label:"CZK - Czech Koruna"},{value:"RON",label:"RON - Romanian Leu"},{value:"PKR",label:"PKR - Pakistani Rupee"},{value:"BDT",label:"BDT - Bangladeshi Taka"},{value:"VND",label:"VND - Vietnamese Dong"},{value:"TWD",label:"TWD - New Taiwan Dollar"},{value:"ILS",label:"ILS - Israeli New Shekel"}],Xr=[{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"}],Zr=s=>s.charAt(0).toUpperCase()+s.slice(1);function jt({formatOptions:s={},onFormatOptionsChange:a,showTitle:n=!0,title:r="NUMBER FORMAT"}){const c=s.type||"auto",i=c==="auto"?s:vn(s,c),l=m=>{m.stopPropagation()},d=(m,g)=>{a({...i,[m]:g})},[o,u]=y.useState(()=>String(i.decimalPlaces??Bt(c))),[p,h]=y.useState(()=>i.multiplyBy!==void 0?String(i.multiplyBy):""),x=m=>{a(vn(s,m))};return y.useEffect(()=>{u(String(i.decimalPlaces??Bt(c)))},[i.decimalPlaces,c]),y.useEffect(()=>{h(i.multiplyBy!==void 0?String(i.multiplyBy):"")},[i.multiplyBy]),e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[n&&e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(t.Select,{value:c,onValueChange:m=>x(m),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",onClick:l,onPointerDown:l,onKeyDown:l,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Yr.map(m=>e.jsx(t.SelectItem,{value:m,className:"text-xs",children:m==="auto"?"Auto (Default)":Zr(m)},m))})]})]}),c!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent","scientific"].includes(c)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{type:"text",inputMode:"numeric",min:"0",max:"10",placeholder:"0",value:o,onClick:l,onPointerDown:l,onKeyDown:l,onChange:m=>{const g=m.target.value.replace(/[^\d]/g,"");u(g),g!==""&&a(is(i,Math.max(0,Math.min(10,parseInt(g,10)))))},onBlur:()=>{if(o!=="")return;const m=Bt(c);u(String(m)),a(is(i,m))},className:"h-8 text-xs"})})]}),c==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(t.Select,{value:s.currency||"USD",onValueChange:m=>d("currency",m),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:l,onPointerDown:l,onKeyDown:l,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Wr.map(m=>e.jsx(t.SelectItem,{value:m.value,className:"text-xs",children:m.label},m.value))})]})]}),["number","currency"].includes(c)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(t.Switch,{size:"sm",checked:s.useSuffix??!1,onClick:m=>m.stopPropagation(),onCheckedChange:m=>d("useSuffix",m)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(t.Select,{value:s.locale||"en-US",onValueChange:m=>d("locale",m),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:l,onPointerDown:l,onKeyDown:l,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Xr.map(m=>e.jsx(t.SelectItem,{value:m.value,className:"text-xs",children:m.label},m.value))})]})]}),c==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{placeholder:"e.g., $",value:s.prefix||"",onClick:l,onPointerDown:l,onKeyDown:l,onChange:m=>d("prefix",m.target.value),className:"h-8 text-xs"})})]}),c==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{placeholder:"e.g., units",value:s.suffix||"",onClick:l,onPointerDown:l,onKeyDown:l,onChange:m=>d("suffix",m.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(c)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Negative in ()"}),e.jsx(t.Switch,{size:"sm",checked:s.negativeInParentheses??!1,onClick:m=>m.stopPropagation(),onCheckedChange:m=>d("negativeInParentheses",m)})]}),c==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{type:"text",inputMode:"decimal",placeholder:"100",value:p,onClick:l,onPointerDown:l,onKeyDown:l,onChange:m=>{const g=m.target.value.replace(/[^0-9.]/g,"");h(g),d("multiplyBy",g?parseFloat(g):void 0)},className:"h-8 text-xs"})})]}),c==="date"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Format"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{type:"text",placeholder:"MM/DD/YYYY",value:s.dateFormat||"",onClick:l,onPointerDown:l,onKeyDown:l,onChange:m=>d("dateFormat",m.target.value),className:"h-8 text-xs"})})]})]})]})}function hs({value:s,onChange:a,showTitle:n=!0,title:r="NUMBER FORMAT"}){const c=t.toTFormatOptions(t.fromSemanticFormat(s))||{},i=l=>{a(t.fromTFormatOptions(l))};return e.jsx(jt,{formatOptions:c,onFormatOptionsChange:i,showTitle:n,title:r})}function el(){const s=t.useDashboardStore(d=>d.dashboard.filters),a=t.useEditorStore(d=>d.frame),{setFrame:n}=t.useEditorActions(),{dashboardFilterableFields:r}=t.useFilterableFields(),{assignFilter:c}=t.useAssignFilter();function i(d){const o=c(d,"frame");n({...a,filterId:o})}const l=s==null?void 0:s.find(d=>d.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Card Filter"}),e.jsx(tl,{onSelect:i,columns:r}),l&&e.jsx(t.FilterHeader,{filter:l})]})}function tl({columns:s,onSelect:a}){var d;const[n,r]=Pt.useState(!1),[c,i]=Pt.useState(""),l=Pt.useCallback(o=>[o.label,o.name,o.qualifiedEntityName].filter(Boolean).join(" "),[]);return e.jsxs(t.Popover,{open:n,onOpenChange:r,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[c?((d=s.find(o=>o.id===c))==null?void 0:d.label)||c:"Select Column...",e.jsx(t.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No column found."}),e.jsx(t.CommandGroup,{children:s==null?void 0:s.map(o=>e.jsxs(t.CommandItem,{value:l(o),onSelect:()=>{const u=o.id===c?"":o.id;i(u),r(!1),u&&a(o)},children:[o.label||o.name,e.jsx(t.CheckIcon,{className:t.cn("ml-auto h-4 w-4",c===o.id?"opacity-100":"opacity-0")})]},o.id))})]})]})})]})}const sl=[{value:"difference",label:"Difference"},{value:"change",label:"Change (%)"},{value:"change_difference",label:"Change + Difference"},{value:"ratio",label:"Ratio"}],nl=[{value:"arrow_badge",label:"Arrow + Badge"},{value:"arrow",label:"Arrow Only"},{value:"badge",label:"Badge Only"},{value:"none",label:"None"}];function al({cardType:s="table"}){var p,h,x,m,g;const a=t.useEditorStore(b=>b.card),n=t.useEditorStore(b=>{var j;return(j=b.card)==null?void 0:j.preferences}),r=t.useEditorStore(b=>b.actions.setCardPreferences),c=((p=a.config)==null?void 0:p.metricColumns)||[],i=c.some(b=>b.comparisonType&&b.comparisonType!=="none"),l=((h=n==null?void 0:n.tableVisualOptions)==null?void 0:h.metricComparison)||{},d=b=>{r({...n,tableVisualOptions:{...n==null?void 0:n.tableVisualOptions,metricComparison:{...l,...b}}})},o={increase:((x=l.colors)==null?void 0:x.increase)||"green",decrease:((m=l.colors)==null?void 0:m.decrease)||"red",neutral:((g=l.colors)==null?void 0:g.neutral)||"neutral"},u=b=>{r({...n,allowDownload:b})};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(An,{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:b=>d({calculatedAs:b}),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:sl.map(b=>e.jsx(t.SelectItem,{value:b.value,className:"text-xs",children:b.label},b.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:b=>d({formatOptions:b}),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:b=>d({indicatorStyle:b}),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:nl.map(b=>e.jsx(t.SelectItem,{value:b.value,className:"text-xs",children:b.label},b.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:b=>d({colors:{...o,increase:b}}),label:"Increase"}),e.jsx(at,{value:o.decrease,onChange:b=>d({colors:{...o,decrease:b}}),label:"Decrease"}),e.jsx(at,{value:o.neutral,onChange:b=>d({colors:{...o,neutral:b}}),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:b=>d({lowerIsBetter:!!b})})]})]})]}),c.length>0&&e.jsxs(t.AccordionItem,{value:"metric-formats",className:"border-none",children:[e.jsx(t.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsx("span",{children:"Metric Formats"})}),e.jsx(t.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:c.map(b=>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:b.label||b.name}),e.jsx(hs,{value:b.format,onChange:j=>{var T;const w=(((T=a.config)==null?void 0:T.metricColumns)||[]).map(P=>P.id===b.id?{...P,format:j}:P);t.useEditorStore.getState().actions.updateCardConfig(a.id,{metricColumns:w})},showTitle:!1})]},b.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(Kn,{}),e.jsx(el,{})]})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Checkbox,{onCheckedChange:u,id:"allow-download"}),e.jsx("label",{htmlFor:"allow-download",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Allow Download"})]})]})}function rl(){var r;const s=t.useEditorStore(c=>c.card.preferences),{setCardPreferences:a}=t.useEditorStore(c=>c.actions);function n(c){a({...s,textVisualOptions:{...s==null?void 0:s.textVisualOptions,isDynamicText:c==="dynamic"}})}return e.jsxs(t.RadioGroup,{value:(r=s==null?void 0:s.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:n,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function ll(){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(rl,{})]})]})}const ol=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function il(){var A,S,I,D,M,v,R,C,k,F;const s=t.useEditorStore(f=>f.card),a=t.useEditorStore(f=>{var L;return(L=f.card)==null?void 0:L.preferences}),n=ke.useEffectiveEditorCardType(),{setCardPreferences:r,updateCardInFrame:c}=t.useEditorActions(),i=y.useMemo(()=>n!==s.type?{...s,type:n}:s,[s,n]),{data:l}=t.useEditorCardQuery(i),[d,o]=y.useState({}),[u,p]=y.useState(null),[h,x]=y.useState(null),m=y.useMemo(()=>{var O,B,V,z,_,U,H;if(!(l!=null&&l.records)||l.records.length===0)return[];const f=n==="stackedBar"||n==="stackedLine",L=n==="bar"||n==="line"||n==="horizontalBar"||n==="bullet"||n==="combo"||n==="area"||n==="stackedArea",E=((O=s==null?void 0:s.config)==null?void 0:O.pivotByColumns)&&s.config.pivotByColumns.length>0;if((f||L)&&E){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const $=new Set;return l.pivotSchema.forEach(Z=>{Z.alias&&$.add(Z.alias)}),Array.from($)}if(l.records.length>0){const $=l.records[0],Z=Object.keys($),re=new Set;(B=s==null?void 0:s.config)!=null&&B.groupByColumns&&s.config.groupByColumns.forEach(he=>{re.add(he.label||he.name),re.add(he.alias||he.name)});const ie=new Set;return(V=s==null?void 0:s.config)!=null&&V.metricColumns&&s.config.metricColumns.forEach(he=>{const me=he.alias||he.name;ie.add(me),ie.add(`${me}_count`),ie.add(`${me}_sum`),ie.add(`${me}_avg`),ie.add(`${me}_min`),ie.add(`${me}_max`);const se=he.entityName||he.qualifiedEntityName;se&&(ie.add(`${se}_${me}`),ie.add(`${se}_${me}_count`))}),Z.filter(he=>!re.has(he)&&!ie.has(he))}}if((L||f)&&!E&&((_=(z=s==null?void 0:s.config)==null?void 0:z.metricColumns)!=null&&_.length))return s.config.metricColumns.map($=>$.alias||$.label||$.name);if((H=(U=s==null?void 0:s.config)==null?void 0:U.groupByColumns)!=null&&H.length){const $=s.config.groupByColumns[0],Z=$.label||$.name,re=new Set;return l.records.forEach(ie=>{const ce=ie[Z];ce!=null&&re.add(String(ce))}),Array.from(re)}return[]},[l,(A=s==null?void 0:s.config)==null?void 0:A.groupByColumns,(S=s==null?void 0:s.config)==null?void 0:S.pivotByColumns,(I=s==null?void 0:s.config)==null?void 0:I.metricColumns,n]),g=y.useMemo(()=>t.getDefaultChartColors(),[]);y.useEffect(()=>{const f={};m.forEach((L,E)=>{f[L]=t.getColorForValue(L,E,a==null?void 0:a.colorConfig)}),o(f)},[m,a==null?void 0:a.colorConfig,g]);const b=(f,L)=>{const E={...d,[f]:L};o(E);const O={...a||{},colorConfig:{segments:E}};r(O);const B={...s,preferences:O};c(B)},j=(f,L)=>{var _;const E=g[L%g.length],{[f]:O,...B}=((_=a==null?void 0:a.colorConfig)==null?void 0:_.segments)||{},V={...a||{},colorConfig:{segments:B}};r(V);const z={...s,preferences:V};c(z),o(U=>({...U,[f]:E}))};if(!m.length||!((s==null?void 0:s.type)==="stackedBar"||(s==null?void 0:s.type)==="stackedLine"?((M=(D=s==null?void 0:s.config)==null?void 0:D.groupByColumns)==null?void 0:M.length)||((R=(v=s==null?void 0:s.config)==null?void 0:v.pivotByColumns)==null?void 0:R.length):(k=(C=s==null?void 0:s.config)==null?void 0:C.groupByColumns)==null?void 0:k.length)||["table","kpi","text","custom","heatmap"].includes(n))return null;const P=()=>{const f={...a||{},colorConfig:{segments:{}}};r(f);const L={...s,preferences:f};c(L);const E={};m.forEach((O,B)=>{E[O]=t.getColorForValue(O,B,void 0)}),o(E)},N=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-sm 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:"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:N&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:P,children:[e.jsx(os,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:m.map((f,L)=>{const E=t.isDefaultColor(d[f],L),O=!E;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Popover,{open:u===f,onOpenChange:B=>p(B?f:null),children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"h-5 w-5 shrink-0 rounded border border-input shadow-sm transition-colors hover:border-gray-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",style:{backgroundColor:d[f]}})}),e.jsx(t.PopoverContent,{align:"start",className:"w-auto p-3",children:e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Theme Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:g.slice(0,10).map((B,V)=>e.jsxs("button",{className:t.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",d[f]===B?"border-gray-900":"border-transparent"),style:{backgroundColor:B},onClick:()=>{b(f,B),p(null)},children:[V===L%g.length&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-white/90 px-0.5 text-[8px] font-bold text-gray-900 shadow-sm",children:"D"})}),e.jsx("span",{className:"sr-only",children:B})]},`default-${V}`))})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Popular Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:ol.map((B,V)=>e.jsx("button",{className:t.cn("h-5 w-5 rounded border transition-all hover:scale-110",d[f]===B?"border-2 border-gray-900":B==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:B},onClick:()=>{b(f,B),p(null)},children:e.jsx("span",{className:"sr-only",children:B})},`preset-${V}`))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsx("button",{className:"text-sm font-medium text-blue-600 hover:text-blue-700",onClick:()=>{x({value:f,color:d[f]}),p(null)},children:"Custom color"}),!E&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{j(f,L),p(null)},children:[e.jsx(os,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:f}),O&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},f)})}),h&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>x(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Gn,{color:h.color,onColorChange:f=>{b(h.value,f),x(null)},onClose:()=>x(null)})})]})]})})]})}function He({value:s,onSave:a,placeholder:n="",type:r="text",className:c=""}){const[i,l]=y.useState(s??""),[d,o]=y.useState(!1);y.useEffect(()=>{l(s??"")},[s]);const u=()=>{a(i),o(!1)},p=()=>{l(s??""),o(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${c}`,children:[e.jsx(t.Input,{placeholder:n,type:r,value:d?i:s??"",onChange:h=>{l(h.target.value),o(!0)},onFocus:()=>o(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&d&&i!==s?u():h.key==="Escape"&&p()},"aria-label":n||"Edit field"}),d&&i!==s&&e.jsxs(e.Fragment,{children:[e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:u,children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:p,children:e.jsx(t.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function ss({axis:s,label:a,type:n,config:r,onChange:c,defaultTitle:i,hidePosition:l}){var g,b,j,w,T,P,N,A,S,I,D,M,v,R;const d=t.normalizeContextFormatMode({formatMode:r==null?void 0:r.formatMode,formatOptions:r==null?void 0:r.formatOptions}),o=(C,k)=>{c({...r??{},[C]:k})},u=(C,k)=>{var E,O,B,V;const F=C==="enabled"&&k===!0,f=(E=r==null?void 0:r.name)==null?void 0:E.text,L=F&&!f&&i;c({...r??{},name:{...r==null?void 0:r.name,enabled:C==="enabled"?k:((O=r==null?void 0:r.name)==null?void 0:O.enabled)??!1,text:C==="text"?k:L?i:f,fontSize:C==="fontSize"?k:(B=r==null?void 0:r.name)==null?void 0:B.fontSize,fontWeight:C==="fontWeight"?k:(V=r==null?void 0:r.name)==null?void 0:V.fontWeight}})},p=(C,k)=>{var F,f;c({...r??{},labels:{enabled:C==="enabled"?k:((F=r==null?void 0:r.labels)==null?void 0:F.enabled)??!0,rotation:C==="rotation"?k:(f=r==null?void 0:r.labels)==null?void 0:f.rotation}})},h=(C,k)=>{c({...r??{},scale:{...r==null?void 0:r.scale,[C]:k===""?"auto":Number(k)}})},x=s==="x"?["auto","top","bottom"]:["auto","left","right"],m=["auto","0","45","90","-45","-90"];return e.jsxs(t.AccordionItem,{value:`${s}-axis`,className:"border-b-0",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx(t.AccordionTrigger,{className:"flex grow items-center justify-between gap-3 py-2 text-sm font-medium hover:no-underline",children:e.jsx("div",{className:"flex grow items-center justify-between gap-2",children:e.jsx("span",{children:a})})}),e.jsx(t.Switch,{size:"sm",checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:C=>o("enabled",C),onClick:C=>C.stopPropagation()})]}),e.jsxs(t.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Checkbox,{id:`${s}-title-enabled`,checked:((g=r==null?void 0:r.name)==null?void 0:g.enabled)??!1,onCheckedChange:C=>u("enabled",C===!0)}),e.jsx(t.Label,{htmlFor:`${s}-title-enabled`,className:"text-xs font-medium cursor-pointer",children:"TITLE"})]}),((b=r==null?void 0:r.name)==null?void 0:b.enabled)&&e.jsxs("div",{className:"space-y-2 pl-6",children:[e.jsx(He,{placeholder:`${a} title`,value:((j=r==null?void 0:r.name)==null?void 0:j.text)||"",onSave:C=>u("text",C),className:""}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Size"}),e.jsx("div",{className:"w-14",children:e.jsx(He,{type:"number",placeholder:"12",value:String(((w=r==null?void 0:r.name)==null?void 0:w.fontSize)||12),onSave:C=>u("fontSize",Number(C)||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:((T=r==null?void 0:r.name)==null?void 0:T.fontWeight)||"normal",onValueChange:C=>u("fontWeight",C),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:C=>o("position",C),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:x.map(C=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:C==="auto"?"Auto (Default)":t.titleCase(C)},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",children:"LABELS"}),e.jsx(t.Switch,{size:"sm",checked:((P=r==null?void 0:r.labels)==null?void 0:P.enabled)!==!1,onCheckedChange:C=>p("enabled",C)})]}),((N=r==null?void 0:r.labels)==null?void 0:N.enabled)!==!1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Rotation"}),e.jsxs(t.Select,{value:String(((A=r==null?void 0:r.labels)==null?void 0:A.rotation)||"auto"),onValueChange:C=>p("rotation",C==="auto"?"auto":Number(C)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:m.map(C=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:C==="auto"?"Auto (Default)":`${C}°`},C))})]})]})]}),n==="value"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"FORMAT"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Inherit from the bound metric by default."})]}),e.jsx(t.Switch,{size:"sm",checked:d==="override",onCheckedChange:C=>c({...r,formatMode:C?"override":"inherit"})})]}),d==="override"&&e.jsx(jt,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:C=>c({...r,formatMode:"override",formatOptions:C}),showTitle:!1})]}),n==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"SCALE"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(He,{type:"number",placeholder:"auto",value:((S=r==null?void 0:r.scale)==null?void 0:S.min)==="auto"||((I=r==null?void 0:r.scale)==null?void 0:I.min)===void 0?"":String(r.scale.min),onSave:C=>h("min",C),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-8 text-xs text-muted-foreground",children:"Max"}),e.jsx("div",{className:"flex-1",children:e.jsx(He,{type:"number",placeholder:"auto",value:((D=r==null?void 0:r.scale)==null?void 0:D.max)==="auto"||((M=r==null?void 0:r.scale)==null?void 0:M.max)===void 0?"":String(r.scale.max),onSave:C=>h("max",C),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-8 text-xs text-muted-foreground",children:"Step"}),e.jsx("div",{className:"flex-1",children:e.jsx(He,{type:"number",placeholder:"auto",value:((v=r==null?void 0:r.scale)==null?void 0:v.stepSize)==="auto"||((R=r==null?void 0:r.scale)==null?void 0:R.stepSize)===void 0?"":String(r.scale.stepSize),onSave:C=>h("stepSize",C),className:""})})]})]})]})]})]})}function ns(s,a,n){var i,l,d;if(s==="x"){const o=(l=(i=a==null?void 0:a.config)==null?void 0:i.groupByColumns)==null?void 0:l[0];return(o==null?void 0:o.label)||(o==null?void 0:o.name)||""}const r=((d=a==null?void 0:a.config)==null?void 0:d.metricColumns)||[],c=(n==null?void 0:n.datasetOptions)||[];if(s==="y"){const o=r.filter((u,p)=>{const h=c.find(x=>x.idx===p);return!h||h.yAxisId!=="y2"});return o.length===1&&(o[0].label||o[0].name)||""}if(s==="y2"){const o=r.filter((u,p)=>{const h=c.find(x=>x.idx===p);return(h==null?void 0:h.yAxisId)==="y2"});return o.length===1&&(o[0].label||o[0].name)||""}return""}function cl(){const s=t.useEditorStore(o=>o.card),a=t.useEditorStore(o=>{var u;return(u=o.card)==null?void 0:u.preferences}),{setCardPreferences:n,updateCardInFrame:r}=t.useEditorActions(),c=ke.useEffectiveEditorCardType();if(!s||["tornado","pyramid","kpi","treemap"].includes(c))return null;const i=t.AxisConfigurator.getAxisInfo(c,a);if(!i.hasXAxis&&!i.hasYAxis)return null;const l=(o,u)=>{let p;o==="x"?p="xAxisConfig":o==="y"?p="yAxisConfig":p="secondaryYAxisConfig";const h={...a||{},[p]:u};n(h);const x={...s,preferences:h};r(x)},d=i.hasY2Axis&&c==="combo";return e.jsxs(t.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.SlidersHorizontal,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Axes"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsxs(t.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[i.hasXAxis&&e.jsx(ss,{axis:"x",label:"X-Axis",type:i.xAxisType,config:t.mergeAxisConfig(t.getDefaultAxisConfig(c,"x"),a==null?void 0:a.xAxisConfig),onChange:o=>l("x",o),defaultTitle:ns("x",s,a)}),i.hasYAxis&&e.jsx(ss,{axis:"y",label:d?"Y-Axis (Left)":"Y-Axis",type:i.yAxisType,config:t.mergeAxisConfig(t.getDefaultAxisConfig(c,"y"),a==null?void 0:a.yAxisConfig),onChange:o=>l("y",o),defaultTitle:ns("y",s,a)}),d&&e.jsx(ss,{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:ns("y2",s,a),hidePosition:!0})]})})]})}function dl(){const s=t.useEditorStore(h=>h.card),a=ke.useEffectiveEditorCardType(),n=t.useEditorStore(h=>{var x,m,g,b;return(b=(g=(m=(x=h.card)==null?void 0:x.preferences)==null?void 0:m.chartOptions)==null?void 0:g.plugins)==null?void 0:b.legend}),{setLegendOptions:r}=t.useEditorActions();if(!s||!t.chartSupportsLegend(a))return null;const c=t.getDefaultLegendConfig(a),i=(c==null?void 0:c.display)??!0,l=(c==null?void 0:c.position)??"top",d=(c==null?void 0:c.align)??"center",o=(h,x)=>{const m={...n,[h]:x};r(m)},u=["top","bottom","left","right"],p=["start","center","end"];return e.jsxs(t.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(va,{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:h=>o("display",h)})]}),((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:h=>o("position",h),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:u.map(h=>e.jsx(t.SelectItem,{value:h,className:"text-xs",children:t.titleCase(h)},h))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(t.Select,{value:(n==null?void 0:n.align)||d,onValueChange:h=>o("align",h),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:p.map(h=>e.jsx(t.SelectItem,{value:h,className:"text-xs",children:t.titleCase(h)},h))})]})]})]})]})})]})}function ul(){var k,F,f,L,E,O,B;const s=t.useEditorStore(V=>V.card),a=ke.useEffectiveEditorCardType(),n=t.useEditorStore(V=>{var z,_;return(_=(z=V.card)==null?void 0:z.preferences)==null?void 0:_.dataLabelsConfig}),r=t.useEditorStore(V=>{var z;return(z=V.card)==null?void 0:z.preferences}),{setCardPreferences:c,updateCardInFrame:i}=t.useEditorActions();if(!s||!t.chartSupportsDataLabels(a))return null;const l=a==="bullet"?((k=r==null?void 0:r.bulletConfig)==null?void 0:k.orientation)??(((F=r==null?void 0:r.chartOptions)==null?void 0:F.indexAxis)==="x"?"vertical":"horizontal"):void 0,d=l!=null?l==="horizontal":((f=r==null?void 0:r.chartOptions)==null?void 0:f.indexAxis)==="y",o=a==="stackedBar"||a==="stackedLine",u=a==="pie"||a==="doughnut"||a==="polarArea"||a==="funnel",p=a==="bubble"||a==="scatter",h=(E=(L=r==null?void 0:r.chartOptions)==null?void 0:L.plugins)==null?void 0:E.datalabels,x=(h==null?void 0:h.display)!==!1&&((h==null?void 0:h.anchor)||(h==null?void 0:h.align)),m=t.getDefaultDataLabelsConfig(a,s.preferences),g=n??m,b=(m==null?void 0:m.enabled)??x??!1,j=(n==null?void 0:n.enabled)!==void 0?n.enabled:b,w=(V,z)=>{const H={...m??{},...n??{},[V]:z};V==="enabled"&&(H.display=z,z&&p&&!H.position&&(H.position="bottom")),V==="position"&&p&&(H.position="bottom"),V==="formatMode"&&z==="inherit"&&(H.format=void 0,H.formatOptions=void 0);const $={...s.preferences||{},dataLabelsConfig:H};c($);const Z={...s,preferences:$};i(Z)},T=(V,z)=>{const _=n??{},H={...m??{},..._,font:{..._.font||{},[V]:z}},$={...s.preferences||{},dataLabelsConfig:H};c($);const Z={...s,preferences:$};i(Z)},P=()=>{const V=a;return V==="stackedBar"||V==="stackedLine"||V==="pie"||V==="doughnut"?"center":d?"right":"top"},N=a!=="treemap"&&a!=="heatmap",A=a!=="treemap",S=P();let I=[];if(N)if(p)I=["bottom"];else if(o||u)I=["center"];else{const V=d?["center","left","right"]:["center","top","bottom"];I=["auto",...a==="bullet"?V:V.filter(_=>_!==S),"custom"]}const D=()=>t.titleCase(S),M=["center","start","end"],v=["center","start","end","top","bottom"],R=(g==null?void 0:g.formatMode)||(g!=null&&g.format&&!["auto"].includes(g.format)?"override":"inherit"),C=(g==null?void 0:g.format)==="none";return e.jsxs(t.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(La,{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:j,onCheckedChange:V=>w("enabled",V)})]}),j&&e.jsxs(e.Fragment,{children:[N&&!o&&!u&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(t.Select,{value:p?(g==null?void 0:g.position)||"bottom":(g==null?void 0:g.position)||"auto",onValueChange:V=>w("position",V),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:I.map(V=>e.jsx(t.SelectItem,{value:V,className:"text-xs",children:V==="auto"?D():V==="custom"?"Custom (Advanced)":t.titleCase(V)},V))})]})]}),o&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Show Total"}),e.jsx(t.Switch,{size:"sm",checked:(n==null?void 0:n.showTotal)??!1,onCheckedChange:V=>w("showTotal",V)})]}),(g==null?void 0:g.position)==="custom"&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground w-16",children:"Anchor"}),e.jsxs(t.Select,{value:(g==null?void 0:g.anchor)||"center",onValueChange:V=>w("anchor",V),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:M.map(V=>e.jsx(t.SelectItem,{value:V,className:"text-xs",children:t.titleCase(V)},V))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground w-16",children:"Align"}),e.jsxs(t.Select,{value:String((g==null?void 0:g.align)||"center"),onValueChange:V=>w("align",V),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:v.map(V=>e.jsx(t.SelectItem,{value:V,className:"text-xs",children:t.titleCase(V)},V))})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Format"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Keep this off to inherit from the bound metric."})]}),e.jsx(t.Switch,{size:"sm",checked:R==="override",onCheckedChange:V=>w("formatMode",V?"override":"inherit")})]}),R==="override"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Raw Value"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Show the unformatted numeric value."})]}),e.jsx(t.Switch,{size:"sm",checked:C,onCheckedChange:V=>{const z=n??{},U={...m??{},...z,formatMode:"override",format:V?"none":void 0,formatOptions:V?void 0:z.formatOptions},H={...s.preferences||{},dataLabelsConfig:U};c(H),i({...s,preferences:H})}})]}),!C&&e.jsx(jt,{formatOptions:(g==null?void 0:g.formatOptions)||{},onFormatOptionsChange:V=>{const U={...m??{},...n??{},formatMode:"override",format:V.type&&V.type!=="auto"?V.type:void 0,formatOptions:V},H={...s.preferences||{},dataLabelsConfig:U};c(H),i({...s,preferences:H})},showTitle:!1})]})]}),A&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Appearance"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground w-20",children:"Size"}),e.jsx("div",{className:"flex-1",children:e.jsx(He,{type:"number",placeholder:"12",value:String(((O=g==null?void 0:g.font)==null?void 0:O.size)||12),onSave:V=>T("size",Number(V)),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground w-20",children:"Weight"}),e.jsxs(t.Select,{value:((B=g==null?void 0:g.font)==null?void 0:B.weight)||"normal",onValueChange:V=>T("weight",V),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(t.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground w-20",children:"Color"}),e.jsxs(t.Select,{value:(g==null?void 0:g.color)==="auto"||!(g!=null&&g.color)?"auto":"custom",onValueChange:V=>{V==="auto"&&w("color","auto")},children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Smart Contrast)"}),e.jsx(t.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom (Coming Soon)"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground w-20",children:"Rotation"}),e.jsx("div",{className:"flex-1",children:e.jsx(He,{type:"number",placeholder:"0",value:String((g==null?void 0:g.rotation)||0),onSave:V=>w("rotation",Number(V)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}const yn={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%
|
|
183
|
+
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 ml(){var x,m,g,b,j,w,T,P,N,A;const s=t.useEditorStore(S=>S.card),{setCardPreferences:a}=t.useEditorActions(),n=ke.useEffectiveEditorCardType(),r=((x=s.config)==null?void 0:x.metricColumns)||[],c=((m=s.config)==null?void 0:m.groupByColumns)||[],i=r.length===2&&c.length===0,l=r.some(S=>S.comparisonType&&S.comparisonType!=="none");if(!(n==="kpi"&&(i||l)))return null;const o=((b=(g=s.preferences)==null?void 0:g.kpiVisualOptions)==null?void 0:b.metricComparison)||{},u=S=>{var D;const I={...s.preferences,kpiVisualOptions:{...(D=s.preferences)==null?void 0:D.kpiVisualOptions,metricComparison:{...o,...S}}};a(I)},p=l||o.enabled,h=r.some(S=>S.comparisonType==="previous_period"||S.comparisonType==="same_period_last_year"||S.comparisonType==="start_vs_end");return e.jsxs(t.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(t.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(An,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[i&&r.length===2&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(t.Switch,{size:"sm",id:"enable-comparison",checked:o.enabled||!1,onCheckedChange:S=>u({enabled:S,...S&&!o.calculationType?{calculationType:"difference"}:{}})})]}),p&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(t.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.Info,{className:"h-3 w-3 cursor-help text-muted-foreground"})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:(()=>{const S=o.calculationType||"difference",I=yn[S];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:I==null?void 0:I.label}),e.jsx("p",{children:I==null?void 0:I.description}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Formula:"})," ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-[10px]",children:I==null?void 0:I.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",I==null?void 0:I.example]})]})})()})]})]}),e.jsxs(t.Select,{value:o.calculationType||"difference",onValueChange:S=>u({calculationType:S}),children:[e.jsx(t.SelectTrigger,{id:"calculation-type",className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Object.entries(yn).map(([S,I])=>e.jsx(t.SelectItem,{value:S,className:"text-xs",children:I.label},S))})]})]}),e.jsx(jt,{formatOptions:o.formatOptions||{},onFormatOptionsChange:S=>u({formatOptions:S}),showTitle:!0,title:"COMPARISON FORMAT"}),(h||i)&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator"}),i&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(t.Select,{value:o.position||"right",onValueChange:S=>u({position:S}),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"right",className:"text-xs",children:"Right"}),e.jsx(t.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(t.SelectItem,{value:"top",className:"text-xs",children:"Top"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Checkbox,{id:"show-arrow",checked:o.showArrow!==!1,onCheckedChange:S=>u({showArrow:S})}),e.jsx(t.Label,{htmlFor:"show-arrow",className:"cursor-pointer text-xs text-muted-foreground",children:"Arrow"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Checkbox,{id:"show-color",checked:o.showColor!==!1,onCheckedChange:S=>u({showColor:S})}),e.jsx(t.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),o.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(at,{value:((j=o.colorConfig)==null?void 0:j.increase)||"green",onChange:S=>u({colorConfig:{...o.colorConfig,increase:S}}),label:"Primary > Secondary"}),e.jsx(at,{value:((w=o.colorConfig)==null?void 0:w.decrease)||"red",onChange:S=>u({colorConfig:{...o.colorConfig,decrease:S}}),label:"Primary < Secondary"}),e.jsx(at,{value:((T=o.colorConfig)==null?void 0:T.noChange)||"neutral",onChange:S=>u({colorConfig:{...o.colorConfig,noChange:S}}),label:"Primary = Secondary"})]})]}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Checkbox,{id:"conditional-label",checked:o.conditionalLabel||!1,onCheckedChange:S=>u({conditionalLabel:S})}),e.jsx(t.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),o.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(t.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(t.Input,{id:"label-increase",type:"text",value:((P=o.conditionalLabels)==null?void 0:P.increase)??"Increase",onChange:S=>u({conditionalLabels:{...o.conditionalLabels,increase:S.target.value}}),placeholder:"Increase",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(t.Label,{htmlFor:"label-decrease",className:"text-xs text-muted-foreground",children:["Primary ","<"," Secondary"]}),e.jsx(t.Input,{id:"label-decrease",type:"text",value:((N=o.conditionalLabels)==null?void 0:N.decrease)??"Decrease",onChange:S=>u({conditionalLabels:{...o.conditionalLabels,decrease:S.target.value}}),placeholder:"Decrease",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{htmlFor:"label-no-change",className:"text-xs text-muted-foreground",children:"Primary = Secondary"}),e.jsx(t.Input,{id:"label-no-change",type:"text",value:((A=o.conditionalLabels)==null?void 0:A.noChange)??"No change",onChange:S=>u({conditionalLabels:{...o.conditionalLabels,noChange:S.target.value}}),placeholder:"No change",className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{htmlFor:"label-name",className:"text-xs text-muted-foreground",children:"Previous Label"}),e.jsx(t.Input,{id:"label-name",type:"text",value:o.labelName??"",onChange:S=>u({labelName:S.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function xl(){var i;const s=t.useEditorStore(l=>{var d;return(d=l.card)==null?void 0:d.type}),a=t.useEditorStore(l=>{var d;return(d=l.card)==null?void 0:d.preferences}),{setCardPreferences:n}=t.useEditorActions();if(s!=="treemap")return null;const r=((i=a==null?void 0:a.chartOptions)==null?void 0:i.treemapColorMode)??"branch",c=l=>{const d={...a||{},chartOptions:{...a==null?void 0:a.chartOptions,treemapColorMode:l}};n(d)};return e.jsxs(t.AccordionItem,{value:"treemap-color-mode",className:"border-none",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.TbChartTreemap,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Treemap Colors"})]})}),e.jsx(t.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:e.jsxs(t.RadioGroup,{value:r,onValueChange:l=>c(l??"branch"),className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(t.RadioGroupItem,{id:"treemap-color-branch",value:"branch"}),e.jsxs(t.Label,{htmlFor:"treemap-color-branch",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Shade by value (default)"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Keeps parent hue and adjusts lightness based on the node's share within the branch."})]})]}),e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(t.RadioGroupItem,{id:"treemap-color-category",value:"category"}),e.jsxs(t.Label,{htmlFor:"treemap-color-category",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Single color per category"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Applies the top-level color to all descendants without lightening/darkening."})]})]})]})})]})}const hl=Object.keys(t.HEATMAP_PRESET_PALETTES);function pl(){const s=t.useEditorStore(x=>x.card),a=t.useEditorStore(x=>{var m;return(m=x.card)==null?void 0:m.preferences}),{setCardPreferences:n}=t.useEditorActions(),r=(s==null?void 0:s.type)==="heatmap",c=(a==null?void 0:a.heatmapConfig)||{},i=c.colorPalette??"green",l=c.legendPosition??"bottom",d=y.useMemo(()=>c.colorRange&&c.colorRange[0]&&c.colorRange[1]?[c.colorRange[0],c.colorRange[1]]:[...t.DEFAULT_HEATMAP_CUSTOM_RANGE],[c.colorRange]),o=x=>{const m={...c,...x};m.colorPalette!=="custom"?delete m.colorRange:(!m.colorRange||!m.colorRange[0]||!m.colorRange[1])&&(m.colorRange=[...t.DEFAULT_HEATMAP_CUSTOM_RANGE]),n({...a||{},heatmapConfig:m})},u=x=>{o({colorPalette:x,colorRange:x==="custom"?c.colorRange??[...t.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},p=(x,m)=>{const g=[...d];g[x]=m,o({colorPalette:"custom",colorRange:g})},h=x=>{o({legendPosition:x})};return r?e.jsxs(t.AccordionItem,{value:"heatmap-color-config",className:"border-none",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Grid3x3,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Heatmap Settings"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs(t.RadioGroup,{value:i,onValueChange:x=>u(x??"blue"),className:"space-y-3",children:[hl.map(x=>{const m=t.HEATMAP_PRESET_PALETTES[x];return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(t.RadioGroupItem,{id:`heatmap-${x}`,value:x}),e.jsxs(t.Label,{htmlFor:`heatmap-${x}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:m.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${m.start}, ${m.end})`}})]})]},x)}),e.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.RadioGroupItem,{id:"heatmap-custom",value:"custom"}),e.jsx(t.Label,{htmlFor:"heatmap-custom",className:"text-sm font-medium",children:"Custom colors"})]}),i==="custom"&&e.jsxs("div",{className:"flex flex-col gap-3 pl-6",children:[e.jsx(at,{value:d[0],onChange:x=>p(0,x),label:"Start color"}),e.jsx(at,{value:d[1],onChange:x=>p(1,x),label:"End color"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Color scale position"}),e.jsxs(t.Select,{value:l,onValueChange:x=>h(x??"bottom"),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:["top","bottom","left","right"].map(x=>e.jsx(t.SelectItem,{value:x,className:"text-xs",children:x[0].toUpperCase()+x.slice(1)},x))})]})]})]})]}):null}const Nn=["poor","satisfactory","good"];function Cn(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 fl(){var k,F;const s=t.useEditorStore(f=>f.card.preferences),a=t.useEditorStore(f=>f.card),n=t.useEditorStore(f=>f.isDevMode),{setCardPreferences:r,setChartOrientation:c}=t.useEditorActions(),i=y.useMemo(()=>(s==null?void 0:s.bulletConfig)||{},[s==null?void 0:s.bulletConfig]),d=t.hasValidCardConfig(a==null?void 0:a.config)&&!n,[o,u]=y.useState(i.showRanges??!1),[p,h]=y.useState(i.rangesArePercentages??!1),x=i.disableAutoComparative?!1:i.comparativeMetricKey!==void 0||!d,[m,g]=y.useState(x);y.useEffect(()=>{u(i.showRanges??!1)},[i.showRanges]),y.useEffect(()=>{h(i.rangesArePercentages??!1)},[i.rangesArePercentages]);const b=i.targetValue===void 0?"":String(i.targetValue);y.useEffect(()=>{const f=i.disableAutoComparative?!1:i.comparativeMetricKey!==void 0||!d;g(f)},[i.disableAutoComparative,i.comparativeMetricKey,d]);const j=y.useMemo(()=>{var f,L;return((L=(f=a==null?void 0:a.config)==null?void 0:f.metricColumns)==null?void 0:L.map(E=>{const O=E.label||E.name||E.alias||"";return{value:O,label:O}}))||[]},[(k=a==null?void 0:a.config)==null?void 0:k.metricColumns]);y.useEffect(()=>{var _,U;if(!s||j.length===0)return;const f={};let L=!1;const E=(_=j[1])==null?void 0:_.value;!i.targetMetricKey&&E&&(f.targetMetricKey=E,L=!0);const O=(U=j[2])==null?void 0:U.value;!i.comparativeMetricKey&&!i.disableAutoComparative&&O&&(f.comparativeMetricKey=O,L=!0);const B=j.slice(3),V={...i.rangeKeys||{}};let z=!1;if(Nn.forEach((H,$)=>{!V[H]&&B[$]&&(V[H]=B[$].value,z=!0)}),z&&(f.rangeKeys=V,L=!0,i.showRanges===void 0&&(f.showRanges=!0)),L){const H=Cn({...i,...f});r({...s,bulletConfig:H})}},[j,i,s,r]);const w=f=>{const L=Cn({...i,...f});r({...s,bulletConfig:L})},T=(f,L)=>{const E={...i.rangeKeys||{},[f]:L.trim()};L.trim()||delete E[f],w({rangeKeys:Object.keys(E).length>0?E:void 0})},P=(f,L)=>{const E=L===""?void 0:Number(L),O={...i.ranges||{}};E===void 0||Number.isNaN(E)?delete O[f]:O[f]=E,w({ranges:Object.keys(O).length?O:void 0})},N=f=>{if(f===""){w({targetValue:void 0});return}const L=Number(f);w({targetValue:Number.isNaN(L)?void 0:L})},A=(f,L)=>{const E=L.trim(),O={...i.rangeLabels||{}};E?O[f]=E:delete O[f],w({rangeLabels:Object.keys(O).length>0?O:void 0})},S=f=>{u(f),w({showRanges:f})},I=f=>{h(f),w({rangesArePercentages:f})},D=i.orientation||(((F=s==null?void 0:s.chartOptions)==null?void 0:F.indexAxis)==="y"?"horizontal":"vertical"),M=f=>{w({orientation:f}),c(f==="horizontal"?"y":"x")},v=[{value:"__none",label:"None"},...j.map(f=>({value:f.value,label:f.label}))],R=v,C=f=>{if(g(f),!f){w({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!d){w({disableAutoComparative:!1});return}if(i.comparativeMetricKey)w({disableAutoComparative:!1});else{const L=j.find(E=>E.value!==i.targetMetricKey);w({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-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.BulletChartIcon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bullet Chart"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-6 border-t border-border/50 py-4",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"ORIENTATION"}),e.jsxs(t.Select,{value:D,onValueChange:f=>M(f),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"horizontal",className:"text-xs",children:"Horizontal"}),e.jsx(t.SelectItem,{value:"vertical",className:"text-xs",children:"Vertical"})]})]})]}),d&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"TARGET METRIC"}),e.jsxs(t.Select,{value:i.targetMetricKey||"__none",onValueChange:f=>w({targetMetricKey:f==="__none"?void 0:f}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select metric"})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"__none",className:"text-xs",children:"None"}),j.map(f=>e.jsx(t.SelectItem,{value:f.value,className:"text-xs",children:f.label},f.value))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"COMPARATIVE METRIC"}),d?e.jsxs(t.Select,{value:i.comparativeMetricKey||"__none",onValueChange:f=>w({comparativeMetricKey:f==="__none"?void 0:f,disableAutoComparative:f==="__none"}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select metric"})}),e.jsx(t.SelectContent,{children:v.map(f=>e.jsx(t.SelectItem,{value:f.value,className:"text-xs",children:f.label},f.value))})]}):e.jsxs("div",{className:"space-y-2 rounded-md border border-border/50 p-3 text-xs",children:[e.jsxs("div",{className:"flex items-center justify-between font-medium",children:[e.jsx("span",{children:"Show comparative"}),e.jsx(t.Switch,{size:"sm",checked:m,onCheckedChange:f=>C(f)})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Comparative values are auto-detected from the third metric in your results."})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"TARGET VALUE (FALLBACK)"}),e.jsx(qe,{type:"number",className:"h-8 text-xs",value:b,onCommit:N,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:S})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:p,disabled:!o,onChange:f=>I(f.target.checked),className:"h-3.5 w-3.5 accent-primary disabled:opacity-50"}),e.jsx("span",{children:"Use % of value"})]})]}),o&&e.jsx("div",{className:"space-y-3",children:Nn.map(f=>{var L,E,O,B,V;return e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-muted/40 p-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[f," LABEL"]}),e.jsx(qe,{placeholder:`Display label (${f})`,value:((L=i.rangeLabels)==null?void 0:L[f])||"",onCommit:z=>A(f,z),className:"h-8 text-xs"})]}),d?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[f," COLUMN"]}),e.jsxs(t.Select,{value:((E=i.rangeKeys)==null?void 0:E[f])||"__none",onValueChange:z=>{z==="__none"?T(f,""):T(f,z)},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(z=>e.jsx(t.SelectItem,{value:z.value,className:"text-xs",children:z.label},z.value))})]})]}):e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[f," COLUMN KEY"]}),e.jsx(qe,{placeholder:"Column key",value:((O=i.rangeKeys)==null?void 0:O[f])||"",onCommit:z=>T(f,z),className:"h-8 text-xs"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[f," VALUE"]}),e.jsx(qe,{type:"number",placeholder:p?"0.80":"Static value",value:((B=i.ranges)==null?void 0:B[f])===void 0?"":String((V=i.ranges)==null?void 0:V[f]),onCommit:z=>P(f,z),className:"h-8 text-xs"})]})]},f)})})]})]})]})}function Sn(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 gl(){var A,S,I,D,M,v,R,C,k,F,f,L;const s=t.useEditorStore(E=>E.card.preferences),a=t.useEditorStore(E=>E.card),n=ke.useEffectiveEditorCardType(),r=t.useEditorStore(E=>E.isDevMode),{setCardPreferences:c,updateCardInFrame:i}=t.useEditorActions(),l=n==="bubble",d=n==="scatter",o=y.useMemo(()=>(s==null?void 0:s.bubbleScatterConfig)||{},[s==null?void 0:s.bubbleScatterConfig]),p=t.hasValidCardConfig(a==null?void 0:a.config)&&!r,h=y.useMemo(()=>{var E,O;return((O=(E=a==null?void 0:a.config)==null?void 0:E.metricColumns)==null?void 0:O.map(B=>{const V=B.label||B.name||B.alias||"";return{value:V,label:V}}))||[]},[(A=a==null?void 0:a.config)==null?void 0:A.metricColumns]),x=y.useMemo(()=>{var E,O;return((O=(E=a==null?void 0:a.config)==null?void 0:E.groupByColumns)==null?void 0:O.map(B=>{const V=B.label||B.name||B.alias||"";return{value:V,label:V}}))||[]},[(S=a==null?void 0:a.config)==null?void 0:S.groupByColumns]),m=y.useMemo(()=>o.enableGrouping!==void 0?o.enableGrouping:!r&&x.length>=2,[o.enableGrouping,r,x.length]),[g,b]=y.useState(m);y.useEffect(()=>{b(m)},[m]);const j=E=>{const O={...s||{},bubbleScatterConfig:E};c(O),a&&i({...a,preferences:O})},w=E=>{c(E),a&&i({...a,preferences:E})};y.useEffect(()=>{if(!s||h.length===0)return;const E={};let O=!1;if(!o.xMetricKey&&h[0]&&(E.xMetricKey=h[0].value,O=!0),!o.yMetricKey&&h[1]&&(E.yMetricKey=h[1].value,O=!0),l&&!o.radiusMetricKey&&h[2]&&(E.radiusMetricKey=h[2].value,O=!0),!o.labelKey&&x[0]&&(E.labelKey=x[0].value,O=!0),m&&!o.groupKey&&x[1]&&(E.groupKey=x[1].value,E.enableGrouping=!0,O=!0),O){const B=Sn({...o,...E});j(B)}},[h,x,o,s,c,l,m]);const T=E=>{const O=Sn({...o,...E});j(O)},P=E=>{b(E),T({enableGrouping:E,groupKey:E?o.groupKey:void 0})};if(!l&&!d)return null;const N=l?t.Circle:t.ChartScatter;return e.jsxs(t.AccordionItem,{value:"bubble-scatter-config",children:[e.jsx(t.AccordionTrigger,{className:"py-2 text-sm",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(N,{className:"h-4 w-4"}),e.jsxs("span",{children:[l?"Bubble":"Scatter"," Configuration"]})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-1 pb-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-1 text-xs font-medium text-muted-foreground",children:["Dimensions",e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{children:e.jsx(t.Info,{className:"h-3 w-3"})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{children:"Label identifies each point. Group creates separate series in the legend."})})]})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Label Column"}),p?e.jsxs(t.Select,{value:o.labelKey||"",onValueChange:E=>T({labelKey:E}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select label column"})}),e.jsx(t.SelectContent,{children:x.map(E=>e.jsx(t.SelectItem,{value:E.value,children:E.label},E.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for labels",value:o.labelKey||"",onCommit:E=>T({labelKey:E})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Group points into series"}),e.jsx(t.Switch,{size:"sm",checked:g,onCheckedChange:P})]}),g&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Group By"}),p?e.jsxs(t.Select,{value:o.groupKey||"",onValueChange:E=>T({groupKey:E}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select group column"})}),e.jsx(t.SelectContent,{children:x.map(E=>e.jsx(t.SelectItem,{value:E.value,children:E.label},E.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:o.groupKey||"",onCommit:E=>T({groupKey:E})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Metrics"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"X Axis"}),p?e.jsxs(t.Select,{value:o.xMetricKey||"",onValueChange:E=>T({xMetricKey:E}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select X metric"})}),e.jsx(t.SelectContent,{children:h.map(E=>e.jsx(t.SelectItem,{value:E.value,children:E.label},E.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:o.xMetricKey||"",onCommit:E=>T({xMetricKey:E})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Axis"}),p?e.jsxs(t.Select,{value:o.yMetricKey||"",onValueChange:E=>T({yMetricKey:E}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select Y metric"})}),e.jsx(t.SelectContent,{children:h.map(E=>e.jsx(t.SelectItem,{value:E.value,children:E.label},E.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:o.yMetricKey||"",onCommit:E=>T({yMetricKey:E})})]}),l&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Radius"}),p?e.jsxs(t.Select,{value:o.radiusMetricKey||"",onValueChange:E=>T({radiusMetricKey:E}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select radius metric"})}),e.jsx(t.SelectContent,{children:h.map(E=>e.jsx(t.SelectItem,{value:E.value,children:E.label},E.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for radius",value:o.radiusMetricKey||"",onCommit:E=>T({radiusMetricKey:E})})]})]}),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:E=>T({radiusScale:E}),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:((I=o.minRadius)==null?void 0:I.toString())||"",onCommit:E=>T({minRadius:E?Number(E):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:((D=o.maxRadius)==null?void 0:D.toString())||"",onCommit:E=>T({maxRadius:E?Number(E):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:([E])=>T({fixedRadius:E}),min:3,max:30,step:1,className:"py-2"})]})]}),d&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Point Settings"}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(t.Label,{className:"text-xs",children:["Point Size: ",o.fixedRadius||5]}),e.jsx(t.Slider,{value:[o.fixedRadius||5],onValueChange:([E])=>T({fixedRadius:E}),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:((v=(M=s==null?void 0:s.xAxisConfig)==null?void 0:M.name)==null?void 0:v.enabled)??!1,onCheckedChange:E=>{var V,z,_,U;const O=o.xMetricKey||"X Axis",B=o.yMetricKey||"Y Axis";w({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{enabled:E,text:((z=(V=s==null?void 0:s.xAxisConfig)==null?void 0:V.name)==null?void 0:z.text)||O}},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{enabled:E,text:((U=(_=s==null?void 0:s.yAxisConfig)==null?void 0:_.name)==null?void 0:U.text)||B}}})}})]}),((C=(R=s==null?void 0:s.xAxisConfig)==null?void 0:R.name)==null?void 0:C.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=(k=s==null?void 0:s.xAxisConfig)==null?void 0:k.name)==null?void 0:F.text)||"",onCommit:E=>{var O;w({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{...(O=s==null?void 0:s.xAxisConfig)==null?void 0:O.name,enabled:!0,text:E||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=(f=s==null?void 0:s.yAxisConfig)==null?void 0:f.name)==null?void 0:L.text)||"",onCommit:E=>{var O;w({...s??{},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{...(O=s==null?void 0:s.yAxisConfig)==null?void 0:O.name,enabled:!0,text:E||o.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const jl=[{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 bl(){const s=t.useEditorStore(x=>x.card),a=t.useEditorStore(x=>{var m;return(m=x.card)==null?void 0:m.preferences}),{setCardPreferences:n}=t.useEditorActions(),r=(s==null?void 0:s.type)==="funnel",c=(a==null?void 0:a.funnelConfig)||{},i=c.percentMode??"percentOfTotal",l=c.shrinkFraction??1,d=c.labelThreshold??0,o=x=>{const m={...c,...x};n({...a||{},funnelConfig:m})},u=x=>{o({percentMode:x})},p=x=>{o({shrinkFraction:x[0]})},h=x=>{o({labelThreshold:x[0]})};return r?e.jsxs(t.AccordionItem,{value:"funnel-config",className:"border-none",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Filter,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Funnel Settings"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"PERCENTAGE MODE"}),e.jsx(t.RadioGroup,{value:i,onValueChange:x=>u(x),className:"space-y-2",children:jl.map(x=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(t.RadioGroupItem,{id:`funnel-${x.value}`,value:x.value,className:"mt-0.5"}),e.jsxs(t.Label,{htmlFor:`funnel-${x.value}`,className:"flex flex-col gap-0.5 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:x.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:x.description})]})]},x.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"SEGMENT SHRINK"}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Same Width"}),e.jsx(t.Slider,{value:[l],onValueChange:p,min:0,max:1,step:.1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Full Shrink"})]}),e.jsxs("p",{className:"text-center text-xs text-muted-foreground",children:["Current: ",Math.round(l*100),"%"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"LABEL VISIBILITY THRESHOLD"}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Show All"}),e.jsx(t.Slider,{value:[d],onValueChange:h,min:0,max:25,step:1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Hide Small"})]}),e.jsx("p",{className:"text-center text-xs text-muted-foreground",children:d===0?"Showing all labels":`Hide labels below ${d}%`})]})]})]}):null}function qt(){const s=t.useEditorStore(i=>i.card),{data:a}=t.useEditorCardQuery(s),{keys:n}=t.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(i=>!t.METADATA_KEYS.includes(i));let c=r;if(["stackedBar","stackedLine"].includes(s.type)){const i=t.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:l}=t.getKeys(i);c=l.slice(1)}return{transformedMetricKeys:c,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}const vl=[{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"}],yl=[{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)"}],Nl=["center","start","end"],Cl=["center","start","end","top","bottom"];function $t({config:s,onChange:a,isHorizontal:n=!1,showAutoFormat:r=!0,positionOptions:c,showAppearance:i=!0}){var g,b,j,w,T,P;const l=c??(n?["auto","center","left","right","custom"]:["auto","center","top","bottom","custom"]),d=r?["auto","number","currency","percent","none"]:["number","currency","percent","none"],o=(N,A)=>{const S={...s,[N]:A};a(S)},u=(N,A)=>{const S={...s,font:{...(s==null?void 0:s.font)||{},[N]:A}};a(S)},p=(N,A)=>{const S={...s,formatOptions:{...(s==null?void 0:s.formatOptions)||{},[N]:A}};a(S)},h=()=>n?"Right":"Top",x=s||{},m=x.format||(r?"auto":"number");return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(t.Select,{value:x.position||"auto",onValueChange:N=>o("position",N),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:l.map(N=>e.jsx(t.SelectItem,{value:N,className:"text-xs",children:N==="auto"?h():N==="custom"?"Custom (Advanced)":t.titleCase(N)},N))})]})]}),x.position==="custom"&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Anchor"}),e.jsxs(t.Select,{value:x.anchor||"center",onValueChange:N=>o("anchor",N),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Nl.map(N=>e.jsx(t.SelectItem,{value:N,className:"text-xs",children:t.titleCase(N)},N))})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Align"}),e.jsxs(t.Select,{value:String(x.align||"center"),onValueChange:N=>o("align",N),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Cl.map(N=>e.jsx(t.SelectItem,{value:N,className:"text-xs",children:t.titleCase(N)},N))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Format"}),e.jsxs(t.Select,{value:m,onValueChange:N=>o("format",N),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:d.map(N=>e.jsx(t.SelectItem,{value:N,className:"text-xs",children:N==="auto"&&r?"Auto (Use Axis)":N==="none"?"None (Raw Value)":t.titleCase(N)},N))})]})]}),!["auto","none"].includes(m)&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[["number","currency","percent"].includes(m)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Decimals"}),e.jsx("div",{className:"w-16",children:e.jsx(He,{type:"number",placeholder:"0",value:String(((g=x.formatOptions)==null?void 0:g.decimalPlaces)??(m==="currency"?2:m==="percent"?1:0)),onSave:N=>p("decimalPlaces",Number(N)),className:""})})]}),m==="currency"&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Currency"}),e.jsxs(t.Select,{value:((b=x.formatOptions)==null?void 0:b.currency)||"USD",onValueChange:N=>p("currency",N),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:vl.map(N=>e.jsx(t.SelectItem,{value:N.value,className:"text-xs",children:N.label},N.value))})]})]}),["number","currency"].includes(m)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Abbreviate (K, M, B)"}),e.jsx(t.Switch,{size:"sm",checked:((j=x.formatOptions)==null?void 0:j.useSuffix)??!1,onCheckedChange:N=>p("useSuffix",N)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Locale"}),e.jsxs(t.Select,{value:((w=x.formatOptions)==null?void 0:w.locale)||"en-US",onValueChange:N=>p("locale",N),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:yl.map(N=>e.jsx(t.SelectItem,{value:N.value,className:"text-xs",children:N.label},N.value))})]})]})]}),i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Appearance"}),e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Size"}),e.jsx("div",{className:"w-16",children:e.jsx(He,{type:"number",placeholder:"12",value:String(((T=x.font)==null?void 0:T.size)||12),onSave:N=>u("size",Number(N)),className:""})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Weight"}),e.jsxs(t.Select,{value:((P=x.font)==null?void 0:P.weight)||"normal",onValueChange:N=>u("weight",N),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(t.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Color"}),e.jsxs(t.Select,{value:x.color==="auto"||!x.color?"auto":"custom",onValueChange:N=>{N==="auto"&&o("color","auto")},children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Contrast)"}),e.jsx(t.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Rotation"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-12",children:e.jsx(He,{type:"number",placeholder:"0",value:String(x.rotation||0),onSave:N=>o("rotation",Number(N)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"°"})]})]})]})]})]})}const Sl=[{type:"bar",icon:t.ChartColumnIncreasing,label:"Bar"},{type:"line",icon:t.ChartLine,label:"Line"}],wl=[0,1,2,3,4,5,6,8,10],Tl=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],El=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Il(){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-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsx(Dl,{})})]})}function Dl(){const{transformedMetricKeys:s}=qt();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((a,n)=>e.jsx(kl,{metricKey:a,idx:n},a))})}function kl({metricKey:s,idx:a}){var w;const[n,r]=y.useState(!1),c=t.useEditorStore(T=>{var P;return(P=T.card)==null?void 0:P.preferences}),i=t.useEditorStore(T=>{var P,N;return(N=(P=T.card)==null?void 0:P.preferences)==null?void 0:N.datasetOptions}),l=i==null?void 0:i.find(T=>T.idx===a),{setCardPreferences:d}=t.useEditorStore(T=>T.actions),o=(l==null?void 0:l.type)||"bar",u=(l==null?void 0:l.yAxisId)||"y",p=((w=l==null?void 0:l.dataLabels)==null?void 0:w.enabled)??!1,h=o==="line"?t.ChartLine:t.ChartColumnIncreasing;function x(T){const P={idx:a,type:o,yAxisId:u,dataLabels:l==null?void 0:l.dataLabels,...T};if(!l)d({...c||{},datasetOptions:[...i||[],P]});else{const N=i==null?void 0:i.map(A=>A.idx===a?{...A,...P}:A);d({...c||{},datasetOptions:N})}}function m(T){x({type:T})}function g(T){x({yAxisId:T})}function b(T){x({dataLabels:{...l==null?void 0:l.dataLabels,enabled:T}})}function j(T){x({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.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(h,{className:"h-3 w-3"}),o==="line"?"Line":"Bar"]}),e.jsx("span",{className:t.cn("rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:u==="y2"?"Y2":"Y1"})]})]})}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"flex items-end gap-4",children:[e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Chart Type"}),e.jsx("div",{className:"flex gap-2",children:Sl.map(({type:T,icon:P,label:N})=>{const A=o===T;return e.jsxs("button",{onClick:()=>m(T),className:t.cn("flex items-center gap-2 rounded-md border px-3 py-1.5 text-xs transition-colors",A?"border-primary bg-primary/10 text-primary":"border-border bg-background text-muted-foreground hover:bg-muted"),children:[e.jsx(P,{className:"h-4 w-4"}),e.jsx("span",{children:N})]},T)})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Axis"}),e.jsxs(t.Select,{value:u,onValueChange:T=>g(T),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:T=>x({lineStyle:T}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:El.map(({value:T,label:P})=>e.jsx(t.SelectItem,{value:T,className:"text-xs",children:P},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((l==null?void 0:l.pointRadius)??3),onValueChange:T=>x({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:(l==null?void 0:l.pointStyle)||"circle",onValueChange:T=>x({pointStyle:T}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Tl.map(({value:T,label:P})=>e.jsx(t.SelectItem,{value:T,className:"text-xs",children:P},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:p,onCheckedChange:b})]}),p&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx($t,{config:l==null?void 0:l.dataLabels,onChange:j,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const as=[{value:"origin",label:"Origin (X-axis)",description:"Fill to the X-axis (y=0)"},{value:"start",label:"Start (Top)",description:"Fill to the top of chart area"},{value:"end",label:"End (Bottom)",description:"Fill to the bottom of chart area"},{value:"-1",label:"Previous Series",description:"Fill to the series below"},{value:"+1",label:"Next Series",description:"Fill to the series above"},{value:"false",label:"No Fill (Line)",description:"Show as line without fill"}],Al=[0,1,2,3,4,5,6,8,10],Ml=[{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 │"}],Ll=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Fl(s){return s==null?"origin":s===!1?"false":s}function Rl(){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-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsx(Ol,{})})]})}function Ol(){const{transformedMetricKeys:s}=qt();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((a,n)=>e.jsx(Pl,{metricKey:a,idx:n},a))})}function Pl({metricKey:s,idx:a}){var b;const[n,r]=y.useState(!1),c=t.useEditorStore(j=>{var w;return(w=j.card)==null?void 0:w.preferences}),i=t.useEditorStore(j=>{var w,T;return(T=(w=j.card)==null?void 0:w.preferences)==null?void 0:T.datasetOptions}),l=i==null?void 0:i.find(j=>j.idx===a),{setCardPreferences:d}=t.useEditorStore(j=>j.actions),o=Fl(l==null?void 0:l.fill),u=((b=l==null?void 0:l.dataLabels)==null?void 0:b.enabled)??!1,p=as.find(j=>j.value===o)||as[0];function h(j){const w={idx:a,fill:o,dataLabels:l==null?void 0:l.dataLabels,...j};if(!l)d({...c||{},datasetOptions:[...i||[],w]});else{const T=i==null?void 0:i.map(P=>P.idx===a?{...P,...w}:P);d({...c||{},datasetOptions:T})}}function x(j){h({fill:j==="false"?!1:j})}function m(j){h({dataLabels:{...l==null?void 0:l.dataLabels,enabled:j}})}function g(j){h({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:e.jsxs("span",{className:t.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(t.ChartArea,{className:"h-3 w-3"}),p.label.split(" ")[0]]})})]})}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Fill Target"}),e.jsxs(t.Select,{value:o,onValueChange:j=>x(j),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:as.map(j=>e.jsx(t.SelectItem,{value:j.value,className:"text-xs",children:e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{children:j.label})})},j.value))})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(t.Select,{value:(l==null?void 0:l.lineStyle)||"solid",onValueChange:j=>h({lineStyle:j}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ll.map(({value:j,label:w})=>e.jsx(t.SelectItem,{value:j,className:"text-xs",children:w},j))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(t.Select,{value:String((l==null?void 0:l.pointRadius)??3),onValueChange:j=>h({pointRadius:Number(j)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Al.map(j=>e.jsx(t.SelectItem,{value:String(j),className:"text-xs",children:j===0?"None":j},j))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(t.Select,{value:(l==null?void 0:l.pointStyle)||"circle",onValueChange:j=>h({pointStyle:j}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ml.map(({value:j,label:w})=>e.jsx(t.SelectItem,{value:j,className:"text-xs",children:w},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:u,onCheckedChange:m})]}),u&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx($t,{config:l==null?void 0:l.dataLabels,onChange:g,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Bl=[0,1,2,3,4,5,6,8,10],Vl=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],rs=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function zl(){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-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsx(_l,{})})]})}function _l(){const{transformedMetricKeys:s}=qt();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((a,n)=>e.jsx(ql,{metricKey:a,idx:n},a))})}function ql({metricKey:s,idx:a}){var j;const[n,r]=y.useState(!1),c=t.useEditorStore(w=>{var T;return(T=w.card)==null?void 0:T.preferences}),i=t.useEditorStore(w=>{var T,P;return(P=(T=w.card)==null?void 0:T.preferences)==null?void 0:P.datasetOptions}),l=i==null?void 0:i.find(w=>w.idx===a),{setCardPreferences:d}=t.useEditorStore(w=>w.actions),o=(l==null?void 0:l.lineStyle)||"solid",u=(l==null?void 0:l.pointRadius)??3,p=(l==null?void 0:l.pointStyle)||"circle",h=((j=l==null?void 0:l.dataLabels)==null?void 0:j.enabled)??!1,x=rs.find(w=>w.value===o)||rs[0];function m(w){const T={idx:a,lineStyle:o,pointRadius:u,pointStyle:p,dataLabels:l==null?void 0:l.dataLabels,...w};if(!l)d({...c||{},datasetOptions:[...i||[],T]});else{const P=i==null?void 0:i.map(N=>N.idx===a?{...N,...T}:N);d({...c||{},datasetOptions:P})}}function g(w){m({dataLabels:{...l==null?void 0:l.dataLabels,enabled:w}})}function b(w){m({dataLabels:w})}return e.jsx(t.Collapsible,{open:n,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(t.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(t.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",n&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:s,children:s})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:e.jsxs("span",{className:t.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(t.TrendingUp,{className:"h-3 w-3"}),x.label.split(" ")[0]]})})]})}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(t.Select,{value:o,onValueChange:w=>m({lineStyle:w}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:rs.map(({value:w,label:T})=>e.jsx(t.SelectItem,{value:w,className:"text-xs",children:T},w))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(t.Select,{value:String(u),onValueChange:w=>m({pointRadius:Number(w)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Bl.map(w=>e.jsx(t.SelectItem,{value:String(w),className:"text-xs",children:w===0?"None":w},w))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(t.Select,{value:p,onValueChange:w=>m({pointStyle:w}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Vl.map(({value:w,label:T})=>e.jsx(t.SelectItem,{value:w,className:"text-xs",children:T},w))})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(t.Switch,{size:"sm",checked:h,onCheckedChange:g})]}),h&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx($t,{config:l==null?void 0:l.dataLabels,onChange:b,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const $l=[0,2,4,6,8,10,12,16,20];function Kl(){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-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsx(Gl,{})})]})}function Gl(){const{transformedMetricKeys:s}=qt();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((a,n)=>e.jsx(Ul,{metricKey:a,idx:n},a))})}function Ul({metricKey:s,idx:a}){var g;const[n,r]=y.useState(!1),c=t.useEditorStore(b=>{var j;return(j=b.card)==null?void 0:j.type}),i=t.useEditorStore(b=>{var j;return(j=b.card)==null?void 0:j.preferences}),l=t.useEditorStore(b=>{var j,w;return(w=(j=b.card)==null?void 0:j.preferences)==null?void 0:w.datasetOptions}),d=l==null?void 0:l.find(b=>b.idx===a),{setCardPreferences:o}=t.useEditorStore(b=>b.actions),u=(d==null?void 0:d.borderRadius)??0,p=((g=d==null?void 0:d.dataLabels)==null?void 0:g.enabled)??!1;function h(b){const j={idx:a,borderRadius:u,dataLabels:d==null?void 0:d.dataLabels,...b};if(!d)o({...i||{},datasetOptions:[...l||[],j]});else{const w=l==null?void 0:l.map(T=>T.idx===a?{...T,...j}:T);o({...i||{},datasetOptions:w})}}function x(b){h({dataLabels:{...d==null?void 0:d.dataLabels,enabled:b}})}function m(b){h({dataLabels:b})}return e.jsx(t.Collapsible,{open:n,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(t.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(t.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",n&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:s,children:s})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:u>0&&e.jsxs("span",{className:t.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(t.ChartColumn,{className:"h-3 w-3"}),"r:",u]})})]})}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Bar Style"}),e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Corner Radius"}),e.jsxs(t.Select,{value:String(u),onValueChange:b=>h({borderRadius:Number(b)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:$l.map(b=>e.jsx(t.SelectItem,{value:String(b),className:"text-xs",children:b===0?"None":`${b}px`},b))})]})]})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(t.Switch,{size:"sm",checked:p,onCheckedChange:x})]}),p&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx($t,{config:d==null?void 0:d.dataLabels,onChange:m,isHorizontal:c==="horizontalBar",showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Hl=[0,1,2,3,4,5,6,8,10],Ql=[{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 │"}],Jl=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Yl(){const s=t.useEditorStore(d=>d.card),a=t.useEditorStore(d=>{var o;return(o=d.card)==null?void 0:o.preferences}),n=ke.useEffectiveEditorCardType(),r=a==null?void 0:a.lineStyleConfig,{setCardPreferences:c,updateCardInFrame:i}=t.useEditorActions();if(!s||!["line","area","stackedArea"].includes(n))return null;const l=(d,o)=>{const u={...a||{},lineStyleConfig:{...r,[d]:o}};c(u),i({...s,preferences:u})};return e.jsxs(t.AccordionItem,{value:"line-style",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ka,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Line Style"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Default styles for all series. Override per-series in the Series section."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Line Pattern"}),e.jsxs(t.Select,{value:(r==null?void 0:r.lineStyle)||"solid",onValueChange:d=>l("lineStyle",d),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Jl.map(({value:d,label:o})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:o},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Point Size"}),e.jsxs(t.Select,{value:String((r==null?void 0:r.pointRadius)??3),onValueChange:d=>l("pointRadius",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Hl.map(d=>e.jsx(t.SelectItem,{value:String(d),className:"text-xs",children:d===0?"None":d},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Point Shape"}),e.jsxs(t.Select,{value:(r==null?void 0:r.pointStyle)||"circle",onValueChange:d=>l("pointStyle",d),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ql.map(({value:d,label:o})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:o},d))})]})]})]})})]})}const Wl=[0,2,4,6,8,10,12,16,20],Xl=[{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%"}],Zl=[{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 eo(){const s=t.useEditorStore(d=>d.card),a=t.useEditorStore(d=>{var o;return(o=d.card)==null?void 0:o.preferences}),n=ke.useEffectiveEditorCardType(),r=a==null?void 0:a.barStyleConfig,{setCardPreferences:c,updateCardInFrame:i}=t.useEditorActions();if(!s||!["bar","horizontalBar","stackedBar"].includes(n))return null;const l=(d,o)=>{const u={...a||{},barStyleConfig:{...r,[d]:o}};c(u),i({...s,preferences:u})};return e.jsxs(t.AccordionItem,{value:"bar-style",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.ChartColumn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bar Style"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Default styles for all bars. Override per-series in the Series section."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Corner Radius"}),e.jsxs(t.Select,{value:String((r==null?void 0:r.borderRadius)??0),onValueChange:d=>l("borderRadius",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Wl.map(d=>e.jsx(t.SelectItem,{value:String(d),className:"text-xs",children:d===0?"None":`${d}px`},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Bar Width"}),e.jsxs(t.Select,{value:String((r==null?void 0:r.barPercentage)??.9),onValueChange:d=>l("barPercentage",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Xl.map(({value:d,label:o})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:o},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Category Width"}),e.jsxs(t.Select,{value:String((r==null?void 0:r.categoryPercentage)??.8),onValueChange:d=>l("categoryPercentage",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Zl.map(({value:d,label:o})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:o},d))})]})]})]})})]})}function to(){const s=t.useEditorStore(n=>{var r,c;return(c=(r=n==null?void 0:n.card)==null?void 0:r.preferences)==null?void 0:c.sortChart}),{setSortChart:a}=t.useEditorActions();return e.jsxs(t.AccordionItem,{value:"stacked-sort",children:[e.jsx(t.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.ArrowUpDown,{className:"h-4 w-4"}),"Sort"]})}),e.jsx(t.AccordionContent,{className:"space-y-4 px-1",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Sort Order"}),e.jsx(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 so=["kpi"],wn={none:"None",previous_period:"Previous Period",same_period_last_year:"Same Period Last Year",start_vs_end:"Start vs End",target:"Target"},ls=2;function lt(s){return typeof s=="string"?s.trim().toLowerCase():((s==null?void 0:s.id)||(s==null?void 0:s.qualifiedFieldName)||(s==null?void 0:s.name)||(s==null?void 0:s.label)||"").trim().toLowerCase()}function no(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 ao(s){return{...s,role:"groupby"}}function ro(){var T,P;const s=t.useEditorStore(N=>N.card),a=t.useEditorStore(N=>N.actions.updateCardConfig),n=ke.useEffectiveEditorCardType(),{scopedFields:r}=t.useScopedFields(),c=((T=s.config)==null?void 0:T.metricColumns)||[],i=((P=s.config)==null?void 0:P.summary)||{},l=i.breakdownDimensions||[],d=so.includes(n),o=c.length>0,u=i.enabled===!0,p=d&&o,{comparisonType:h}=t.getEffectiveComparisonSettings(s.config,n),x=wn[h]||wn.none,m=Array.from(new Map(r.filter(no).map(N=>[lt(N),ao(N)])).values()),g=new Set(m.map(N=>lt(N))),b=new Set(l.map(N=>lt(N)).filter(N=>N&&g.has(N)));if(!d)return null;const j=N=>{a(s.id,{summary:{...i,...N}})},w=(N,A)=>{const S=lt(N),I=m.filter(M=>b.has(lt(M))),D=A?b.has(S)?I:[...I,N].slice(0,ls):I.filter(M=>lt(M)!==S);j({breakdownDimensions:D})};return e.jsxs(t.AccordionItem,{value:"summary",className:"border-none",children:[e.jsx(t.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.FileText,{className:"h-4 w-4"}),e.jsx("span",{children:"Summary"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{htmlFor:"summary-enabled",className:"text-xs",children:"Enable Summary"}),!o&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Add at least one metric to enable summary."})]}),e.jsx(t.Switch,{size:"sm",id:"summary-enabled",checked:u,disabled:!p,onCheckedChange:N=>{if(!N){j({enabled:!1,showOnCard:!1,includeInDashboardSummary:!1});return}j({enabled:!0,showOnCard:i.showOnCard??!0,includeInDashboardSummary:i.includeInDashboardSummary??!0,anomalyEnabled:i.anomalyEnabled??!0})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Comparison"}),e.jsxs("p",{className:"rounded-md border border-border bg-muted/40 px-2 py-1.5 text-xs",children:["Using: ",x]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Comparison is configured from card/metric comparison settings."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"summary-show-on-card",className:"text-xs",children:"Show summary on card"}),e.jsx(t.Switch,{size:"sm",id:"summary-show-on-card",checked:i.showOnCard===!0,disabled:!u,onCheckedChange:N=>j({showOnCard:N})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"summary-include-rollup",className:"text-xs",children:"Include in dashboard summary"}),e.jsx(t.Switch,{size:"sm",id:"summary-include-rollup",checked:i.includeInDashboardSummary===!0,disabled:!u,onCheckedChange:N=>j({includeInDashboardSummary:N})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Breakdown Dimensions"}),e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[l.length,"/",ls]})]}),m.length===0?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"No dimension fields available for breakdown."}):e.jsx("div",{className:"max-h-40 space-y-2 overflow-y-auto rounded-md border border-border p-2",children:m.map(N=>{const A=lt(N),S=b.has(A),I=b.size>=ls,D=!u||!S&&I;return e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx(t.Checkbox,{id:`summary-breakdown-${A}`,checked:S,disabled:D,onCheckedChange:M=>w(N,M===!0)}),e.jsx(t.Label,{htmlFor:`summary-breakdown-${A}`,className:"cursor-pointer text-xs",children:N.label||N.name})]},A)})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"summary-anomaly",className:"text-xs",children:"Detect anomalies"}),e.jsx(t.Switch,{size:"sm",id:"summary-anomaly",checked:i.anomalyEnabled!==!1,disabled:!u,onCheckedChange:N=>j({anomalyEnabled:N})})]})]})]})}const lo=[];function oo(){var c;const s=t.useEditorStore(i=>i.card),a=((c=s==null?void 0:s.config)==null?void 0:c.metricColumns)??lo,{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-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ma.Braces,{className:"h-4 w-4"}),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(hs,{value:i.format,onChange:l=>{var d;n(s.id,i.id,{format:l}),r({...s,config:{...s.config,metricColumns:(((d=s.config)==null?void 0:d.metricColumns)||[]).map(o=>o.id===i.id?{...o,format:l}:o)}})}})]},i.id))})]})}const io=new Set(["area","bar","bubble","bullet","combo","doughnut","funnel","horizontalBar","line","pie","polarArea","radar","scatter","stackedArea","stackedBar","stackedLine","tornado"]);function co(){const s=t.useEditorStore(o=>o.card),a=t.useEditorStore(o=>{var u;return(u=o.card)==null?void 0:u.preferences}),n=ke.useEffectiveEditorCardType(),{setCardPreferences:r,updateCardInFrame:c}=t.useEditorActions();if(!s||!io.has(n||""))return null;const i=a==null?void 0:a.tooltipConfig,l=(i==null?void 0:i.formatMode)||(i==null?void 0:i.mode)||"inherit",d=o=>{const u={...a||{},tooltipConfig:{...i||{},...o}};r(u),c({...s,preferences:u})};return e.jsxs(t.AccordionItem,{value:"tooltip-format",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Info,{className:"h-4 w-4"}),e.jsx("span",{children:"Tooltip Format"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Override metric format"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Keep this off to inherit from each metric."})]}),e.jsx(t.Switch,{size:"sm",checked:l==="override",onCheckedChange:o=>d({formatMode:o?"override":"inherit",mode:o?"override":"inherit"})})]}),l==="override"&&e.jsx(jt,{formatOptions:(i==null?void 0:i.formatOptions)||{},onFormatOptionsChange:o=>d({formatMode:"override",mode:"override",formatOptions:o}),showTitle:!1})]})]})}function Un({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(Il,{}),(a==="area"||a==="stackedArea")&&e.jsx(Rl,{}),a==="line"&&e.jsx(zl,{}),(a==="bar"||a==="horizontalBar"||a==="stackedBar")&&e.jsx(Kl,{}),e.jsx(Yl,{}),e.jsx(eo,{}),e.jsx(xl,{}),s==="config"&&e.jsx(ml,{}),s==="config"&&e.jsx(ro,{}),e.jsx(pl,{}),a==="bullet"&&e.jsx(fl,{}),a==="funnel"&&e.jsx(bl,{}),(a==="bubble"||a==="scatter")&&e.jsx(gl,{}),(a==="stackedBar"||a==="stackedLine")&&e.jsx(to,{}),e.jsx(oo,{}),e.jsx(il,{}),e.jsx(cl,{}),e.jsx(dl,{}),e.jsx(ul,{}),e.jsx(co,{})]})}function uo(){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(Un,{mode:"dev"})})]}):null}function mo(){const s=t.useEditorStore(c=>c.card),a=s.type;if(t.getVisualizationMode(s)==="dynamic")return e.jsx("div",{className:"p-6",children:e.jsxs(t.Alert,{children:[e.jsx(t.Info,{className:"h-4 w-4"}),e.jsx(t.AlertTitle,{children:"Dynamic mode manages presentation"}),e.jsx(t.AlertDescription,{children:"Built-in chart settings are hidden while this card is in dynamic mode. Query and data edits still apply, and the dynamic visual editor in the main panel controls the rendered output."})]})});function r(){switch(a){case"kpi":return e.jsx(qr,{});case"table":return e.jsx(al,{});case"map":return e.jsx(Ur,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(qn,{})});case"text":return e.jsx(ll,{});default:return e.jsx(uo,{})}}return e.jsxs(t.ScrollArea,{className:"h-full w-full text-sm",children:[r(),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}function xo(){const s=y.useRef(null),a=y.useRef(null),n=t.useEditorStore(h=>h.isShowingVisual),r=t.useEditorStore(h=>h.isDevMode),c=t.useEditorStore(h=>h.showAIDialog),[i,l]=y.useState(!1),d=n&&!c,o=d&&(!r||i),u=r&&d,p=()=>l(h=>!h);return y.useEffect(()=>{var h,x,m,g;c?((h=s.current)==null||h.resize(0),(x=a.current)==null||x.resize(0)):((m=s.current)==null||m.resize(25),(g=a.current)==null||g.resize(25))},[c]),e.jsxs(t.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:[e.jsx(t.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(rr,{})}),e.jsx(t.ResizableHandle,{withHandle:!0,className:"data-[panel-group-direction=vertical]:ml-2 data-[panel-group-direction=vertical]:mr-6 data-[panel-group-direction=vertical]:w-auto"}),e.jsx(t.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:o?e.jsxs(t.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(t.ResizablePanel,{ref:s,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(mo,{})})}),!c&&e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(pn,{visualAsideControl:u?{show:!0,isOpen:i,onToggle:p}:void 0})})]}):e.jsx(pn,{visualAsideControl:u?{show:!0,isOpen:i,onToggle:p}:void 0})})]})}function ho(s){var Ie;t.useAIInteractionStore(K=>K.currentAIContext);const[a,n]=y.useState(""),[r,c]=y.useState(null),{authToken:i,tokenProps:l}=t.useSemaphorContext(),d=t.useEditorStore(K=>K.card.id),o=t.useEditorStore(K=>{var le;return(le=K==null?void 0:K.card)==null?void 0:le.sql}),u=t.useEditorStore(K=>K.isDevMode),p=t.useEditorStore(K=>{var le;return(le=K==null?void 0:K.card)==null?void 0:le.python}),{setCardPython:h,setCardSql:x,setRunSql:m,switchCardType:g,setQueryConfig:b}=t.useEditorActions(),j=t.useEditorStore(K=>K.currentAssitantScope)||[],w=t.useEditorStore(K=>K.userInputForAI),T=t.useEditorStore(K=>K.triggerAIRun),P=t.useEditorStore(K=>K.card),N=t.useEditorStore(K=>K.selectedDatabaseName),A=t.useEditorStore(K=>K.selectedTableName),S=t.useEditorStore(K=>K.selectedConnectionId),I=t.useEditorStore(K=>K.selectedSchemaName),D=t.useDashboardStore(K=>K.dashboard.aiScopeTables),{errorMessage:M,refetch:v,data:R}=t.useEditorCardQuery(P),{setTriggerAIRun:C,setCurrentAssitantScope:k,setCardConfig:F}=t.useEditorActions(),{selectedDatamodelName:f,connectionType:L,selectedDatamodelId:E}=t.useEditorAside(),O=(Ie=t.useDashboardQuery().data)==null?void 0:Ie.assistantProfileId,B=y.useRef(t.createAssistantConversationId()),V=y.useRef(null),z=y.useRef(d),_=y.useRef(!1),U=()=>{const K=V.current;K&&(V.current=null,B.current=t.createAssistantConversationId(),K==="clear"&&$([]))},{messages:H,setMessages:$,regenerate:Z,error:re,sendMessage:ie,status:ce,addToolResult:he,stop:me,clearError:se}=t.useChat({transport:new t.DefaultChatTransport({api:`${l.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${i==null?void 0:i.accessToken}`}),body:()=>{const K=t.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:O,conversationId:B.current,assistantRequestId:t.createAssistantRequestId(),isDevMode:u,aiContext:K.currentAIContext,reasoningEffort:K.reasoningEffort,showReasoning:K.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:K,body:le})=>({body:{...le,messages:t.cleanupIncompleteMessages(K)}})}),onError:K=>{var le;if(_.current=!1,K.name==="AbortError"||(le=K.message)!=null&&le.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)"),U();return}console.error("[Editor Assistant] Stream error:",K),U()},onToolCall:X,onFinish({isAbort:K,isDisconnect:le,isError:ve}){_.current=!1,n(""),console.log(K?"[Editor Assistant] Stream aborted by user":le?"[Editor Assistant] Stream disconnected (network error)":ve?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully"),U()}}),be=y.useCallback(K=>{_.current=!0;try{const le=ie(K);return t.isPromiseLike(le)?le.catch(ve=>{throw _.current=!1,ve}):le}catch(le){throw _.current=!1,le}},[ie]),je=y.useCallback(()=>{_.current=!0;try{const K=Z();return t.isPromiseLike(K)?K.catch(le=>{throw _.current=!1,le}):K}catch(K){throw _.current=!1,K}},[Z]),ye=K=>{let le=!1;$(ve=>{const te=typeof K=="function"?K(ve):K;if(te.length===0){if(_.current)return V.current="clear",le=!0,ve;V.current=null,B.current=t.createAssistantConversationId()}return te}),le&&me()};y.useEffect(()=>{if(z.current!==d){if(z.current=d,_.current){V.current!=="clear"&&(V.current="rotate"),me();return}V.current=null,B.current=t.createAssistantConversationId()}},[d,me]),y.useEffect(()=>{T&&w&&(be({role:"user",parts:[{type:"text",text:w}]}),C(!1))},[T,w,be,C]);async function X({toolCall:K}){var le,ve,te,Q,ae,ue,Se,Ne,Oe,Ve,We,Je,Ye,ne,De,Be;if(["createChartFromSql","createForecast"].includes(K.toolName)){const Ce=((le=K.input)==null?void 0:le.sql)??((ve=K.args)==null?void 0:ve.sql),Ge=((te=K.input)==null?void 0:te.python)??((Q=K.args)==null?void 0:Q.python),we=((ae=K.input)==null?void 0:ae.chartType)??((ue=K.args)==null?void 0:ue.chartType);g(we),x(Ce),h(Ge),m(!0),he({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(K.toolName==="getUserSql"){if(!o){he({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"error",message:"No SQL found"}});return}he({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",sql:o,python:p||""}})}else if(K.toolName==="generateQueryConfig"){n("Generating query config...");const Ce=((Se=K.input)==null?void 0:Se.chartType)??((Ne=K.args)==null?void 0:Ne.chartType),Ge=((Oe=K.input)==null?void 0:Oe.queryConfig)??((Ve=K.args)==null?void 0:Ve.queryConfig);((We=K.input)==null?void 0:We.cardConfig)??((Je=K.args)==null||Je.cardConfig),g(Ce),F(Ge),x(void 0),h(void 0);const we=await v();if((Ye=we==null?void 0:we.data)!=null&&Ye.error){he({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"error",queryConfig:Ge,message:(ne=we==null?void 0:we.data)==null?void 0:ne.error.message}});return}if((De=we==null?void 0:we.data)!=null&&De.records){he({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",queryConfig:Ge,message:"The data has been visualized"}});return}he({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",queryConfig:Ge,message:"The data has been visualized",records:(Be=we==null?void 0:we.data)==null?void 0:Be.records}})}else n("Analyzing...")}function ge(K){const le=t.removeFromScopeArray(j,K);ee(le)}function ee(K){const le=t.sanitizeAIScope(K);k(le),$(ve=>[...ve,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(le)}`}]}])}function Te(){const K={databaseName:N||"",schemaName:I||"",tableName:A||"",datamodelId:E||"",datamodelName:t.resolveDatamodelName(f),connectionId:S||"",connectionType:L||""},le=t.dedup([...j,K]);ee(le)}function Le(){const K={databaseName:N||"",schemaName:I||"",tableName:A||"",datamodelName:t.resolveDatamodelName(f),connectionId:S||"",connectionType:L||"",datamodelId:E||""};if(!t.isInAiScopeArray([...D||[],...j],K)||j.length===0){const ve=t.dedup([...D||[],...j,K]).filter(te=>te.connectionId===K.connectionId);ee(ve)}}const Ae=!["ready","error"].includes(ce),Ee=t.getErrorMessage(re);return{messages:H,setMessages:ye,sendMessage:be,regenerate:je,isLoading:Ae,handleSetAIScope:Le,handleAddCurrentTableToScope:Te,removeFromCurrentSelections:ge,currentAssitantScope:j,setCurrentAssitantScope:k,stop:me,status:ce,toolStatus:a,llmUsage:r,onFinish:s,errorMessage:Ee,clearError:se}}const po=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Tn({isFullscreen:s,onFullscreenChange:a,fullscreenContainer:n}){const r=y.useRef(null),c=y.useRef(!1),[i,l]=y.useState(!1),[d,o]=y.useState(t.isDevEnv),[u,p]=y.useState(!1),[h,x]=y.useState(!1),[m,g]=y.useState(!1),b=s??m,j=t.useCurrentAIContext(),{setCurrentAIContext:w,setHasEditorEntitySelectionOverride:T}=t.useAIActions(),{clearQueue:P}=t.useQueueActions(),{clearFileAttachments:N}=t.useFileActions(),A=t.useFileAttachments("editor"),{selectedEntities:S}=t.useAssistantContextEntities("editor"),I=t.useEditorStore(ne=>ne.card.id),D=t.useEditorStore(ne=>ne.card.dataSource),M=t.useEditorStore(ne=>{var De;return(De=ne.card.dataSource)==null?void 0:De.selectedEntities}),v=t.useEditorStore(ne=>ne.actions.setCardSql),R=t.useEditorStore(ne=>ne.actions.setRunSql),C=t.useEditorStore(ne=>ne.showAIDialog),k=t.useDashboardStore(ne=>ne.handleOpenAssistantProfile),{setShowAIDialog:F,setCardPython:f}=t.useEditorActions(),{setDataSource:L}=t.useEditorActions(),{assistantProfile:E}=t.useAssistantProfile(),{messages:O,setMessages:B,sendMessage:V,isLoading:z,stop:_,status:U,llmUsage:H,errorMessage:$,clearError:Z}=ho(),[re,ie]=y.useState(""),ce=ne=>{ie(ne.target.value)},he=ne=>{ne.preventDefault();const De=re.trim();if(!De&&A.length===0)return;const Be=[];De&&Be.push({type:"text",text:De}),A.forEach(Ce=>{Ce.data&&Be.push({type:"file",mediaType:Ce.type,filename:Ce.name,url:`data:${Ce.type};base64,${Ce.data}`})}),V({role:"user",parts:Be}),ie(""),N("editor"),Ae({force:!0})},{visibleMessages:me,hasMoreMessages:se,totalMessageCount:be,loadMoreMessages:je,resetMessageWindow:ye}=t.useMessageWindow(O,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:X,contentRef:ge,isAtBottom:ee,hasNewMessages:Te,newMessageCount:Le,scrollToBottom:Ae,handleScroll:Ee,resetNewMessageCount:Ie}=t.useAutoScroll(me,{threshold:40,behavior:"smooth",isStreaming:z});y.useEffect(()=>{var ne;C&&!c.current&&((ne=r.current)==null||ne.focus()),c.current=C},[C]),y.useEffect(()=>{C&&(T(!1),w({selectedEntities:M||[]}))},[I,M,w,T,C]),t.useAutoSubmitQueue({assistantType:"editor",status:U,isLoading:z,sendMessage:V});const{hasActiveTools:K,activeToolText:le}=t.useActiveToolStatus(O),ve=y.useCallback(ne=>{a==null||a(ne),s===void 0&&g(ne)},[s,a]);y.useEffect(()=>{if(!b)return;function ne(De){De.key==="Escape"&&ve(!1)}return window.addEventListener("keydown",ne),()=>{window.removeEventListener("keydown",ne)}},[b,ve]);const te=y.useCallback(ne=>{V({role:"user",parts:[{type:"text",text:ne}]}),Ae({force:!0})},[V,Ae]),Q=y.useCallback(async()=>{const ne=JSON.stringify(O??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(ne),t.ue.success("Conversation copied")}catch(De){console.error("Failed to copy conversation",De),t.ue.error("Unable to copy conversation")}},[O]),ae=y.useCallback(()=>{ve(!b)},[b,ve]);function ue(ne,De){De==="sql"?(v(ne),R(!0)):De==="python"&&(f(ne),R(!0))}function Se(){j.selectedEntities.length===0&&w({selectedEntities:S})}function Ne(ne){Se();const De={role:"user",parts:[{type:"text",text:ne.title+" "+ne.subtitle}]};V(De)}function Oe(ne){Se(),V({role:"user",parts:[{type:"text",text:ne}]})}function Ve(){return e.jsxs(t.DropdownMenu,{children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.Button,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(t.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",children:[e.jsx(t.DropdownMenuLabel,{children:"Options"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsx(t.DropdownMenuCheckboxItem,{checked:i,onCheckedChange:l,children:"Token Usage"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:d,onCheckedChange:o,children:"Tool Invocations"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:u,onCheckedChange:p,children:"System Message"})]})]})}function We(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const Je=(re==null?void 0:re.length)===0&&(O==null?void 0:O.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",b&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[We(),k&&e.jsx(t.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:k,children:(E==null?void 0:E.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[Ve(),d&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Q,children:"Copy Conversation"}),e.jsx(t.IconButton,{tooltip:b?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:ae,children:b?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:()=>{B([]),P("editor"),Z(),ye()},children:e.jsx(t.SquarePen,{className:"size-4"})}),e.jsx(t.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{F(!1)},children:e.jsx(t.X,{className:"size-4"})})]})]}),e.jsx(t.CustomScrollArea,{ref:X,className:"mt-2 flex min-w-0 w-full grow basis-0",onScroll:Ee,children:e.jsxs("div",{ref:ge,className:"min-w-0 space-y-4 py-2 pr-3","data-role":"messages",children:[se&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:je,className:"text-xs",children:["Load ",Math.min(5,be-me.length)," ","more messages (",be-me.length," ","hidden)"]})}),e.jsx(t.PrintMessages,{messages:me,showTools:d,handleRun:ue,showSystemMessage:u,onQuickReply:te,disableQuickReplies:z}),e.jsx(t.AssistantStatus,{status:U,errorMessage:$,activeToolText:z&&K?le:void 0})]})}),C&&!ee&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(t.Button,{onClick:()=>{Ae({force:!0}),Ie()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(t.ChevronDown,{className:"h-4 w-4"}),Te&&Le>0&&e.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:Le>9?"9+":Le})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[Je&&!E&&e.jsx(t.Placeholders,{onClick:Ne,placeholders:po}),e.jsx("div",{children:Je&&E&&e.jsx(t.SeedQuestions,{seedQuestions:E.seedQuestions||[],handleSeedQuestionClick:Oe})})]}),e.jsx(t.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(t.ChatInputWithContext,{ref:r,setInput:ie,stop:_,input:re,handleInputChange:ce,handleSubmit:ne=>{Se(),he(ne),Ae({force:!0})},isLoading:z,status:U,assistantType:"editor",onFocus:()=>{}})]}),H&&i&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",H.inputTokens," prompt tokens, ",H.outputTokens," ","completion tokens, ",H.totalTokens," total tokens"]})}),e.jsx(t.DataSourceDialog,{incomingSelectedEntities:S,open:h,onOpenChange:x,dataSource:D||t.EMPTY_DATA_SOURCE,dialogMode:"aiContext",onSaveSelectedEntities:ne=>{T(!0),w({...j,selectedEntities:ne})}})]});return b&&n?ua.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 fo(s,a,n){if(!a)return!1;const r=a.qualifiedFieldName,c=a.qualifiedEntityName,i=c&&a.name?`${c}.${a.name}`:r;return s.some(l=>{if(!(t.getDataType(l.dataType||"")==="date"))return!1;const o=t.getSelectedDateFilterColumn(l,n),u=o.split("."),p=u[u.length-1]||o,h=u.length>1?u.slice(0,-1).join("."):void 0,x=l.qualifiedTableName||h,m=x?`${x}.${p}`:void 0;return r?m?m===i||m.endsWith(`.${r}`):p===a.name:m?m===i:p===a.name})}function go({aliasTemplate:s,onAliasTemplateChange:a}){var o;const[n,r]=y.useState(s),[c,i]=y.useState(!1),l=(o=t.useEditorStore(u=>{var p;return(p=u.card.config)==null?void 0:p.pivotByColumns}))==null?void 0:o[0],d=l?`e.g. Min Sales in {{${l.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Input,{placeholder:d,value:c?n:s,onChange:u=>{r(u.target.value),i(!0)},onFocus:()=>i(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&c&&n!==s?(a(n),i(!1)):u.key==="Escape"&&(r(s),i(!1))},"aria-label":"Edit alias template"}),c&&n!==s&&e.jsxs(e.Fragment,{children:[e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{a(n),i(!1)},children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(s),i(!1)},children:e.jsx(t.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function jo({valueAliases:s,onValueAliasesChange:a}){const[n,r]=y.useState(null),[c,i]=y.useState(""),[l,d]=y.useState(""),o=()=>{a({...s,"":""})},u=h=>{const x={...s};delete x[h],a(x)},p=h=>{const x={...s};delete x[h],x[c]=l,a(x),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(s).map(([h,x],m)=>e.jsx("div",{className:"flex items-center gap-2",children:n===h?e.jsxs(e.Fragment,{children:[e.jsx(t.Input,{placeholder:"Value key",value:c,onChange:g=>i(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?p(h):g.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(t.Input,{placeholder:"Alias label",value:l,onChange:g=>d(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?p(h):g.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>p(h),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:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),i(h),d(x)},"aria-label":"Edit value alias key"}),e.jsx(t.Input,{placeholder:"Alias label",value:x,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),i(h),d(x)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(h),"aria-label":"Remove value alias",children:e.jsx(t.X,{className:"h-3 w-3"})})]})},h+m)),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:o,children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function bo({idx:s}){var d;const a=t.useEditorStore(o=>{var u;return(u=o.card)==null?void 0:u.preferences}),n=t.useEditorStore(o=>{var u;return(u=o.card.preferences)==null?void 0:u.datasetOptions}),r=t.useEditorStore(o=>o.actions.setCardPreferences),c=(d=a==null?void 0:a.chartOptions)==null?void 0:d.indexAxis,i=n==null?void 0:n.find(o=>o.idx===s);function l(o,u){(o==="end"||o==="start")&&t.getContrastColor(t.getCanvasBackgroundColor());const p={display:o!=="none",align:o,anchor:o,clamp:!0};if(!i)r({...a,datasetOptions:[...n||[],{idx:u,datalabels:p}]});else{const h={...i};h.datalabels=p;const x=n==null?void 0:n.map(m=>m.idx===u?h:m);r({...a,datasetOptions:x})}}return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{children:e.jsx(t.Tag,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(t.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>l("none",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(t.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>l("start",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(ya,{className:t.cn("h-4 w-4",{"rotate-90":c==="y"})})}),e.jsx("button",{onClick:()=>l("center",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Ca,{className:t.cn("h-4 w-4",{"rotate-90":c==="y"})})}),e.jsx("button",{onClick:()=>l("end",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Na,{className:t.cn("h-4 w-4",{"rotate-90":c==="y"})})})]})})]})}function ps({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 vo(s,a=30){return s.length>a?s.slice(0,a)+"...":s}function yo({col:s,idx:a,className:n,iconClassName:r,children:c}){const i=t.useEditorStore(p=>{var h;return(h=p.card)==null?void 0:h.preferences}),l=t.useEditorStore(p=>{var h,x;return(x=(h=p.card)==null?void 0:h.preferences)==null?void 0:x.datasetOptions}),d=l==null?void 0:l.find(p=>p.idx===a),{setCardPreferences:o}=t.useEditorStore(p=>p.actions);function u(p){if(!d)o({...i,datasetOptions:[...l||[],{idx:a,type:p==="area"?"line":p,fill:p==="area"?"origin":""}]});else{const h={...d};h.type=p==="area"?"line":p,h.fill=p==="area"?"origin":"";const x=l==null?void 0:l.map(m=>m.idx===a?h:m);o({...i,datasetOptions:x})}}return e.jsxs("div",{className:t.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[c||e.jsx(ps,{className:"max-w-[100px]",title:s,children:vo(s)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(t.ChartColumnIncreasing,{onClick:()=>u("bar"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(t.ChartLine,{onClick:()=>u("line"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(t.ChartArea,{onClick:()=>u("area"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(bo,{idx:a})]})]})}function No(){const s=t.useEditorStore(d=>d.card.type),a=t.useEditorStore(d=>d.isDevMode),n=t.useEditorStore(d=>d.card.preferences),{setCardPreferences:r}=t.useEditorStore(d=>d.actions);function c(d){var p;const o={datalabels:{display:d!=="none",align:d,anchor:d,clamp:!0}},u={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(p=n==null?void 0:n.chartOptions)==null?void 0:p.plugins,...o}}};r(u)}function i(){var d,o,u;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(t.Select,{value:((u=(o=(d=n==null?void 0:n.chartOptions)==null?void 0:d.plugins)==null?void 0:o.datalabels)==null?void 0:u.anchor)||"none",onValueChange:c,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Data Labels"}),e.jsx(t.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"start",children:"Start"}),e.jsx(t.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"end",children:"End"})]})})]})]})}function l(){var d,o,u;return e.jsx("div",{children:e.jsxs(t.Select,{value:((u=(o=(d=n==null?void 0:n.chartOptions)==null?void 0:d.plugins)==null?void 0:o.datalabels)==null?void 0:u.anchor)||"none",onValueChange:c,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(t.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:a?i():l()})}function Co({column:s}){const a=t.useEditorStore(o=>o.card.type),n=t.useEditorStore(o=>{var u,p;return(p=(u=o.card)==null?void 0:u.config)==null?void 0:p.metricColumns}),r=(n==null?void 0:n.map(o=>o.label))||[],c=r==null?void 0:r.find(o=>o===s.label||o===s.name),i=c?r.indexOf(c):-1;function l(){return e.jsx("div",{className:"pr-1",children:c&&e.jsx(yo,{idx:i,col:c,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function d(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(No,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&l(),["pie","doughnut"].includes(a)&&d()]})}function So({field:s,searchQuery:a="",limit:n=500}){const{authToken:r,tokenProps:c}=t.useSemaphorContext(),i=t.useEditorStore(u=>u.card),l=i==null?void 0:i.dataSource,d=["attribute-values",s.entityName,s.name,a,n],o=t.useQuery({queryKey:d,queryFn:async()=>{if(!(l!=null&&l.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const u={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},p={connection_id:l.connectionId,cardConfig:u,cardDataSource:l,cache_config:t.getCacheConfig({card:i})};console.log("requestBody",p);const h=await t.postRequestRegular(`${c.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",p);if(h!=null&&h.error)return console.error("Error fetching attribute values:",h.error),[];const x=s.name;return((h==null?void 0:h.records)||[]).map(g=>{const b=g[x]||g[s.alias||x]||g[s.label];return{id:b||"",value:b||"",label:String(b||"(empty)")}})}catch(u){return console.error("Error fetching attribute values:",u),[]}},enabled:!!s&&!!(l!=null&&l.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:o.data||[],isLoading:o.isLoading,isFetching:o.isFetching,isError:o.isError,error:o.error,refetch:o.refetch}}function Hn({open:s,onOpenChange:a,availableFields:n,existingFilters:r,editingCondition:c,onSave:i}){var P,N;const l=!!c,[d,o]=y.useState(l?"values":"fields"),[u,p]=y.useState(""),[h,x]=y.useState({id:(c==null?void 0:c.id)||t.v4(),field:(c==null?void 0:c.field)||null,selectedValues:c?Array.isArray(c.value)?c.value:[c.value]:[]}),m=n.filter(A=>{var I;return l?!1:!((I=r==null?void 0:r.conditions)==null?void 0:I.some(D=>D.field.id===A.id))&&A.label.toLowerCase().includes(u.toLowerCase())}),g=A=>{x({...h,field:A}),o("values")},b=()=>{if(h.field&&h.selectedValues.length>0){const A={id:h.id,field:h.field,operator:"in",value:h.selectedValues};let S;if(l){const I=((r==null?void 0:r.conditions)||[]).map(D=>D.id===c.id?A:D);S={...r,conditions:I}}else{const I=(r==null?void 0:r.conditions)||[];S={id:(r==null?void 0:r.id)||t.v4(),logicalOperator:"AND",negate:!1,conditions:[...I,A],groups:[]}}i(S),a(!1)}},j=()=>{if(!l||!c)return;const A=((r==null?void 0:r.conditions)||[]).filter(S=>S.id!==c.id);if(A.length>0){const S={...r,conditions:A};i(S)}else i(void 0);a(!1)},w=A=>{x({...h,selectedValues:A})},T=()=>{l&&c?(x({id:c.id,field:c.field,selectedValues:Array.isArray(c.value)?c.value:[c.value]}),o("values")):(x({id:t.v4(),field:null,selectedValues:[]}),o("fields")),p("")};return y.useEffect(()=>{s&&T()},[s,l,c]),e.jsx(t.Dialog,{open:s,onOpenChange:a,children:e.jsxs(t.DialogContent,{className:"max-w-2xl",children:[e.jsx(t.DialogHeader,{children:e.jsx(t.DialogTitle,{children:l?`Edit Filter: ${(P=h.field)==null?void 0:P.label}`:d==="fields"?"Select Field to Filter":`Select Values for ${(N=h.field)==null?void 0:N.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!l&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&d==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Current Filters:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.conditions.map(A=>e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-muted rounded-md text-xs",children:[e.jsxs("span",{className:"font-medium",children:[A.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(A.value)?`${A.value.length} values`:String(A.value)})]},A.id))})]}),d==="fields"&&!l?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(t.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(t.Input,{placeholder:"Search fields...",value:u,onChange:A=>p(A.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:m.map(A=>e.jsxs(t.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>g(A),children:[e.jsx(t.IconForFieldType,{dataType:t.getDataType(A.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:A.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[A.entityName,".",A.name]})]})]},A.id))}),m.length===0&&u&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',u,'"']}),m.length===0&&!u&&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(wo,{field:h.field,selectedValues:h.selectedValues,onValuesChange:w,onBack:l?void 0:()=>o("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:l?e.jsx(t.Button,{variant:"destructive",onClick:j,children:"Delete Filter"}):e.jsx(t.Button,{variant:"outline",onClick:T,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:b,disabled:!h.field||h.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function wo({field:s,selectedValues:a,onValuesChange:n,onBack:r}){const[c,i]=y.useState(""),{values:l,isLoading:d,isFetching:o}=So({field:s,searchQuery:c,limit:500}),u=c?l.filter(x=>String(x.value).toLowerCase().includes(c.toLowerCase())):l,p=x=>{const m=a.includes(x);n(m?a.filter(g=>g!==x):[...a,x])},h=()=>{a.length===u.length&&u.length>0?n([]):n(u.map(x=>x.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:r,children:"← Back"}),e.jsxs(t.Label,{className:"text-sm font-medium",children:["Select values for ",s.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(t.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(t.Input,{placeholder:"Search values...",value:c,onChange:x=>i(x.target.value),className:"pl-10"})]}),d||o?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(t.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx(t.Checkbox,{checked:a.length===u.length&&u.length>0,onCheckedChange:h}),e.jsxs(t.Label,{className:"text-sm",children:["Select All (",u.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:u.map(x=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>p(x.value),children:[e.jsx(t.Checkbox,{checked:a.includes(x.value),onCheckedChange:()=>p(x.value)}),e.jsx(ps,{className:"text-sm",children:x.label})]},x.id))})]})]})}function To({field:s,zone:a,index:n,sortDirection:r,onSortDirectionChange:c,hasPivotColumns:i=!1,cardType:l}){var Ns,Cs,Ss,ws,Ts,Es,Is,Ds,ks,As,Ms,Ls,Fs,Rs,Os,Ps,Bs,Vs,zs,_s,qs,$s,Ks,Gs,Us,Hs,Qs,Js,Ys,Ws,Xs,Zs,en;const{attributes:d,listeners:o,setNodeRef:u,transform:p,transition:h,isDragging:x}=t.useSortable({id:s.id}),m=t.useEditorStore(G=>G.card),g=t.useEditorStore(G=>G.frame),b=t.useDashboardStore(G=>G.isVisualEditing),j=t.useDashboardStore(G=>G.selectedSheetId),w=t.useDashboardStore(G=>G.actions.updateSheetCalculatedFields),{scopedFields:T,valuePickFilterableFields:P,isLoading:N}=t.useFilterableFields(),{userContext:A}=t.useCurrentUserInfo(),S=(A==null?void 0:A.type)==="organization",{updateLabel:I,handleAggregationChange:D,handleDateFormatChange:M,handleGranularityChange:v,handleAliasTemplateChange:R,handleValueAliasesChange:C,handleMetricFormatChange:k,removeField:F,handleMetricComparisonChange:f,handleMetricWindowTransformChange:L,handleMetricWindowOrderByChange:E,handleMetricWindowDirectionChange:O,handleMetricWindowPartitionToggle:B,handleMetricMovingAverageWindowSizeChange:V,handleMetricMovingAverageMinPeriodsChange:z,handleMetricPreviousPeriodDeltaModeChange:_,handleMetricPercentOfTotalScopeChange:U,handleMetricPercentOfTotalOutputChange:H,handleKpiShowTrendlineChange:$,handleKpiTrendlineWindowChange:Z,handleKpiTrendlineGranularityChange:re,handleMetricTargetValueChange:ie}=t.useFieldManagement(m),[ce,he]=y.useState(!1),[me,se]=y.useState(()=>{var G;return!!((G=s.parameters)!=null&&G.windowTransform)}),[be,je]=y.useState(!1),[ye,X]=y.useState(!1),[ge,ee]=y.useState(null),Te=y.useMemo(()=>{const G=oe=>oe!=null&&oe.startsWith("card-source-")?oe.replace("card-source-",""):oe,Y=G(s.id),xe=T.find(oe=>{if(s.qualifiedFieldName&&oe.qualifiedFieldName&&oe.qualifiedFieldName===s.qualifiedFieldName||s.qualifiedEntityName&&oe.qualifiedEntityName&&oe.qualifiedEntityName===s.qualifiedEntityName&&oe.name===s.name)return!0;const Me=G(oe.id);return!!(Y&&Me&&Y===Me)});return{dataType:(xe==null?void 0:xe.dataType)||s.dataType,resolvedFromScopedField:!!xe}},[s.dataType,s.id,s.name,s.qualifiedEntityName,s.qualifiedFieldName,T]),Le=t.getGranularityOptionsForFieldType(Te.dataType),[Ae,Ee]=y.useState(s.dateFormat||"YYYY-MM-DD"),[Ie,K]=y.useState(s.customFormat||""),[le,ve]=y.useState(!!s.customFormat),te=y.useRef(null),[Q,ae]=y.useState(s.aliasTemplate||""),[ue,Se]=y.useState(s.valueAliases||{}),[Ne,Oe]=y.useState((Ns=s.parameters)==null?void 0:Ns.filters),Ve=G=>{G==="custom"?ve(!0):(ve(!1),Ee(G),(a==="groupBy"||mt)&&M(n,G,"",a))},We=G=>{K(G),(a==="groupBy"||mt)&&M(n,"custom",G,a)},Je=G=>{var oe;const xe=(oe=t.getDateFormatOptionsForGranularity(G)[0])==null?void 0:oe.value;xe&&!le&&(Ee(xe),a==="groupBy"&&M(n,xe,"",a)),a==="groupBy"&&v(n,G)},Ye=G=>{ae(G),a==="metrics"&&R(n,G)},ne=G=>{Se(G),a==="metrics"&&C(n,G)},De=G=>{I(a,n,G)},Be=t.getExpressionFieldKind(s),Ce=t.getFieldExpressionAnnotation(s),Ge=t.isManagedCalculatedExpressionField(s),we=s.role==="metric"&&Ge,bt=Ge&&(Be==="user_calculated"||Be==="inline_expression"&&s.fieldScope!=="domain"),Xe=bt?(Cs=g==null?void 0:g.calculatedFields)==null?void 0:Cs.find(G=>t.matchesCalculatedField(G,s,{allowComparableFallback:!0})):void 0,Tt=bt&&(s.fieldScope==="dashboard"||s.fieldScope===void 0&&!!Xe),Ue=Be==="domain_calculated"||s.fieldScope==="domain",Et=Ue?t.resolveDomainCalculatedFieldForEdit(s,T):void 0,ct=Ue?"domain":Tt?"dashboard":"card",Ze=Ue?Et||s:Tt&&Xe?Xe:s,It=G=>{var Y;if(Oe(G),a==="metrics"){const xe={...s,parameters:{...s.parameters,filters:G}},oe=[...((Y=m.config)==null?void 0:Y.metricColumns)||[]];oe[n]=xe,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:oe})}je(!1)},vt=()=>{F(a,n)},Kt={transform:t.CSS.Transform.toString(p),transition:h},Dt=t.getDataType(Te.dataType||s.dataType),dt=Dt==="date",ut=l==="kpi",mt=a==="detailColumns",xt=(Ss=m.config)==null?void 0:Ss.metricColumns,$e=(ws=m.config)==null?void 0:ws.groupByColumns,et=t.useDashboardStore(G=>{var Y;return(Y=G.dashboard)==null?void 0:Y.filters}),Gt=t.useDashboardStore(G=>G.filterValues),tt=s.granularity||"day",kt=Le.includes(tt)?tt:"day",yt=a==="groupBy"&&!Le.includes(tt),ht=t.getDateFormatOptionsForGranularity(kt),Ut=le?"custom":ht.some(G=>G.value===Ae)?Ae:((Ts=ht[0])==null?void 0:Ts.value)??"YYYY-MM-DD";y.useEffect(()=>{var xe;if(N||!yt){te.current=null;return}const G=`${s.id}:${tt}:${Te.dataType||s.dataType||""}:${n}`;if(te.current===G)return;te.current=G;const Y="day";if(v(n,Y),!le){const oe=(xe=t.getDateFormatOptionsForGranularity(Y)[0])==null?void 0:xe.value;oe&&(Ee(oe),M(n,oe,"",a))}},[s.dataType,s.id,M,v,yt,n,le,N,tt,Te.dataType,a]);const Ht=!!l&&t.COMPARISON_SUPPORTED_CHART_TYPES.includes(l),Qt=l==="kpi"||l==="table",Ke=y.useMemo(()=>$e==null?void 0:$e.find(G=>t.getDataType(G.dataType||"")==="date"),[$e]),At=y.useMemo(()=>($e||[]).some(G=>t.getDataType(G.dataType||"")==="date"),[$e]),pt=y.useMemo(()=>{var oe;if(!Ke)return!1;const G=(oe=m.config)==null?void 0:oe.filters;if(!G)return!1;const Y=Me=>{const Re=Me.field;return Re?Ke.id&&Re.id===Ke.id||Ke.qualifiedFieldName&&Re.qualifiedFieldName===Ke.qualifiedFieldName?!0:Re.name===Ke.name:!1},xe=Me=>Me.conditions.some(_e=>t.getDataType(_e.field.dataType||"")==="date"&&Y(_e))?!0:Me.groups.some(_e=>xe(_e));return xe(G)},[(Es=m.config)==null?void 0:Es.filters,Ke]),Mt=y.useMemo(()=>fo(et||[],Ke,Gt),[et,Gt,Ke]),Nt=pt||Mt,q=s,W=((Ds=(Is=q.parameters)==null?void 0:Is.windowTransform)==null?void 0:Ds.function)||"none",J=t.isMetricTransformEnabled(q),de=J?W:null,pe=t.supportsMetricTransformForMetric({cardType:l||"table",cardConfig:m.config||{},metric:q,transformMode:de||"running_total"}),fe=!!q.comparisonType&&q.comparisonType!=="none",Fe=t.getRunningTotalOrderByCandidates($e||[]),Pe=((Ms=(As=(ks=q.parameters)==null?void 0:ks.windowTransform)==null?void 0:As.orderBy)==null?void 0:Ms.fieldId)||"",Qe=((Rs=(Fs=(Ls=q.parameters)==null?void 0:Ls.windowTransform)==null?void 0:Fs.orderBy)==null?void 0:Rs.direction)||"asc",rt=Fe.find(G=>G.id===Pe),st=de==="running_total"||de==="moving_average"||de==="previous_period_delta",ze=J&&st&&!!rt&&t.getDataType(rt.dataType||"")!=="date",ft=t.getDefaultRunningTotalPartitionByFieldIds({cardType:l||"table",cardConfig:m.config||{},orderByFieldId:Pe||void 0}),Jt=new Set(((Ps=(Os=q.parameters)==null?void 0:Os.windowTransform)==null?void 0:Ps.partitionByFieldIds)||ft),Yt=l==="pivotTable"||t.isSubtotalEnabledAggregateTable(l||"table",m.config||{}),gs=[...($e||[]).filter(G=>G.id&&(!st||G.id!==Pe)),...Yt?(((Bs=m.config)==null?void 0:Bs.pivotByColumns)||[]).filter(G=>G.id):[]],js=((_s=(zs=(Vs=q.parameters)==null?void 0:Vs.windowTransform)==null?void 0:zs.movingAverage)==null?void 0:_s.windowSize)||7,Jn=((Ks=($s=(qs=q.parameters)==null?void 0:qs.windowTransform)==null?void 0:$s.movingAverage)==null?void 0:Ks.minPeriods)||1,Yn=((Hs=(Us=(Gs=q.parameters)==null?void 0:Gs.windowTransform)==null?void 0:Us.previousPeriodDelta)==null?void 0:Hs.mode)||"absolute",bs=((Ys=(Js=(Qs=q.parameters)==null?void 0:Qs.windowTransform)==null?void 0:Js.percentOfTotal)==null?void 0:Ys.scope)||"grand_total",Wn=((Zs=(Xs=(Ws=q.parameters)==null?void 0:Ws.windowTransform)==null?void 0:Xs.percentOfTotal)==null?void 0:Zs.output)||"percent",Xn=y.useMemo(()=>(xt||[]).some(G=>G.comparisonType==="start_vs_end"),[xt]);y.useEffect(()=>{J&&se(!0)},[J]);const Zn=a!=="pivotBy"&&a!=="sortBy",ea=dt&&a==="groupBy"&&(!ut||Xn),ta=!ut&&dt&&(a==="groupBy"||mt),sa=l==="kpi"&&dt&&a==="groupBy",na=a==="metrics",vs=Ht&&a==="metrics",aa=()=>{const G=s,Y=a==="metrics"&&we;return e.jsxs("div",{className:"space-y-1",children:[!Y&&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}`}),Y&&G.calculatedFormula&&e.jsxs("div",{title:t.formatDisplayFormula(G.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(G.calculatedFormula)]})]})},ra=()=>Zn?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(He,{value:s.label??"",onSave:De,placeholder:"Display label...",type:"text"})]}):null,la=()=>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:G=>c(G),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"asc",children:"Ascending"}),e.jsx(t.SelectItem,{className:"text-xs",value:"desc",children:"Descending"})]})]})]}),ys=()=>ea?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(t.Select,{value:kt,onValueChange:Je,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select granularity..."})}),e.jsx(t.SelectContent,{children:Le.map(G=>e.jsx(t.SelectItem,{className:"text-xs",value:G,children:t.toTitleCase(G)},G))})]})]}):null,oa=()=>ta?e.jsxs(e.Fragment,{children:[ys(),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Date Format"}),e.jsxs(t.Select,{value:Ut,onValueChange: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(G=>e.jsx(t.SelectItem,{className:"text-xs",value:G.value,children:G.label},G.value))})]}),le&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(t.Input,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:Ie,onChange:G=>{G.stopPropagation(),We(G.target.value)},onClick:G=>G.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}):null,ia=()=>{var Y,xe,oe,Me;const G=sa;return G?e.jsx(e.Fragment,{children:G&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(t.Switch,{size:"sm",checked:((Y=m.config)==null?void 0:Y.showTrendline)||!1,onCheckedChange:$})]})}),((xe=m.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:((oe=m.config)==null?void 0:oe.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:((Me=m.config)==null?void 0:Me.trendlineGranularity)||"day",onValueChange:re,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},ca=()=>{if(!na)return null;const G=we;return e.jsxs(e.Fragment,{children:[G&&S&&!Ue&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Formula"}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>X(!0),children:[e.jsx(t.Pencil,{className:"mr-2 h-3 w-3"}),"Edit Formula"]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(t.Select,{value:s.aggregate,onValueChange:Y=>{D(n,Y)},disabled:G,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select function..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(t.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),t.getDataType(s.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(t.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(t.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(t.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(t.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Number Format"}),e.jsx(hs,{value:q.format,onChange:Y=>k(n,Y),showTitle:!1})]}),e.jsx(t.Collapsible,{open:me,onOpenChange:se,children:e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-muted/20 p-2.5",children:[e.jsx(t.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between rounded-sm px-0.5 py-0.5 text-left",children:[e.jsx("div",{className:"text-xs font-medium text-foreground",children:"Metric Transform"}),e.jsxs("div",{className:"flex items-center text-[11px] text-muted-foreground",children:[!me&&e.jsx("span",{className:"mr-2",children:J?t.toTitleCase(W.replace(/_/g," ")):"None"}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 transition-transform",me?"rotate-180":"")})]})]})}),e.jsxs(t.CollapsibleContent,{className:"space-y-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Transform"}),e.jsxs(t.Select,{value:J?W:"none",onValueChange:Y=>L(n,Y),disabled:!pe.supported&&!J,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select transform..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"none",children:"None"}),e.jsx(t.SelectItem,{value:"running_total",disabled:fe,children:"Running Total"}),e.jsx(t.SelectItem,{value:"moving_average",disabled:fe,children:"Moving Average"}),e.jsx(t.SelectItem,{value:"previous_period_delta",disabled:fe,children:"Previous Period Delta"}),e.jsx(t.SelectItem,{value:"percent_of_total",disabled:fe,children:"Percent of Total"})]})]}),!pe.supported&&!J&&e.jsx("div",{className:"text-xs text-muted-foreground",children:pe.reason}),fe&&!J&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"Disable comparison to enable metric transforms."})]}),J&&e.jsxs(e.Fragment,{children:[st&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Order By"}),e.jsxs(t.Select,{value:Pe,onValueChange:Y=>E(n,Y),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(Y=>!!Y.id).map(Y=>e.jsx(t.SelectItem,{value:Y.id,className:"text-xs",children:Y.label||Y.name},Y.id))})]}),!Pe&&e.jsx("div",{className:"text-xs text-amber-700",children:"No date trend detected. Select an order field."}),ze&&e.jsx("div",{className:"text-xs text-amber-700",children:"No date trend detected. The transform will follow the selected order field."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Direction"}),e.jsxs(t.Select,{value:Qe,onValueChange:Y=>O(n,Y),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"})]})]})]})]}),de==="moving_average"&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Window Size"}),e.jsx(t.Input,{type:"number",min:1,className:"h-8 text-xs",value:js,onChange:Y=>V(n,Number(Y.target.value))}),e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Min Periods"}),e.jsx(t.Input,{type:"number",min:1,max:js,className:"h-8 text-xs",value:Jn,onChange:Y=>z(n,Number(Y.target.value))})]}),de==="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:Yn,onValueChange:Y=>_(n,Y),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"})]})]})]}),de==="percent_of_total"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Scope"}),e.jsxs(t.Select,{value:bs,onValueChange:Y=>U(n,Y),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:Wn,onValueChange:Y=>H(n,Y),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"})]})]})]})]}),(de==="running_total"||de==="moving_average"||de==="previous_period_delta"||de==="percent_of_total"&&bs==="partition_total")&&gs.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Reset By"}),e.jsx("div",{className:"space-y-1",children:gs.map(Y=>{const xe=!!Y.id&&Jt.has(Y.id);return e.jsxs("button",{type:"button",onClick:()=>Y.id&&B(n,Y.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:Y.label||Y.name}),xe?e.jsx(t.Check,{className:"h-3 w-3"}):null]},Y.id)})})]})]})]})]})}),vs&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(t.Select,{value:q.comparisonType||"none",disabled:J,onValueChange:Y=>f(n,Y),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 Y=!At||!Nt,xe=At?Nt?void 0:"Add a date filter to enable":"Add a date groupBy to enable",oe=(Me,Re)=>e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.SelectItem,{value:Me,disabled:Y,title:xe,children:Re})}),Y&&xe&&e.jsx(t.TooltipContent,{side:"right",children:xe})]})});return e.jsxs(e.Fragment,{children:[oe("previous_period","Previous Period"),oe("same_period_last_year","Same Period Last Year"),oe("start_vs_end","Start vs End")]})})(),Qt&&e.jsx(t.SelectItem,{value:"target",children:"Target"})]})]})]}),vs&&q.comparisonType==="target"&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(t.Input,{type:"number",value:q.targetValue!==void 0&&q.targetValue!==null?String(q.targetValue):"",onChange:Y=>{const xe=Y.target.value;if(xe===""){ie(n,void 0);return}const oe=Number(xe);ie(n,Number.isFinite(oe)?oe:void 0)},className:"h-8 text-xs",placeholder:"Enter target value..."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(Ne==null?void 0:Ne.conditions)&&Ne.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:Ne.conditions.map(Y=>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:()=>{ee(Y),je(!0)},children:[e.jsxs("span",{className:"font-medium",children:[Y.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(Y.value)?Y.value.length===1?String(Y.value[0]):Y.value.length<=2?Y.value.join(", "):`${Y.value.slice(0,2).join(", ")} +${Y.value.length-2}`:String(Y.value)})}),Array.isArray(Y.value)&&Y.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 (",Y.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:Y.value.map((xe,oe)=>e.jsx("div",{children:String(xe)},oe))})]})})]})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:xe=>{var Me;xe.stopPropagation();const oe=Ne.conditions.filter(Re=>Re.id!==Y.id);if(oe.length>0){const Re={...Ne,conditions:oe};It(Re)}else if(Oe(void 0),a==="metrics"){const Re={...s,parameters:{...s.parameters,filters:void 0}},_e=[...((Me=m.config)==null?void 0:Me.metricColumns)||[]];_e[n]=Re,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:_e})}},children:e.jsx(t.X,{className:"h-3 w-3"})})]},Y.id))}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{ee(null),je(!0)},children:[e.jsx(t.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(Co,{column:s}),i&&e.jsxs(e.Fragment,{children:[e.jsx(go,{aliasTemplate:Q,onAliasTemplateChange:Ye}),e.jsx(jo,{valueAliases:ue,onValueAliasesChange:ne})]})]})},da=(Ne==null?void 0:Ne.conditions)&&Ne.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:u,style:Kt,className:t.cn("group mx-auto flex w-full flex-col gap-2 rounded-md border border-border/55 bg-background p-2 transition-colors duration-150","hover:border-border/80 hover:bg-muted/20",ce&&"border-border/80 bg-muted/20 shadow-[inset_0_1px_0_rgba(255,255,255,0.35)]",x&&"z-50 scale-95 opacity-50","cursor-default"),children:[e.jsxs("div",{className:"flex min-w-0 grow items-center gap-2",children:[e.jsx("button",{type:"button",...d,...o,className:"flex shrink-0 cursor-grab items-center rounded-sm p-0.5 text-muted-foreground transition-colors hover:text-foreground active:cursor-grabbing","aria-label":`Drag ${t.getMetricDisplayLabel(s)}`,onClick:G=>{G.stopPropagation()},children:e.jsx(t.GripVertical,{className:"h-3.5 w-3.5"})}),e.jsxs("div",{className:"relative shrink-0",children:[e.jsx(t.IconForFieldType,{dataType:Dt}),Ce&&e.jsx("span",{className:t.cn(t.FIELD_EXPRESSION_BADGE_BASE_CLASS,Ce.badgeClassName),children:Ce.label})]}),e.jsx(ps,{className:t.cn("block w-0 min-w-0 flex-1 text-sm text-foreground/95",da&&"min-w-0"),children:t.getMetricDisplayLabel(s)}),a==="metrics"&&((en=Ne==null?void 0:Ne.conditions)==null?void 0:en.length)&&!ce&&e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 text-xs text-primary/90",children:[e.jsx(t.Filter,{className:"h-3 w-3"}),e.jsx("span",{children:Ne.conditions.length})]})}),e.jsx(t.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:Ne.conditions.map(G=>e.jsxs("div",{children:[G.field.label,":"," ",Array.isArray(G.value)?`${G.value.length} values`:String(G.value)]},G.id))})})]})}),a==="sortBy"&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 shrink-0 p-0 text-foreground/55 hover:text-foreground",onClick:G=>{G.stopPropagation(),c(r==="asc"?"desc":"asc")},children:r==="asc"?e.jsx(t.ArrowUp,{className:"h-3 w-3"}):e.jsx(t.ArrowDown,{className:"h-3 w-3"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 shrink-0 p-0 text-foreground/55 hover:text-foreground",onClick:G=>{G.stopPropagation(),he(!ce)},children:e.jsx(t.ChevronDown,{className:`h-3 w-3 transition-transform ${ce?"rotate-180":""}`})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 shrink-0 p-0 text-foreground/55 hover:text-foreground",onClick:G=>{G.stopPropagation(),vt()},children:e.jsx(t.X,{className:"h-2.5 w-2.5"})})]}),ce&&e.jsxs("div",{className:"space-y-3 rounded-md bg-muted/20 p-2.5",children:[aa(),la(),ra(),l==="kpi"&&ys(),oa(),ia(),ca()]})]}),be&&e.jsx(Hn,{open:be,onOpenChange:G=>{je(G),G||ee(null)},availableFields:P,existingFilters:Ne,editingCondition:ge,onSave:G=>{var Y;if(G)It(G);else if(Oe(void 0),a==="metrics"){const xe={...s,parameters:{...s.parameters,filters:void 0}},oe=[...((Y=m.config)==null?void 0:Y.metricColumns)||[]];oe[n]=xe,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:oe})}ee(null)}}),ye&&a==="metrics"&&we&&e.jsx(t.CalculatedFieldEditor,{open:ye,onOpenChange:X,availableFields:T,existingField:Ze,existingFieldScope:ct,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:G=>{var Ft;if(G.role!=="metric")return;const{card:Y,frame:xe,actions:oe}=t.useEditorStore.getState(),Me=((Ft=Y.config)==null?void 0:Ft.metricColumns)||[],Re=xe.calculatedFields||[],{nextActiveFields:_e,nextStoredFields:Ct,nextSharedFields:Lt}=t.saveCalculatedFieldToCardScope({activeFields:Me,storedFields:Y.calculatedFields||[],sharedFields:Re,updatedField:G,editingField:Ze,previousScope:ct});_e&&oe.updateCardConfig(m.id,{metricColumns:_e}),oe.updateCard(m.id,{calculatedFields:Ct}),Lt!==Re&&t.commitSharedCalculatedFields({nextSharedFields:Lt,currentSharedFields:Re,isVisualEditing:b,selectedSheetId:j,updateFrame:oe.updateFrame,updateSheetCalculatedFields:w})},onSaveToDashboard:G=>{var tn;if(G.role!=="metric")return;const{card:Y,frame:xe,actions:oe}=t.useEditorStore.getState(),Me=s,Re=((tn=Y.config)==null?void 0:tn.metricColumns)||[],_e=xe.calculatedFields||[],{nextActiveFields:Ct,nextStoredFields:Lt,nextSharedFields:Ft}=t.saveCalculatedFieldToSharedScope({activeFields:Re,storedFields:Y.calculatedFields||[],sharedFields:_e,updatedField:{...G,id:Me.id,aliasTemplate:Me.aliasTemplate,valueAliases:Me.valueAliases,parameters:Me.parameters,customFormat:Me.customFormat},editingField:Ze,previousScope:ct});t.commitSharedCalculatedFields({nextSharedFields:Ft,currentSharedFields:_e,isVisualEditing:b,selectedSheetId:j,updateFrame:oe.updateFrame,updateSheetCalculatedFields:w}),Ct&&oe.updateCardConfig(m.id,{metricColumns:Ct}),oe.updateCard(m.id,{calculatedFields:Lt})},cardId:m.id})]})}function Eo({concept:s}){const a=()=>{switch(s){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-100 text-xs font-medium dark:bg-blue-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/50 text-xs font-medium dark:bg-blue-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/30 text-xs font-medium dark:bg-blue-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/20 text-xs font-medium dark:bg-blue-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Pivot Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metric Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});case"detailColumns":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields to display as columns in the detail table. No aggregation applied - shows raw values from the database."})]});default:return null}};return e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:300,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(t.TooltipContent,{side:"right",align:"start",className:"p-3",children:a()})]})})}const Io={groupBy:zt,pivotBy:cs,metrics:Da,detailColumns:t.Table2,sortBy:t.ArrowUpDown};function wt({zone:s,fields:a,label:n,placeholder:r,shouldShow:c,hasPivotColumns:i=!1,activeField:l=null}){const{isOver:d,setNodeRef:o}=t.useDroppable({id:s}),{updateSortByColumn:u}=t.useEditorActions(),p=t.useEditorStore(w=>w.card),h=t.useEditorStore(w=>w.card.type),x=a.length>0,m=y.useMemo(()=>!l||!d?!0:t.validateFieldForChartType(l,s,h).isValid,[l,d,s,h]),g=(w,T)=>{var N;!((N=p.config)!=null&&N.sortByColumns)||p.config.sortByColumns.findIndex(A=>A.id===w)===-1||u(p.id,w,{direction:T})};if(s==="sortBy"&&c===!1)return null;const b=s!=="sortBy"&&h!=="kpi",j=Io[s]||t.Plus;return e.jsxs("div",{className:"mb-3 w-full",children:[e.jsx("div",{className:"mb-1.5 flex items-center gap-2",children:e.jsx(t.Label,{className:t.cn("block text-sm font-medium text-foreground",{}),children:n})}),e.jsx("div",{ref:o,className:t.cn("rounded-lg border p-0.5 transition-colors duration-150",{"border-green-500 bg-green-50 shadow-[0_0_0_1px_rgba(34,197,94,0.18)] dark:bg-green-950":d&&m,"border-red-500 bg-red-50 shadow-[0_0_0_1px_rgba(239,68,68,0.18)] dark:bg-red-950":d&&!m,"border-solid border-border/55 bg-background":!d&&x,"min-h-[56px] border-dashed border-border/60 bg-background":!d&&!x}),children:a.length===0?e.jsxs("div",{className:"flex min-h-[56px] items-center justify-center gap-2 text-sm text-muted-foreground/85",children:[e.jsx(j,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground/80"}),e.jsx("span",{children:r}),b&&e.jsx(Eo,{concept:s})]}):e.jsx(t.SortableContext,{id:s,items:a.map(w=>w.id),strategy:t.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1.5",children:a.map((w,T)=>{const N=w.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(To,{field:w,zone:s,index:T,sortDirection:N,onSortDirectionChange:A=>g(w.id,A),hasPivotColumns:i,cardType:h})})},w.id)})})})})]})}function Do({groupByFields:s,pivotByFields:a,metricsFields:n,sortByFields:r,detailFields:c,activeField:i}){var _,U,H;const[l,d]=y.useState(!1),o=t.useEditorStore($=>{var Z;return!!((Z=$.card.customCardPreferences)!=null&&Z.url)}),u=t.useEditorStore($=>$.card),p=t.useEditorStore($=>$.frame),h=t.findCustomVisualConfigCard(p,u),{manifest:x}=t.useCustomVisual(((_=h==null?void 0:h.customCardPreferences)==null?void 0:_.url)||""),m=(U=x==null?void 0:x.visuals)==null?void 0:U.find($=>{var Z;return $.name===((Z=h==null?void 0:h.customCardPreferences)==null?void 0:Z.componentName)}),g=t.resolveMultiInputType(h,m)==="multiple",b=g&&!!((H=h==null?void 0:h.customCardPreferences)!=null&&H.url),j=t.getConfigSlotExpectedType(m==null?void 0:m.slots);t.useEditorStore($=>$.actions.updateCardConfig);const w=t.useEditorStore($=>$.actions.updateCard),T=t.useEditorStore($=>$.actions.updateFrame),P=t.useDashboardStore($=>$.isVisualEditing),N=t.useDashboardStore($=>$.selectedSheetId),A=t.useDashboardStore($=>$.actions.updateSheetCalculatedFields),{scopedFields:S}=t.useScopedFields(),{userContext:I}=t.useCurrentUserInfo(),D=g&&(h==null?void 0:h.id)===u.id&&j?j:u==null?void 0:u.type,M=D==="detailTable",v=s.length>0||n.length>0||c.length>0,R=!M&&(D!=="kpi"||n.length<=2),C=!M,k=!M&&D!=="kpi",F=D!=="kpi"&&v,f=M,L="Drop sort fields here",E=(I==null?void 0:I.type)==="organization",O=["pie","doughnut","polar","funnel","aggregateTable","bubble","scatter"].includes(D),B=k&&!O,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(t.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full space-y-2.5",children:[e.jsxs(t.AccordionItem,{value:"fields",className:"rounded-xl border border-border/55 border-b-0 bg-card px-3 shadow-[0_1px_2px_rgba(15,23,42,0.04)]",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2.5 text-xs font-semibold tracking-wide text-foreground/70 hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.List,{className:"h-4 w-4 text-foreground/60"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-3 pt-1.5",children:[R&&e.jsx(wt,{zone:"groupBy",fields:s,label:V().label,placeholder:V().placeholder,activeField:i}),B&&e.jsx(wt,{zone:"pivotBy",fields:a,label:"Pivot Columns",placeholder:"Drop pivot fields here",activeField:i}),C&&e.jsx(wt,{zone:"metrics",fields:n,label:z().label,placeholder:z().placeholder,hasPivotColumns:a.length>0,activeField:i}),f&&e.jsx(wt,{zone:"detailColumns",fields:c,label:"Columns",placeholder:"Drop columns here"}),n.length>=1&&E&&e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:()=>d(!0),className:"mt-1.5 w-full justify-start border-border/60 border-dashed bg-background text-xs text-foreground/70 hover:bg-muted/40 hover:text-foreground",children:[e.jsx(t.Calculator,{className:"mr-2 h-4 w-4"}),"Create Metric"]}),F&&e.jsx(wt,{zone:"sortBy",fields:r,label:"Sort By",placeholder:L,activeField:i})]})]}),(!o||b)&&e.jsxs(t.AccordionItem,{value:"configuration",className:"rounded-xl border border-border/55 border-b-0 bg-card px-3 shadow-[0_1px_2px_rgba(15,23,42,0.04)]",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2.5 text-xs font-semibold tracking-wide text-foreground/70 hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Settings2,{className:"h-4 w-4 text-foreground/60"}),e.jsx("span",{children:"CHART SETTINGS"})]})}),e.jsx(t.AccordionContent,{className:"mb-2 rounded-md bg-muted/20 px-3 py-0.5",children:e.jsx(t.Accordion,{type:"single",collapsible:!0,className:"w-full",children:e.jsx(Un,{mode:"config"})})})]}),(o||b)&&e.jsxs(t.AccordionItem,{value:"plugin",className:"rounded-xl border border-border/55 border-b-0 bg-card px-3 shadow-[0_1px_2px_rgba(15,23,42,0.04)]",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2.5 text-xs font-semibold tracking-wide text-foreground/70 outline-none ring-0 hover:no-underline focus:outline-none focus-visible:outline-none focus-visible:ring-0 focus-visible:ring-offset-0",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dn,{className:"h-4 w-4 text-foreground/60"}),e.jsx("span",{children:"COMPONENT SETTINGS"})]})}),e.jsx(t.AccordionContent,{className:"mb-2 rounded-md bg-muted/20 px-3 py-0.5",children:e.jsx(qn,{})})]})]}),e.jsx(t.CalculatedFieldEditor,{open:l,onOpenChange:d,availableFields:S,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:$=>{if($.role!=="metric")return;const{nextStoredFields:Z}=t.saveCalculatedFieldToCardScope({activeFields:n,storedFields:u.calculatedFields||[],sharedFields:p.calculatedFields||[],updatedField:$,previousScope:"card"});w(u.id,{calculatedFields:Z})},onSaveToDashboard:$=>{if($.role!=="metric")return;const Z=p.calculatedFields||[],{nextSharedFields:re}=t.saveCalculatedFieldToSharedScope({activeFields:n,storedFields:u.calculatedFields||[],sharedFields:Z,updatedField:$,previousScope:"dashboard"});t.commitSharedCalculatedFields({nextSharedFields:re,currentSharedFields:Z,isVisualEditing:P,selectedSheetId:N,updateFrame:T,updateSheetCalculatedFields:A})},cardId:u.id})]})}function ko({onEditJoins:s}){const a=t.useEditorStore(d=>d.card),{autoJoinMetadata:n}=t.useEditorCardQuery(a);if(!(n!=null&&n.autoResolved))return null;const{resolvedJoinPlan:r}=n,c=(r==null?void 0:r.joins)||[];if(c.length===0)return null;const i=d=>!d||d.length===0?"No conditions":d.map(o=>{var x,m,g,b;const u=`${(x=o.source)==null?void 0:x.entityName}.${(m=o.source)==null?void 0:m.name}`,p=`${(g=o.target)==null?void 0:g.entityName}.${(b=o.target)==null?void 0:b.name}`,h=o.operator||"=";return`${u} ${h} ${p}`}).join(" AND "),l=d=>!d.joinKeyGroups||d.joinKeyGroups.length===0?"No conditions defined":d.joinKeyGroups.length===1?i(d.joinKeyGroups[0].keys):d.joinKeyGroups.map((o,u)=>({id:u,operator:o.operator,condition:i(o.keys)}));return e.jsx(t.Card,{className:"border-blue-500/20 bg-blue-50/15 shadow-sm dark:bg-blue-950/10",children:e.jsxs("div",{className:"flex items-center justify-between p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fa,{className:"size-4 text-blue-600/90 dark:text-blue-400"}),e.jsx("h3",{className:"text-xs font-semibold tracking-wide text-blue-900/90 dark:text-blue-100",children:"Resolved Joins"}),e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.Badge,{variant:"secondary",className:"cursor-help bg-blue-100/80 text-xs text-blue-700 dark:bg-blue-900/70 dark:text-blue-300",children:c.length})}),e.jsx(t.TooltipContent,{side:"bottom",align:"start",className:"max-w-md p-3",children:e.jsx("div",{className:"space-y-2",children:c.map((d,o)=>{const u=l(d),p=Array.isArray(u);return e.jsxs("div",{className:"rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"font-medium text-foreground",children:d.source.name}),e.jsx(t.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:d.target.name})]}),e.jsx(t.Badge,{variant:"outline",className:"border-green-500/40 bg-green-50/30 text-xs text-green-700 dark:bg-green-950/30 dark:text-green-300",children:d.joinType})]}),e.jsx("div",{className:"mt-1 space-y-1",children:p?u.map(h=>e.jsxs("div",{className:"rounded bg-muted/30 px-2 py-1",children:[e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:h.condition}),h.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",h.operator,")"]})]},h.id)):e.jsx("div",{className:"rounded bg-muted/30 px-2 py-1",children:e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:u})})})]},d.id||o)})})})]})})]}),s&&e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:s,className:"h-7 gap-1 p-2 text-xs text-blue-700/80 hover:text-blue-900 dark:text-blue-300 dark:hover:text-blue-100",children:e.jsx(t.SquarePen,{className:"size-3.5"})})]})})}const En={getItem(s){if(typeof window>"u")return null;try{return localStorage.getItem(s)}catch(a){return console.warn(`Failed to read from localStorage (${s}):`,a),null}},setItem(s,a){if(!(typeof window>"u"))try{localStorage.setItem(s,a)}catch(n){console.warn(`Failed to write to localStorage (${s}):`,n)}}};function Ao({selectedChart:s,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:c,sortByFields:i,detailFields:l,activeField:d}){var R,C;const[o,u]=y.useState(()=>En.getItem("chart-selector-expanded")==="true"),[p,h]=y.useState(!1),x=t.useEditorStore(k=>k.card),m=t.useEditorStore(k=>k.editorContext),g=t.useEditorStore(k=>k.actions.updateCardConfig),b=(m==null?void 0:m.type)==="documentSection",j=n.length>0||r.length>0||c.length>0||l.length>0,{data:w,autoJoinMetadata:T}=t.useEditorCardQuery(x),P=j||!!w,N=((R=x==null?void 0:x.config)==null?void 0:R.joinPlan)||(T!=null&&T.autoResolved?T.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),A=((C=x==null?void 0:x.dataSource)==null?void 0:C.selectedEntities)||[],S=k=>{g(x.id,{...x==null?void 0:x.config,joinPlan:k}),h(!1)},I=()=>{g(x.id,{...x==null?void 0:x.config,joinPlan:void 0}),h(!1)},D=()=>{h(!1)},M=()=>{h(!0)};y.useEffect(()=>{En.setItem("chart-selector-expanded",String(o))},[o]);const v=()=>{u(k=>!k)};return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col bg-background",children:[e.jsx("div",{className:"pl-2 pr-4 pt-4",children:!b&&e.jsxs("div",{className:"rounded-xl border border-border/60 bg-card p-3 shadow-[0_1px_2px_rgba(15,23,42,0.05)]",children:[e.jsx("div",{className:t.cn("overflow-hidden transition-all duration-300 ease-in-out",o?"max-h-[210px] opacity-100":"max-h-0 opacity-0"),children:o&&e.jsx(us,{selectedChart:s,onChartChange:a,variant:"outline"})}),e.jsx("div",{"data-content":"Chart Quick Selector",className:t.cn("flex items-center justify-center",{"mt-3":o,"mt-2":!o}),children:e.jsx(t.ChartQuickSelector,{selectedChart:s,onChartChange:a,isDropdownExpanded:o,onToggleDropdown:v})})]})}),P&&e.jsx("div",{className:"pl-2 pr-4 py-3",children:e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(ke.EditorClearButton,{label:"Reset",variant:"secondary",className:"h-7 px-2 text-xs"})})}),e.jsx(t.ScrollArea,{className:"min-h-0 w-full flex-1 basis-0",children:e.jsxs("div",{className:t.cn("space-y-3 pl-2 pr-4 pb-6",P?"pt-1":"pt-4"),children:[e.jsx(ko,{onEditJoins:M}),e.jsx(Do,{groupByFields:n,pivotByFields:r,metricsFields:c,sortByFields:i,detailFields:l,activeField:d})]})}),e.jsx(Ln,{open:p,onOpenChange:h,joinPlan:N,availableDataSources:A,onSave:S,onCancel:D,onRemove:I,children:e.jsx("div",{})})]})}function Mo({initialFilters:s,availableFields:a}={}){const[n,r]=y.useState(s||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});t.useEditorStore(N=>N.card.dataSource);const{filterableFields:c,isLoading:i}=t.useFilterableFields(),l=a||c||[],d={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},o=N=>{const A=S=>{if(S.id===N){const I=l[0]||d,D=t.getDataType(I.dataType)==="date";return{...S,conditions:[...S.conditions,{id:`condition-${Date.now()}`,field:I,operator:D?"between":"=",value:D?[]:""}]}}return{...S,groups:S.groups.map(A)}};r(A(n))},u=N=>{const A=S=>{if(S.id===N){const I=l[0]||d,D=t.getDataType(I.dataType)==="date";return{...S,groups:[...S.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:I,operator:D?"between":"=",value:D?[]:""}],groups:[]}]}}return{...S,groups:S.groups.map(A)}};r(A(n))},p=(N,A)=>{const S=I=>I.id===N?{...I,conditions:I.conditions.filter(D=>D.id!==A)}:{...I,groups:I.groups.map(S)};r(S(n))},h=(N,A)=>{const S=I=>I.id===N?{...I,groups:I.groups.filter(D=>D.id!==A)}:{...I,groups:I.groups.map(S)};r(S(n))},x=(N,A,S,I)=>{if(S==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const D=M=>M.id===N?{...M,conditions:M.conditions.map(v=>v.id===A?{...v,[S]:I}:v)}:{...M,groups:M.groups.map(D)};r(D(n))},m=(N,A,S)=>{const I=D=>D.id===N?{...D,conditions:D.conditions.map(M=>M.id===A?{...M,...S}:M)}:{...D,groups:D.groups.map(I)};r(I(n))},g=(N,A)=>{const S=I=>I.id===N?{...I,logicalOperator:A}:{...I,groups:I.groups.map(S)};r(S(n))},b=(N,A)=>{const S=I=>I.id===N?{...I,negate:A}:{...I,groups:I.groups.map(S)};r(S(n))},j=(N,A,S)=>{const I=D=>D.id===N?{...D,conditions:t.arrayMove(D.conditions,A,S)}:{...D,groups:D.groups.map(I)};r(I(n))},w=(N,A,S)=>{const I=D=>D.id===N?{...D,groups:t.arrayMove(D.groups,A,S)}:{...D,groups:D.groups.map(I)};r(I(n))},T=N=>{if(!N||N.conditions.length===0&&N.groups.length===0)return"-- No filters defined";const A=I=>{let D="";typeof I.field=="object"?D=I.field.entityName?`${I.field.entityName}.${I.field.name}`:I.field.name:D=String(I.field);const M=I.operator;let v=I.value;if(I.field.dataType==="string"&&!["in","not in"].includes(I.operator))typeof v=="string"?v=`'${v}'`:Array.isArray(v)&&(v=`'${v.join(", ")}'`);else if(I.field.dataType==="date"||I.field.dataType==="datetime"||I.field.dataType==="timestamp")if(I.operator==="between"&&Array.isArray(v)&&v.length===2){const R=v[0]?`'${v[0]}'`:"NULL",C=v[1]?`'${v[1]}'`:"NULL";return`${D} BETWEEN ${R} AND ${C}`}else if((I.operator==="in"||I.operator==="not in")&&Array.isArray(v)){const R=v.map(C=>C?`'${C}'`:"NULL").join(", ");return`${D} ${M} (${R})`}else typeof v=="string"||v instanceof Date?v=`'${v}'`:Array.isArray(v)&&v.length>0&&(v=`'${v[0]}'`);else if(["in","not in"].includes(I.operator)){let R=[];Array.isArray(v)?R=v.map(C=>typeof C=="string"?`'${C}'`:String(C)):typeof v=="string"?R=v.split(",").map(C=>{const k=C.trim();return I.field.dataType==="string"?`'${k}'`:k}):typeof v=="number"&&(R=[String(v)]),v=`(${R.join(", ")})`}switch(M){case"contains":return typeof v=="string"?`${D} LIKE '%${v.replace(/'/g,"")}'`:`${D} LIKE '%${String(v)}'`;case"startsWith":return typeof v=="string"?`${D} LIKE '${v.replace(/'/g,"")}%'`:`${D} LIKE '${String(v)}%'`;case"endsWith":return typeof v=="string"?`${D} LIKE '%${v.replace(/'/g,"")}'`:`${D} LIKE '%${String(v)}'`;case"isNull":return`${D} IS NULL`;case"isNotNull":return`${D} IS NOT NULL`;default:return`${D} ${M} ${v}`}},S=I=>{const D=I.conditions.map(A),M=I.groups.map(k=>S(k)),v=[...D,...M].filter(Boolean);if(v.length===0)return"";const R=v.join(` ${I.logicalOperator} `),C=v.length>1?`(${R})`:R;return I.negate?`NOT ${C}`:C};return S(N)},P=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:l,isLoading:i,addCondition:o,addGroup:u,removeCondition:p,removeGroup:h,updateCondition:x,updateConditionFields:m,updateGroupOperator:g,updateGroupNegate:b,reorderConditions:j,reorderGroups:w,generateSQLPreview:T,hasAnyFilters:P}}function Lo({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 Fo=s=>{if(s.qualifiedEntityName){const a=s.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function Ro({value:s,onValueChange:a,availableFields:n,placeholder:r="Select field",className:c="w-64"}){const[i,l]=y.useState(!1),d=y.useMemo(()=>{const o={};return n.forEach(u=>{const p=Fo(u);o[p]||(o[p]={}),o[p][u.entityId]||(o[p][u.entityId]=[]),o[p][u.entityId].push(u)}),o},[n]);return e.jsxs(t.Popover,{modal:!0,open:i,onOpenChange:l,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:t.cn("justify-between",!s&&"text-muted-foreground",c),children:[s?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Lo,{children:[s.entityName,".",s.name]})}):r,e.jsx(t.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(t.CommandEmpty,{children:"No fields found."}),e.jsx(t.CommandList,{className:"max-h-80",children:Object.entries(d).map(([o,u])=>e.jsx(t.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Database,{className:"h-3 w-3"}),o]}),children:Object.entries(u).map(([p,h])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[t.getEntityIcon(h[0].entityType,{size:"h-3 w-3"}),e.jsx("span",{children:h[0].entityName})]}),h.map((x,m)=>e.jsxs(t.CommandItem,{value:x.id,onSelect:()=>{a(x),l(!1)},className:"overflow-x-auto",children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",(s==null?void 0:s.id)===x.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:x.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:x.description&&e.jsx("span",{children:x.description})})]})]},x.id+m))]},`${o}-${p}`))},o))})]})})]})}function fs(s){var b;const a=t.useEditorStore(j=>j.card),{authToken:n,tokenProps:r}=t.useSemaphorContext(),c=t.useEditorStore(j=>j.card.config),i=c==null?void 0:c.joinPlan,l={...s,alias:s.name,label:"value",role:"groupby"},d={...s,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},o={...l,role:"sortby",direction:"asc"},u={joinPlan:i,groupByColumns:[l],metricColumns:[d],sortByColumns:[o]},p=((b=a.dataSource)==null?void 0:b.connectionId)||a.connectionId,{data:h,isPending:x,error:m}=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:p,cardConfig:u,cardDataSource:a.dataSource})}catch(j){console.log(s),console.error("error",j)}},enabled:!!p,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((h==null?void 0:h.records)||[]).map(j=>({label:j.value||"BLANK",value:j.value||"BLANK",count:(j==null?void 0:j.count)||0})),isPending:x,error:m}}function Oo({field:s,selected:a,onChange:n,placeholder:r="Select items...",className:c}){const[i,l]=Pt.useState(!1),{filterValues:d}=fs(s),o=p=>{n(a.filter(h=>h!==p))},u=p=>{a.includes(p)?n(a.filter(h=>h!==p)):n([...a,p])};return e.jsx("div",{className:t.cn("w-full",c),children:e.jsxs(t.Popover,{open:i,onOpenChange:l,modal:!0,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(p=>{const h=d.find(x=>x.value===p);return e.jsxs(t.Badge,{variant:"secondary",className:"text-xs",children:[h==null?void 0:h.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:x=>{x.key==="Enter"&&o(p)},onMouseDown:x=>{x.preventDefault(),x.stopPropagation()},onClick:x=>{x.stopPropagation(),o(p)},children:e.jsx(t.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},p)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(t.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No results found."}),e.jsx(t.CommandGroup,{children:d.map((p,h)=>e.jsxs(t.CommandItem,{onSelect:()=>u(p.value),children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",a.includes(p.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:p.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:p.count})]})]},p.value+h))})]})]})})]})})}function Po({field:s,value:a,onChange:n,placeholder:r="Select value...",className:c}){const{filterValues:i,isPending:l,error:d}=fs(s);return l?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(t.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):d?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(t.Select,{value:a,onValueChange:n,children:[e.jsx(t.SelectTrigger,{className:c||"flex-1",children:e.jsx(t.SelectValue,{placeholder:r,children:a})}),e.jsx(t.SelectContent,{children:i.map((o,u)=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:o.value,children:o.label},o.value+u))})]})}function Bo({value:s,operator:a,onChange:n,className:r}){var m,g,b;const{tokenProps:c}=t.useSemaphorContext(),i=((g=(m=c==null?void 0:c.params)==null?void 0:m.calendarContext)==null?void 0:g.tz)||((b=c==null?void 0:c.params)==null?void 0:b.timezone),l=i||Intl.DateTimeFormat().resolvedOptions().timeZone,d=a==="between"||a==="not between",o=y.useMemo(()=>{if(!(!s||!d)&&Array.isArray(s)&&s.length===2){const j=s[0]?new Date(s[0]):void 0,w=s[1]?new Date(s[1]):void 0;if(j&&w)return{from:j,to:w}}},[s,d]),u=y.useMemo(()=>{if(!s||d)return;const j=Array.isArray(s)?s[0]:s;if(!j)return;const w=new Date(j);if(!isNaN(w.getTime()))return w},[s,d]),p=j=>a==="<="||a===">"?t.endOfDayInTimezone(j,l):t.startOfDayInTimezone(j,l),h=j=>{if(!j){n([]);return}if(j.from&&j.to){n([j.from.toISOString(),j.to.toISOString()]);return}n([])},x=j=>{if(!j){n("");return}const w=p(j);n(w.toISOString())};return e.jsx(t.DateRangePicker,{value:d?o:void 0,selectionMode:d?"range":"single",singleValue:d?void 0:u,onChange:h,onSingleChange:x,timezone:i,showRelativeTab:d,className:r,placeholder:"Select date..."})}const Vo=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],zo=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],_o=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],qo=["=","!=","isNull","isNotNull"],$o=["between","=","!=","<","<=",">",">=","isNull","isNotNull"],Ko={"=":"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 In(s){return Ko[s]||t.titleCase(s)}function Go(s){switch(s){case"string":return zo;case"number":return _o;case"boolean":return qo;case"date":return $o;default:return Vo}}function Qn({condition:s,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:c,onRemoveCondition:i,onUpdateGroupOperator:l,availableFields:d,updateConditionFields:o}){const{attributes:u,listeners:p,setNodeRef:h,transform:x,transition:m,isDragging:g}=t.useSortable({id:s.id}),{isPending:b,error:j}=fs(s.field),w={transform:t.CSS.Transform.toString(x),transition:m};return e.jsxs("div",{ref:h,style:w,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${g?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...p,className:"cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(t.Select,{value:r,onValueChange:T=>l(n,T),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(Ro,{value:s.field,onValueChange:T=>{const P=T,N=t.getDataType(P.dataType)==="date";o(n,s.id,{field:P,value:"",operator:N?"between":"="})},availableFields:d,placeholder:"Select field",className:"w-64"}),e.jsxs(t.Select,{value:s.operator,onValueChange:T=>{T==="in"||T==="not in"?o(n,s.id,{operator:T,value:[]}):T==="isNull"||T==="isNotNull"?o(n,s.id,{operator:T,value:null}):T==="between"||T==="not between"?o(n,s.id,{operator:T,value:[]}):o(n,s.id,{operator:T,value:""})},children:[e.jsx(t.SelectTrigger,{className:"w-32",children:e.jsx(t.SelectValue,{children:s.operator?In(s.operator):""})}),e.jsx(t.SelectContent,{children:Go(t.getDataType(s.field.dataType)).map(T=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:T,children:In(T)},T))})]}),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"?b?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(t.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):j?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(Oo,{field:s.field,selected:Array.isArray(s.value)&&s.value.every(T=>typeof T=="string")?s.value:[],onChange:T=>o(n,s.id,{value:T}),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:T=>o(n,s.id,{value:T.target.value}),className:"flex-1",placeholder:s.operator.charAt(0).toUpperCase()+s.operator.slice(1)+"..."}):e.jsx(Po,{field:s.field,value:typeof s.value=="string"?s.value:"",onChange:T=>o(n,s.id,{value:T}),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:T=>o(n,s.id,{value:T==="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(Bo,{value:s.value,operator:s.operator,onChange:T=>o(n,s.id,{value:T}),className:"flex-1"}):e.jsx(t.Input,{value:typeof s.value=="string"||typeof s.value=="number"?s.value:"",onChange:T=>c(n,s.id,"value",T.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 Uo({group:s,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:c,onRemoveGroup:i,onUpdateCondition:l,onUpdateField:d,onRemoveCondition:o,onReorderConditions:u,onReorderGroups:p,onAddCondition:h,onAddGroup:x,availableFields:m,renderFilterGroup:g,updateConditionFields:b}){const{attributes:j,listeners:w,setNodeRef:T,transform:P,transition:N,isDragging:A}=t.useSortable({id:s.id}),S={transform:t.CSS.Transform.toString(P),transition:N},I=M=>{const{active:v,over:R}=M;if(R&&v.id!==R.id){const C=s.conditions.findIndex(F=>F.id===v.id),k=s.conditions.findIndex(F=>F.id===R.id);C!==-1&&k!==-1&&u(s.id,C,k)}},D=M=>{const{active:v,over:R}=M;if(R&&v.id!==R.id&&n){const C=s.groups.findIndex(F=>F.id===v.id),k=s.groups.findIndex(F=>F.id===R.id);C!==-1&&k!==-1&&p(n,C,k)}};return e.jsxs("div",{ref:T,style:S,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${A?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...j,...w,className:"cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(t.Button,{variant:s.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>c(s.id,!s.negate),children:"NOT"}),e.jsxs(t.Select,{value:s.logicalOperator,onValueChange:M=>r(s.id,M),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:I,children:e.jsx(t.SortableContext,{items:s.conditions.map(M=>M.id),strategy:t.verticalListSortingStrategy,children:s.conditions.map((M,v)=>e.jsx(Qn,{condition:M,index:v,groupId:s.id,groupLogicalOperator:s.logicalOperator,onUpdateCondition:l,onUpdateField:d,onRemoveCondition:o,onUpdateGroupOperator:r,availableFields:m,updateConditionFields:b},M.id))})}),e.jsx(t.DndContext,{sensors:t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),collisionDetection:t.closestCenter,onDragEnd:D,children:e.jsx(t.SortableContext,{items:s.groups.map(M=>M.id),strategy:t.verticalListSortingStrategy,children:s.groups.map(M=>g(M,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:()=>h(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>x(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Ho({filters:s,availableFields:a,onSave:n,onClearAll:r,onCancel:c}){const{currentFilters:i,availableFields:l,isLoading:d,addCondition:o,addGroup:u,removeCondition:p,removeGroup:h,updateCondition:x,updateConditionFields:m,updateGroupOperator:g,updateGroupNegate:b,reorderConditions:j,reorderGroups:w,generateSQLPreview:T,hasAnyFilters:P,setCurrentFilters:N}=Mo({initialFilters:s,availableFields:a}),A=t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),[S,I]=y.useState(!1),D=(R,C,k)=>{const F=f=>f.id===R?{...f,conditions:f.conditions.map(L=>L.id===C?{...L,field:k,dataType:k.dataType}:L)}:{...f,groups:f.groups.map(F)};N(F(i))},M=(R,C=0,k)=>C===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(t.DndContext,{sensors:A,collisionDetection:t.closestCenter,onDragEnd:F=>{const{active:f,over:L}=F;if(L&&f.id!==L.id){const E=R.conditions.findIndex(B=>B.id===f.id),O=R.conditions.findIndex(B=>B.id===L.id);E!==-1&&O!==-1&&j(R.id,E,O)}},children:e.jsx(t.SortableContext,{items:R.conditions.map(F=>F.id),strategy:t.verticalListSortingStrategy,children:R.conditions.map((F,f)=>e.jsx(Qn,{condition:F,index:f,groupId:R.id,groupLogicalOperator:R.logicalOperator,onUpdateCondition:x,onUpdateField:D,onRemoveCondition:p,onUpdateGroupOperator:g,availableFields:l,updateConditionFields:m},F.id))})}),e.jsx(t.DndContext,{sensors:A,collisionDetection:t.closestCenter,onDragEnd:F=>{const{active:f,over:L}=F;if(L&&f.id!==L.id){const E=R.groups.findIndex(B=>B.id===f.id),O=R.groups.findIndex(B=>B.id===L.id);E!==-1&&O!==-1&&w(R.id,E,O)}},children:e.jsx(t.SortableContext,{items:R.groups.map(F=>F.id),strategy:t.verticalListSortingStrategy,children:R.groups.map(F=>M(F,C+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"]}),S&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(R.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},R.id):e.jsx(Uo,{group:R,depth:C,parentGroupId:k,onUpdateGroupOperator:g,onUpdateGroupNegate:b,onRemoveGroup:h,onUpdateCondition:x,onUpdateField:D,onRemoveCondition:p,onReorderConditions:j,onReorderGroups:w,onAddCondition:o,onAddGroup:u,availableFields:l,renderFilterGroup:M,updateConditionFields:m},R.id),v=t.getFilterCount(s);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(t.Card,{children:e.jsx(t.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[d?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):M(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:S,onCheckedChange:R=>I(R)}),e.jsx(t.Label,{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),P&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:T(i)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(t.Button,{size:"sm",variant:"outline",onClick:c,children:"Cancel"}),v>0&&e.jsx(t.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(t.Button,{size:"sm",onClick:()=>n(P?i:null),children:"Apply Filters"})]})]})}function Qo({cardId:s,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:c,isOpen:i,onOpenChange:l}){const d=u=>{n(s,u),l(!1)},o=()=>{r(s),l(!1)};return e.jsxs(t.Dialog,{modal:!1,open:i,onOpenChange:l,children:[i&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(t.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:u=>{u.preventDefault()},children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Card Filters"}),e.jsx(t.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(Ho,{filters:a,availableFields:c,onSave:d,onCancel:()=>l(!1),onClearAll:o})]})]})}function Jo({activeCardId:s,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var T,P;const[c,i]=y.useState(null),l=t.useEditorStore(N=>N.card),d=t.useEditorStore(N=>N.actions.updateCardConfig),o=t.useEditorStore(N=>N.actions.setCardPreferences),u=(T=l==null?void 0:l.config)==null?void 0:T.joinPlan,p=y.useCallback(N=>N.entityName===t.CALCULATED_FIELD_ENTITY_MARKER||N.entityName==="calculated_fields"||N.qualifiedEntityName==="calculated_fields",[]),h=(P=l==null?void 0:l.dataSource)==null?void 0:P.semanticDomainId,{data:x}=t.useJoinabilityMap(h),m=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy"),...n("detailColumns")],g=y.useCallback(N=>N.startsWith("card-source-")?"source":N.startsWith("card-")?null:N.startsWith("source-")||a.find(A=>A.id===N)?"source":n("groupBy").find(A=>A.id===N)?"groupBy":n("metrics").find(A=>A.id===N)?"metrics":n("pivotBy").find(A=>A.id===N)?"pivotBy":n("sortBy").find(A=>A.id===N)?"sortBy":n("detailColumns").find(A=>A.id===N)?"detailColumns":null,[a,n]),b=y.useCallback(N=>{i(N.active.id)},[]),j=y.useCallback(N=>{var R;const{active:A,over:S}=N;if(!S||!s){i(null);return}const I=A.id,D=S.id,M=g(I),v=g(D)||D;if(v==="sortBy"){if(M==="source"){const C=a.find(F=>F.id===I);if(!C){i(null);return}if(!(n("groupBy").some(F=>F.name===C.name&&F.qualifiedEntityName===C.qualifiedEntityName)||n("metrics").some(F=>F.name===C.name&&F.qualifiedEntityName===C.qualifiedEntityName)||n("detailColumns").some(F=>F.name===C.name&&F.qualifiedEntityName===C.qualifiedEntityName))){i(null);return}}else if(M==="pivotBy"){i(null);return}else if(M!=="groupBy"&&M!=="metrics"&&M!=="sortBy"&&M!=="detailColumns"){i(null);return}}if(M==="source"&&v==="sortBy"){const C=[...a].find(L=>L.id===I);if(!C){i(null);return}const k=n("sortBy");if(t.fieldAlreadyExists(C,k)){i(null);return}const F=t.validateFieldForChartType(C,"sortBy",l.type);if(!F.isValid){t.ue.error("Invalid Field Type",{description:F.reason,position:"top-center",duration:3e3}),i(null);return}const f=t.getNewField(C,"sortBy",k);i(null),r("sortBy",[...k,f]);return}if(M==="source"&&v!=="source"&&v!=="sortBy"){const C=[...a].find(B=>B.id===I);if(!C){i(null);return}const k=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy"),...n("detailColumns")],F=k.filter(B=>!p(B));if(F.length>0){const B=F[0].qualifiedEntityName;if(!B){i(null);return}if(B!==C.qualifiedEntityName&&!p(C)&&C.qualifiedEntityName)if(h&&(x!=null&&x.joinabilityMap)){if(t.calculateFieldState(C,{joinabilityMap:x.joinabilityMap,selectedFields:k,baseEntityName:(R=u==null?void 0:u.baseEntity)==null?void 0:R.name}).state==="unreachable"){t.showJoinRequiredNotification(),i(null);return}}else{if(!u){t.showJoinRequiredNotification(),i(null);return}if(!t.areEntitiesJoined(B,C.qualifiedEntityName,u)){t.showJoinRequiredNotification(),i(null);return}}}const f=n(v);if(t.fieldAlreadyExists(C,f)){i(null);return}const L=t.validateFieldForChartType(C,v,l.type);if(!L.isValid){t.ue.error("Invalid Field Type",{description:L.reason,position:"top-center",duration:3e3}),i(null);return}const E=t.getNewField(C,v,f),O=[...f,E];if(i(null),r(v,O),v==="metrics"&&s){const B=t.seedSemanticMetricFormatDefaults(l,E,l.preferences);B&&o(B),t.cleanupKpiMetricComparisonMode(l.type,l.config,d,s,O)}return}if(M&&v&&M!=="source"&&v!=="source"&&M!==v){const C=n(M),k=n(v),F=C.find(B=>B.id===I);if(!F){i(null);return}const f=t.validateFieldForChartType(F,v,l.type);if(!f.isValid){t.ue.error("Invalid Field Type",{description:f.reason,position:"top-center",duration:3e3}),i(null);return}const L=t.getNewField(F,v,k);if(i(null),v==="sortBy"){t.fieldAlreadyExists(F,k)||r(v,[...k,L]);return}const E=C.filter(B=>B.id!==I),O=[...k,L];if(r(M,E),r(v,O),v==="metrics"&&s){const B=t.seedSemanticMetricFormatDefaults(l,L,l.preferences);B&&o(B),t.cleanupKpiMetricComparisonMode(l.type,l.config,d,s,O)}return}if(M&&v&&M===v&&M!=="source"){const C=n(M),k=C.findIndex(f=>f.id===I),F=C.findIndex(f=>f.id===D);if(k!==F){const f=t.arrayMove(C,k,F);r(M,f)}}i(null)},[s,a,n,r,g,u,h,x,p,l,d,o]),w=c?m.find(N=>N.id===c):null;return{activeId:c,activeField:w,handleDragStart:b,handleDragEnd:j}}function Yo({activeView:s,onViewChange:a,splitViewEnabled:n}){const r=t.useEditorStore(d=>d.card),{config:c}=y.useContext(t.SemaphorContext).tokenProps,i=(c==null?void 0:c.showInfoTab)!==!1,l=()=>n?!1:t.getVisualizationMode(r)==="dynamic"?!0:!["table","pivotTable","aggregateTable","detailTable"].includes(r.type);return e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(t.Tabs,{value:s,onValueChange:d=>a(d),children:e.jsxs(t.TabsList,{className:"h-9 w-fit gap-1 bg-background p-0",children:[e.jsx(t.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),l()&&e.jsx(t.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),r.type!=="kpi"&&i&&e.jsx(t.TabsTrigger,{value:"info",className:"rounded-md transition data-[state=active]:bg-muted",children:"Info"})]})})})}const Wo=[{value:"10",label:"Top 10"},{value:"20",label:"Top 20"},{value:"50",label:"Top 50"},{value:"100",label:"Top 100"},{value:"200",label:"Top 200"},{value:"500",label:"Top 500"},{value:"1000",label:"Top 1000"}];function Xo(){var o,u;const s=t.useEditorStore(p=>p.card),{updateRowLimit:a}=t.useEditorActions(),[n,r]=y.useState(!1),[c,i]=y.useState(""),l=p=>{if(p==="custom"){r(!0);return}r(!1),a(s.id,parseInt(p))},d=p=>{const h=p.target.value;i(h),h&&!isNaN(parseInt(h))&&a(s.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(t.Input,{type:"number",value:c,onChange:d,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(t.Select,{value:((u=(o=s.config)==null?void 0:o.rowLimit)==null?void 0:u.toString())||"100",onValueChange:l,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(t.SelectValue,{placeholder:"Select limit"})}),e.jsx(t.SelectContent,{children:Wo.map(p=>e.jsx(t.SelectItem,{value:p.value,children:p.label},p.value))})]})})}function Zo({card:s,queryData:a,isLoading:n,isFetching:r,pagination:c,onPaginationChange:i,onSortChange:l,sortState:d,splitViewEnabled:o,isDynamicInspectorOpen:u,onDynamicInspectorOpenChange:p}){const h=y.useMemo(()=>(a==null?void 0:a.records)||[],[a==null?void 0:a.records]),x=t.getVisualizationMode(s)==="dynamic",m=e.jsx(ot,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(zn,{fallbackPreview:e.jsx(ot,{}),records:h,title:s.title,isInspectorOpen:u,onInspectorOpenChange:p})});return x?o?e.jsxs(t.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(t.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:m}),e.jsx(t.ResizableHandle,{withHandle:!0}),e.jsx(t.ResizablePanel,{defaultSize:40,minSize:20,role:"results-section",className:"flex flex-col",children:e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 py-4 pl-2 pr-4",children:[(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:h,paginationMetadata:c,onPaginationChange:i,isLoading:n||r,onSortChange:l,sortState:d})]})})]}):m:!o||["table","pivotTable","aggregateTable","detailTable"].includes(s.type)?e.jsx(ot,{}):e.jsxs(t.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(t.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:e.jsx(ot,{})}),e.jsx(t.ResizableHandle,{withHandle:!0}),e.jsx(t.ResizablePanel,{defaultSize:40,minSize:20,role:"results-section",className:"flex flex-col",children:e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 py-4 pl-2 pr-4",children:[(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:h,paginationMetadata:c,onPaginationChange:i,isLoading:n||r,onSortChange:l,sortState:d})]})})]})}const ei="semaphor-split-view-enabled";function ti(){return Fn(ei,!0)}function si({activeView:s,onViewChange:a,onFiltersClick:n,activeCard:r,columns:c}){var ye,X,ge;const i=t.useEditorStore(ee=>ee.card),l=t.useEditorStore(ee=>ee.editorContext),d=t.useEditorStore(ee=>ee.inlineFilterValuesMap[(r==null?void 0:r.id)||""]),o=t.useEditorStore(ee=>ee.actions.removeCardInlineFilterValue),u=t.useDashboardStore(ee=>ee.filterValues),p=t.useDashboardStore(ee=>ee.selectedSheetId),{updateCardConfig:h,setCard:x,updateCardInFrame:m,setShowAIDialog:g}=t.useEditorActions(),b=t.useEditorStore(ee=>ee.showAIDialog),j=t.useEditorStore(ee=>ee.isDevMode),w=t.useDashboardStore(ee=>ee.isVisualEditing),[T,P]=y.useState(!1),[N,A]=y.useState(!1),[S,I]=y.useState(!1),[D,M]=y.useState(null),{config:v}=y.useContext(t.SemaphorContext).tokenProps,R=(v==null?void 0:v.showInfoTab)!==!1,C=(v==null?void 0:v.showQueryDebugTools)!==!1,[k,F]=ti();t.useEditorStore(ee=>{var Te;return!!((Te=ee.card.customCardPreferences)!=null&&Te.url)});const L=t.getVisualizationMode(i)==="dynamic",E=(l==null?void 0:l.type)==="documentSection",{data:O,errorMessage:B,isLoading:V,isFetching:z,errorSql:_,pagination:U,refetch:H,comparisonMetadata:$,queryRequestPayload:Z,resolvedPrimaryDateField:re}=t.useEditorCardQuery(r),ie=y.useMemo(()=>(O==null?void 0:O.records)||[],[O==null?void 0:O.records]),[ce,he]=y.useState(!1);y.useEffect(()=>{z||he(!1)},[z]);const me=()=>{const ee=!k;ee&&s==="table"&&a("chart"),F(ee)},se=(ee,Te)=>{const Le={...r,paginationConfig:{page:ee+1,pageSize:Te}};x(Le),m(Le)},be=ee=>{if(!i.config)return;const Te=t.sortStateToSortByColumns(ee,i.config.metricColumns,i.config.groupByColumns,i.config.detailColumns);h(i.id,{...i.config,sortByColumns:Te})},je=y.useMemo(()=>{var ee;return t.sortByColumnsToSortState((ee=i.config)==null?void 0:ee.sortByColumns)},[(ye=i.config)==null?void 0:ye.sortByColumns]);return e.jsx("div",{className:t.cn("relative flex w-0 grow flex-col",{"border-l":b&&w}),children:e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-3",children:[e.jsxs("div",{className:"flex items-center gap-2 pl-2 pr-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s==="chart"&&b&&!E&&!L&&e.jsx("div",{className:"w-[200px]",children:e.jsx(us,{variant:j?"secondary":"ghost"})}),e.jsx(Yo,{activeView:s,onViewChange:a,splitViewEnabled:k}),e.jsx(t.FilterInfo,{cardId:r.id,cardFilters:(X=r.config)==null?void 0:X.filters,cardFilterCount:t.getFilterCount(((ge=r.config)==null?void 0:ge.filters)||null),onFiltersClick:n,inlineFilters:r.inlineFilters,inlineFilterValues:d,sheetId:p||"",removeInlineFilterValue:ee=>o(r.id,ee),resolvedPrimaryDateField:re}),$&&i.type!=="table"&&e.jsx(t.ComparisonMetadataBadge,{metadata:$,variant:"compact"}),e.jsx("div",{className:"ml-2",children:e.jsx(Xo,{})}),b&&e.jsx(ke.EditorClearButton,{})]}),e.jsxs("div",{className:t.cn("flex grow items-center justify-end gap-2"),children:[e.jsx(t.IconButton,{tooltip:"Refresh",disabled:V||z,onClick:()=>{he(!0),H()},children:e.jsx(t.RefreshCcw,{className:t.cn("h-4 w-4",{"animate-spin":ce})})}),s==="chart"&&!L&&e.jsx(Vn,{showInlineFilters:!1,showDisplayOptions:!1}),s==="chart"&&e.jsxs(t.DropdownMenu,{modal:!1,children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"More Options",className:"h-8","aria-label":"More options",children:e.jsx(t.EllipsisVertical,{className:"size-4"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(t.DropdownMenuLabel,{children:"More Options"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{onClick:me,children:[k?e.jsx(ja,{className:"mr-2 h-4 w-4"}):e.jsx(Ma,{className:"mr-2 h-4 w-4"}),k?"Hide Results Table":"Show Results Table"]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs("div",{className:"px-1 py-1",children:[e.jsx(xs,{triggerVariant:"menu",className:"w-full"}),e.jsx(ms,{triggerVariant:"menu",className:"w-full"})]}),e.jsx(_n,{onCustomize:()=>I(!0)})]})]})]})]}),e.jsxs("div",{className:"mt-2 flex min-h-0 grow flex-col",children:[s==="chart"&&e.jsx("div",{className:t.cn("flex grow flex-col pb-4",{"pb-0":k&&!["table","pivotTable","aggregateTable","detailTable"].includes(r.type)}),children:e.jsx(Zo,{card:r,queryData:O,isLoading:V,isFetching:z,pagination:U,onPaginationChange:se,onSortChange:be,sortState:je,splitViewEnabled:k,isDynamicInspectorOpen:S,onDynamicInspectorOpenChange:I})}),s==="table"&&(O==null?void 0:O.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 py-4 pl-2 pr-4",children:[(V||z)&&(O==null?void 0:O.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),e.jsx(t.TableVisual,{card:r,data:ie,comparisonMetadata:$,paginationMetadata:U,onPaginationChange:se,isLoading:V||z,onSortChange:be,sortState:je})]}),s==="info"&&R&&e.jsx("div",{className:"flex min-h-0 flex-1 flex-col pb-4",children:e.jsx("div",{className:"flex min-h-0 flex-1 flex-col rounded-md bg-background pl-2 pr-4",children:B?e.jsx(ds,{error:B,errorSql:_,onSendFeedback:()=>{const ee=t.prepareFeedbackData(t.FeedbackCategory.QUERY_GENERATION,{cardConfig:i.config,dataSource:r.dataSource,dashboardFilters:u,errorMessage:B,errorSql:_,generatedSql:O==null?void 0:O.sql});M(ee),A(!0)},onOpenInEditor:()=>{g(!0),setTimeout(()=>{const ee=t.useEditorStore.getState().actions;ee.setIsDevMode(!0),ee.setCardSql(_||""),setTimeout(()=>{ee.setRunSql(!0)},100)},100)}}):(O==null?void 0:O.sql)&&e.jsx(On,{sql:O.sql,showCardDetails:!0,debugPayloads:C?{queryRequest:Z,queryResponse:O,columns:c,dashboardFilters:u}:void 0})})})]}),D&&e.jsx(t.FeedbackDialog,{open:N,onOpenChange:A,feedbackData:D})]})})}function ni({activeField:s}){const[a,n]=y.useState(!0);return y.useEffect(()=>{s&&n(!0)},[s]),s?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${a?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(t.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(t.IconForFieldType,{dataType:s.dataType}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-sm dark:text-muted-foreground",children:s.label||s.name})]}):null}const ai=()=>{const s=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||s.apply(console,r)};const a=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},n=r=>{var c;if((c=r.reason)!=null&&c.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=s,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function ri({column:s,isSelected:a,onSelect:n,availableFields:r,width:c,onWidthChange:i}){var B,V,z;const l=t.useEditorStore(_=>_.card),{updateCardConfig:d,removeGroupByColumn:o,removeMetricColumn:u,updateFilters:p}=t.useEditorActions(),[h,x]=y.useState(!1),[m,g]=y.useState(!1),b=y.useRef(null),j=y.useCallback(_=>{_.preventDefault(),_.stopPropagation(),g(!0),b.current={startX:_.clientX,startWidth:c||150};const U=$=>{if(!b.current)return;const Z=$.clientX-b.current.startX,re=Math.max(80,b.current.startWidth+Z);i==null||i(s.id,re)},H=()=>{g(!1),b.current=null,document.removeEventListener("mousemove",U),document.removeEventListener("mouseup",H)};document.addEventListener("mousemove",U),document.addEventListener("mouseup",H)},[c,s.id,i]),w=(B=l==null?void 0:l.config)==null?void 0:B.filters,T=(V=w==null?void 0:w.conditions)==null?void 0:V.some(_=>_.field.name===s.name&&_.field.qualifiedEntityName===s.qualifiedEntityName),P=_=>{_?p(l.id,_):d(l.id,{filters:void 0})},{attributes:N,listeners:A,setNodeRef:S,transform:I,transition:D,isDragging:M}=t.useSortable({id:s.id}),v={transform:t.CSS.Transform.toString(I),transition:D},R=t.getDataType(s.dataType),C=li(R),k=()=>{var H;const _=((H=l==null?void 0:l.config)==null?void 0:H.sortByColumns)||[],U=_.findIndex($=>$.name===s.name);if(U!==-1){const $=[..._];$[U]={...$[U],direction:"asc"},d(l.id,{sortByColumns:$})}else d(l.id,{sortByColumns:[..._,{...s,id:`sort-${s.id}`,role:"sortby",direction:"asc"}]})},F=()=>{var H;const _=((H=l==null?void 0:l.config)==null?void 0:H.sortByColumns)||[],U=_.findIndex($=>$.name===s.name);if(U!==-1){const $=[..._];$[U]={...$[U],direction:"desc"},d(l.id,{sortByColumns:$})}else d(l.id,{sortByColumns:[..._,{...s,id:`sort-${s.id}`,role:"sortby",direction:"desc"}]})},f=()=>{var H;const _=((H=l==null?void 0:l.config)==null?void 0:H.groupByColumns)||[];if(!_.some($=>$.name===s.name)){const $={...s,id:`groupby-${s.id}-${Date.now()}`,role:"groupby"};d(l.id,{groupByColumns:[..._,$]})}},L=_=>{var $;const U=(($=l==null?void 0:l.config)==null?void 0:$.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:_};d(l.id,{metricColumns:[...U,Z]})}},E=()=>{s.role==="groupby"?o(l.id,s.id):s.role==="metric"&&u(l.id,s.id)},O={...v,width:c?`${c}px`:void 0,minWidth:c?`${c}px`:"120px"};return e.jsxs("th",{ref:S,style:O,className:t.cn("group relative border-r border-border bg-background px-1 py-0",M&&"opacity-50",a&&"bg-primary/10",m&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...N,...A,className:"cursor-grab p-1 text-muted-foreground opacity-0 transition-opacity hover:text-foreground group-hover:opacity-100 active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-3 w-3"})}),e.jsxs(t.DropdownMenu,{children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsxs("button",{onClick:n,className:t.cn("flex flex-1 items-center justify-between gap-1 rounded px-2 py-2 text-left text-sm font-medium transition-colors hover:bg-muted/50",a&&"bg-primary/10"),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(C,{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,")"]}),T&&e.jsx(t.Filter,{className:"h-3 w-3 text-primary"})]}),e.jsx(t.ChevronDown,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsxs(t.DropdownMenuContent,{align:"start",className:"w-48",children:[e.jsxs(t.DropdownMenuItem,{onClick:()=>x(!0),children:[e.jsx(t.Filter,{className:t.cn("mr-2 h-4 w-4",T&&"text-primary")}),T?"Edit Filter":"Filter"]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{onClick:k,children:[e.jsx(pa,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(t.DropdownMenuItem,{onClick:F,children:[e.jsx(ha,{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:f,children:[e.jsx(zt,{className:"mr-2 h-4 w-4"}),"Group by this column"]}),e.jsxs(t.DropdownMenuItem,{disabled:!0,children:[e.jsx(cs,{className:"mr-2 h-4 w-4"}),"Pivot by this column"]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{disabled:!0,children:[e.jsx(t.EyeOff,{className:"mr-2 h-4 w-4"}),"Hide column"]}),e.jsxs(t.DropdownMenuItem,{onClick:E,className:"text-destructive focus:text-destructive",children:[e.jsx(t.Trash2,{className:"mr-2 h-4 w-4"}),"Remove column"]})]})]})]}),e.jsx("div",{onMouseDown:j,className:t.cn("absolute right-0 top-0 h-full w-1 cursor-col-resize bg-transparent hover:bg-primary/50",m&&"bg-primary")}),e.jsx(Hn,{open:h,onOpenChange:x,availableFields:r.length>0?r:[s],existingFilters:w,editingCondition:T?(z=w==null?void 0:w.conditions)==null?void 0:z.find(_=>_.field.name===s.name&&_.field.qualifiedEntityName===s.qualifiedEntityName):void 0,onSave:P})]})}function li(s){switch(s){case"number":return t.Hash;case"date":return t.Calendar;case"string":default:return t.Type}}function oi({selectedColumn:s,onColumnSelect:a,isLoading:n=!1,sourceFields:r=[],filterableFields:c=r}){var M,v,R,C;const i=t.useEditorStore(k=>k.card),{updateCardConfig:l}=t.useEditorActions(),[d,o]=y.useState(null),[u,p]=y.useState({}),[h,x]=y.useState(!1),m=y.useMemo(()=>{var f,L;const k=((f=i==null?void 0:i.config)==null?void 0:f.groupByColumns)||[],F=((L=i==null?void 0:i.config)==null?void 0:L.metricColumns)||[];return[...k,...F]},[(M=i==null?void 0:i.config)==null?void 0:M.groupByColumns,(v=i==null?void 0:i.config)==null?void 0:v.metricColumns]),g=y.useMemo(()=>{const k=new Set(m.map(F=>`${F.qualifiedEntityName}.${F.name}`));return r.filter(F=>!k.has(`${F.qualifiedEntityName}.${F.name}`))},[r,m]),{data:b,isLoading:j}=t.useEditorCardQuery(i),w=(b==null?void 0:b.records)||[],T=y.useCallback((k,F)=>{p(f=>({...f,[k]:F}))},[]),P=y.useCallback(k=>{var E,O;const F=t.getDataType(k.dataType),f=((E=i==null?void 0:i.config)==null?void 0:E.groupByColumns)||[],L=((O=i==null?void 0:i.config)==null?void 0:O.metricColumns)||[];if(F==="number"){const B={...k,id:`metric-${k.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};l(i.id,{metricColumns:[...L,B]})}else{const B={...k,id:`groupby-${k.id}-${Date.now()}`,role:"groupby"};l(i.id,{groupByColumns:[...f,B]})}x(!1)},[(R=i==null?void 0:i.config)==null?void 0:R.groupByColumns,(C=i==null?void 0:i.config)==null?void 0:C.metricColumns,i.id,l]),N=t.useSensors(t.useSensor(t.PointerSensor,{activationConstraint:{distance:8}})),A=k=>{o(k.active.id)},S=k=>{const{active:F,over:f}=k;if(o(null),!f||F.id===f.id)return;const L=m.findIndex(O=>O.id===F.id),E=m.findIndex(O=>O.id===f.id);if(L!==-1&&E!==-1){const O=t.arrayMove(m,L,E),B=O.filter(z=>z.role==="groupby"),V=O.filter(z=>z.role==="metric");l(i.id,{groupByColumns:B,metricColumns:V})}},I=d?m.find(k=>k.id===d):null,D=k=>{let F="";for(;k>=0;)F=String.fromCharCode(k%26+65)+F,k=Math.floor(k/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"})}):m.length===0?e.jsx("div",{className:"flex h-full flex-col items-center justify-center gap-4 p-8 text-center",children:e.jsxs("div",{className:"rounded-lg border-2 border-dashed border-muted-foreground/25 p-12",children:[e.jsx("h3",{className:"text-lg font-medium text-muted-foreground",children:"No columns selected"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground/75",children:"Select columns from the panel on the right to build your table"})]})}):e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsxs(t.DndContext,{sensors:N,collisionDetection:t.closestCenter,onDragStart:A,onDragEnd:S,children:[e.jsxs("table",{className:"w-full border-collapse",children:[e.jsxs("thead",{children:[e.jsxs("tr",{className:"border-b border-border bg-muted/30",children:[e.jsx("th",{className:"sticky left-0 z-20 w-12 border-r border-border bg-muted/50 px-2 py-1 text-center text-xs font-medium text-muted-foreground"}),e.jsx(t.SortableContext,{items:m.map(k=>k.id),strategy:t.horizontalListSortingStrategy,children:m.map((k,F)=>e.jsx("th",{style:{width:u[k.id]?`${u[k.id]}px`:void 0,minWidth:u[k.id]?`${u[k.id]}px`:"120px"},className:"border-r border-border bg-muted/30 px-2 py-1 text-center text-xs font-medium text-muted-foreground",children:D(F)},`letter-${k.id}`))}),e.jsx("th",{className:"w-10 border-r border-border bg-muted/30 px-2 py-1"})]}),e.jsxs("tr",{className:"border-b-2 border-border bg-background",children:[e.jsx("th",{className:"sticky left-0 z-20 w-12 border-r border-border bg-muted/50 px-2 py-2 text-center text-xs font-medium text-muted-foreground",children:"#"}),e.jsx(t.SortableContext,{items:m.map(k=>k.id),strategy:t.horizontalListSortingStrategy,children:m.map(k=>e.jsx(ri,{column:k,isSelected:(s==null?void 0:s.id)===k.id,onSelect:()=>a(k),availableFields:c,width:u[k.id],onWidthChange:T},k.id))}),e.jsx("th",{className:"w-10 border-r border-border bg-background px-1 py-2",children:e.jsxs(t.Popover,{open:h,onOpenChange:x,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Add column",children:e.jsx(t.Plus,{className:"h-4 w-4"})})}),e.jsx(t.PopoverContent,{className:"w-[280px] p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search columns..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No columns available."}),e.jsx(t.CommandGroup,{heading:"Available Columns",children:g.map(k=>{const F=t.getDataType(k.dataType),f=F==="number"?t.Hash:F==="date"?t.Calendar:t.Type;return e.jsxs(t.CommandItem,{value:k.label||k.name,onSelect:()=>P(k),children:[e.jsx(f,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm",children:k.label||k.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:k.entityName})]})]},k.id)})})]})]})})]})})]})]}),e.jsx("tbody",{children:j?e.jsx("tr",{children:e.jsx("td",{colSpan:m.length+2,className:"h-32 text-center",children:e.jsx(t.LoaderCircle,{className:"mx-auto h-6 w-6 animate-spin text-muted-foreground"})})}):w.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:m.length+2,className:"h-32 text-center text-muted-foreground",children:"No data available"})}):w.slice(0,100).map((k,F)=>e.jsxs("tr",{className:t.cn("border-b border-border transition-colors hover:bg-muted/50",F%2===0?"bg-background":"bg-muted/20"),children:[e.jsx("td",{className:"sticky left-0 z-10 w-12 border-r border-border bg-muted/50 px-2 py-2 text-center text-xs font-medium text-muted-foreground",children:F+1}),m.map(f=>{const L=k[f.name]??k[f.label??""];return e.jsx("td",{style:{width:u[f.id]?`${u[f.id]}px`:void 0,minWidth:u[f.id]?`${u[f.id]}px`:"120px"},className:t.cn("border-r border-border px-3 py-2 text-sm",(s==null?void 0:s.id)===f.id&&"bg-primary/5"),children:e.jsx("span",{className:"block truncate",children:ii(L,f)})},`${F}-${f.id}`)}),e.jsx("td",{className:"w-10 border-r border-border"})]},F))})]}),e.jsx(t.DragOverlay,{children:I&&e.jsx("div",{className:"rounded border border-primary bg-background px-3 py-2 text-sm font-medium shadow-lg",children:I.label||I.name})})]})}),e.jsxs("div",{className:"flex items-center justify-between border-t border-border bg-muted/30 px-4 py-2 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Showing ",Math.min(w.length,100)," of ",w.length," rows"]}),e.jsxs("span",{children:[m.length," columns"]})]})]})}function ii(s,a){if(s==null)return"—";if(typeof s=="number")return a.role==="metric"?new Intl.NumberFormat("en-US",{minimumFractionDigits:0,maximumFractionDigits:2}).format(s):s.toString();if(s instanceof Date||typeof s=="string"&&!isNaN(Date.parse(s))){const n=new Date(s);if(!isNaN(n.getTime()))return n.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}return String(s)}function ci({entityGroups:s,isLoading:a=!1}){var P,N;const n=t.useEditorStore(A=>A.card),{updateCardConfig:r,removeGroupByColumn:c,removeMetricColumn:i}=t.useEditorActions(),[l,d]=y.useState(!0),[o,u]=y.useState(""),[p,h]=y.useState(new Set),x=((P=n==null?void 0:n.config)==null?void 0:P.groupByColumns)||[],m=((N=n==null?void 0:n.config)==null?void 0:N.metricColumns)||[],g=A=>{const S=new Set(p);S.has(A)?S.delete(A):S.add(A),h(S)},b=A=>x.some(S=>S.name===A.name&&S.qualifiedEntityName===A.qualifiedEntityName)||m.some(S=>S.name===A.name&&S.qualifiedEntityName===A.qualifiedEntityName),j=(A,S)=>{if(S)if(t.getDataType(A.dataType)==="number"){const D={...A,id:`metric-${A.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};r(n.id,{metricColumns:[...m,D]})}else{const D={...A,id:`groupby-${A.id}-${Date.now()}`,role:"groupby"};r(n.id,{groupByColumns:[...x,D]})}else{const I=x.findIndex(M=>M.name===A.name&&M.qualifiedEntityName===A.qualifiedEntityName),D=m.findIndex(M=>M.name===A.name&&M.qualifiedEntityName===A.qualifiedEntityName);I!==-1&&c(n.id,x[I].id),D!==-1&&i(n.id,m[D].id)}},w=A=>{if(!o)return A;const S=o.toLowerCase();return A.filter(I=>I.name.toLowerCase().includes(S)||I.label&&I.label.toLowerCase().includes(S))},T=A=>{switch(t.getDataType(A)){case"number":return t.Hash;case"date":return t.Calendar;default:return t.Type}};return l?e.jsxs("div",{className:"flex h-full w-72 flex-col border-l border-border bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border px-3 py-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Columns"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:()=>d(!1),title:"Close panel",children:e.jsx(wa,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"border-b border-border p-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(t.Search,{className:"absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),e.jsx(t.Input,{placeholder:"Search columns...",value:o,onChange:A=>u(A.target.value),className:"h-8 pl-8 text-sm"})]})}),(x.length>0||m.length>0)&&e.jsxs("div",{className:"border-b border-border",children:[x.length>0&&e.jsxs(t.Collapsible,{defaultOpen:!0,children:[e.jsxs(t.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(t.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(zt,{className:"h-3.5 w-3.5 text-blue-500"}),e.jsx("span",{children:"Groupings"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:x.length})]}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:x.map(A=>{const S=T(A.dataType);return e.jsxs("div",{className:"group flex items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted/50",children:[e.jsx(t.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(S,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:A.label||A.name}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>c(n.id,A.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]},A.id)})})})]}),m.length>0&&e.jsxs(t.Collapsible,{defaultOpen:!0,children:[e.jsxs(t.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(t.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(t.Calculator,{className:"h-3.5 w-3.5 text-green-500"}),e.jsx("span",{children:"Metrics"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:m.length})]}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:m.map(A=>{const S=T(A.dataType);return e.jsxs("div",{className:"group flex items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted/50",children:[e.jsx(t.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(S,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:A.label||A.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:A.aggregate}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>i(n.id,A.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]},A.id)})})})]})]}),e.jsx(t.ScrollArea,{className:"flex-1",children:e.jsx("div",{className:"p-2",children:a?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent"})}):s.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No columns available"}):s.map(A=>{const S=w(A.columns);if(S.length===0)return null;const I=p.has(A.entityId)||o.length>0;return e.jsxs(t.Collapsible,{open:I,onOpenChange:()=>g(A.entityId),children:[e.jsxs(t.CollapsibleTrigger,{className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm font-medium hover:bg-muted/50",children:[e.jsx(t.ChevronRight,{className:t.cn("h-3.5 w-3.5 transition-transform duration-200",I&&"rotate-90")}),e.jsx(t.Table2,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate text-left",children:A.label||A.entityName}),e.jsx("span",{className:"text-xs text-muted-foreground",children:S.length})]}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:S.map(D=>{const M=T(D.dataType),v=b(D);return e.jsxs("label",{className:t.cn("flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-sm transition-colors hover:bg-muted/50",v&&"bg-primary/5"),children:[e.jsx(t.Checkbox,{checked:v,onCheckedChange:R=>j(D,R),className:"h-3.5 w-3.5"}),e.jsx(M,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:D.label||D.name})]},D.id)})})})]},A.entityId)})})})]}):e.jsx("div",{className:"flex h-full items-start border-l border-border bg-muted/30 p-2",children:e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>d(!0),title:"Open panel",children:e.jsx(Ta,{className:"h-4 w-4"})})})}const di=[{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 ui({value:s,onChange:a,onSubmit:n,onCancel:r,selectedColumn:c,availableColumns:i}){const[l,d]=y.useState(!1),[o,u]=y.useState("column"),p=y.useRef(null);y.useEffect(()=>{const g=b=>{b.key==="Escape"&&s?r():b.key==="Enter"&&s&&!l&&n(s)};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[s,r,n,l]);const h=g=>{const b=`[${g.label||g.name}]`,j=p.current;if(j){const w=j.selectionStart||0,T=j.selectionEnd||0,P=s.slice(0,w)+b+s.slice(T);a(P),setTimeout(()=>{j.setSelectionRange(w+b.length,w+b.length),j.focus()},0)}else a(s+b);d(!1)},x=g=>{const b=p.current;if(b){const j=b.selectionStart||0,w=b.selectionEnd||0,T=s.slice(0,j)+g.syntax+s.slice(w);a(T),setTimeout(()=>{b.setSelectionRange(j+g.name.length+1,j+g.syntax.length-1),b.focus()},0)}else a(s+g.syntax);d(!1)},m=g=>{switch(t.getDataType(g)){case"number":return t.Hash;case"date":return t.Calendar;default:return t.Type}};return e.jsxs("div",{className:"flex items-center gap-2 border-b border-border bg-muted/30 px-3 py-1.5",children:[e.jsx("div",{className:"flex min-w-[100px] items-center justify-center rounded border border-border bg-background px-2 py-1 text-xs font-medium text-muted-foreground",children:c?e.jsx("span",{className:"truncate",children:c.label||c.name}):e.jsx("span",{children:"—"})}),e.jsxs(t.Popover,{open:l&&o==="function",onOpenChange:g=>{d(g),g&&u("function")},children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Insert function",children:e.jsx(Aa,{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:di.map(g=>e.jsx(t.CommandItem,{value:g.name,onSelect:()=>x(g),children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-sm font-medium",children:g.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:g.description})]}),e.jsx("span",{className:"font-mono text-xs text-muted-foreground/75",children:g.syntax})]})},g.name))})]})]})})]}),e.jsxs(t.Popover,{open:l&&o==="column",onOpenChange:g=>{d(g),g&&u("column")},children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"ghost",size:"sm",className:"h-7 gap-1 px-2 text-xs text-muted-foreground hover:text-foreground",title:"Insert column reference",children:[e.jsx("span",{children:"Columns"}),e.jsx(t.ChevronDown,{className:"h-3 w-3"})]})}),e.jsx(t.PopoverContent,{className:"w-[250px] p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search columns..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No columns found."}),e.jsx(t.CommandGroup,{heading:"Available Columns",children:i.map(g=>{const b=m(g.dataType);return e.jsxs(t.CommandItem,{value:g.label||g.name,onSelect:()=>h(g),children:[e.jsx(b,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:g.label||g.name})]},g.id)})})]})]})})]}),e.jsx("div",{className:"relative flex-1",children:e.jsx(t.Input,{ref:p,value:s,onChange:g=>a(g.target.value),placeholder:"Enter a formula or select a column...",className:"h-7 border-border bg-background font-mono text-sm"})}),s&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-destructive hover:bg-destructive/10 hover:text-destructive",onClick:r,title:"Cancel (Esc)",children:e.jsx(t.X,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-green-600 hover:bg-green-600/10 hover:text-green-600",onClick:()=>n(s),title:"Apply (Enter)",children:e.jsx(t.Check,{className:"h-4 w-4"})})]})]})}function mi({className:s}){var m,g,b,j;const a=t.useEditorStore(w=>w.card),[n,r]=y.useState(null),[c,i]=y.useState(""),{columns:l=[],columnGroups:d=[],isLoading:o}=t.useColumns(),{valuePickFilterableFields:u=[]}=t.useFilterableFields();(m=a==null?void 0:a.config)!=null&&m.groupByColumns,(g=a==null?void 0:a.config)!=null&&g.metricColumns,(b=a==null?void 0:a.config)!=null&&b.groupByColumns,(j=a==null?void 0:a.config)!=null&&j.pivotByColumns;const p=w=>{r(w),i(w?`[${w.label||w.name}]`:"")},h=w=>{console.log("Formula submitted:",w),i(""),r(null)},x=()=>{i(""),r(null)};return e.jsxs("div",{className:t.cn("flex h-full w-full flex-col",s),children:[e.jsx(ui,{value:c,onChange:i,onSubmit:h,onCancel:x,selectedColumn:n,availableColumns:l}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(oi,{selectedColumn:n,onColumnSelect:p,isLoading:o,sourceFields:l,filterableFields:u})}),e.jsx(ci,{entityGroups:d,isLoading:o})]})]})}function xi(){var E,O;const[s,a]=y.useState("chart"),[n,r]=y.useState(!1),[c,i]=y.useState(!0),l=t.useEditorStore(B=>B.showAIDialog),d=t.useDashboardStore(B=>B.isVisualEditing),{setCardType:o}=t.useEditorActions(),u=t.useEditorStore(B=>B.card.type);y.useEffect(()=>ai(),[]);const p=B=>{o(B)},h=t.useEditorStore(B=>B.frame),x=t.useEditorStore(B=>B.card);t.useEditorStore(B=>B.activeTabCardId),t.useEditorStore(B=>B.actions.getAvailableFields);const{addCard:m,removeCard:g,updateCard:b,setActiveCard:j,updateFilters:w}=t.useEditorActions(),{columnFields:T=[],scopedFields:P=[],filterableFields:N=[]}=t.useFilterableFields(),A=t.useSensors(t.useSensor(t.PointerSensor,{activationConstraint:{distance:8}})),S=x,{getFieldsForContainer:I,setFieldsForContainer:D}=t.useFieldManagement(S),{activeField:M,handleDragStart:v,handleDragEnd:R}=Jo({activeCardId:h.activeCardId,sourceFields:P,getFieldsForContainer:I,setFieldsForContainer:D}),C=(B,V)=>{V&&w(B,V)},k=B=>{var V;b(B,{config:{...(V=h.cards.find(z=>z.id===B))==null?void 0:V.config,filters:void 0}})},F=N,f=B=>{if(!B)return 0;let V=B.conditions.length;return B.groups.forEach(z=>{V+=f(z)}),V},L=f(((E=S==null?void 0:S.config)==null?void 0:E.filters)||null);return e.jsxs(t.DndContext,{sensors:A,collisionDetection:t.closestCenter,onDragStart:v,onDragEnd:R,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Rn,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:u==="tableBuilder"?e.jsx(mi,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!l&&e.jsx(Ao,{selectedChart:u,onChartChange:p,groupByFields:I("groupBy"),pivotByFields:I("pivotBy"),metricsFields:I("metrics"),sortByFields:I("sortBy"),detailFields:I("detailColumns"),activeField:M}),e.jsx(si,{selectedChart:u,activeView:s,onViewChange:a,onFiltersClick:()=>r(!0),filterCount:L,activeCard:S,columns:T,getFieldsForContainer:I,cards:h.cards,activeCardId:h.activeCardId,addCard:m,setActiveCard:j})]})}),!c&&d&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(t.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>i(!0),title:"Show Data Source Panel",children:e.jsx(t.Database,{className:"h-4 w-4"})})})]}),S&&e.jsx(Qo,{cardId:S.id,filters:((O=S.config)==null?void 0:O.filters)||null,onFiltersChange:C,onClearFilters:k,availableFields:F,isOpen:n,onOpenChange:r}),e.jsx(t.DragOverlay,{dropAnimation:null,children:e.jsx(ni,{activeField:M||null})})]})}function hi({authToken:s,onSave:a,onClose:n}){const r=y.useRef(null),c=t.useEditorStore(S=>S.showAIDialog),i=t.useEditorStore(S=>S.isDevMode),l=t.useAssistantLayoutStore(S=>S.setFullscreen),d=t.useAssistantLayoutStore(S=>S.setPanelOpen),o=t.useAssistantLayoutStore(S=>S.setContainer),u=t.useAssistantPanel("editor"),p=t.useFullscreenAssistant(),h=t.useAssistantContainer("editor"),x=p==="editor",m=y.useCallback(S=>{o("editor",S)},[o]),{setAuthToken:g}=t.useDashboardActions(),{setShowAIDialog:b,setOnSave:j,setOnClose:w}=t.useEditorActions(),{setActiveAssistantType:T}=t.useAIActions();y.useEffect(()=>{a&&j(a),n&&w(n)},[a,j,n,w]),y.useEffect(()=>{s&&s.accessToken&&g(s)},[s,g]),y.useEffect(()=>{var S,I;c?((S=r.current)==null||S.resize(40),d("editor",!0),T("editor")):((I=r.current)==null||I.resize(0),d("editor",!1),p==="editor"&&l(null),T(null))},[c,d,T,l,p]);function P(S){var I;S<1?(b(!1),d("editor",!1),p==="editor"&&l(null),T(null),(I=r.current)==null||I.resize(0)):(c||(b(!0),T("editor")),u.isOpen||d("editor",!0))}function N(){return e.jsxs(e.Fragment,{children:[e.jsx(Rn,{isVisible:!0,onToggleVisibility:()=>{}}),e.jsxs("div",{className:"relative flex grow",children:[e.jsxs(t.ResizablePanelGroup,{"data-content":"editor-main",className:t.cn("grow transition-opacity",x&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(xo,{})}),e.jsx(t.ResizableHandle,{disabled:!c}),e.jsx(t.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:P,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Tn,{isFullscreen:x,onFullscreenChange:S=>l(S?"editor":null),fullscreenContainer:h})})})]}),e.jsx("div",{ref:m,className:t.cn("absolute inset-0",!x&&"pointer-events-none")})]})]})}function A(){return e.jsxs("div",{className:"relative flex h-full grow",children:[e.jsxs(t.ResizablePanelGroup,{"data-content":"explorer",className:t.cn("flex grow transition-opacity",x&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(xi,{})}),e.jsx(t.ResizableHandle,{disabled:!c}),e.jsx(t.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:P,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Tn,{isFullscreen:x,onFullscreenChange:S=>l(S?"editor":null),fullscreenContainer:h})})})]}),e.jsx("div",{ref:m,className:t.cn("absolute inset-0",!x&&"pointer-events-none")})]})}return e.jsx(t.ErrorBoundary,{FallbackComponent:t.Fallback,children:i?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:N()}):A()})}function pi(){t.useDashboardStore(x=>x.selectedCardId);const s=t.useDashboardStore(x=>x.selectedSheetId),a=t.useDashboardStore(x=>x.dashboard),{setIsVisualEditing:n,setSelectedSheetId:r}=t.useDashboardStore(x=>x.actions),c=t.useEditorStore(x=>x.editorContext),{clearEditorContext:i}=t.useEditorStore(x=>x.actions),l=t.useDashboardStore(x=>x.isVisualEditing),d=t.useDashboardStore(x=>x.actions.updateFrame),o=t.useDashboardStore(x=>x.actions.updateDocumentSectionCard),u=t.useResolveExistingFrameSemanticExecutionPayload();async function p(x){var w,T,P;if((c==null?void 0:c.type)==="documentSection"){const N=t.getDocumentSectionEditorCard(x,c.cardId);if(!N){t.ue.error("No document section card found");return}if(!t.isSupportedDocumentTableCardType(N)){t.ue.error("Document table sections support Table and Pivot Table");return}o(c.sheetId,c.sectionId,N,{calculatedFields:x.calculatedFields}),i(),n(!1);return}const m=s?(w=a==null?void 0:a.sheets)==null?void 0:w.some(N=>{var A;return N.id===s&&((A=N.frames)==null?void 0:A.some(S=>S.id===x.id))}):!1,g=(P=(T=a==null?void 0:a.sheets)==null?void 0:T.find(N=>{var A;return(A=N.frames)==null?void 0:A.some(S=>S.id===x.id)}))==null?void 0:P.id,b=m?s:g||null;if(!b)return;const j=t.findDashboardFrameById(a,x.id);try{const N=await u(x,{previousFrame:j});d(b,x,{semanticExecutionPayload:N}),s!==b&&r(b),n(!1)}catch(N){console.error("Failed to resolve semantic metadata on save:",N),t.ue.error(N instanceof Error?N.message:"Failed to resolve semantic metadata for this visual")}}function h(){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(hi,{onSave:p,onClose:h})})}exports.default=pi;
|