react-semaphor 0.1.375 → 0.1.377
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/analytics-protocol/index.cjs +1 -1
- package/dist/analytics-protocol/index.js +47 -43
- package/dist/brand-studio/index.cjs +4 -9
- package/dist/brand-studio/index.js +98 -108
- package/dist/chunks/{braces-C3-w6xDL.js → braces-C2uBgj3t.js} +1 -1
- package/dist/chunks/{braces-C8QqW4wu.js → braces-CkXyWzRh.js} +1 -1
- package/dist/chunks/{calendar-preferences-dialog-DXgi7q5u.js → calendar-preferences-dialog-C55VOTIy.js} +6 -5
- package/dist/chunks/calendar-preferences-dialog-DAukJOaP.js +1 -0
- package/dist/chunks/catalog-field-grounding-BGW0hnB9.js +1 -0
- package/dist/chunks/catalog-field-grounding-DHXEI7cW.js +199 -0
- package/dist/chunks/{chevrons-up-down-DSvLu4Ye.js → chevrons-up-down-BnzChFLU.js} +1 -1
- package/dist/chunks/{chevrons-up-down-CnCSGY02.js → chevrons-up-down-W0nzHzx0.js} +1 -1
- package/dist/chunks/{dashboard-briefing-launcher-Jwbmrcl_.js → dashboard-briefing-launcher-CUyeiL_T.js} +3141 -2372
- package/dist/chunks/dashboard-briefing-launcher-DMKfG_z3.js +111 -0
- package/dist/chunks/dashboard-controls-B4hxFc3Q.js +2279 -0
- package/dist/chunks/dashboard-controls-D4vI0wvU.js +52 -0
- package/dist/chunks/dashboard-json-DQnm6daE.js +1 -0
- package/dist/chunks/{dashboard-json-Cl1O3uh0.js → dashboard-json-pl1_mFqJ.js} +14 -13
- package/dist/chunks/{edit-dashboard-visual-B_0sbc43.js → edit-dashboard-visual-CF4aSsav.js} +4729 -4645
- package/dist/chunks/edit-dashboard-visual-CjTXY51a.js +178 -0
- package/dist/chunks/{index-BIks0ktd.js → index-B2kPleRS.js} +186 -181
- package/dist/chunks/{index-BSkBy5cH.js → index-Bn866BBY.js} +22824 -22664
- package/dist/chunks/layout-grid-BFmJ7vmH.js +16 -0
- package/dist/chunks/layout-grid-CTOW9oTg.js +6 -0
- package/dist/chunks/{palette-DUGktM-M.js → palette-DrhPeer-.js} +1 -1
- package/dist/chunks/{palette-D-f4-82S.js → palette-OFaniMPn.js} +1 -1
- package/dist/chunks/{save-D3YYinDz.js → save-BxWBiQv1.js} +1 -1
- package/dist/chunks/{save-kkBEBeLg.js → save-Dh6gSC4x.js} +1 -1
- package/dist/chunks/{switch-Dkx2qEOr.js → switch-C-fGjxjY.js} +2002 -1983
- package/dist/chunks/switch-D5xopzFD.js +168 -0
- package/dist/chunks/use-create-flow-overlay-state-Dg2ffpCE.js +21 -0
- package/dist/chunks/use-create-flow-overlay-state-DrKP0jWE.js +1968 -0
- package/dist/chunks/{validation-1V7bWmYw.js → validation-BHFaWDU-.js} +1 -1
- package/dist/chunks/{validation-DlrTIf1N.js → validation-bMedDBOo.js} +1 -1
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +1 -1
- package/dist/dashboard-authoring/index.cjs +1 -1
- package/dist/dashboard-authoring/index.js +1 -1
- package/dist/data-app-builder/index.cjs +18 -13
- package/dist/data-app-builder/index.js +141 -131
- package/dist/data-app-sdk/index.cjs +1 -1
- package/dist/data-app-sdk/index.js +22 -21
- package/dist/data-app-sdk-validation/index.cjs +1 -1
- package/dist/data-app-sdk-validation/index.js +2 -2
- package/dist/index.cjs +1 -1
- package/dist/index.js +151 -151
- package/dist/style.css +1 -1
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +2 -2
- package/dist/types/analytics-protocol.d.ts +84 -0
- package/dist/types/main.d.ts +8 -12
- package/package.json +1 -1
- package/dist/chunks/calendar-preferences-dialog-CsRzDpDs.js +0 -1
- package/dist/chunks/catalog-field-grounding-DoEBOXQd.js +0 -100
- package/dist/chunks/catalog-field-grounding-Du6mKDcF.js +0 -1
- package/dist/chunks/dashboard-briefing-launcher-C-G6vQTL.js +0 -106
- package/dist/chunks/dashboard-controls-DzGGNQxv.js +0 -2269
- package/dist/chunks/dashboard-controls-p7VKzWSb.js +0 -57
- package/dist/chunks/dashboard-json-CvPhMpbM.js +0 -1
- package/dist/chunks/edit-dashboard-visual-CSrdS10O.js +0 -178
- package/dist/chunks/resource-management-panel-IHbUOh2g.js +0 -6
- package/dist/chunks/resource-management-panel-tFjbtgPw.js +0 -1018
- package/dist/chunks/switch-fIkmwzUt.js +0 -168
- package/dist/chunks/use-create-flow-overlay-state-D-yGZTR3.js +0 -1647
- package/dist/chunks/use-create-flow-overlay-state-DbaUD5xc.js +0 -26
- package/dist/chunks/use-visual-utils-B5hwU_av.js +0 -1
- package/dist/chunks/use-visual-utils-Dj82r7DA.js +0 -340
|
@@ -1,178 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),v=require("react"),n=require("./index-BIks0ktd.js");require("./index-BxM99sFL.js");const t=require("./switch-fIkmwzUt.js"),Ne=require("./use-create-flow-overlay-state-DbaUD5xc.js"),bt=require("./use-visual-utils-B5hwU_av.js"),Hn=require("./chevrons-up-down-CnCSGY02.js"),qa=require("react-dom");require("./index-DRlMUglg.js");const $a=require("./palette-DUGktM-M.js"),Ka=require("./common-types-C73-Ud1-.js");function Ua(s){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const r in s)if(r!=="default"){const o=Object.getOwnPropertyDescriptor(s,r);Object.defineProperty(a,r,o.get?o:{enumerable:!0,get:()=>s[r]})}}return a.default=s,Object.freeze(a)}const Ga=Ua(v);/**
|
|
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 Qa=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 Qn=t.createLucideIcon("ArrowUpDown",[["path",{d:"m21 16-4 4-4-4",key:"f6ql7i"}],["path",{d:"M17 20V4",key:"1ejh1v"}],["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}]]);/**
|
|
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 Wn=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"}]]);/**
|
|
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 Is=t.createLucideIcon("Columns3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
|
|
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 Wa=t.createLucideIcon("Component",[["path",{d:"M15.536 11.293a1 1 0 0 0 0 1.414l2.376 2.377a1 1 0 0 0 1.414 0l2.377-2.377a1 1 0 0 0 0-1.414l-2.377-2.377a1 1 0 0 0-1.414 0z",key:"1uwlt4"}],["path",{d:"M2.297 11.293a1 1 0 0 0 0 1.414l2.377 2.377a1 1 0 0 0 1.414 0l2.377-2.377a1 1 0 0 0 0-1.414L6.088 8.916a1 1 0 0 0-1.414 0z",key:"10291m"}],["path",{d:"M8.916 17.912a1 1 0 0 0 0 1.415l2.377 2.376a1 1 0 0 0 1.414 0l2.377-2.376a1 1 0 0 0 0-1.415l-2.377-2.376a1 1 0 0 0-1.414 0z",key:"1tqoq1"}],["path",{d:"M8.916 4.674a1 1 0 0 0 0 1.414l2.377 2.376a1 1 0 0 0 1.414 0l2.377-2.376a1 1 0 0 0 0-1.414l-2.377-2.377a1 1 0 0 0-1.414 0z",key:"1x6lto"}]]);/**
|
|
32
|
-
* @license lucide-react v0.453.0 - ISC
|
|
33
|
-
*
|
|
34
|
-
* This source code is licensed under the ISC license.
|
|
35
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
36
|
-
*/const Yn=t.createLucideIcon("FileCode2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m5 12-3 3 3 3",key:"oke12k"}],["path",{d:"m9 18 3-3-3-3",key:"112psh"}]]);/**
|
|
37
|
-
* @license lucide-react v0.453.0 - ISC
|
|
38
|
-
*
|
|
39
|
-
* This source code is licensed under the ISC license.
|
|
40
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
41
|
-
*/const Ya=t.createLucideIcon("FileJson2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1",key:"fq0c9t"}],["path",{d:"M8 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1",key:"4gibmv"}]]);/**
|
|
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 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"}]]);/**
|
|
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 Xa=t.createLucideIcon("GitCompareArrows",[["circle",{cx:"5",cy:"6",r:"3",key:"1qnov2"}],["path",{d:"M12 6h5a2 2 0 0 1 2 2v7",key:"1yj91y"}],["path",{d:"m15 9-3-3 3-3",key:"1lwv8l"}],["circle",{cx:"19",cy:"18",r:"3",key:"1qljk2"}],["path",{d:"M12 18H7a2 2 0 0 1-2-2V9",key:"16sdep"}],["path",{d:"m9 15 3 3-3 3",key:"1m3kbl"}]]);/**
|
|
52
|
-
* @license lucide-react v0.453.0 - ISC
|
|
53
|
-
*
|
|
54
|
-
* This source code is licensed under the ISC license.
|
|
55
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
56
|
-
*/const Za=t.createLucideIcon("Hammer",[["path",{d:"m15 12-8.373 8.373a1 1 0 1 1-3-3L12 9",key:"eefl8a"}],["path",{d:"m18 15 4-4",key:"16gjal"}],["path",{d:"m21.5 11.5-1.914-1.914A2 2 0 0 1 19 8.172V7l-2.26-2.26a6 6 0 0 0-4.202-1.756L9 2.96l.92.82A6.18 6.18 0 0 1 12 8.4V10l2 2h1.172a2 2 0 0 1 1.414.586L18.5 14.5",key:"b7pghm"}]]);/**
|
|
57
|
-
* @license lucide-react v0.453.0 - ISC
|
|
58
|
-
*
|
|
59
|
-
* This source code is licensed under the ISC license.
|
|
60
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
61
|
-
*/const er=t.createLucideIcon("LayoutList",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}],["path",{d:"M14 4h7",key:"3xa0d5"}],["path",{d:"M14 9h7",key:"1icrd9"}],["path",{d:"M14 15h7",key:"1mj8o2"}],["path",{d:"M14 20h7",key:"11slyb"}]]);/**
|
|
62
|
-
* @license lucide-react v0.453.0 - ISC
|
|
63
|
-
*
|
|
64
|
-
* This source code is licensed under the ISC license.
|
|
65
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
66
|
-
*/const tr=t.createLucideIcon("ListEnd",[["path",{d:"M16 12H3",key:"1a2rj7"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M10 18H3",key:"13769t"}],["path",{d:"M21 6v10a2 2 0 0 1-2 2h-5",key:"ilrcs8"}],["path",{d:"m16 16-2 2 2 2",key:"kkc6pm"}]]);/**
|
|
67
|
-
* @license lucide-react v0.453.0 - ISC
|
|
68
|
-
*
|
|
69
|
-
* This source code is licensed under the ISC license.
|
|
70
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
71
|
-
*/const En=t.createLucideIcon("ListFilter",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M7 12h10",key:"b7w52i"}],["path",{d:"M10 18h4",key:"1ulq68"}]]);/**
|
|
72
|
-
* @license lucide-react v0.453.0 - ISC
|
|
73
|
-
*
|
|
74
|
-
* This source code is licensed under the ISC license.
|
|
75
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
76
|
-
*/const sr=t.createLucideIcon("ListStart",[["path",{d:"M16 12H3",key:"1a2rj7"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"M10 6H3",key:"lf8lx7"}],["path",{d:"M21 18V8a2 2 0 0 0-2-2h-5",key:"1hghli"}],["path",{d:"m16 8-2-2 2-2",key:"160uvd"}]]);/**
|
|
77
|
-
* @license lucide-react v0.453.0 - ISC
|
|
78
|
-
*
|
|
79
|
-
* This source code is licensed under the ISC license.
|
|
80
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
81
|
-
*/const nr=t.createLucideIcon("ListX",[["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"m19 10-4 4",key:"1tz659"}],["path",{d:"m15 10 4 4",key:"1n7nei"}]]);/**
|
|
82
|
-
* @license lucide-react v0.453.0 - ISC
|
|
83
|
-
*
|
|
84
|
-
* This source code is licensed under the ISC license.
|
|
85
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
86
|
-
*/const is=t.createLucideIcon("MoveHorizontal",[["path",{d:"m18 8 4 4-4 4",key:"1ak13k"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}]]);/**
|
|
87
|
-
* @license lucide-react v0.453.0 - ISC
|
|
88
|
-
*
|
|
89
|
-
* This source code is licensed under the ISC license.
|
|
90
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
91
|
-
*/const cs=t.createLucideIcon("MoveVertical",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m8 18 4 4 4-4",key:"bh5tu3"}],["path",{d:"m8 6 4-4 4 4",key:"ybng9g"}]]);/**
|
|
92
|
-
* @license lucide-react v0.453.0 - ISC
|
|
93
|
-
*
|
|
94
|
-
* This source code is licensed under the ISC license.
|
|
95
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
96
|
-
*/const ar=t.createLucideIcon("Paintbrush",[["path",{d:"m14.622 17.897-10.68-2.913",key:"vj2p1u"}],["path",{d:"M18.376 2.622a1 1 0 1 1 3.002 3.002L17.36 9.643a.5.5 0 0 0 0 .707l.944.944a2.41 2.41 0 0 1 0 3.408l-.944.944a.5.5 0 0 1-.707 0L8.354 7.348a.5.5 0 0 1 0-.707l.944-.944a2.41 2.41 0 0 1 3.408 0l.944.944a.5.5 0 0 0 .707 0z",key:"18tc5c"}],["path",{d:"M9 8c-1.804 2.71-3.97 3.46-6.583 3.948a.507.507 0 0 0-.302.819l7.32 8.883a1 1 0 0 0 1.185.204C12.735 20.405 16 16.792 16 15",key:"ytzfxy"}]]);/**
|
|
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 rr=t.createLucideIcon("PanelRightClose",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m8 9 3 3-3 3",key:"12hl5m"}]]);/**
|
|
102
|
-
* @license lucide-react v0.453.0 - ISC
|
|
103
|
-
*
|
|
104
|
-
* This source code is licensed under the ISC license.
|
|
105
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
106
|
-
*/const or=t.createLucideIcon("PanelRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
|
|
107
|
-
* @license lucide-react v0.453.0 - ISC
|
|
108
|
-
*
|
|
109
|
-
* This source code is licensed under the ISC license.
|
|
110
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
111
|
-
*/const Jn=t.createLucideIcon("RefreshCcw",[["path",{d:"M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"14sxne"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16",key:"1hlbsb"}],["path",{d:"M16 16h5v5",key:"ccwih5"}]]);/**
|
|
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 lr=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"}]]);/**
|
|
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 ir=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"}]]);/**
|
|
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 cr=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"}]]);/**
|
|
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 dr=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"}]]);/**
|
|
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 ur=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"}]]);/**
|
|
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 mr=t.createLucideIcon("Tag",[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]]);/**
|
|
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 xr=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"}]]);function hr({open:s,onOpenChange:a}){const[r,o]=v.useState([]),{updateDataSource:u}=t.useEditorActions(),{selectedEntities:i}=n.useAssistantContextEntities("dashboard");v.useEffect(()=>{s&&o([])},[s]);const l=m=>{o(f=>f.some(b=>n.areContextEntitiesEqual(b,m))?f.filter(b=>!n.areContextEntitiesEqual(b,m)):[...f,m])},c=()=>{o([...i])},d=()=>{o([])},h=()=>{if(r.length===0)return;const m=r[0],f=m.connectionId||"",w=m.connectionType||"",N=r.some(_=>_.type==="dataset")?"semanticDomain":"database";u({connectionId:f,connectionType:w,mode:N,selectedEntities:r}),a(!1)},x=m=>"label"in m&&m.label?m.label:m.name,g=m=>{if("description"in m&&m.description)return m.description;const f=[];return m.database&&f.push(m.database),m.schema&&f.push(m.schema),m.name&&f.push(m.name),f.join(".")},p=m=>r.some(f=>n.areContextEntitiesEqual(f,m));return i.length===0?e.jsx(n.Dialog,{open:s,onOpenChange:a,children:e.jsxs(n.DialogContent,{className:"max-w-md",children:[e.jsxs(n.DialogHeader,{children:[e.jsx(n.DialogTitle,{children:"No Data Available"}),e.jsx(n.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(n.DialogFooter,{children:e.jsx(t.Button,{onClick:()=>a(!1),children:"Close"})})]})}):e.jsx(n.Dialog,{open:s,onOpenChange:a,children:e.jsxs(n.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(n.DialogHeader,{children:[e.jsx(n.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(n.DialogDescription,{children:"Choose entities from the dashboard's context"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"outline",size:"sm",onClick:c,disabled:r.length===i.length,children:"Select All"}),e.jsx(t.Button,{variant:"outline",size:"sm",onClick:d,disabled:r.length===0,children:"Clear All"})]}),e.jsxs(n.Badge,{variant:"secondary",children:[r.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,f)=>e.jsxs("div",{className:t.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",p(m)&&"border-primary bg-primary/5"),children:[e.jsx(n.Checkbox,{checked:p(m),onCheckedChange:()=>l(m)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:n.getEntityIcon(m.type)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:x(m)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:g(m)})]}),e.jsx(n.Badge,{variant:"outline",className:"text-xs",children:m.type})]},`${m.type}-${m.name}-${f}`))})})]}),e.jsx(n.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:h,disabled:r.length===0,children:["Select"," ",r.length>0?`(${r.length})`:""]})]})})})]})})}function Me(s){return typeof s=="string"&&s.trim().length>0?s.trim():null}function Xn(s){return Array.from(new Set(s.filter(a=>!!a)))}function pr(s){const a=Me(s.table),r=Me(s.schema),o=Me(s.catalog)||Me(s.database);return a?Xn([a,r?`${r}.${a}`:null,o?`${o}.${a}`:null,o&&r?`${o}.${r}.${a}`:null]):[]}function Ts(s){const a=Me(s.table)||Me(s.tableName);return Xn([Me(s.name),Me(s.alias),...pr({table:a,schema:Me(s.schema)||Me(s.schemaName),catalog:Me(s.catalog),database:Me(s.database)||Me(s.databaseName)})])}function fr(s,a){if(s.type==="dataset"){const d=Me(s.domainId),h=Me(a.domainId);if(d&&h&&d!==h)return!0;if(a.type==="dataset"){const x=Me(s.id),g=Me(a.id);if(x&&g&&x!==g)return!0;const p=Me(a.name);if(p&&!Ts(s).includes(p))return!0}return!1}const r=Me(s.id),o=Me(a.id);if(r&&o&&r!==o)return!0;const u=Me(s.domainId),i=Me(a.domainId);if(u&&i&&u!==i)return!0;const l=Me(s.connectionId),c=Me(a.connectionId);return!!(l&&c&&l!==c)}function gr(s,a){if(!a||!(s!=null&&s.length))return;const r=Ts(a);if(r.length===0)return;const o=s.filter(i=>!fr(i,a));for(const i of r){const l=o.find(c=>Me(c.name)===i);if(l)return l}const u=o.filter(i=>Ts(i).some(c=>r.includes(c)));return u.length===1?u[0]:void 0}function ds(s,a){const r=gr(s,a);return r?{...a,...r}:a}function br(s,a){const r=a||[];return r.length===0?s:{...s,baseEntity:ds(r,s.baseEntity),joins:s.joins.map(o=>({...o,source:ds(r,o.source),target:ds(r,o.target)}))}}function In(){return{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}}function jr({initialJoinPlan:s,availableDataSources:a}){const[r,o]=v.useState(()=>br(s,a)),[u,i]=v.useState(new Set),l=()=>{const I=r.joins.length>0?Math.max(...r.joins.map(D=>D.sequence))+1:1,E={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:I,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};o({...r,joins:[...r.joins,E]}),i(new Set([...u,E.id]))},c=I=>{o({...r,joins:r.joins.filter(E=>E.id!==I)}),i(new Set([...u].filter(E=>E!==I)))},d=(I,E)=>{var M,P,F,j,k;const D=r.joins.find(O=>O.id===I);if(!D)return;const T={...D,...E};if((M=T.source)!=null&&M.name&&((P=T.target)!=null&&P.name)&&T.source.name===T.target.name){n.ue.error("Self-joins are not yet supported",{description:`Joining ${T.source.name} to itself is not currently supported. Please select a different target table.`});return}const y=r.joins.filter(O=>{var R;return O.id!==I&&O.target.name===((R=T.target)==null?void 0:R.name)});if((F=T.target)!=null&&F.name&&y.length>0){n.ue.error("Duplicate join targets are not supported",{description:`The table ${T.target.name} is already used as a target in another join. Each table can only be joined once.`});return}const L=r.joins.map(O=>O.id===I?T:O);if((j=T.source)!=null&&j.name&&((k=T.target)!=null&&k.name)&&T.joinKeyGroups[0].keys.length===0){const O=a.find(V=>{var q;return V.name===((q=T.source)==null?void 0:q.name)}),R=a.find(V=>{var q;return V.name===((q=T.target)==null?void 0:q.name)}),B={id:`key-${Date.now()}`,source:{id:`source-${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"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(R==null?void 0:R.name)||"",entityName:(R==null?void 0:R.name)||"",entityType:(R==null?void 0:R.type)||"table"},operator:"="},z=[...T.joinKeyGroups];z[0]={...z[0],keys:[B]},T.joinKeyGroups=z,L[L.findIndex(V=>V.id===I)]=T}o({...r,joins:L})};return{joinPlan:r,expandedJoins:u,setJoinPlan:o,addJoin:l,removeJoin:c,updateJoin:d,moveJoinUp:I=>{const E=r.joins.findIndex(D=>D.id===I);if(E>0){const D=[...r.joins],T={...D[E]},y={...D[E-1]};D[E]=y,D[E-1]=T,D.forEach((M,P)=>{M.sequence=P+1});const L={...r,joins:D};o(L)}},moveJoinDown:I=>{const E=r.joins.findIndex(D=>D.id===I);if(E<r.joins.length-1){const D=[...r.joins],T={...D[E]},y={...D[E+1]};D[E]=y,D[E+1]=T,D.forEach((M,P)=>{M.sequence=P+1});const L={...r,joins:D};o(L)}},toggleJoinExpansion:I=>{const E=new Set(u);E.has(I)?E.delete(I):E.add(I),i(E)},getAvailableSourceEntities:I=>{if(r.joins.length===0)return a;const E=r.joins.findIndex(T=>T.id===I);if(E===0)return a.filter(T=>T.name===r.baseEntity.name);const D=new Set;return r.baseEntity.name&&D.add(r.baseEntity.name),r.joins.slice(0,E).forEach(T=>{D.add(T.source.name),D.add(T.target.name)}),a.filter(T=>D.has(T.name))},getAvailableTargetEntities:I=>a.filter(E=>E.name!==I),addJoinKeyGroup:I=>{const E=r.joins.find(T=>T.id===I);if(!E)return;const D=[...E.joinKeyGroups,In()];d(I,{joinKeyGroups:D})},updateGroupOperator:(I,E,D)=>{const T=r.joins.find(L=>L.id===I);if(!T)return;const y=[...T.joinKeyGroups];y[E]={...y[E],operator:D},d(I,{joinKeyGroups:y})},removeJoinKeyGroup:(I,E)=>{const D=r.joins.find(y=>y.id===I);if(!D)return;const T=[...D.joinKeyGroups];T.splice(E,1),d(I,{joinKeyGroups:T})},addJoinKey:(I,E)=>{const D=r.joins.find(P=>P.id===I);if(!D)return;const T=a.find(P=>P.name===D.source.name),y=a.find(P=>P.name===D.target.name),L=[...D.joinKeyGroups];L[E]||(L[E]=In());const M={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(T==null?void 0:T.name)||"",entityName:(T==null?void 0:T.name)||"",entityType:(T==null?void 0:T.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(y==null?void 0:y.name)||"",entityName:(y==null?void 0:y.name)||"",entityType:(y==null?void 0:y.type)||"table"},operator:"="};L[E]={...L[E],keys:[...L[E].keys,M]},d(I,{joinKeyGroups:L})},updateJoinKey:(I,E,D,T,y)=>{const L=r.joins.find(k=>k.id===I);if(!L)return;const M=a.find(k=>k.name===L.source.name),P=a.find(k=>k.name===L.target.name),F=[...L.joinKeyGroups],j=F[E].keys[D];T==="sourceColumnName"&&M?F[E].keys[D]={...j,source:{...j.source,name:y}}:T==="targetColumnName"&&P?F[E].keys[D]={...j,target:{...j.target,name:y}}:T==="operator"&&(F[E].keys[D]={...j,operator:y}),d(I,{joinKeyGroups:F})},removeJoinKey:(I,E,D)=>{const T=r.joins.find(L=>L.id===I);if(!T)return;const y=[...T.joinKeyGroups];y[E].keys.splice(D,1),d(I,{joinKeyGroups:y})},generateSQLPreview:()=>{const I=[...r.joins].sort((T,y)=>T.sequence-y.sequence),E=r.baseEntity;if(!E.name)return"SELECT * FROM table -- Please select a base entity";let D=`SELECT *
|
|
147
|
-
FROM ${E.name}`;return I.forEach(T=>{const y=a.find(P=>P.name===T.target.name);if(!y)return;const L=T.joinKeyGroups.filter(P=>P.keys&&P.keys.length>0).map(P=>{const F=P.keys.filter(j=>{var k,O,R,B;return((k=j.source)==null?void 0:k.name)&&((O=j.target)==null?void 0:O.name)&&((R=j.source)==null?void 0:R.entityName)&&((B=j.target)==null?void 0:B.entityName)}).map(j=>`${j.source.entityName}.${j.source.name} ${j.operator} ${j.target.entityName}.${j.target.name}`);return F.length>1?`(${F.join(` ${P.operator} `)})`:F[0]}).filter(Boolean),M=L.length>1?L.join(" OR "):L[0]||"condition_here";D+=`
|
|
148
|
-
${T.joinType} JOIN ${y.name}
|
|
149
|
-
ON ${M}`}),D},isValidConfiguration:()=>!(!r.baseEntity.name||r.joins.some(T=>!T.source.name||!T.target.name)||r.joins.some(T=>T.joinKeyGroups.some(y=>y.keys.length===0))||r.joins.some(T=>T.joinKeyGroups.some(y=>y.keys.some(L=>!L.source.name||!L.target.name||!L.operator))))}}const vr=[{value:"LEFT",label:"Keep rows without a match"},{value:"INNER",label:"Only matching rows"},{value:"RIGHT",label:"Keep all target rows"},{value:"FULL",label:"Keep all rows"}],yr={one_to_one:"One to one",one_to_many:"One to many",many_to_one:"Many to one",many_to_many:"Many to many"},Nr={one_to_one:"1 : 1",one_to_many:"1 : N",many_to_one:"N : 1",many_to_many:"N : N"},Cr=["=","<",">","<=",">="];function Sr({joinPlan:s,availableDataSources:a,onSave:r,onRemove:o,onCancel:u}){const{columnGroups:i}=n.useColumns(),l=i.filter(R=>R.entityName!==t.CALCULATED_FIELDS_GROUP_NAME),{joinPlan:c,expandedJoins:d,setJoinPlan:h,addJoin:x,removeJoin:g,updateJoin:p,moveJoinUp:m,moveJoinDown:f,toggleJoinExpansion:w,getAvailableSourceEntities:b,getAvailableTargetEntities:N,addJoinKeyGroup:A,updateGroupOperator:_,removeJoinKeyGroup:C,addJoinKey:S,updateJoinKey:I,removeJoinKey:E,generateSQLPreview:D,isValidConfiguration:T}=jr({initialJoinPlan:s,availableDataSources:a}),[y,L]=v.useState(new Set),[M,P]=v.useState(!1),F=R=>{const B=l.find(z=>z.entityName===R);return(B==null?void 0:B.columns)||[]},j=R=>L(B=>{const z=new Set(B);return z.has(R)?z.delete(R):z.add(R),z}),k=[];c.baseEntity.name&&k.push(c.baseEntity.name);for(const R of[...c.joins].sort((B,z)=>B.sequence-z.sequence))R.target.name&&!k.includes(R.target.name)&&k.push(R.target.name);const O=R=>{const B=R.joinKeyGroups.flatMap(q=>q.keys),z=B.find(q=>{var U,G;return((U=q.source)==null?void 0:U.name)&&((G=q.target)==null?void 0:G.name)});if(!z)return null;const V=B.length>1?` +${B.length-1}`:"";return`${z.source.name} ${z.operator||"="} ${z.target.name}${V}`};return e.jsxs("div",{className:"min-w-0 space-y-5",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Start from"}),e.jsxs(t.Select,{value:c.baseEntity.name,onValueChange:R=>{const B=a.find(z=>z.name===R);h({...c,baseEntity:{connectionId:(B==null?void 0:B.connectionId)||"",connectionType:(B==null?void 0:B.connectionType)||"none",type:(B==null?void 0:B.type)||"table",name:R,database:B==null?void 0:B.database,schema:B==null?void 0:B.schema}})},children:[e.jsx(t.SelectTrigger,{className:"h-8 text-[12px]",children:e.jsx(t.SelectValue,{placeholder:"Select the dataset to start from..."})}),e.jsx(t.SelectContent,{children:a.map(R=>e.jsx(t.SelectItem,{value:R.name,className:"text-[12px]",children:R.name},R.name))})]}),e.jsx("p",{className:"text-[11px] leading-relaxed text-muted-foreground",children:"Every other dataset connects back to this one."})]}),k.length>0&&e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsx(t.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Join path"}),e.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:k.map((R,B)=>e.jsxs("span",{className:"flex items-center gap-1.5",children:[B>0&&e.jsx(n.ArrowRight,{className:"h-3 w-3 text-muted-foreground"}),e.jsxs("span",{className:`inline-flex max-w-[220px] items-center gap-1.5 rounded-[4px] border px-2 py-1 leading-none ${B===0?"border-border bg-muted font-medium text-foreground":"border-border/60 text-muted-foreground"}`,children:[e.jsx(n.Database,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"min-w-0 truncate text-[11.5px] leading-none",children:R}),B===0&&e.jsx("span",{className:"shrink-0 text-[9.5px] uppercase leading-none tracking-[0.06em] text-muted-foreground",children:"BASE"})]})]},R))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(t.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:["How datasets connect (",c.joins.length,")"]}),e.jsxs(t.Button,{variant:"outline",size:"xs",className:"gap-1.5",onClick:x,children:[e.jsx(n.Plus,{className:"h-3.5 w-3.5"}),"Add join"]})]}),c.joins.length===0?e.jsxs("div",{className:"rounded-[6px] border border-dashed border-border px-4 py-8 text-center",children:[e.jsx("p",{className:"text-[12.5px] font-medium text-foreground",children:"No joins yet"}),e.jsxs("p",{className:"mx-auto mt-1 max-w-[360px] text-[11.5px] leading-relaxed text-muted-foreground",children:["Add a join to connect another dataset to"," ",c.baseEntity.name||"your base dataset","."]})]}):e.jsx("div",{className:"max-h-[340px] space-y-1.5 overflow-y-auto",children:c.joins.map(R=>{var Q;const B=a.find(Y=>Y.name===R.source.name),z=a.find(Y=>Y.name===R.target.name),V=d.has(R.id),q=y.has(R.id)||R.joinKeyGroups.length>1||R.joinKeyGroups.some(Y=>Y.operator!=="AND"),U=O(R),G=R.relationshipCardinality;return e.jsxs("div",{className:`rounded-[6px] border ${V?"border-border":"border-border/60"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2.5",children:[e.jsxs("button",{type:"button",onClick:()=>w(R.id),className:"flex min-w-0 flex-1 items-center gap-2 text-left",children:[V?e.jsx(t.ChevronDown,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):e.jsx(n.ChevronRight,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 text-[12.5px] font-medium text-foreground",children:[e.jsx("span",{className:"truncate",children:R.source.name||"source"}),e.jsx(n.ArrowRight,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:R.target.name||"target"})]}),U&&e.jsx("code",{className:"hidden max-w-[180px] shrink-0 truncate rounded-[4px] bg-muted px-1.5 py-0.5 font-mono text-[10.5px] text-muted-foreground lg:inline-block",children:U})]}),e.jsxs("span",{className:"flex shrink-0 items-center gap-0.5",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>m(R.id),disabled:R.sequence===1,"aria-label":"Move join earlier",children:e.jsx(wr,{})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>f(R.id),disabled:R.sequence===c.joins.length,"aria-label":"Move join later",children:e.jsx(Tr,{})}),e.jsxs(t.Button,{variant:"ghost",size:"sm",className:"h-6 gap-1 px-1.5 text-[11px] font-medium text-muted-foreground",onClick:()=>w(R.id),children:[e.jsx(n.Pencil,{className:"h-3 w-3"}),V?"Editing":"Edit"]}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground",onClick:()=>g(R.id),"aria-label":"Remove join",children:e.jsx(t.X,{className:"h-3.5 w-3.5"})})]})]}),V&&e.jsxs("div",{className:"space-y-4 border-t border-border/60 px-3 pb-4 pt-3",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsx(t.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"From"}),e.jsxs(t.Select,{value:R.source.name,onValueChange:Y=>{const H=a.find(se=>se.name===Y);p(R.id,{source:{connectionId:(H==null?void 0:H.connectionId)||"",connectionType:(H==null?void 0:H.connectionType)||"none",type:(H==null?void 0:H.type)||"table",name:Y,database:H==null?void 0:H.database,schema:H==null?void 0:H.schema}})},children:[e.jsx(t.SelectTrigger,{className:"h-8 text-[12px]",children:e.jsx(t.SelectValue,{placeholder:"Select source..."})}),e.jsx(t.SelectContent,{children:b(R.id).map(Y=>e.jsx(t.SelectItem,{value:Y.name,className:"text-[12px]",children:Y.name},Y.name))})]})]}),e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsx(t.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"To"}),e.jsxs(t.Select,{value:R.target.name,onValueChange:Y=>{const H=a.find(se=>se.name===Y);p(R.id,{target:{connectionId:(H==null?void 0:H.connectionId)||"",connectionType:(H==null?void 0:H.connectionType)||"none",type:(H==null?void 0:H.type)||"table",name:Y,database:H==null?void 0:H.database,schema:H==null?void 0:H.schema}})},disabled:!R.source.name,children:[e.jsx(t.SelectTrigger,{className:"h-8 text-[12px]",children:e.jsx(t.SelectValue,{placeholder:"Select target..."})}),e.jsx(t.SelectContent,{children:R.source.name?N(R.source.name).map(Y=>e.jsx(t.SelectItem,{value:Y.name,className:"text-[12px]",children:Y.name},Y.name)):null})]})]}),e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsx(t.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"When a row has no match"}),e.jsxs(t.Select,{value:R.joinType,onValueChange:Y=>p(R.id,{joinType:Y}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-[12px]",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:vr.map(Y=>e.jsx(t.SelectItem,{value:Y.value,className:"text-[12px]",children:e.jsxs("span",{className:"flex w-full min-w-0 items-center justify-between gap-3",children:[e.jsx("span",{className:"truncate",children:Y.label}),e.jsx("span",{className:"shrink-0 font-mono text-[10px] tracking-[0.04em] text-muted-foreground",children:Y.value})]})},Y.value))})]})]})]}),G&&e.jsxs("div",{className:"flex min-w-0 items-center gap-2 rounded-[5px] border border-border/60 bg-muted/40 px-2.5 py-1.5 text-[11.5px]",children:[e.jsx("span",{className:"shrink-0 rounded-[3px] bg-muted px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground",children:Nr[G]}),e.jsx("span",{className:"text-muted-foreground",children:yr[G]}),e.jsxs("span",{className:"truncate text-muted-foreground/70",children:["(",R.source.name||"source"," →"," ",R.target.name||"target",")"]})]}),R.source.name&&R.target.name&&B&&z&&e.jsx("div",{className:"space-y-2",children:q?e.jsx(Er,{join:R,getColumnsForEntity:F,addJoinKey:S,addJoinKeyGroup:A,updateGroupOperator:_,removeJoinKeyGroup:C,updateJoinKey:I,removeJoinKey:E,canCollapse:R.joinKeyGroups.length<=1&&R.joinKeyGroups.every(Y=>Y.operator==="AND"),onCollapse:()=>j(R.id)}):e.jsxs(e.Fragment,{children:[e.jsx(t.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Match on"}),(Q=R.joinKeyGroups[0])!=null&&Q.keys.length?e.jsx("div",{className:"min-w-0 space-y-1.5",children:R.joinKeyGroups[0].keys.map((Y,H)=>e.jsx(Zn,{join:R,groupIndex:0,keyIndex:H,conditionKey:Y,getColumnsForEntity:F,updateJoinKey:I,removeJoinKey:E,showRemove:R.joinKeyGroups[0].keys.length>1},Y.id||H))}):e.jsx("p",{className:"rounded-[5px] border border-border/60 px-3 py-2 text-[11.5px] text-muted-foreground",children:"No match condition yet. Add one to define how these connect."}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Button,{type:"button",variant:"outline",size:"xs",className:"gap-1.5",onClick:()=>S(R.id,0),children:[e.jsx(n.Plus,{className:"h-3 w-3"})," Add condition"]}),e.jsxs("button",{type:"button",onClick:()=>j(R.id),className:"inline-flex items-center gap-1 text-[11px] font-medium text-muted-foreground hover:text-foreground",children:[e.jsx(n.Settings2,{className:"h-3 w-3"}),"Advanced"]})]})]})})]})]},R.id)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("button",{type:"button",onClick:()=>P(R=>!R),className:"inline-flex items-center gap-1.5 text-[11px] font-medium text-muted-foreground hover:text-foreground",children:[M?e.jsx(t.ChevronDown,{className:"h-3 w-3"}):e.jsx(n.ChevronRight,{className:"h-3 w-3"}),"View SQL"]}),M&&e.jsx("div",{className:"rounded-[5px] border border-border/60 bg-muted/40 p-3",children:e.jsx("code",{className:"block whitespace-pre-wrap break-all font-mono text-[11px] text-muted-foreground",children:D()})})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 border-t border-border pt-4",children:[e.jsxs(t.Button,{variant:"ghost",size:"xs",className:"gap-1.5 text-muted-foreground",onClick:()=>{o(),u()},children:[e.jsx(n.Trash2,{className:"h-3.5 w-3.5"}),"Remove all"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"outline",size:"xs",onClick:u,children:"Cancel"}),e.jsxs(t.Button,{size:"xs",className:"gap-1.5",onClick:()=>r(c),disabled:!T(),children:["Save joins",e.jsx(n.ArrowRight,{className:"h-3.5 w-3.5"})]})]})]})]})}function wr(){return e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:e.jsx("path",{d:"m18 15-6-6-6 6"})})}function Tr(){return e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:e.jsx("path",{d:"m6 9 6 6 6-6"})})}function Zn({join:s,groupIndex:a,keyIndex:r,conditionKey:o,getColumnsForEntity:u,updateJoinKey:i,removeJoinKey:l,showRemove:c,showOperator:d=!1}){const h=d||(o.operator||"=")!=="=";return e.jsxs("div",{className:"flex items-center gap-2 rounded-[5px] border border-border/60 p-2",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsxs(t.Select,{value:o.source.name,onValueChange:x=>i(s.id,a,r,"sourceColumnName",x),children:[e.jsx(t.SelectTrigger,{className:"h-7 font-mono text-[11px]",children:e.jsx(t.SelectValue,{placeholder:"Source column"})}),e.jsx(t.SelectContent,{children:u(s.source.name).map(x=>e.jsx(t.SelectItem,{value:x.name,children:e.jsxs("span",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx("span",{className:"font-mono",children:x.name}),x.dataType&&e.jsx("span",{className:"text-[10px] text-muted-foreground",children:x.dataType})]})},x.name))})]})}),h?e.jsx("div",{className:"w-16 shrink-0",children:e.jsxs(t.Select,{value:o.operator,onValueChange:x=>i(s.id,a,r,"operator",x),children:[e.jsx(t.SelectTrigger,{className:"h-7 justify-center px-1 font-mono text-[11px]",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Cr.map(x=>e.jsx(t.SelectItem,{value:x,children:x},x))})]})}):e.jsx("span",{className:"shrink-0 px-1 font-mono text-[12px] text-muted-foreground",children:"="}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsxs(t.Select,{value:o.target.name,onValueChange:x=>i(s.id,a,r,"targetColumnName",x),children:[e.jsx(t.SelectTrigger,{className:"h-7 font-mono text-[11px]",children:e.jsx(t.SelectValue,{placeholder:"Target column"})}),e.jsx(t.SelectContent,{children:u(s.target.name).map(x=>e.jsx(t.SelectItem,{value:x.name,children:e.jsxs("span",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx("span",{className:"font-mono",children:x.name}),x.dataType&&e.jsx("span",{className:"text-[10px] text-muted-foreground",children:x.dataType})]})},x.name))})]})}),c&&e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 shrink-0 p-0 text-muted-foreground",onClick:()=>l(s.id,a,r),"aria-label":"Remove condition",children:e.jsx(t.X,{className:"h-3.5 w-3.5"})})]})}function Er({join:s,getColumnsForEntity:a,addJoinKey:r,addJoinKeyGroup:o,updateGroupOperator:u,removeJoinKeyGroup:i,updateJoinKey:l,removeJoinKey:c,canCollapse:d,onCollapse:h}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(t.Label,{className:"flex items-center gap-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:[e.jsx(n.Settings2,{className:"h-3 w-3"}),"Advanced conditions"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[d&&e.jsx("button",{type:"button",onClick:h,className:"text-[11px] font-medium text-muted-foreground hover:text-foreground",children:"Use simple"}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"xs",className:"gap-1.5",onClick:()=>o(s.id),children:[e.jsx(n.Plus,{className:"h-3 w-3"})," Add OR group"]})]})]}),s.joinKeyGroups.map((x,g)=>e.jsxs("div",{className:"space-y-2 rounded-[5px] border border-border/60 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("span",{className:"text-[11px] font-medium text-foreground",children:["Group ",g+1]}),g>0&&e.jsx("span",{className:"rounded-[3px] bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground",children:"OR with previous"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-[0.06em] text-muted-foreground",children:"within group"}),e.jsxs(t.Select,{value:x.operator,onValueChange:p=>u(s.id,g,p),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-[76px] text-[11px]",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"})]})]}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground",onClick:()=>i(s.id,g),"aria-label":"Remove group",children:e.jsx(n.Trash2,{className:"h-3.5 w-3.5"})})]})]}),x.keys.length===0?e.jsx("p",{className:"rounded-[5px] border border-dashed border-border/60 px-3 py-2 text-center text-[11.5px] text-muted-foreground",children:"No conditions in this group."}):e.jsx("div",{className:"min-w-0 space-y-1.5",children:x.keys.map((p,m)=>e.jsxs("div",{className:"flex items-center gap-2",children:[m>0&&e.jsx("span",{className:"w-9 shrink-0 text-center text-[10px] font-medium text-muted-foreground",children:x.operator}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(Zn,{join:s,groupIndex:g,keyIndex:m,conditionKey:p,getColumnsForEntity:a,updateJoinKey:l,removeJoinKey:c,showRemove:!0,showOperator:!0})})]},p.id||m))}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"xs",className:"gap-1.5",onClick:()=>r(s.id,g),children:[e.jsx(n.Plus,{className:"h-3 w-3"})," Add condition"]})]},x.id))]})}function ea({children:s,open:a,onOpenChange:r,joinPlan:o,availableDataSources:u,onRemove:i,onSave:l,onCancel:c}){return e.jsxs(n.Dialog,{open:a,onOpenChange:r,children:[e.jsxs(n.DialogContent,{className:"max-h-[88vh] w-[calc(100vw-2rem)] max-w-4xl overflow-y-auto overflow-x-hidden",children:[e.jsxs(n.DialogHeader,{children:[e.jsx(n.DialogTitle,{className:"text-[15px] font-semibold tracking-tight",children:"How datasets connect"}),e.jsx(n.DialogDescription,{className:"text-[12px] text-muted-foreground",children:"Datasets joined together so a card can use fields from all of them."})]}),e.jsx(Sr,{joinPlan:o,availableDataSources:u,onSave:l,onCancel:c,onRemove:i})]}),s]})}function Ir({joins:s,baseEntityId:a,availableDataSources:r,generateSQLPreview:o}){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 u=[...s].sort((l,c)=>l.sequence-c.sequence),i=r.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(n.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(n.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),u.map(l=>{const c=r.find(d=>d.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(n.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(n.Badge,{variant:"secondary",className:"text-xs",children:c==null?void 0:c.type}),e.jsx("span",{className:"text-xs font-medium",children:c==null?void 0:c.name})]})]},l.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",s.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...s].sort((u,i)=>u.sequence-i.sequence).map((u,i)=>{const l=r.find(h=>h.name===u.source.name),c=r.find(h=>h.name===u.target.name),d=u.joinKeyGroups.reduce((h,x)=>h+x.keys.length,0);return e.jsxs("div",{className:"rounded-md bg-muted p-2 text-left",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:i+1}),e.jsx(n.Badge,{variant:"outline",className:"shrink-0 text-xs",children:u.joinType}),e.jsxs(n.Badge,{variant:"outline",className:"ml-auto shrink-0 text-xs",children:[d," condition",d>1?"s":""]})]}),e.jsxs("div",{className:"mt-1 truncate pl-1 text-xs text-muted-foreground",children:[l==null?void 0:l.name," → ",c==null?void 0:c.name]})]},u.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:o()})})]})]})}function Dr({open:s,onOpenChange:a,variant:r="button"}={}){var A,_;const o=t.useEditorStore(C=>C.card),{autoJoinMetadata:u}=n.useEditorCardQuery(o),i=t.useEditorStore(C=>C.actions.updateCardConfig),l=((A=o==null?void 0:o.config)==null?void 0:A.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[c,d]=v.useState(!1),h=s!==void 0,x=h?s:c,g=h?a:d,p=((_=o==null?void 0:o.dataSource)==null?void 0:_.selectedEntities)||[],m=C=>{i(o.id,{...o==null?void 0:o.config,joinPlan:C}),g(!1)},f=()=>{i(o.id,{...o==null?void 0:o.config,joinPlan:void 0})},w=()=>{g(!1)},b=()=>{const C=[...l.joins].sort((E,D)=>E.sequence-D.sequence),S=l.baseEntity;if(!S.name)return"SELECT * FROM table -- Please select a base entity";let I=`SELECT *
|
|
150
|
-
FROM ${S.name}`;return C.forEach(E=>{const D=p.find(L=>L.name===E.target.name);if(!D)return;const T=E.joinKeyGroups.filter(L=>L.keys&&L.keys.length>0).map(L=>{const M=L.keys.filter(P=>{var F,j,k,O;return((F=P.source)==null?void 0:F.name)&&((j=P.target)==null?void 0:j.name)&&((k=P.source)==null?void 0:k.entityName)&&((O=P.target)==null?void 0:O.entityName)}).map(P=>`${P.source.entityName}.${P.source.name} ${P.operator} ${P.target.entityName}.${P.target.name}`);return M.length>1?`(${M.join(` ${L.operator} `)})`:M[0]}).filter(Boolean),y=T.length>1?T.join(" OR "):T[0]||"condition_here";I+=`
|
|
151
|
-
${E.joinType} JOIN ${D.name}
|
|
152
|
-
ON ${y}`}),I};if(p.length<2)return null;const N=l.joins.length>0&&e.jsx(t.TooltipContent,{side:"bottom",className:"ml-4 max-w-md overflow-hidden p-0",children:e.jsx(Ir,{joins:l.joins,baseEntityId:l.baseEntity.name,availableDataSources:p,generateSQLPreview:b})});return e.jsxs(e.Fragment,{children:[e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:r==="badge"?e.jsxs(n.Badge,{variant:"secondary",className:"h-5 cursor-pointer gap-1 px-1.5 text-xs transition-colors hover:bg-secondary/80",onClick:C=>{C.stopPropagation(),g(!0)},children:[e.jsx(n.Link,{className:"h-3 w-3"}),l.joins.length]}):e.jsxs("button",{type:"button",onClick:()=>g(!0),className:"flex h-7 w-full items-center gap-2 rounded-control border border-input bg-background px-2 text-left transition-colors hover:bg-muted focus:outline-none focus-visible:border-ring",children:[e.jsx(n.Link,{className:"h-3 w-3 shrink-0 text-muted-foreground",strokeWidth:1.75}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-[13px] text-foreground",children:l.joins.length===0?"Configure joins":`${l.joins.length} ${l.joins.length===1?"join":"joins"}`}),(u==null?void 0:u.autoResolved)&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-muted-foreground",children:[e.jsx(n.Sparkles,{className:"h-3 w-3",strokeWidth:1.75}),"Auto"]})]})}),N]})}),e.jsx(ea,{open:x,onOpenChange:g,joinPlan:l,availableDataSources:p,onSave:m,onCancel:w,onRemove:f,children:e.jsx("div",{})})]})}function kr(){var C,S,I,E,D,T;const[s,a]=v.useState(!1),[r,o]=v.useState(!1),[u,i]=v.useState(!1),l=t.useEditorStore(y=>y.card.dataSource),c=t.useEditorStore(y=>y.card),d=t.useEditorStore(y=>y.isDevMode),{updateDataSource:h}=t.useEditorActions(),{autoJoinMetadata:x}=n.useEditorCardQuery(c),p={...{connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},...l,selectedEntities:(l==null?void 0:l.selectedEntities)||[]},m=n.toEntityArray(p.selectedEntities),f=m.length,w=f===0?"Choose dataset":f===1?us(m[0]):`${f} datasets`,b=((I=(S=(C=c==null?void 0:c.config)==null?void 0:C.joinPlan)==null?void 0:S.joins)==null?void 0:I.length)??0,N=!!(x!=null&&x.autoResolved);((D=(E=x==null?void 0:x.resolvedJoinPlan)==null?void 0:E.joins)==null?void 0:D.length)??((T=x==null?void 0:x.relationshipsUsed)==null||T.length);const A=f<2?null:b>0?`${b} join${b===1?"":"s"}`:N?"auto":null,_=y=>{const L=m.filter(M=>!n.areContextEntitiesEqual(M,y));h({...p,selectedEntities:L})};return e.jsxs(e.Fragment,{children:[e.jsxs(t.Popover,{open:s,onOpenChange:a,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex h-7 w-full items-center gap-2 rounded-control border border-input bg-background px-2 text-left transition-colors hover:bg-muted focus:outline-none focus-visible:border-ring",children:[e.jsx(n.Database,{className:"h-3 w-3 shrink-0 text-muted-foreground",strokeWidth:1.75}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-[13px] text-foreground",children:w}),A&&e.jsxs("span",{className:"shrink-0 text-[11px] text-muted-foreground",children:["· ",A]}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform",s&&"rotate-180")})]})}),e.jsx(t.PopoverContent,{align:"start",sideOffset:4,className:"w-[320px] overflow-hidden rounded-control border border-border bg-popover p-0 shadow-[0_4px_16px_rgba(0,0,0,0.08)]",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between px-3 pb-1.5 pt-2.5",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Datasets"}),e.jsx("span",{className:"font-mono text-[10px] tabular-nums text-muted-foreground/70",children:f})]}),f===0?e.jsx("div",{className:"px-3 pb-2 text-[12px] text-muted-foreground",children:"No datasets selected."}):e.jsx("ul",{className:"mb-1",children:m.map((y,L)=>e.jsxs("li",{className:"flex items-start gap-2 px-3 py-1.5 hover:bg-muted/50",children:[e.jsx(n.Database,{className:"mt-[3px] h-3 w-3 shrink-0 text-muted-foreground",strokeWidth:1.75}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-[13px] text-foreground",children:us(y)}),e.jsx("p",{className:"truncate text-[11px] text-muted-foreground",children:Ar(y)})]}),e.jsx("button",{type:"button",onClick:()=>_(y),"aria-label":`Remove ${us(y)}`,className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-control text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:e.jsx(t.X,{className:"h-3 w-3"})})]},`${y.connectionId}-${y.name}-${L}`))}),e.jsxs("button",{type:"button",onClick:()=>{a(!1),o(!0)},className:"flex w-full items-center gap-1.5 px-3 py-1.5 text-left text-[12px] text-muted-foreground transition-colors hover:bg-muted/50 hover:text-foreground",children:[e.jsx(n.Plus,{className:"h-3 w-3"}),"Add dataset"]})]}),f>1&&!d&&e.jsxs("div",{className:"border-t border-border/60 px-3 py-2.5",children:[e.jsx("div",{className:"mb-1.5 flex items-center justify-between",children:e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Join"})}),e.jsxs("button",{type:"button",onClick:()=>{a(!1),i(!0)},className:"flex h-7 w-full items-center gap-2 rounded-control border border-input bg-background px-2 text-left transition-colors hover:bg-muted focus:outline-none focus-visible:border-ring",children:[e.jsx(n.Link,{className:"h-3 w-3 shrink-0 text-muted-foreground",strokeWidth:1.75}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-[13px] text-foreground",children:b>0?`${b} ${b===1?"join":"joins"}`:"Configure joins"}),N&&b===0&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-muted-foreground",children:[e.jsx(n.Sparkles,{className:"h-3 w-3",strokeWidth:1.75}),"Auto"]})]})]}),e.jsx("div",{className:"flex items-center justify-end border-t border-border/60 px-2 py-1.5",children:e.jsx("button",{type:"button",onClick:()=>a(!1),className:"inline-flex h-6 items-center rounded-control px-2 text-[11px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:"Done"})})]})})]}),e.jsx(n.AddDataPicker,{incomingSelectedEntities:(l==null?void 0:l.selectedEntities)||[],dialogMode:"dataSource",open:r,onOpenChange:o,dataSource:p}),f>1&&!d&&e.jsx("div",{className:"hidden",children:e.jsx(Dr,{open:u,onOpenChange:i})})]})}function us(s){return"label"in s&&s.label?s.label:s.name||"Dataset"}function Ar(s){const a=[];return s.connectionType&&a.push(String(s.connectionType)),s.database&&a.push(s.database),s.schema&&a.push(s.schema),a.join(" · ")}function ta({isVisible:s}){Ne.useSyncLegacyEditorState();const[a,r]=v.useState(!1);return e.jsxs("div",{className:t.cn("flex shrink-0 flex-col overflow-hidden border-r border-border bg-background transition-all duration-300 ease-in-out",{"w-[290px]":s,"min-w-[290px]":s,"w-0 border-r-0":!s,"min-w-0":!s}),children:[e.jsx("div",{className:"px-4 pt-4",children:e.jsx(kr,{})}),e.jsx("div",{className:"min-h-0 flex-1",children:e.jsx(n.FieldsSection,{})}),e.jsx(hr,{open:a,onOpenChange:r})]})}function sa({storeValue:s,defaultValue:a="",onStoreUpdate:r,delay:o=300}){const[u,i]=v.useState(s??a),l=v.useRef(null),c=v.useRef(u),d=v.useRef(s),h=v.useRef(!1),x=v.useCallback(()=>{l.current&&(clearTimeout(l.current),l.current=null),h.current&&c.current!==(d.current??a)&&(r(c.current),d.current=c.current)},[a,r]);v.useEffect(()=>{if(s!==d.current){l.current&&(clearTimeout(l.current),l.current=null);const p=s??a;i(p),c.current=p,d.current=s,h.current=!1}},[s,a]),v.useEffect(()=>{if(h.current)return l.current=setTimeout(()=>{x()},o),()=>{l.current&&(clearTimeout(l.current),l.current=null)}},[o,x,u]),v.useEffect(()=>()=>{l.current&&clearTimeout(l.current)},[]);const g=v.useCallback(p=>{const m=p??a;h.current=!0,c.current=m,i(m)},[a]);return{value:u,onChange:g,flush:x}}const Lr=300;function Mr(){const s=t.useEditorStore(N=>N.card.sql),a=t.useEditorStore(N=>N.sqlGen),r=t.useEditorStore(N=>N.card),o=Ne.useEffectiveEditorCardType(),{setCardSql:u,setSqlGen:i,setRunSql:l}=t.useEditorActions(),c=v.useMemo(()=>o!==r.type?{...r,type:o}:r,[r,o]),{queryKey:d}=n.useEditorCardQuery(c),h=n.useQueryClient(),x=v.useRef(d);x.current=d;const g=v.useRef(a);g.current=a;const p=v.useCallback(N=>{u(N)},[u]),{value:m,onChange:f,flush:w}=sa({storeValue:s,defaultValue:"",onStoreUpdate:p,delay:Lr});v.useEffect(()=>bt.registerPendingEditorDraftFlusher(w),[w]);function b(N){f(N),t.isObjectEmpty(g.current)||i({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!m&&e.jsx("div",{className:"pointer-events-none absolute left-[56px] top-4 z-10 font-mono text-[12px] leading-[1.55] text-muted-foreground",children:"Write your SQL here"}),e.jsx(t.CodeEditor,{value:m??"",onValueChange:b,language:"sql-jinja",embedded:!0,flushGutter:!0,wrapLines:!0,onKeyDown:N=>{N.key==="Enter"&&N.shiftKey&&(N.preventDefault(),bt.flushPendingEditorDrafts(),setTimeout(()=>{h.removeQueries({queryKey:x.current,exact:!0}),l(!0)},0))}})]})}const Fr=300;function Rr(){const s=t.useEditorStore(p=>p.card.python),a=t.useEditorStore(p=>p.card),r=Ne.useEffectiveEditorCardType(),{setCardPython:o,setRunSql:u}=t.useEditorActions(),i=v.useMemo(()=>r!==a.type?{...a,type:r}:a,[a,r]),{queryKey:l}=n.useEditorCardQuery(i),c=n.useQueryClient(),d=v.useRef(l);d.current=l;const{value:h,onChange:x,flush:g}=sa({storeValue:s,defaultValue:n.PYTHON_DEFAULT_CODE,onStoreUpdate:o,delay:Fr});return v.useEffect(()=>bt.registerPendingEditorDraftFlusher(g),[g]),e.jsx(t.CodeEditor,{value:h??"",onValueChange:x,language:"python",embedded:!0,flushGutter:!0,wrapLines:!0,onKeyDown:p=>{p.key==="Enter"&&p.shiftKey&&(p.preventDefault(),bt.flushPendingEditorDrafts(),setTimeout(()=>{c.removeQueries({queryKey:d.current,exact:!0}),u(!0)},0))}})}const Or=/\{\{-?\s*filters\s*\|\s*where\s*-?\}\}/i,Pr=/\{\{-?\s*filters\s*\|\s*and\s*-?\}\}/i,Vr=/\bwhere\b/i;function Br(s){return s!=null&&s.trim()?Or.test(s)||Pr.test(s):!1}function _r(s){return!(s!=null&&s.trim())||Br(s)?null:Vr.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 zr(s){const{request:a,mode:r="draft",currentSql:o,selectedTableName:u,selectedSchemaName:i,selectedDatabaseName:l}=s,c=[l?`Database: ${l}`:"",i?`Schema: ${i}`:"",u?`Table: ${u}`:""].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: ${n.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.",r==="refine"&&o?"Mode: Refine existing SQL. Keep the current query structure and only apply the requested changes unless the current query is invalid.":"Mode: Draft new SQL from the request.",c.length>0?`Context:
|
|
153
|
-
${c.join(`
|
|
154
|
-
`)}`:"",o?r==="refine"?`Current SQL (must refine):
|
|
155
|
-
${o}`:`Current SQL (revise if useful):
|
|
156
|
-
${o}`:"",`User request:
|
|
157
|
-
${a}`].filter(Boolean).join(`
|
|
158
|
-
|
|
159
|
-
`)}function qr(s){const{request:a,failedSql:r,errorMessage:o,errorCode:u,selectedDatabaseName:i,selectedSchemaName:l,selectedTableName:c,contextEntityLabels:d}=s,h=[i?`Database: ${i}`:"",l?`Schema: ${l}`:"",c?`Table: ${c}`:"",d.length>0?`Selected context entities: ${d.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.",h.length>0?`Context:
|
|
160
|
-
${h.join(`
|
|
161
|
-
`)}`:"",`Original user request:
|
|
162
|
-
${a}`,`Previous SQL draft:
|
|
163
|
-
${r}`,`Validation failure${u?` (${u})`:""}:
|
|
164
|
-
${o}`].filter(Boolean).join(`
|
|
165
|
-
|
|
166
|
-
`)}function $r(s,a){typeof window>"u"||window.dispatchEvent(new CustomEvent("semaphor:inline-query-writer",{detail:{event:s,...a,timestamp:Date.now()}}))}const ms={runId:0,phase:"idle",attempt:0,activeStep:"",timelineSteps:[],lastValidation:null,finalOutcome:"idle",hasTools:!1};function Kr(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 Dn(s){let a=0;for(let r=0;r<s.length;r+=1)a=(a<<5)-a+s.charCodeAt(r),a|=0;return String(a)}function kn(s){return s==="getTableColumns"?"Discovering columns":s==="getDomainRelationships"?"Resolving relationships":s==="getChartSQLSyntax"?"Reviewing SQL syntax":s==="getUserSql"?"Inspecting current query":"Analyzing context"}function Ur(s,a){return s===n.SELF_HEAL_TIMELINE_STEP&&a>0?`${n.SELF_HEAL_TIMELINE_STEP} ${a}/${n.MAX_SELF_HEAL_ATTEMPTS}`:s}function Zt(s){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`${s}-${crypto.randomUUID()}`:`${s}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function An(s){var a;for(let r=s.length-1;r>=0;r-=1){const o=s[r];if(o.role!=="user")continue;const u=(a=o.metadata)==null?void 0:a.inlineRunToken;if(typeof u=="string"&&u.length>0)return u}}function Gr(s){if(!s)return"";const a=s.trim(),r=s.match(/```sql\s*([\s\S]*?)```/i);if(r!=null&&r[1])return r[1].trim();const o=s.match(/```[\w-]*\s*([\s\S]*?)```/i);return o!=null&&o[1]?o[1].trim():/^(select|with|insert|update|delete)\b/i.test(a)?a:""}function Ln(s){for(let a=s.length-1;a>=0;a-=1){const r=s[a];if(!(r.role!=="assistant"||!Array.isArray(r.parts)))for(let o=r.parts.length-1;o>=0;o-=1){const u=r.parts[o];if((u==null?void 0:u.type)!=="text"||typeof(u==null?void 0:u.text)!="string")continue;const i=Gr(u.text);if(i)return i}}return""}function Hr({currentSql:s,currentPython:a,selectedDatabaseName:r,selectedSchemaName:o,selectedTableName:u,onApplySql:i,onOpenFullAssistant:l}){var ct,Ot;const{authToken:c,tokenProps:d}=n.useSemaphorContext(),h=(ct=n.useDashboardQuery().data)==null?void 0:ct.assistantProfileId,x=t.useEditorStore(W=>W.isDevMode),g=t.useEditorStore(W=>W.selectedConnectionId),p=t.useEditorStore(W=>{var Z;return(Z=W.card.dataSource)==null?void 0:Z.selectedEntities}),m=t.useAIInteractionStore(W=>W.currentAIContext.selectedEntities),f=m.length,{setCurrentAIContext:w}=t.useAIActions(),[b,N]=v.useState(""),[A,_]=v.useState(""),[C,S]=v.useState(""),[I,E]=v.useState("draft"),[D,T]=v.useState("draft"),[y,L]=v.useState(""),[M,P]=v.useState(!1),[F,j]=v.useState({status:"idle"}),[k,O]=v.useState(ms),[R,B]=v.useState(!1),[z,V]=v.useState(()=>Zt("inline-query-session")),q=v.useRef(null),U=v.useRef(null),G=v.useRef(null),Q=v.useRef(0),Y=v.useRef(0),H=v.useRef(Zt("inline-run-token")),se=v.useRef(z),ue=v.useRef(new Set),ae=v.useRef(new Map),me=v.useRef(0),ve=v.useRef(""),Oe=v.useRef(!1),Fe=v.useRef(!1),X=v.useRef(ms),ge=v.useRef(!1),Ce=v.useRef(null),Pe=v.useRef(()=>{}),_e=(Ot=d.apiServiceUrl)==null?void 0:Ot.replace(/\/$/,""),le=_e?`${_e}/v1/sql/validate`:"/v1/sql/validate",De=v.useCallback(W=>{O(Z=>{const ee=W(Z);return X.current=ee,ee})},[]),Se=v.useCallback((W,Z)=>{De(ee=>ee.runId===W?Z(ee):ee)},[De]),ie=v.useCallback(W=>Y.current===W&&!ue.current.has(W),[]),$=v.useCallback((W,Z,ee)=>{Se(W,be=>{const je=be.timelineSteps.includes(Z)?be.timelineSteps:[...be.timelineSteps,Z];return{...be,phase:(ee==null?void 0:ee.phase)||be.phase,attempt:typeof(ee==null?void 0:ee.attempt)=="number"?ee.attempt:be.attempt,activeStep:Z,timelineSteps:je,finalOutcome:(ee==null?void 0:ee.finalOutcome)||be.finalOutcome,hasTools:ee!=null&&ee.hasTools?!0:be.hasTools}})},[Se]),oe=v.useCallback(()=>{const W=Y.current+1,Z=Zt("inline-run-token"),ee=Zt("inline-query-session");return Y.current=W,H.current=Z,se.current=ee,V(ee),ue.current=new Set,ae.current=new Map,me.current=0,ve.current="",ge.current=!1,De(()=>({runId:W,phase:"drafting",attempt:0,activeStep:"Drafting SQL",timelineSteps:["Drafting SQL"],lastValidation:null,finalOutcome:"drafting",hasTools:!1})),{runId:W,runToken:Z,chatSessionId:ee}},[De]),fe=v.useCallback(()=>{if(Oe.current||Fe.current||f>0)return;const W=p||[];if(W.length===0)return;const Z=t.useAIInteractionStore.getState().currentAIContext;w({...Z,selectedEntities:W}),Fe.current=!0},[f,p,w]),ne=v.useCallback(()=>{Oe.current=!0},[]),ce=v.useCallback((W,Z,ee)=>{$r(W,{runId:Z,attemptCount:typeof(ee==null?void 0:ee.attemptCount)=="number"?ee.attemptCount:me.current,errorCode:ee==null?void 0:ee.errorCode,hasTools:typeof(ee==null?void 0:ee.hasTools)=="boolean"?ee.hasTools:k.hasTools,entityCount:f,finalOutcome:(ee==null?void 0:ee.finalOutcome)||k.finalOutcome})},[f,k.finalOutcome,k.hasTools]),Te=v.useCallback((W,Z)=>{const ee=G.current;if(!ee)return;const be={inlineRunToken:Z};ee({role:"user",parts:[{type:"text",text:W}],metadata:be},{metadata:be})},[]);v.useEffect(()=>{const W=Ce.current;!W||W.sessionId!==z||(Ce.current=null,Te(W.message,W.runToken))},[z,Te]);const ke=z,ze=v.useCallback(async({toolCall:W})=>{var He,at,pt,Re,$e,Ge;if(ke!==se.current)return;const Z=String(W.toolName||"").trim();if(!Z)return;const ee=Y.current;if(!ie(ee)){(He=U.current)==null||He.call(U,{tool:Z,toolCallId:W.toolCallId,output:{status:"error",message:"Inline run is no longer active; ignoring tool output."}});return}if(Z==="getUserSql"){$(ee,kn(Z),{hasTools:!0}),ce("inline_tool_step",ee,{hasTools:!0}),(at=U.current)==null||at.call(U,{tool:Z,toolCallId:W.toolCallId,output:{status:"success",sql:s||"",python:a||""}});return}const be=n.INLINE_BLOCKED_MUTATING_TOOLS.has(Z),je=n.INLINE_ALLOWED_READ_ONLY_TOOLS.has(Z);if(be||!je){(pt=U.current)==null||pt.call(U,{tool:Z,toolCallId:W.toolCallId,output:{status:"error",message:"This action is unavailable in inline draft mode. Open Full Assistant for this action."}});return}const pe=kn(Z);$(ee,pe,{phase:k.phase==="self-healing"?"self-healing":"drafting",hasTools:!0}),ce("inline_tool_step",ee,{hasTools:!0});const Ve=((Re=W.input)==null?void 0:Re.sql)??(($e=W.args)==null?void 0:$e.sql);typeof Ve=="string"&&Ve.trim().length>0&&(ge.current=!1,S(Ve.trim())),(Ge=U.current)==null||Ge.call(U,{tool:Z,toolCallId:W.toolCallId,output:{status:"success",message:"Read-only tool result received."}})},[a,s,ce,k.phase,ie,ke,$]),re=v.useCallback(({message:W,messages:Z})=>{if(ke!==se.current)return;const ee=An(Z);if(!ee||ee!==H.current)return;const be=Y.current;if(!ie(be))return;const je=Ln([W])||Ln(Z);if(je){ge.current=!1,S(je.trim());return}ge.current&&X.current.phase==="self-healing"&&Pe.current(be)},[ie,ke]),te=v.useCallback(W=>{if(ke!==se.current)return;const Z=Y.current;ie(Z)&&ge.current&&X.current.phase==="self-healing"&&Pe.current(Z)},[ie,ke]),{setMessages:xe,sendMessage:ye,addToolResult:Ee,status:qe,stop:Ie,error:Qe,clearError:Ue}=n.useChat({id:z,transport:new n.DefaultChatTransport({api:`${d.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${c==null?void 0:c.accessToken}`}),body:()=>{const W=t.useAIInteractionStore.getState();return{assistantId:"editor-assistant",assistantProfileId:h,isDevMode:x,aiContext:W.currentAIContext,reasoningEffort:W.reasoningEffort,showReasoning:!1}},credentials:"omit",prepareSendMessagesRequest:({messages:W,body:Z,requestMetadata:ee})=>{const be=ee==null?void 0:ee.inlineRunToken,je=An(W);return{body:{...Z,inlineRunToken:be||je,messages:t.cleanupIncompleteMessages(W)}}}}),onToolCall:ze,onFinish:re,onError:te,sendAutomaticallyWhen:n.lastAssistantMessageIsCompleteWithToolCalls});U.current=Ee,G.current=ye;const Ae=!["ready","error"].includes(qe),tt=(Qe==null?void 0:Qe.message)||"Unable to generate a SQL draft right now. Try again.",Le=v.useCallback(W=>{const Z=Y.current,ee=X.current.phase;if(!(ee==="drafting"||ee==="self-healing"||ee==="validating")){W==="stopped"&&Ae&&Ie();return}ue.current.add(Z),ge.current=!1,Q.current+=1,ve.current="",j({status:"idle"}),S(""),Ue(),xe([]),Se(Z,je=>({...je,phase:"idle",activeStep:"",finalOutcome:"cancelled"})),ce("inline_self_heal_stopped",Z,{finalOutcome:"cancelled"}),(Ae||W==="stopped")&&Ie()},[Ue,ce,Ae,xe,Ie,Se]),Gt=v.useCallback(async(W,Z)=>{var be;if(!ie(Z))return null;const ee=Q.current+1;Q.current=ee,$(Z,"Validating SQL",{phase:"validating"}),j({status:"validating"});try{const je=await t.postRequestRegular(le,(c==null?void 0:c.accessToken)||"",{sql:W,connectionId:g||void 0});if(Q.current!==ee||!ie(Z))return null;if((je==null?void 0:je.valid)===!0)return j({status:"valid",message:"SQL validation passed."}),Se(Z,He=>({...He,phase:"ready",finalOutcome:"validated",lastValidation:{valid:!0}})),ce("inline_draft_validated",Z,{finalOutcome:"validated"}),{status:"valid"};const pe=Kr(je==null?void 0:je.errorCode)||"UNKNOWN",Ve=typeof(je==null?void 0:je.error)=="string"&&je.error||typeof((be=je==null?void 0:je.details)==null?void 0:be.error)=="string"&&je.details.error||"SQL validation failed. Please revise the query draft.";return j({status:"invalid",message:Ve,errorCode:pe}),Se(Z,He=>({...He,lastValidation:{valid:!1,error:Ve,errorCode:pe}})),ce("inline_validation_failed",Z,{errorCode:pe,finalOutcome:"validation_failed"}),{status:"invalid",error:Ve,errorCode:pe}}catch(je){if(Q.current!==ee||!ie(Z))return null;const pe=t.getRequestErrorMessage(je,"Validation service unavailable. You can still replace and run.");return j({status:"error",message:pe,errorCode:"SQL_CONNECTION_ERROR"}),Se(Z,Ve=>({...Ve,phase:"error",finalOutcome:"error",lastValidation:{valid:!1,error:pe,errorCode:"SQL_CONNECTION_ERROR"}})),{status:"error",error:pe,errorCode:"SQL_CONNECTION_ERROR"}}},[c==null?void 0:c.accessToken,ce,ie,g,le,Se,$]),jt=v.useCallback((W,Z,ee,be)=>{let je=ee,pe="validation_failed",Ve="Validating SQL";Z==="attempt_limit"?(je=`Couldn't auto-fix after ${n.MAX_SELF_HEAL_ATTEMPTS} attempts. ${ee}`,pe="self_heal_exhausted",Ve=`Auto-fix stopped (${n.MAX_SELF_HEAL_ATTEMPTS} attempts)`):Z==="duplicate"&&(je=`Auto-fix stopped (repeated validation failure). ${ee}`,pe="self_heal_duplicate_stopped",Ve="Auto-fix stopped (repeated failure)"),j({status:"invalid",message:je,errorCode:be}),$(W,Ve,{phase:"error",finalOutcome:pe}),Se(W,He=>({...He,phase:"error",finalOutcome:pe,lastValidation:{valid:!1,error:je,errorCode:be}})),Z!=="terminal"&&ce("inline_self_heal_stopped",W,{errorCode:be,finalOutcome:pe}),ge.current=!1},[ce,Se,$]),At=v.useCallback(W=>{const Z="Auto-fix stopped (no SQL returned). Open Full Assistant to continue.",ee="self_heal_no_draft";j({status:"invalid",message:Z,errorCode:"UNKNOWN"}),$(W,"Auto-fix stopped (no SQL returned)",{phase:"error",finalOutcome:ee}),Se(W,be=>({...be,phase:"error",finalOutcome:ee,lastValidation:{valid:!1,error:Z,errorCode:"UNKNOWN"}})),ce("inline_self_heal_stopped",W,{errorCode:"UNKNOWN",finalOutcome:ee}),ge.current=!1},[ce,Se,$]);Pe.current=At,v.useEffect(()=>{const W=C.trim(),Z=Y.current;if(!W){if(Q.current+=1,ve.current="",X.current.phase==="error")return;j({status:"idle"});return}if(!ie(Z)||Ae)return;const ee=`${Z}:${me.current}:${Dn(W)}`;if(ve.current===ee)return;ve.current=ee;let be=!1;return(async()=>{const pe=await Gt(W,Z);if(!pe||be||!ie(Z)||pe.status!=="invalid")return;if(!n.RECOVERABLE_SQL_ERROR_CODES.has(pe.errorCode)){jt(Z,"terminal",pe.error,pe.errorCode);return}const Ve=`${Dn(W)}::${pe.errorCode}`,He=(ae.current.get(Ve)||0)+1;if(ae.current.set(Ve,He),He>=2){jt(Z,"duplicate",pe.error,pe.errorCode);return}if(me.current>=n.MAX_SELF_HEAL_ATTEMPTS){jt(Z,"attempt_limit",pe.error,pe.errorCode);return}const at=me.current+1;me.current=at,$(Z,n.SELF_HEAL_TIMELINE_STEP,{phase:"self-healing",attempt:at}),ce("inline_self_heal_attempt",Z,{attemptCount:at,errorCode:pe.errorCode}),ge.current=!0,Ue(),xe([]),S("");const pt=m.map($e=>{const Ge=$e!=null&&$e.database?`${$e.database}.`:"",Ye=$e!=null&&$e.schema?`${$e.schema}.`:"",Pt=($e==null?void 0:$e.name)||"unknown";return`${Ge}${Ye}${Pt}`}),Re=qr({request:A,failedSql:W,errorMessage:pe.error,errorCode:pe.errorCode,selectedDatabaseName:r||"",selectedSchemaName:o||"",selectedTableName:u||"",contextEntityLabels:pt});Te(Re,H.current)})(),()=>{be=!0}},[Ue,m,ce,Ae,ie,A,C,r,o,u,Te,xe,jt,$,Gt]);const lt=(s==null?void 0:s.trim())||"",Lt=v.useCallback((W="draft")=>{if(Ae)return;const Z=b.trim();if(!Z)return;const ee=W==="refine"&<?"refine":"draft",be=ee==="refine"?lt:"",je=lt,{runId:pe,runToken:Ve,chatSessionId:He}=oe();ce("inline_draft_started",pe,{attemptCount:0,hasTools:!1,finalOutcome:"drafting"}),fe(),Ue(),_(Z),S(""),E(ee),L(be),P(!1),j({status:"idle"}),Q.current+=1,xe([]),B(!0);const at=zr({request:Z,mode:ee,currentSql:je,selectedTableName:u||"",selectedSchemaName:o||"",selectedDatabaseName:r||""});Ce.current={sessionId:He,message:at,runToken:Ve}},[oe,Ue,lt,ce,Ae,b,fe,r,o,u,xe]),vt=v.useCallback(W=>{const Z=C.trim();Z&&(i(Z,W),W||B(!1))},[i,C]),it=C.trim().length>0,Je=["valid","invalid","error"].includes(F.status),yt=it&&Je,Ht=F.status==="invalid",Nt=F.status==="validating",Qt=it&&A.length>0&&A===b.trim(),st=lt.length>0,mt=b.length>0,Ct=Qt&&I==="draft",Mt=Qt&&I==="refine"&&y===lt,xt=D==="refine"&&!st?"draft":D,St=(xt==="refine"?Mt:Ct)?"Open composer preview":"Generate composer SQL",Wt=b.trim().length>0||A.trim().length>0||it||F.status!=="idle"||k.timelineSteps.length>0,wt=v.useCallback((W="draft")=>{if(Ae)return;if((W==="refine"?Mt:Ct)&&!R){fe(),B(!0);return}Lt(W)},[Ct,Mt,Lt,Ae,R,fe]),Ft=v.useCallback(()=>{fe(),B(!0)},[fe]),nt=v.useCallback(W=>{Le("cancelled"),N(W)},[Le]),Yt=v.useCallback(()=>{Ae||(Le("cancelled"),ge.current=!1,Q.current+=1,ve.current="",me.current=0,N(""),_(""),S(""),E("draft"),T("draft"),L(""),P(!1),j({status:"idle"}),Ue(),xe([]),De(W=>({...ms,runId:W.runId})))},[Le,Ue,Ae,xe,De]),Jt=v.useCallback(W=>{W||Le("cancelled"),B(W)},[Le]),Rt=k.timelineSteps.findIndex(W=>W===k.activeStep),Xt=k.phase==="self-healing"?"Fixing validation issue":k.phase==="validating"?"Validating SQL":k.activeStep||"Drafting SQL",ht=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:q,className:"relative flex h-7 min-w-[320px] flex-1 items-center",children:[e.jsx(n.Sparkles,{className:"pointer-events-none absolute left-2.5 top-1/2 h-3 w-3 -translate-y-1/2 text-muted-foreground",strokeWidth:1.75}),e.jsx(t.Input,{value:b,onChange:W=>nt(W.target.value),onFocus:Ft,onClick:Ft,onKeyDown:W=>{W.key==="Enter"&&(W.preventDefault(),wt(xt))},placeholder:"Ask in plain English — e.g. top 10 customers by profit last quarter",className:["h-7 rounded-[5px] border border-border/60 bg-background pl-7 text-[12px] shadow-none placeholder:text-muted-foreground/70 focus-visible:border-ring focus-visible:ring-0",mt?"pr-[56px]":"pr-9"].join(" ")}),e.jsxs(t.Popover,{open:R,onOpenChange:Jt,children:[e.jsx(t.PopoverAnchor,{asChild:!0,children:e.jsx("div",{className:"pointer-events-none absolute inset-0"})}),e.jsxs("div",{className:"absolute right-1 flex items-center gap-1",children:[mt&&e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"size-6 p-0",onClick:W=>{W.preventDefault(),Le("cancelled"),N("")},disabled:Ae,"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:W=>{W.preventDefault(),wt(xt)},disabled:Ae,"aria-label":St,title:St,children:e.jsx(Ne.SendHorizontal,{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:W=>{W.preventDefault()},onInteractOutside:W=>{var ee;const Z=W.target;Z&&((ee=q.current)!=null&&ee.contains(Z))&&W.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",{className:"flex min-w-0 flex-1 flex-wrap 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]",xt==="draft"?"bg-accent text-foreground":"text-muted-foreground hover:text-foreground"].join(" "),onClick:()=>{T("draft"),P(!1)},children:"Draft New"}),e.jsx(t.Button,{type:"button",variant:"ghost",className:["h-6 rounded-[4px] px-2 text-[12px]",xt==="refine"?"bg-accent text-foreground":"text-muted-foreground hover:text-foreground"].join(" "),onClick:()=>T("refine"),disabled:!st,children:"Refine"})]}),e.jsx(n.AssistantContextEntityControls,{mode:"full",compact:!0,inlineLayout:!0,inlineTriggerFirst:!0,triggerVariant:"outline",triggerIconOnly:!1,triggerLabel:"Context",onSelectionChange:ne})]}),e.jsxs("div",{className:"flex shrink-0 items-center",children:[Ae&&e.jsx(t.Button,{variant:"ghost",size:"xs",onClick:()=>{Le("stopped")},children:"Stop"}),!Ae&&e.jsx(t.Button,{variant:"ghost",size:"xs",onClick:Yt,disabled:!Wt,children:"Clear"})]})]}),k.timelineSteps.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[k.timelineSteps.map((W,Z)=>{const ee=W===k.activeStep&&["drafting","validating","self-healing"].includes(k.phase),be=!ee&&Rt>=0&&Z<Rt;return e.jsx("span",{className:["rounded-full border px-2 py-0.5 text-[11px]",ee?"border-foreground/30 bg-foreground/10 text-foreground":be?"border-border/60 bg-muted/20 text-muted-foreground":"border-border/50 bg-background text-muted-foreground/80"].join(" "),children:Ur(W,k.attempt)},`${W}-${Z}`)}),ht&&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]",ht.className].join(" "),children:ht.label})}),e.jsx(t.TooltipContent,{side:"top",align:"start",className:"max-w-[680px] whitespace-pre-wrap break-words text-xs",children:ht.detail})]})})]}),(Ae||k.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"}),Xt]}),Qe&&e.jsx("div",{className:"rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-xs text-destructive",children:tt}),I==="refine"&&y&&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:()=>P(W=>!W),children:M?"Hide base SQL":"View base SQL"})]}),M&&e.jsx("div",{className:"max-h-[120px] overflow-auto rounded-[5px] border border-border/60",children:e.jsx(t.CodeEditor,{value:y,onValueChange:()=>{},language:"sql",readOnly:!0,embedded:!0,wrapLines:!0,dense:!0,hideLineNumbers:!0,ariaLabel:"Base SQL"})})]}),yt?e.jsxs("div",{className:"space-y-1",children:[I==="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.CodeEditor,{value:C,onValueChange:()=>{},language:"sql",readOnly:!0,embedded:!0,wrapLines:!0,dense:!0,hideLineNumbers:!0,ariaLabel:"Drafted SQL"})})]}):it?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."}):!Ae&&e.jsx("div",{className:"rounded-[5px] border border-dashed border-border/70 px-3 py-2 text-[11px] text-muted-foreground",children:st?"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:Ae||!yt,onClick:()=>vt(!1),children:"Replace SQL"}),e.jsx(t.Button,{size:"xs",disabled:Ae||!yt||Nt||Ht,onClick:()=>vt(!0),children:"Replace & Run"})]})]})})]})]})}function Qr(){var Oe,Fe;const s=n.useQueryClient(),[a,r]=v.useState(!1),o=t.useEditorStore(X=>X.frame),u=t.useEditorStore(X=>X.card);t.useEditorStore(X=>X.isShowingVisual),t.useEditorStore(X=>X.selectedConnectionId),t.useEditorStore(X=>X.tempQueryData);const i=t.useEditorStore(X=>X.selectedDatabaseName);t.useEditorStore(X=>X.selectedDatamodelId);const l=t.useEditorStore(X=>X.selectedSchemaName);t.useEditorStore(X=>X.showAIDialog);const c=t.useEditorStore(X=>X.selectedTableName),d=t.useDashboardStore(X=>{var ge,Ce;return((Ce=(ge=X.dashboard)==null?void 0:ge.filters)==null?void 0:Ce.length)??0}),h=t.useEditorStore(X=>X.inlineFilterValuesMap[(u==null?void 0:u.id)??""]),x=v.useMemo(()=>n.findCustomVisualConfigCard(o,u),[o,u]),{manifest:g}=n.useCustomVisual(((Oe=x==null?void 0:x.customCardPreferences)==null?void 0:Oe.url)||""),p=v.useMemo(()=>{var X;return(X=g==null?void 0:g.visuals)==null?void 0:X.find(ge=>{var Ce;return ge.name===((Ce=x==null?void 0:x.customCardPreferences)==null?void 0:Ce.componentName)})},[g,(Fe=x==null?void 0:x.customCardPreferences)==null?void 0:Fe.componentName]),m=n.resolveMultiInputType(x,p),f=v.useMemo(()=>n.getCustomVisualInputCards({frame:o,configCard:x,isMultiInputVisual:m==="multiple"}),[o,x,m]),w=v.useMemo(()=>{const X=f.findIndex(ge=>(ge==null?void 0:ge.id)===(u==null?void 0:u.id));return X<0?-1:n.getSlotIndexForCard(u,X)},[f,u]),b=v.useMemo(()=>!x||m!=="multiple"||w<0?u.type:n.getEffectiveCardTypeForSlot(u,w,p==null?void 0:p.slots)??u.type,[x,m,w,u,p==null?void 0:p.slots]),N=v.useMemo(()=>b!==u.type?{...u,type:b}:u,[u,b]),A=v.useMemo(()=>d===0?null:_r(u==null?void 0:u.sql),[u==null?void 0:u.sql,d]),_=v.useRef(!0),{setCardCustomCfg:C,setQueryResultColumns:S,setCardSql:I,setTempQueryData:E,setPythonStdOut:D,setCardPreferences:T,setCardType:y,setCardPython:L,setShowAIDialog:M,setCard:P,updateCardInFrame:F}=t.useEditorActions();t.useEditorStore(X=>X.onSave),t.useEditorStore(X=>X.onClose),t.useEditorStore(X=>X.actions.setSqlGen);const j=t.useEditorStore(X=>X.runSql),k=t.useEditorStore(X=>X.actions.setRunSql),O=t.useEditorStore(X=>X.actions.setIsSqlRunning),{data:R,isLoading:B,isFetching:z,isSuccess:V,isError:q,error:U,errorSql:G,queryKey:Q,refetch:Y,errorMessage:H}=n.useEditorCardQuery(N),se=v.useRef(Q);se.current=Q,v.useEffect(()=>{if(R)if(R.rowLimitExceeded&&n.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),D((R==null?void 0:R.output)||""),R.records.length>0){const{keys:X}=n.getKeys(R.records);S(X)}else S([])},[R,S,D]),v.useEffect(()=>{(B||z)&&(O(!0),S([])),(q||V)&&O(!1),q&&(S([]),D(""))},[B,z,R,D,q,V,O,S,U]),v.useEffect(()=>{j&&(s.getQueryData(Q)||Y(),k(!1))},[j,Y,k,Q,s]);const ue=v.useRef(Y);ue.current=Y,v.useEffect(()=>{if(_.current){_.current=!1;return}ue.current()},[h]);function ae(X,ge){I(X),ge&&k(!0)}function me(){return e.jsxs(n.ResizablePanelGroup,{className:"flex grow gap-2 px-4",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(n.ResizablePanel,{id:"1",order:1,defaultSize:a?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-full overflow-hidden rounded-control border border-border bg-background",children:e.jsx(Mr,{})}),a&&e.jsx("code",{className:"absolute right-3 top-2 text-[10px] uppercase tracking-[0.08em] text-muted-foreground/70",children:"sql"})]}),a&&e.jsxs(e.Fragment,{children:[e.jsxs(n.PanelResizeHandle,{className:"group/divider relative my-1 flex h-6 w-full shrink-0 cursor-row-resize items-center gap-3 px-1 outline-none",children:[e.jsx("span",{className:"h-px flex-1 bg-border transition-colors group-hover/divider:bg-foreground/30"}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:[e.jsx(n.ArrowDown,{className:"h-3 w-3",strokeWidth:1.75}),"Post-process with Python"]}),e.jsx("span",{className:"h-px flex-1 bg-border transition-colors group-hover/divider:bg-foreground/30"}),e.jsx("button",{type:"button","aria-label":"Close Python editor",onClick:X=>{X.stopPropagation(),r(!1)},onPointerDown:X=>X.stopPropagation(),className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-control text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:e.jsx(t.X,{className:"h-3 w-3",strokeWidth:1.75})})]}),e.jsx(n.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:e.jsxs("div",{id:"python-container",className:"relative flex w-full flex-col overflow-hidden rounded-control border border-border bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border bg-muted/30 px-3 py-1.5 text-[11px] text-muted-foreground",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"rounded-control bg-background px-1.5 py-0.5 font-mono text-[10px] text-foreground/80",children:"Py"}),e.jsx("code",{className:"truncate font-mono text-[11px] text-foreground/80",children:"def process(df) → df"}),e.jsx("span",{className:"hidden truncate text-muted-foreground/80 sm:inline",children:"Runs after SQL · receives a DataFrame"})]}),e.jsx("span",{className:"shrink-0 font-mono text-[10px] uppercase tracking-[0.08em] text-muted-foreground/70",children:"Python 3.11"})]}),e.jsx("div",{className:"relative flex flex-1",children:e.jsx(Rr,{})})]})})]})]})}function ve(){return e.jsxs("div",{role:"editor-controls",className:"flex w-full flex-wrap items-center gap-2 px-4 pb-2 pt-3",children:[A&&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(n.Filter,{className:"h-3 w-3 shrink-0"}),e.jsxs("span",{className:"min-w-0 truncate",children:["Not subscribed to dashboard filters. Add"," ",e.jsx("button",{type:"button",title:"Click to copy",onClick:()=>{var X;typeof navigator>"u"||!((X=navigator.clipboard)!=null&&X.writeText)||navigator.clipboard.writeText(A.helper).then(()=>n.ue.success("Copied to clipboard")).catch(()=>n.ue.error("Failed to copy"))},className:"cursor-pointer rounded-[4px] bg-muted px-1 py-0.5 font-mono text-[10px] text-foreground transition-colors hover:bg-muted-foreground/20",children:A.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:B||z,onClick:()=>{bt.flushPendingEditorDrafts(),setTimeout(()=>{s.removeQueries({queryKey:se.current,exact:!0}),k(!0)},0)},className:"shrink-0",size:"xs",children:[B||z?e.jsx(t.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(n.Play,{className:"h-3.5 w-3.5"}),"Run"]}),e.jsx(Ne.EditorClearButton,{}),e.jsxs(n.Toggle,{pressed:a,onPressedChange:X=>r(X),title:a?"Remove Python post-processor":"Add a Python step to post-process the SQL result",className:"h-7 gap-1.5 rounded-control px-2.5 text-[12px]",size:"sm",variant:"outline",children:[e.jsx("span",{className:"inline-flex h-3 w-3 items-center justify-center rounded-[2px] bg-muted font-mono text-[8px] font-bold text-muted-foreground",children:"Py"}),"Python",a?e.jsx(t.Check,{className:"h-3 w-3",strokeWidth:1.75}):e.jsx(n.Plus,{className:"h-3 w-3 text-muted-foreground",strokeWidth:1.75})]}),e.jsx(Hr,{currentSql:u==null?void 0:u.sql,currentPython:u==null?void 0:u.python,selectedDatabaseName:i,selectedSchemaName:l,selectedTableName:c,onApplySql:ae,onOpenFullAssistant:()=>M(!0)})]})]})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsxs("div",{className:"flex shrink-0 flex-col gap-1.5 px-4 pb-3 pt-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(n.EditableText,{value:u.title,onSave:X=>P({...u,title:X}),isEditable:!0,placeholder:"Add title",displayClassName:"text-[17px] font-semibold leading-tight tracking-[-0.005em]",inputClassName:"text-[17px] font-semibold leading-tight tracking-[-0.005em]"})}),e.jsx(n.InfoHover,{card:u})]}),e.jsx(n.EditableText,{value:(u.description||"").trim(),onSave:X=>P({...u,description:X.trim()}),isEditable:!0,placeholder:"Add description",displayClassName:"text-[12px] leading-snug text-muted-foreground",inputClassName:"text-[12px] leading-snug"})]}),e.jsx("div",{className:"relative flex grow overflow-y-scroll",children:me()}),ve()]})}function Wr(s,a){var i;let r=0,o=0;const u=Math.min(s.length,50);for(let l=0;l<u;l++){const c=(i=s[l])==null?void 0:i[a];if(!(c==null||c==="")){if(o++,typeof c=="number"||typeof c=="bigint")r++;else if(typeof c=="boolean")return"boolean"}}return o===0?"null":r/o>.7?"number":"text"}function Yr(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 Jr({data:s,card:a,paginationMetadata:r,onPaginationChange:o,onPageSizePreferenceChange:u,onSortChange:i,isLoading:l}){var T,y,L,M,P,F;const c=v.useMemo(()=>Object.keys(s[0]??{}),[s]),d=a.sql&&!((y=(T=a.preferences)==null?void 0:T.tablePrefs)!=null&&y.enableDevModePagination)?(M=(L=a.preferences)==null?void 0:L.tablePrefs)==null?void 0:M.pageSize:void 0,h=v.useMemo(()=>{var j;return n.sortByColumnsToSortState((j=a.config)==null?void 0:j.sortByColumns)},[(P=a.config)==null?void 0:P.sortByColumns]),{canSort:x,canUseLocalSorting:g,handlePaginationChange:p,handleSortChange:m,pagination:f,paginationMode:w,sorting:b}=n.useTableQueryState({card:a,dataLength:s.length,onPaginationChange:o,onSortChange:i,pageSize:d,paginationMetadata:r,sortState:h}),N=v.useMemo(()=>b.filter(j=>c.includes(j.id)),[b,c]),A=v.useMemo(()=>{const j={};for(const k of c)j[k]=Wr(s,k);return j},[c,s]),_=v.useMemo(()=>c.map(j=>{const O=A[j]==="number";return{accessorKey:j,enableSorting:x,header:({column:R})=>{const B=R.getIsSorted();return e.jsxs("div",{className:t.cn("flex min-w-0 select-none items-center gap-1.5 transition-colors",R.getCanSort()&&"cursor-pointer hover:text-foreground",O&&"justify-end"),onClick:()=>R.getCanSort()&&R.toggleSorting(R.getIsSorted()==="asc"),children:[e.jsx("span",{className:"min-w-0 truncate",title:j,children:j}),B==="asc"?e.jsx(n.ArrowUpIcon,{className:"h-3.5 w-3.5 shrink-0 text-foreground"}):B==="desc"?e.jsx(n.ArrowDownIcon,{className:"h-3.5 w-3.5 shrink-0 text-foreground"}):R.getCanSort()?e.jsx(Hn.ChevronsUpDown,{className:"h-3 w-3 shrink-0 opacity-0 transition-opacity group-hover/header:opacity-50"}):null]})},cell:({getValue:R})=>{const B=R(),z=B===null;return e.jsx("div",{className:t.cn("overflow-hidden truncate whitespace-nowrap leading-5",O&&"text-right tabular-nums",z&&"text-muted-foreground/50 italic"),children:Yr(B)})}}}),[x,A,c]),C=Math.max(_.length,1),S=n.useReactTable({data:s,columns:_,getCoreRowModel:n.getCoreRowModel(),getPaginationRowModel:w==="client"?n.getPaginationRowModel():void 0,onSortingChange:m,getSortedRowModel:g?n.getSortedRowModel():void 0,onPaginationChange:w==="disabled"?void 0:p,manualPagination:w==="server"||w==="disabled",manualSorting:!g,pageCount:w==="server"&&r?r.pageCount:void 0,state:{sorting:N,pagination:f}}),I=w==="server"&&r?r.totalCount:s.length,E=w!=="disabled"&&(w==="server"||I>10),D=c.length>0?`${c.length*144}px`:"100%";return e.jsxs("div",{className:"relative flex h-full min-h-0 w-full 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(n.CustomScrollArea,{className:"relative min-h-0 w-full grow overflow-auto rounded-none border-0 bg-transparent text-foreground",children:[e.jsxs("table",{className:"w-full text-sm [border-spacing:0]",style:{minWidth:D},children:[e.jsx(n.TableHeader,{className:"sticky top-0 z-10 bg-muted [&_tr]:border-b-0",children:S.getHeaderGroups().map(j=>e.jsx(n.TableRow,{className:"border-b-0 hover:bg-transparent",children:j.headers.map(k=>{const R=A[k.id]==="number";return e.jsx(n.TableHead,{className:t.cn("group/header relative h-auto border-b border-transparent bg-muted/95 px-4 py-2 align-middle text-[10px] font-medium tracking-[0.08em] text-muted-foreground after:absolute after:bottom-0 after:left-0 after:right-0 after:h-px after:bg-border/60",R&&"text-right"),children:k.isPlaceholder?null:n.flexRender(k.column.columnDef.header,k.getContext())},k.id)})},j.id))}),e.jsx(n.TableBody,{children:(F=S.getRowModel().rows)!=null&&F.length?S.getRowModel().rows.map(j=>e.jsx(n.TableRow,{className:"border-b border-border/40 transition-colors","data-state":j.getIsSelected()&&"selected",children:j.getVisibleCells().map(k=>{const R=A[k.column.id]==="number";return e.jsx(n.TableCell,{className:t.cn("overflow-hidden px-4 py-2 text-[13px] text-foreground/90",R&&"text-right"),children:n.flexRender(k.column.columnDef.cell,k.getContext())},k.id)})},j.id)):e.jsx(n.TableRow,{children:e.jsx(n.TableCell,{colSpan:C,className:"h-auto py-12 text-center text-[13px] text-muted-foreground",children:"No results."})})})]}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]}),e.jsx("div",{className:"shrink-0 border-t border-border/60 bg-background text-[13px]",children:E?e.jsx(n.DataTablePagination,{totalColumns:c.length,pageCount:w==="server"&&r?r.pageCount:S.getPageCount(),pageIndex:S.getState().pagination.pageIndex,pageSize:S.getState().pagination.pageSize,rowCount:I,selectedRowCount:0,setPageIndex:S.setPageIndex,setPageSize:S.setPageSize,canPreviousPage:w==="server"&&r?r.hasPrevPage:S.getCanPreviousPage(),canNextPage:w==="server"&&r?r.hasNextPage:S.getCanNextPage(),previousPage:S.previousPage,nextPage:S.nextPage,onPageSizePreferenceChange:u,onClearSelection:()=>{},paginationMode:w,showExport:!1}):e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-[11px] tabular-nums text-muted-foreground",children:[I.toLocaleString()," ",I===1?"row":"rows"," · ",c.length," ",c.length===1?"column":"columns"]}),N.length>0&&e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["Sorted by"," ",e.jsx("span",{className:"font-medium text-foreground/70",children:N[0].id})," ",N[0].desc?"↓":"↑"]})]})})]})}const Mn=[{value:"table",label:"Table"},{value:"aggregateTable",label:"Aggregate"},{value:"pivotTable",label:"Pivot"},{value:"detailTable",label:"Detail"}];function Xr({className:s}){const a=t.useEditorStore(m=>m.card),r=t.useEditorStore(m=>m.frame),o=t.useEditorStore(m=>m.editorContext),u=Ne.useEffectiveEditorCardType(),{setCard:i,updateCardInFrame:l}=t.useEditorActions(),c=(o==null?void 0:o.type)==="documentSection"?Mn.filter(m=>["table","pivotTable"].includes(m.value)):Mn,d=["table","aggregateTable","pivotTable","detailTable"].includes(u),h=t.hasValidCardConfig(a.config),x=n.isCustomVisualConfigCard(a,r.cards);if(!d||!h||x)return e.jsx("div",{"aria-hidden":"true",className:t.cn("invisible flex items-center gap-5",s),children:e.jsx("span",{className:"-mb-px flex h-9 items-center border-b-2 border-transparent text-[12px]",children:"Placeholder"})});const g=m=>{if(m===u||x)return;const f=m,w=a.config??{},b=p(u,f,w),N={...a,type:f,config:b};i(N),l(N)},p=(m,f,w)=>{var N;if(m===f)return w;if(f==="detailTable"){const A=I=>I==null?void 0:I.toLowerCase().replace(/\s+/g,"").trim(),_=(I,E)=>{const D=[A(I.label),A(I.qualifiedFieldName),A(I.name)].filter(Boolean),T=[A(E.label),A(E.qualifiedFieldName),A(E.name)].filter(Boolean);return D.some(y=>T.includes(y))},C=(w.groupByColumns||[]).map(I=>({...I,role:"detail"})),S=((N=w.sortByColumns)==null?void 0:N.filter(I=>C.some(E=>_(I,E))))??[];return{...w,detailTableBackup:{groupByColumns:w.groupByColumns,metricColumns:w.metricColumns,pivotByColumns:w.pivotByColumns,sortByColumns:w.sortByColumns,rowAggregates:w.rowAggregates,columnAggregates:w.columnAggregates,comparisonType:w.comparisonType},detailColumns:C,groupByColumns:[],metricColumns:[],pivotByColumns:[],sortByColumns:S,rowAggregates:[],columnAggregates:[],comparisonType:"none"}}let b=w;if(m==="detailTable")if(w.detailTableBackup)b={...w,...w.detailTableBackup,detailColumns:[],detailTableBackup:void 0};else{const A=(w.detailColumns||[]).map(_=>({..._,role:"groupby"}));b={...w,groupByColumns:A,detailColumns:[]}}return f==="aggregateTable"?{...b,pivotByColumns:[]}:b};return e.jsx("div",{role:"tablist",className:t.cn("flex items-center gap-5",s),children:c.map(m=>{const f=u===m.value;return e.jsx("button",{type:"button",role:"tab","aria-selected":f,onClick:()=>g(m.value),className:t.cn("-mb-px flex h-9 items-center border-b-2 text-[12px] transition-colors",f?"border-foreground font-medium text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),children:m.label},m.value)})})}const Fn="text-[11px] text-muted-foreground underline-offset-2 hover:text-foreground hover:underline";function ns({error:s,errorSql:a,errorTitle:r="Unable to load data",onOpenInEditor:o,onDebugWithAssistant:u,onSendFeedback:i,showFeedbackButton:l=!0,className:c}){const[d,h]=v.useState(!1),p=!!u||!!(o&&a);return e.jsxs("div",{className:t.cn("w-full space-y-3 rounded-[6px] border border-border/60 bg-card p-4",c),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.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:r})]}),e.jsxs("div",{className:"relative rounded-[5px] border border-border/60 bg-background",children:[e.jsx(n.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})})]}),p&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[u&&e.jsxs(t.Button,{variant:"outline",size:"xs",onClick:u,children:[e.jsx(Za,{className:"h-3.5 w-3.5"}),"Debug with Assistant"]}),o&&a&&e.jsxs(t.Button,{variant:"outline",size:"xs",onClick:o,children:[e.jsx(Yn,{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:()=>h(m=>!m),className:Fn,children:d?"Hide query details":"Show query details"}),l&&i&&e.jsx("button",{type:"button",onClick:i,className:Fn,children:"Report this issue"})]}),a&&e.jsx(n.Collapsible,{open:d,onOpenChange:h,children:e.jsxs(n.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(n.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(n.CodeHighlighter,{code:a,language:"sql"})})]})})]})}function Ds(s,a){const r=t.useEditorStore(h=>h.card),o=t.useEditorStore(h=>h.isDevMode),{switchEditorMode:u,setRunSql:i,runAssistant:l}=t.useEditorActions();return{isDevMode:o,handleOpenInEditor:o?void 0:()=>{const h=a||r.sql||r.python||"";u("dev",{sqlToLoad:h}),setTimeout(()=>{i(!0)},100)},handleDebugWithAssistant:o?()=>{const h=`Can you help me debug this query?
|
|
167
|
-
|
|
168
|
-
Error:
|
|
169
|
-
|
|
170
|
-
${s}
|
|
171
|
-
|
|
172
|
-
Error SQL:
|
|
173
|
-
|
|
174
|
-
${a||r.sql||r.python}
|
|
175
|
-
|
|
176
|
-
`;l(h)}:void 0}}function na({className:s,style:a,...r}){var ce,Te,ke,ze,re;const o=t.useEditorStore(te=>te.card),u=n.useDashboardAppearance(),l=t.useEditorStore(te=>te.isDevMode)?!1:((ce=o.customCardPreferences)==null?void 0:ce.showCardHeader)??!0,c=((ke=(Te=o.preferences)==null?void 0:Te.displayOptions)==null?void 0:ke.showInlineFilterBar)??!0,d=t.useEditorStore(te=>te.frame),h=t.useEditorStore(te=>te.inlineFilterValuesMap[o.id]),x=t.useDashboardStore(te=>te.dashboard.filters),g=t.useDashboardStore(te=>te.selectedSheetId),[p,m]=v.useState(!1),{currentUser:f}=n.useCurrentUserInfo(),{tokenProps:w}=v.useContext(n.SemaphorContext),b=t.useEditorStore(te=>te.actions.setRunSql),N=t.useEditorStore(te=>te.actions.setCardInlineFilterValue),A=t.useEditorStore(te=>te.actions.removeCardInlineFilterValue),{updateFilter:_}=t.useDashboardActions(),C=x==null?void 0:x.find(te=>te.id===d.filterId),S=v.useMemo(()=>n.findCustomVisualConfigCard(d,o),[d,o]),{manifest:I}=n.useCustomVisual(((ze=S==null?void 0:S.customCardPreferences)==null?void 0:ze.url)||""),E=v.useMemo(()=>{var te;return(te=I==null?void 0:I.visuals)==null?void 0:te.find(xe=>{var ye;return xe.name===((ye=S==null?void 0:S.customCardPreferences)==null?void 0:ye.componentName)})},[I,(re=S==null?void 0:S.customCardPreferences)==null?void 0:re.componentName]),D=n.resolveMultiInputType(S,E),T=v.useMemo(()=>n.getCustomVisualInputCards({frame:d,configCard:S,isMultiInputVisual:D==="multiple"}),[d,S,D]),y=v.useMemo(()=>{const te=T.findIndex(xe=>(xe==null?void 0:xe.id)===(o==null?void 0:o.id));return te<0?-1:n.getSlotIndexForCard(o,te)},[T,o]),L=v.useMemo(()=>!S||D!=="multiple"||y<0?o.type:n.getEffectiveCardTypeForSlot(o,y,E==null?void 0:E.slots)??o.type,[S,D,y,o,E==null?void 0:E.slots]),M=L??o.type,P=v.useMemo(()=>M===o.type?o:{...o,type:M},[o,M]),F=P.type==="table"||P.type==="matrixTable"||P.type==="pivotTable"||P.type==="aggregateTable"||P.type==="detailTable",j=v.useMemo(()=>L!==o.type?{...o,type:L}:o,[o,L]),{data:k,isLoading:O,isFetching:R,errorMessage:B,errorSql:z,pagination:V}=n.useEditorCardQuery(j),q=M==="matrixTable"&&n.hasMatrixResultData(k),U=n.getMatrixVisualLoadingState({data:k,isLoading:O,isFetching:R}),{handleOpenInEditor:G,handleDebugWithAssistant:Q}=Ds(B,z||o.sql||o.python),Y=v.useMemo(()=>(k==null?void 0:k.records)||[],[k==null?void 0:k.records]),{setCard:H,updateCardInFrame:se}=t.useEditorActions(),{data:ue}=n.useTopoJson(P),ae=P.id,me=P.config,ve=P.interactionConfig,Oe=P.customCfg,Fe=P.preferences,X=P.queryConfig,ge=!!P.sql,Ce=k==null?void 0:k.records,Pe=v.useMemo(()=>({id:ae,type:M,config:me,interactionConfig:ve,sql:ge?"__editor_sql__":""}),[ae,M,me,ve,ge]),_e=v.useMemo(()=>{var te;return M!=="pivotTable"||!((te=k==null?void 0:k.records)!=null&&te.length)?null:{records:k.records,columnSubtotalMeta:k.columnSubtotalMeta,subtotalColumns:k.subtotalColumns||[],pivotSchema:k.pivotSchema||[],groupByColumns:k.groupByColumns}},[M,k==null?void 0:k.records,k==null?void 0:k.columnSubtotalMeta,k==null?void 0:k.subtotalColumns,k==null?void 0:k.pivotSchema,k==null?void 0:k.groupByColumns]),le=n.usePivotTableConfig(P,_e),De=()=>{m(!0)},Se=v.useMemo(()=>{const te=typeof window<"u"?window.location.href:"",xe=typeof navigator<"u"?navigator.userAgent:"",ye=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:n.FeedbackCategory.QUERY_GENERATION,user:f,tokenContext:w,systemState:{cardConfig:o.config,dataSource:o.dataSource,dashboardFilters:x,errorMessage:B||void 0,errorSql:z||o.sql||o.python,generatedSql:z||o.sql},metadata:{url:te,userAgent:xe,timestamp:new Date().toISOString(),viewport:ye}}},[f,w,o,x,B,z]),ie=(te,xe)=>{var Ee,qe;const ye={...o,paginationConfig:{page:te+1,pageSize:xe}};H(ye),se(ye),o.sql&&((qe=(Ee=o.preferences)==null?void 0:Ee.tablePrefs)!=null&&qe.enableDevModePagination)&&b(!0)},$=te=>{var Ee,qe,Ie,Qe,Ue;const xe=n.sortStateToSortByColumns(te,(Ee=o.config)==null?void 0:Ee.metricColumns,(qe=o.config)==null?void 0:qe.groupByColumns,(Ie=o.config)==null?void 0:Ie.detailColumns),ye={...o,config:{...o.config||{},sortByColumns:xe}};H(ye),se(ye),o.sql&&((Ue=(Qe=o.preferences)==null?void 0:Qe.tablePrefs)!=null&&Ue.enableDevModePagination)&&b(!0)},oe=v.useMemo(()=>!ae||!Ce?null:n.createChartConfig({card:Pe,data:Ce,cardType:M,queryConfig:X,customCfg:Oe,preferences:Fe,topoJson:ue}),[Pe,ae,Oe,Fe,X,Ce,M,ue]);function fe(te){return e.jsx(n.ErrorBoundary,{FallbackComponent:n.FallbackVisual,children:e.jsx(n.EditorCustomVisual,{card:te})})}function ne(){var te;if(k!=null&&k.records&&(k==null?void 0:k.records.length)===0&&!O&&!R&&!q)return B?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(ns,{error:B,errorSql:z||o.sql||o.python,onOpenInEditor:G,onDebugWithAssistant:Q,onSendFeedback:De,showFeedbackButton:!0})}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(n.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((O||R)&&(!(k!=null&&k.records)||k.records.length===0)&&!q)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(n.TableSkeleton,{})}):e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!P.id)return null;if(M==="custom")return fe(o);if(!["table","matrixTable","pivotTable","aggregateTable","detailTable","custom"].includes(M)&&oe)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:O||R?e.jsx(e.Fragment,{}):e.jsx(n.ChartJsVisual,{cfg:oe})});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(n.TableVisual,{card:P,data:Y,totalsByColumnId:k==null?void 0:k.tableTotalsByColumnId,comparisonMetadata:(te=k==null?void 0:k.metadata)==null?void 0:te.comparisonMetadata,paginationMetadata:V,onPaginationChange:ie,onSortChange:$,isLoading:O||R})});if(M==="matrixTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(n.MatrixTableVisual,{result:k==null?void 0:k.matrixResult,isLoading:U})});if(M==="pivotTable"&&le)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(n.PivotTableTanstack,{card:P,data:le.data,options:le.options,onAggregationChange:xe=>{const ye=n.handleAggregationChange(xe,o.config),Ee={...o,config:ye};H(Ee),se(Ee)},onAggregationLabelChange:xe=>{const ye=n.handleAggregationLabelChange(xe,o.config),Ee={...o,config:ye};H(Ee),se(Ee)}})});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(n.AggregateTable,{card:P,data:(k==null?void 0:k.records)||[],groupByColumns:k==null?void 0:k.groupByColumns,pivotSchema:k==null?void 0:k.pivotSchema,paginationMetadata:V,onPaginationChange:ie,onAggregationChange:xe=>{const ye=n.handleAggregationChange(xe,o.config),Ee={...o,config:ye};H(Ee),se(Ee)},isLoading:O||R})})}return e.jsxs(n.Card,{role:"editor-visual-card",className:t.cn("relative flex h-full flex-col rounded-none bg-card text-card-foreground",s),style:{...u.cardFrameStyle,...a},...r,children:[(O||R)&&(k==null?void 0:k.records)&&k.records.length>0&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),l&&e.jsxs(n.CardHeader,{className:t.cn("flex flex-row items-start justify-between gap-4 px-4 pb-3 pt-3"),style:u.cardGutterStyle,children:[e.jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.CardTitle,{className:"min-w-0 text-[17px] font-semibold leading-tight tracking-[-0.005em]",children:e.jsx(n.EditableText,{value:o.title,onSave:te=>H({...o,title:te}),isEditable:!0,placeholder:"Add title",displayClassName:"text-[17px] font-semibold leading-tight tracking-[-0.005em]",inputClassName:"text-[17px] font-semibold leading-tight tracking-[-0.005em]"})}),e.jsx(n.InfoHover,{card:o}),e.jsx(Ne.VisualBadge,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(Xr,{})})]}),e.jsx("div",{className:"min-w-0",children:e.jsx(n.EditableText,{value:(o.description||"").trim(),onSave:te=>H({...o,description:te.trim()}),isEditable:!0,placeholder:"Add description",displayClassName:"text-[12px] leading-snug text-muted-foreground",inputClassName:"text-[12px] leading-snug"})})]}),C&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Label,{className:"my-1",children:e.jsx(n.EditableText,{value:C.title||C.column,onSave:te=>_({...C,title:te}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(n.FilterComponent,{filter:C})]})]}),c&&o.inlineFilters&&o.inlineFilters.length>0&&e.jsx("div",{className:"px-4 pb-2",style:u.cardGutterStyle,children:e.jsx(n.InlineFilterBar,{card:o,sheetId:g||"",inlineFilterValues:h,setInlineFilterValue:te=>N(o.id,te),removeInlineFilterValue:te=>A(o.id,te)})}),e.jsxs(n.CardContent,{className:t.cn("flex min-h-0 grow flex-col",F?"p-0 [&_.data-table-scroll-container]:border-0 [&_.data-table-scroll-container]:bg-transparent":"px-4"),style:F?void 0:u.cardGutterStyle,children:[e.jsx("div",{className:"min-h-0 flex-1 grow basis-0",children:ne()}),n.isCardSummaryVisibleOnCard(P)&&e.jsx("div",{className:t.cn("pt-3",F&&"px-4"),children:e.jsx(n.CardSummary,{card:P,mode:"editor"})})]}),e.jsx(n.FeedbackDialog,{open:p,onOpenChange:m,feedbackData:Se,showDebugInfo:!0})]})}const xs=({language:s,value:a,onChange:r,readonly:o})=>e.jsx(t.CodeEditor,{className:"h-full w-full text-xs",language:s,value:a,onValueChange:r,readOnly:o,embedded:!0}),Zr=()=>e.jsxs(n.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(n.DialogTitle,{children:"Customize Card"})}),e.jsxs(n.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."})]})]}),eo=({customCode:s,cardCustomCfgString:a,mergedConfig:r,onConfigChange:o,onCodeChange:u})=>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(xs,{language:"json",value:r,onChange:o})}),e.jsx(t.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(xs,{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(xs,{language:"javascript",value:s,onChange:u})})]}),to=({error:s,hasCardCustomConfig:a,onReset:r,onApply:o,onClose:u})=>e.jsxs(n.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:r,variant:"outline",children:"Reset"}),e.jsx(t.Button,{onClick:o,variant:"outline",children:"Apply"}),e.jsx(t.Button,{onClick:u,variant:"outline",children:"Close"})]});function so({triggerVariant:s="icon",className:a,label:r="Customize Visual"}={}){const[o,u]=v.useState(!1),[i,l]=v.useState(""),[c,d]=v.useState(""),[h,x]=v.useState(""),[g,p]=v.useState(""),m=t.useEditorStore(y=>y.card),f=Ne.useEffectiveEditorCardType(),w=t.useEditorStore(y=>y.card.customCfg),b=w?JSON.stringify(w,null,2):"",N=v.useMemo(()=>f!==m.type?{...m,type:f}:m,[m,f]),{data:A}=n.useEditorCardQuery(N),{data:_}=n.useTopoJson(m),{setCardCustomCfg:C,setCustomVisualCode:S}=t.useEditorActions(),I=y=>{var L,M;return JSON.stringify({...y,data:{...y.data,datasets:(M=(L=y.data)==null?void 0:L.datasets)==null?void 0:M.map(P=>({...P,data:[]}))}},null,2)},E=()=>{var L,M;if(!((L=A==null?void 0:A.records)!=null&&L.length))return;const y=n.createChartConfig({card:m,data:A.records,cardType:m.type,queryConfig:m.queryConfig,preferences:m.preferences,topoJson:_});if(y){l(I(y)),x(((M=m.preferences)==null?void 0:M.customVisualCode)||"");const P=n.merge(y,w);d(I(P))}},D=()=>{try{if(h&&S(h),c){const y=JSON.parse(c),L=n.getObjectDiff(JSON.parse(i),y);C(L),p("")}}catch{p("Invalid JSON configuration")}},T=Object.keys(w||{}).length===0;return e.jsxs(n.Dialog,{open:o,onOpenChange:u,children:[e.jsx(n.DialogTrigger,{asChild:!0,children:s==="menu"?e.jsxs(t.Button,{variant:"ghost",onClick:E,className:t.cn("h-7 w-full justify-start gap-2 px-2 text-[13px] font-normal",T?"":"text-green-600 hover:text-green-700",a),children:[e.jsx(n.Settings,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:r})]}):e.jsx(n.IconButton,{tooltip:"Customize Visual",onClick:E,className:t.cn(T?"":"text-green-600 hover:text-green-700",a),children:e.jsx(n.Settings,{className:"h-4 w-4"})})}),e.jsxs(n.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(Zr,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(n.ErrorBoundary,{FallbackComponent:n.FallbackVisual,children:e.jsx(na,{className:"w-1/2 rounded shadow-none"})}),e.jsx(eo,{customCode:h,cardCustomCfgString:b,mergedConfig:c,onConfigChange:y=>d(y??""),onCodeChange:y=>x(y??"")})]}),e.jsx(to,{error:g,hasCardCustomConfig:!!w,onReset:()=>{d(i),C(null)},onApply:D,onClose:()=>u(!1)})]})]})}function no(s){let a=0;for(let o=0;o<s.length;o++)a=s.charCodeAt(o)+((a<<5)-a);return`hsl(${Math.abs(a%360)}, 65%, 45%)`}function ao(s){const a=s.trim().split(/\s+/);return a.length>1?(a[0][0]+a[1][0]).toUpperCase():s.slice(0,2).toUpperCase()}function ks({chartType:s,chartName:a,isCustom:r=!1,className:o="h-6 w-6"}){if(!r&&s)return n.getChartIconByType(s,o);const u=n.getAutoDetectedChartIcon(a);if(u)return v.cloneElement(u,{className:o});const i=ao(a),l=no(a);return e.jsx("div",{className:t.cn("flex items-center justify-center rounded text-white font-semibold text-xs",o),style:{backgroundColor:l},children:i})}function ro({isStarred:s,onClick:a,className:r}){const o=u=>{u.stopPropagation(),u.preventDefault(),a(u)};return e.jsx("button",{type:"button",onClick:o,className:t.cn("flex items-center justify-center rounded-control p-0.5 transition-all","hover:bg-muted/80",r),"aria-label":s?"Remove from favorites":"Add to favorites",children:e.jsx(n.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 Rn({chartType:s,chartName:a,isCustom:r=!1,pluginName:o,isStarred:u,showStar:i=!0,isSelected:l=!1,onSelect:c,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",u?"opacity-100":"opacity-0 group-focus-within:opacity-100 group-hover:opacity-100"),children:e.jsx(ro,{isStarred:u,onClick:()=>d()})}),r&&o&&e.jsx("div",{className:"absolute right-1 top-1 z-10",children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center justify-center",children:e.jsx(t.Info,{className:"h-3 w-3 text-muted-foreground"})})}),e.jsx(t.TooltipContent,{side:"top",children:o})]})}),e.jsxs("button",{type:"button",onClick:c,"aria-pressed":l,className:t.cn("flex w-full flex-col items-center justify-center gap-1.5 rounded-control border border-input bg-background px-2 py-2.5 transition-colors","hover:border-foreground/30 hover:bg-muted/40",l&&"border-foreground/50 bg-muted/50 hover:border-foreground/50"),children:[e.jsx(ks,{chartType:s,chartName:a,isCustom:r,className:"h-4 w-4 text-foreground/80"}),e.jsx("span",{title:a,className:"line-clamp-2 text-center text-[11px] text-foreground/80",children:a})]})]})}function aa(s,a){return s==="matrixTable"?!a.isDevMode:!0}function Kt(s,a){return s==="matrixTable"?!1:aa(s,a)}const oo=[{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"},{id:"matrixTable",name:"Matrix Table"}];function lo(s){return oo.filter(a=>aa(a.id,s))}function ra({onChartSelect:s,onClose:a}){const[r,o]=v.useState(""),{starredCharts:u,isStarred:i,toggleStar:l}=n.useStarredChartsStore(),{data:c=[],isLoading:d}=n.useCustomVisualsQuery(),{setCardType:h,setCardPreferences:x,setIsDevMode:g}=t.useEditorStore(L=>L.actions),p=t.useEditorStore(L=>L.card),m=t.useEditorStore(L=>L.isDevMode),{setCardCustomCfg:f,setCustomCardPreferences:w,setVisualizationMode:b,setQueryConfig:N,replaceFrameCards:A,clearModeDrafts:_,initializeModeDrafts:C}=t.useEditorActions(),S=v.useMemo(()=>{const L=lo({isDevMode:m});if(!r)return L;const M=r.toLowerCase();return L.filter(P=>P.name.toLowerCase().includes(M))},[m,r]),I=v.useMemo(()=>{const L=c.filter(P=>P.componentType==="chart"&&P.pluginType!=="standard");if(!r)return L;const M=r.toLowerCase();return L.filter(P=>P.name.toLowerCase().includes(M))},[c,r]),E=L=>{f(null),x({}),b("builtin"),h(L),["custom","text","map"].includes(L)&&(g(!0),N(void 0)),s==null||s(L),a==null||a()},D=L=>{f(null),x({}),b("builtin"),N(void 0);const M=n.resolveMultiInputTypeFromVisual(L);if(M==="multiple"&&L.slots&&L.slots.length>0){_();const F=n.createCardsFromSlots(L.slots,L,p);A(F),F[0]&&C(F[0]),a==null||a();return}else h("custom"),w({type:"component",visualType:M,url:L.url,componentName:L.name,icon:L.icon,pluginChartType:L.chartType,minInputs:L.minInputs,maxInputs:L.maxInputs});s==null||s("custom",L),a==null||a()},T=L=>{const M={type:"default",id:L.id,name:L.name};l(M)},y=L=>{const M={type:"custom",id:L.name,url:L.url,icon:L.icon,name:L.name};l(M)};return e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"mb-2 flex h-7 items-center gap-1.5 rounded-control border border-input bg-background px-2 focus-within:border-ring",children:[e.jsx(n.Search,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx("input",{type:"text",placeholder:"Search charts",value:r,onChange:L=>o(L.target.value),className:"h-full w-full bg-transparent text-[12px] text-foreground placeholder:text-muted-foreground focus:outline-none"})]}),e.jsxs("div",{className:"max-h-[360px] overflow-y-auto pr-1",children:[S.length>0&&e.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:S.map(L=>e.jsx(Rn,{chartType:L.id,chartName:L.name,isCustom:!1,isStarred:i("default",L.id),onSelect:()=>E(L.id),onToggleStar:()=>T(L)},L.id))}),I.length>0&&e.jsxs(e.Fragment,{children:[S.length>0&&e.jsxs("div",{className:"my-3 flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Custom charts"}),e.jsx("span",{className:"font-mono text-[10px] tabular-nums text-muted-foreground/70",children:I.length})]}),e.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:I.map((L,M)=>e.jsx(Rn,{chartName:L.name,isCustom:!0,pluginName:L.pluginName,isStarred:i("custom",L.name),onSelect:()=>D(L),onToggleStar:()=>y(L)},`${L.url}-${L.name}-${M}`))})]}),d&&e.jsx("div",{className:"mt-3 py-4 text-center text-[11px] text-muted-foreground",children:"Loading custom charts…"}),S.length===0&&I.length===0&&!d&&e.jsx("div",{className:"py-8 text-center text-[11px] text-muted-foreground",children:"No charts found"})]})]})}function io({selectedChart:s,onChartChange:a}){var I,E,D,T;const r=t.useEditorStore(y=>y.card),o=t.useEditorStore(y=>y.frame),u=t.useEditorStore(y=>y.isDevMode),{replaceFrameCards:i,clearModeDrafts:l,initializeModeDrafts:c,setIsDevMode:d}=t.useEditorActions(),h=v.useMemo(()=>n.findCustomVisualConfigCard(o,r),[o,r]),{manifest:x}=n.useCustomVisual(((I=h==null?void 0:h.customCardPreferences)==null?void 0:I.url)||""),g=v.useMemo(()=>{var y;return(y=x==null?void 0:x.visuals)==null?void 0:y.find(L=>{var M;return L.name===((M=h==null?void 0:h.customCardPreferences)==null?void 0:M.componentName)})},[x,(E=h==null?void 0:h.customCardPreferences)==null?void 0:E.componentName]),p=n.resolveMultiInputType(h,g)==="multiple",m=Ne.useEffectiveEditorCardType(),f=p?m:s??r.type,w=(D=r==null?void 0:r.customCardPreferences)==null?void 0:D.componentName,b=(T=h==null?void 0:h.customCardPreferences)==null?void 0:T.componentName,N=p&&!!b,A=v.useMemo(()=>{const y=n.chartTypes.find(L=>L.id===f);return y?y.label:f==="custom"?w||"Custom Visual":"Select chart type"},[f,w]),_=v.useMemo(()=>{const y=n.chartTypes.find(L=>L.id===f);if(y){const L=y.icon;return e.jsx(L,{className:"h-4 w-4"})}if(f==="custom"&&w){const L=n.getAutoDetectedChartIcon(w);return L||e.jsx(ks,{chartName:w,isCustom:!0,className:"h-4 w-4"})}return e.jsx(lr,{className:"h-4 w-4"})},[f,w]);return{displayChartType:f,displayLabel:A,displayIcon:_,showBadge:N,badgeLabel:b,isMultiInputContext:p,handleChartSelect:y=>{a==null||a(y)},handleClearCustomVisual:y=>{y.stopPropagation();const L={...r,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([L]),l(),c(L),u&&d(!0),a==null||a("bar")}}}function co({selectedChart:s,onChartChange:a,variant:r="ghost",className:o}){const[u,i]=v.useState(!1),{displayLabel:l,displayIcon:c,showBadge:d,badgeLabel:h,handleChartSelect:x,handleClearCustomVisual:g}=io({selectedChart:s,onChartChange:a}),p=r==="header";return e.jsxs("div",{className:t.cn("relative w-full",o),children:[e.jsxs(t.Popover,{open:u,onOpenChange:i,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:p?e.jsxs("button",{type:"button",role:"combobox","aria-expanded":u,className:"flex h-9 w-full items-center justify-between gap-2 border-b border-border bg-card px-3 text-left transition-colors hover:bg-muted/50 focus:outline-none focus-visible:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[c,e.jsx("span",{className:"truncate text-[12px] font-medium text-foreground",children:l})]}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform",u&&"rotate-180")})]}):e.jsxs(t.Button,{size:"xs",variant:r,role:"combobox","aria-expanded":u,className:t.cn("w-full justify-between gap-2",r==="ghost"&&"border border-border/70 bg-background text-foreground/90",r==="outline"&&"border-border/70 bg-background text-foreground/90",r==="secondary"&&"text-foreground"),children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[c,e.jsx("span",{className:"truncate",children:l})]}),e.jsx(t.ChevronDown,{className:"h-3.5 w-3.5 shrink-0 opacity-70"})]})}),e.jsx(t.PopoverContent,{className:"w-[360px] p-3",align:"start",onOpenAutoFocus:m=>m.preventDefault(),children:e.jsx(ra,{onChartSelect:m=>x(m),onClose:()=>i(!1)})})]}),d&&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:h,children:[e.jsx(n.Layers,{className:"h-2.5 w-2.5 shrink-0"}),e.jsx("span",{className:"truncate",children:h}),e.jsx("button",{onClick:g,className:"rounded-full p-0.5 hover:bg-muted",title:"Clear custom visual",children:e.jsx(t.X,{className:"h-2.5 w-2.5"})})]})]})}const Dt={table:t.Table2,matrixTable:n.Grid3x3,bar:n.ChartColumnIncreasing,line:n.ChartLine,stackedBar:n.ChartColumnStacked,stackedLine:n.MdStackedLineChart,scatter:n.ChartScatter,bubble:n.TbChartBubble,pie:n.ChartPie,doughnut:n.Donut,kpi:n.TiSortNumerically,treemap:n.TbChartTreemap,bullet:n.BulletChartIcon,funnel:n.TbChartFunnel,tornado:n.Tornado,heatmap:n.Grid3x3,range:n.ChartNoAxesGantt,radar:n.Radar,polarArea:n.PiChartPolar,text:n.BookType,map:n.Map},Ut={table:"Table",matrixTable:"Matrix Table",bar:"Bar Chart",line:"Line Chart",stackedBar:"Stacked Bar",stackedLine:"Stacked Line",scatter:"Scatter",bubble:"Bubble",pie:"Pie Chart",doughnut:"Donut",kpi:"KPI",treemap:"Treemap",bullet:"Bullet",funnel:"Funnel",tornado:"Tornado",heatmap:"Heatmap",range:"Range",radar:"Radar",polarArea:"Polar Area",text:"Text",map:"Map"},oa=[{id:"table"},{id:"bar"},{id:"line"},{id:"pie"},{id:"kpi"},{id:"doughnut"}],la=6;function uo({selectedChart:s,onChartChange:a}){var _,C;const[r,o]=v.useState(!1),u=t.useEditorStore(S=>S.card),{setCardType:i,setCardPreferences:l}=t.useEditorStore(S=>S.actions),{setCardCustomCfg:c,setCustomCardPreferences:d,setQueryConfig:h,replaceFrameCards:x,clearModeDrafts:g,initializeModeDrafts:p}=t.useEditorActions(),{starredCharts:m}=n.useStarredChartsStore(),{data:f=[]}=n.useCustomVisualsQuery(),w=t.useEditorStore(S=>S.isDevMode),b=v.useMemo(()=>{const S=m.filter(T=>T.type==="default"?Kt(T.id,{isDevMode:w}):f.some(y=>y.name===T.id)),I=new Set(S.map(T=>T.id)),E=oa.filter(T=>!I.has(T.id)&&Kt(T.id,{isDevMode:w}));return[...S.map(T=>({id:T.id,label:T.name,icon:T.type==="default"?Dt[T.id]:void 0,isCustom:T.type==="custom",url:T.url})),...E.map(T=>({id:T.id,label:Ut[T.id]??T.id,icon:Dt[T.id],isCustom:!1}))].slice(0,la)},[m,f,w]),N=s==="custom"&&((_=u==null?void 0:u.customCardPreferences)==null?void 0:_.componentName);return b.some(S=>{var I;return S.isCustom?N&&((I=u==null?void 0:u.customCardPreferences)==null?void 0:I.componentName)===S.id:s===S.id})||(s==="custom"?(C=u==null?void 0:u.customCardPreferences)!=null&&C.componentName:Ut[s]),e.jsxs("div",{className:"px-4 pb-3 pt-4",children:[e.jsx("p",{className:"pb-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Chart type"}),e.jsx(ia,{selectedChart:s,onChartChange:a,compactMore:!0})]})}function ia({selectedChart:s,onChartChange:a,compactMore:r=!1}){var E,D;const[o,u]=v.useState(!1),i=t.useEditorStore(T=>T.card),{setCardType:l,setCardPreferences:c}=t.useEditorStore(T=>T.actions),{setCardCustomCfg:d,setCustomCardPreferences:h,setQueryConfig:x,replaceFrameCards:g,clearModeDrafts:p,initializeModeDrafts:m}=t.useEditorActions(),{starredCharts:f}=n.useStarredChartsStore(),{data:w=[]}=n.useCustomVisualsQuery(),b=t.useEditorStore(T=>T.isDevMode),N=((E=i==null?void 0:i.customCardPreferences)==null?void 0:E.componentName)??null,A=v.useMemo(()=>{const T=f.filter(F=>F.type==="default"?Kt(F.id,{isDevMode:b}):w.some(j=>j.name===F.id)),y=new Set(T.map(F=>F.id)),L=oa.filter(F=>!y.has(F.id)&&Kt(F.id,{isDevMode:b})),M=[...T.map(F=>({id:F.id,label:F.name,icon:F.type==="default"?Dt[F.id]:void 0,isCustom:F.type==="custom",url:F.url})),...L.map(F=>({id:F.id,label:Ut[F.id]??F.id,icon:Dt[F.id],isCustom:!1}))];if(!M.some(F=>F.isCustom?s==="custom"&&F.id===N:F.id===s))if(s==="custom"&&N){const F=w.find(j=>j.name===N);F&&M.unshift({id:F.name,label:F.name,icon:void 0,isCustom:!0,url:F.url})}else s&&Dt[s]&&Kt(s,{isDevMode:b})&&M.unshift({id:s,label:Ut[s]??s,icon:Dt[s],isCustom:!1});return M.slice(0,la)},[f,w,s,N,b]),_=s==="custom"&&N,C=T=>{if(T.isCustom){const y=w.find(P=>P.name===T.id);if(!y)return;d(null),c({}),x(void 0);const L=n.resolveMultiInputTypeFromVisual(y);if(L==="multiple"&&y.slots&&y.slots.length>0){p();const P=n.createCardsFromSlots(y.slots,y,i);g(P),P[0]&&m(P[0]);return}l("custom"),h({type:"component",visualType:L,url:y.url,componentName:y.name,icon:y.icon,pluginChartType:y.chartType,minInputs:y.minInputs,maxInputs:y.maxInputs}),a("custom");return}a(T.id)},S=A.some(T=>{var y;return T.isCustom?_&&((y=i==null?void 0:i.customCardPreferences)==null?void 0:y.componentName)===T.id:s===T.id}),I=S?"More":s==="custom"?((D=i==null?void 0:i.customCardPreferences)==null?void 0:D.componentName)||"Custom":Ut[s]||"More";return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"inline-flex h-7 items-center overflow-hidden rounded-control border border-input bg-background",children:A.map(T=>{var M;const y=T.icon,L=T.isCustom?_&&((M=i==null?void 0:i.customCardPreferences)==null?void 0:M.componentName)===T.id:s===T.id;return e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>C(T),"aria-label":T.label,"aria-pressed":!!L,className:t.cn("flex h-full w-7 items-center justify-center text-foreground/65 transition-colors hover:bg-muted/50 hover:text-foreground",L&&"bg-foreground/[0.08] font-medium text-foreground"),children:[y?e.jsx(y,{className:"h-3.5 w-3.5"}):e.jsx(ks,{chartName:T.label,isCustom:!0,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"sr-only",children:T.label})]})}),e.jsx(t.TooltipContent,{side:"bottom",children:T.label})]},`${T.isCustom?"custom":"default"}-${T.id}`)})}),e.jsxs(t.Popover,{open:o,onOpenChange:u,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs("button",{type:"button","aria-label":r?"More chart types":I,className:t.cn("inline-flex h-7 items-center gap-1 rounded-control transition-colors hover:bg-muted/50",r?"w-7 justify-center":"px-2 text-[12px]",!r&&(S?"text-muted-foreground":"text-foreground")),children:[!r&&e.jsx("span",{className:"truncate",children:I}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform",o&&"rotate-180"),strokeWidth:1.75})]})}),e.jsx(t.PopoverContent,{className:"w-[360px] p-3",align:"end",onOpenAutoFocus:T=>T.preventDefault(),children:e.jsx(ra,{onChartSelect:T=>{a(T),u(!1)},onClose:()=>u(!1)})})]})]})}function mo(){const s=t.useEditorStore(d=>{var h,x;return(x=(h=d.card.preferences)==null?void 0:h.chartOptions)==null?void 0:x.indexAxis}),a=t.useEditorStore(d=>d.card.type),{setChartOrientation:r,setCardPreferences:o}=t.useEditorStore(d=>d.actions),u=d=>{if(r(d),a!=="bullet")return;const h=d==="y"?"horizontal":"vertical",x=t.useEditorStore.getState().card.preferences,g={...x||{},bulletConfig:{...(x==null?void 0:x.bulletConfig)||{},orientation:h}};o(g)};function i(){const d=s??"x",h=()=>{u(d==="x"?"y":"x")};return e.jsx(n.IconButton,{onClick:h,tooltip:"Chart Orientation",className:"h-7 w-7 px-0",children:d==="x"?e.jsx(cs,{className:"h-3.5 w-3.5"}):e.jsx(is,{className:"h-3.5 w-3.5"})})}function l(){const d=()=>{u(s==="y"||s===void 0?"x":"y")};return e.jsx(n.IconButton,{onClick:d,tooltip:"Chart Orientation",className:"h-7 w-7 px-0",children:s==="y"||s===void 0?e.jsx(cs,{className:"h-3.5 w-3.5"}):e.jsx(is,{className:"h-3.5 w-3.5"})})}function c(){const d=s??"y",h=()=>{u(d==="y"?"x":"y")};return e.jsx(n.IconButton,{onClick:h,tooltip:"Chart Orientation",className:"h-7 w-7 px-0",children:d==="y"?e.jsx(is,{className:"h-3.5 w-3.5"}):e.jsx(cs,{className:"h-3.5 w-3.5"})})}return e.jsx(e.Fragment,{children:a==="funnel"?l():a==="bullet"?c():i()})}function As({className:s,triggerVariant:a="icon",label:r="Display Options"}){var w,b,N,A,_,C,S,I,E,D;const o=t.useEditorStore(T=>T.card),{setCardPreferences:u,updateCardInFrame:i,setCard:l}=t.useEditorActions(),[c,d]=v.useState(!1),h=((b=(w=o.preferences)==null?void 0:w.displayOptions)==null?void 0:b.showFilterInfo)??!0,x=((A=(N=o.preferences)==null?void 0:N.displayOptions)==null?void 0:A.showCardToolbar)??!0,g=((C=(_=o.preferences)==null?void 0:_.displayOptions)==null?void 0:C.showChrome)??!0,p=((I=(S=o.preferences)==null?void 0:S.displayOptions)==null?void 0:I.allowScroll)??!0,m=((D=(E=o.preferences)==null?void 0:E.displayOptions)==null?void 0:D.showInlineFilterBar)??!0,f=(T,y)=>{var P;const L={...o.preferences,displayOptions:{...(P=o.preferences)==null?void 0:P.displayOptions,[T]:y}};u(L);const M={...o,preferences:L};l(M),i(M)};return e.jsx("div",{className:t.cn("flex items-center",s),children:e.jsxs(n.DropdownMenu,{modal:!1,open:c,onOpenChange:d,children:[e.jsx(n.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:r})]}):e.jsx(n.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(n.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(n.DropdownMenuLabel,{children:"Display Options"}),e.jsx(n.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(n.DropdownMenuCheckboxItem,{checked:h,onCheckedChange:T=>{f("showFilterInfo",T)},onSelect:T=>T.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(n.DropdownMenuCheckboxItem,{checked:x,onCheckedChange:T=>{f("showCardToolbar",T)},onSelect:T=>T.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(n.DropdownMenuCheckboxItem,{checked:g,onCheckedChange:T=>{f("showChrome",T)},onSelect:T=>T.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(n.DropdownMenuCheckboxItem,{checked:p,onCheckedChange:T=>{f("allowScroll",T)},onSelect:T=>T.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(n.DropdownMenuCheckboxItem,{checked:m,onCheckedChange:T=>{f("showInlineFilterBar",T)},onSelect:T=>T.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 Ls({className:s,triggerVariant:a="icon",label:r="Inline Filters"}){var S,I,E;const[o,u]=v.useState(!1),i=t.useEditorStore(D=>D.card),l=t.useEditorStore(D=>D.selectedConnectionId),{tokenProps:c}=n.useSemaphorContext(),{setCard:d}=t.useEditorActions(),h=t.useDashboardStore(D=>D.actions.removeCardInlineFilterValue),x=t.useDashboardStore(D=>D.actions.setCardInlineFilterValue),g=t.useEditorStore(D=>D.actions.removeCardInlineFilterValue),p=t.useEditorStore(D=>D.actions.setCardInlineFilterValue),m=t.useDashboardStore(D=>D.isVisualEditing),f=(i==null?void 0:i.inlineFilters)||[],w=((I=(S=c==null?void 0:c.params)==null?void 0:S.calendarContext)==null?void 0:I.tz)||((E=c==null?void 0:c.params)==null?void 0:E.timezone)||Intl.DateTimeFormat().resolvedOptions().timeZone;function b(D){var z,V,q,U,G,Q,Y;const T=((q=(V=(z=i==null?void 0:i.dataSource)==null?void 0:z.selectedEntities)==null?void 0:V[0])==null?void 0:q.database)||"",y=D.qualifiedFieldName||D.name;if(f.find(H=>n.doesStoredFilterMatchField(H,D)))return;const M=D.qualifiedFieldName?D.qualifiedFieldName.split(".").slice(0,-1).join("."):D.qualifiedEntityName||D.entityName,F=t.fmt(D.name),j=n.buildFilterFieldMeta(D),k=n.buildFilterSemanticContext(i==null?void 0:i.dataSource,{connectionId:l||((U=i==null?void 0:i.dataSource)==null?void 0:U.connectionId),connectionType:(G=i==null?void 0:i.dataSource)==null?void 0:G.connectionType}),O=n.isCalculatedFilterField(j),R=!!(((Q=i==null?void 0:i.dataSource)==null?void 0:Q.mode)==="semanticDomain"&&((Y=k==null?void 0:k.selectedEntities)!=null&&Y.length||k!=null&&k.semanticDomainId)),B={id:t.v4(),column:y,title:D.label||D.name,dataType:D.dataType,table:D.entityName||"",database:T,qualifiedTableName:M,connectionId:l||"",operation:"in",sql:O||R?"":n.getDefaultFilterSql(D.dataType,M,F),fieldMeta:j,semanticContext:k,width:250};d({...i,inlineFilters:[...f,B]})}function N(D){const T=f.filter(y=>y.id!==D);d({...i,inlineFilters:T}),m?g(i.id,D):h(i.id,D)}function A(D,T){const y=f.map(F=>F.id===D?{...F,...T}:F);if(d({...i,inlineFilters:y}),!(Object.prototype.hasOwnProperty.call(T,"defaultValues")||Object.prototype.hasOwnProperty.call(T,"defaultDateFilter")))return;const M=y.find(F=>F.id===D);if(!M)return;const P=t.buildFilterValueFromDefaults(M,w);P?m?p(i.id,P):x(i.id,P):m?g(i.id,D):h(i.id,D)}if(!["bar","line","pie","doughnut","table","detailTable","stackedBar","stackedLine","horizontalBar","radar","polarArea","scatter","bubble","funnel","aggregateTable","custom"].includes(i==null?void 0:i.type))return null;const C=a==="menu";return e.jsx("div",{className:t.cn("flex items-center gap-1",C&&"w-full",s),children:e.jsxs(t.Popover,{open:o,onOpenChange:u,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:C?e.jsxs(t.Button,{variant:"ghost",className:t.cn("h-7 w-full justify-start gap-2 px-2 text-[13px]",f.length>0&&"text-primary"),children:[e.jsx(En,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:r}),f.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:f.length})]}):e.jsxs(n.IconButton,{tooltip:"Add Inline Filter",className:t.cn("relative h-7 w-7 px-0",{"text-primary":f.length>0}),children:[e.jsx(En,{className:"h-3.5 w-3.5"}),f.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:f.length})]})}),e.jsx(t.PopoverContent,{align:"end",className:t.cn("w-80 p-0",C&&"z-[60]"),children:e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"border-b px-4 py-3",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Inline Filters"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"On-card filters for fast, focused exploration."})]}),e.jsx("div",{className:"flex h-[320px] min-h-0 flex-col overflow-hidden",children:e.jsx(n.DndContext,{collisionDetection:n.closestCenter,children:e.jsx(n.SortableContext,{items:[],strategy:n.verticalListSortingStrategy,children:e.jsx(n.FieldsList,{context:"inline-filter",onFieldSelect:b,inlineFilters:f})})})}),f.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:f.map(D=>e.jsx(xo,{filter:D,onUpdate:T=>A(D.id,T),onRemove:()=>N(D.id)},D.id))})]})]})})]})})}function xo({filter:s,onUpdate:a,onRemove:r}){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(n.CustomFilterPopover,{filter:s,variant:"inline",onAccept:o=>a(o),trigger:e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0",title:"Configure filter",children:e.jsx(n.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:r,children:e.jsx(t.X,{className:"h-3 w-3"})})]})]})}const ho={metric_selector:"Displayed metric",field_selector:"Group by field",aggregation_selector:"Aggregation",grain_selector:"Time grain"};function po(s,a){return s&&typeof s=="object"&&"label"in s&&typeof s.label=="string"&&s.label.trim().length>0?s.label:a||null}const fo={metric_selector:"config_metric_selector",field_selector:"config_field_selector",aggregation_selector:"config_aggregation",grain_selector:"config_grain"};function ss(s,a){return`${s}:${a}`}function go(s,a,r){const o=new Set(r.filter(i=>i.target!=="sql_param").map(i=>ss(i.controlId,i.target))),u=a.map(i=>{const l=t.getCompatibleBindingTargetOptions({card:s,control:i}).map(x=>x.value),c=fo[i.type],h=[...c?[c]:[],...l.filter(x=>x!==c)].find(x=>!o.has(ss(i.id,x)));return h?{controlId:i.id,target:h}:null}).find(Boolean);return u?{controlId:u.controlId,target:u.target,mapping:{}}:null}function bo({card:s,dashboardControls:a,bindings:r,onChange:o,availableFieldChoices:u,availableMetricChoices:i,suppressTransientStaleState:l=!1}){const c=[...a,...s.controls||[]],[d,h]=v.useState({}),x=n.extractSqlParamReferences({sql:s.sql,controlBindings:s.controlBindings}),g=t.getBindingTargetSuggestions(s),p=new Set(r.map(_=>ss(_.controlId,_.target))),m=c.some(_=>t.getCompatibleBindingTargetOptions({card:s,control:_}).some(C=>!p.has(ss(_.id,C.value)))),f=l?0:r.reduce((_,C)=>{const S=w(C.target),I=Object.values(C.mapping).filter(E=>{const D=C.target==="config_metric_selector"||C.target==="config_field_selector"?typeof E=="string"?E:E==null?void 0:E.id:typeof E=="string"?E:void 0;return typeof D=="string"&&!S.some(T=>T.value===D)}).length;return _+I},0);function w(_){var C,S,I,E;switch(_){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})):((S=(C=s.config)==null?void 0:C.metricColumns)==null?void 0:S.map(D=>({value:D.id,label:D.label||D.id,target:D})))||[];case"config_field_selector":return u?u.filter(D=>!!D.target).map(D=>({value:D.target.id,label:D.target.label||D.option.label,target:D.target})):((E=(I=s.config)==null?void 0:I.groupByColumns)==null?void 0:E.map(D=>({value:D.id,label:D.label||D.id,target:D})))||[];case"config_aggregation":return(g.config_aggregation||[]).map(D=>({value:D,label:D}));case"config_grain":return(g.config_grain||[]).map(D=>({value:D,label:D.charAt(0).toUpperCase()+D.slice(1)}));default:return[]}}const b=(_,C)=>{o(r.map((S,I)=>I!==_?S:C(S)))},N=_=>{o(r.filter((C,S)=>S!==_))},A=()=>{const _=go(s,c,r);_&&o([...r,_])};if(typeof s.sql=="string"&&s.sql.trim().length>0){const _=x.map(({controlId:C,paramId:S})=>{const I=c.find(E=>E.id===C);return I?{id:C,paramId:S,label:I.label,reference:`[[param.${S}]]`}:{id:C,paramId:S,label:C,reference:`[[param.${S}]]`}});return e.jsx("div",{className:"space-y-2",children:_.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]]`."}):_.map(C=>e.jsx("div",{className:"rounded-md border p-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:C.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Referenced in SQL"})]}),e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted/40 px-2 py-1",children:[e.jsx("code",{className:"text-xs",children:C.reference}),e.jsx(n.CopyButton,{text:C.reference,ariaLabel:`Copy ${C.reference}`})]})]})},`${C.id}:${C.paramId}`))})}return e.jsxs("div",{className:"space-y-4",children:[f>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(n.CircleAlert,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{children:[f," ",f===1?"mapping needs":"mappings need"," attention before save. Replace each missing target or choose Not mapped."]})]}):null,r.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."}):r.map((_,C)=>{const S=g[_.target]||[],I=c.find(j=>j.id===_.controlId),E=I?t.ensureManualSource(I):null,D=(E==null?void 0:E.source.kind)==="manual"?E.source.options:[],T=w(_.target),y=Array.from(new Set([...D.map(j=>j.value),...Object.keys(_.mapping)])).map(j=>{const k=D.find(O=>O.value===j);return{value:j,label:(k==null?void 0:k.label)||j}}),L=`${_.controlId}-${_.target}-${C}`,M=d[L]??C===0,P=Object.keys(_.mapping).length,F=I!=null&&I.type?ho[I.type]||I.type:null;return e.jsxs(n.Collapsible,{open:M,onOpenChange:j=>h(k=>({...k,[L]:j})),className:"rounded-md border",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 p-3",children:[e.jsx(n.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-start gap-2 text-left",children:[M?e.jsx(t.ChevronDown,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}):e.jsx(n.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:(I==null?void 0:I.label)||"Control"}),F?e.jsx(n.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:P>0?`${P} mapped`:"No mappings yet"})]})]})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>N(C),children:e.jsx(n.Trash2,{className:"h-4 w-4"})})]}),e.jsx(n.CollapsibleContent,{className:"space-y-3 border-t px-3 pb-3 pt-2",children:y.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."}):T.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:y.map(j=>{const k=_.mapping[j.value],O=_.target==="config_metric_selector"||_.target==="config_field_selector"?typeof k=="string"?k:k==null?void 0:k.id:typeof k=="string"?k:void 0,R=!l&&typeof O=="string"&&!T.some(V=>V.value===O),B=po(k,O),z=O&&R?[...T,{value:O,label:"Needs remap",target:k}]:T;return e.jsxs("div",{className:"grid gap-2 rounded-md border p-2 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-[11px] text-muted-foreground",children:"Viewer picks"}),e.jsx("div",{className:"rounded-md bg-muted/50 px-3 py-2 text-sm",children:j.label})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-[11px] text-muted-foreground",children:"Switch to"}),e.jsxs(t.Select,{value:O||"__none__",onValueChange:V=>b(C,q=>{if(q.target==="config_metric_selector"){const G={...q.mapping};if(V==="__none__")delete G[j.value];else{const Q=z.find(Y=>Y.value===V);Q!=null&&Q.target?G[j.value]=Q.target:delete G[j.value]}return{...q,mapping:G}}if(q.target==="config_field_selector"){const G={...q.mapping};if(V==="__none__")delete G[j.value];else{const Q=z.find(Y=>Y.value===V);Q!=null&&Q.target?G[j.value]=Q.target:delete G[j.value]}return{...q,mapping:G}}const U={...q.mapping};return V==="__none__"?delete U[j.value]:U[j.value]=V,{...q,mapping:U}}),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Choose what this should use"})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"__none__",children:"Not mapped"}),z.map(V=>e.jsx(t.SelectItem,{value:V.value,children:V.label},V.value))]})]}),R?e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-amber-700",children:[e.jsx(n.CircleAlert,{className:"h-3 w-3 shrink-0"}),e.jsxs("span",{children:["Needs remap",B?` · Previously: ${B}`:""]})]}):null]})]},`${_.controlId}-${_.target}-${j.value}`)})}),S.length>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Available choices for this card: ",S.join(", ")]})]})})]},L)}),m?e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",onClick:A,children:[e.jsx(n.Plus,{className:"mr-2 h-4 w-4"}),"Add another control response"]}):null]})}const jo=[];function Ms({className:s,triggerVariant:a="icon",label:r="Controls"}){var M,P;const{handleOpenChange:o,preventPassiveDismissDuringCreate:u,resolvedOpen:i,setIsCreateFlowActive:l}=Ne.useCreateFlowOverlayState({}),c=t.useEditorStore(F=>F.card),d=t.useEditorStore(F=>F.frame),h=t.useDashboardStore(F=>F.dashboard),g=t.useDashboardStore(F=>F.dashboard.controls)||jo,{setCard:p,updateCardInFrame:m}=t.useEditorActions(),[f,w]=v.useState(null);v.useEffect(()=>{i&&!f&&(c!=null&&c.id)&&w(c.id)},[c==null?void 0:c.id,i,f]),v.useEffect(()=>{!i&&f!==null&&w(null)},[i,f]);const b=v.useMemo(()=>f?(d==null?void 0:d.cards.find(F=>F.id===f))||((c==null?void 0:c.id)===f?c:void 0):c,[c,d==null?void 0:d.cards,f]),N=(b==null?void 0:b.controls)||[],A=b?t.collectDashboardControlIds(h,{excludeCardId:b.id}):g.map(F=>F.id),_=((b==null?void 0:b.controlBindings)||[]).filter(F=>F.target!=="sql_param"),C=n.buildCardControlUsageById({card:b,controls:N}),S={choices:t.getFieldSelectorChoicesForCard(b),targetMap:Object.fromEntries((((M=b==null?void 0:b.config)==null?void 0:M.groupByColumns)||[]).map(F=>[F.id,F]))},I={choices:t.getMetricSelectorChoicesForCard(b),targetMap:Object.fromEntries((((P=b==null?void 0:b.config)==null?void 0:P.metricColumns)||[]).map(F=>[F.id,F]))},E=S.choices.map(F=>({option:F,target:S.targetMap[F.value]})),D=I.choices.map(F=>({option:F,target:I.targetMap[F.value]})),T=(F,j)=>{if(!b)return;const k=(j==null?void 0:j.type)==="rename"?t.applyControlMutationToCard(b,{type:"rename",oldId:j.oldId,newId:j.newId}):(j==null?void 0:j.type)==="remove"?t.applyControlMutationToCard(b,{type:"remove",controlId:j.controlId}):b,O={...k,controls:F,controlBindings:t.syncStructuralBindingsWithControls(k.controlBindings,F)};m(O),(c==null?void 0:c.id)===O.id&&p(O)},y=F=>{if(!b)return;const j={...b,controlBindings:t.mergeConfigBindingsWithSqlParamBindings(F,b.controlBindings)};m(j),(c==null?void 0:c.id)===j.id&&p(j)},L=a==="menu";return e.jsx("div",{className:t.cn("flex items-center gap-1",L&&"w-full",s),children:e.jsxs(t.Popover,{modal:!0,open:i,onOpenChange:o,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:L?e.jsxs(t.Button,{variant:"ghost",className:t.cn("h-7 w-full justify-start gap-2 px-2 text-[13px]",(N.length>0||_.length>0)&&"text-primary"),children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:r}),N.length+_.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:N.length+_.length})]}):e.jsxs(n.IconButton,{tooltip:"Configure Controls",className:t.cn("relative h-7 w-7 px-0",{"text-primary":N.length>0||_.length>0}),children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"}),N.length+_.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:N.length+_.length})]})}),e.jsxs(t.PopoverContent,{className:t.cn("flex max-h-[85vh] w-[560px] max-w-[95vw] flex-col",L&&"z-[60]"),align:"end",onEscapeKeyDown:u,onPointerDownOutside:u,children:[e.jsxs("div",{className:"space-y-1 border-b pb-4",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Card-only controls"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add controls that belong only to this card, or decide how this card should respond to shared dashboard controls."}),b!=null&&b.sql?e.jsx("p",{className:"text-xs text-muted-foreground",children:"SQL cards reference controls explicitly with syntax like `[[param.wac_type]]`."}):null]}),e.jsx("div",{className:"flex-1 overflow-y-auto pt-5",children:e.jsxs("div",{className:"space-y-5 pr-1",children:[e.jsx(Ne.ControlDefinitionListEditor,{scope:"card",card:b,controls:N,reservedControlIds:A,usageByControlId:C,availableFieldChoices:E,availableMetricChoices:D,onCreateFlowActiveChange:l,onChange:(F,j,k)=>T(F,k),emptyMessage:"No card-scoped controls yet."}),e.jsxs("div",{className:"space-y-1 border-t pt-4",children:[e.jsx("h4",{className:"text-sm font-medium",children:"How this card uses controls"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Choose what each control changes in this card."})]}),b?e.jsx(bo,{card:b,dashboardControls:g,bindings:_,onChange:y,availableFieldChoices:E,availableMetricChoices:D}):null]})})]})]})})}function ca({showOrientation:s=!0,showGridStyle:a=!0,showInlineFilters:r=!0,showControls:o=!0,showDisplayOptions:u=!0}={}){const i=t.useEditorStore(m=>m.card),l=t.useEditorStore(m=>{var f,w;return(w=(f=m.card)==null?void 0:f.preferences)==null?void 0:w.chartOptions}),c=n.getChartGridStyle(l),{setChartGrid:d}=t.useEditorActions();function h(){const m=["xy","none","x","y"],w=(m.indexOf(c)+1)%m.length;d(m[w])}const x=s&&["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel","bullet"].includes(i.type),g=a&&!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(i.type);return x||g||r||o||u?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[x&&e.jsx(e.Fragment,{children:e.jsx(mo,{})}),g&&e.jsxs(n.IconButton,{tooltip:"Grid Style",onClick:h,className:"h-7 w-7 px-0",children:[(c==="xy"||!c)&&e.jsx(n.Grid3x3,{className:"h-3.5 w-3.5"}),c==="x"&&e.jsx(Is,{className:"h-3.5 w-3.5"}),c==="y"&&e.jsx(Ne.Rows3,{className:"h-3.5 w-3.5"}),c==="none"&&e.jsx(n.Square,{className:"h-3.5 w-3.5"})]}),r&&e.jsx(Ls,{}),o&&e.jsx(Ms,{}),u&&e.jsx(As,{})]}):null}function vo({isPreviewMode:s,onPreviewToggle:a,configCard:r}){var k,O,R,B,z;const o=t.useEditorStore(V=>V.frame),u=t.useEditorStore(V=>V.card),i=t.useEditorStore(V=>V.editorContext),l=(i==null?void 0:i.type)==="documentSection",{setFrame:c,setActiveTabCardId:d,setCard:h,updateCardInFrame:x,clearModeDrafts:g,initializeModeDrafts:p}=t.useEditorActions(),{manifest:m}=n.useCustomVisual(((k=r==null?void 0:r.customCardPreferences)==null?void 0:k.url)||""),f=(O=m==null?void 0:m.visuals)==null?void 0:O.find(V=>{var q;return V.name===((q=r==null?void 0:r.customCardPreferences)==null?void 0:q.componentName)}),b=n.resolveMultiInputType(r,f)==="multiple",N=(f==null?void 0:f.minInputs)??((R=r==null?void 0:r.customCardPreferences)==null?void 0:R.minInputs)??1,A=(f==null?void 0:f.maxInputs)??((B=r==null?void 0:r.customCardPreferences)==null?void 0:B.maxInputs),_=v.useMemo(()=>n.getCustomVisualInputCards({frame:o,configCard:r,isMultiInputVisual:b}),[o,r,b]),C=b?_.filter(Boolean).length:o.cards.length,S=l?!1:A?C<A:!0,I=C>Math.max(N||1,1),E=!!((z=r==null?void 0:r.customCardPreferences)!=null&&z.dataInputCardIds),D=(V,q)=>{V.dataTransfer.setData("tabIndex",q.toString())},T=V=>{V.preventDefault()},y=(V,q)=>{const U=V.dataTransfer.getData("tabIndex");if(U===q.toString())return;const G=Array.from(o.cards),[Q]=G.splice(parseInt(U),1);G.splice(q,0,Q),c({...o,cards:G})};function L(V){const q=(r==null?void 0:r.id)===V;if(!(E&&q?o.cards.length>1:I))return;let G=o.cards.filter(se=>se.id!==V);b&&!E&&(G=n.reindexSlotCards(G));const Q=G[0],Y={...o,cards:G,activeCardId:Q.id},H=V===u.id;H&&g(),c(Y),d(Q.id),h(Q),H&&p(Q)}function M(V,q){if(!S)return;const U={...o,cards:[...o.cards,q],activeCardId:V.id};c(U),d(q.id)}function P(){if(l)return;if(b&&(r==null?void 0:r.id)===u.id){F(u);return}const V={...u,id:t.v4(),title:`${u.title} Copy`,tabTitle:`${u.tabTitle||u.title} Copy`,customCardPreferences:u.customCardPreferences?{...u.customCardPreferences,slotIndex:b?Math.max(-1,..._.map((q,U)=>n.getSlotIndexForCard(q,U)))+1:u.customCardPreferences.slotIndex}:void 0};M(u,V)}function F(V){var H;if(l||!S)return;let q=b?"table":"bar",U="Title",G="";const Q=b?Math.max(-1,..._.map((se,ue)=>n.getSlotIndexForCard(se,ue)))+1:C;if(b&&((H=f==null?void 0:f.slots)!=null&&H.length)){const se=n.getSlotDefinitionForIndex(f.slots,Q);se&&(q=n.getSlotExpectedChartType(se),U=se.label||`Tab ${Q+1}`,G=se.description||"")}const Y={dataSource:V.dataSource,connectionId:V.connectionId,lastSelectedDatabase:V.lastSelectedDatabase,lastSelectedSchema:V.lastSelectedSchema,lastSelectedTable:V.lastSelectedTable,lastSelectedDatamodelId:V.lastSelectedDatamodelId,id:t.v4(),title:U,tabTitle:U,description:G,preferences:{onClickFilter:[{columnIndex:0,expression:""}],...q==="text"?{textVisualOptions:{richContent:t.createEmptyRichContent()}}:{}},type:q,sql:"",data:[],mode:"explorer",...b&&{customCardPreferences:{slotIndex:Q}}};M(V,Y)}function j(V,q){return V.cards.length===1&&(q.displayTab===!0||q.displayTab===void 0)||V.activeCardId!==q.id&&(q.displayTab===!0||q.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const U=q.displayTab===void 0?!1:!q.displayTab;h({...q,displayTab:U}),x({...q,displayTab:U})},children:q.displayTab===!0||q.displayTab===void 0?e.jsx(n.Eye,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"}):e.jsx(n.EyeOff,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})}return e.jsx(t.TabsList,{variant:"underline",className:"group flex h-9 items-center justify-start gap-1 overflow-x-auto rounded-none border-b-0 border-t border-border bg-background px-4",children:e.jsxs("div",{className:"flex items-center gap-1",children:[o.cards.map((V,q)=>{var H,se;const U=b?n.getSlotIndexForCard(V,q):-1,G=b&&((H=f==null?void 0:f.slots)!=null&&H.length)&&U>=0?n.getSlotDefinitionForIndex(f.slots,U):null,Q=G?(Array.isArray(G.expectedType)?G.expectedType[0]:G.expectedType)||"table":V.type,Y=b&&((se=f==null?void 0:f.slots)==null?void 0:se.length)&&f.slots.every(ue=>typeof ue.position=="number"||typeof ue.position=="string"&&!ue.position.includes("+"));return e.jsxs(t.TabsTrigger,{draggable:!b&&!l,onDragStart:b||l?void 0:ue=>D(ue,q),onDragOver:b||l?void 0:T,onDrop:b||l?void 0:ue=>y(ue,q),className:t.cn("inline-flex h-6 shrink-0 items-center gap-1.5 rounded-[5px] border px-2 text-[12px] font-normal text-muted-foreground transition-colors","mb-0 border-transparent pb-0","hover:bg-muted/40 hover:text-foreground","data-[state=active]:border-border data-[state=active]:bg-card data-[state=active]:text-foreground"),value:V.id,children:[b&&G?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:n.getChartIconByType(Q,"size-3.5")}),e.jsx("span",{children:G.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:G.label}),G.description&&e.jsx("p",{className:"whitespace-normal break-words text-xs text-muted-foreground",children:G.description}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[G.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(G.expectedType)?G.expectedType.join(" / "):G.expectedType}),G.required&&e.jsx("span",{className:"inline-flex items-center rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground",children:"Required"})]})]})})]})}):e.jsxs(e.Fragment,{children:[j(o,V),e.jsx(n.Editable,{enabled:o.activeCardId===V.id,text:V.tabTitle||V.title,onSave:ue=>{h({...u,tabTitle:ue}),x({...u,tabTitle:ue})},children:V.tabTitle||V.title},V.id)]}),!l&&o.activeCardId===V.id&&!Y&&e.jsx(n.CopyPlus,{className:"h-3 w-3 text-muted-foreground hover:text-foreground",onClick:ue=>{ue.stopPropagation(),P()}}),!l&&o.activeCardId===V.id&&(E&&(r==null?void 0:r.id)===V.id?o.cards.length>1:I)&&e.jsx(t.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground",onClick:()=>L(V.id)})]},V.id)}),!l&&e.jsx(n.IconButton,{tooltip:"Add Card",className:"h-6 w-6 rounded-[5px] p-0 text-muted-foreground hover:bg-muted hover:text-foreground",onClick:()=>F(u),disabled:!S,children:e.jsx(n.Plus,{className:"h-3 w-3"})}),b&&e.jsxs(n.Toggle,{pressed:s,onPressedChange:a,size:"sm",className:"ml-1 h-6 gap-1 rounded-[5px] px-2 text-[11px] data-[state=on]:bg-muted data-[state=on]:text-foreground","aria-label":"Toggle preview",children:[s?e.jsx(n.EyeOff,{className:"h-3 w-3"}):e.jsx(n.Eye,{className:"h-3 w-3"}),e.jsx("span",{children:"Preview"})]})]})})}function gt({renderCardOverride:s,alwaysRenderOverride:a=!1}={}){var ne,ce,Te,ke,ze;const r=t.useEditorStore(re=>re.frame),o=t.useEditorStore(re=>re.card),[u,i]=v.useState(!1),l=v.useMemo(()=>n.findCustomVisualConfigCard(r,o),[r,o]),c=t.useEditorStore(re=>re.isSqlRunning);t.useEditorStore(re=>re.isDevMode);const{setFrame:d,setActiveTabCardId:h,setCard:x,setRunSql:g,mergeDraftsIntoCard:p,clearModeDrafts:m,initializeModeDrafts:f}=t.useEditorActions(),[w,b]=v.useState({}),[N,A]=v.useState(()=>new Set),{authToken:_}=n.useSemaphorContext(),C=t.getTokenParams(_==null?void 0:_.accessToken),{compiledAppearance:S}=t.useAppearance(),I=v.useMemo(()=>n.buildCustomCardTheme(S),[S]),{getCard:E,manifest:D,isLoading:T}=n.useCustomVisual(((ne=l==null?void 0:l.customCardPreferences)==null?void 0:ne.url)||""),y=(ce=l==null?void 0:l.customCardPreferences)==null?void 0:ce.componentName,L=y?E(y):null,M=(Te=D==null?void 0:D.visuals)==null?void 0:Te.find(re=>re.name===y),P=n.resolveMultiInputType(l,M),F=u&&P==="multiple"&&!!l,j=v.useMemo(()=>n.getCustomVisualInputCards({frame:r,configCard:l,isMultiInputVisual:!0}).map(te=>(te==null?void 0:te.id)===o.id?o:te),[r,l,o]),k=v.useMemo(()=>n.buildSlotOrderedCards(j),[j]),O=v.useMemo(()=>{const re=j.findIndex(te=>(te==null?void 0:te.id)===o.id);return re<0?-1:n.getSlotIndexForCard(o,re)},[j,o]),R=v.useMemo(()=>!l||P!=="multiple"||O<0?o.type:n.getEffectiveCardTypeForSlot(o,O,M==null?void 0:M.slots)??o.type,[l,P,O,o,M==null?void 0:M.slots]),B=v.useMemo(()=>F?{...o,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:R!==o.type?{...o,type:R}:o,[o,R,F]),{data:z,isLoading:V,isFetching:q,isError:U,errorMessage:G,errorSql:Q}=n.useEditorCardQuery(B),{handleOpenInEditor:Y,handleDebugWithAssistant:H}=Ds(G,Q||o.sql||o.python),se=o.type==="text"&&((ze=(ke=o.preferences)==null?void 0:ke.textVisualOptions)==null?void 0:ze.isDynamicText)===!0&&!!G,ue=v.useCallback((re,te)=>{const xe=n.normalizeMultiInputPayload(te);b(ye=>({...ye,[re]:xe}))},[]),ae=v.useCallback((re,te)=>{A(xe=>{const ye=new Set(xe);return te?ye.add(re):ye.delete(re),ye})},[]),me=N.size>0,ve=t.useInteractionStore(re=>re.interactionStates),Oe=t.useDashboardStore(re=>{var te;return(te=re.dashboard)==null?void 0:te.id}),Fe=t.useDashboardStore(re=>re.dashboard.filters),X=t.useDashboardStore(re=>re.filterValues),ge=t.useDashboardStore(re=>re.selectedSheetId),Ce=t.useEditorStore(re=>re.inlineFilterValuesMap[(l==null?void 0:l.id)||""]),Pe=t.useEditorStore(re=>re.actions.setCardInlineFilterValue),_e=t.useEditorStore(re=>re.actions.removeCardInlineFilterValue),le=v.useMemo(()=>l?n.buildInlineFilterNodes({card:l,sheetId:ge||"",inlineFilterValues:Ce,setInlineFilterValue:re=>Pe(l.id,re),removeInlineFilterValue:re=>_e(l.id,re)}):[],[l,ge,Ce,Pe,_e]),{cardFilters:De,cardFilterValues:Se}=v.useMemo(()=>l?n.calculateContextAwareFilters({card:l,interactionStates:ve,currentDashboardId:Oe,filters:Fe,filterValues:X,selectedSheetId:ge}):{cardFilters:[],cardFilterValues:[]},[l,ve,Oe,Fe,X,ge]);function ie(re){const te=r.cards.find(xe=>xe.id===re);te&&(bt.flushPendingEditorDrafts(),p(),$(re),h(re),m(),f(te))}function $(re){const te=t.useEditorStore.getState().card,xe=t.useEditorStore.getState().frame,ye={...xe,cards:xe.cards.map(qe=>qe.id===te.id?te:qe),activeCardId:re};d(ye);const Ee=ye.cards.find(qe=>qe.id===re);Ee.sql&&g(!0),x(Ee)}function oe(){if(T)return e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading manifest"})});if(!L)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 te=k.map((xe,ye)=>n.getEffectiveCardTypeForSlot(xe,ye,M==null?void 0:M.slots));return e.jsxs("div",{className:"relative flex h-full flex-col pl-2 pr-4",children:[j.map((xe,ye)=>{if(!xe)return null;const Ee=n.getSlotIndexForCard(xe,ye),qe=n.getEffectiveCardTypeForSlot(xe,Ee,M==null?void 0:M.slots);return e.jsx(n.MultiInputEmptyRenderer,{onLoadingStatus:ae,onDataChange:ue,card:xe,effectiveCardType:qe},`${xe.id}-${Ee}`)}),me&&e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/50",children:e.jsx(n.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",me&&"opacity-50"),children:e.jsx(v.Suspense,{fallback:e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(n.LoadingDots,{size:"md",color:"muted"})}),children:e.jsx(L,{editing:!0,...n.buildMultiInputCustomVisualProps({configCard:l,slotOrderedCards:k,slotTypes:te,multiInputData:w,params:C,theme:I,filters:De,filterValues:[...Se||[],...Ce||[]],inlineFilters:le})})})})]})}function fe(){var re;return F?oe():s&&(a||!V&&!q&&!U&&!G)?s({card:o,data:z,isLoading:V,isFetching:q,isError:U}):o.type==="kpi"?V||q?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(n.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("div",{className:"rounded-md border border-border",children:e.jsx(n.KPICard,{card:o,data:z==null?void 0:z.records,isPending:V||q,isError:U,comparisonMetadata:(re=z==null?void 0:z.metadata)==null?void 0:re.comparisonMetadata})}),n.isCardSummaryVisibleOnCard(o)&&e.jsx(n.CardSummary,{card:o,mode:"editor"})]})}):o.type==="text"?V||q?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):se?e.jsx("div",{className:"flex h-full min-h-0 flex-col overflow-auto p-4",children:e.jsx(ns,{error:G,errorSql:Q||o.sql||o.python,onOpenInEditor:Y,onDebugWithAssistant:H,showFeedbackButton:!1})}):e.jsx("div",{className:"flex h-full min-h-0 flex-col px-4 py-4",children:e.jsx(n.TextCard,{isLoading:c,card:o,data:z==null?void 0:z.records})}):e.jsx(n.ErrorBoundary,{FallbackComponent:n.FallbackVisual,children:e.jsx(na,{className:"grow border-none shadow-none"})})}return e.jsxs(t.Tabs,{onValueChange:ie,value:r.activeCardId,className:"flex grow flex-col",children:[F?e.jsx("div",{className:"mt-0 grow",children:fe()}):r.cards.map(re=>e.jsx(t.TabsContent,{className:"mt-0 grow focus-visible:ring-0 focus-visible:ring-offset-0",value:re.id,children:fe()},re.id)),e.jsx(vo,{isPreviewMode:F,onPreviewToggle:i,configCard:l})]})}function yo({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 da({fallbackPreview:s,records:a,title:r,isInspectorOpen:o,onInspectorOpenChange:u}){var P;const i=t.useEditorStore(F=>F.card),l=t.useEditorStore(F=>F.actions.setCard),c=t.useEditorStore(F=>F.actions.updateCardInFrame),d=t.normalizeDynamicRendererSource((P=i.dynamicCardPreferences)==null?void 0:P.rendererCode),[h,x]=v.useState(d),[g,p]=v.useState(d);v.useEffect(()=>{x(d),p(d)},[d,i.id]);const m=v.useMemo(()=>t.normalizeDynamicRendererSource(h),[h]),f=v.useMemo(()=>t.validateDynamicRendererSource(m),[m]),w=!!d,b=v.useMemo(()=>{var F;return t.buildCardWithVisualizationMode(i,g?"dynamic":"builtin",{rendererCode:g||void 0,artifactId:((F=i.dynamicCardPreferences)==null?void 0:F.artifactId)||i.id,title:r||i.title})},[i,g,r]),N=!!g,A=m!==g,_=g!==d,C=!m||!f.valid||A||_,S=m?f.valid?A?"Unapplied changes":"Pending save":"Needs attention":"Draft",I=!m||A||_?"outline":"destructive",E=m?f.valid?A?"The preview still reflects the last applied code until you apply this draft.":_?"Preview reflects pending changes. Accept changes to save them.":"":f.error||"Visual code is invalid.":"Paste visual code or generate one before saving this card.";function D(){if(!f.valid){n.ue.error(f.error||"Visual code is invalid.");return}p(m),n.ue.success("Dynamic preview updated.")}function T(){x(g)}function y(){var j;const F=t.buildCardWithVisualizationMode(i,g?"dynamic":"builtin",{rendererCode:g||void 0,artifactId:((j=i.dynamicCardPreferences)==null?void 0:j.artifactId)||t.v4(),title:r||i.title});l(F),c(F),u(!1),n.ue.success(g?"Dynamic visual changes saved.":"Dynamic visual cleared.")}function L(){x(d),p(d),u(!1)}function M(){x(""),p("")}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:w?e.jsx(n.PersistedDynamicVisual,{card:i,records:a,title:r,layoutMode:"fill",fallback:s},d||"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(n.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(yo,{onClick:()=>u(!0)})]})}),e.jsx(n.Dialog,{open:o,onOpenChange:F=>{if(!F){L();return}u(!0)},children:e.jsxs(n.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(n.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(n.DialogTitle,{children:"Dynamic Visual Editor"}),e.jsx(n.DialogDescription,{children:"Adjust the preview and visual code here. Query editing stays in the normal editor controls."})]}),C&&e.jsx(n.Badge,{className:"mr-4 shrink-0",variant:I,children:S})]})}),e.jsx("div",{className:"min-h-0 flex-1",children:e.jsxs(n.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(n.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:N?e.jsx(n.PersistedDynamicVisual,{card:b,records:a,title:r,layoutMode:"fill",fallback:s},g||"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(n.ResizableHandle,{withHandle:!0}),e.jsx(n.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(n.CodeXml,{className:"h-4 w-4 text-muted-foreground"}),"Visual Code"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(n.AlertDialog,{children:[e.jsx(n.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:!w&&!m,children:[e.jsx(t.X,{className:"h-3.5 w-3.5 shrink-0"}),"Clear"]})}),e.jsxs(n.AlertDialogContent,{children:[e.jsxs(n.AlertDialogHeader,{children:[e.jsx(n.AlertDialogTitle,{children:"Clear dynamic visual?"}),e.jsx(n.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(n.AlertDialogFooter,{children:[e.jsx(n.AlertDialogCancel,{children:"Cancel"}),e.jsx(n.AlertDialogAction,{className:"bg-foreground text-background hover:bg-foreground/90",onClick:M,children:"Clear"})]})]})]}),e.jsxs(t.Button,{type:"button",size:"sm",variant:"outline",className:"h-8 gap-1.5 px-2.5 text-xs",onClick:T,disabled:!A,children:[e.jsx(t.RotateCcw,{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:!A||!f.valid,children:[e.jsx(n.Play,{className:"h-3.5 w-3.5 shrink-0"}),"Apply to Preview"]})]})]}),e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3 p-4",children:[E&&e.jsx("p",{className:t.cn("text-xs",f.valid?"text-muted-foreground":"text-destructive"),children:E}),e.jsx("div",{className:t.cn("min-h-0 flex-1 overflow-hidden rounded-md border",!f.valid&&m&&"border-destructive"),children:e.jsx(t.CodeEditor,{value:h,onValueChange:F=>x(F||""),language:"javascript",embedded:!0})})]})]})})]})}),e.jsxs(n.DialogFooter,{className:"border-t px-6 py-4 sm:justify-between",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:E||"Preview changes here before saving them."}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{type:"button",variant:"outline",size:"sm",className:"h-8 px-3 text-xs",onClick:L,children:"Cancel"}),e.jsx(t.Button,{type:"button",size:"sm",className:"h-8 px-3 text-xs",onClick:y,disabled:!_,children:"Accept changes"})]})]})]})})]})}function ua({onCustomize:s}){const a=t.useEditorStore(h=>h.card),r=t.useEditorStore(h=>h.frame),o=t.useEditorStore(h=>h.actions.setIsShowingVisual),{setVisualizationMode:u,setDynamicCardPreferences:i}=t.useEditorActions(),c=t.getVisualizationMode(a)==="dynamic";if(r.cards.length!==1||t.isCustomVisualizationCard(a))return null;const d=h=>{var x;h==="dynamic"&&!a.dynamicCardPreferences&&i(t.createEmptyDynamicCardPreferences(a.type,(x=a.preferences)==null?void 0:x.displayOptions)),u(h),o(!0)};return e.jsxs(e.Fragment,{children:[e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuItem,{onSelect:h=>{h.preventDefault(),d(c?"builtin":"dynamic")},className:"flex items-center justify-between gap-2 text-[13px]",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.CodeXml,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Dynamic"})]}),e.jsx(t.Switch,{size:"xs",checked:c,onCheckedChange:h=>d(h?"dynamic":"builtin"),onClick:h=>h.stopPropagation()})]}),c&&s?e.jsxs(n.DropdownMenuItem,{onSelect:h=>{h.preventDefault(),s()},className:"gap-2 text-[13px]",children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"}),"Customize Visual"]}):null]})}const No={async writeTextToClipboard(s){return typeof navigator>"u"||!navigator.clipboard?!1:(await navigator.clipboard.writeText(s),!0)}},es=50,Co=[{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 On(s){try{return JSON.stringify(s,null,2)}catch(a){return console.error("Unable to stringify debug payload",a),null}}function It(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 So(s){if(!s||typeof s!="object")return{value:s};const a=s.records;return!Array.isArray(a)||a.length<=es?{value:s}:{value:{...s,records:a.slice(0,es),previewMeta:{truncatedRecords:!0,displayedRecords:es,totalRecords:a.length}},truncationMessage:`Preview showing first ${es} records of ${a.length}. Copy actions include full payload.`}}function ma({sql:s,showCardDetails:a=!1,debugPayloads:r,className:o}){const[u,i]=v.useState(!1),[l,c]=v.useState(null),d=t.useEditorStore(y=>y.card),h=t.useEditorStore(y=>y.frame),x=t.useEditorStore(y=>y.isDevMode),g=t.useDashboardStore(y=>y.selectedSheetId),p=t.useDashboardStore(y=>{var L;return(L=y.dashboard)==null?void 0:L.id}),{switchEditorMode:m,setRunSql:f}=t.useEditorActions(),w=v.useMemo(()=>({cardId:d.id||null,frameId:h.id||null,sheetId:g||null,dashboardId:p||null}),[d.id,h.id,g,p]),b=v.useMemo(()=>({queryRequest:r==null?void 0:r.queryRequest,queryResponse:r==null?void 0:r.queryResponse,cardConfig:d.config,dataSource:d.dataSource,columns:r==null?void 0:r.columns,dashboardFilters:r==null?void 0:r.dashboardFilters,cardMetadata:w}),[r==null?void 0:r.queryRequest,r==null?void 0:r.queryResponse,r==null?void 0:r.columns,r==null?void 0:r.dashboardFilters,d.config,d.dataSource,w]),N=a&&u&&!!r,A=v.useMemo(()=>[{label:"Card ID",value:d.id||""},{label:"Frame ID",value:h.id||""},{label:"Sheet ID",value:g||""},{label:"Dashboard ID",value:p||""}],[d.id,h.id,g,p]),_=()=>{m("dev",{sqlToLoad:s}),setTimeout(()=>{f(!0)},100)},C=y=>b[y]!==void 0,S=v.useMemo(()=>{if(!l)return null;const y=b[l];if(y===void 0)return null;const L=l==="queryResponse"?So(y):{value:y},M=On(L.value);return M?{target:l,title:It(l),json:M,truncationMessage:L.truncationMessage}:null},[l,b]),I=S?S.title:"Preview Payload",E=async y=>{const L=b[y];if(L===void 0)return n.ue.error(`No ${It(y).toLowerCase()} available`),!1;const M=On(L);if(!M)return n.ue.error(`Unable to serialize ${It(y).toLowerCase()}`),!1;try{return await No.writeTextToClipboard(M)?(n.ue.success(`${It(y)} copied`),!0):(n.ue.error("Clipboard is not available"),!1)}catch(P){return console.error("Failed to copy debug payload",P),n.ue.error(`Unable to copy ${It(y).toLowerCase()}`),!1}},D=async()=>S?E(S.target):!1,T=y=>{if(b[y]===void 0){n.ue.error(`No ${It(y).toLowerCase()} available`);return}c(y)};return e.jsxs("div",{className:t.cn("flex max-h-full min-h-0 flex-1 flex-col overflow-hidden pt-3",o),children:[!x&&e.jsxs("div",{className:"mb-3 flex items-center gap-1.5",children:[e.jsxs(t.Button,{onClick:_,variant:"outline",size:"xs",children:[e.jsx(Yn,{className:"mr-1.5 h-3 w-3"}),"View in SQL Editor"]}),a&&e.jsxs(t.Button,{onClick:()=>i(!u),variant:"outline",size:"xs",children:[e.jsx(t.Info,{className:"mr-1.5 h-3 w-3"}),"Card Details"]})]}),u&&a&&e.jsx("div",{className:"mb-3 rounded-[6px] border border-border bg-card p-3",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-[12px] font-semibold uppercase tracking-[0.08em] text-foreground/70",children:"Card Information"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 rounded-[3px] p-0",onClick:()=>i(!1),children:e.jsx(Ne.CircleX,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"grid grid-cols-1 gap-2 md:grid-cols-2",children:A.map(y=>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:y.label}),e.jsx(n.CopyButton,{text:y.value,className:"h-6 w-6 shrink-0"})]}),e.jsx("code",{title:y.value||"N/A",className:"mt-1 block whitespace-normal break-all font-mono text-xs",children:y.value||"N/A"})]},y.label))}),N&&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(n.DropdownMenu,{children:[e.jsx(n.DropdownMenuTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8","aria-label":"Preview Payload Menu",children:[e.jsx(n.Eye,{className:"mr-1.5 h-3.5 w-3.5"}),I,e.jsx(t.ChevronDown,{className:"ml-1.5 h-3.5 w-3.5"})]})}),e.jsx(n.DropdownMenuContent,{align:"start",className:"w-56",children:Co.map(y=>e.jsx(n.DropdownMenuItem,{disabled:!C(y.target),onSelect:()=>T(y.target),className:t.cn(l===y.target&&"bg-accent"),children:y.label},`preview-${y.target}`))})]})}),S&&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:[S.title," Preview"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(n.CopyButton,{text:S.json,className:"h-6 w-6",ariaLabel:"Copy Payload",onCopy:D}),e.jsxs(t.Button,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>c(null),children:[e.jsx(Ne.CircleX,{className:"mr-1 h-3.5 w-3.5"}),"Hide"]})]})]}),S.truncationMessage&&e.jsx("p",{className:"text-xs text-muted-foreground",children:S.truncationMessage}),e.jsx("div",{className:"max-h-80 overflow-auto",children:e.jsx(n.CodeHighlighter,{code:S.json,language:"json"})})]})]})]})}),e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden",children:[e.jsxs("div",{className:"flex h-7 shrink-0 items-center justify-between border-b border-border px-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"rounded-[3px] bg-muted px-1.5 py-0.5 font-mono text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"SQL"}),e.jsx("span",{className:"text-[12px] text-muted-foreground",children:"Generated query"})]}),e.jsx(n.CopyButton,{text:s,className:"h-5 w-5 rounded-[3px] px-0 text-muted-foreground hover:bg-muted hover:text-foreground"})]}),e.jsx("div",{className:"max-h-[calc(min(70vh,640px)-2.75rem)] min-h-[80px] flex-1 overflow-auto px-3 py-2",children:e.jsx(t.CodeEditor,{value:s,onValueChange:()=>{},language:"sql",readOnly:!0,embedded:!0,wrapLines:!0,dense:!0,hideLineNumbers:!0,ariaLabel:"Executed SQL"})})]})]})}function hs({children:s,visualAsideControl:a,mode:r="both",isDynamicInspectorOpen:o,onDynamicInspectorOpenChange:u}){var Se;const i=n.useQueryClient(),l=t.useEditorStore(ie=>ie.frame),c=t.useEditorStore(ie=>ie.card),d=t.useEditorStore(ie=>ie.isDevMode),h=t.useEditorStore(ie=>ie.editorContext),x=(h==null?void 0:h.type)==="documentSection",g=t.useEditorStore(ie=>ie.isShowingVisual),p=t.useEditorStore(ie=>ie.actions.setIsShowingVisual),m=t.useDashboardStore(ie=>ie.isVisualEditing),{isConsoleMode:f}=n.useDashboardPreferences(),w=t.useEditorStore(ie=>ie.pythonStdOut),b=t.useEditorStore(ie=>ie.actions.setRunSql),N=Ne.useEffectiveEditorCardType(),A=N==="table"||N==="detailTable"||N==="matrixTable",C=["table","detailTable","aggregateTable","pivotTable"].includes(N||"")&&!!(a!=null&&a.onOpen),I=t.getVisualizationMode(c)==="dynamic",[E,D]=v.useState(!1),T=o??E,y=u??D,{setFrame:L,setCard:M,setActiveTabCardId:P,setCardPreferences:F,mergeDraftsIntoCard:j,clearModeDrafts:k,initializeModeDrafts:O,updatePageSize:R,setCardType:B}=t.useEditorActions(),z=v.useMemo(()=>N!==c.type?{...c,type:N}:c,[c,N]),{data:V,isLoading:q,isFetching:U,errorMessage:G,errorSql:Q,refetch:Y,queryKey:H,pagination:se}=n.useEditorCardQuery(z),ue=v.useRef(H);ue.current=H;const{handleDebugWithAssistant:ae}=Ds(G,Q),me=v.useMemo(()=>(V==null?void 0:V.records)||[],[V==null?void 0:V.records]),{cardFilterValues:ve}=n.useCardFilterValues((c==null?void 0:c.id)??""),[Oe,Fe]=v.useState(!1);v.useEffect(()=>{U||Fe(!1)},[U]),v.useEffect(()=>{A&&!g&&!d&&!f&&p(!0)},[f,d,A,g,p]);function X(ie,$){var ne,ce;const oe={...c,paginationConfig:{page:ie+1,pageSize:$}};M(oe);const fe={...l,cards:l.cards.map(Te=>Te.id===c.id?oe:Te)};L(fe),c.sql&&((ce=(ne=c.preferences)==null?void 0:ne.tablePrefs)!=null&&ce.enableDevModePagination)&&b(!0)}function ge(ie){var ne,ce,Te,ke,ze;const $=n.sortStateToSortByColumns(ie,(ne=c.config)==null?void 0:ne.metricColumns,(ce=c.config)==null?void 0:ce.groupByColumns,(Te=c.config)==null?void 0:Te.detailColumns),oe={...c,config:{...c.config||{},sortByColumns:$}};M(oe);const fe={...l,cards:l.cards.map(re=>re.id===c.id?oe:re)};L(fe),c.sql&&((ze=(ke=c.preferences)==null?void 0:ke.tablePrefs)!=null&&ze.enableDevModePagination)&&b(!0)}function Ce(){var $;const ie=JSON.stringify(V==null?void 0:V.records,null,2);typeof navigator>"u"||!(($=navigator.clipboard)!=null&&$.writeText)||navigator.clipboard.writeText(ie).catch(oe=>{console.error("Failed to copy JSON",oe)})}function Pe(){const ie=JSON.stringify(V==null?void 0:V.records,null,2),$=new Blob([ie],{type:"application/json"}),oe=URL.createObjectURL($),fe=document.createElement("a");fe.href=oe,fe.download=`${c.title}.json`,fe.click()}function _e(){const $=[Object.keys(V==null?void 0:V.records.reduce((ce,Te)=>({...ce,...Te}),{})).join(","),...((V==null?void 0:V.records)||[]).map(ce=>Object.values(ce).join(","))].join(`
|
|
177
|
-
`),oe=new Blob([$],{type:"text/csv"}),fe=URL.createObjectURL(oe),ne=document.createElement("a");ne.href=fe,ne.download=`${c.title}.csv`,ne.click()}if(!c)return e.jsx(e.Fragment,{children:"No Active Card"});const le=r==="both"||r==="toolbar",De=r==="both"||r==="canvas";return e.jsxs("div",{className:t.cn("relative isolate flex flex-col",r==="toolbar"?"h-auto pb-1":t.cn("h-full",!A&&"pt-2")),children:[le&&e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center gap-2 px-4",children:[g&&e.jsx("div",{className:"flex grow items-center gap-4",children:e.jsx("div",{className:"flex items-center gap-3",children:!x&&!I&&e.jsx(ia,{selectedChart:c.type,onChartChange:ie=>B(ie),compactMore:!0})})}),!g&&e.jsx("div",{className:"grow"}),!q&&!U&&!G&&(V==null?void 0:V.sql)&&e.jsx("div",{className:"inline-flex shrink-0 items-center text-[11px] text-muted-foreground",children:e.jsxs(n.HoverCard,{openDelay:200,children:[e.jsx(n.HoverCardTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"cursor-pointer text-[11px] underline-offset-4 hover:text-foreground hover:underline",children:"Executed SQL"})}),e.jsx(n.HoverCardContent,{align:"end",className:"max-h-[min(70vh,640px)] w-[500px] overflow-hidden p-0",children:e.jsx(ma,{sql:V.sql})})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[s,ve&&ve.length>0&&e.jsxs(n.HoverCard,{openDelay:200,children:[e.jsx(n.HoverCardTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",size:"xs",className:"h-7 gap-1.5 px-2",children:[e.jsx(n.Filter,{className:"h-3.5 w-3.5",strokeWidth:1.75}),e.jsx(n.Badge,{variant:"secondary",className:"h-4 min-w-4 rounded-[4px] px-1 text-[10px] font-medium",children:ve.length})]})}),e.jsxs(n.HoverCardContent,{align:"end",className:"flex max-h-[400px] w-[500px] flex-col overflow-hidden p-0",children:[e.jsx("div",{className:"shrink-0 border-b border-border px-3 py-2 text-[13px] font-medium",children:"Active Dashboard Filters"}),e.jsx("div",{className:"min-h-0 flex-1 overflow-auto",children:e.jsx(t.CodeEditor,{value:JSON.stringify(ve,null,2),onValueChange:()=>{},language:"json",readOnly:!0,embedded:!0,wrapLines:!0,dense:!0,hideLineNumbers:!0,ariaLabel:"Active dashboard filters JSON"})})]})]}),e.jsx(n.IconButton,{tooltip:"Refresh",disabled:q||U,className:"h-7 w-7 px-0",onClick:()=>{if(Fe(!0),d){bt.flushPendingEditorDrafts(),setTimeout(()=>{i.removeQueries({queryKey:ue.current,exact:!0}),b(!0)},0);return}Y()},children:e.jsx(Jn,{className:t.cn("h-3.5 w-3.5",{"animate-spin":Oe})})}),!I&&e.jsx(ca,{showInlineFilters:!1,showControls:!1,showDisplayOptions:!1}),(a==null?void 0:a.show)&&e.jsxs(t.Button,{type:"button",variant:"outline",size:"xs","aria-pressed":a.isOpen,onClick:a.onToggle,className:t.cn("h-7 gap-1.5 px-2 text-[12px]",a.isOpen&&"bg-muted/40 text-foreground"),children:[e.jsx(n.Settings2,{className:"h-3.5 w-3.5",strokeWidth:1.75}),"Settings"]}),(d||f)&&e.jsx(Eo,{}),(d||f)&&A&&e.jsx(To,{}),e.jsxs(n.DropdownMenu,{modal:!1,children:[e.jsx(n.DropdownMenuTrigger,{asChild:!0,children:e.jsx(n.IconButton,{tooltip:"More Options",className:"h-7 w-7 px-0","aria-label":"More options",children:e.jsx(n.EllipsisVertical,{className:"h-3.5 w-3.5"})})}),e.jsxs(n.DropdownMenuContent,{align:"end",className:"w-56",children:[e.jsx(n.DropdownMenuLabel,{children:"Customize"}),!I&&!["table","detailTable","custom"].includes(c.type)&&m&&e.jsx(so,{triggerVariant:"menu",className:"w-full"}),e.jsx(Ls,{triggerVariant:"menu",className:"w-full"}),e.jsx(Ms,{triggerVariant:"menu",className:"w-full"}),e.jsx(As,{triggerVariant:"menu",className:"w-full"}),C&&e.jsxs(n.DropdownMenuItem,{onSelect:()=>{var ie;return(ie=a==null?void 0:a.onOpen)==null?void 0:ie.call(a,"style")},className:"gap-2 text-[13px]",children:[e.jsx(ar,{className:"h-3.5 w-3.5"}),"Table settings"]}),e.jsx(ua,{onCustomize:()=>y(!0)}),e.jsx(n.DropdownMenuSeparator,{}),e.jsx(n.DropdownMenuLabel,{children:"Export"}),e.jsxs(n.DropdownMenuItem,{onSelect:_e,className:"gap-2 text-[13px]",children:[e.jsx(n.Download,{className:"h-3.5 w-3.5"}),"Download CSV"]}),e.jsxs(n.DropdownMenuItem,{onSelect:Pe,className:"gap-2 text-[13px]",children:[e.jsx(Ya,{className:"h-3.5 w-3.5"}),"Download JSON"]}),e.jsxs(n.DropdownMenuItem,{onSelect:Ce,className:"gap-2 text-[13px]",children:[e.jsx(n.Copy,{className:"h-3.5 w-3.5"}),"Copy JSON"]})]})]})]})]}),De&&(g?I?e.jsx(gt,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(da,{fallbackPreview:e.jsx(gt,{}),records:me,title:c.title,isInspectorOpen:T,onInspectorOpenChange:y})}):e.jsx(gt,{}):e.jsxs(n.ResizablePanelGroup,{className:t.cn(w&&"py-2 pl-2 pr-6"),direction:"horizontal",children:[w&&e.jsxs(e.Fragment,{children:[e.jsx(n.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:w&&e.jsx(wo,{})}),e.jsx(n.ResizableHandle,{})]}),e.jsxs(n.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":w}),children:[Array.isArray(V==null?void 0:V.records)&&!G&&(d?e.jsx(Jr,{data:V.records,card:z,paginationMetadata:se,onPaginationChange:X,onPageSizePreferenceChange:R,onSortChange:ge,isLoading:q||U}):V.records.length>0?e.jsx(n.TableVisual,{card:c,data:me,totalsByColumnId:V==null?void 0:V.tableTotalsByColumnId,comparisonMetadata:(Se=V==null?void 0:V.metadata)==null?void 0:Se.comparisonMetadata,paginationMetadata:se,onPaginationChange:X,onSortChange:ge,isLoading:q||U}):null),G&&e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(ns,{error:G,errorSql:Q||c.sql||c.python,onDebugWithAssistant:ae,showFeedbackButton:!1})})]})]}))]})}function wo(){const s=t.useEditorStore(r=>r.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 To(){var c,d,h,x,g,p,m,f;const s=t.useEditorStore(w=>w.card),a=t.useEditorStore(w=>w.actions.setCard),r=t.useEditorStore(w=>w.actions.setRunSql),o=t.useEditorStore(w=>w.actions.setCardPreferences),u=t.useEditorStore(w=>w.actions.updateCardInFrame),i=v.useMemo(()=>{var w,b;return n.getTablePageSizeOptions((b=(w=s.preferences)==null?void 0:w.tablePrefs)==null?void 0:b.pageSize)},[(d=(c=s.preferences)==null?void 0:c.tablePrefs)==null?void 0:d.pageSize]),l=n.resolveTablePageSize((x=(h=s.preferences)==null?void 0:h.tablePrefs)==null?void 0:x.pageSize);return s.type!=="table"&&s.type!=="detailTable"?null:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Checkbox,{id:"dev-pagination",checked:((p=(g=s.preferences)==null?void 0:g.tablePrefs)==null?void 0:p.enableDevModePagination)??!1,onCheckedChange:w=>{var b;o({...s.preferences,tablePrefs:{...(b=s.preferences)==null?void 0:b.tablePrefs,enableDevModePagination:w}})}}),e.jsx(t.Label,{htmlFor:"dev-pagination",className:"cursor-pointer text-[13px]",children:"Paginate"}),((f=(m=s.preferences)==null?void 0:m.tablePrefs)==null?void 0:f.enableDevModePagination)&&e.jsxs(t.Select,{value:String(l),onValueChange:w=>{var A,_,C;const b=Number(w),N={...s,preferences:{...s.preferences,tablePrefs:{...(A=s.preferences)==null?void 0:A.tablePrefs,pageSize:b}},paginationConfig:{page:1,pageSize:b}};a(N),u(N),s.sql&&((C=(_=s.preferences)==null?void 0:_.tablePrefs)!=null&&C.enableDevModePagination)&&r(!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(w=>e.jsx(t.SelectItem,{value:String(w),children:w},w))})]})]})}function Eo(){const s=t.useEditorStore(r=>r.isShowingVisual),a=t.useEditorStore(r=>r.actions.setIsShowingVisual);return e.jsxs(n.Toggle,{pressed:!s,onPressedChange:r=>{a(!r)},variant:"default",size:"sm","aria-label":"Toggle results",className:"h-7 gap-1.5 rounded-[5px] border border-border/60 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:"Results"})]})}function We({value:s,onCommit:a,type:r="text",placeholder:o,className:u}){const[i,l]=v.useState(s),c=v.useRef(!1);v.useEffect(()=>{l(s)},[s]);const d=()=>{if(c.current){c.current=!1;return}i!==s&&a(i)},h=x=>{if(x.key==="Enter"){x.currentTarget.blur();return}x.key==="Escape"&&(c.current=!0,l(s),x.currentTarget.blur())};return e.jsx(t.Input,{type:r,placeholder:o,value:i,onChange:x=>l(x.target.value),onBlur:d,onKeyDown:h,className:u})}function ut({defaultValue:s,label:a,options:r,value:o,onValueChange:u,className:i,icon:l,showPlaceholderLabel:c=!0}){return e.jsxs(t.Select,{defaultValue:s,value:o,onValueChange:u,children:[e.jsx(t.SelectTrigger,{className:t.cn("w-full focus:ring-0 focus:ring-offset-0",i),children:e.jsxs("div",{className:"flex items-center gap-2",children:[l&&e.jsx("span",{children:l}),c&&e.jsx(t.SelectValue,{placeholder:a})]})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:a}),r.map(d=>e.jsx(t.SelectItem,{value:d.value,children:d.label},d.value))]})})]})}function Io(s,a){return n.getSlotDefinitionForIndex(s,a)||null}function zt(s){if(typeof s=="number")return`Tab ${s+1}`;const a=s.match(/^(\d+)-(\d+)$/);if(a){const[,o,u]=a;return`Tabs ${Number(o)+1}-${Number(u)+1}`}const r=s.match(/^(\d+)\+$/);return r?`Tabs ${Number(r[1])+1}+`:`Tab ${s}`}function Do(s){return s?Array.isArray(s)?s:[s]:[]}function ps(s){var o,u;if(!s)return!1;if(s.type==="text")return!!((o=s.description)!=null&&o.trim());const a=!!((u=s.sql)!=null&&u.trim()),r=t.hasValidCardConfig(s.config);return a||r}function ko({slots:s,cards:a,minInputs:r}){const o=[],u=a.filter(Boolean).length;return r&&u<r&&o.push({type:"too-few-inputs",message:`This visual requires at least ${r} tab${r===1?"":"s"}.`}),!s||s.length===0||(s.forEach(i=>{if(!i.required)return;if(typeof i.position=="number"){const d=a[i.position];ps(d)||o.push({type:"missing-required",message:`${zt(i.position)} ("${i.label}") is required but has no data configured.`});return}const l=i.position.match(/^(\d+)-(\d+)$/);if(l){const[,d,h]=l.map(Number);for(let x=d;x<=h;x+=1){const g=a[x];if(!ps(g)){o.push({type:"missing-required",message:`${zt(x)} ("${i.label}") is required but has no data configured.`});break}}return}const c=i.position.match(/^(\d+)\+$/);if(c){const d=Number(c[1]);if(a.length<=d){o.push({type:"missing-required",message:`${zt(d)} ("${i.label}") is required but has no data configured.`});return}for(let h=d;h<a.length;h+=1){const x=a[h];if(!ps(x)){o.push({type:"missing-required",message:`${zt(h)} ("${i.label}") is required but has no data configured.`});break}}}}),a.forEach((i,l)=>{if(!i)return;const c=Io(s,l);if(!c||!c.expectedType)return;const d=Do(c.expectedType);d.length!==0&&(d.includes(i.type)||o.push({type:"wrong-type",message:`${zt(l)} ("${c.label}") expects ${d.join(", ")}, but is configured as ${i.type}.`}))})),o}const Ao={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 xa(){var M,P,F;const s=t.useEditorStore(j=>j.card.customCardPreferences),{data:a}=n.usePluginQuery(),r=(a==null?void 0:a.plugins)||[],o=t.useEditorStore(j=>j.card),u=t.useEditorStore(j=>j.frame),{setCustomCardPreferences:i}=t.useEditorActions(),l=v.useMemo(()=>n.findCustomVisualConfigCard(u,o),[u,o]),c=l==null?void 0:l.customCardPreferences,{components:d,manifest:h}=n.useCustomVisual((c==null?void 0:c.url)||(s==null?void 0:s.url)||""),x=(M=h==null?void 0:h.visuals)==null?void 0:M.find(j=>j.name===((c==null?void 0:c.componentName)||(s==null?void 0:s.componentName))),p=n.resolveMultiInputType(l||o,x)==="multiple",m=!!l&&l.id===o.id,f=(x==null?void 0:x.minInputs)??((P=l==null?void 0:l.customCardPreferences)==null?void 0:P.minInputs),w=(x==null?void 0:x.maxInputs)??((F=l==null?void 0:l.customCardPreferences)==null?void 0:F.maxInputs),b=v.useMemo(()=>n.getCustomVisualInputCards({frame:u,configCard:l||o,isMultiInputVisual:p}),[u,l,o,p]),N=v.useMemo(()=>n.buildSlotOrderedCards(b),[b]),A=v.useMemo(()=>N.map((j,k)=>{if(!j)return null;const O=n.getSlotIndexForCard(j,k),R=n.getEffectiveCardTypeForSlot(j,O,x==null?void 0:x.slots);return{...j,type:R??j.type}}),[N,x==null?void 0:x.slots]),_=v.useMemo(()=>ko({slots:x==null?void 0:x.slots,cards:A,minInputs:f}),[x==null?void 0:x.slots,A,f]),C=v.useMemo(()=>{const j=b.findIndex(k=>(k==null?void 0:k.id)===o.id);return j<0?-1:n.getSlotIndexForCard(o,j)},[b,o]);function S(j){if(typeof j=="number")return`Tab ${j+1}`;const k=j.match(/^(\d+)-(\d+)$/);if(k){const[,R,B]=k;return`Tabs ${Number(R)+1}-${Number(B)+1}`}const O=j.match(/^(\d+)\+$/);return O?`Tabs ${Number(O[1])+1}+`:`Tab ${j}`}function I(j){return j?(Array.isArray(j)?j:[j]).join(", "):null}function E(j,k,O=[],R="",B,z,V){const q=D({key:k,defaultValue:R,settingsValue:z,sourceCard:V});return j==="input"?e.jsx(We,{className:`h-8 w-full ${t.removeRing}`,value:String(q??""),onCommit:U=>{T({key:k,value:U,settingsField:B,settingsValue:z,sourceCard:V})}},k):j==="select"?e.jsx(ut,{className:"h-8 w-full",label:"",options:O,value:String(q!==void 0?q:R??""),onValueChange:U=>{T({key:k,value:U,settingsField:B,settingsValue:z,sourceCard:V})}}):null}function D({key:j,defaultValue:k,settingsValue:O,sourceCard:R}){const B=O==null?void 0:O[j];return B!==void 0?B:j==="title"&&(R==null?void 0:R.title)!==void 0?R.title:j==="description"&&(R==null?void 0:R.description)!==void 0?R.description:k}function T({key:j,value:k,settingsField:O,settingsValue:R,sourceCard:B}){const z={...R||{}},V=j==="title"&&(B==null?void 0:B.title)!==void 0,q=j==="description"&&(B==null?void 0:B.description)!==void 0;V&&k===String((B==null?void 0:B.title)??"")||q&&k===String((B==null?void 0:B.description)??"")?delete z[j]:z[j]=k,i({...s||{},[O]:z})}function y({settingsSchema:j,settingsField:k,settingsValue:O,sourceCard:R,headerLabel:B}){const z=Object.entries(j||{});return e.jsxs("div",{className:"space-y-3",children:[B&&e.jsx(t.Label,{children:B}),z.map(([V,q])=>{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:q.title}),((U=q.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:q.docs.description})})]})})]}),E(q.ui,V,q.options,q.defaultValue,k,O,R)]},V)})]})}function L(){return e.jsxs(e.Fragment,{children:[p&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Slot Guide"}),e.jsx("div",{className:"space-y-3 rounded-md border border-border bg-muted/40 px-3 py-2 text-xs",children:x!=null&&x.slots&&x.slots.length>0?e.jsx("div",{className:"space-y-3",children:x.slots.map((j,k)=>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:S(j.position)}),e.jsx("span",{className:"text-muted-foreground",children:"•"}),e.jsx("span",{className:"font-medium",children:j.label})]}),j.description&&e.jsx("p",{className:"text-muted-foreground",children:j.description}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-muted-foreground",children:[I(j.expectedType)&&e.jsxs("span",{children:["Expected: ",I(j.expectedType)]}),j.required&&e.jsx("span",{children:"Required"})]})]},`${j.label}-${k}`))}):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."}),(f||w)&&e.jsxs("p",{children:[f?`Min ${f} tabs`:"",f&&w?" • ":"",w?`Max ${w} tabs`:""]})]})})]}),p&&_.length>0&&e.jsx(n.Alert,{className:"mt-3 border-yellow-500/40 bg-yellow-500/10 text-yellow-900 dark:text-yellow-100",children:e.jsx(n.AlertDescription,{children:e.jsx("ul",{className:"list-disc space-y-1 pl-4 text-xs",children:_.map((j,k)=>e.jsx("li",{children:j.message},`${j.type}-${k}`))})})}),x&&!p&&x.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:y({settingsSchema:x.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:o})})}),x&&p&&(x.settings||x.slotSettings)&&e.jsxs("div",{className:"mt-4 space-y-4",children:[m&&x.settings&&e.jsx("div",{className:"px-2",children:y({settingsSchema:x.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:l||o,headerLabel:"Global Settings"})}),x.slotSettings&&e.jsx("div",{className:"px-2",children:y({settingsSchema:x.slotSettings,settingsField:"slotSettings",settingsValue:s==null?void 0:s.slotSettings,sourceCard:o,headerLabel:(()=>{const j=o.tabTitle||o.title,k=C>=0?C:0,O=m?"Slot 0":`Slot ${k}`;return j?`${O}: ${j} Settings`:`${O} Settings`})()})})]})]})}return e.jsxs(n.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"",children:[e.jsxs(n.AccordionItem,{value:"plugin-settings",children:[e.jsx(n.AccordionTrigger,{children:"Plugin"}),e.jsx(n.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[(!p||m)&&e.jsx(ut,{icon:e.jsx(Wn,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:r,value:(c==null?void 0:c.url)||"",onValueChange:j=>i({...s||{url:"",componentName:""},url:j})}),p&&!m&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Switch to the config tab to change the plugin or component."})]})}),((s==null?void 0:s.type)==="component"||(s==null?void 0:s.type)===void 0)&&s&&(!p||m)&&e.jsx(e.Fragment,{children:d&&e.jsx(ut,{icon:e.jsx(Wa,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(d==null?void 0:d.map(j=>({value:j.name,label:j.name})))||[],value:s.componentName||"",onValueChange:j=>{var R;const k=(R=h==null?void 0:h.visuals)==null?void 0:R.find(B=>B.name===j),O=d==null?void 0:d.find(B=>B.name===j);i({...s,componentName:j,visualType:(k==null?void 0:k.visualType)||(O==null?void 0:O.type)||"single",minInputs:k==null?void 0:k.minInputs,maxInputs:k==null?void 0:k.maxInputs,pluginChartType:k==null?void 0:k.chartType})}})})]})})]}),((c==null?void 0:c.componentName)||(s==null?void 0:s.componentName))&&e.jsxs(n.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(n.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:(x==null?void 0:x.name)||"Settings"}),(x==null?void 0:x.docs)&&e.jsxs(n.HoverCard,{openDelay:0,closeDelay:100,children:[e.jsx(n.HoverCardTrigger,{asChild:!0,onClick:j=>j.stopPropagation(),children:e.jsx(t.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground transition-colors hover:text-foreground"})}),e.jsx(n.HoverCardContent,{side:"right",align:"start",className:"max-h-[40vh] w-[500px] overflow-y-auto text-left",children:e.jsxs("div",{className:"space-y-4 text-left",children:[x.docs.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:x.docs.description}),x.docs.dataSchema&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Data Schema"}),e.jsx("div",{className:"prose prose-sm dark:prose-invert prose-pre:bg-muted prose-pre:text-xs max-w-none",children:e.jsx(n.Markdown,{remarkPlugins:[n.remarkGfm],components:Ao,children:x.docs.dataSchema})})]}),(()=>{var k;const j=(k=x.docs)==null?void 0:k.useCases;return!j||j.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Use Cases"}),e.jsx("ul",{className:"space-y-1 text-sm",children:j.map((O,R)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1 text-primary",children:"•"}),e.jsx("span",{children:O})]},R))})]})})()]})})]})]})}),e.jsx(n.AccordionContent,{children:L()})]})]})}function Lo({colorRanges:s,setColorRanges:a}){const r={start:-1/0,end:100,color:""};function o(l,c,d){const h=[...s];h[l]={...h[l],[c]:d},a(h)}function u(l){const c=[...s];c.splice(l,1),a(c)}function i(){a([...s,r])}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(n.Plus,{className:"size-3"})})]}),s.map((l,c)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(t.Input,{onChange:d=>o(c,"start",d.target.value),value:l.start,className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(t.Input,{value:l.end,onChange:d=>o(c,"end",d.target.value),className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx(t.Input,{onChange:d=>o(c,"color",d.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:()=>u(c),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(t.X,{className:"size-3"})})]},c))]})}function Mo(){var x,g,p,m,f;const s=t.useEditorStore(w=>w.card.preferences),a=t.useEditorStore(w=>w.actions.setCardPreferences),r=t.useEditorStore(w=>w.card),o=t.hasValidCardConfig(r.config),u=t.useEditorStore(w=>w.actions.setNumberFormat);t.useEditorStore(w=>{var b,N;return(N=(b=w.card.preferences)==null?void 0:b.formatNumber)==null?void 0:N.decimalPlaces});const i=t.useEditorStore(w=>{var b,N;return(N=(b=w.card.preferences)==null?void 0:b.formatNumber)==null?void 0:N.locale}),l=t.useEditorStore(w=>{var b,N;return(N=(b=w.card.preferences)==null?void 0:b.formatNumber)==null?void 0:N.currency});t.useEditorStore(w=>w.actions.setFilterOnClickField);const c=t.useEditorStore(w=>{var b,N;return(N=(b=w.card.preferences)==null?void 0:b.formatNumber)==null?void 0:N.colorRanges})||[],d=t.useEditorStore(w=>w.actions.setColorRanges),h=[...new Set(t.LOCALE_CURRENCY_PAIRS.map(w=>w.currency))];return e.jsxs("div",{children:[!o&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(n.Checkbox,{checked:!!((x=s==null?void 0:s.formatNumber)!=null&&x.enabled),onCheckedChange:w=>{a({...s,formatNumber:{...s==null?void 0:s.formatNumber,enabled:w}})}}),e.jsx(t.Label,{children:"Format Number"})]}),(((g=s==null?void 0:s.formatNumber)==null?void 0:g.enabled)===!0||o)&&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:w=>{var b,N,A;return u(((b=s==null?void 0:s.formatNumber)==null?void 0:b.decimalPlaces)||0,((N=s==null?void 0:s.formatNumber)==null?void 0:N.currency)||"",w,((A=s==null?void 0:s.formatNumber)==null?void 0:A.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(w=>e.jsx(t.SelectItem,{value:w.locale,children:w.locale},w.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:w=>{var b,N,A;console.log("currency",w),u(((b=s==null?void 0:s.formatNumber)==null?void 0:b.decimalPlaces)||0,w==="none"?"":w,((N=s==null?void 0:s.formatNumber)==null?void 0:N.locale)||"",((A=s==null?void 0:s.formatNumber)==null?void 0:A.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"),h.map(w=>e.jsx(t.SelectItem,{value:w,children:w},w))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Decimals"}),e.jsxs(t.Select,{value:((m=(p=s==null?void 0:s.formatNumber)==null?void 0:p.decimalPlaces)==null?void 0:m.toString())||"0",onValueChange:w=>{var b,N,A;return u(Number(w),((b=s==null?void 0:s.formatNumber)==null?void 0:b.currency)||"",((N=s==null?void 0:s.formatNumber)==null?void 0:N.locale)||"",((A=s==null?void 0:s.formatNumber)==null?void 0:A.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(w=>e.jsx(t.SelectItem,{value:w,children:w},w))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Suffix"}),e.jsx(t.Input,{value:((f=s==null?void 0:s.formatNumber)==null?void 0:f.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:w=>{var b,N,A;return u(((b=s==null?void 0:s.formatNumber)==null?void 0:b.decimalPlaces)||0,((N=s==null?void 0:s.formatNumber)==null?void 0:N.currency)||"",((A=s==null?void 0:s.formatNumber)==null?void 0:A.locale)||"",w.target.value)}})]})]})]})}),e.jsx(t.Separator,{className:"my-3"}),e.jsx(Lo,{colorRanges:c,setColorRanges:d})]})]})}const Fo={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 ha(s){return Fo[s]}function Ro({chartType:s,showDocsLink:a=!0}){const r=ha(s);return r?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:r.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:r.fields.map((o,u)=>e.jsxs("tr",{className:u<r.fields.length-1?"border-b":"",children:[e.jsxs("td",{className:"px-2.5 py-1.5 font-medium text-foreground",children:[o.name,o.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:o.type}),e.jsx("td",{className:"px-2.5 py-1.5 text-muted-foreground",children:o.description||"—"})]},o.name))})]})})]}),e.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:r.description}),a&&r.docsUrl&&e.jsxs("a",{href:r.docsUrl,target:"_blank",rel:"noopener noreferrer",onClick:o=>o.stopPropagation(),className:"inline-flex items-center gap-1.5 text-xs font-medium text-primary hover:underline",children:["View documentation",e.jsx(n.ExternalLink,{className:"h-3 w-3"})]})]}):null}function Oo({chartType:s}){return ha(s)?e.jsxs(n.HoverCard,{openDelay:200,children:[e.jsx(n.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(n.HoverCardContent,{className:"w-80 p-4",side:"left",align:"start",sideOffset:8,children:e.jsx(Ro,{chartType:s})})]}):null}function Fs({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(Oo,{chartType:s})]})}function Po(){return e.jsxs("div",{className:"space-y-6 px-6 py-4",children:[e.jsx(Fs,{chartType:"kpi"}),e.jsx("section",{children:e.jsx(Mo,{})})]})}function Pn({children:s,summary:a,open:r,className:o}){return e.jsxs("details",{open:r,className:t.cn("space-y-4 [&_summary>svg]:open:-rotate-180",o),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 Vo(){const[s,a]=v.useState([]),r=t.useEditorStore(h=>h.card.preferences),{setFilterOnClickColumnIndex:o,setCardPreferences:u}=t.useEditorStore(h=>h.actions),i=t.useEditorStore(h=>h.queryResultColumns);t.useEditorStore(h=>{var x;return(x=h.card.preferences)==null?void 0:x.filterOnClickColumnIndex}),v.useEffect(()=>{i&&a(new Array(i.length).fill(!1))},[i]);function l(h,x){var g,p;x?r!=null&&r.onClickFilter&&((g=r==null?void 0:r.onClickFilter)==null?void 0:g.length)>0?u({...r,onClickFilter:[...r.onClickFilter,{columnIndex:h,expression:""}]}):u({...r,onClickFilter:[{columnIndex:h,expression:""}]}):(u({...r,onClickFilter:(p=r==null?void 0:r.onClickFilter)==null?void 0:p.filter(m=>m.columnIndex!==h)}),a(m=>{const f=[...m];return f[h]=!1,f}))}function c(h,x){var p;const g=(p=r==null?void 0:r.onClickFilter)==null?void 0:p.map(m=>m.columnIndex===h?{...m,expression:x.target.value}:m);u({...r,onClickFilter:g})}function d(h){var x,g,p,m;if(s!=null&&s[h]||(g=(x=r==null?void 0:r.onClickFilter)==null?void 0:x.find(f=>f.columnIndex===h))!=null&&g.expression)return e.jsx(t.Input,{value:(m=(p=r==null?void 0:r.onClickFilter)==null?void 0:p.find(f=>f.columnIndex===h))==null?void 0:m.expression,onChange:f=>c(h,f),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((h,x)=>{var g,p;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(n.Checkbox,{checked:!!((g=r==null?void 0:r.onClickFilter)!=null&&g.find(m=>m.columnIndex===x)),onCheckedChange:m=>l(x,m)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:h}),e.jsx("div",{className:"flex items-center gap-2",children:((p=r==null?void 0:r.onClickFilter)==null?void 0:p.find(m=>m.columnIndex===x))&&e.jsx(n.Pencil,{onClick:()=>{a(m=>{const f=[...m];return f[x]=!m[x],f})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(x)]})},h)})})}const Bo=[{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"}],_o=["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"],zo=_o.map(s=>({label:s,value:s}));function qo(){var d,h,x,g,p,m,f,w,b,N,A,_,C,S,I,E,D,T;const s=t.useEditorStore(y=>y.card),a=(h=(d=s==null?void 0:s.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:h.topoJsonUrl,[r,o]=v.useState(((g=(x=s==null?void 0:s.preferences)==null?void 0:x.mapVisualOptions)==null?void 0:g.customTopoJsonUrl)||""),{setCardPreferences:u}=t.useEditorActions(),{data:i}=n.useTopoJson(s),l=Object.keys((i==null?void 0:i.objects)||{}).map(y=>({label:y,value:y}))||[],c=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(Fs,{chartType:"map"}),e.jsx(Pn,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(ut,{className:"h-9",options:c,onValueChange:y=>{console.log("value",y),u({...s.preferences,mapVisualOptions:{topoJsonUrl:y}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(t.Input,{onChange:y=>{o(y.target.value)},onBlur:()=>{var y;console.log("onBlur",r),u({...s.preferences,mapVisualOptions:{...(y=s.preferences)==null?void 0:y.mapVisualOptions,customTopoJsonUrl:r}})},value:r,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(ut,{className:"h-9",options:l,value:((m=(p=s.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:m.objectKey)||"",label:"Map Object",onValueChange:y=>{var L;u({...s.preferences,mapVisualOptions:{...(L=s.preferences)==null?void 0:L.mapVisualOptions,objectKey:y}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Projection"}),e.jsx(ut,{className:"h-9",options:Bo,value:((w=(f=s.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:w.projection)||"",label:"Projection",onValueChange:y=>{var L;u({...s.preferences,mapVisualOptions:{...(L=s.preferences)==null?void 0:L.mapVisualOptions,projection:y}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Colors"}),e.jsx(ut,{className:"h-9",options:zo,value:((N=(b=s.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:N.colorScale)||"",label:"Select Color Scale",onValueChange:y=>{var L;u({...s.preferences,mapVisualOptions:{...(L=s.preferences)==null?void 0:L.mapVisualOptions,colorScale:y}})}})]})]})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(Pn,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:.1,value:((_=(A=s.preferences)==null?void 0:A.mapVisualOptions)==null?void 0:_.projectionScale)||1,onChange:y=>{var L;u({...s.preferences,mapVisualOptions:{...(L=s.preferences)==null?void 0:L.mapVisualOptions,projectionScale:Number(y.target.value)}})}}),e.jsx(t.Label,{children:"X"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((I=(S=(C=s.preferences)==null?void 0:C.mapVisualOptions)==null?void 0:S.projectionOffset)==null?void 0:I[0])||0,onChange:y=>{var L,M,P,F;u({...s.preferences,mapVisualOptions:{...(L=s.preferences)==null?void 0:L.mapVisualOptions,projectionOffset:[Number(y.target.value),((F=(P=(M=s.preferences)==null?void 0:M.mapVisualOptions)==null?void 0:P.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:((T=(D=(E=s.preferences)==null?void 0:E.mapVisualOptions)==null?void 0:D.projectionOffset)==null?void 0:T[1])||0,onChange:y=>{var L,M,P,F;u({...s.preferences,mapVisualOptions:{...(L=s.preferences)==null?void 0:L.mapVisualOptions,projectionOffset:[((F=(P=(M=s.preferences)==null?void 0:M.mapVisualOptions)==null?void 0:P.projectionOffset)==null?void 0:F[0])||0,Number(y.target.value)]}})}})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(Vo,{})]})}function ts(s){return s==="currency"?2:s==="percent"?1:s==="scientific"?2:0}function pa(s,a){if(!a||a==="auto")return{type:"auto"};if(a==="duration")return{type:"duration",multiplyBy:void 0,percentValueMode:void 0,durationInputUnit:s.durationInputUnit||"second",durationDisplayStyle:s.durationDisplayStyle||"compact",durationLargestUnit:s.durationLargestUnit||"day",durationSmallestUnit:s.durationSmallestUnit||"second",durationMaxUnits:s.durationMaxUnits};const r={...s,type:a,multiplyBy:a==="percent"?s.multiplyBy:void 0,percentValueMode:a==="percent"?s.percentValueMode:void 0,durationInputUnit:void 0,durationDisplayStyle:void 0,durationLargestUnit:void 0,durationSmallestUnit:void 0,durationMaxUnits:void 0};return a&&["number","currency","percent","scientific"].includes(a)&&s.decimalPlaces===void 0&&s.minimumFractionDigits===void 0&&s.maximumFractionDigits===void 0?Es(r,ts(a)):r}function $o(s){const a=s.type||"auto";return a==="auto"?s:a==="duration"?{type:"duration",prefix:s.prefix,suffix:s.suffix,negativeInParentheses:s.negativeInParentheses,durationInputUnit:s.durationInputUnit||"second",durationDisplayStyle:s.durationDisplayStyle||"compact",durationLargestUnit:s.durationLargestUnit||"day",durationSmallestUnit:s.durationSmallestUnit||"second",durationMaxUnits:s.durationMaxUnits}:pa(s,a)}function Es(s,a){return{...s,decimalPlaces:a,minimumFractionDigits:a,maximumFractionDigits:a}}const Ko=["auto","number","currency","percent","scientific","date","duration"],Uo=[{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"}],Go=[{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"}],fs=[{value:"millisecond",label:"Milliseconds"},{value:"second",label:"Seconds"},{value:"minute",label:"Minutes"},{value:"hour",label:"Hours"},{value:"day",label:"Days"}],Ho=[{value:"compact",label:"Compact (6min 32s)"},{value:"digital",label:"Digital (6:32)"},{value:"long",label:"Long (6 minutes 32 seconds)"}],Qo=s=>s.charAt(0).toUpperCase()+s.slice(1);function kt({formatOptions:s={},onFormatOptionsChange:a,showTitle:r=!0,title:o="NUMBER FORMAT"}){const u=s.type||"auto",i=$o(s),l=m=>{m.stopPropagation()},c=(m,f)=>{a({...i,[m]:f})},[d,h]=v.useState(()=>String(i.decimalPlaces??ts(u))),[x,g]=v.useState(()=>i.multiplyBy!==void 0?String(i.multiplyBy):""),p=m=>{a(pa(s,m))};return v.useEffect(()=>{h(String(i.decimalPlaces??ts(u)))},[i.decimalPlaces,u]),v.useEffect(()=>{g(i.multiplyBy!==void 0?String(i.multiplyBy):"")},[i.multiplyBy]),e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[r&&e.jsx(t.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:o}),e.jsxs(t.Select,{value:u,onValueChange:m=>p(m),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",onClick:l,onPointerDown:l,onKeyDown:l,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ko.map(m=>e.jsx(t.SelectItem,{value:m,className:"text-xs",children:m==="auto"?"Auto (Default)":Qo(m)},m))})]})]}),u!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent","scientific"].includes(u)&&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:d,onClick:l,onPointerDown:l,onKeyDown:l,onChange:m=>{const f=m.target.value.replace(/[^\d]/g,"");h(f),f!==""&&a(Es(i,Math.max(0,Math.min(10,parseInt(f,10)))))},onBlur:()=>{if(d!=="")return;const m=ts(u);h(String(m)),a(Es(i,m))},className:"h-8 text-xs"})})]}),u==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(t.Select,{value:s.currency||"USD",onValueChange:m=>c("currency",m),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:l,onPointerDown:l,onKeyDown:l,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Uo.map(m=>e.jsx(t.SelectItem,{value:m.value,className:"text-xs",children:m.label},m.value))})]})]}),["number","currency"].includes(u)&&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=>c("useSuffix",m)})]}),u!=="duration"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(t.Select,{value:s.locale||"en-US",onValueChange:m=>c("locale",m),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:l,onPointerDown:l,onKeyDown:l,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Go.map(m=>e.jsx(t.SelectItem,{value:m.value,className:"text-xs",children:m.label},m.value))})]})]}),u==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{placeholder:"e.g., $",value:s.prefix||"",onClick:l,onPointerDown:l,onKeyDown:l,onChange:m=>c("prefix",m.target.value),className:"h-8 text-xs"})})]}),u==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{placeholder:"e.g., units",value:s.suffix||"",onClick:l,onPointerDown:l,onKeyDown:l,onChange:m=>c("suffix",m.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(u)&&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=>c("negativeInParentheses",m)})]}),u==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{type:"text",inputMode:"decimal",placeholder:"100",value:x,onClick:l,onPointerDown:l,onKeyDown:l,onChange:m=>{const f=m.target.value.replace(/[^0-9.]/g,"");g(f),c("multiplyBy",f?parseFloat(f):void 0)},className:"h-8 text-xs"})})]}),u==="date"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Format"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{type:"text",placeholder:"MM/DD/YYYY",value:s.dateFormat||"",onClick:l,onPointerDown:l,onKeyDown:l,onChange:m=>c("dateFormat",m.target.value),className:"h-8 text-xs"})})]}),u==="duration"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Value Is"}),e.jsxs(t.Select,{value:s.durationInputUnit||"second",onValueChange:m=>c("durationInputUnit",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:fs.map(m=>e.jsx(t.SelectItem,{value:m.value,className:"text-xs",children:m.label},m.value))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Display"}),e.jsxs(t.Select,{value:s.durationDisplayStyle||"compact",onValueChange:m=>c("durationDisplayStyle",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:Ho.map(m=>e.jsx(t.SelectItem,{value:m.value,className:"text-xs",children:m.label},m.value))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Smallest"}),e.jsxs(t.Select,{value:s.durationSmallestUnit||"second",onValueChange:m=>c("durationSmallestUnit",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:fs.map(m=>e.jsx(t.SelectItem,{value:m.value,className:"text-xs",children:m.label},m.value))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Largest"}),e.jsxs(t.Select,{value:s.durationLargestUnit||"day",onValueChange:m=>c("durationLargestUnit",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:fs.map(m=>e.jsx(t.SelectItem,{value:m.value,className:"text-xs",children:m.label},m.value))})]})]})]})]})]})}const Wo=[{value:"difference",label:"Difference"},{value:"change",label:"Change (%)"},{value:"change_difference",label:"Change + Difference"},{value:"ratio",label:"Ratio"}],Yo=[{value:"arrow_badge",label:"Arrow + Badge"},{value:"arrow",label:"Arrow Only"},{value:"badge",label:"Badge Only"},{value:"none",label:"None"}];function fa({cardType:s,queryResultColumns:a,focusSection:r,focusRequestId:o}){var U,G,Q,Y,H,se,ue;const u=t.useEditorStore(ae=>ae.card),i=t.useEditorStore(ae=>ae.queryResultColumns),l=t.useEditorStore(ae=>{var me;return(me=ae.card)==null?void 0:me.preferences}),c=l==null?void 0:l.tablePrefs,d=t.useEditorStore(ae=>ae.actions.setCardPreferences),h=t.useEditorStore(ae=>ae.actions.updateTableConditionalFormatting),x=((U=u.config)==null?void 0:U.metricColumns)||[],g=s??u.type,p=a??i,m=u.type===g?u:{...u,type:g},f=n.getTableConditionalFormattingColumnOptions(m,p),w=n.getTableOutputColumnOptions(m,p),b=n.supportsTableConditionalFormatting(g),N=g==="table",A=g==="table",_=((G=f[0])==null?void 0:G.value)||"",C=n.normalizeConditionalFormatting((Q=l==null?void 0:l.tablePrefs)==null?void 0:Q.conditionalFormatting),S=n.resolveTablePresentationStyle(c),I=n.isEligibleFlatTableTotalsCard(m),E=n.hasFlatTableTotalsBehavior(m),[D,T]=v.useState("style");v.useEffect(()=>{if(r==="style"){T("style");return}if(r==="columns"&&A){T("columns");return}r==="conditional-formatting"&&b&&T("conditional-formatting")},[A,b,o,r]);const y=x.some(ae=>ae.comparisonType&&ae.comparisonType!=="none"),L=((Y=l==null?void 0:l.tableVisualOptions)==null?void 0:Y.metricComparison)||{},M=ae=>{d({...l,tableVisualOptions:{...l==null?void 0:l.tableVisualOptions,metricComparison:{...L,...ae}}})},P={increase:((H=L.colors)==null?void 0:H.increase)||"green",decrease:((se=L.colors)==null?void 0:se.decrease)||"red",neutral:((ue=L.colors)==null?void 0:ue.neutral)||"neutral"},F=ae=>{h({version:1,rules:ae})},j=ae=>{d({...l,tablePrefs:{...c,density:ae}})},k=ae=>{d({...l,tablePrefs:{...c,tableStyle:{...c==null?void 0:c.tableStyle,...ae}}})},O=ae=>{var me;k({totals:{...(me=c==null?void 0:c.tableStyle)==null?void 0:me.totals,...ae}})},R=ae=>{var me;d({...l,tablePrefs:{...c,tableStyle:{...c==null?void 0:c.tableStyle,totals:{...(me=c==null?void 0:c.tableStyle)==null?void 0:me.totals,enabled:ae}}}})},B=(ae,me)=>{d({...l,tablePrefs:{...c,columnVisibility:n.setTableColumnVisibility(c==null?void 0:c.columnVisibility,ae,me)}})},z=()=>{d({...l,tablePrefs:{...c,columnVisibility:n.showAllTableColumns()}})},V=()=>{d({...l,tablePrefs:{...c,density:n.TABLE_PRESENTATION_DEFAULT_STYLE.density,tableStyle:{headerStyle:n.TABLE_PRESENTATION_DEFAULT_STYLE.headerStyle,headerWrapText:n.TABLE_PRESENTATION_DEFAULT_STYLE.headerWrapText,stripedRows:n.TABLE_PRESENTATION_DEFAULT_STYLE.stripedRows,wrapText:n.TABLE_PRESENTATION_DEFAULT_STYLE.wrapText,totals:{enabled:I?E:n.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.enabled,backgroundColor:n.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.backgroundColor,textColor:n.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.textColor,fontWeight:n.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.fontWeight,borderTop:n.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.borderTop,borderTopStyle:n.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.borderTopStyle,borderTopColor:n.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.borderTopColor}}}})},q=y?e.jsx(Jo,{calculatedAs:L.calculatedAs??"change_difference",indicatorStyle:L.indicatorStyle??"arrow_badge",formatOptions:L.formatOptions??{},colors:P,lowerIsBetter:L.lowerIsBetter??!1,onUpdate:M}):null;return e.jsx("div",{className:"px-4 py-3",children:e.jsxs(t.Tabs,{value:D,onValueChange:ae=>T(ae),className:"space-y-4",children:[e.jsxs(t.TabsList,{variant:"underline",children:[e.jsx(t.TabsTrigger,{value:"style",children:"Appearance"}),A?e.jsx(t.TabsTrigger,{value:"columns",children:"Columns"}):null,e.jsx(t.TabsTrigger,{value:"conditional-formatting",disabled:!b,children:"Conditional formatting"})]}),e.jsx(t.TabsContent,{value:"style",className:"mt-0",children:e.jsx(n.TablePresentationSettings,{style:S,onDensityChange:j,onStyleChange:k,showFullStyle:N,showBorderStyle:!1,totals:N&&I?{enabled:E,onEnabledChange:R,onStyleChange:O}:void 0,extraSection:q,onReset:N?V:void 0})}),e.jsx(t.TabsContent,{value:"columns",className:"mt-0",children:A?e.jsx(n.TableColumnVisibilitySettings,{columns:w,columnVisibility:c==null?void 0:c.columnVisibility,onColumnVisibilityChange:B,onShowAllColumns:z}):e.jsx("p",{className:"py-6 text-center text-[12px] text-muted-foreground",children:"Column visibility is available for table cards."})}),e.jsx(t.TabsContent,{value:"conditional-formatting",className:"mt-0",children:b?_?e.jsx(n.DataTableConditionalFormattingSettings,{columnId:_,availableColumns:f,conditionalRules:C.rules,onConditionalRulesChange:F,startRulesWithNoTrigger:!0}):e.jsx("p",{className:"py-6 text-center text-[12px] text-muted-foreground",children:"Run the query to configure conditional formatting."}):e.jsx("p",{className:"py-6 text-center text-[12px] text-muted-foreground",children:"Conditional formatting is available for table cards."})})]})})}function Jo({calculatedAs:s,indicatorStyle:a,formatOptions:r,colors:o,lowerIsBetter:u,onUpdate:i}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Comparison"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(qt,{label:"Calc as",children:e.jsxs(t.Select,{value:s,onValueChange:l=>i({calculatedAs:l}),children:[e.jsx(t.SelectTrigger,{size:"xs",className:"w-full",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Wo.map(l=>e.jsx(t.SelectItem,{value:l.value,children:l.label},l.value))})]})}),e.jsx(qt,{label:"Indicator",children:e.jsxs(t.Select,{value:a,onValueChange:l=>i({indicatorStyle:l}),children:[e.jsx(t.SelectTrigger,{size:"xs",className:"w-full",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Yo.map(l=>e.jsx(t.SelectItem,{value:l.value,children:l.label},l.value))})]})}),e.jsx(qt,{label:"Format",align:"start",children:e.jsx(kt,{formatOptions:r,onFormatOptionsChange:l=>i({formatOptions:l}),showTitle:!1})}),e.jsx(qt,{label:"Colors",align:"start",children:e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(bs,{label:"Increase",value:gs(o.increase),defaultValue:"#16a34a",onChange:l=>i({colors:{...o,increase:l??"#16a34a"}})}),e.jsx(bs,{label:"Decrease",value:gs(o.decrease),defaultValue:"#dc2626",onChange:l=>i({colors:{...o,decrease:l??"#dc2626"}})}),e.jsx(bs,{label:"No change",value:gs(o.neutral),defaultValue:"#6b7280",onChange:l=>i({colors:{...o,neutral:l??"#6b7280"}})})]})}),e.jsx(qt,{label:"Lower is better",children:e.jsx(n.Checkbox,{checked:u,onCheckedChange:l=>i({lowerIsBetter:!!l})})})]})]})}function qt({label:s,children:a,align:r="center"}){return e.jsxs("div",{className:r==="start"?"flex items-start gap-2":"flex items-center gap-2",children:[e.jsx("span",{className:"w-20 shrink-0 text-[11px] text-muted-foreground"+(r==="start"?" pt-1.5":""),children:s}),e.jsx("div",{className:"min-w-0 flex-1",children:a})]})}const Xo={green:"#16a34a",red:"#dc2626",neutral:"#6b7280"};function gs(s){return s&&(Xo[s]??s)}function bs({label:s,value:a,onChange:r,defaultValue:o}){return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.ColorField,{value:a,onChange:r,defaultValue:o,ariaLabel:s,allowEmpty:!1}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:s})]})}function Zo(){var u;const s=t.useEditorStore(i=>i.card.preferences),{setCardPreferences:a}=t.useEditorStore(i=>i.actions),r=(u=s==null?void 0:s.textVisualOptions)!=null&&u.isDynamicText?"dynamic":"static";function o(i){a({...s,textVisualOptions:{...s==null?void 0:s.textVisualOptions,isDynamicText:i==="dynamic"}})}return e.jsx(t.Tabs,{value:r,onValueChange:o,children:e.jsxs(t.TabsList,{variant:"underline",children:[e.jsx(t.TabsTrigger,{value:"static",children:"Static"}),e.jsx(t.TabsTrigger,{value:"dynamic",children:"Dynamic"})]})})}function el(){return e.jsxs("div",{className:"space-y-2 px-6 py-4",children:[e.jsx("div",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Text mode"}),e.jsx(Zo,{}),e.jsx("p",{className:"pt-1 text-[12px] leading-[1.55] text-muted-foreground",children:"Static text is authored inline. Dynamic text reads from the first cell of the card's query."})]})}function tl({color:s,onColorChange:a,onClose:r}){const[o,u]=v.useState(0),[i,l]=v.useState(100),[c,d]=v.useState(50),[h,x]=v.useState(s);v.useEffect(()=>{const b=Vn(s);if(b){const N=Bn(b.r,b.g,b.b);u(N.h),l(N.s),d(N.l),x(s)}},[s]);const g=b=>{u(b),m(b,i,c)},p=b=>{const N=b.currentTarget.getBoundingClientRect(),A=Math.max(0,Math.min(1,(b.clientX-N.left)/N.width)),_=Math.max(0,Math.min(1,(b.clientY-N.top)/N.height)),C=A*100,S=(1-_)*100;l(C),d(S),m(o,C,S)},m=(b,N,A)=>{const _=nl(b,N,A),C=sl(_.r,_.g,_.b);x(C)},f=b=>{if(x(b),/^#[0-9A-Fa-f]{6}$/.test(b)){const N=Vn(b);if(N){const A=Bn(N.r,N.g,N.b);u(A.h),l(A.s),d(A.l)}}},w=()=>{/^#[0-9A-Fa-f]{6}$/.test(h)&&(a(h),r())};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(${o}, 100%, 50%)`},onClick:p,onMouseMove:b=>{b.buttons===1&&p(b)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${i}%`,top:`${100-c}%`,backgroundColor:h}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:o,onChange:b=>g(Number(b.target.value)),className:"w-full h-4 rounded-lg appearance-none cursor-pointer",style:{background:"linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"}})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"HEX"}),e.jsx(t.Input,{value:h,onChange:b=>f(b.target.value),placeholder:"#000000",className:"font-mono"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:s}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:h}}),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:r,children:"Cancel"}),e.jsx(t.Button,{onClick:w,children:"OK"})]})]})}function Vn(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 sl(s,a,r){return"#"+((1<<24)+(s<<16)+(a<<8)+r).toString(16).slice(1)}function Bn(s,a,r){s/=255,a/=255,r/=255;const o=Math.max(s,a,r),u=Math.min(s,a,r);let i=0,l=0;const c=(o+u)/2;if(o!==u){const d=o-u;switch(l=c>.5?d/(2-o-u):d/(o+u),o){case s:i=((a-r)/d+(a<r?6:0))/6;break;case a:i=((r-s)/d+2)/6;break;case r:i=((s-a)/d+4)/6;break}}return{h:Math.round(i*360),s:Math.round(l*100),l:Math.round(c*100)}}function nl(s,a,r){s/=360,a/=100,r/=100;let o,u,i;if(a===0)o=u=i=r;else{const l=(h,x,g)=>(g<0&&(g+=1),g>1&&(g-=1),g<.16666666666666666?h+(x-h)*6*g:g<.5?x:g<.6666666666666666?h+(x-h)*(.6666666666666666-g)*6:h),c=r<.5?r*(1+a):r+a-r*a,d=2*r-c;o=l(d,c,s+1/3),u=l(d,c,s),i=l(d,c,s-1/3)}return{r:Math.round(o*255),g:Math.round(u*255),b:Math.round(i*255)}}const al=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function rl(){var S,I,E,D,T,y,L,M,P,F;const s=t.useEditorStore(j=>j.card),a=t.useEditorStore(j=>{var k;return(k=j.card)==null?void 0:k.preferences}),r=Ne.useEffectiveEditorCardType(),{setCardPreferences:o,updateCardInFrame:u}=t.useEditorActions(),i=v.useMemo(()=>r!==s.type?{...s,type:r}:s,[s,r]),{data:l}=n.useEditorCardQuery(i),[c,d]=v.useState({}),[h,x]=v.useState(null),[g,p]=v.useState(null),m=v.useMemo(()=>{var R,B,z,V,q,U,G;if(!(l!=null&&l.records)||l.records.length===0)return[];const j=r==="stackedBar"||r==="stackedLine",k=r==="bar"||r==="line"||r==="horizontalBar"||r==="bullet"||r==="combo"||r==="area"||r==="stackedArea",O=((R=s==null?void 0:s.config)==null?void 0:R.pivotByColumns)&&s.config.pivotByColumns.length>0;if((j||k)&&O){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const Q=new Set;return l.pivotSchema.forEach(Y=>{Y.alias&&Q.add(Y.alias)}),Array.from(Q)}if(l.records.length>0){const Q=l.records[0],Y=Object.keys(Q),H=new Set;(B=s==null?void 0:s.config)!=null&&B.groupByColumns&&s.config.groupByColumns.forEach(ae=>{H.add(ae.label||ae.name),H.add(ae.alias||ae.name)});const se=new Set;return(z=s==null?void 0:s.config)!=null&&z.metricColumns&&s.config.metricColumns.forEach(ae=>{const me=ae.alias||ae.name;se.add(me),se.add(`${me}_count`),se.add(`${me}_sum`),se.add(`${me}_avg`),se.add(`${me}_min`),se.add(`${me}_max`);const ve=ae.entityName||ae.qualifiedEntityName;ve&&(se.add(`${ve}_${me}`),se.add(`${ve}_${me}_count`))}),Y.filter(ae=>!H.has(ae)&&!se.has(ae))}}if((k||j)&&!O&&((q=(V=s==null?void 0:s.config)==null?void 0:V.metricColumns)!=null&&q.length))return s.config.metricColumns.map(Q=>Q.alias||Q.label||Q.name);if((G=(U=s==null?void 0:s.config)==null?void 0:U.groupByColumns)!=null&&G.length){const Q=s.config.groupByColumns[0],Y=Q.label||Q.name,H=new Set;return l.records.forEach(se=>{const ue=se[Y];ue!=null&&H.add(String(ue))}),Array.from(H)}return[]},[l,(S=s==null?void 0:s.config)==null?void 0:S.groupByColumns,(I=s==null?void 0:s.config)==null?void 0:I.pivotByColumns,(E=s==null?void 0:s.config)==null?void 0:E.metricColumns,r]),f=v.useMemo(()=>n.getDefaultChartColors(),[]);v.useEffect(()=>{const j={};m.forEach((k,O)=>{j[k]=n.getColorForValue(k,O,a==null?void 0:a.colorConfig)}),d(j)},[m,a==null?void 0:a.colorConfig,f]);const w=(j,k)=>{const O={...c,[j]:k};d(O);const R={...a||{},colorConfig:{segments:O}};o(R);const B={...s,preferences:R};u(B)},b=(j,k)=>{var q;const O=f[k%f.length],{[j]:R,...B}=((q=a==null?void 0:a.colorConfig)==null?void 0:q.segments)||{},z={...a||{},colorConfig:{segments:B}};o(z);const V={...s,preferences:z};u(V),d(U=>({...U,[j]:O}))};if(!m.length||!((s==null?void 0:s.type)==="stackedBar"||(s==null?void 0:s.type)==="stackedLine"?((T=(D=s==null?void 0:s.config)==null?void 0:D.groupByColumns)==null?void 0:T.length)||((L=(y=s==null?void 0:s.config)==null?void 0:y.pivotByColumns)==null?void 0:L.length):(P=(M=s==null?void 0:s.config)==null?void 0:M.groupByColumns)==null?void 0:P.length)||["table","kpi","text","custom","heatmap"].includes(r))return null;const _=()=>{const j={...a||{},colorConfig:{segments:{}}};o(j);const k={...s,preferences:j};u(k);const O={};m.forEach((R,B)=>{O[R]=n.getColorForValue(R,B,void 0)}),d(O)},C=Object.keys(((F=a==null?void 0:a.colorConfig)==null?void 0:F.segments)||{}).length>0;return e.jsxs(n.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($a.Palette,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Colors"})]})}),e.jsx(n.AccordionContent,{className:"",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("div",{className:"flex items-center justify-between",children:C&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:_,children:[e.jsx(t.RotateCcw,{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((j,k)=>{const O=n.isDefaultColor(c[j],k),R=!O;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Popover,{open:h===j,onOpenChange:B=>x(B?j:null),children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"h-5 w-5 shrink-0 rounded border border-input shadow-sm transition-colors hover:border-gray-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",style:{backgroundColor:c[j]}})}),e.jsx(t.PopoverContent,{align:"start",className:"w-auto p-3",children:e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Theme Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:f.slice(0,10).map((B,z)=>e.jsxs("button",{className:t.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",c[j]===B?"border-gray-900":"border-transparent"),style:{backgroundColor:B},onClick:()=>{w(j,B),x(null)},children:[z===k%f.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-${z}`))})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Popular Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:al.map((B,z)=>e.jsx("button",{className:t.cn("h-5 w-5 rounded border transition-all hover:scale-110",c[j]===B?"border-2 border-gray-900":B==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:B},onClick:()=>{w(j,B),x(null)},children:e.jsx("span",{className:"sr-only",children:B})},`preset-${z}`))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsx("button",{className:"text-sm font-medium text-blue-600 hover:text-blue-700",onClick:()=>{p({value:j,color:c[j]}),x(null)},children:"Custom color"}),!O&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{b(j,k),x(null)},children:[e.jsx(t.RotateCcw,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:j}),R&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},j)})}),g&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>p(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(tl,{color:g.color,onColorChange:j=>{w(g.value,j),p(null)},onClose:()=>p(null)})})]})]})})]})}function et({value:s,onSave:a,placeholder:r="",type:o="text",className:u=""}){const[i,l]=v.useState(s??""),[c,d]=v.useState(!1);v.useEffect(()=>{l(s??"")},[s]);const h=()=>{a(i),d(!1)},x=()=>{l(s??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${u}`,children:[e.jsx(t.Input,{placeholder:r,type:o,value:c?i:s??"",onChange:g=>{l(g.target.value),d(!0)},onFocus:()=>d(!0),onClick:g=>g.stopPropagation(),className:"h-8 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.stopPropagation(),g.key==="Enter"&&c&&i!==s?h():g.key==="Escape"&&x()},"aria-label":r||"Edit field"}),c&&i!==s&&e.jsxs(e.Fragment,{children:[e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick: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 edit",onClick:x,children:e.jsx(t.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function js({axis:s,label:a,type:r,config:o,onChange:u,defaultTitle:i,hidePosition:l}){var f,w,b,N,A,_,C,S,I,E,D,T,y,L;const c=n.normalizeContextFormatMode({formatMode:o==null?void 0:o.formatMode,formatOptions:o==null?void 0:o.formatOptions}),d=(M,P)=>{u({...o??{},[M]:P})},h=(M,P)=>{var O,R,B,z;const F=M==="enabled"&&P===!0,j=(O=o==null?void 0:o.name)==null?void 0:O.text,k=F&&!j&&i;u({...o??{},name:{...o==null?void 0:o.name,enabled:M==="enabled"?P:((R=o==null?void 0:o.name)==null?void 0:R.enabled)??!1,text:M==="text"?P:k?i:j,fontSize:M==="fontSize"?P:(B=o==null?void 0:o.name)==null?void 0:B.fontSize,fontWeight:M==="fontWeight"?P:(z=o==null?void 0:o.name)==null?void 0:z.fontWeight}})},x=(M,P)=>{var F,j;u({...o??{},labels:{enabled:M==="enabled"?P:((F=o==null?void 0:o.labels)==null?void 0:F.enabled)??!0,rotation:M==="rotation"?P:(j=o==null?void 0:o.labels)==null?void 0:j.rotation}})},g=(M,P)=>{u({...o??{},scale:{...o==null?void 0:o.scale,[M]:P===""?"auto":Number(P)}})},p=s==="x"?["auto","top","bottom"]:["auto","left","right"],m=["auto","0","45","90","-45","-90"];return e.jsxs(n.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(n.AccordionTrigger,{className:"flex grow items-center justify-between gap-3 py-2 text-[12px] font-medium hover:no-underline",children:e.jsx("div",{className:"flex grow items-center justify-between gap-2",children:e.jsx("span",{children:a})})}),e.jsx(t.Switch,{size:"sm",checked:(o==null?void 0:o.enabled)!==!1,onCheckedChange:M=>d("enabled",M),onClick:M=>M.stopPropagation()})]}),e.jsxs(n.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(n.Checkbox,{id:`${s}-title-enabled`,checked:((f=o==null?void 0:o.name)==null?void 0:f.enabled)??!1,onCheckedChange:M=>h("enabled",M===!0)}),e.jsx(t.Label,{htmlFor:`${s}-title-enabled`,className:"text-xs font-medium cursor-pointer",children:"TITLE"})]}),((w=o==null?void 0:o.name)==null?void 0:w.enabled)&&e.jsxs("div",{className:"space-y-2 pl-6",children:[e.jsx(et,{placeholder:`${a} title`,value:((b=o==null?void 0:o.name)==null?void 0:b.text)||"",onSave:M=>h("text",M),className:""}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Size"}),e.jsx("div",{className:"w-14",children:e.jsx(et,{type:"number",placeholder:"12",value:String(((N=o==null?void 0:o.name)==null?void 0:N.fontSize)||12),onSave:M=>h("fontSize",Number(M)||12),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Weight"}),e.jsxs(t.Select,{value:((A=o==null?void 0:o.name)==null?void 0:A.fontWeight)||"normal",onValueChange:M=>h("fontWeight",M),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(t.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]})]})]})]}),!l&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(t.Select,{value:(o==null?void 0:o.position)||"auto",onValueChange:M=>d("position",M),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:p.map(M=>e.jsx(t.SelectItem,{value:M,className:"text-xs",children:M==="auto"?"Auto (Default)":t.titleCase(M)},M))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(t.Switch,{size:"sm",checked:((_=o==null?void 0:o.labels)==null?void 0:_.enabled)!==!1,onCheckedChange:M=>x("enabled",M)})]}),((C=o==null?void 0:o.labels)==null?void 0:C.enabled)!==!1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Rotation"}),e.jsxs(t.Select,{value:String(((S=o==null?void 0:o.labels)==null?void 0:S.rotation)||"auto"),onValueChange:M=>x("rotation",M==="auto"?"auto":Number(M)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:m.map(M=>e.jsx(t.SelectItem,{value:M,className:"text-xs",children:M==="auto"?"Auto (Default)":`${M}°`},M))})]})]})]}),r==="value"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"FORMAT"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Inherit from the bound metric by default."})]}),e.jsx(t.Switch,{size:"sm",checked:c==="override",onCheckedChange:M=>u({...o,formatMode:M?"override":"inherit"})})]}),c==="override"&&e.jsx(kt,{formatOptions:(o==null?void 0:o.formatOptions)||{},onFormatOptionsChange:M=>u({...o,formatMode:"override",formatOptions:M}),showTitle:!1})]}),r==="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(et,{type:"number",placeholder:"auto",value:((I=o==null?void 0:o.scale)==null?void 0:I.min)==="auto"||((E=o==null?void 0:o.scale)==null?void 0:E.min)===void 0?"":String(o.scale.min),onSave:M=>g("min",M),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-8 text-xs text-muted-foreground",children:"Max"}),e.jsx("div",{className:"flex-1",children:e.jsx(et,{type:"number",placeholder:"auto",value:((D=o==null?void 0:o.scale)==null?void 0:D.max)==="auto"||((T=o==null?void 0:o.scale)==null?void 0:T.max)===void 0?"":String(o.scale.max),onSave:M=>g("max",M),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-8 text-xs text-muted-foreground",children:"Step"}),e.jsx("div",{className:"flex-1",children:e.jsx(et,{type:"number",placeholder:"auto",value:((y=o==null?void 0:o.scale)==null?void 0:y.stepSize)==="auto"||((L=o==null?void 0:o.scale)==null?void 0:L.stepSize)===void 0?"":String(o.scale.stepSize),onSave:M=>g("stepSize",M),className:""})})]})]})]})]})]})}function vs(s,a,r){var i,l,c;if(s==="x"){const d=(l=(i=a==null?void 0:a.config)==null?void 0:i.groupByColumns)==null?void 0:l[0];return(d==null?void 0:d.label)||(d==null?void 0:d.name)||""}const o=((c=a==null?void 0:a.config)==null?void 0:c.metricColumns)||[],u=(r==null?void 0:r.datasetOptions)||[];if(s==="y"){const d=o.filter((h,x)=>{const g=u.find(p=>p.idx===x);return!g||g.yAxisId!=="y2"});return d.length===1&&(d[0].label||d[0].name)||""}if(s==="y2"){const d=o.filter((h,x)=>{const g=u.find(p=>p.idx===x);return(g==null?void 0:g.yAxisId)==="y2"});return d.length===1&&(d[0].label||d[0].name)||""}return""}function ol(){const s=t.useEditorStore(d=>d.card),a=t.useEditorStore(d=>{var h;return(h=d.card)==null?void 0:h.preferences}),{setCardPreferences:r,updateCardInFrame:o}=t.useEditorActions(),u=Ne.useEffectiveEditorCardType();if(!s||["tornado","pyramid","kpi","treemap"].includes(u))return null;const i=n.AxisConfigurator.getAxisInfo(u,a);if(!i.hasXAxis&&!i.hasYAxis)return null;const l=(d,h)=>{let x;d==="x"?x="xAxisConfig":d==="y"?x="yAxisConfig":x="secondaryYAxisConfig";const g={...a||{},[x]:h};r(g);const p={...s,preferences:g};o(p)},c=i.hasY2Axis&&u==="combo";return e.jsxs(n.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.SlidersHorizontal,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Axes"})]})}),e.jsx(n.AccordionContent,{className:"pt-2",children:e.jsxs(n.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[i.hasXAxis&&e.jsx(js,{axis:"x",label:"X-Axis",type:i.xAxisType,config:n.mergeAxisConfig(n.getDefaultAxisConfig(u,"x"),a==null?void 0:a.xAxisConfig),onChange:d=>l("x",d),defaultTitle:vs("x",s,a)}),i.hasYAxis&&e.jsx(js,{axis:"y",label:c?"Y-Axis (Left)":"Y-Axis",type:i.yAxisType,config:n.mergeAxisConfig(n.getDefaultAxisConfig(u,"y"),a==null?void 0:a.yAxisConfig),onChange:d=>l("y",d),defaultTitle:vs("y",s,a)}),c&&e.jsx(js,{axis:"y2",label:"Y2-Axis (Right)",type:"value",config:n.mergeAxisConfig({enabled:!0,position:"right"},a==null?void 0:a.secondaryYAxisConfig),onChange:d=>l("y2",d),defaultTitle:vs("y2",s,a),hidePosition:!0})]})})]})}function ll(){const s=t.useEditorStore(g=>g.card),a=Ne.useEffectiveEditorCardType(),r=t.useEditorStore(g=>{var p,m,f,w;return(w=(f=(m=(p=g.card)==null?void 0:p.preferences)==null?void 0:m.chartOptions)==null?void 0:f.plugins)==null?void 0:w.legend}),{setLegendOptions:o}=t.useEditorActions();if(!s||!n.chartSupportsLegend(a))return null;const u=n.getDefaultLegendConfig(a),i=(u==null?void 0:u.display)??!0,l=(u==null?void 0:u.position)??"top",c=(u==null?void 0:u.align)??"center",d=(g,p)=>{const m={...r,[g]:p};o(m)},h=["top","bottom","left","right"],x=["start","center","end"];return e.jsxs(n.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(er,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(n.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:(r==null?void 0:r.display)??i,onCheckedChange:g=>d("display",g)})]}),((r==null?void 0:r.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:(r==null?void 0:r.position)||l,onValueChange:g=>d("position",g),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:h.map(g=>e.jsx(t.SelectItem,{value:g,className:"text-xs",children:t.titleCase(g)},g))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(t.Select,{value:(r==null?void 0:r.align)||c,onValueChange:g=>d("align",g),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:x.map(g=>e.jsx(t.SelectItem,{value:g,className:"text-xs",children:t.titleCase(g)},g))})]})]})]})]})})]})}function il(){var P,F,j,k,O,R,B;const s=t.useEditorStore(z=>z.card),a=Ne.useEffectiveEditorCardType(),r=t.useEditorStore(z=>{var V,q;return(q=(V=z.card)==null?void 0:V.preferences)==null?void 0:q.dataLabelsConfig}),o=t.useEditorStore(z=>{var V;return(V=z.card)==null?void 0:V.preferences}),{setCardPreferences:u,updateCardInFrame:i}=t.useEditorActions();if(!s||!n.chartSupportsDataLabels(a))return null;const l=a==="bullet"?((P=o==null?void 0:o.bulletConfig)==null?void 0:P.orientation)??(((F=o==null?void 0:o.chartOptions)==null?void 0:F.indexAxis)==="x"?"vertical":"horizontal"):void 0,c=l!=null?l==="horizontal":((j=o==null?void 0:o.chartOptions)==null?void 0:j.indexAxis)==="y",d=a==="stackedBar"||a==="stackedLine",h=a==="pie"||a==="doughnut"||a==="polarArea"||a==="funnel",x=a==="bubble"||a==="scatter",g=(O=(k=o==null?void 0:o.chartOptions)==null?void 0:k.plugins)==null?void 0:O.datalabels,p=(g==null?void 0:g.display)!==!1&&((g==null?void 0:g.anchor)||(g==null?void 0:g.align)),m=n.getDefaultDataLabelsConfig(a,s.preferences),f=r??m,w=(m==null?void 0:m.enabled)??p??!1,b=(r==null?void 0:r.enabled)!==void 0?r.enabled:w,N=(z,V)=>{const G={...m??{},...r??{},[z]:V};z==="enabled"&&(G.display=V,V&&x&&!G.position&&(G.position="bottom")),z==="position"&&x&&(G.position="bottom"),z==="formatMode"&&V==="inherit"&&(G.format=void 0,G.formatOptions=void 0);const Q={...s.preferences||{},dataLabelsConfig:G};u(Q);const Y={...s,preferences:Q};i(Y)},A=(z,V)=>{const q=r??{},G={...m??{},...q,font:{...q.font||{},[z]:V}},Q={...s.preferences||{},dataLabelsConfig:G};u(Q);const Y={...s,preferences:Q};i(Y)},_=()=>{const z=a;return z==="stackedBar"||z==="stackedLine"||z==="pie"||z==="doughnut"?"center":c?"right":"top"},C=a!=="treemap"&&a!=="heatmap",S=a!=="treemap",I=_();let E=[];if(C)if(x)E=["bottom"];else if(d||h)E=["center"];else{const z=c?["center","left","right"]:["center","top","bottom"];E=["auto",...a==="bullet"?z:z.filter(q=>q!==I),"custom"]}const D=()=>t.titleCase(I),T=["center","start","end"],y=["center","start","end","top","bottom"],L=(f==null?void 0:f.formatMode)||(f!=null&&f.format&&!["auto"].includes(f.format)?"override":"inherit"),M=(f==null?void 0:f.format)==="none";return e.jsxs(n.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(n.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(t.Switch,{size:"sm",checked:b,onCheckedChange:z=>N("enabled",z)})]}),b&&e.jsxs(e.Fragment,{children:[C&&!d&&!h&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(t.Select,{value:x?(f==null?void 0:f.position)||"bottom":(f==null?void 0:f.position)||"auto",onValueChange:z=>N("position",z),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:E.map(z=>e.jsx(t.SelectItem,{value:z,className:"text-xs",children:z==="auto"?D():z==="custom"?"Custom (Advanced)":t.titleCase(z)},z))})]})]}),d&&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:(r==null?void 0:r.showTotal)??!1,onCheckedChange:z=>N("showTotal",z)})]}),(f==null?void 0:f.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:(f==null?void 0:f.anchor)||"center",onValueChange:z=>N("anchor",z),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:T.map(z=>e.jsx(t.SelectItem,{value:z,className:"text-xs",children:t.titleCase(z)},z))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground w-16",children:"Align"}),e.jsxs(t.Select,{value:String((f==null?void 0:f.align)||"center"),onValueChange:z=>N("align",z),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:y.map(z=>e.jsx(t.SelectItem,{value:z,className:"text-xs",children:t.titleCase(z)},z))})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Format"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Keep this off to inherit from the bound metric."})]}),e.jsx(t.Switch,{size:"sm",checked:L==="override",onCheckedChange:z=>N("formatMode",z?"override":"inherit")})]}),L==="override"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Raw Value"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Show the unformatted numeric value."})]}),e.jsx(t.Switch,{size:"sm",checked:M,onCheckedChange:z=>{const V=r??{},U={...m??{},...V,formatMode:"override",format:z?"none":void 0,formatOptions:z?void 0:V.formatOptions},G={...s.preferences||{},dataLabelsConfig:U};u(G),i({...s,preferences:G})}})]}),!M&&e.jsx(kt,{formatOptions:(f==null?void 0:f.formatOptions)||{},onFormatOptionsChange:z=>{const U={...m??{},...r??{},formatMode:"override",format:z.type&&z.type!=="auto"?z.type:void 0,formatOptions:z},G={...s.preferences||{},dataLabelsConfig:U};u(G),i({...s,preferences:G})},showTitle:!1})]})]}),S&&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(et,{type:"number",placeholder:"12",value:String(((R=f==null?void 0:f.font)==null?void 0:R.size)||12),onSave:z=>A("size",Number(z)),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground w-20",children:"Weight"}),e.jsxs(t.Select,{value:((B=f==null?void 0:f.font)==null?void 0:B.weight)||"normal",onValueChange:z=>A("weight",z),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(t.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground w-20",children:"Color"}),e.jsxs(t.Select,{value:(f==null?void 0:f.color)==="auto"||!(f!=null&&f.color)?"auto":"custom",onValueChange:z=>{z==="auto"&&N("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(et,{type:"number",placeholder:"0",value:String((f==null?void 0:f.rotation)||0),onSave:z=>N("rotation",Number(z)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}const cl={green:"#16a34a",red:"#dc2626",neutral:"#6b7280"};function ys(s){return s&&(cl[s]??s)}const _n={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%
|
|
178
|
-
Difference: Primary - Secondary`,example:"Sales grew by 25% ($5,000) compared to last year."},ratio:{label:"Ratio",description:"Shows how much of one value is covered by another — useful for quotas and benchmarks.",formula:"Primary / Secondary × 100%",example:"You've achieved 80% of your sales quota."}};function dl(){var p,m,f,w,b,N,A,_,C,S;const s=t.useEditorStore(I=>I.card),{setCardPreferences:a}=t.useEditorActions(),r=Ne.useEffectiveEditorCardType(),o=((p=s.config)==null?void 0:p.metricColumns)||[],u=((m=s.config)==null?void 0:m.groupByColumns)||[],i=o.length===2&&u.length===0,l=o.some(I=>I.comparisonType&&I.comparisonType!=="none");if(!(r==="kpi"&&(i||l)))return null;const d=((w=(f=s.preferences)==null?void 0:f.kpiVisualOptions)==null?void 0:w.metricComparison)||{},h=I=>{var D;const E={...s.preferences,kpiVisualOptions:{...(D=s.preferences)==null?void 0:D.kpiVisualOptions,metricComparison:{...d,...I}}};a(E)},x=l||d.enabled,g=o.some(I=>I.comparisonType==="previous_period"||I.comparisonType==="same_period_last_year"||I.comparisonType==="start_vs_end");return e.jsxs(n.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(n.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-[12px] hover:no-underline [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xa,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(n.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[i&&o.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:"xs",id:"enable-comparison",checked:d.enabled||!1,onCheckedChange:I=>h({enabled:I,...I&&!d.calculationType?{calculationType:"difference"}:{}})})]}),x&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(t.Label,{htmlFor:"calculation-type",className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Calculated as"}),e.jsxs(n.HoverCard,{openDelay:120,closeDelay:80,children:[e.jsx(n.HoverCardTrigger,{asChild:!0,children:e.jsx(t.Info,{className:"h-3 w-3 cursor-help text-muted-foreground"})}),e.jsx(n.HoverCardContent,{side:"right",align:"start",className:"w-72 p-3",children:(()=>{const I=d.calculationType||"difference",E=_n[I];return e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:E==null?void 0:E.label}),e.jsx("p",{className:"text-[12px] leading-[18px] text-foreground",children:E==null?void 0:E.description}),e.jsxs("div",{className:"text-[12px] text-foreground",children:[e.jsx("span",{className:"text-muted-foreground",children:"Formula:"})," ",e.jsx("code",{className:"rounded-[3px] border border-border/60 bg-muted px-1 py-0.5 text-[11px] tabular-nums",children:E==null?void 0:E.formula})]}),e.jsxs("div",{className:"border-t border-border/60 pt-2 text-[12px] italic leading-[18px] text-muted-foreground",children:[e.jsx("span",{className:"not-italic text-foreground",children:"Example:"})," ",E==null?void 0:E.example]})]})})()})]})]}),e.jsxs(t.Select,{value:d.calculationType||"difference",onValueChange:I=>h({calculationType:I}),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(_n).map(([I,E])=>e.jsx(t.SelectItem,{value:I,className:"text-xs",children:E.label},I))})]})]}),e.jsx(kt,{formatOptions:d.formatOptions||{},onFormatOptionsChange:I=>h({formatOptions:I}),showTitle:!0,title:"COMPARISON FORMAT"}),(g||i)&&e.jsxs("div",{className:"space-y-2 border-t border-border/60 pt-3",children:[e.jsx(t.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Indicator"}),i&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-foreground",children:"Position"}),e.jsxs(t.Select,{value:d.position||"right",onValueChange:I=>h({position:I}),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-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Checkbox,{id:"show-arrow",checked:d.showArrow!==!1,onCheckedChange:I=>h({showArrow:I})}),e.jsx(t.Label,{htmlFor:"show-arrow",className:"cursor-pointer text-xs text-foreground",children:"Arrow"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Checkbox,{id:"show-color",checked:d.showColor!==!1,onCheckedChange:I=>h({showColor:I})}),e.jsx(t.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-foreground",children:"Color"})]})]}),d.showColor!==!1&&e.jsxs("div",{className:"space-y-1.5 pt-1",children:[e.jsx(Ns,{label:"Increase",children:e.jsx(n.ColorField,{value:ys(((b=d.colorConfig)==null?void 0:b.increase)||"green"),onChange:I=>h({colorConfig:{...d.colorConfig,increase:I??"#16a34a"}}),defaultValue:"#16a34a",ariaLabel:"Increase color",allowEmpty:!1})}),e.jsx(Ns,{label:"Decrease",children:e.jsx(n.ColorField,{value:ys(((N=d.colorConfig)==null?void 0:N.decrease)||"red"),onChange:I=>h({colorConfig:{...d.colorConfig,decrease:I??"#dc2626"}}),defaultValue:"#dc2626",ariaLabel:"Decrease color",allowEmpty:!1})}),e.jsx(Ns,{label:"No change",children:e.jsx(n.ColorField,{value:ys(((A=d.colorConfig)==null?void 0:A.noChange)||"neutral"),onChange:I=>h({colorConfig:{...d.colorConfig,noChange:I??"#6b7280"}}),defaultValue:"#6b7280",ariaLabel:"No change color",allowEmpty:!1})})]})]}),e.jsxs("div",{className:"space-y-2 border-t border-border/60 pt-3",children:[e.jsx(t.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Checkbox,{id:"conditional-label",checked:d.conditionalLabel||!1,onCheckedChange:I=>h({conditionalLabel:I})}),e.jsx(t.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-foreground",children:"Different label per direction"})]}),d.conditionalLabel?e.jsxs("div",{className:"space-y-1.5 pt-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{htmlFor:"label-increase",className:"w-24 shrink-0 text-xs text-muted-foreground",children:"Increase"}),e.jsx(t.Input,{id:"label-increase",type:"text",value:((_=d.conditionalLabels)==null?void 0:_.increase)??"Increase",onChange:I=>h({conditionalLabels:{...d.conditionalLabels,increase:I.target.value}}),placeholder:"Increase",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{htmlFor:"label-decrease",className:"w-24 shrink-0 text-xs text-muted-foreground",children:"Decrease"}),e.jsx(t.Input,{id:"label-decrease",type:"text",value:((C=d.conditionalLabels)==null?void 0:C.decrease)??"Decrease",onChange:I=>h({conditionalLabels:{...d.conditionalLabels,decrease:I.target.value}}),placeholder:"Decrease",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{htmlFor:"label-no-change",className:"w-24 shrink-0 text-xs text-muted-foreground",children:"No change"}),e.jsx(t.Input,{id:"label-no-change",type:"text",value:((S=d.conditionalLabels)==null?void 0:S.noChange)??"No change",onChange:I=>h({conditionalLabels:{...d.conditionalLabels,noChange:I.target.value}}),placeholder:"No change",className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(t.Label,{htmlFor:"label-name",className:"w-24 shrink-0 text-xs text-muted-foreground",children:"Previous"}),e.jsx(t.Input,{id:"label-name",type:"text",value:d.labelName??"",onChange:I=>h({labelName:I.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function Ns({label:s,children:a}){return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-24 shrink-0 text-xs text-muted-foreground",children:s}),e.jsx("div",{className:"min-w-0 flex-1",children:a})]})}function ul(){var i;const s=t.useEditorStore(l=>{var c;return(c=l.card)==null?void 0:c.type}),a=t.useEditorStore(l=>{var c;return(c=l.card)==null?void 0:c.preferences}),{setCardPreferences:r}=t.useEditorActions();if(s!=="treemap")return null;const o=((i=a==null?void 0:a.chartOptions)==null?void 0:i.treemapColorMode)??"branch",u=l=>{const c={...a||{},chartOptions:{...a==null?void 0:a.chartOptions,treemapColorMode:l}};r(c)};return e.jsxs(n.AccordionItem,{value:"treemap-color-mode",className:"border-none",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.TbChartTreemap,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Treemap Colors"})]})}),e.jsx(n.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:e.jsxs(n.RadioGroup,{value:o,onValueChange:l=>u(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(n.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(n.RadioGroupItem,{id:"treemap-color-category",value:"category"}),e.jsxs(t.Label,{htmlFor:"treemap-color-category",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Single color per category"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Applies the top-level color to all descendants without lightening/darkening."})]})]})]})})]})}const ml=Object.keys(n.HEATMAP_PRESET_PALETTES);function xl(){const s=t.useEditorStore(p=>p.card),a=t.useEditorStore(p=>{var m;return(m=p.card)==null?void 0:m.preferences}),{setCardPreferences:r}=t.useEditorActions(),o=(s==null?void 0:s.type)==="heatmap",u=(a==null?void 0:a.heatmapConfig)||{},i=u.colorPalette??"green",l=u.legendPosition??"bottom",c=v.useMemo(()=>u.colorRange&&u.colorRange[0]&&u.colorRange[1]?[u.colorRange[0],u.colorRange[1]]:[...n.DEFAULT_HEATMAP_CUSTOM_RANGE],[u.colorRange]),d=p=>{const m={...u,...p};m.colorPalette!=="custom"?delete m.colorRange:(!m.colorRange||!m.colorRange[0]||!m.colorRange[1])&&(m.colorRange=[...n.DEFAULT_HEATMAP_CUSTOM_RANGE]),r({...a||{},heatmapConfig:m})},h=p=>{d({colorPalette:p,colorRange:p==="custom"?u.colorRange??[...n.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},x=(p,m)=>{const f=[...c];f[p]=m,d({colorPalette:"custom",colorRange:f})},g=p=>{d({legendPosition:p})};return o?e.jsxs(n.AccordionItem,{value:"heatmap-color-config",className:"border-none",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Grid3x3,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Heatmap Settings"})]})}),e.jsxs(n.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs(n.RadioGroup,{value:i,onValueChange:p=>h(p??"blue"),className:"space-y-3",children:[ml.map(p=>{const m=n.HEATMAP_PRESET_PALETTES[p];return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(n.RadioGroupItem,{id:`heatmap-${p}`,value:p}),e.jsxs(t.Label,{htmlFor:`heatmap-${p}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:m.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${m.start}, ${m.end})`}})]})]},p)}),e.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.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-2 pl-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.ColorField,{value:c[0],onChange:p=>x(0,p??"#000000"),ariaLabel:"Start color",allowEmpty:!1}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Start color"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.ColorField,{value:c[1],onChange:p=>x(1,p??"#000000"),ariaLabel:"End color",allowEmpty:!1}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"End color"})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Color scale position"}),e.jsxs(t.Select,{value:l,onValueChange:p=>g(p??"bottom"),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:["top","bottom","left","right"].map(p=>e.jsx(t.SelectItem,{value:p,className:"text-xs",children:p[0].toUpperCase()+p.slice(1)},p))})]})]})]})]}):null}const zn=["poor","satisfactory","good"];function qn(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 hl(){var P,F;const s=t.useEditorStore(j=>j.card.preferences),a=t.useEditorStore(j=>j.card),r=t.useEditorStore(j=>j.isDevMode),{setCardPreferences:o,setChartOrientation:u}=t.useEditorActions(),i=v.useMemo(()=>(s==null?void 0:s.bulletConfig)||{},[s==null?void 0:s.bulletConfig]),c=t.hasValidCardConfig(a==null?void 0:a.config)&&!r,[d,h]=v.useState(i.showRanges??!1),[x,g]=v.useState(i.rangesArePercentages??!1),p=i.disableAutoComparative?!1:i.comparativeMetricKey!==void 0||!c,[m,f]=v.useState(p);v.useEffect(()=>{h(i.showRanges??!1)},[i.showRanges]),v.useEffect(()=>{g(i.rangesArePercentages??!1)},[i.rangesArePercentages]);const w=i.targetValue===void 0?"":String(i.targetValue);v.useEffect(()=>{const j=i.disableAutoComparative?!1:i.comparativeMetricKey!==void 0||!c;f(j)},[i.disableAutoComparative,i.comparativeMetricKey,c]);const b=v.useMemo(()=>{var j,k;return((k=(j=a==null?void 0:a.config)==null?void 0:j.metricColumns)==null?void 0:k.map(O=>{const R=O.label||O.name||O.alias||"";return{value:R,label:R}}))||[]},[(P=a==null?void 0:a.config)==null?void 0:P.metricColumns]);v.useEffect(()=>{var q,U;if(!s||b.length===0)return;const j={};let k=!1;const O=(q=b[1])==null?void 0:q.value;!i.targetMetricKey&&O&&(j.targetMetricKey=O,k=!0);const R=(U=b[2])==null?void 0:U.value;!i.comparativeMetricKey&&!i.disableAutoComparative&&R&&(j.comparativeMetricKey=R,k=!0);const B=b.slice(3),z={...i.rangeKeys||{}};let V=!1;if(zn.forEach((G,Q)=>{!z[G]&&B[Q]&&(z[G]=B[Q].value,V=!0)}),V&&(j.rangeKeys=z,k=!0,i.showRanges===void 0&&(j.showRanges=!0)),k){const G=qn({...i,...j});o({...s,bulletConfig:G})}},[b,i,s,o]);const N=j=>{const k=qn({...i,...j});o({...s,bulletConfig:k})},A=(j,k)=>{const O={...i.rangeKeys||{},[j]:k.trim()};k.trim()||delete O[j],N({rangeKeys:Object.keys(O).length>0?O:void 0})},_=(j,k)=>{const O=k===""?void 0:Number(k),R={...i.ranges||{}};O===void 0||Number.isNaN(O)?delete R[j]:R[j]=O,N({ranges:Object.keys(R).length?R:void 0})},C=j=>{if(j===""){N({targetValue:void 0});return}const k=Number(j);N({targetValue:Number.isNaN(k)?void 0:k})},S=(j,k)=>{const O=k.trim(),R={...i.rangeLabels||{}};O?R[j]=O:delete R[j],N({rangeLabels:Object.keys(R).length>0?R:void 0})},I=j=>{h(j),N({showRanges:j})},E=j=>{g(j),N({rangesArePercentages:j})},D=i.orientation||(((F=s==null?void 0:s.chartOptions)==null?void 0:F.indexAxis)==="y"?"horizontal":"vertical"),T=j=>{N({orientation:j}),u(j==="horizontal"?"y":"x")},y=[{value:"__none",label:"None"},...b.map(j=>({value:j.value,label:j.label}))],L=y,M=j=>{if(f(j),!j){N({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!c){N({disableAutoComparative:!1});return}if(i.comparativeMetricKey)N({disableAutoComparative:!1});else{const k=b.find(O=>O.value!==i.targetMetricKey);N({comparativeMetricKey:k==null?void 0:k.value,disableAutoComparative:!1})}};return e.jsxs(n.AccordionItem,{value:"bullet-config",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.BulletChartIcon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bullet Chart"})]})}),e.jsxs(n.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:j=>T(j),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"horizontal",className:"text-xs",children:"Horizontal"}),e.jsx(t.SelectItem,{value:"vertical",className:"text-xs",children:"Vertical"})]})]})]}),c&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"TARGET METRIC"}),e.jsxs(t.Select,{value:i.targetMetricKey||"__none",onValueChange:j=>N({targetMetricKey:j==="__none"?void 0:j}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select metric"})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"__none",className:"text-xs",children:"None"}),b.map(j=>e.jsx(t.SelectItem,{value:j.value,className:"text-xs",children:j.label},j.value))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"COMPARATIVE METRIC"}),c?e.jsxs(t.Select,{value:i.comparativeMetricKey||"__none",onValueChange:j=>N({comparativeMetricKey:j==="__none"?void 0:j,disableAutoComparative:j==="__none"}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select metric"})}),e.jsx(t.SelectContent,{children:y.map(j=>e.jsx(t.SelectItem,{value:j.value,className:"text-xs",children:j.label},j.value))})]}):e.jsxs("div",{className:"space-y-2 rounded-md border border-border/50 p-3 text-xs",children:[e.jsxs("div",{className:"flex items-center justify-between font-medium",children:[e.jsx("span",{children:"Show comparative"}),e.jsx(t.Switch,{size:"sm",checked:m,onCheckedChange:j=>M(j)})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Comparative values are auto-detected from the third metric in your results."})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"TARGET VALUE (FALLBACK)"}),e.jsx(We,{type:"number",className:"h-8 text-xs",value:w,onCommit:C,placeholder:"Optional numeric fallback"})]})]}),e.jsxs("section",{className:"space-y-4 rounded-md border border-border/60 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"QUALITATIVE RANGES"}),e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:200,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"text-muted-foreground transition-colors hover:text-foreground",children:e.jsx(t.Info,{className:"h-3.5 w-3.5"})})}),e.jsx(t.TooltipContent,{side:"top",children:"Use columns or static values for Poor / Average / Good."})]})})]}),e.jsx("div",{className:"flex items-center gap-2 text-xs font-medium",children:e.jsx(t.Switch,{size:"sm",checked:d,onCheckedChange:I})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:x,disabled:!d,onChange:j=>E(j.target.checked),className:"h-3.5 w-3.5 accent-primary disabled:opacity-50"}),e.jsx("span",{children:"Use % of value"})]})]}),d&&e.jsx("div",{className:"space-y-3",children:zn.map(j=>{var k,O,R,B,z;return e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-muted/40 p-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[j," LABEL"]}),e.jsx(We,{placeholder:`Display label (${j})`,value:((k=i.rangeLabels)==null?void 0:k[j])||"",onCommit:V=>S(j,V),className:"h-8 text-xs"})]}),c?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[j," COLUMN"]}),e.jsxs(t.Select,{value:((O=i.rangeKeys)==null?void 0:O[j])||"__none",onValueChange:V=>{V==="__none"?A(j,""):A(j,V)},children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select column"})}),e.jsx(t.SelectContent,{children:L.map(V=>e.jsx(t.SelectItem,{value:V.value,className:"text-xs",children:V.label},V.value))})]})]}):e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[j," COLUMN KEY"]}),e.jsx(We,{placeholder:"Column key",value:((R=i.rangeKeys)==null?void 0:R[j])||"",onCommit:V=>A(j,V),className:"h-8 text-xs"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[j," VALUE"]}),e.jsx(We,{type:"number",placeholder:x?"0.80":"Static value",value:((B=i.ranges)==null?void 0:B[j])===void 0?"":String((z=i.ranges)==null?void 0:z[j]),onCommit:V=>_(j,V),className:"h-8 text-xs"})]})]},j)})})]})]})]})}function $n(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 pl(){var S,I,E,D,T,y,L,M,P,F,j,k;const s=t.useEditorStore(O=>O.card.preferences),a=t.useEditorStore(O=>O.card),r=Ne.useEffectiveEditorCardType(),o=t.useEditorStore(O=>O.isDevMode),{setCardPreferences:u,updateCardInFrame:i}=t.useEditorActions(),l=r==="bubble",c=r==="scatter",d=v.useMemo(()=>(s==null?void 0:s.bubbleScatterConfig)||{},[s==null?void 0:s.bubbleScatterConfig]),x=t.hasValidCardConfig(a==null?void 0:a.config)&&!o,g=v.useMemo(()=>{var O,R;return((R=(O=a==null?void 0:a.config)==null?void 0:O.metricColumns)==null?void 0:R.map(B=>{const z=B.label||B.name||B.alias||"";return{value:z,label:z}}))||[]},[(S=a==null?void 0:a.config)==null?void 0:S.metricColumns]),p=v.useMemo(()=>{var O,R;return((R=(O=a==null?void 0:a.config)==null?void 0:O.groupByColumns)==null?void 0:R.map(B=>{const z=B.label||B.name||B.alias||"";return{value:z,label:z}}))||[]},[(I=a==null?void 0:a.config)==null?void 0:I.groupByColumns]),m=v.useMemo(()=>d.enableGrouping!==void 0?d.enableGrouping:!o&&p.length>=2,[d.enableGrouping,o,p.length]),[f,w]=v.useState(m);v.useEffect(()=>{w(m)},[m]);const b=O=>{const R={...s||{},bubbleScatterConfig:O};u(R),a&&i({...a,preferences:R})},N=O=>{u(O),a&&i({...a,preferences:O})};v.useEffect(()=>{if(!s||g.length===0)return;const O={};let R=!1;if(!d.xMetricKey&&g[0]&&(O.xMetricKey=g[0].value,R=!0),!d.yMetricKey&&g[1]&&(O.yMetricKey=g[1].value,R=!0),l&&!d.radiusMetricKey&&g[2]&&(O.radiusMetricKey=g[2].value,R=!0),!d.labelKey&&p[0]&&(O.labelKey=p[0].value,R=!0),m&&!d.groupKey&&p[1]&&(O.groupKey=p[1].value,O.enableGrouping=!0,R=!0),R){const B=$n({...d,...O});b(B)}},[g,p,d,s,u,l,m]);const A=O=>{const R=$n({...d,...O});b(R)},_=O=>{w(O),A({enableGrouping:O,groupKey:O?d.groupKey:void 0})};if(!l&&!c)return null;const C=l?n.Circle:n.ChartScatter;return e.jsxs(n.AccordionItem,{value:"bubble-scatter-config",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(C,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsxs("span",{children:[l?"Bubble":"Scatter"," Configuration"]})]})}),e.jsxs(n.AccordionContent,{className:"space-y-4 px-1 pb-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-1 text-xs font-medium text-muted-foreground",children:["Dimensions",e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{children:e.jsx(t.Info,{className:"h-3 w-3"})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{children:"Label identifies each point. Group creates separate series in the legend."})})]})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Label Column"}),x?e.jsxs(t.Select,{value:d.labelKey||"",onValueChange:O=>A({labelKey:O}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select label column"})}),e.jsx(t.SelectContent,{children:p.map(O=>e.jsx(t.SelectItem,{value:O.value,children:O.label},O.value))})]}):e.jsx(We,{className:"h-8 text-xs",placeholder:"Column name for labels",value:d.labelKey||"",onCommit:O=>A({labelKey:O})})]}),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:f,onCheckedChange:_})]}),f&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Group By"}),x?e.jsxs(t.Select,{value:d.groupKey||"",onValueChange:O=>A({groupKey:O}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select group column"})}),e.jsx(t.SelectContent,{children:p.map(O=>e.jsx(t.SelectItem,{value:O.value,children:O.label},O.value))})]}):e.jsx(We,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:d.groupKey||"",onCommit:O=>A({groupKey:O})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Metrics"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"X Axis"}),x?e.jsxs(t.Select,{value:d.xMetricKey||"",onValueChange:O=>A({xMetricKey:O}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select X metric"})}),e.jsx(t.SelectContent,{children:g.map(O=>e.jsx(t.SelectItem,{value:O.value,children:O.label},O.value))})]}):e.jsx(We,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:d.xMetricKey||"",onCommit:O=>A({xMetricKey:O})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Axis"}),x?e.jsxs(t.Select,{value:d.yMetricKey||"",onValueChange:O=>A({yMetricKey:O}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select Y metric"})}),e.jsx(t.SelectContent,{children:g.map(O=>e.jsx(t.SelectItem,{value:O.value,children:O.label},O.value))})]}):e.jsx(We,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:d.yMetricKey||"",onCommit:O=>A({yMetricKey:O})})]}),l&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Radius"}),x?e.jsxs(t.Select,{value:d.radiusMetricKey||"",onValueChange:O=>A({radiusMetricKey:O}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select radius metric"})}),e.jsx(t.SelectContent,{children:g.map(O=>e.jsx(t.SelectItem,{value:O.value,children:O.label},O.value))})]}):e.jsx(We,{className:"h-8 text-xs",placeholder:"Column name for radius",value:d.radiusMetricKey||"",onCommit:O=>A({radiusMetricKey:O})})]})]}),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:d.radiusScale||"sqrt",onValueChange:O=>A({radiusScale:O}),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"})]})]})]}),d.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(We,{className:"h-8 text-xs",type:"number",placeholder:"5",value:((E=d.minRadius)==null?void 0:E.toString())||"",onCommit:O=>A({minRadius:O?Number(O):void 0})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Max Radius"}),e.jsx(We,{className:"h-8 text-xs",type:"number",placeholder:"30",value:((D=d.maxRadius)==null?void 0:D.toString())||"",onCommit:O=>A({maxRadius:O?Number(O):void 0})})]})]}),d.radiusScale==="fixed"&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs(t.Label,{className:"text-xs",children:["Fixed Radius: ",d.fixedRadius||10]}),e.jsx(n.Slider,{value:[d.fixedRadius||10],onValueChange:([O])=>A({fixedRadius:O}),min:3,max:30,step:1,className:"py-2"})]})]}),c&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Point Settings"}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(t.Label,{className:"text-xs",children:["Point Size: ",d.fixedRadius||5]}),e.jsx(n.Slider,{value:[d.fixedRadius||5],onValueChange:([O])=>A({fixedRadius:O}),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:((y=(T=s==null?void 0:s.xAxisConfig)==null?void 0:T.name)==null?void 0:y.enabled)??!1,onCheckedChange:O=>{var z,V,q,U;const R=d.xMetricKey||"X Axis",B=d.yMetricKey||"Y Axis";N({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{enabled:O,text:((V=(z=s==null?void 0:s.xAxisConfig)==null?void 0:z.name)==null?void 0:V.text)||R}},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{enabled:O,text:((U=(q=s==null?void 0:s.yAxisConfig)==null?void 0:q.name)==null?void 0:U.text)||B}}})}})]}),((M=(L=s==null?void 0:s.xAxisConfig)==null?void 0:L.name)==null?void 0:M.enabled)&&e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"X Title"}),e.jsx(We,{className:"h-8 text-xs",placeholder:d.xMetricKey||"X Axis",value:((F=(P=s==null?void 0:s.xAxisConfig)==null?void 0:P.name)==null?void 0:F.text)||"",onCommit:O=>{var R;N({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{...(R=s==null?void 0:s.xAxisConfig)==null?void 0:R.name,enabled:!0,text:O||d.xMetricKey||"X Axis"}}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Title"}),e.jsx(We,{className:"h-8 text-xs",placeholder:d.yMetricKey||"Y Axis",value:((k=(j=s==null?void 0:s.yAxisConfig)==null?void 0:j.name)==null?void 0:k.text)||"",onCommit:O=>{var R;N({...s??{},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{...(R=s==null?void 0:s.yAxisConfig)==null?void 0:R.name,enabled:!0,text:O||d.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const fl=[{value:"percentOfTotal",label:"% of Total",description:"Each stage shows percentage of the sum of all values"},{value:"percentOfFirst",label:"% of Stage 1",description:"First stage = 100%, others relative to first stage"}];function gl(){const s=t.useEditorStore(p=>p.card),a=t.useEditorStore(p=>{var m;return(m=p.card)==null?void 0:m.preferences}),{setCardPreferences:r}=t.useEditorActions(),o=(s==null?void 0:s.type)==="funnel",u=(a==null?void 0:a.funnelConfig)||{},i=u.percentMode??"percentOfTotal",l=u.shrinkFraction??1,c=u.labelThreshold??0,d=p=>{const m={...u,...p};r({...a||{},funnelConfig:m})},h=p=>{d({percentMode:p})},x=p=>{d({shrinkFraction:p[0]})},g=p=>{d({labelThreshold:p[0]})};return o?e.jsxs(n.AccordionItem,{value:"funnel-config",className:"border-none",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Filter,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Funnel Settings"})]})}),e.jsxs(n.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(n.RadioGroup,{value:i,onValueChange:p=>h(p),className:"space-y-2",children:fl.map(p=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(n.RadioGroupItem,{id:`funnel-${p.value}`,value:p.value,className:"mt-0.5"}),e.jsxs(t.Label,{htmlFor:`funnel-${p.value}`,className:"flex flex-col gap-0.5 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:p.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:p.description})]})]},p.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"SEGMENT SHRINK"}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Same Width"}),e.jsx(n.Slider,{value:[l],onValueChange:x,min:0,max:1,step:.1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Full Shrink"})]}),e.jsxs("p",{className:"text-center text-xs text-muted-foreground",children:["Current: ",Math.round(l*100),"%"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"LABEL VISIBILITY THRESHOLD"}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Show All"}),e.jsx(n.Slider,{value:[c],onValueChange:g,min:0,max:25,step:1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Hide Small"})]}),e.jsx("p",{className:"text-center text-xs text-muted-foreground",children:c===0?"Showing all labels":`Hide labels below ${c}%`})]})]})]}):null}function as(){const s=t.useEditorStore(i=>i.card),{data:a}=n.useEditorCardQuery(s),{keys:r}=n.getKeys((a==null?void 0:a.records)||[]),o=r.slice(1).filter(i=>!t.METADATA_KEYS.includes(i));let u=o;if(["stackedBar","stackedLine"].includes(s.type)){const i=n.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:r[0],pivotKey:r[1],valueKey:r[2]}),{keys:l}=n.getKeys(i);u=l.slice(1)}return{transformedMetricKeys:u,dimensionKeys:r.slice(0,1),keys:r,defaultMetricKeys:o}}const bl=[{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"}],jl=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"}],vl=["center","start","end"],yl=["center","start","end","top","bottom"];function rs({config:s,onChange:a,isHorizontal:r=!1,showAutoFormat:o=!0,positionOptions:u,showAppearance:i=!0}){var f,w,b,N,A,_;const l=u??(r?["auto","center","left","right","custom"]:["auto","center","top","bottom","custom"]),c=o?["auto","number","currency","percent","none"]:["number","currency","percent","none"],d=(C,S)=>{const I={...s,[C]:S};a(I)},h=(C,S)=>{const I={...s,font:{...(s==null?void 0:s.font)||{},[C]:S}};a(I)},x=(C,S)=>{const I={...s,formatOptions:{...(s==null?void 0:s.formatOptions)||{},[C]:S}};a(I)},g=()=>r?"Right":"Top",p=s||{},m=p.format||(o?"auto":"number");return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(t.Select,{value:p.position||"auto",onValueChange:C=>d("position",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:l.map(C=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:C==="auto"?g():C==="custom"?"Custom (Advanced)":t.titleCase(C)},C))})]})]}),p.position==="custom"&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Anchor"}),e.jsxs(t.Select,{value:p.anchor||"center",onValueChange:C=>d("anchor",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:vl.map(C=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:t.titleCase(C)},C))})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Align"}),e.jsxs(t.Select,{value:String(p.align||"center"),onValueChange:C=>d("align",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:yl.map(C=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:t.titleCase(C)},C))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Format"}),e.jsxs(t.Select,{value:m,onValueChange:C=>d("format",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:c.map(C=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:C==="auto"&&o?"Auto (Use Axis)":C==="none"?"None (Raw Value)":t.titleCase(C)},C))})]})]}),!["auto","none"].includes(m)&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[["number","currency","percent"].includes(m)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Decimals"}),e.jsx("div",{className:"w-16",children:e.jsx(et,{type:"number",placeholder:"0",value:String(((f=p.formatOptions)==null?void 0:f.decimalPlaces)??(m==="currency"?2:m==="percent"?1:0)),onSave:C=>x("decimalPlaces",Number(C)),className:""})})]}),m==="currency"&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Currency"}),e.jsxs(t.Select,{value:((w=p.formatOptions)==null?void 0:w.currency)||"USD",onValueChange:C=>x("currency",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:bl.map(C=>e.jsx(t.SelectItem,{value:C.value,className:"text-xs",children:C.label},C.value))})]})]}),["number","currency"].includes(m)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Abbreviate (K, M, B)"}),e.jsx(t.Switch,{size:"sm",checked:((b=p.formatOptions)==null?void 0:b.useSuffix)??!1,onCheckedChange:C=>x("useSuffix",C)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Locale"}),e.jsxs(t.Select,{value:((N=p.formatOptions)==null?void 0:N.locale)||"en-US",onValueChange:C=>x("locale",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:jl.map(C=>e.jsx(t.SelectItem,{value:C.value,className:"text-xs",children:C.label},C.value))})]})]})]}),i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Appearance"}),e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Size"}),e.jsx("div",{className:"w-16",children:e.jsx(et,{type:"number",placeholder:"12",value:String(((A=p.font)==null?void 0:A.size)||12),onSave:C=>h("size",Number(C)),className:""})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Weight"}),e.jsxs(t.Select,{value:((_=p.font)==null?void 0:_.weight)||"normal",onValueChange:C=>h("weight",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(t.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Color"}),e.jsxs(t.Select,{value:p.color==="auto"||!p.color?"auto":"custom",onValueChange:C=>{C==="auto"&&d("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(et,{type:"number",placeholder:"0",value:String(p.rotation||0),onSave:C=>d("rotation",Number(C)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"°"})]})]})]})]})]})}const Nl=[{type:"bar",icon:n.ChartColumnIncreasing,label:"Bar"},{type:"line",icon:n.ChartLine,label:"Line"}],Cl=[0,1,2,3,4,5,6,8,10],Sl=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],wl=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Tl(){return t.useEditorStore(a=>{var r;return(r=a.card)==null?void 0:r.type})!=="combo"?null:e.jsxs(n.AccordionItem,{value:"combo-series",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(n.AccordionContent,{className:"pt-2",children:e.jsx(El,{})})]})}function El(){const{transformedMetricKeys:s}=as();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,r)=>e.jsx(Il,{metricKey:a,idx:r},a))})}function Il({metricKey:s,idx:a}){var N;const[r,o]=v.useState(!1),u=t.useEditorStore(A=>{var _;return(_=A.card)==null?void 0:_.preferences}),i=t.useEditorStore(A=>{var _,C;return(C=(_=A.card)==null?void 0:_.preferences)==null?void 0:C.datasetOptions}),l=i==null?void 0:i.find(A=>A.idx===a),{setCardPreferences:c}=t.useEditorStore(A=>A.actions),d=(l==null?void 0:l.type)||"bar",h=(l==null?void 0:l.yAxisId)||"y",x=((N=l==null?void 0:l.dataLabels)==null?void 0:N.enabled)??!1,g=d==="line"?n.ChartLine:n.ChartColumnIncreasing;function p(A){const _={idx:a,type:d,yAxisId:h,dataLabels:l==null?void 0:l.dataLabels,...A};if(!l)c({...u||{},datasetOptions:[...i||[],_]});else{const C=i==null?void 0:i.map(S=>S.idx===a?{...S,..._}:S);c({...u||{},datasetOptions:C})}}function m(A){p({type:A})}function f(A){p({yAxisId:A})}function w(A){p({dataLabels:{...l==null?void 0:l.dataLabels,enabled:A}})}function b(A){p({dataLabels:A})}return e.jsx(n.Collapsible,{open:r,onOpenChange:o,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(n.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(n.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",r&&"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(g,{className:"h-3 w-3"}),d==="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:h==="y2"?"Y2":"Y1"})]})]})}),e.jsx(n.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"flex items-end gap-4",children:[e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Chart Type"}),e.jsx("div",{className:"flex gap-2",children:Nl.map(({type:A,icon:_,label:C})=>{const S=d===A;return e.jsxs("button",{onClick:()=>m(A),className:t.cn("flex items-center gap-2 rounded-md border px-3 py-1.5 text-xs transition-colors",S?"border-primary bg-primary/10 text-primary":"border-border bg-background text-muted-foreground hover:bg-muted"),children:[e.jsx(_,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:C})]},A)})})]}),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:h,onValueChange:A=>f(A),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)"})]})]})]})]}),d==="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:A=>p({lineStyle:A}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:wl.map(({value:A,label:_})=>e.jsx(t.SelectItem,{value:A,className:"text-xs",children:_},A))})]})]}),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:A=>p({pointRadius:Number(A)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Cl.map(A=>e.jsx(t.SelectItem,{value:String(A),className:"text-xs",children:A===0?"None":A},A))})]})]}),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:A=>p({pointStyle:A}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Sl.map(({value:A,label:_})=>e.jsx(t.SelectItem,{value:A,className:"text-xs",children:_},A))})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(t.Switch,{size:"sm",checked:x,onCheckedChange:w})]}),x&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(rs,{config:l==null?void 0:l.dataLabels,onChange:b,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Cs=[{value:"origin",label:"Origin (X-axis)",description:"Fill to the X-axis (y=0)"},{value:"start",label:"Start (Top)",description:"Fill to the top of chart area"},{value:"end",label:"End (Bottom)",description:"Fill to the bottom of chart area"},{value:"-1",label:"Previous Series",description:"Fill to the series below"},{value:"+1",label:"Next Series",description:"Fill to the series above"},{value:"false",label:"No Fill (Line)",description:"Show as line without fill"}],Dl=[0,1,2,3,4,5,6,8,10],kl=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],Al=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Ll(s){return s==null?"origin":s===!1?"false":s}function Ml(){const s=t.useEditorStore(a=>{var r;return(r=a.card)==null?void 0:r.type});return s!=="area"&&s!=="stackedArea"?null:e.jsxs(n.AccordionItem,{value:"area-series",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(n.AccordionContent,{className:"pt-2",children:e.jsx(Fl,{})})]})}function Fl(){const{transformedMetricKeys:s}=as();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,r)=>e.jsx(Rl,{metricKey:a,idx:r},a))})}function Rl({metricKey:s,idx:a}){var w;const[r,o]=v.useState(!1),u=t.useEditorStore(b=>{var N;return(N=b.card)==null?void 0:N.preferences}),i=t.useEditorStore(b=>{var N,A;return(A=(N=b.card)==null?void 0:N.preferences)==null?void 0:A.datasetOptions}),l=i==null?void 0:i.find(b=>b.idx===a),{setCardPreferences:c}=t.useEditorStore(b=>b.actions),d=Ll(l==null?void 0:l.fill),h=((w=l==null?void 0:l.dataLabels)==null?void 0:w.enabled)??!1,x=Cs.find(b=>b.value===d)||Cs[0];function g(b){const N={idx:a,fill:d,dataLabels:l==null?void 0:l.dataLabels,...b};if(!l)c({...u||{},datasetOptions:[...i||[],N]});else{const A=i==null?void 0:i.map(_=>_.idx===a?{..._,...N}:_);c({...u||{},datasetOptions:A})}}function p(b){g({fill:b==="false"?!1:b})}function m(b){g({dataLabels:{...l==null?void 0:l.dataLabels,enabled:b}})}function f(b){g({dataLabels:b})}return e.jsx(n.Collapsible,{open:r,onOpenChange:o,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(n.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(n.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",r&&"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(n.ChartArea,{className:"h-3 w-3"}),x.label.split(" ")[0]]})})]})}),e.jsx(n.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:d,onValueChange:b=>p(b),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Cs.map(b=>e.jsx(t.SelectItem,{value:b.value,className:"text-xs",children:e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{children:b.label})})},b.value))})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(t.Select,{value:(l==null?void 0:l.lineStyle)||"solid",onValueChange:b=>g({lineStyle:b}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Al.map(({value:b,label:N})=>e.jsx(t.SelectItem,{value:b,className:"text-xs",children:N},b))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(t.Select,{value:String((l==null?void 0:l.pointRadius)??3),onValueChange:b=>g({pointRadius:Number(b)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Dl.map(b=>e.jsx(t.SelectItem,{value:String(b),className:"text-xs",children:b===0?"None":b},b))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(t.Select,{value:(l==null?void 0:l.pointStyle)||"circle",onValueChange:b=>g({pointStyle:b}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:kl.map(({value:b,label:N})=>e.jsx(t.SelectItem,{value:b,className:"text-xs",children:N},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:h,onCheckedChange:m})]}),h&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(rs,{config:l==null?void 0:l.dataLabels,onChange:f,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Ol=[0,1,2,3,4,5,6,8,10],Pl=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],Ss=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Vl(){return t.useEditorStore(a=>{var r;return(r=a.card)==null?void 0:r.type})!=="line"?null:e.jsxs(n.AccordionItem,{value:"line-series",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(n.AccordionContent,{className:"pt-2",children:e.jsx(Bl,{})})]})}function Bl(){const{transformedMetricKeys:s}=as();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,r)=>e.jsx(_l,{metricKey:a,idx:r},a))})}function _l({metricKey:s,idx:a}){var b;const[r,o]=v.useState(!1),u=t.useEditorStore(N=>{var A;return(A=N.card)==null?void 0:A.preferences}),i=t.useEditorStore(N=>{var A,_;return(_=(A=N.card)==null?void 0:A.preferences)==null?void 0:_.datasetOptions}),l=i==null?void 0:i.find(N=>N.idx===a),{setCardPreferences:c}=t.useEditorStore(N=>N.actions),d=(l==null?void 0:l.lineStyle)||"solid",h=(l==null?void 0:l.pointRadius)??3,x=(l==null?void 0:l.pointStyle)||"circle",g=((b=l==null?void 0:l.dataLabels)==null?void 0:b.enabled)??!1,p=Ss.find(N=>N.value===d)||Ss[0];function m(N){const A={idx:a,lineStyle:d,pointRadius:h,pointStyle:x,dataLabels:l==null?void 0:l.dataLabels,...N};if(!l)c({...u||{},datasetOptions:[...i||[],A]});else{const _=i==null?void 0:i.map(C=>C.idx===a?{...C,...A}:C);c({...u||{},datasetOptions:_})}}function f(N){m({dataLabels:{...l==null?void 0:l.dataLabels,enabled:N}})}function w(N){m({dataLabels:N})}return e.jsx(n.Collapsible,{open:r,onOpenChange:o,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(n.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(n.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",r&&"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(n.TrendingUp,{className:"h-3 w-3"}),p.label.split(" ")[0]]})})]})}),e.jsx(n.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:d,onValueChange:N=>m({lineStyle:N}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ss.map(({value:N,label:A})=>e.jsx(t.SelectItem,{value:N,className:"text-xs",children:A},N))})]})]}),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(h),onValueChange:N=>m({pointRadius:Number(N)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ol.map(N=>e.jsx(t.SelectItem,{value:String(N),className:"text-xs",children:N===0?"None":N},N))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(t.Select,{value:x,onValueChange:N=>m({pointStyle:N}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Pl.map(({value:N,label:A})=>e.jsx(t.SelectItem,{value:N,className:"text-xs",children:A},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 text-muted-foreground",children:"Data Labels"}),e.jsx(t.Switch,{size:"sm",checked:g,onCheckedChange:f})]}),g&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(rs,{config:l==null?void 0:l.dataLabels,onChange:w,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const zl=[0,2,4,6,8,10,12,16,20];function ql(){const s=t.useEditorStore(a=>{var r;return(r=a.card)==null?void 0:r.type});return!s||!["bar","horizontalBar","stackedBar"].includes(s)?null:e.jsxs(n.AccordionItem,{value:"bar-series",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(n.AccordionContent,{className:"pt-2",children:e.jsx($l,{})})]})}function $l(){const{transformedMetricKeys:s}=as();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,r)=>e.jsx(Kl,{metricKey:a,idx:r},a))})}function Kl({metricKey:s,idx:a}){var f;const[r,o]=v.useState(!1),u=t.useEditorStore(w=>{var b;return(b=w.card)==null?void 0:b.type}),i=t.useEditorStore(w=>{var b;return(b=w.card)==null?void 0:b.preferences}),l=t.useEditorStore(w=>{var b,N;return(N=(b=w.card)==null?void 0:b.preferences)==null?void 0:N.datasetOptions}),c=l==null?void 0:l.find(w=>w.idx===a),{setCardPreferences:d}=t.useEditorStore(w=>w.actions),h=(c==null?void 0:c.borderRadius)??0,x=((f=c==null?void 0:c.dataLabels)==null?void 0:f.enabled)??!1;function g(w){const b={idx:a,borderRadius:h,dataLabels:c==null?void 0:c.dataLabels,...w};if(!c)d({...i||{},datasetOptions:[...l||[],b]});else{const N=l==null?void 0:l.map(A=>A.idx===a?{...A,...b}:A);d({...i||{},datasetOptions:N})}}function p(w){g({dataLabels:{...c==null?void 0:c.dataLabels,enabled:w}})}function m(w){g({dataLabels:w})}return e.jsx(n.Collapsible,{open:r,onOpenChange:o,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(n.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(n.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",r&&"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:h>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:",h]})})]})}),e.jsx(n.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(h),onValueChange:w=>g({borderRadius:Number(w)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:zl.map(w=>e.jsx(t.SelectItem,{value:String(w),className:"text-xs",children:w===0?"None":`${w}px`},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:x,onCheckedChange:p})]}),x&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(rs,{config:c==null?void 0:c.dataLabels,onChange:m,isHorizontal:u==="horizontalBar",showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Ul=[0,1,2,3,4,5,6,8,10],Gl=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],Hl=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Ql(){const s=t.useEditorStore(c=>c.card),a=t.useEditorStore(c=>{var d;return(d=c.card)==null?void 0:d.preferences}),r=Ne.useEffectiveEditorCardType(),o=a==null?void 0:a.lineStyleConfig,{setCardPreferences:u,updateCardInFrame:i}=t.useEditorActions();if(!s||!["line","area","stackedArea"].includes(r))return null;const l=(c,d)=>{const h={...a||{},lineStyleConfig:{...o,[c]:d}};u(h),i({...s,preferences:h})};return e.jsxs(n.AccordionItem,{value:"line-style",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Line Style"})]})}),e.jsx(n.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:(o==null?void 0:o.lineStyle)||"solid",onValueChange:c=>l("lineStyle",c),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Hl.map(({value:c,label:d})=>e.jsx(t.SelectItem,{value:c,className:"text-xs",children:d},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Point Size"}),e.jsxs(t.Select,{value:String((o==null?void 0:o.pointRadius)??3),onValueChange:c=>l("pointRadius",Number(c)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ul.map(c=>e.jsx(t.SelectItem,{value:String(c),className:"text-xs",children:c===0?"None":c},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Point Shape"}),e.jsxs(t.Select,{value:(o==null?void 0:o.pointStyle)||"circle",onValueChange:c=>l("pointStyle",c),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Gl.map(({value:c,label:d})=>e.jsx(t.SelectItem,{value:c,className:"text-xs",children:d},c))})]})]})]})})]})}const Wl=[0,2,4,6,8,10,12,16,20],Yl=[{value:"0.5",label:"50%"},{value:"0.6",label:"60%"},{value:"0.7",label:"70%"},{value:"0.8",label:"80%"},{value:"0.9",label:"90%"},{value:"1",label:"100%"}],Jl=[{value:"0.5",label:"50%"},{value:"0.6",label:"60%"},{value:"0.7",label:"70%"},{value:"0.8",label:"80%"},{value:"0.9",label:"90%"},{value:"1",label:"100%"}];function Xl(){const s=t.useEditorStore(c=>c.card),a=t.useEditorStore(c=>{var d;return(d=c.card)==null?void 0:d.preferences}),r=Ne.useEffectiveEditorCardType(),o=a==null?void 0:a.barStyleConfig,{setCardPreferences:u,updateCardInFrame:i}=t.useEditorActions();if(!s||!["bar","horizontalBar","stackedBar"].includes(r))return null;const l=(c,d)=>{const h={...a||{},barStyleConfig:{...o,[c]:d}};u(h),i({...s,preferences:h})};return e.jsxs(n.AccordionItem,{value:"bar-style",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.ChartColumn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bar Style"})]})}),e.jsx(n.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((o==null?void 0:o.borderRadius)??0),onValueChange:c=>l("borderRadius",Number(c)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Wl.map(c=>e.jsx(t.SelectItem,{value:String(c),className:"text-xs",children:c===0?"None":`${c}px`},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Bar Width"}),e.jsxs(t.Select,{value:String((o==null?void 0:o.barPercentage)??.9),onValueChange:c=>l("barPercentage",Number(c)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Yl.map(({value:c,label:d})=>e.jsx(t.SelectItem,{value:c,className:"text-xs",children:d},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Category Width"}),e.jsxs(t.Select,{value:String((o==null?void 0:o.categoryPercentage)??.8),onValueChange:c=>l("categoryPercentage",Number(c)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Jl.map(({value:c,label:d})=>e.jsx(t.SelectItem,{value:c,className:"text-xs",children:d},c))})]})]})]})})]})}function Zl(){const s=t.useEditorStore(r=>{var o,u;return(u=(o=r==null?void 0:r.card)==null?void 0:o.preferences)==null?void 0:u.sortChart}),{setSortChart:a}=t.useEditorActions();return e.jsxs(n.AccordionItem,{value:"stacked-sort",children:[e.jsx(n.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qn,{className:"h-3.5 w-3.5 text-foreground/60"}),"Sort"]})}),e.jsx(n.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(ut,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"Ascending",value:"asc"},{label:"Descending",value:"desc"}],value:s||"none",onValueChange:r=>{a(r)}})]})})]})}const ei=["kpi"],ws=2;function ft(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 ti(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 si(s){return{...s,role:"groupby"}}function ni(){var A,_;const s=t.useEditorStore(C=>C.card),a=t.useEditorStore(C=>C.actions.updateCardConfig),r=Ne.useEffectiveEditorCardType(),{scopedFields:o}=n.useScopedFields(),u=((A=s.config)==null?void 0:A.metricColumns)||[],i=((_=s.config)==null?void 0:_.summary)||{},l=i.breakdownDimensions||[],c=l.length>0,d=ei.includes(r),h=u.length>0,x=i.enabled===!0,g=d&&h,p=Array.from(new Map(o.filter(ti).map(C=>[ft(C),si(C)])).values()),m=new Set(p.map(C=>ft(C))),f=new Set(l.map(C=>ft(C)).filter(C=>C&&m.has(C)));if(!d)return null;const w=C=>{a(s.id,{summary:{...i,...C}})},b=(C,S)=>{const I=ft(C),E=p.filter(T=>f.has(ft(T))),D=S?f.has(I)?E:[...E,C].slice(0,ws):E.filter(T=>ft(T)!==I);w({breakdownDimensions:D,...D.length>0?{showOnCard:!0}:{}})},N=C=>{if(!C){w({enabled:!1,showOnCard:!1,includeInDashboardSummary:!1});return}w({enabled:!0,showOnCard:i.showOnCard??!0,includeInDashboardSummary:i.includeInDashboardSummary??!0})};return e.jsxs(n.AccordionItem,{value:"summary",className:"border-none",children:[e.jsxs(n.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-[12px] hover:no-underline [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground",children:[e.jsxs("div",{className:"flex flex-1 items-center gap-2",children:[e.jsx(n.FileText,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:"Summary"})]}),e.jsx(t.Switch,{size:"xs",checked:x,disabled:!g,onClick:C=>C.stopPropagation(),onPointerDown:C=>C.stopPropagation(),onCheckedChange:N,"aria-label":"Enable summary"})]}),e.jsx(n.AccordionContent,{className:"pb-4 pt-2",children:e.jsxs("div",{className:t.cn("space-y-3 transition-opacity",!x&&"opacity-60"),children:[!g&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:h?"Summary is not supported for this card type.":"Add at least one metric to enable summary."}),!c&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Checkbox,{id:"summary-show-on-card",checked:i.showOnCard===!0,disabled:!x,onCheckedChange:C=>w({showOnCard:C===!0})}),e.jsx(t.Label,{htmlFor:"summary-show-on-card",className:"cursor-pointer text-xs",children:"Show summary on card"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Checkbox,{id:"summary-include-rollup",checked:i.includeInDashboardSummary===!0,disabled:!x,onCheckedChange:C=>w({includeInDashboardSummary:C===!0})}),e.jsx(t.Label,{htmlFor:"summary-include-rollup",className:"cursor-pointer text-xs",children:"Include in dashboard summary"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Breakdown Dimensions"}),e.jsxs("span",{className:"text-[11px] tabular-nums text-muted-foreground",children:[l.length,"/",ws]})]}),p.length===0?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"No dimension fields available for breakdown."}):e.jsx("ul",{className:"max-h-40 space-y-1 overflow-y-auto",children:p.map(C=>{const S=ft(C),I=f.has(S),E=f.size>=ws,D=!x||!I&&E;return e.jsxs("li",{className:"flex items-center gap-2 text-xs",children:[e.jsx(n.Checkbox,{id:`summary-breakdown-${S}`,checked:I,disabled:D,onCheckedChange:T=>b(C,T===!0)}),e.jsx(t.Label,{htmlFor:`summary-breakdown-${S}`,className:"cursor-pointer text-xs",children:C.label||C.name})]},S)})})]})]})})]})}const ai=new Set(["area","bar","bubble","bullet","combo","doughnut","funnel","horizontalBar","line","pie","polarArea","radar","scatter","stackedArea","stackedBar","stackedLine","tornado"]);function ri(){const s=t.useEditorStore(d=>d.card),a=t.useEditorStore(d=>{var h;return(h=d.card)==null?void 0:h.preferences}),r=Ne.useEffectiveEditorCardType(),{setCardPreferences:o,updateCardInFrame:u}=t.useEditorActions();if(!s||!ai.has(r||""))return null;const i=a==null?void 0:a.tooltipConfig,l=(i==null?void 0:i.formatMode)||(i==null?void 0:i.mode)||"inherit",c=d=>{const h={...a||{},tooltipConfig:{...i||{},...d}};o(h),u({...s,preferences:h})};return e.jsxs(n.AccordionItem,{value:"tooltip-format",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Info,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:"Tooltip Format"})]})}),e.jsxs(n.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:d=>c({formatMode:d?"override":"inherit",mode:d?"override":"inherit"})})]}),l==="override"&&e.jsx(kt,{formatOptions:(i==null?void 0:i.formatOptions)||{},onFormatOptionsChange:d=>c({formatMode:"override",mode:"override",formatOptions:d}),showTitle:!1})]})]})}function ga({mode:s}){const a=t.useEditorStore(r=>{var o;return(o=r.card)==null?void 0:o.type});return e.jsxs(e.Fragment,{children:[a==="combo"&&e.jsx(Tl,{}),(a==="area"||a==="stackedArea")&&e.jsx(Ml,{}),a==="line"&&e.jsx(Vl,{}),(a==="bar"||a==="horizontalBar"||a==="stackedBar")&&e.jsx(ql,{}),e.jsx(Ql,{}),e.jsx(Xl,{}),e.jsx(ul,{}),s==="config"&&e.jsx(dl,{}),s==="config"&&e.jsx(ni,{}),e.jsx(xl,{}),a==="bullet"&&e.jsx(hl,{}),a==="funnel"&&e.jsx(gl,{}),(a==="bubble"||a==="scatter")&&e.jsx(pl,{}),(a==="stackedBar"||a==="stackedLine")&&e.jsx(Zl,{}),e.jsx(rl,{}),e.jsx(ol,{}),e.jsx(ll,{}),e.jsx(il,{}),e.jsx(ri,{})]})}function oi(){const s=t.useEditorStore(r=>r.card),a=s==null?void 0:s.type;return a?e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(Fs,{chartType:a}),e.jsx(n.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:e.jsx(ga,{mode:"dev"})})]}):null}function li({focusSection:s,focusRequestId:a}){const r=t.useEditorStore(l=>l.card),o=r.type;if(t.getVisualizationMode(r)==="dynamic")return e.jsx("div",{className:"p-6",children:e.jsxs(n.Alert,{children:[e.jsx(t.Info,{className:"h-4 w-4"}),e.jsx(n.AlertTitle,{children:"Dynamic mode manages presentation"}),e.jsx(n.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 i(){switch(o){case"kpi":return e.jsx(Po,{});case"table":case"detailTable":case"aggregateTable":case"pivotTable":return e.jsx(fa,{cardType:o,focusSection:s,focusRequestId:a});case"map":return e.jsx(qo,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(xa,{})});case"text":return e.jsx(el,{});default:return e.jsx(oi,{})}}return e.jsxs(t.ScrollArea,{className:"h-full w-full text-sm",children:[i(),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}function ii(){const s=v.useRef(null),a=v.useRef(null),r=t.useEditorStore(N=>N.isShowingVisual),o=t.useEditorStore(N=>N.isDevMode),u=t.useEditorStore(N=>N.showAIDialog),[i,l]=v.useState(!1),[c,d]=v.useState({section:null,id:0}),h=r&&!u,x=h&&(!o||i),g=o&&h,p=()=>l(N=>!N),m=N=>{N&&d(A=>({section:N,id:A.id+1})),o&&l(!0)};v.useEffect(()=>{var N,A,_,C;u?((N=s.current)==null||N.resize(0),(A=a.current)==null||A.resize(0)):((_=s.current)==null||_.resize(25),(C=a.current)==null||C.resize(25))},[u]);const[f,w]=v.useState(!1),b=h?{show:g,isOpen:x,onToggle:p,onOpen:m}:void 0;return e.jsxs(n.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:[e.jsx(n.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:50,children:e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex min-h-0 flex-1 flex-col",children:e.jsx(Qr,{})}),e.jsx(hs,{mode:"toolbar",visualAsideControl:b,isDynamicInspectorOpen:f,onDynamicInspectorOpenChange:w})]})}),e.jsx(n.ResizableHandle,{}),e.jsx(n.ResizablePanel,{role:"visual-section",minSize:0,defaultSize:50,children:x?e.jsxs(n.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(n.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(hs,{mode:"canvas",visualAsideControl:b,isDynamicInspectorOpen:f,onDynamicInspectorOpenChange:w})}),!u&&e.jsx(n.ResizableHandle,{}),e.jsx(n.ResizablePanel,{ref:s,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(li,{focusSection:c.section,focusRequestId:c.id})})]}):e.jsx(hs,{mode:"canvas",visualAsideControl:b,isDynamicInspectorOpen:f,onDynamicInspectorOpenChange:w})})]})}function ci(s){var ie;t.useAIInteractionStore($=>$.currentAIContext);const[a,r]=v.useState(""),[o,u]=v.useState(null),{authToken:i,tokenProps:l}=n.useSemaphorContext(),c=t.useEditorStore($=>$.card.id),d=t.useEditorStore($=>{var oe;return(oe=$==null?void 0:$.card)==null?void 0:oe.sql}),h=t.useEditorStore($=>$.isDevMode),x=t.useEditorStore($=>{var oe;return(oe=$==null?void 0:$.card)==null?void 0:oe.python}),{setCardPython:g,setCardSql:p,setRunSql:m,switchCardType:f,setQueryConfig:w}=t.useEditorActions(),b=t.useEditorStore($=>$.currentAssitantScope)||[],N=t.useEditorStore($=>$.userInputForAI),A=t.useEditorStore($=>$.triggerAIRun),_=t.useEditorStore($=>$.card),C=t.useEditorStore($=>$.selectedDatabaseName),S=t.useEditorStore($=>$.selectedTableName),I=t.useEditorStore($=>$.selectedConnectionId),E=t.useEditorStore($=>$.selectedSchemaName),D=t.useDashboardStore($=>$.dashboard.aiScopeTables),{errorMessage:T,refetch:y,data:L}=n.useEditorCardQuery(_),{setTriggerAIRun:M,setCurrentAssitantScope:P,setCardConfig:F}=t.useEditorActions(),{selectedDatamodelName:j,connectionType:k,selectedDatamodelId:O}=n.useEditorAside(),R=(ie=n.useDashboardQuery().data)==null?void 0:ie.assistantProfileId,B=v.useRef(n.createAssistantConversationId()),z=v.useRef(null),V=v.useRef(c),q=v.useRef(!1),U=()=>{const $=z.current;$&&(z.current=null,B.current=n.createAssistantConversationId(),$==="clear"&&Q([]))},{messages:G,setMessages:Q,regenerate:Y,error:H,sendMessage:se,status:ue,addToolResult:ae,stop:me,clearError:ve}=n.useChat({transport:new n.DefaultChatTransport({api:`${l.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${i==null?void 0:i.accessToken}`}),body:()=>{const $=t.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:R,conversationId:B.current,assistantRequestId:n.createAssistantRequestId(),isDevMode:h,aiContext:$.currentAIContext,reasoningEffort:$.reasoningEffort,showReasoning:$.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:$,body:oe})=>({body:{...oe,messages:t.cleanupIncompleteMessages($)}})}),onError:$=>{var oe;if(q.current=!1,$.name==="AbortError"||(oe=$.message)!=null&&oe.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)"),U();return}console.error("[Editor Assistant] Stream error:",$),U()},onToolCall:ge,onFinish({isAbort:$,isDisconnect:oe,isError:fe}){q.current=!1,r(""),console.log($?"[Editor Assistant] Stream aborted by user":oe?"[Editor Assistant] Stream disconnected (network error)":fe?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully"),U()}}),Oe=v.useCallback($=>{q.current=!0;try{const oe=se($);return n.isPromiseLike(oe)?oe.catch(fe=>{throw q.current=!1,fe}):oe}catch(oe){throw q.current=!1,oe}},[se]),Fe=v.useCallback(()=>{q.current=!0;try{const $=Y();return n.isPromiseLike($)?$.catch(oe=>{throw q.current=!1,oe}):$}catch($){throw q.current=!1,$}},[Y]),X=$=>{let oe=!1;Q(fe=>{const ne=typeof $=="function"?$(fe):$;if(ne.length===0){if(q.current)return z.current="clear",oe=!0,fe;z.current=null,B.current=n.createAssistantConversationId()}return ne}),oe&&me()};v.useEffect(()=>{if(V.current!==c){if(V.current=c,q.current){z.current!=="clear"&&(z.current="rotate"),me();return}z.current=null,B.current=n.createAssistantConversationId()}},[c,me]),v.useEffect(()=>{A&&N&&(Oe({role:"user",parts:[{type:"text",text:N}]}),M(!1))},[A,N,Oe,M]);async function ge({toolCall:$}){var oe,fe,ne,ce,Te,ke,ze,re,te,xe,ye,Ee,qe,Ie,Qe,Ue;if(["createChartFromSql","createForecast"].includes($.toolName)){const Ae=((oe=$.input)==null?void 0:oe.sql)??((fe=$.args)==null?void 0:fe.sql),tt=((ne=$.input)==null?void 0:ne.python)??((ce=$.args)==null?void 0:ce.python),Le=((Te=$.input)==null?void 0:Te.chartType)??((ke=$.args)==null?void 0:ke.chartType);f(Le),p(Ae),g(tt),m(!0),ae({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if($.toolName==="getUserSql"){if(!d){ae({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",message:"No SQL found"}});return}ae({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",sql:d,python:x||""}})}else if($.toolName==="generateQueryConfig"){r("Generating query config...");const Ae=((ze=$.input)==null?void 0:ze.chartType)??((re=$.args)==null?void 0:re.chartType),tt=((te=$.input)==null?void 0:te.queryConfig)??((xe=$.args)==null?void 0:xe.queryConfig);((ye=$.input)==null?void 0:ye.cardConfig)??((Ee=$.args)==null||Ee.cardConfig),f(Ae),F(tt),p(void 0),g(void 0);const Le=await y();if((qe=Le==null?void 0:Le.data)!=null&&qe.error){ae({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",queryConfig:tt,message:(Ie=Le==null?void 0:Le.data)==null?void 0:Ie.error.message}});return}if((Qe=Le==null?void 0:Le.data)!=null&&Qe.records){ae({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:tt,message:"The data has been visualized"}});return}ae({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:tt,message:"The data has been visualized",records:(Ue=Le==null?void 0:Le.data)==null?void 0:Ue.records}})}else r("Analyzing...")}function Ce($){const oe=n.removeFromScopeArray(b,$);Pe(oe)}function Pe($){const oe=n.sanitizeAIScope($);P(oe),Q(fe=>[...fe,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(oe)}`}]}])}function _e(){const $={databaseName:C||"",schemaName:E||"",tableName:S||"",datamodelId:O||"",datamodelName:t.resolveDatamodelName(j),connectionId:I||"",connectionType:k||""},oe=n.dedup([...b,$]);Pe(oe)}function le(){const $={databaseName:C||"",schemaName:E||"",tableName:S||"",datamodelName:t.resolveDatamodelName(j),connectionId:I||"",connectionType:k||"",datamodelId:O||""};if(!n.isInAiScopeArray([...D||[],...b],$)||b.length===0){const fe=n.dedup([...D||[],...b,$]).filter(ne=>ne.connectionId===$.connectionId);Pe(fe)}}const De=!["ready","error"].includes(ue),Se=n.getErrorMessage(H);return{messages:G,setMessages:X,sendMessage:Oe,regenerate:Fe,isLoading:De,handleSetAIScope:le,handleAddCurrentTableToScope:_e,removeFromCurrentSelections:Ce,currentAssitantScope:b,setCurrentAssitantScope:P,stop:me,status:ue,toolStatus:a,llmUsage:o,onFinish:s,errorMessage:Se,clearError:ve}}const di=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Kn({isFullscreen:s,onFullscreenChange:a,fullscreenContainer:r}){const o=v.useRef(null),u=v.useRef(!1),[i,l]=v.useState(!1),[c,d]=v.useState(t.isDevEnv),[h,x]=v.useState(!1),[g,p]=v.useState(!1),[m,f]=v.useState(!1),[w,b]=v.useState(0),N=s??m,A=t.useCurrentAIContext(),{setCurrentAIContext:_,setHasEditorEntitySelectionOverride:C}=t.useAIActions(),{clearQueue:S}=t.useQueueActions(),{clearFileAttachments:I}=t.useFileActions(),E=t.useFileAttachments("editor"),{selectedEntities:D}=n.useAssistantContextEntities("editor"),T=t.useEditorStore(ne=>ne.card.id),y=t.useEditorStore(ne=>ne.card.dataSource),L=t.useEditorStore(ne=>{var ce;return(ce=ne.card.dataSource)==null?void 0:ce.selectedEntities}),M=t.useEditorStore(ne=>ne.actions.setCardSql),P=t.useEditorStore(ne=>ne.actions.setRunSql),F=t.useEditorStore(ne=>ne.showAIDialog),j=t.useDashboardStore(ne=>ne.handleOpenAssistantProfile),{setShowAIDialog:k,setCardPython:O}=t.useEditorActions(),{assistantProfile:R}=n.useAssistantProfile(),{messages:B,setMessages:z,sendMessage:V,isLoading:q,stop:U,status:G,llmUsage:Q,errorMessage:Y,clearError:H}=ci(),[se,ue]=v.useState(""),ae=ne=>{ue(ne.target.value)},me=ne=>{ne.preventDefault();const ce=se.trim();if(!ce&&E.length===0)return;const Te=[];ce&&Te.push({type:"text",text:ce}),E.forEach(ke=>{ke.data&&Te.push({type:"file",mediaType:ke.type,filename:ke.name,url:`data:${ke.type};base64,${ke.data}`})}),V({role:"user",parts:Te}),ue(""),I("editor"),ve()},ve=v.useCallback(()=>{b(ne=>ne+1)},[]);v.useEffect(()=>{var ne;F&&!u.current&&((ne=o.current)==null||ne.focus()),u.current=F},[F]),v.useEffect(()=>{F&&(C(!1),_({selectedEntities:L||[]}))},[T,L,_,C,F]),n.useAutoSubmitQueue({assistantType:"editor",status:G,isLoading:q,sendMessage:V});const{hasActiveTools:Oe,activeToolText:Fe}=n.useActiveToolStatus(B),X=v.useCallback(ne=>{a==null||a(ne),s===void 0&&f(ne)},[s,a]);v.useEffect(()=>{if(!N)return;function ne(ce){ce.key==="Escape"&&X(!1)}return window.addEventListener("keydown",ne),()=>{window.removeEventListener("keydown",ne)}},[N,X]);const ge=v.useCallback(ne=>{V({role:"user",parts:[{type:"text",text:ne}]}),ve()},[ve,V]),Ce=v.useCallback(async()=>{const ne=JSON.stringify(B??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(ne),n.ue.success("Conversation copied")}catch(ce){console.error("Failed to copy conversation",ce),n.ue.error("Unable to copy conversation")}},[B]),Pe=v.useCallback(()=>{X(!N)},[N,X]);function _e(ne,ce){ce==="sql"?(M(ne),P(!0)):ce==="python"&&(O(ne),P(!0))}function le(){A.selectedEntities.length===0&&_({selectedEntities:D})}function De(ne){le();const ce={role:"user",parts:[{type:"text",text:ne.title+" "+ne.subtitle}]};V(ce),ve()}function Se(ne){le(),V({role:"user",parts:[{type:"text",text:ne}]}),ve()}function ie(){return e.jsxs(n.DropdownMenu,{children:[e.jsx(n.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(n.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(n.DropdownMenuContent,{align:"end",children:[e.jsx(n.DropdownMenuLabel,{children:"Options"}),e.jsx(n.DropdownMenuSeparator,{}),e.jsx(n.DropdownMenuCheckboxItem,{checked:i,onCheckedChange:l,children:"Token Usage"}),e.jsx(n.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:d,children:"Tool Invocations"}),e.jsx(n.DropdownMenuCheckboxItem,{checked:h,onCheckedChange:x,children:"System Message"})]})]})}function $(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const oe=(se==null?void 0:se.length)===0&&(B==null?void 0:B.filter(ne=>ne.role==="user").length)===0,fe=e.jsxs("div",{"data-role":"editor-assistant",className:t.cn("flex h-full w-full flex-col justify-between px-6 py-4",N&&"rounded-card 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:[$(),j&&e.jsx(t.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:j,children:(R==null?void 0:R.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[ie(),c&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Ce,children:"Copy Conversation"}),e.jsx(n.IconButton,{tooltip:N?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:Pe,children:N?e.jsx(n.Minimize2,{className:"size-4"}):e.jsx(n.Maximize2,{className:"size-4"})}),e.jsx(n.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{z([]),S("editor"),H()},children:e.jsx(n.SquarePen,{className:"size-4"})}),e.jsx(t.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{k(!1)},children:e.jsx(t.X,{className:"size-4"})})]})]}),e.jsx(n.AssistantVirtualizedMessages,{messages:B,showTools:c,handleRun:_e,showSystemMessage:h,onQuickReply:ge,disableQuickReplies:q,status:G,errorMessage:Y,activeToolText:q&&Oe?Fe:void 0,className:"mt-2 w-full grow px-0 py-2 pr-3",latestButtonClassName:F?"bottom-24 right-8":"hidden",scrollToEndSignal:w}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[oe&&!R&&e.jsx(n.Placeholders,{onClick:De,placeholders:di}),e.jsx("div",{children:oe&&R&&e.jsx(n.SeedQuestions,{seedQuestions:R.seedQuestions||[],handleSeedQuestionClick:Se})})]}),e.jsx(n.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(n.ChatInputWithContext,{ref:o,setInput:ue,stop:U,input:se,handleInputChange:ae,handleSubmit:ne=>{le(),me(ne)},isLoading:q,status:G,assistantType:"editor",onFocus:()=>{}})]}),Q&&i&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",Q.inputTokens," prompt tokens, ",Q.outputTokens," ","completion tokens, ",Q.totalTokens," total tokens"]})}),e.jsx(n.AddDataPicker,{incomingSelectedEntities:D,open:g,onOpenChange:p,dataSource:y||n.EMPTY_DATA_SOURCE,dialogMode:"aiContext",onSaveSelectedEntities:ne=>{C(!0),_({...A,selectedEntities:ne})}})]});return N&&r?qa.createPortal(e.jsx(n.SemaphorStyleWrapper,{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:fe})}),r):fe}function ba(s,a,r){if(!a)return!1;const o=a.qualifiedFieldName,u=a.qualifiedEntityName,i=u&&a.name?`${u}.${a.name}`:o;return s.some(l=>{if(!(t.getDataType(l.dataType||"")==="date"))return!1;const d=n.getSelectedDateFilterColumn(l,r),h=d.split("."),x=h[h.length-1]||d,g=h.length>1?h.slice(0,-1).join("."):void 0,p=l.qualifiedTableName||g,m=p?`${p}.${x}`:void 0;return o?m?m===i||m.endsWith(`.${o}`):x===a.name:m?m===i:x===a.name})}function ui({dashboard:s,dateGroupByField:a,dashboardInputValues:r,dashboardInputValuesAreAuthoritative:o,sheetId:u,card:i,timezone:l}){var x;if(!s||!a)return!1;const c=(x=s.inputs)==null?void 0:x.filter(g=>g.kind==="filter"&&!g.compatibility);if(!(c!=null&&c.length))return!1;const d={...s,inputs:c,filters:[],controls:[]};return n.resolveDashboardInputContext({dashboard:d,sheetId:u,card:i,sheetKind:"dashboard",runtimeValues:{dashboardInputValues:r,dashboardInputValuesAreAuthoritative:o},mode:"editor",timezone:l}).resolvedInputs.some(g=>g.kind!=="filter"||!g.filter||!g.filterValue?!1:ba([g.filter],a,[g.filterValue]))}function mi({aliasTemplate:s,onAliasTemplateChange:a}){var d;const[r,o]=v.useState(s),[u,i]=v.useState(!1),l=(d=t.useEditorStore(h=>{var x;return(x=h.card.config)==null?void 0:x.pivotByColumns}))==null?void 0:d[0],c=l?`e.g. Min Sales in {{${l.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Input,{placeholder:c,value:u?r:s,onChange:h=>{o(h.target.value),i(!0)},onFocus:()=>i(!0),onPointerDown:h=>h.stopPropagation(),className:"h-8 text-xs",onKeyDown:h=>{h.key==="Enter"&&u&&r!==s?(a(r),i(!1)):h.key==="Escape"&&(o(s),i(!1))},"aria-label":"Edit alias template"}),u&&r!==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(r),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:()=>{o(s),i(!1)},children:e.jsx(t.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function xi({valueAliases:s,onValueAliasesChange:a}){const[r,o]=v.useState(null),[u,i]=v.useState(""),[l,c]=v.useState(""),d=()=>{a({...s,"":""})},h=g=>{const p={...s};delete p[g],a(p)},x=g=>{const p={...s};delete p[g],p[u]=l,a(p),o(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(([g,p],m)=>e.jsx("div",{className:"flex items-center gap-2",children:r===g?e.jsxs(e.Fragment,{children:[e.jsx(t.Input,{placeholder:"Value key",value:u,onChange:f=>i(f.target.value),className:"h-8 w-24 text-xs",onPointerDown:f=>f.stopPropagation(),onKeyDown:f=>{f.key==="Enter"?x(g):f.key==="Escape"&&o(null)},"aria-label":"Edit value alias key"}),e.jsx(t.Input,{placeholder:"Alias label",value:l,onChange:f=>c(f.target.value),className:"h-8 w-24 text-xs",onPointerDown:f=>f.stopPropagation(),onKeyDown:f=>{f.key==="Enter"?x(g):f.key==="Escape"&&o(null)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>x(g),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:()=>o(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:g,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{o(g),i(g),c(p)},"aria-label":"Edit value alias key"}),e.jsx(t.Input,{placeholder:"Alias label",value:p,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{o(g),i(g),c(p)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>h(g),"aria-label":"Remove value alias",children:e.jsx(t.X,{className:"h-3 w-3"})})]})},g+m)),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:d,children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function hi({idx:s}){var c;const a=t.useEditorStore(d=>{var h;return(h=d.card)==null?void 0:h.preferences}),r=t.useEditorStore(d=>{var h;return(h=d.card.preferences)==null?void 0:h.datasetOptions}),o=t.useEditorStore(d=>d.actions.setCardPreferences),u=(c=a==null?void 0:a.chartOptions)==null?void 0:c.indexAxis,i=r==null?void 0:r.find(d=>d.idx===s);function l(d,h){(d==="end"||d==="start")&&t.getContrastColor(t.getCanvasBackgroundColor());const x={display:d!=="none",align:d,anchor:d,clamp:!0};if(!i)o({...a,datasetOptions:[...r||[],{idx:h,datalabels:x}]});else{const g={...i};g.datalabels=x;const p=r==null?void 0:r.map(m=>m.idx===h?g:m);o({...a,datasetOptions:p})}}return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{children:e.jsx(mr,{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(tr,{className:t.cn("h-4 w-4",{"rotate-90":u==="y"})})}),e.jsx("button",{onClick:()=>l("center",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(nr,{className:t.cn("h-4 w-4",{"rotate-90":u==="y"})})}),e.jsx("button",{onClick:()=>l("end",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(sr,{className:t.cn("h-4 w-4",{"rotate-90":u==="y"})})})]})})]})}function Rs({children:s,className:a,delayDuration:r}){return e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:r,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 pi(s,a=30){return s.length>a?s.slice(0,a)+"...":s}function fi({col:s,idx:a,className:r,iconClassName:o,children:u}){const i=t.useEditorStore(x=>{var g;return(g=x.card)==null?void 0:g.preferences}),l=t.useEditorStore(x=>{var g,p;return(p=(g=x.card)==null?void 0:g.preferences)==null?void 0:p.datasetOptions}),c=l==null?void 0:l.find(x=>x.idx===a),{setCardPreferences:d}=t.useEditorStore(x=>x.actions);function h(x){if(!c)d({...i,datasetOptions:[...l||[],{idx:a,type:x==="area"?"line":x,fill:x==="area"?"origin":""}]});else{const g={...c};g.type=x==="area"?"line":x,g.fill=x==="area"?"origin":"";const p=l==null?void 0:l.map(m=>m.idx===a?g:m);d({...i,datasetOptions:p})}}return e.jsxs("div",{className:t.cn("group flex items-center justify-between gap-2 rounded-md",r),children:[u||e.jsx(Rs,{className:"max-w-[100px]",title:s,children:pi(s)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(n.ChartColumnIncreasing,{onClick:()=>h("bar"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",o)}),e.jsx(n.ChartLine,{onClick:()=>h("line"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",o)}),e.jsx(n.ChartArea,{onClick:()=>h("area"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",o)}),e.jsx(hi,{idx:a})]})]})}function gi(){const s=t.useEditorStore(c=>c.card.type),a=t.useEditorStore(c=>c.isDevMode),r=t.useEditorStore(c=>c.card.preferences),{setCardPreferences:o}=t.useEditorStore(c=>c.actions);function u(c){var x;const d={datalabels:{display:c!=="none",align:c,anchor:c,clamp:!0}},h={...r,chartOptions:{...r==null?void 0:r.chartOptions,plugins:{...(x=r==null?void 0:r.chartOptions)==null?void 0:x.plugins,...d}}};o(h)}function i(){var c,d,h;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(t.Select,{value:((h=(d=(c=r==null?void 0:r.chartOptions)==null?void 0:c.plugins)==null?void 0:d.datalabels)==null?void 0:h.anchor)||"none",onValueChange:u,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Data Labels"}),e.jsx(t.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"start",children:"Start"}),e.jsx(t.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"end",children:"End"})]})})]})]})}function l(){var c,d,h;return e.jsx("div",{children:e.jsxs(t.Select,{value:((h=(d=(c=r==null?void 0:r.chartOptions)==null?void 0:c.plugins)==null?void 0:d.datalabels)==null?void 0:h.anchor)||"none",onValueChange:u,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 bi({column:s}){const a=t.useEditorStore(d=>d.card.type),r=t.useEditorStore(d=>{var h,x;return(x=(h=d.card)==null?void 0:h.config)==null?void 0:x.metricColumns}),o=(r==null?void 0:r.map(d=>d.label))||[],u=o==null?void 0:o.find(d=>d===s.label||d===s.name),i=u?o.indexOf(u):-1;function l(){return e.jsx("div",{className:"pr-1",children:u&&e.jsx(fi,{idx:i,col:u,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function c(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(gi,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&l(),["pie","doughnut"].includes(a)&&c()]})}function ji({field:s,searchQuery:a="",limit:r=500}){const{authToken:o,tokenProps:u}=n.useSemaphorContext(),i=t.useEditorStore(h=>h.card),l=i==null?void 0:i.dataSource,c=["attribute-values",s.entityName,s.name,a,r],d=n.useQuery({queryKey:c,queryFn:async()=>{if(!(l!=null&&l.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const h={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:r},x={connection_id:l.connectionId,cardConfig:h,cardDataSource:l,cache_config:t.getCacheConfig({card:i})};console.log("requestBody",x);const g=await t.postRequestRegular(`${u.apiServiceUrl}/v1/query`,(o==null?void 0:o.accessToken)||"",x);if(g!=null&&g.error)return console.error("Error fetching attribute values:",g.error),[];const p=s.name;return((g==null?void 0:g.records)||[]).map(f=>{const w=f[p]||f[s.alias||p]||f[s.label];return{id:w||"",value:w||"",label:String(w||"(empty)")}})}catch(h){return console.error("Error fetching attribute values:",h),[]}},enabled:!!s&&!!(l!=null&&l.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:d.data||[],isLoading:d.isLoading,isFetching:d.isFetching,isError:d.isError,error:d.error,refetch:d.refetch}}function ja({open:s,onOpenChange:a,availableFields:r,existingFilters:o,editingCondition:u,onSave:i}){var _,C;const l=!!u,[c,d]=v.useState(l?"values":"fields"),[h,x]=v.useState(""),[g,p]=v.useState({id:(u==null?void 0:u.id)||t.v4(),field:(u==null?void 0:u.field)||null,selectedValues:u?Array.isArray(u.value)?u.value:[u.value]:[]}),m=r.filter(S=>{var E;return l?!1:!((E=o==null?void 0:o.conditions)==null?void 0:E.some(D=>D.field.id===S.id))&&S.label.toLowerCase().includes(h.toLowerCase())}),f=S=>{p({...g,field:S}),d("values")},w=()=>{if(g.field&&g.selectedValues.length>0){const S={id:g.id,field:g.field,operator:"in",value:g.selectedValues};let I;if(l){const E=((o==null?void 0:o.conditions)||[]).map(D=>D.id===u.id?S:D);I={...o,conditions:E}}else{const E=(o==null?void 0:o.conditions)||[];I={id:(o==null?void 0:o.id)||t.v4(),logicalOperator:"AND",negate:!1,conditions:[...E,S],groups:[]}}i(I),a(!1)}},b=()=>{if(!l||!u)return;const S=((o==null?void 0:o.conditions)||[]).filter(I=>I.id!==u.id);if(S.length>0){const I={...o,conditions:S};i(I)}else i(void 0);a(!1)},N=S=>{p({...g,selectedValues:S})},A=()=>{l&&u?(p({id:u.id,field:u.field,selectedValues:Array.isArray(u.value)?u.value:[u.value]}),d("values")):(p({id:t.v4(),field:null,selectedValues:[]}),d("fields")),x("")};return v.useEffect(()=>{s&&A()},[s,l,u]),e.jsx(n.Dialog,{open:s,onOpenChange:a,children:e.jsxs(n.DialogContent,{className:"max-w-2xl",children:[e.jsx(n.DialogHeader,{children:e.jsx(n.DialogTitle,{children:l?`Edit Filter: ${(_=g.field)==null?void 0:_.label}`:c==="fields"?"Select Field to Filter":`Select Values for ${(C=g.field)==null?void 0:C.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!l&&(o==null?void 0:o.conditions)&&o.conditions.length>0&&c==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Current Filters:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:o.conditions.map(S=>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:[S.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(S.value)?`${S.value.length} values`:String(S.value)})]},S.id))})]}),c==="fields"&&!l?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex h-7 items-center gap-1.5 rounded-[5px] border border-border bg-background px-2 focus-within:border-ring",children:[e.jsx(n.Search,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx("input",{type:"text",placeholder:"Search fields",value:h,onChange:S=>x(S.target.value),className:"h-full w-full bg-transparent text-[12px] text-foreground placeholder:text-muted-foreground focus:outline-none"}),h&&e.jsx("button",{type:"button","aria-label":"Clear search",onClick:()=>x(""),className:"inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground hover:bg-muted hover:text-foreground",children:e.jsx(t.X,{className:"h-3 w-3"})})]}),e.jsx("div",{className:"grid max-h-[400px] grid-cols-2 gap-1 overflow-y-auto",children:m.map(S=>e.jsxs("button",{type:"button",onClick:()=>f(S),className:"group flex items-center gap-2 rounded-[5px] border border-border px-2 py-1.5 text-left transition-colors hover:bg-muted focus-visible:border-ring focus-visible:outline-none",children:[e.jsx(n.IconForFieldType,{dataType:t.getDataType(S.dataType)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-[13px] text-foreground",children:S.label}),e.jsxs("div",{className:"truncate font-mono text-[10px] text-muted-foreground",children:[S.entityName,".",S.name]})]})]},S.id))}),m.length===0&&h&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',h,'"']}),m.length===0&&!h&&r.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(vi,{field:g.field,selectedValues:g.selectedValues,onValuesChange:N,onBack:l?void 0:()=>d("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:l?e.jsx(t.Button,{variant:"destructive",onClick:b,children:"Delete Filter"}):e.jsx(t.Button,{variant:"outline",onClick:A,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:w,disabled:!g.field||g.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function vi({field:s,selectedValues:a,onValuesChange:r,onBack:o}){const[u,i]=v.useState(""),{values:l,isLoading:c,isFetching:d}=ji({field:s,searchQuery:u,limit:500}),h=u?l.filter(p=>String(p.value).toLowerCase().includes(u.toLowerCase())):l,x=p=>{const m=a.includes(p);r(m?a.filter(f=>f!==p):[...a,p])},g=()=>{a.length===h.length&&h.length>0?r([]):r(h.map(p=>p.value))};return e.jsxs("div",{className:"space-y-4",children:[o&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:o,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(n.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:u,onChange:p=>i(p.target.value),className:"pl-10"})]}),c||d?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(n.Checkbox,{checked:a.length===h.length&&h.length>0,onCheckedChange:g}),e.jsxs(t.Label,{className:"text-sm",children:["Select All (",h.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:h.map(p=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>x(p.value),children:[e.jsx(n.Checkbox,{checked:a.includes(p.value),onCheckedChange:()=>x(p.value)}),e.jsx(Rs,{className:"text-sm",children:p.label})]},p.id))})]})]})}function yi({value:s,onChange:a,showTitle:r=!0,title:o="NUMBER FORMAT"}){const u=t.toTFormatOptions(t.fromSemanticFormat(s))||{},i=l=>{a(t.fromTFormatOptions(l))};return e.jsx(kt,{formatOptions:u,onFormatOptionsChange:i,showTitle:r,title:o})}const Ni=[];function Ci({field:s,zone:a,index:r,sortDirection:o,onSortDirectionChange:u,hasPivotColumns:i=!1,cardType:l}){var Us,Gs,Hs,Qs,Ws,Ys,Js,Xs,Zs,en,tn,sn,nn,an,rn,on,ln,cn,dn,un,mn,xn,hn,pn,fn,gn,bn,jn,vn,yn,Nn,Cn,Sn,wn,Tn;const{attributes:c,listeners:d,setNodeRef:h,transform:x,transition:g,isDragging:p}=n.useSortable({id:s.id}),m=t.useEditorStore(K=>K.card),f=t.useEditorStore(K=>K.frame),w=t.useDashboardStore(K=>K.isVisualEditing),b=t.useDashboardStore(K=>K.selectedSheetId),N=t.useDashboardStore(K=>K.actions.updateSheetCalculatedFields),A=t.useDashboardStore(K=>K.actions.updateDashboardCalculatedFields),C=t.useDashboardStore(K=>{var J;return K.visualEditPendingDashboardCalculatedFields??((J=K.dashboard)==null?void 0:J.calculatedFields)})??Ni,{scopedFields:S,valuePickFilterableFields:I,isLoading:E}=n.useFilterableFields(),{userContext:D}=n.useCurrentUserInfo(),{tokenProps:T}=n.useSemaphorContext(),y=(D==null?void 0:D.type)==="organization",M=((Gs=(Us=T==null?void 0:T.params)==null?void 0:Us.calendarContext)==null?void 0:Gs.tz)||((Hs=T==null?void 0:T.params)==null?void 0:Hs.timezone)||Intl.DateTimeFormat().resolvedOptions().timeZone,{updateLabel:P,handleAggregationChange:F,handleDateFormatChange:j,handleGranularityChange:k,handleAliasTemplateChange:O,handleValueAliasesChange:R,handleMetricFormatChange:B,removeField:z,handleMetricComparisonChange:V,handleMetricWindowTransformChange:q,handleMetricWindowOrderByChange:U,handleMetricWindowDirectionChange:G,handleMetricWindowPartitionToggle:Q,handleMetricMovingAverageWindowSizeChange:Y,handleMetricMovingAverageMinPeriodsChange:H,handleMetricPreviousPeriodDeltaModeChange:se,handleMetricPercentOfTotalScopeChange:ue,handleMetricPercentOfTotalOutputChange:ae,handleKpiShowTrendlineChange:me,handleKpiTrendlineWindowChange:ve,handleKpiTrendlineGranularityChange:Oe,handleMetricTargetValueChange:Fe}=n.useFieldManagement(m),[X,ge]=v.useState(!1),[Ce,Pe]=v.useState(()=>{var K;return!!((K=s.parameters)!=null&&K.windowTransform)}),[_e,le]=v.useState(!1),[De,Se]=v.useState(!1),[ie,$]=v.useState(null),oe=v.useMemo(()=>{const K=de=>de!=null&&de.startsWith("card-source-")?de.replace("card-source-",""):de,J=K(s.id),he=S.find(de=>{if(s.qualifiedFieldName&&de.qualifiedFieldName&&de.qualifiedFieldName===s.qualifiedFieldName||s.qualifiedEntityName&&de.qualifiedEntityName&&de.qualifiedEntityName===s.qualifiedEntityName&&de.name===s.name)return!0;const we=K(de.id);return!!(J&&we&&J===we)});return{dataType:(he==null?void 0:he.dataType)||s.dataType,resolvedFromScopedField:!!he}},[s.dataType,s.id,s.name,s.qualifiedEntityName,s.qualifiedFieldName,S]),fe=n.getGranularityOptionsForFieldType(oe.dataType),[ne,ce]=v.useState(s.dateFormat||"YYYY-MM-DD"),[Te,ke]=v.useState(s.customFormat||""),[ze,re]=v.useState(!!s.customFormat),te=v.useRef(null),[xe,ye]=v.useState(s.aliasTemplate||""),[Ee,qe]=v.useState(s.valueAliases||{}),[Ie,Qe]=v.useState((Qs=s.parameters)==null?void 0:Qs.filters),Ue=K=>{K==="custom"?re(!0):(re(!1),ce(K),(a==="groupBy"||wt)&&j(r,K,"",a))},Ae=K=>{ke(K),(a==="groupBy"||wt)&&j(r,"custom",K,a)},tt=K=>{var de;const he=(de=n.getDateFormatOptionsForGranularity(K)[0])==null?void 0:de.value;he&&!ze&&(ce(he),a==="groupBy"&&j(r,he,"",a)),a==="groupBy"&&k(r,K)},Le=K=>{ye(K),a==="metrics"&&O(r,K)},Gt=K=>{qe(K),a==="metrics"&&R(r,K)},jt=K=>{P(a,r,K)},At=n.getExpressionFieldKind(s),lt=n.getFieldExpressionAnnotation(s),Lt=n.isManagedCalculatedExpressionField(s),vt=s.role==="metric"&&Lt,it=Lt&&(At==="user_calculated"||At==="inline_expression"&&s.fieldScope!=="domain"),Je=it?t.resolveLocalCalculatedFieldScope({field:s,sheetFields:(f==null?void 0:f.calculatedFields)||[],dashboardFields:C}):void 0,yt=it&&(Je==null?void 0:Je.scope)==="sheet",Ht=it&&(Je==null?void 0:Je.scope)==="dashboard",Nt=At==="domain_calculated"||s.fieldScope==="domain",Qt=Nt?n.resolveDomainCalculatedFieldForEdit(s,S):void 0,st=Nt?"domain":yt?"sheet":Ht?"dashboard":"card",mt=Nt?Qt||s:(yt||Ht)&&(Je!=null&&Je.matchedField)?Je.matchedField:s,Ct=K=>{var J;if(Qe(K),a==="metrics"){const he={...s,parameters:{...s.parameters,filters:K}},de=[...((J=m.config)==null?void 0:J.metricColumns)||[]];de[r]=he,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:de})}le(!1)},Mt=()=>{z(a,r)},xt={transform:n.CSS.Transform.toString(x),transition:g},os=t.getDataType(oe.dataType||s.dataType),St=os==="date",Wt=l==="kpi",wt=a==="detailColumns",Ft=(Ws=m.config)==null?void 0:Ws.metricColumns,nt=(Ys=m.config)==null?void 0:Ys.groupByColumns,Yt=t.useDashboardStore(K=>K.dashboard),Jt=t.useDashboardStore(K=>{var J;return(J=K.dashboard)==null?void 0:J.filters}),Rt=t.useDashboardStore(K=>K.filterValues),Xt=t.useDashboardStore(K=>K.dashboardInputValues),ht=t.useDashboardStore(K=>K.dashboardInputValuesAreAuthoritative),ct=s.granularity||"day",Ot=fe.includes(ct)?ct:"day",W=a==="groupBy"&&!fe.includes(ct),Z=n.getDateFormatOptionsForGranularity(Ot),ee=ze?"custom":Z.some(K=>K.value===ne)?ne:((Js=Z[0])==null?void 0:Js.value)??"YYYY-MM-DD";v.useEffect(()=>{var he;if(E||!W){te.current=null;return}const K=`${s.id}:${ct}:${oe.dataType||s.dataType||""}:${r}`;if(te.current===K)return;te.current=K;const J="day";if(k(r,J),!ze){const de=(he=n.getDateFormatOptionsForGranularity(J)[0])==null?void 0:he.value;de&&(ce(de),j(r,de,"",a))}},[s.dataType,s.id,j,k,W,r,ze,E,ct,oe.dataType,a]);const be=!!l&&t.COMPARISON_SUPPORTED_CHART_TYPES.includes(l),je=l==="kpi"||l==="table",pe=v.useMemo(()=>nt==null?void 0:nt.find(K=>t.getDataType(K.dataType||"")==="date"),[nt]),Ve=v.useMemo(()=>(nt||[]).some(K=>t.getDataType(K.dataType||"")==="date"),[nt]),He=v.useMemo(()=>{var de;if(!pe)return!1;const K=(de=m.config)==null?void 0:de.filters;if(!K)return!1;const J=we=>{const Be=we.field;return Be?pe.id&&Be.id===pe.id||pe.qualifiedFieldName&&Be.qualifiedFieldName===pe.qualifiedFieldName?!0:Be.name===pe.name:!1},he=we=>we.conditions.some(Ke=>t.getDataType(Ke.field.dataType||"")==="date"&&J(Ke))?!0:we.groups.some(Ke=>he(Ke));return he(K)},[(Xs=m.config)==null?void 0:Xs.filters,pe]),at=v.useMemo(()=>ba(Jt||[],pe,Rt)||ui({dashboard:Yt,dateGroupByField:pe,dashboardInputValues:Xt,dashboardInputValuesAreAuthoritative:ht,sheetId:b,card:m,timezone:M}),[m,Yt,Jt,Rt,Xt,ht,pe,b,M]),pt=He||at,Re=s,$e=((en=(Zs=Re.parameters)==null?void 0:Zs.windowTransform)==null?void 0:en.function)||"none",Ge=n.isMetricTransformEnabled(Re),Ye=Ge?$e:null,Pt=n.supportsMetricTransformForMetric({cardType:l||"table",cardConfig:m.config||{},metric:Re,transformMode:Ye||"running_total"}),Vt=!!Re.comparisonType&&Re.comparisonType!=="none",Vs=n.getRunningTotalOrderByCandidates(nt||[]),Tt=((nn=(sn=(tn=Re.parameters)==null?void 0:tn.windowTransform)==null?void 0:sn.orderBy)==null?void 0:nn.fieldId)||"",ya=((on=(rn=(an=Re.parameters)==null?void 0:an.windowTransform)==null?void 0:rn.orderBy)==null?void 0:on.direction)||"asc",Bs=Vs.find(K=>K.id===Tt),ls=Ye==="running_total"||Ye==="moving_average"||Ye==="previous_period_delta",Na=Ge&&ls&&!!Bs&&t.getDataType(Bs.dataType||"")!=="date",Ca=n.getDefaultRunningTotalPartitionByFieldIds({cardType:l||"table",cardConfig:m.config||{},orderByFieldId:Tt||void 0}),Sa=new Set(((cn=(ln=Re.parameters)==null?void 0:ln.windowTransform)==null?void 0:cn.partitionByFieldIds)||Ca),wa=l==="pivotTable"||n.isSubtotalEnabledAggregateTable(l||"table",m.config||{}),_s=[...(nt||[]).filter(K=>K.id&&(!ls||K.id!==Tt)),...wa?(((dn=m.config)==null?void 0:dn.pivotByColumns)||[]).filter(K=>K.id):[]],zs=((xn=(mn=(un=Re.parameters)==null?void 0:un.windowTransform)==null?void 0:mn.movingAverage)==null?void 0:xn.windowSize)||7,Ta=((fn=(pn=(hn=Re.parameters)==null?void 0:hn.windowTransform)==null?void 0:pn.movingAverage)==null?void 0:fn.minPeriods)||1,Ea=((jn=(bn=(gn=Re.parameters)==null?void 0:gn.windowTransform)==null?void 0:bn.previousPeriodDelta)==null?void 0:jn.mode)||"absolute",qs=((Nn=(yn=(vn=Re.parameters)==null?void 0:vn.windowTransform)==null?void 0:yn.percentOfTotal)==null?void 0:Nn.scope)||"grand_total",Ia=((wn=(Sn=(Cn=Re.parameters)==null?void 0:Cn.windowTransform)==null?void 0:Sn.percentOfTotal)==null?void 0:wn.output)||"percent",Da=v.useMemo(()=>(Ft||[]).some(K=>K.comparisonType==="start_vs_end"),[Ft]);v.useEffect(()=>{Ge&&Pe(!0)},[Ge]);const ka=a!=="pivotBy"&&a!=="sortBy",Aa=St&&a==="groupBy"&&(!Wt||Da),La=!Wt&&St&&(a==="groupBy"||wt),Ma=l==="kpi"&&St&&a==="groupBy",Fa=a==="metrics",$s=be&&a==="metrics",Ra=()=>{const K=s,J=a==="metrics"&&vt;return e.jsxs("div",{className:"space-y-1",children:[!J&&e.jsx("div",{title:`${s.entityName}.${s.name}`,onPointerDown:he=>{he.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-muted-foreground/80",children:`${s.entityName}.${s.name}`}),J&&K.calculatedFormula&&e.jsxs("div",{title:n.formatDisplayFormula(K.calculatedFormula),onPointerDown:he=>{he.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:["= ",n.formatDisplayFormula(K.calculatedFormula)]})]})},Oa=()=>ka?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(et,{value:s.label??"",onSave:jt,placeholder:"Display label...",type:"text"})]}):null,Pa=()=>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:o||"asc",onValueChange:K=>u(K),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"asc",children:"Ascending"}),e.jsx(t.SelectItem,{className:"text-xs",value:"desc",children:"Descending"})]})]})]}),Ks=()=>Aa?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(t.Select,{value:Ot,onValueChange:tt,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:fe.map(K=>e.jsx(t.SelectItem,{className:"text-xs",value:K,children:t.toTitleCase(K)},K))})]})]}):null,Va=()=>La?e.jsxs(e.Fragment,{children:[Ks(),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:ee,onValueChange:Ue,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:Z.map(K=>e.jsx(t.SelectItem,{className:"text-xs",value:K.value,children:K.label},K.value))})]}),ze&&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:Te,onChange:K=>{K.stopPropagation(),Ae(K.target.value)},onClick:K=>K.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}):null,Ba=()=>{var J,he,de,we;const K=Ma;return K?e.jsx(e.Fragment,{children:K&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(t.Switch,{size:"sm",checked:((J=m.config)==null?void 0:J.showTrendline)||!1,onCheckedChange:me})]})}),((he=m.config)==null?void 0:he.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:((de=m.config)==null?void 0:de.trendlineWindow)||30,onChange:Be=>{const Ke=parseInt(Be.target.value)||30;ve(Ke)},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:((we=m.config)==null?void 0:we.trendlineGranularity)||"day",onValueChange:Oe,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},_a=()=>{if(!Fa)return null;const K=vt;return e.jsxs(e.Fragment,{children:[K&&y&&!Nt&&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:()=>Se(!0),children:[e.jsx(n.Pencil,{className:"mr-2 h-3 w-3"}),"Edit Formula"]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(t.Select,{value:s.aggregate,onValueChange:J=>{F(r,J)},disabled:K,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select function..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(t.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),t.getDataType(s.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(t.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(t.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(t.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(t.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Number Format"}),e.jsx(yi,{value:Re.format,onChange:J=>B(r,J),showTitle:!1})]}),e.jsx(n.Collapsible,{open:Ce,onOpenChange:Pe,children:e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-muted/20 p-2.5",children:[e.jsx(n.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:[!Ce&&e.jsx("span",{className:"mr-2",children:Ge?t.toTitleCase($e.replace(/_/g," ")):"None"}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 transition-transform",Ce?"rotate-180":"")})]})]})}),e.jsxs(n.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:Ge?$e:"none",onValueChange:J=>q(r,J),disabled:!Pt.supported&&!Ge,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:Vt,children:"Running Total"}),e.jsx(t.SelectItem,{value:"moving_average",disabled:Vt,children:"Moving Average"}),e.jsx(t.SelectItem,{value:"previous_period_delta",disabled:Vt,children:"Previous Period Delta"}),e.jsx(t.SelectItem,{value:"percent_of_total",disabled:Vt,children:"Percent of Total"})]})]}),!Pt.supported&&!Ge&&e.jsx("div",{className:"text-xs text-muted-foreground",children:Pt.reason}),Vt&&!Ge&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"Disable comparison to enable metric transforms."})]}),Ge&&e.jsxs(e.Fragment,{children:[ls&&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:Tt,onValueChange:J=>U(r,J),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select order field..."})}),e.jsx(t.SelectContent,{children:Vs.filter(J=>!!J.id).map(J=>e.jsx(t.SelectItem,{value:J.id,className:"text-xs",children:J.label||J.name},J.id))})]}),!Tt&&e.jsx("div",{className:"text-xs text-amber-700",children:"No date trend detected. Select an order field."}),Na&&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:ya,onValueChange:J=>G(r,J),disabled:!Tt,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"})]})]})]})]}),Ye==="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:zs,onChange:J=>Y(r,Number(J.target.value))}),e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Min Periods"}),e.jsx(t.Input,{type:"number",min:1,max:zs,className:"h-8 text-xs",value:Ta,onChange:J=>H(r,Number(J.target.value))})]}),Ye==="previous_period_delta"&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Output"}),e.jsxs(t.Select,{value:Ea,onValueChange:J=>se(r,J),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select output..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"absolute",children:"Absolute Delta"}),e.jsx(t.SelectItem,{value:"percent",children:"Percent Delta"})]})]})]}),Ye==="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:qs,onValueChange:J=>ue(r,J),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select scope..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"grand_total",children:"Grand Total"}),e.jsx(t.SelectItem,{value:"partition_total",children:"Partition Total"})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Output"}),e.jsxs(t.Select,{value:Ia,onValueChange:J=>ae(r,J),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select output..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"percent",children:"Percent"}),e.jsx(t.SelectItem,{value:"fraction",children:"Fraction"})]})]})]})]}),(Ye==="running_total"||Ye==="moving_average"||Ye==="previous_period_delta"||Ye==="percent_of_total"&&qs==="partition_total")&&_s.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:_s.map(J=>{const he=!!J.id&&Sa.has(J.id);return e.jsxs("button",{type:"button",onClick:()=>J.id&&Q(r,J.id),className:t.cn("flex h-7 w-full items-center justify-between rounded border px-2 text-xs",he?"border-primary bg-primary/5 text-primary":"border-border text-muted-foreground"),children:[e.jsx("span",{children:J.label||J.name}),he?e.jsx(t.Check,{className:"h-3 w-3"}):null]},J.id)})})]})]})]})]})}),$s&&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:Re.comparisonType||"none",disabled:Ge,onValueChange:J=>V(r,J),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"none",children:"No Comparison"}),(()=>{const J=!Ve||!pt,he=Ve?pt?void 0:"Add a date filter to enable":"Add a date groupBy to enable",de=(we,Be)=>e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.SelectItem,{value:we,disabled:J,title:he,children:Be})}),J&&he&&e.jsx(t.TooltipContent,{side:"right",children:he})]})});return e.jsxs(e.Fragment,{children:[de("previous_period","Previous Period"),de("same_period_last_year","Same Period Last Year"),de("start_vs_end","Start vs End")]})})(),je&&e.jsx(t.SelectItem,{value:"target",children:"Target"})]})]})]}),$s&&Re.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:Re.targetValue!==void 0&&Re.targetValue!==null?String(Re.targetValue):"",onChange:J=>{const he=J.target.value;if(he===""){Fe(r,void 0);return}const de=Number(he);Fe(r,Number.isFinite(de)?de: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"}),(Ie==null?void 0:Ie.conditions)&&Ie.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:Ie.conditions.map(J=>e.jsxs("div",{className:"flex cursor-pointer items-center gap-2 rounded bg-muted/50 p-2 text-xs transition-colors hover:bg-muted/70",onClick:()=>{$(J),le(!0)},children:[e.jsxs("span",{className:"font-medium",children:[J.field.label,":"]}),e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"cursor-help text-muted-foreground",children:Array.isArray(J.value)?J.value.length===1?String(J.value[0]):J.value.length<=2?J.value.join(", "):`${J.value.slice(0,2).join(", ")} +${J.value.length-2}`:String(J.value)})}),Array.isArray(J.value)&&J.value.length>1&&e.jsx(t.TooltipContent,{side:"top",className:"max-w-[300px]",children:e.jsxs("div",{className:"text-xs",children:[e.jsxs("div",{className:"mb-1 font-medium",children:["Selected values (",J.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:J.value.map((he,de)=>e.jsx("div",{children:String(he)},de))})]})})]})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:he=>{var we;he.stopPropagation();const de=Ie.conditions.filter(Be=>Be.id!==J.id);if(de.length>0){const Be={...Ie,conditions:de};Ct(Be)}else if(Qe(void 0),a==="metrics"){const Be={...s,parameters:{...s.parameters,filters:void 0}},Ke=[...((we=m.config)==null?void 0:we.metricColumns)||[]];Ke[r]=Be,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:Ke})}},children:e.jsx(t.X,{className:"h-3 w-3"})})]},J.id))}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{$(null),le(!0)},children:[e.jsx(n.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(bi,{column:s}),i&&e.jsxs(e.Fragment,{children:[e.jsx(mi,{aliasTemplate:xe,onAliasTemplateChange:Le}),e.jsx(xi,{valueAliases:Ee,onValueAliasesChange:Gt})]})]})};Ie!=null&&Ie.conditions&&Ie.conditions.length>0;const za=a!=="sortBy";return e.jsxs(e.Fragment,{children:[e.jsxs(t.Popover,{open:X,onOpenChange:ge,children:[e.jsxs("div",{ref:h,style:xt,className:t.cn("group flex h-7 w-full items-center gap-1.5 rounded-control border bg-background px-1.5 transition-colors",X?"border-foreground/30 bg-muted/40":"border-border hover:bg-muted/40",p&&"z-50 scale-95 opacity-50"),children:[e.jsx("button",{type:"button",...c,...d,className:"inline-flex shrink-0 cursor-grab items-center text-muted-foreground transition-colors hover:text-foreground active:cursor-grabbing","aria-label":`Drag ${n.getMetricDisplayLabel(s)}`,onClick:K=>{K.stopPropagation()},children:e.jsx(n.GripVertical,{className:"h-3 w-3"})}),e.jsx(n.TypeGlyph,{dataType:os,calculated:!!lt}),e.jsx(Rs,{className:"block w-0 min-w-0 flex-1 text-[12px] text-foreground",children:n.getMetricDisplayLabel(s)}),a==="metrics"&&((Tn=Ie==null?void 0:Ie.conditions)==null?void 0:Tn.length)&&!X&&e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex shrink-0 items-center gap-1 rounded-[3px] bg-primary/10 px-1 text-[10px] tabular-nums text-primary/90",children:[e.jsx(n.Filter,{className:"h-2.5 w-2.5"}),e.jsx("span",{children:Ie.conditions.length})]})}),e.jsx(t.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:Ie.conditions.map(K=>e.jsxs("div",{children:[K.field.label,":"," ",Array.isArray(K.value)?`${K.value.length} values`:String(K.value)]},K.id))})})]})}),a==="sortBy"&&e.jsx("button",{type:"button","aria-label":o==="asc"?"Switch to descending":"Switch to ascending",className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",onClick:K=>{K.stopPropagation(),u(o==="asc"?"desc":"asc")},children:o==="asc"?e.jsx(n.ArrowUp,{className:"h-3 w-3"}):e.jsx(n.ArrowDown,{className:"h-3 w-3"})}),za&&e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":"Field configuration",className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground data-[state=open]:bg-muted data-[state=open]:text-foreground",onClick:K=>K.stopPropagation(),children:e.jsx(n.Ellipsis,{className:"h-3 w-3"})})}),e.jsx("button",{type:"button","aria-label":"Remove",className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground opacity-0 transition-opacity hover:bg-muted hover:text-foreground group-focus-within:opacity-100 group-hover:opacity-100 [@media(hover:none)]:opacity-100",onClick:K=>{K.stopPropagation(),Mt()},children:e.jsx(t.X,{className:"h-3 w-3"})})]}),e.jsx(t.PopoverContent,{align:"start",sideOffset:6,className:"w-[320px] p-0",children:e.jsxs("div",{className:"max-h-[480px] space-y-3 overflow-y-auto p-3",children:[Ra(),Pa(),Oa(),l==="kpi"&&Ks(),Va(),Ba(),_a()]})})]}),_e&&e.jsx(ja,{open:_e,onOpenChange:K=>{le(K),K||$(null)},availableFields:I,existingFilters:Ie,editingCondition:ie,onSave:K=>{var J;if(K)Ct(K);else if(Qe(void 0),a==="metrics"){const he={...s,parameters:{...s.parameters,filters:void 0}},de=[...((J=m.config)==null?void 0:J.metricColumns)||[]];de[r]=he,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:de})}$(null)}}),De&&a==="metrics"&&vt&&e.jsx(n.CalculatedFieldEditor,{open:De,onOpenChange:Se,availableFields:S,existingField:mt,existingFieldScope:st,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:K=>{var Et,rt;if(K.role!=="metric")return;const{card:J,frame:he,actions:de}=t.useEditorStore.getState(),we=((Et=J.config)==null?void 0:Et.metricColumns)||[],Be=((rt=J.config)==null?void 0:rt.sortByColumns)||[],Ke=st==="dashboard"?C:he.calculatedFields||[],{nextActiveFields:Xe,nextSortByFields:Ze,nextStoredFields:ot,nextSharedFields:dt}=n.saveCalculatedFieldToCardScope({activeFields:we,sortByFields:Be,storedFields:J.calculatedFields||[],sharedFields:Ke,updatedField:K,editingField:mt,previousScope:st});(Xe||Ze)&&de.updateCardConfig(m.id,{...Xe?{metricColumns:Xe}:{},...Ze?{sortByColumns:Ze}:{}}),de.updateCard(m.id,{calculatedFields:ot}),st==="dashboard"&&dt!==Ke?A(dt):dt!==Ke&&n.commitSharedCalculatedFields({nextSharedFields:dt,currentSharedFields:Ke,isVisualEditing:w,selectedSheetId:b,updateFrame:de.updateFrame,updateSheetCalculatedFields:N})},onSaveToSheet:K=>{var Bt,_t;if(K.role!=="metric")return;const{card:J,frame:he,actions:de}=t.useEditorStore.getState(),we=s,Be=((Bt=J.config)==null?void 0:Bt.metricColumns)||[],Ke=((_t=J.config)==null?void 0:_t.sortByColumns)||[],Xe=he.calculatedFields||[],{nextActiveFields:Ze,nextSortByFields:ot,nextStoredFields:dt,nextSheetFields:Et,nextDashboardFields:rt}=n.saveCalculatedFieldToSheetScope({activeFields:Be,sortByFields:Ke,storedFields:J.calculatedFields||[],sheetFields:Xe,dashboardFields:C,updatedField:{...K,id:we.id,aliasTemplate:we.aliasTemplate,valueAliases:we.valueAliases,parameters:we.parameters,customFormat:we.customFormat},editingField:mt,previousScope:st});n.commitSharedCalculatedFields({nextSharedFields:Et,currentSharedFields:Xe,isVisualEditing:w,selectedSheetId:b,updateFrame:de.updateFrame,updateSheetCalculatedFields:N}),rt&&rt!==C&&A(rt),(Ze||ot)&&de.updateCardConfig(m.id,{...Ze?{metricColumns:Ze}:{},...ot?{sortByColumns:ot}:{}}),de.updateCard(m.id,{calculatedFields:dt})},onSaveToDashboard:K=>{var Bt,_t;if(K.role!=="metric")return;const{card:J,frame:he,actions:de}=t.useEditorStore.getState(),we=s,Be=((Bt=J.config)==null?void 0:Bt.metricColumns)||[],Ke=((_t=J.config)==null?void 0:_t.sortByColumns)||[],Xe=he.calculatedFields||[],{nextActiveFields:Ze,nextSortByFields:ot,nextStoredFields:dt,nextSharedFields:Et,nextSheetFields:rt}=n.saveCalculatedFieldToSharedScope({activeFields:Be,sortByFields:Ke,storedFields:J.calculatedFields||[],sharedFields:C,sheetFields:Xe,updatedField:{...K,id:we.id,aliasTemplate:we.aliasTemplate,valueAliases:we.valueAliases,parameters:we.parameters,customFormat:we.customFormat},editingField:mt,previousScope:st});A(Et),rt&&rt!==Xe&&n.commitSharedCalculatedFields({nextSharedFields:rt,currentSharedFields:Xe,isVisualEditing:w,selectedSheetId:b,updateFrame:de.updateFrame,updateSheetCalculatedFields:N}),(Ze||ot)&&de.updateCardConfig(m.id,{...Ze?{metricColumns:Ze}:{},...ot?{sortByColumns:ot}:{}}),de.updateCard(m.id,{calculatedFields:dt})},cardId:m.id})]})}function Si({concept:s}){const{title:a,description:r}=wi[s];return e.jsxs(n.HoverCard,{openDelay:150,closeDelay:50,children:[e.jsx(n.HoverCardTrigger,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":`What does ${a} mean?`,className:"inline-flex h-3 w-3 shrink-0 items-center justify-center text-muted-foreground/70 transition-colors hover:text-foreground",children:e.jsx(n.CircleHelp,{className:"h-3 w-3"})})}),e.jsxs(n.HoverCardContent,{side:"right",align:"start",sideOffset:8,className:"w-[260px] space-y-2 rounded-control border border-border bg-popover p-3 shadow-[0_4px_16px_rgba(0,0,0,0.08)]",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-[12px] font-semibold text-foreground",children:a}),e.jsx("p",{className:"text-[11px] leading-[1.45] text-muted-foreground",children:r})]}),s!=="detailColumns"&&e.jsx(Ti,{highlight:s})]})]})}const wi={groupBy:{title:"Rows",description:"Each unique value becomes a row. Use for the dimensions you want stacked vertically."},pivotBy:{title:"Pivot Columns",description:"Each unique value spreads across as a column, splitting your metrics horizontally."},metrics:{title:"Metrics",description:"The aggregated numbers (sum, count, avg…) that fill the cells of your chart or table."},detailColumns:{title:"Columns",description:"Raw column values with no aggregation — the underlying detail rows from the database."}};function Ti({highlight:s}){const a=s==="pivotBy",r=s==="groupBy",o=s==="metrics",u="bg-foreground/[0.06] font-medium text-foreground dark:bg-foreground/[0.12]";return e.jsx("div",{className:"overflow-hidden rounded-control border border-border",children:e.jsxs("table",{className:"w-full text-[10px]",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border bg-muted/40",children:[e.jsx("th",{className:"px-1.5 py-1 text-left font-normal text-muted-foreground"}),["North","South","East"].map(i=>e.jsx("th",{className:t.cn("px-1.5 py-1 text-center font-normal text-muted-foreground",a&&u),children:i},i))]})}),e.jsx("tbody",{children:Un.map((i,l)=>e.jsxs("tr",{className:t.cn(l!==Un.length-1&&"border-b border-border/60"),children:[e.jsx("td",{className:t.cn("px-1.5 py-1 text-left text-muted-foreground",r&&u),children:i.label}),i.values.map((c,d)=>e.jsx("td",{className:t.cn("px-1.5 py-1 text-right font-mono tabular-nums text-muted-foreground",o&&u),children:c},d))]},i.label))})]})})}const Un=[{label:"Electronics",values:["2,300","1,800","3,400"]},{label:"Clothing",values:["1,300","620","480"]}],Ei={groupBy:Ne.Rows3,pivotBy:Is,metrics:ir,detailColumns:t.Table2,sortBy:Qn};function $t({zone:s,fields:a,label:r,placeholder:o,shouldShow:u,hasPivotColumns:i=!1,activeField:l=null}){const{isOver:c,setNodeRef:d}=n.useDroppable({id:s}),{updateSortByColumn:h}=t.useEditorActions(),x=t.useEditorStore(N=>N.card),g=t.useEditorStore(N=>N.card.type),p=a.length>0,m=v.useMemo(()=>!l||!c?!0:n.validateFieldForChartType(l,s,g).isValid,[l,c,s,g]),f=(N,A)=>{var C;!((C=x.config)!=null&&C.sortByColumns)||x.config.sortByColumns.findIndex(S=>S.id===N)===-1||h(x.id,N,{direction:A})};if(s==="sortBy"&&u===!1)return null;const w=s!=="sortBy"&&g!=="kpi",b=Ei[s]||n.Plus;return e.jsxs("div",{className:"w-full",children:[e.jsx(t.Label,{className:"mb-1 block text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:r}),e.jsx("div",{ref:d,className:t.cn("rounded-control transition-colors",{"border border-foreground/40 bg-muted/50":c&&m,"border border-destructive/40 bg-destructive/5":c&&!m,"border border-dashed border-border/50 bg-background":!c&&!p}),children:a.length===0?e.jsxs("div",{className:"flex h-9 items-center justify-center gap-1.5 text-[11px] text-muted-foreground/80",children:[e.jsx(b,{className:"h-3 w-3 shrink-0 text-muted-foreground/60"}),e.jsx("span",{children:o}),w&&e.jsx(Si,{concept:s})]}):e.jsx(n.SortableContext,{id:s,items:a.map(N=>N.id),strategy:n.verticalListSortingStrategy,children:e.jsx("div",{className:"space-y-1",children:a.map((N,A)=>{const C=N.direction;return e.jsx(Ci,{field:N,zone:s,index:A,sortDirection:C,onSortDirectionChange:S=>f(N.id,S),hasPivotColumns:i,cardType:g},N.id)})})})})]})}const Ii=[];function Di({groupByFields:s,pivotByFields:a,metricsFields:r,sortByFields:o,detailFields:u,activeField:i}){var G,Q,Y;const[l,c]=v.useState(!1);t.useEditorStore(H=>{var se;return!!((se=H.card.customCardPreferences)!=null&&se.url)});const d=t.useEditorStore(H=>H.card),h=t.useEditorStore(H=>H.frame),x=n.findCustomVisualConfigCard(h,d),{manifest:g}=n.useCustomVisual(((G=x==null?void 0:x.customCardPreferences)==null?void 0:G.url)||""),p=(Q=g==null?void 0:g.visuals)==null?void 0:Q.find(H=>{var se;return H.name===((se=x==null?void 0:x.customCardPreferences)==null?void 0:se.componentName)}),m=n.resolveMultiInputType(x,p)==="multiple";m&&((Y=x==null?void 0:x.customCardPreferences)!=null&&Y.url);const f=n.getConfigSlotExpectedType(p==null?void 0:p.slots),w=t.useEditorStore(H=>H.actions.updateCardConfig),b=t.useEditorStore(H=>H.actions.updateCard),N=t.useEditorStore(H=>H.actions.updateFrame),A=t.useDashboardStore(H=>H.isVisualEditing),_=t.useDashboardStore(H=>H.selectedSheetId),C=t.useDashboardStore(H=>H.actions.updateSheetCalculatedFields),S=t.useDashboardStore(H=>H.actions.updateDashboardCalculatedFields),E=t.useDashboardStore(H=>{var se;return H.visualEditPendingDashboardCalculatedFields??((se=H.dashboard)==null?void 0:se.calculatedFields)})??Ii,{scopedFields:D}=n.useScopedFields(),{userContext:T}=n.useCurrentUserInfo(),y=m&&(x==null?void 0:x.id)===d.id&&f?f:d==null?void 0:d.type,L=y==="detailTable",M=s.length>0||r.length>0||u.length>0,P=!L&&(y!=="kpi"||r.length<=2),F=!L,j=!L&&y!=="kpi",k=y!=="kpi"&&M,O=L,R="Drop sort fields here",B=(T==null?void 0:T.type)==="organization",z=["pie","doughnut","polar","funnel","aggregateTable","bubble","scatter"].includes(y),V=j&&!z,q=()=>y==="kpi"?{label:"Trend By",placeholder:"Drop trend field here"}:{label:"Rows",placeholder:"Drop dimensions here"},U=()=>y==="kpi"?{label:"Metric",placeholder:"Drop metric here"}:{label:"Metrics",placeholder:"Drop metrics here"};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between bg-background px-4 py-2",children:[e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-foreground/70",children:"Fields"}),M&&e.jsx("button",{type:"button","aria-label":"Reset all field selections",onClick:()=>{w(d.id,{groupByColumns:[],pivotByColumns:[],metricColumns:[],sortByColumns:[],detailColumns:[]})},className:"text-[11px] text-muted-foreground transition-colors hover:text-foreground",children:"Reset"})]}),e.jsxs("div",{className:"space-y-3 px-4 pb-6 pt-3",children:[P&&e.jsx($t,{zone:"groupBy",fields:s,label:q().label,placeholder:q().placeholder,activeField:i}),V&&e.jsx($t,{zone:"pivotBy",fields:a,label:"Pivot Columns",placeholder:"Drop pivot fields here",activeField:i}),F&&e.jsx($t,{zone:"metrics",fields:r,label:U().label,placeholder:U().placeholder,hasPivotColumns:a.length>0,activeField:i}),O&&e.jsx($t,{zone:"detailColumns",fields:u,label:"Columns",placeholder:"Drop columns here"}),r.length>=1&&B&&e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:()=>c(!0),className:"mt-1.5 w-full justify-start border-border/60 border-dashed bg-background text-xs text-foreground/70 hover:bg-muted/40 hover:text-foreground",children:[e.jsx(n.Calculator,{className:"mr-2 h-4 w-4"}),"Create Metric"]}),k&&e.jsx($t,{zone:"sortBy",fields:o,label:"Sort By",placeholder:R,activeField:i})]}),e.jsx(n.CalculatedFieldEditor,{open:l,onOpenChange:c,availableFields:D,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:H=>{if(H.role!=="metric")return;const{nextStoredFields:se}=n.saveCalculatedFieldToCardScope({activeFields:r,storedFields:d.calculatedFields||[],sharedFields:h.calculatedFields||[],updatedField:H,previousScope:"card"});b(d.id,{calculatedFields:se})},onSaveToSheet:H=>{if(H.role!=="metric")return;const se=h.calculatedFields||[],{nextSheetFields:ue}=n.saveCalculatedFieldToSheetScope({activeFields:r,storedFields:d.calculatedFields||[],sheetFields:se,updatedField:H,previousScope:"sheet"});n.commitSharedCalculatedFields({nextSharedFields:ue,currentSharedFields:se,isVisualEditing:A,selectedSheetId:_,updateFrame:N,updateSheetCalculatedFields:C})},onSaveToDashboard:H=>{if(H.role!=="metric")return;const{nextSharedFields:se}=n.saveCalculatedFieldToSharedScope({activeFields:r,storedFields:d.calculatedFields||[],sharedFields:E,updatedField:H,previousScope:"dashboard"});S(se)},cardId:d.id})]})}function ki(){var N,A,_;const a=t.useEditorStore(C=>{var S;return(S=C.card)==null?void 0:S.type})==="kpi",[r,o]=v.useState(a),[u,i]=v.useState(!1),l=t.useEditorStore(C=>{var S;return!!((S=C.card.customCardPreferences)!=null&&S.url)}),c=t.useEditorStore(C=>C.card),d=t.useEditorStore(C=>C.frame),h=n.findCustomVisualConfigCard(d,c),{manifest:x}=n.useCustomVisual(((N=h==null?void 0:h.customCardPreferences)==null?void 0:N.url)||""),g=(A=x==null?void 0:x.visuals)==null?void 0:A.find(C=>{var S;return C.name===((S=h==null?void 0:h.customCardPreferences)==null?void 0:S.componentName)}),m=n.resolveMultiInputType(h,g)==="multiple"&&!!((_=h==null?void 0:h.customCardPreferences)!=null&&_.url),f=!l||m,w=l||m,b=a?"KPI Settings":"Chart Settings";return v.useEffect(()=>{a&&o(!0)},[a]),!f&&!w?null:e.jsxs("div",{className:"shrink-0 border-t border-border bg-background",children:[f&&r&&e.jsx("div",{className:t.cn("overflow-y-auto border-b border-border px-4",a?"max-h-[72vh]":"max-h-[50vh]"),children:e.jsx(n.Accordion,{type:"single",collapsible:!0,className:"w-full divide-y divide-border/60 [&_h3]:sticky [&_h3]:top-0 [&_h3]:z-10 [&_h3]:bg-background",children:e.jsx(ga,{mode:"config"})})}),f&&e.jsxs("button",{type:"button",onClick:()=>o(C=>!C),className:"flex w-full items-center justify-between px-4 py-2.5 text-left transition-colors hover:bg-muted/50",children:[e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(n.Settings2,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-foreground/70",children:b})]}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 text-muted-foreground transition-transform",r&&"rotate-180"),strokeWidth:1.75})]}),w&&u&&e.jsx("div",{className:"max-h-[40vh] overflow-y-auto border-b border-t border-border px-4",children:e.jsx(xa,{})}),w&&e.jsxs("button",{type:"button",onClick:()=>i(C=>!C),className:t.cn("flex w-full items-center justify-between px-4 py-2.5 text-left transition-colors hover:bg-muted/50",f&&"border-t border-border"),children:[e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Wn,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-foreground/70",children:"Component settings"})]}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 text-muted-foreground transition-transform",u&&"rotate-180"),strokeWidth:1.75})]})]})}function Ai({onEditJoins:s}){const a=t.useEditorStore(d=>d.card),{autoJoinMetadata:r}=n.useEditorCardQuery(a);if(!(r!=null&&r.autoResolved))return null;const{resolvedJoinPlan:o}=r,u=(o==null?void 0:o.joins)||[];if(u.length===0)return null;const i=d=>!d||d.length===0?"No conditions":d.map(h=>{var m,f,w,b;const x=`${(m=h.source)==null?void 0:m.entityName}.${(f=h.source)==null?void 0:f.name}`,g=`${(w=h.target)==null?void 0:w.entityName}.${(b=h.target)==null?void 0:b.name}`,p=h.operator||"=";return`${x} ${p} ${g}`}).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((h,x)=>({id:x,operator:h.operator,condition:i(h.keys)})),c=e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"shrink-0 cursor-help rounded-control px-1 font-mono text-[10px] tabular-nums text-muted-foreground/70 transition-colors hover:bg-muted hover:text-foreground","aria-label":`${u.length} resolved ${u.length===1?"join":"joins"}`,children:u.length})}),e.jsx(t.TooltipContent,{side:"bottom",align:"start",className:"max-w-md border border-border bg-popover p-2 text-popover-foreground shadow-[0_4px_16px_rgba(0,0,0,0.08)]",children:e.jsx("div",{className:"space-y-2",children:u.map((d,h)=>{const x=l(d),g=Array.isArray(x);return e.jsxs("div",{className:"rounded-md border border-border bg-background p-2 text-foreground",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(n.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:d.target.name})]}),e.jsx("span",{className:"shrink-0 rounded-[3px] border border-border px-1 font-mono text-[10px] uppercase tracking-[0.06em] text-muted-foreground",children:d.joinType})]}),e.jsx("div",{className:"mt-1 space-y-1",children:g?x.map(p=>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:p.condition}),p.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",p.operator,")"]})]},p.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:x})})})]},d.id||h)})})})]})});return e.jsxs("div",{className:"flex h-7 w-full items-center gap-2 rounded-control border border-input bg-background px-2 text-left transition-colors hover:bg-muted",children:[e.jsx(n.Link,{className:"h-3 w-3 shrink-0 text-muted-foreground",strokeWidth:1.75}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-[13px] text-foreground",children:"Resolved joins"}),c,s&&e.jsx("button",{type:"button",onClick:s,className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-control text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus:outline-none focus-visible:border-ring","aria-label":"Edit resolved joins",children:e.jsx(n.SquarePen,{className:"h-3 w-3",strokeWidth:1.75})})]})}function Li({selectedChart:s,onChartChange:a,isVisible:r=!0,onToggleVisibility:o,groupByFields:u,pivotByFields:i,metricsFields:l,sortByFields:c,detailFields:d,activeField:h}){var E,D;const[x,g]=v.useState(!1),p=t.useEditorStore(T=>T.card),m=t.useEditorStore(T=>T.editorContext),f=t.useEditorStore(T=>T.actions.updateCardConfig),w=(m==null?void 0:m.type)==="documentSection",{autoJoinMetadata:b}=n.useEditorCardQuery(p),N=((E=p==null?void 0:p.config)==null?void 0:E.joinPlan)||(b!=null&&b.autoResolved?b.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),A=((D=p==null?void 0:p.dataSource)==null?void 0:D.selectedEntities)||[],_=T=>{f(p.id,{...p==null?void 0:p.config,joinPlan:T}),g(!1)},C=()=>{f(p.id,{...p==null?void 0:p.config,joinPlan:void 0}),g(!1)},S=()=>{g(!1)},I=()=>{g(!0)};return r?e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[325px] min-w-[325px] shrink-0 flex-col overflow-hidden border-r border-border bg-background transition-all duration-300 ease-in-out",children:[!w&&e.jsxs("div",{className:"flex items-start",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(uo,{selectedChart:s,onChartChange:a})}),o&&e.jsx("div",{className:"px-2 pt-4",children:e.jsx(n.IconButton,{tooltip:"Hide chart configuration","aria-label":"Hide chart configuration",onClick:o,className:"h-7 w-7 rounded-[5px] p-0 text-muted-foreground hover:text-foreground",children:e.jsx(n.ChevronLeft,{className:"h-4 w-4",strokeWidth:1.75})})})]}),e.jsxs(t.ScrollArea,{className:"min-h-0 w-full flex-1 basis-0 border-t border-border [&>[data-radix-scroll-area-viewport]]:overscroll-none [&>[data-radix-scroll-area-viewport]>div]:!block [&>[data-radix-scroll-area-viewport]>div]:w-full",children:[e.jsx("div",{className:"px-4 pt-4 empty:hidden",children:e.jsx(Ai,{onEditJoins:I})}),e.jsx(Di,{groupByFields:u,pivotByFields:i,metricsFields:l,sortByFields:c,detailFields:d,activeField:h})]}),e.jsx(ki,{}),e.jsx(ea,{open:x,onOpenChange:g,joinPlan:N,availableDataSources:A,onSave:_,onCancel:S,onRemove:C,children:e.jsx("div",{})})]}):e.jsx("div",{"data-content":"Chart Configuration Panel (collapsed)",className:"flex w-9 shrink-0 flex-col items-center border-r border-border bg-background transition-all duration-300 ease-in-out",children:o&&e.jsx(n.IconButton,{tooltip:"Show chart configuration","aria-label":"Show chart configuration",onClick:o,className:"mt-3 h-7 w-7 rounded-[5px] p-0 text-muted-foreground hover:text-foreground",children:e.jsx(n.ChevronRight,{className:"h-4 w-4",strokeWidth:1.75})})})}function Mi({initialFilters:s,availableFields:a}={}){const[r,o]=v.useState(s||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});t.useEditorStore(C=>C.card.dataSource);const{filterableFields:u,isLoading:i}=n.useFilterableFields(),l=a||u||[],c={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},d=C=>{const S=I=>{if(I.id===C){const E=l[0]||c,D=t.getDataType(E.dataType)==="date";return{...I,conditions:[...I.conditions,{id:`condition-${Date.now()}`,field:E,operator:D?"between":"=",value:D?[]:""}]}}return{...I,groups:I.groups.map(S)}};o(S(r))},h=C=>{const S=I=>{if(I.id===C){const E=l[0]||c,D=t.getDataType(E.dataType)==="date";return{...I,groups:[...I.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:E,operator:D?"between":"=",value:D?[]:""}],groups:[]}]}}return{...I,groups:I.groups.map(S)}};o(S(r))},x=(C,S)=>{const I=E=>E.id===C?{...E,conditions:E.conditions.filter(D=>D.id!==S)}:{...E,groups:E.groups.map(I)};o(I(r))},g=(C,S)=>{const I=E=>E.id===C?{...E,groups:E.groups.filter(D=>D.id!==S)}:{...E,groups:E.groups.map(I)};o(I(r))},p=(C,S,I,E)=>{if(I==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const D=T=>T.id===C?{...T,conditions:T.conditions.map(y=>y.id===S?{...y,[I]:E}:y)}:{...T,groups:T.groups.map(D)};o(D(r))},m=(C,S,I)=>{const E=D=>D.id===C?{...D,conditions:D.conditions.map(T=>T.id===S?{...T,...I}:T)}:{...D,groups:D.groups.map(E)};o(E(r))},f=(C,S)=>{const I=E=>E.id===C?{...E,logicalOperator:S}:{...E,groups:E.groups.map(I)};o(I(r))},w=(C,S)=>{const I=E=>E.id===C?{...E,negate:S}:{...E,groups:E.groups.map(I)};o(I(r))},b=(C,S,I)=>{const E=D=>D.id===C?{...D,conditions:n.arrayMove(D.conditions,S,I)}:{...D,groups:D.groups.map(E)};o(E(r))},N=(C,S,I)=>{const E=D=>D.id===C?{...D,groups:n.arrayMove(D.groups,S,I)}:{...D,groups:D.groups.map(E)};o(E(r))},A=C=>{if(!C||C.conditions.length===0&&C.groups.length===0)return"-- No filters defined";const S=E=>{let D="";typeof E.field=="object"?D=E.field.entityName?`${E.field.entityName}.${E.field.name}`:E.field.name:D=String(E.field);const T=E.operator;let y=E.value;if(E.field.dataType==="string"&&!["in","not in"].includes(E.operator))typeof y=="string"?y=`'${y}'`:Array.isArray(y)&&(y=`'${y.join(", ")}'`);else if(E.field.dataType==="date"||E.field.dataType==="datetime"||E.field.dataType==="timestamp")if(E.operator==="between"&&Array.isArray(y)&&y.length===2){const L=y[0]?`'${y[0]}'`:"NULL",M=y[1]?`'${y[1]}'`:"NULL";return`${D} BETWEEN ${L} AND ${M}`}else if((E.operator==="in"||E.operator==="not in")&&Array.isArray(y)){const L=y.map(M=>M?`'${M}'`:"NULL").join(", ");return`${D} ${T} (${L})`}else typeof y=="string"||y instanceof Date?y=`'${y}'`:Array.isArray(y)&&y.length>0&&(y=`'${y[0]}'`);else if(["in","not in"].includes(E.operator)){let L=[];Array.isArray(y)?L=y.map(M=>typeof M=="string"?`'${M}'`:String(M)):typeof y=="string"?L=y.split(",").map(M=>{const P=M.trim();return E.field.dataType==="string"?`'${P}'`:P}):typeof y=="number"&&(L=[String(y)]),y=`(${L.join(", ")})`}switch(T){case"contains":return typeof y=="string"?`${D} LIKE '%${y.replace(/'/g,"")}'`:`${D} LIKE '%${String(y)}'`;case"startsWith":return typeof y=="string"?`${D} LIKE '${y.replace(/'/g,"")}%'`:`${D} LIKE '${String(y)}%'`;case"endsWith":return typeof y=="string"?`${D} LIKE '%${y.replace(/'/g,"")}'`:`${D} LIKE '%${String(y)}'`;case"isNull":return`${D} IS NULL`;case"isNotNull":return`${D} IS NOT NULL`;default:return`${D} ${T} ${y}`}},I=E=>{const D=E.conditions.map(S),T=E.groups.map(P=>I(P)),y=[...D,...T].filter(Boolean);if(y.length===0)return"";const L=y.join(` ${E.logicalOperator} `),M=y.length>1?`(${L})`:L;return E.negate?`NOT ${M}`:M};return I(C)},_=r.conditions.length>0||r.groups.length>0;return{currentFilters:r,setCurrentFilters:o,availableFields:l,isLoading:i,addCondition:d,addGroup:h,removeCondition:x,removeGroup:g,updateCondition:p,updateConditionFields:m,updateGroupOperator:f,updateGroupNegate:w,reorderConditions:b,reorderGroups:N,generateSQLPreview:A,hasAnyFilters:_}}function Fi({children:s,className:a,delayDuration:r}){return e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:r,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 Ri=s=>{if(s.qualifiedEntityName){const a=s.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function Oi({value:s,onValueChange:a,availableFields:r,placeholder:o="Select field",className:u="w-64"}){const[i,l]=v.useState(!1),c=v.useMemo(()=>{const d={};return r.forEach(h=>{const x=Ri(h);d[x]||(d[x]={}),d[x][h.entityId]||(d[x][h.entityId]=[]),d[x][h.entityId].push(h)}),d},[r]);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",u),children:[s?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Fi,{children:[s.entityName,".",s.name]})}):o,e.jsx(Hn.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(n.Command,{children:[e.jsx(n.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(n.CommandEmpty,{children:"No fields found."}),e.jsx(n.CommandList,{className:"max-h-80",children:Object.entries(c).map(([d,h])=>e.jsx(n.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Database,{className:"h-3 w-3"}),d]}),children:Object.entries(h).map(([x,g])=>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:[n.getEntityIcon(g[0].entityType,{size:"h-3 w-3"}),e.jsx("span",{children:g[0].entityName})]}),g.map((p,m)=>e.jsxs(n.CommandItem,{value:p.id,onSelect:()=>{a(p),l(!1)},className:"overflow-x-auto",children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",(s==null?void 0:s.id)===p.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:p.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:p.description&&e.jsx("span",{children:p.description})})]})]},p.id+m))]},`${d}-${x}`))},d))})]})})]})}function Os(s){var w;const a=t.useEditorStore(b=>b.card),{authToken:r,tokenProps:o}=n.useSemaphorContext(),u=t.useEditorStore(b=>b.card.config),i=u==null?void 0:u.joinPlan,l={...s,alias:s.name,label:"value",role:"groupby"},c={...s,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},d={...l,role:"sortby",direction:"asc"},h={joinPlan:i,groupByColumns:[l],metricColumns:[c],sortByColumns:[d]},x=((w=a.dataSource)==null?void 0:w.connectionId)||a.connectionId,{data:g,isPending:p,error:m}=n.useQuery({queryKey:["filterValues",s.entityId,s.name,s.qualifiedEntityName],queryFn:async()=>{try{return await t.postRequestRegular(`${o.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",{connection_id:x,cardConfig:h,cardDataSource:a.dataSource})}catch(b){console.log(s),console.error("error",b)}},enabled:!!x,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((g==null?void 0:g.records)||[]).map(b=>({label:b.value||"BLANK",value:b.value||"BLANK",count:(b==null?void 0:b.count)||0})),isPending:p,error:m}}function Pi({field:s,selected:a,onChange:r,placeholder:o="Select items...",className:u}){const[i,l]=Ga.useState(!1),{filterValues:c}=Os(s),d=x=>{r(a.filter(g=>g!==x))},h=x=>{a.includes(x)?r(a.filter(g=>g!==x)):r([...a,x])};return e.jsx("div",{className:t.cn("w-full",u),children:e.jsxs(t.Popover,{open:i,onOpenChange:l,modal:!0,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(x=>{const g=c.find(p=>p.value===x);return e.jsxs(n.Badge,{variant:"secondary",className:"text-xs",children:[g==null?void 0:g.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:p=>{p.key==="Enter"&&d(x)},onMouseDown:p=>{p.preventDefault(),p.stopPropagation()},onClick:p=>{p.stopPropagation(),d(x)},children:e.jsx(t.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},x)}):e.jsx("span",{className:"text-muted-foreground",children:o})}),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(n.Command,{children:[e.jsx(n.CommandInput,{placeholder:"Search..."}),e.jsxs(n.CommandList,{children:[e.jsx(n.CommandEmpty,{children:"No results found."}),e.jsx(n.CommandGroup,{children:c.map((x,g)=>e.jsxs(n.CommandItem,{onSelect:()=>h(x.value),children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",a.includes(x.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:x.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:x.count})]})]},x.value+g))})]})]})})]})})}function Vi({field:s,value:a,onChange:r,placeholder:o="Select value...",className:u}){const{filterValues:i,isPending:l,error:c}=Os(s);return l?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(t.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):c?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(t.Select,{value:a,onValueChange:r,children:[e.jsx(t.SelectTrigger,{className:u||"flex-1",children:e.jsx(t.SelectValue,{placeholder:o,children:a})}),e.jsx(t.SelectContent,{children:i.map((d,h)=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+h))})]})}function Bi({value:s,operator:a,onChange:r,className:o}){var m,f,w;const{tokenProps:u}=n.useSemaphorContext(),i=((f=(m=u==null?void 0:u.params)==null?void 0:m.calendarContext)==null?void 0:f.tz)||((w=u==null?void 0:u.params)==null?void 0:w.timezone),l=i||Intl.DateTimeFormat().resolvedOptions().timeZone,c=a==="between"||a==="not between",d=v.useMemo(()=>{if(!(!s||!c)&&Array.isArray(s)&&s.length===2){const b=s[0]?new Date(s[0]):void 0,N=s[1]?new Date(s[1]):void 0;if(b&&N)return{from:b,to:N}}},[s,c]),h=v.useMemo(()=>{if(!s||c)return;const b=Array.isArray(s)?s[0]:s;if(!b)return;const N=new Date(b);if(!isNaN(N.getTime()))return N},[s,c]),x=b=>a==="<="||a===">"?t.endOfDayInTimezone(b,l):t.startOfDayInTimezone(b,l),g=b=>{if(!b){r([]);return}if(b.from&&b.to){r([b.from.toISOString(),b.to.toISOString()]);return}r([])},p=b=>{if(!b){r("");return}const N=x(b);r(N.toISOString())};return e.jsx(n.DateRangePicker,{value:c?d:void 0,selectionMode:c?"range":"single",singleValue:c?void 0:h,onChange:g,onSingleChange:p,timezone:i,showRelativeTab:c,className:o,placeholder:"Select date..."})}const Ps=["contains","startsWith","endsWith","like","not like"],_i=["=","!=",">",">=","<","<=",...Ps,"in","not in","isNull","isNotNull"],zi=["=","!=",...Ps,"in","not in","isNull","isNotNull"],qi=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],$i=["=","!=","isNull","isNotNull"],Ki=["between","=","!=","<","<=",">",">=","isNull","isNotNull"],Ui={"=":"Equals","!=":"Not Equals",">":"Greater Than",">=":"Greater Than or Equal","<":"Less Than","<=":"Less Than or Equal",contains:"Contains",startsWith:"Starts With",endsWith:"Ends With",like:"Like","not like":"Not Like",in:"In","not in":"Not In",between:"Between",isNull:"Is Null",isNotNull:"Is Not Null","not between":"Not Between"};function Gn(s){return Ui[s]||t.titleCase(s)}function Gi(s){switch(s){case"string":return zi;case"number":return qi;case"boolean":return $i;case"date":return Ki;default:return _i}}function va({condition:s,index:a,groupId:r,groupLogicalOperator:o,onUpdateCondition:u,onRemoveCondition:i,onUpdateGroupOperator:l,availableFields:c,updateConditionFields:d}){const{attributes:h,listeners:x,setNodeRef:g,transform:p,transition:m,isDragging:f}=n.useSortable({id:s.id}),{isPending:w,error:b}=Os(s.field),N={transform:n.CSS.Transform.toString(p),transition:m};return e.jsxs("div",{ref:g,style:N,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${f?"z-50 opacity-50":""}`,children:[e.jsx("div",{...h,...x,className:"cursor-grab active:cursor-grabbing",children:e.jsx(n.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(t.Select,{value:o,onValueChange:A=>l(r,A),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(Oi,{value:s.field,onValueChange:A=>{const _=A,C=t.getDataType(_.dataType)==="date";d(r,s.id,{field:_,value:"",operator:C?"between":"="})},availableFields:c,placeholder:"Select field",className:"w-64"}),e.jsxs(t.Select,{value:s.operator,onValueChange:A=>{A==="in"||A==="not in"?d(r,s.id,{operator:A,value:[]}):A==="isNull"||A==="isNotNull"?d(r,s.id,{operator:A,value:null}):A==="between"||A==="not between"?d(r,s.id,{operator:A,value:[]}):d(r,s.id,{operator:A,value:""})},children:[e.jsx(t.SelectTrigger,{className:"w-32",children:e.jsx(t.SelectValue,{children:s.operator?Gn(s.operator):""})}),e.jsx(t.SelectContent,{children:Gi(t.getDataType(s.field.dataType)).map(A=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:A,children:Gn(A)},A))})]}),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"?w?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(t.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):b?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(Pi,{field:s.field,selected:Array.isArray(s.value)&&s.value.every(A=>typeof A=="string")?s.value:[],onChange:A=>d(r,s.id,{value:A}),placeholder:`Select values for ${s.operator}...`,className:"flex-1"}):Ps.includes(s.operator)?e.jsx(t.Input,{value:typeof s.value=="string"?s.value:"",onChange:A=>d(r,s.id,{value:A.target.value}),className:"flex-1",placeholder:s.operator.charAt(0).toUpperCase()+s.operator.slice(1)+"..."}):e.jsx(Vi,{field:s.field,value:typeof s.value=="string"?s.value:"",onChange:A=>d(r,s.id,{value:A}),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:A=>d(r,s.id,{value:A==="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(Bi,{value:s.value,operator:s.operator,onChange:A=>d(r,s.id,{value:A}),className:"flex-1"}):e.jsx(t.Input,{value:typeof s.value=="string"||typeof s.value=="number"?s.value:"",onChange:A=>u(r,s.id,"value",A.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(r,s.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]})}function Hi({group:s,depth:a,parentGroupId:r,onUpdateGroupOperator:o,onUpdateGroupNegate:u,onRemoveGroup:i,onUpdateCondition:l,onUpdateField:c,onRemoveCondition:d,onReorderConditions:h,onReorderGroups:x,onAddCondition:g,onAddGroup:p,availableFields:m,renderFilterGroup:f,updateConditionFields:w}){const{attributes:b,listeners:N,setNodeRef:A,transform:_,transition:C,isDragging:S}=n.useSortable({id:s.id}),I={transform:n.CSS.Transform.toString(_),transition:C},E=T=>{const{active:y,over:L}=T;if(L&&y.id!==L.id){const M=s.conditions.findIndex(F=>F.id===y.id),P=s.conditions.findIndex(F=>F.id===L.id);M!==-1&&P!==-1&&h(s.id,M,P)}},D=T=>{const{active:y,over:L}=T;if(L&&y.id!==L.id&&r){const M=s.groups.findIndex(F=>F.id===y.id),P=s.groups.findIndex(F=>F.id===L.id);M!==-1&&P!==-1&&x(r,M,P)}};return e.jsxs("div",{ref:A,style:I,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${S?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...b,...N,className:"cursor-grab active:cursor-grabbing",children:e.jsx(n.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:()=>u(s.id,!s.negate),children:"NOT"}),e.jsxs(t.Select,{value:s.logicalOperator,onValueChange:T=>o(s.id,T),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:()=>r&&i(r,s.id),children:e.jsx(n.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>0?"":"px-0"}`,children:[e.jsx(n.DndContext,{sensors:n.useSensors(n.useSensor(n.PointerSensor),n.useSensor(n.KeyboardSensor,{coordinateGetter:n.sortableKeyboardCoordinates})),collisionDetection:n.closestCenter,onDragEnd:E,children:e.jsx(n.SortableContext,{items:s.conditions.map(T=>T.id),strategy:n.verticalListSortingStrategy,children:s.conditions.map((T,y)=>e.jsx(va,{condition:T,index:y,groupId:s.id,groupLogicalOperator:s.logicalOperator,onUpdateCondition:l,onUpdateField:c,onRemoveCondition:d,onUpdateGroupOperator:o,availableFields:m,updateConditionFields:w},T.id))})}),e.jsx(n.DndContext,{sensors:n.useSensors(n.useSensor(n.PointerSensor),n.useSensor(n.KeyboardSensor,{coordinateGetter:n.sortableKeyboardCoordinates})),collisionDetection:n.closestCenter,onDragEnd:D,children:e.jsx(n.SortableContext,{items:s.groups.map(T=>T.id),strategy:n.verticalListSortingStrategy,children:s.groups.map(T=>f(T,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:()=>g(s.id),children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>p(s.id),children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Qi({filters:s,availableFields:a,onSave:r,onClearAll:o,onCancel:u}){const{currentFilters:i,availableFields:l,isLoading:c,addCondition:d,addGroup:h,removeCondition:x,removeGroup:g,updateCondition:p,updateConditionFields:m,updateGroupOperator:f,updateGroupNegate:w,reorderConditions:b,reorderGroups:N,generateSQLPreview:A,hasAnyFilters:_,setCurrentFilters:C}=Mi({initialFilters:s,availableFields:a}),S=n.useSensors(n.useSensor(n.PointerSensor),n.useSensor(n.KeyboardSensor,{coordinateGetter:n.sortableKeyboardCoordinates})),[I,E]=v.useState(!1),D=(L,M,P)=>{const F=j=>j.id===L?{...j,conditions:j.conditions.map(k=>k.id===M?{...k,field:P,dataType:P.dataType}:k)}:{...j,groups:j.groups.map(F)};C(F(i))},T=(L,M=0,P)=>M===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(n.DndContext,{sensors:S,collisionDetection:n.closestCenter,onDragEnd:F=>{const{active:j,over:k}=F;if(k&&j.id!==k.id){const O=L.conditions.findIndex(B=>B.id===j.id),R=L.conditions.findIndex(B=>B.id===k.id);O!==-1&&R!==-1&&b(L.id,O,R)}},children:e.jsx(n.SortableContext,{items:L.conditions.map(F=>F.id),strategy:n.verticalListSortingStrategy,children:L.conditions.map((F,j)=>e.jsx(va,{condition:F,index:j,groupId:L.id,groupLogicalOperator:L.logicalOperator,onUpdateCondition:p,onUpdateField:D,onRemoveCondition:x,onUpdateGroupOperator:f,availableFields:l,updateConditionFields:m},F.id))})}),e.jsx(n.DndContext,{sensors:S,collisionDetection:n.closestCenter,onDragEnd:F=>{const{active:j,over:k}=F;if(k&&j.id!==k.id){const O=L.groups.findIndex(B=>B.id===j.id),R=L.groups.findIndex(B=>B.id===k.id);O!==-1&&R!==-1&&N(L.id,O,R)}},children:e.jsx(n.SortableContext,{items:L.groups.map(F=>F.id),strategy:n.verticalListSortingStrategy,children:L.groups.map(F=>T(F,M+1,L.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:()=>d(L.id),children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),I&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>h(L.id),children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},L.id):e.jsx(Hi,{group:L,depth:M,parentGroupId:P,onUpdateGroupOperator:f,onUpdateGroupNegate:w,onRemoveGroup:g,onUpdateCondition:p,onUpdateField:D,onRemoveCondition:x,onReorderConditions:b,onReorderGroups:N,onAddCondition:d,onAddGroup:h,availableFields:l,renderFilterGroup:T,updateConditionFields:m},L.id),y=n.getFilterCount(s);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(n.Card,{children:e.jsx(n.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[c?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):T(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:I,onCheckedChange:L=>E(L)}),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)"})]})}),_&&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:A(i)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(t.Button,{size:"sm",variant:"outline",onClick:u,children:"Cancel"}),y>0&&e.jsx(t.Button,{variant:"outline",size:"sm",onClick:o,children:"Clear All"}),e.jsx(t.Button,{size:"sm",onClick:()=>r(_?i:null),children:"Apply Filters"})]})]})}function Wi({cardId:s,filters:a,onFiltersChange:r,onClearFilters:o,availableFields:u,isOpen:i,onOpenChange:l}){const c=h=>{r(s,h),l(!1)},d=()=>{o(s),l(!1)};return e.jsxs(n.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(n.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:h=>{h.preventDefault()},children:[e.jsxs(n.DialogHeader,{children:[e.jsx(n.DialogTitle,{children:"Card Filters"}),e.jsx(n.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(Qi,{filters:a,availableFields:u,onSave:c,onCancel:()=>l(!1),onClearAll:d})]})]})}function Yi({activeCardId:s,sourceFields:a,getFieldsForContainer:r,setFieldsForContainer:o}){var A,_;const[u,i]=v.useState(null),l=t.useEditorStore(C=>C.card),c=t.useEditorStore(C=>C.actions.updateCardConfig),d=t.useEditorStore(C=>C.actions.setCardPreferences),h=(A=l==null?void 0:l.config)==null?void 0:A.joinPlan,x=v.useCallback(C=>C.entityName===Ka.CALCULATED_FIELD_ENTITY_MARKER||C.entityName==="calculated_fields"||C.qualifiedEntityName==="calculated_fields",[]),g=(_=l==null?void 0:l.dataSource)==null?void 0:_.semanticDomainId,{data:p}=n.useJoinabilityMap(g),m=[...a,...r("groupBy"),...r("pivotBy"),...r("metrics"),...r("sortBy"),...r("detailColumns")],f=v.useCallback(C=>C.startsWith("card-source-")?"source":C.startsWith("card-")?null:C.startsWith("source-")||a.find(S=>S.id===C)?"source":r("groupBy").find(S=>S.id===C)?"groupBy":r("metrics").find(S=>S.id===C)?"metrics":r("pivotBy").find(S=>S.id===C)?"pivotBy":r("sortBy").find(S=>S.id===C)?"sortBy":r("detailColumns").find(S=>S.id===C)?"detailColumns":null,[a,r]),w=v.useCallback(C=>{i(C.active.id)},[]),b=v.useCallback(C=>{var L;const{active:S,over:I}=C;if(!I||!s){i(null);return}const E=S.id,D=I.id,T=f(E),y=f(D)||D;if(y==="sortBy"){if(T==="source"){const M=a.find(F=>F.id===E);if(!M){i(null);return}if(!(r("groupBy").some(F=>F.name===M.name&&F.qualifiedEntityName===M.qualifiedEntityName)||r("metrics").some(F=>F.name===M.name&&F.qualifiedEntityName===M.qualifiedEntityName)||r("detailColumns").some(F=>F.name===M.name&&F.qualifiedEntityName===M.qualifiedEntityName))){i(null);return}}else if(T==="pivotBy"){i(null);return}else if(T!=="groupBy"&&T!=="metrics"&&T!=="sortBy"&&T!=="detailColumns"){i(null);return}}if(T==="source"&&y==="sortBy"){const M=[...a].find(k=>k.id===E);if(!M){i(null);return}const P=r("sortBy");if(n.fieldAlreadyExists(M,P)){i(null);return}const F=n.validateFieldForChartType(M,"sortBy",l.type);if(!F.isValid){n.ue.error("Invalid Field Type",{description:F.reason,position:"top-center",duration:3e3}),i(null);return}const j=n.getNewField(M,"sortBy",P);i(null),o("sortBy",[...P,j]);return}if(T==="source"&&y!=="source"&&y!=="sortBy"){const M=[...a].find(B=>B.id===E);if(!M){i(null);return}const P=[...r("groupBy"),...r("pivotBy"),...r("metrics"),...r("sortBy"),...r("detailColumns")],F=P.filter(B=>!x(B));if(F.length>0){const B=F[0].qualifiedEntityName;if(!B){i(null);return}if(B!==M.qualifiedEntityName&&!x(M)&&M.qualifiedEntityName)if(g&&(p!=null&&p.joinabilityMap)){if(n.calculateFieldState(M,{joinabilityMap:p.joinabilityMap,selectedFields:P,baseEntityName:(L=h==null?void 0:h.baseEntity)==null?void 0:L.name,datasetAliases:p.datasets}).state==="unreachable"){n.showJoinRequiredNotification(),i(null);return}}else{if(!h){n.showJoinRequiredNotification(),i(null);return}if(!n.areEntitiesJoined(B,M.qualifiedEntityName,h)){n.showJoinRequiredNotification(),i(null);return}}}const j=r(y);if(n.fieldAlreadyExists(M,j)){i(null);return}const k=n.validateFieldForChartType(M,y,l.type);if(!k.isValid){n.ue.error("Invalid Field Type",{description:k.reason,position:"top-center",duration:3e3}),i(null);return}const O=n.getNewField(M,y,j),R=[...j,O];if(i(null),o(y,R),y==="metrics"&&s){const B=n.seedSemanticMetricFormatDefaults(l,O,l.preferences);B&&d(B),n.cleanupKpiMetricComparisonMode(l.type,l.config,c,s,R)}return}if(T&&y&&T!=="source"&&y!=="source"&&T!==y){const M=r(T),P=r(y),F=M.find(B=>B.id===E);if(!F){i(null);return}const j=n.validateFieldForChartType(F,y,l.type);if(!j.isValid){n.ue.error("Invalid Field Type",{description:j.reason,position:"top-center",duration:3e3}),i(null);return}const k=n.getNewField(F,y,P);if(i(null),y==="sortBy"){n.fieldAlreadyExists(F,P)||o(y,[...P,k]);return}const O=M.filter(B=>B.id!==E),R=[...P,k];if(o(T,O),o(y,R),y==="metrics"&&s){const B=n.seedSemanticMetricFormatDefaults(l,k,l.preferences);B&&d(B),n.cleanupKpiMetricComparisonMode(l.type,l.config,c,s,R)}return}if(T&&y&&T===y&&T!=="source"){const M=r(T),P=M.findIndex(j=>j.id===E),F=M.findIndex(j=>j.id===D);if(P!==F){const j=n.arrayMove(M,P,F);o(T,j)}}i(null)},[s,a,r,o,f,h,g,p,x,l,c,d]),N=u?m.find(C=>C.id===u):null;return{activeId:u,activeField:N,handleDragStart:w,handleDragEnd:b}}function Ji({activeView:s,onViewChange:a,splitViewEnabled:r}){const o=t.useEditorStore(d=>d.card),{config:u}=v.useContext(n.SemaphorContext).tokenProps,i=(u==null?void 0:u.showInfoTab)!==!1,l=()=>r?!1:t.getVisualizationMode(o)==="dynamic"?!0:!["table","pivotTable","aggregateTable","detailTable"].includes(o.type),c=[{id:"chart",label:"Chart"}];return l()&&c.push({id:"table",label:"Results"}),i&&c.push({id:"info",label:"Info",icon:t.Info}),e.jsx(t.Tabs,{value:s,onValueChange:d=>a(d),children:e.jsx(t.TabsList,{variant:"underline",className:"gap-5 border-b-0",children:c.map(d=>{const h=d.icon;return e.jsxs(t.TabsTrigger,{value:d.id,className:"gap-1.5 px-0 text-[13px]",children:[h&&e.jsx(h,{className:"h-3 w-3",strokeWidth:1.75}),d.label]},d.id)})})})}const Xi=[{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 Zi(){var d,h;const s=t.useEditorStore(x=>x.card),{updateRowLimit:a}=t.useEditorActions(),[r,o]=v.useState(!1),[u,i]=v.useState(""),l=x=>{if(x==="custom"){o(!0);return}o(!1),a(s.id,parseInt(x))},c=x=>{const g=x.target.value;i(g),g&&!isNaN(parseInt(g))&&a(s.id,parseInt(g))};return e.jsx("div",{className:"flex items-center gap-2",children:r?e.jsx(t.Input,{type:"number",value:u,onChange:c,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(t.Select,{value:((h=(d=s.config)==null?void 0:d.rowLimit)==null?void 0:h.toString())||"100",onValueChange:l,children:[e.jsxs(t.SelectTrigger,{className:"mb-0.5 h-auto w-auto gap-1.5 border-none bg-transparent px-0.5 pb-2.5 pt-0 text-[13px] font-normal text-muted-foreground shadow-none transition-colors hover:text-foreground focus:ring-0 focus:ring-offset-0 [&>svg]:hidden",children:[e.jsx(n.Filter,{className:"h-3 w-3",strokeWidth:1.75}),e.jsx(t.SelectValue,{placeholder:"Select limit"})]}),e.jsx(t.SelectContent,{children:Xi.map(x=>e.jsx(t.SelectItem,{value:x.value,children:x.label},x.value))})]})})}function ec({card:s,queryData:a,isLoading:r,isFetching:o,pagination:u,onPaginationChange:i,onSortChange:l,sortState:c,splitViewEnabled:d,isDynamicInspectorOpen:h,onDynamicInspectorOpenChange:x}){const g=v.useMemo(()=>(a==null?void 0:a.records)||[],[a==null?void 0:a.records]),p=t.getVisualizationMode(s)==="dynamic",m=e.jsx(gt,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(da,{fallbackPreview:e.jsx(gt,{}),records:g,title:s.title,isInspectorOpen:h,onInspectorOpenChange:x})});return p?d?e.jsxs(n.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(n.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:m}),e.jsx(n.ResizableHandle,{withHandle:!0}),e.jsx(n.ResizablePanel,{defaultSize:40,minSize:20,role:"results-section",className:"flex flex-col",children:e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 px-4 py-4",children:[(r||o)&&(a==null?void 0:a.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),(a==null?void 0:a.records)&&e.jsx(n.TableVisual,{card:s,data:g,totalsByColumnId:a==null?void 0:a.tableTotalsByColumnId,paginationMetadata:u,onPaginationChange:i,isLoading:r||o,onSortChange:l,sortState:c})]})})]}):m:!d||["table","pivotTable","aggregateTable","detailTable"].includes(s.type)?e.jsx(gt,{}):e.jsxs(n.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(n.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:e.jsx(gt,{})}),e.jsx(n.ResizableHandle,{withHandle:!0}),e.jsx(n.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:[(r||o)&&(a==null?void 0:a.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),(a==null?void 0:a.records)&&e.jsx(n.TableVisual,{card:s,data:g,totalsByColumnId:a==null?void 0:a.tableTotalsByColumnId,paginationMetadata:u,onPaginationChange:i,isLoading:r||o,onSortChange:l,sortState:c})]})})]})}function tc(s,a){const[r,o]=v.useState(()=>{const u=localStorage.getItem(s);return u?JSON.parse(u):a});return v.useEffect(()=>{localStorage.setItem(s,JSON.stringify(r))},[r,s]),[r,o]}const sc="semaphor-split-view-enabled";function nc(){return tc(sc,!0)}function ac({card:s,effectiveCardType:a=s.type,queryResultColumns:r}){return["table","detailTable","aggregateTable","pivotTable"].includes(a)?e.jsxs(n.Sheet,{modal:!1,children:[e.jsx(n.SheetTrigger,{asChild:!0,children:e.jsxs(n.IconButton,{tooltip:"Table settings",className:"h-7 w-auto gap-1.5 rounded-[5px] px-2 text-[12px] font-medium",buttonProps:{type:"button","aria-label":"Table settings"},children:[e.jsx(n.Settings2,{className:"h-3.5 w-3.5",strokeWidth:1.75}),e.jsx("span",{children:"Table Settings"})]})}),e.jsxs(n.SheetContent,{side:"right",hideOverlay:!0,className:"flex w-[420px] flex-col gap-0 p-0 sm:max-w-[420px]",children:[e.jsx(n.SheetTitle,{className:"sr-only",children:"Table settings"}),e.jsx(n.SheetDescription,{className:"sr-only",children:"Configure table presentation and conditional formatting."}),e.jsxs("div",{className:"border-b px-4 py-3",children:[e.jsx("div",{className:"text-[13px] font-semibold text-foreground",children:"Table settings"}),e.jsx("div",{className:"mt-0.5 text-[11px] text-muted-foreground",children:"Settings apply to this table and document exports that reuse it."})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-auto",children:e.jsx(fa,{cardType:a,queryResultColumns:r,focusSection:"style"})})]})]}):null}function rc({className:s,visible:a}){const r=t.useDashboardStore(c=>c.selectedFrameId),o=n.useManagementStore(c=>c.selectedVisual),u=t.useEditorStore(c=>c.frame),l=!!!(u!=null&&u.visualId||o!=null&&o.id)&&!!r;return!a||l?null:e.jsx("div",{className:t.cn("flex",s),children:e.jsx(Ne.VisualBadge,{showLabel:!0,className:"h-6 w-fit px-2 py-0.5 text-[11px]"})})}function oc({activeView:s,onViewChange:a,onFiltersClick:r,activeCard:o,columns:u}){var Ce,Pe,_e;const i=t.useEditorStore(le=>le.card),l=t.useEditorStore(le=>le.editorContext),c=t.useEditorStore(le=>le.inlineFilterValuesMap[(o==null?void 0:o.id)||""]),d=t.useEditorStore(le=>le.actions.removeCardInlineFilterValue),h=t.useDashboardStore(le=>le.filterValues),x=t.useDashboardStore(le=>le.selectedSheetId),{updateCardConfig:g,setCard:p,updateCardInFrame:m,setShowAIDialog:f}=t.useEditorActions(),w=t.useEditorStore(le=>le.showAIDialog),b=t.useEditorStore(le=>le.isDevMode),N=t.useDashboardStore(le=>le.isVisualEditing),[A,_]=v.useState(!1),[C,S]=v.useState(!1),[I,E]=v.useState(!1),[D,T]=v.useState(null),{config:y}=v.useContext(n.SemaphorContext).tokenProps,L=(y==null?void 0:y.showInfoTab)!==!1,M=(y==null?void 0:y.showQueryDebugTools)!==!1,[P,F]=nc();t.useEditorStore(le=>{var De;return!!((De=le.card.customCardPreferences)!=null&&De.url)});const k=t.getVisualizationMode(i)==="dynamic",O=(l==null?void 0:l.type)==="documentSection",R=Ne.useEffectiveEditorCardType(),{data:B,errorMessage:z,isLoading:V,isFetching:q,errorSql:U,pagination:G,refetch:Q,comparisonMetadata:Y,queryRequestPayload:H,resolvedPrimaryDateField:se}=n.useEditorCardQuery(o),ue=v.useMemo(()=>(B==null?void 0:B.records)||[],[B==null?void 0:B.records]),ae=v.useMemo(()=>!q&&ue.length>0?Object.keys(ue[0]):[],[q,ue]),[me,ve]=v.useState(!1);v.useEffect(()=>{q||ve(!1)},[q]);const Oe=()=>{const le=!P;le&&s==="table"&&a("chart"),F(le)},Fe=(le,De)=>{const Se={...o,paginationConfig:{page:le+1,pageSize:De}};p(Se),m(Se)},X=le=>{if(!i.config)return;const De=n.sortStateToSortByColumns(le,i.config.metricColumns,i.config.groupByColumns,i.config.detailColumns);g(i.id,{...i.config,sortByColumns:De})},ge=v.useMemo(()=>{var le;return n.sortByColumnsToSortState((le=i.config)==null?void 0:le.sortByColumns)},[(Ce=i.config)==null?void 0:Ce.sortByColumns]);return e.jsx("div",{className:t.cn("relative flex w-0 grow flex-col",{"border-l":w&&N}),children:e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col",children:[e.jsxs("div",{className:"flex h-11 items-center gap-3 border-b border-border px-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[s==="chart"&&w&&!O&&!k&&e.jsx("div",{className:"w-[200px]",children:e.jsx(co,{variant:b?"secondary":"ghost"})}),e.jsxs("div",{className:"flex h-11 items-end gap-5 self-stretch",children:[e.jsx(Ji,{activeView:s,onViewChange:a,splitViewEnabled:P}),e.jsx(Zi,{})]}),R==="kpi"&&e.jsx(rc,{visible:!0,className:"self-center"}),Y&&i.type!=="table"&&e.jsx(n.ComparisonMetadataBadge,{metadata:Y,variant:"compact"}),w&&e.jsx(Ne.EditorClearButton,{})]}),e.jsxs("div",{className:"flex grow items-center justify-end gap-1",children:[e.jsx(n.FilterInfo,{cardId:o.id,cardFilters:(Pe=o.config)==null?void 0:Pe.filters,cardFilterCount:n.getFilterCount(((_e=o.config)==null?void 0:_e.filters)||null),onFiltersClick:r,inlineFilters:o.inlineFilters,inlineFilterValues:c,sheetId:x||"",removeInlineFilterValue:le=>d(o.id,le),resolvedPrimaryDateField:se}),e.jsx(n.IconButton,{tooltip:"Refresh",className:"h-7 w-7 rounded-[5px] p-0",disabled:V||q,onClick:()=>{ve(!0),Q()},children:e.jsx(Jn,{className:t.cn("h-3.5 w-3.5",{"animate-spin":me})})}),s==="chart"&&e.jsx(ac,{card:o,effectiveCardType:R,queryResultColumns:ae}),s==="chart"&&!k&&e.jsx(ca,{showInlineFilters:!1,showControls:!1,showDisplayOptions:!1}),s==="chart"&&e.jsxs(n.DropdownMenu,{modal:!1,children:[e.jsx(n.DropdownMenuTrigger,{asChild:!0,children:e.jsx(n.IconButton,{tooltip:"More Options",className:"h-7 w-7 rounded-[5px] p-0","aria-label":"More options",children:e.jsx(n.EllipsisVertical,{className:"h-3.5 w-3.5"})})}),e.jsxs(n.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(n.DropdownMenuLabel,{children:"More Options"}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuItem,{onClick:Oe,children:[P?e.jsx(Ja,{className:"mr-2 h-4 w-4"}):e.jsx(ur,{className:"mr-2 h-4 w-4"}),P?"Hide Results Table":"Show Results Table"]}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs("div",{className:"px-1 py-1",children:[e.jsx(Ls,{triggerVariant:"menu",className:"w-full"}),e.jsx(Ms,{triggerVariant:"menu",className:"w-full"}),e.jsx(As,{triggerVariant:"menu",className:"w-full"})]}),e.jsx(ua,{onCustomize:()=>E(!0)})]})]})]})]}),e.jsxs("div",{className:"flex min-h-0 grow flex-col",children:[s==="chart"&&e.jsx("div",{className:"flex grow flex-col",children:e.jsx(ec,{card:o,queryData:B,isLoading:V,isFetching:q,pagination:G,onPaginationChange:Fe,onSortChange:X,sortState:ge,splitViewEnabled:P,isDynamicInspectorOpen:I,onDynamicInspectorOpenChange:E})}),s==="table"&&(B==null?void 0:B.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 px-4 py-4",children:[(V||q)&&(B==null?void 0:B.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),e.jsx(n.TableVisual,{card:o,data:ue,totalsByColumnId:B==null?void 0:B.tableTotalsByColumnId,comparisonMetadata:Y,paginationMetadata:G,onPaginationChange:Fe,isLoading:V||q,onSortChange:X,sortState:ge})]}),s==="info"&&L&&e.jsx("div",{className:"flex min-h-0 flex-1 flex-col pb-2",children:e.jsx("div",{className:"flex min-h-0 flex-1 flex-col rounded-md bg-background px-4",children:z?e.jsx(ns,{error:z,errorSql:U,onSendFeedback:()=>{const le=n.prepareFeedbackData(n.FeedbackCategory.QUERY_GENERATION,{cardConfig:i.config,dataSource:o.dataSource,dashboardFilters:h,errorMessage:z,errorSql:U,generatedSql:B==null?void 0:B.sql});T(le),S(!0)},onOpenInEditor:()=>{f(!0),setTimeout(()=>{const le=t.useEditorStore.getState().actions;le.setIsDevMode(!0),le.setCardSql(U||""),setTimeout(()=>{le.setRunSql(!0)},100)},100)}}):(B==null?void 0:B.sql)&&e.jsx(ma,{sql:B.sql,showCardDetails:!0,debugPayloads:M?{queryRequest:H,queryResponse:B,columns:u,dashboardFilters:h}:void 0})})})]}),D&&e.jsx(n.FeedbackDialog,{open:C,onOpenChange:S,feedbackData:D})]})})}function lc({activeField:s}){const[a,r]=v.useState(!0);if(v.useEffect(()=>{s&&r(!0)},[s]),!s)return null;const o=!!n.getFieldExpressionAnnotation(s);return e.jsxs("div",{className:`flex h-7 max-w-[300px] items-center gap-2 rounded-[5px] border border-border bg-popover px-3 text-[13px] text-foreground/90 shadow-[0_4px_12px_rgba(0,0,0,0.08)] transition-all duration-150 ${a?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(n.TypeGlyph,{dataType:s.dataType,calculated:o}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap",children:s.label||s.name})]})}const ic=()=>{const s=console.error;console.error=(...o)=>{o.length>0&&typeof o[0]=="string"&&o[0].includes("ResizeObserver loop completed with undelivered notifications")||s.apply(console,o)};const a=o=>{if(o.message&&(o.message.includes("ResizeObserver loop completed with undelivered notifications")||o.message.includes("ResizeObserver loop limit exceeded")))return o.preventDefault(),o.stopPropagation(),!1},r=o=>{var u;if((u=o.reason)!=null&&u.message&&(o.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||o.reason.message.includes("ResizeObserver loop limit exceeded")))return o.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",r,!0),()=>{console.error=s,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",r,!0)}};function cc({column:s,isSelected:a,onSelect:r,availableFields:o,width:u,onWidthChange:i}){var B,z,V;const l=t.useEditorStore(q=>q.card),{updateCardConfig:c,removeGroupByColumn:d,removeMetricColumn:h,updateFilters:x}=t.useEditorActions(),[g,p]=v.useState(!1),[m,f]=v.useState(!1),w=v.useRef(null),b=v.useCallback(q=>{q.preventDefault(),q.stopPropagation(),f(!0),w.current={startX:q.clientX,startWidth:u||150};const U=Q=>{if(!w.current)return;const Y=Q.clientX-w.current.startX,H=Math.max(80,w.current.startWidth+Y);i==null||i(s.id,H)},G=()=>{f(!1),w.current=null,document.removeEventListener("mousemove",U),document.removeEventListener("mouseup",G)};document.addEventListener("mousemove",U),document.addEventListener("mouseup",G)},[u,s.id,i]),N=(B=l==null?void 0:l.config)==null?void 0:B.filters,A=(z=N==null?void 0:N.conditions)==null?void 0:z.some(q=>q.field.name===s.name&&q.field.qualifiedEntityName===s.qualifiedEntityName),_=q=>{q?x(l.id,q):c(l.id,{filters:void 0})},{attributes:C,listeners:S,setNodeRef:I,transform:E,transition:D,isDragging:T}=n.useSortable({id:s.id}),y={transform:n.CSS.Transform.toString(E),transition:D},L=t.getDataType(s.dataType),M=dc(L),P=()=>{var G;const q=((G=l==null?void 0:l.config)==null?void 0:G.sortByColumns)||[],U=q.findIndex(Q=>Q.name===s.name);if(U!==-1){const Q=[...q];Q[U]={...Q[U],direction:"asc"},c(l.id,{sortByColumns:Q})}else c(l.id,{sortByColumns:[...q,{...s,id:`sort-${s.id}`,role:"sortby",direction:"asc"}]})},F=()=>{var G;const q=((G=l==null?void 0:l.config)==null?void 0:G.sortByColumns)||[],U=q.findIndex(Q=>Q.name===s.name);if(U!==-1){const Q=[...q];Q[U]={...Q[U],direction:"desc"},c(l.id,{sortByColumns:Q})}else c(l.id,{sortByColumns:[...q,{...s,id:`sort-${s.id}`,role:"sortby",direction:"desc"}]})},j=()=>{var G;const q=((G=l==null?void 0:l.config)==null?void 0:G.groupByColumns)||[];if(!q.some(Q=>Q.name===s.name)){const Q={...s,id:`groupby-${s.id}-${Date.now()}`,role:"groupby"};c(l.id,{groupByColumns:[...q,Q]})}},k=q=>{var Q;const U=((Q=l==null?void 0:l.config)==null?void 0:Q.metricColumns)||[];if(!U.some(Y=>Y.name===s.name&&Y.aggregate===q)){const Y={...s,id:`metric-${s.id}-${q}-${Date.now()}`,label:`${q} of ${s.label||s.name}`,role:"metric",aggregate:q};c(l.id,{metricColumns:[...U,Y]})}},O=()=>{s.role==="groupby"?d(l.id,s.id):s.role==="metric"&&h(l.id,s.id)},R={...y,width:u?`${u}px`:void 0,minWidth:u?`${u}px`:"120px"};return e.jsxs("th",{ref:I,style:R,className:t.cn("group relative border-r border-border bg-background px-1 py-0",T&&"opacity-50",a&&"bg-primary/10",m&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...C,...S,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(n.GripVertical,{className:"h-3 w-3"})}),e.jsxs(n.DropdownMenu,{children:[e.jsx(n.DropdownMenuTrigger,{asChild:!0,children:e.jsxs("button",{onClick:r,className:t.cn("flex flex-1 items-center justify-between gap-1 rounded px-2 py-2 text-left text-sm font-medium transition-colors hover:bg-muted/50",a&&"bg-primary/10"),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(M,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:s.label||s.name}),s.role==="metric"&&s.aggregate&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",s.aggregate,")"]}),A&&e.jsx(n.Filter,{className:"h-3 w-3 text-primary"})]}),e.jsx(t.ChevronDown,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsxs(n.DropdownMenuContent,{align:"start",className:"w-48",children:[e.jsxs(n.DropdownMenuItem,{onClick:()=>p(!0),children:[e.jsx(n.Filter,{className:t.cn("mr-2 h-4 w-4",A&&"text-primary")}),A?"Edit Filter":"Filter"]}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuItem,{onClick:P,children:[e.jsx(Qa,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(n.DropdownMenuItem,{onClick:F,children:[e.jsx(Ha,{className:"mr-2 h-4 w-4"}),"Sort Z → A"]}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuSub,{children:[e.jsxs(n.DropdownMenuSubTrigger,{children:[e.jsx(n.Calculator,{className:"mr-2 h-4 w-4"}),"Summarize"]}),e.jsxs(n.DropdownMenuSubContent,{children:[e.jsx(n.DropdownMenuItem,{onClick:()=>k("SUM"),children:"Sum"}),e.jsx(n.DropdownMenuItem,{onClick:()=>k("AVG"),children:"Average"}),e.jsx(n.DropdownMenuItem,{onClick:()=>k("COUNT"),children:"Count"}),e.jsx(n.DropdownMenuItem,{onClick:()=>k("DISTINCT"),children:"Count Distinct"}),e.jsx(n.DropdownMenuItem,{onClick:()=>k("MIN"),children:"Min"}),e.jsx(n.DropdownMenuItem,{onClick:()=>k("MAX"),children:"Max"})]})]}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuItem,{onClick:j,children:[e.jsx(Ne.Rows3,{className:"mr-2 h-4 w-4"}),"Group by this column"]}),e.jsxs(n.DropdownMenuItem,{disabled:!0,children:[e.jsx(Is,{className:"mr-2 h-4 w-4"}),"Pivot by this column"]}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuItem,{disabled:!0,children:[e.jsx(n.EyeOff,{className:"mr-2 h-4 w-4"}),"Hide column"]}),e.jsxs(n.DropdownMenuItem,{onClick:O,className:"text-destructive focus:text-destructive",children:[e.jsx(n.Trash2,{className:"mr-2 h-4 w-4"}),"Remove column"]})]})]})]}),e.jsx("div",{onMouseDown:b,className:t.cn("absolute right-0 top-0 h-full w-1 cursor-col-resize bg-transparent hover:bg-primary/50",m&&"bg-primary")}),e.jsx(ja,{open:g,onOpenChange:p,availableFields:o.length>0?o:[s],existingFilters:N,editingCondition:A?(V=N==null?void 0:N.conditions)==null?void 0:V.find(q=>q.field.name===s.name&&q.field.qualifiedEntityName===s.qualifiedEntityName):void 0,onSave:_})]})}function dc(s){switch(s){case"number":return n.Hash;case"date":return n.Calendar;case"string":default:return t.Type}}function uc({selectedColumn:s,onColumnSelect:a,isLoading:r=!1,sourceFields:o=[],filterableFields:u=o}){var T,y,L,M;const i=t.useEditorStore(P=>P.card),{updateCardConfig:l}=t.useEditorActions(),[c,d]=v.useState(null),[h,x]=v.useState({}),[g,p]=v.useState(!1),m=v.useMemo(()=>{var j,k;const P=((j=i==null?void 0:i.config)==null?void 0:j.groupByColumns)||[],F=((k=i==null?void 0:i.config)==null?void 0:k.metricColumns)||[];return[...P,...F]},[(T=i==null?void 0:i.config)==null?void 0:T.groupByColumns,(y=i==null?void 0:i.config)==null?void 0:y.metricColumns]),f=v.useMemo(()=>{const P=new Set(m.map(F=>`${F.qualifiedEntityName}.${F.name}`));return o.filter(F=>!P.has(`${F.qualifiedEntityName}.${F.name}`))},[o,m]),{data:w,isLoading:b}=n.useEditorCardQuery(i),N=(w==null?void 0:w.records)||[],A=v.useCallback((P,F)=>{x(j=>({...j,[P]:F}))},[]),_=v.useCallback(P=>{var O,R;const F=t.getDataType(P.dataType),j=((O=i==null?void 0:i.config)==null?void 0:O.groupByColumns)||[],k=((R=i==null?void 0:i.config)==null?void 0:R.metricColumns)||[];if(F==="number"){const B={...P,id:`metric-${P.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};l(i.id,{metricColumns:[...k,B]})}else{const B={...P,id:`groupby-${P.id}-${Date.now()}`,role:"groupby"};l(i.id,{groupByColumns:[...j,B]})}p(!1)},[(L=i==null?void 0:i.config)==null?void 0:L.groupByColumns,(M=i==null?void 0:i.config)==null?void 0:M.metricColumns,i.id,l]),C=n.useSensors(n.useSensor(n.PointerSensor,{activationConstraint:{distance:8}})),S=P=>{d(P.active.id)},I=P=>{const{active:F,over:j}=P;if(d(null),!j||F.id===j.id)return;const k=m.findIndex(R=>R.id===F.id),O=m.findIndex(R=>R.id===j.id);if(k!==-1&&O!==-1){const R=n.arrayMove(m,k,O),B=R.filter(V=>V.role==="groupby"),z=R.filter(V=>V.role==="metric");l(i.id,{groupByColumns:B,metricColumns:z})}},E=c?m.find(P=>P.id===c):null,D=P=>{let F="";for(;P>=0;)F=String.fromCharCode(P%26+65)+F,P=Math.floor(P/26)-1;return F};return r?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(n.DndContext,{sensors:C,collisionDetection:n.closestCenter,onDragStart:S,onDragEnd:I,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(n.SortableContext,{items:m.map(P=>P.id),strategy:n.horizontalListSortingStrategy,children:m.map((P,F)=>e.jsx("th",{style:{width:h[P.id]?`${h[P.id]}px`:void 0,minWidth:h[P.id]?`${h[P.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-${P.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(n.SortableContext,{items:m.map(P=>P.id),strategy:n.horizontalListSortingStrategy,children:m.map(P=>e.jsx(cc,{column:P,isSelected:(s==null?void 0:s.id)===P.id,onSelect:()=>a(P),availableFields:u,width:h[P.id],onWidthChange:A},P.id))}),e.jsx("th",{className:"w-10 border-r border-border bg-background px-1 py-2",children:e.jsxs(t.Popover,{open:g,onOpenChange:p,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Add column",children:e.jsx(n.Plus,{className:"h-4 w-4"})})}),e.jsx(t.PopoverContent,{className:"w-[280px] p-0",align:"start",children:e.jsxs(n.Command,{children:[e.jsx(n.CommandInput,{placeholder:"Search columns..."}),e.jsxs(n.CommandList,{children:[e.jsx(n.CommandEmpty,{children:"No columns available."}),e.jsx(n.CommandGroup,{heading:"Available Columns",children:f.map(P=>{const F=t.getDataType(P.dataType),j=F==="number"?n.Hash:F==="date"?n.Calendar:t.Type;return e.jsxs(n.CommandItem,{value:P.label||P.name,onSelect:()=>_(P),children:[e.jsx(j,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm",children:P.label||P.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:P.entityName})]})]},P.id)})})]})]})})]})})]})]}),e.jsx("tbody",{children:b?e.jsx("tr",{children:e.jsx("td",{colSpan:m.length+2,className:"h-32 text-center",children:e.jsx(t.LoaderCircle,{className:"mx-auto h-6 w-6 animate-spin text-muted-foreground"})})}):N.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"})}):N.slice(0,100).map((P,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(j=>{const k=P[j.name]??P[j.label??""];return e.jsx("td",{style:{width:h[j.id]?`${h[j.id]}px`:void 0,minWidth:h[j.id]?`${h[j.id]}px`:"120px"},className:t.cn("border-r border-border px-3 py-2 text-sm",(s==null?void 0:s.id)===j.id&&"bg-primary/5"),children:e.jsx("span",{className:"block truncate",children:mc(k,j)})},`${F}-${j.id}`)}),e.jsx("td",{className:"w-10 border-r border-border"})]},F))})]}),e.jsx(n.DragOverlay,{children:E&&e.jsx("div",{className:"rounded border border-primary bg-background px-3 py-2 text-sm font-medium shadow-lg",children:E.label||E.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(N.length,100)," of ",N.length," rows"]}),e.jsxs("span",{children:[m.length," columns"]})]})]})}function mc(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 r=new Date(s);if(!isNaN(r.getTime()))return r.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}return String(s)}function xc({entityGroups:s,isLoading:a=!1}){var _,C;const r=t.useEditorStore(S=>S.card),{updateCardConfig:o,removeGroupByColumn:u,removeMetricColumn:i}=t.useEditorActions(),[l,c]=v.useState(!0),[d,h]=v.useState(""),[x,g]=v.useState(new Set),p=((_=r==null?void 0:r.config)==null?void 0:_.groupByColumns)||[],m=((C=r==null?void 0:r.config)==null?void 0:C.metricColumns)||[],f=S=>{const I=new Set(x);I.has(S)?I.delete(S):I.add(S),g(I)},w=S=>p.some(I=>I.name===S.name&&I.qualifiedEntityName===S.qualifiedEntityName)||m.some(I=>I.name===S.name&&I.qualifiedEntityName===S.qualifiedEntityName),b=(S,I)=>{if(I)if(t.getDataType(S.dataType)==="number"){const D={...S,id:`metric-${S.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};o(r.id,{metricColumns:[...m,D]})}else{const D={...S,id:`groupby-${S.id}-${Date.now()}`,role:"groupby"};o(r.id,{groupByColumns:[...p,D]})}else{const E=p.findIndex(T=>T.name===S.name&&T.qualifiedEntityName===S.qualifiedEntityName),D=m.findIndex(T=>T.name===S.name&&T.qualifiedEntityName===S.qualifiedEntityName);E!==-1&&u(r.id,p[E].id),D!==-1&&i(r.id,m[D].id)}},N=S=>{if(!d)return S;const I=d.toLowerCase();return S.filter(E=>E.name.toLowerCase().includes(I)||E.label&&E.label.toLowerCase().includes(I))},A=S=>{switch(t.getDataType(S)){case"number":return n.Hash;case"date":return n.Calendar;default:return t.Type}};return l?e.jsxs("div",{className:"flex h-full w-72 flex-col border-l border-border bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border px-3 py-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Columns"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:()=>c(!1),title:"Close panel",children:e.jsx(rr,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"border-b border-border p-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(n.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:d,onChange:S=>h(S.target.value),className:"h-8 pl-8 text-sm"})]})}),(p.length>0||m.length>0)&&e.jsxs("div",{className:"border-b border-border",children:[p.length>0&&e.jsxs(n.Collapsible,{defaultOpen:!0,children:[e.jsxs(n.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(n.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(Ne.Rows3,{className:"h-3.5 w-3.5 text-blue-500"}),e.jsx("span",{children:"Groupings"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:p.length})]}),e.jsx(n.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:p.map(S=>{const I=A(S.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(n.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(I,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:S.label||S.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:()=>u(r.id,S.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]},S.id)})})})]}),m.length>0&&e.jsxs(n.Collapsible,{defaultOpen:!0,children:[e.jsxs(n.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(n.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(n.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(n.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:m.map(S=>{const I=A(S.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(n.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(I,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:S.label||S.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:S.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(r.id,S.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]},S.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(S=>{const I=N(S.columns);if(I.length===0)return null;const E=x.has(S.entityId)||d.length>0;return e.jsxs(n.Collapsible,{open:E,onOpenChange:()=>f(S.entityId),children:[e.jsxs(n.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(n.ChevronRight,{className:t.cn("h-3.5 w-3.5 transition-transform duration-200",E&&"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:S.label||S.entityName}),e.jsx("span",{className:"text-xs text-muted-foreground",children:I.length})]}),e.jsx(n.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:I.map(D=>{const T=A(D.dataType),y=w(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",y&&"bg-primary/5"),children:[e.jsx(n.Checkbox,{checked:y,onCheckedChange:L=>b(D,L),className:"h-3.5 w-3.5"}),e.jsx(T,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:D.label||D.name})]},D.id)})})})]},S.entityId)})})})]}):e.jsx("div",{className:"flex h-full items-start border-l border-border bg-muted/30 p-2",children:e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>c(!0),title:"Open panel",children:e.jsx(or,{className:"h-4 w-4"})})})}const hc=[{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 pc({value:s,onChange:a,onSubmit:r,onCancel:o,selectedColumn:u,availableColumns:i}){const[l,c]=v.useState(!1),[d,h]=v.useState("column"),x=v.useRef(null);v.useEffect(()=>{const f=w=>{w.key==="Escape"&&s?o():w.key==="Enter"&&s&&!l&&r(s)};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[s,o,r,l]);const g=f=>{const w=`[${f.label||f.name}]`,b=x.current;if(b){const N=b.selectionStart||0,A=b.selectionEnd||0,_=s.slice(0,N)+w+s.slice(A);a(_),setTimeout(()=>{b.setSelectionRange(N+w.length,N+w.length),b.focus()},0)}else a(s+w);c(!1)},p=f=>{const w=x.current;if(w){const b=w.selectionStart||0,N=w.selectionEnd||0,A=s.slice(0,b)+f.syntax+s.slice(N);a(A),setTimeout(()=>{w.setSelectionRange(b+f.name.length+1,b+f.syntax.length-1),w.focus()},0)}else a(s+f.syntax);c(!1)},m=f=>{switch(t.getDataType(f)){case"number":return n.Hash;case"date":return n.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:u?e.jsx("span",{className:"truncate",children:u.label||u.name}):e.jsx("span",{children:"—"})}),e.jsxs(t.Popover,{open:l&&d==="function",onOpenChange:f=>{c(f),f&&h("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(dr,{className:"h-4 w-4"})})}),e.jsx(t.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(n.Command,{children:[e.jsx(n.CommandInput,{placeholder:"Search functions..."}),e.jsxs(n.CommandList,{children:[e.jsx(n.CommandEmpty,{children:"No functions found."}),e.jsx(n.CommandGroup,{heading:"Functions",children:hc.map(f=>e.jsx(n.CommandItem,{value:f.name,onSelect:()=>p(f),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:f.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:f.description})]}),e.jsx("span",{className:"font-mono text-xs text-muted-foreground/75",children:f.syntax})]})},f.name))})]})]})})]}),e.jsxs(t.Popover,{open:l&&d==="column",onOpenChange:f=>{c(f),f&&h("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(n.Command,{children:[e.jsx(n.CommandInput,{placeholder:"Search columns..."}),e.jsxs(n.CommandList,{children:[e.jsx(n.CommandEmpty,{children:"No columns found."}),e.jsx(n.CommandGroup,{heading:"Available Columns",children:i.map(f=>{const w=m(f.dataType);return e.jsxs(n.CommandItem,{value:f.label||f.name,onSelect:()=>g(f),children:[e.jsx(w,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:f.label||f.name})]},f.id)})})]})]})})]}),e.jsx("div",{className:"relative flex-1",children:e.jsx(t.Input,{ref:x,value:s,onChange:f=>a(f.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:o,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:()=>r(s),title:"Apply (Enter)",children:e.jsx(t.Check,{className:"h-4 w-4"})})]})]})}function fc({className:s}){var m,f,w,b;const a=t.useEditorStore(N=>N.card),[r,o]=v.useState(null),[u,i]=v.useState(""),{columns:l=[],columnGroups:c=[],isLoading:d}=n.useColumns(),{valuePickFilterableFields:h=[]}=n.useFilterableFields();(m=a==null?void 0:a.config)!=null&&m.groupByColumns,(f=a==null?void 0:a.config)!=null&&f.metricColumns,(w=a==null?void 0:a.config)!=null&&w.groupByColumns,(b=a==null?void 0:a.config)!=null&&b.pivotByColumns;const x=N=>{o(N),i(N?`[${N.label||N.name}]`:"")},g=N=>{console.log("Formula submitted:",N),i(""),o(null)},p=()=>{i(""),o(null)};return e.jsxs("div",{className:t.cn("flex h-full w-full flex-col",s),children:[e.jsx(pc,{value:u,onChange:i,onSubmit:g,onCancel:p,selectedColumn:r,availableColumns:l}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(uc,{selectedColumn:r,onColumnSelect:x,isLoading:d,sourceFields:l,filterableFields:h})}),e.jsx(xc,{entityGroups:c,isLoading:d})]})]})}function gc(){var B,z;const[s,a]=v.useState("chart"),[r,o]=v.useState(!1),[u,i]=v.useState(!0),[l,c]=v.useState(!0),d=t.useEditorStore(V=>V.showAIDialog),h=t.useDashboardStore(V=>V.isVisualEditing),{setCardType:x}=t.useEditorActions(),g=t.useEditorStore(V=>V.card.type);v.useEffect(()=>ic(),[]);const p=V=>{x(V)},m=t.useEditorStore(V=>V.frame),f=t.useEditorStore(V=>V.card);t.useEditorStore(V=>V.activeTabCardId),t.useEditorStore(V=>V.actions.getAvailableFields);const{addCard:w,removeCard:b,updateCard:N,setActiveCard:A,updateFilters:_}=t.useEditorActions(),{columnFields:C=[],scopedFields:S=[],filterableFields:I=[]}=n.useFilterableFields(),E=n.useSensors(n.useSensor(n.PointerSensor,{activationConstraint:{distance:8}})),D=f,{getFieldsForContainer:T,setFieldsForContainer:y}=n.useFieldManagement(D),{activeField:L,handleDragStart:M,handleDragEnd:P}=Yi({activeCardId:m.activeCardId,sourceFields:S,getFieldsForContainer:T,setFieldsForContainer:y}),F=(V,q)=>{q&&_(V,q)},j=V=>{var q;N(V,{config:{...(q=m.cards.find(U=>U.id===V))==null?void 0:q.config,filters:void 0}})},k=I,O=V=>{if(!V)return 0;let q=V.conditions.length;return V.groups.forEach(U=>{q+=O(U)}),q},R=O(((B=D==null?void 0:D.config)==null?void 0:B.filters)||null);return e.jsxs(n.DndContext,{sensors:E,collisionDetection:n.closestCenter,onDragStart:M,onDragEnd:P,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(ta,{isVisible:u,onToggleVisibility:()=>i(!u)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:g==="tableBuilder"?e.jsx(fc,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!d&&e.jsx(Li,{selectedChart:g,onChartChange:p,groupByFields:T("groupBy"),pivotByFields:T("pivotBy"),metricsFields:T("metrics"),sortByFields:T("sortBy"),detailFields:T("detailColumns"),activeField:L,isVisible:l,onToggleVisibility:()=>c(!l)}),e.jsx(oc,{selectedChart:g,activeView:s,onViewChange:a,onFiltersClick:()=>o(!0),filterCount:R,activeCard:D,columns:C,getFieldsForContainer:T,cards:m.cards,activeCardId:m.activeCardId,addCard:w,setActiveCard:A})]})}),!u&&h&&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(n.Database,{className:"h-4 w-4"})})})]}),D&&e.jsx(Wi,{cardId:D.id,filters:((z=D.config)==null?void 0:z.filters)||null,onFiltersChange:F,onClearFilters:j,availableFields:k,isOpen:r,onOpenChange:o}),e.jsx(n.DragOverlay,{dropAnimation:null,children:e.jsx(lc,{activeField:L||null})})]})}function bc({authToken:s,onSave:a,onClose:r}){const o=v.useRef(null),u=t.useEditorStore(E=>E.showAIDialog),i=t.useEditorStore(E=>E.isDevMode),l=n.useAssistantLayoutStore(E=>E.setFullscreen),c=n.useAssistantLayoutStore(E=>E.setPanelOpen),d=n.useAssistantLayoutStore(E=>E.setContainer),h=n.useAssistantPanel("editor"),x=n.useFullscreenAssistant(),g=n.useAssistantContainer("editor"),p=x==="editor",m=n.useDashboardAppearance(),f=v.useCallback(E=>{d("editor",E)},[d]),{setAuthToken:w}=t.useDashboardActions(),{setShowAIDialog:b,setOnSave:N,setOnClose:A}=t.useEditorActions(),{setActiveAssistantType:_}=t.useAIActions();v.useEffect(()=>{a&&N(a),r&&A(r)},[a,N,r,A]),v.useEffect(()=>{s&&s.accessToken&&w(s)},[s,w]),v.useEffect(()=>{var E,D;u?((E=o.current)==null||E.resize(40),c("editor",!0),_("editor")):((D=o.current)==null||D.resize(0),c("editor",!1),x==="editor"&&l(null),_(null))},[u,c,_,l,x]);function C(E){var D;E<1?(b(!1),c("editor",!1),x==="editor"&&l(null),_(null),(D=o.current)==null||D.resize(0)):(u||(b(!0),_("editor")),h.isOpen||c("editor",!0))}function S(){return e.jsxs(e.Fragment,{children:[e.jsx(ta,{isVisible:!0,onToggleVisibility:()=>{}}),e.jsxs("div",{className:"relative flex grow",children:[e.jsxs(n.ResizablePanelGroup,{"data-content":"editor-main",className:t.cn("grow transition-opacity",p&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(n.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(ii,{})}),e.jsx(n.ResizableHandle,{disabled:!u}),e.jsx(n.ResizablePanel,{"data-role":"editor-assistant-panel",ref:o,onResize:C,defaultSize:h.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Kn,{isFullscreen:p,onFullscreenChange:E=>l(E?"editor":null),fullscreenContainer:g})})})]}),e.jsx("div",{ref:f,className:t.cn("absolute inset-0",!p&&"pointer-events-none")})]})]})}function I(){return e.jsxs("div",{className:"relative flex h-full grow",children:[e.jsxs(n.ResizablePanelGroup,{"data-content":"explorer",className:t.cn("flex grow transition-opacity",p&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(n.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(gc,{})}),e.jsx(n.ResizableHandle,{disabled:!u}),e.jsx(n.ResizablePanel,{"data-role":"editor-assistant-panel",ref:o,onResize:C,defaultSize:h.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Kn,{isFullscreen:p,onFullscreenChange:E=>l(E?"editor":null),fullscreenContainer:g})})})]}),e.jsx("div",{ref:f,className:t.cn("absolute inset-0",!p&&"pointer-events-none")})]})}return e.jsx(n.ErrorBoundary,{FallbackComponent:n.Fallback,children:i?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",style:m.dashboardContainerStyle,children:S()}):e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",style:m.dashboardContainerStyle,children:I()})})}function jc(){t.useDashboardStore(m=>m.selectedCardId);const s=t.useDashboardStore(m=>m.selectedSheetId),a=t.useDashboardStore(m=>m.dashboard),{setIsVisualEditing:r,setSelectedSheetId:o}=t.useDashboardStore(m=>m.actions),u=t.useEditorStore(m=>m.editorContext),{clearEditorContext:i}=t.useEditorStore(m=>m.actions),l=n.useDashboardAppearance(),c=t.useDashboardStore(m=>m.isVisualEditing),d=t.useDashboardStore(m=>m.actions.updateFrame),h=t.useDashboardStore(m=>m.actions.updateDocumentSectionCard),x=n.useResolveExistingFrameSemanticExecutionPayload();async function g(m){var A,_,C;if((u==null?void 0:u.type)==="documentSection"){const S=n.getDocumentSectionEditorCard(m,u.cardId);if(!S){n.ue.error("No document section card found");return}if(!n.isSupportedDocumentTableCardType(S)){n.ue.error("Document table sections support Table and Pivot Table");return}h(u.sheetId,u.sectionId,S,{calculatedFields:m.calculatedFields}),i(),r(!1);return}const f=s?(A=a==null?void 0:a.sheets)==null?void 0:A.some(S=>{var I;return S.id===s&&((I=S.frames)==null?void 0:I.some(E=>E.id===m.id))}):!1,w=(C=(_=a==null?void 0:a.sheets)==null?void 0:_.find(S=>{var I;return(I=S.frames)==null?void 0:I.some(E=>E.id===m.id)}))==null?void 0:C.id,b=f?s:w||null;if(!b)return;const N=n.findDashboardFrameById(a,m.id);try{const S=await x(m,{previousFrame:N});d(b,m,{semanticExecutionPayload:S}),s!==b&&o(b),r(!1)}catch(S){console.error("Failed to resolve semantic metadata on save:",S),n.ue.error(S instanceof Error?S.message:"Failed to resolve semantic metadata for this visual")}}function p(){i(),r(!1)}return e.jsx("div",{role:"editor-container",className:t.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!c}),style:l.dashboardContainerStyle,children:e.jsx(bc,{onSave:g,onClose:p})})}exports.default=jc;
|