react-semaphor 0.1.310 → 0.1.311

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.
Files changed (46) hide show
  1. package/dist/brand-studio/index.cjs +1 -1
  2. package/dist/brand-studio/index.js +4 -4
  3. package/dist/chunks/{braces-BataYVhi.js → braces-CSECDaJQ.js} +1 -1
  4. package/dist/chunks/{braces-B_1DhXjs.js → braces-DwaAt32i.js} +1 -1
  5. package/dist/chunks/{chevrons-up-down-2PuJgXa0.js → chevrons-up-down-3vBEM7eI.js} +1 -1
  6. package/dist/chunks/{chevrons-up-down-CfMX77Ug.js → chevrons-up-down-DJhB8JNW.js} +1 -1
  7. package/dist/chunks/{dashboard-controls-DKNSTyu3.js → dashboard-controls-CeKjYa7s.js} +8 -8
  8. package/dist/chunks/{dashboard-controls-CZH2CHE6.js → dashboard-controls-Ds8Hmo3Q.js} +1 -1
  9. package/dist/chunks/{dashboard-filter-controls-button-CRYFNfgr.js → dashboard-filter-controls-button-CWL2jJcu.js} +1 -1
  10. package/dist/chunks/{dashboard-filter-controls-button-C5FGXiyJ.js → dashboard-filter-controls-button-Tk5lhwVV.js} +4 -4
  11. package/dist/chunks/{dashboard-json-CUYxXIbj.js → dashboard-json-B_rQbUUz.js} +1 -1
  12. package/dist/chunks/{dashboard-json-A9m16zgO.js → dashboard-json-GL_IXTCk.js} +2 -2
  13. package/dist/chunks/{dashboard-summary-settings-dialog-BFldiulJ.js → dashboard-summary-settings-dialog-CcszMc1A.js} +3 -3
  14. package/dist/chunks/{dashboard-summary-settings-dialog-Dl80Vf3Y.js → dashboard-summary-settings-dialog-DgqFlYl9.js} +1 -1
  15. package/dist/chunks/edit-dashboard-visual-Bu2rxJjm.js +183 -0
  16. package/dist/chunks/{edit-dashboard-visual-C013lDvS.js → edit-dashboard-visual-nGSsSTYx.js} +6760 -6657
  17. package/dist/chunks/{index-scc12bkM.js → index-9v7DehZd.js} +33034 -32819
  18. package/dist/chunks/index-CGCrm-dj.js +1330 -0
  19. package/dist/chunks/{palette-CuxyTPBF.js → palette-C5o9bLo6.js} +1 -1
  20. package/dist/chunks/{palette-DIqG9FgB.js → palette-CI2J34i6.js} +1 -1
  21. package/dist/chunks/{resource-management-panel-CkS-1IEw.js → resource-management-panel-CNmVHnCz.js} +1 -1
  22. package/dist/chunks/{resource-management-panel-xJtqTzS8.js → resource-management-panel-DTg9_DI9.js} +3 -3
  23. package/dist/chunks/{save-CPHrveZg.js → save-CMv91_Hz.js} +1 -1
  24. package/dist/chunks/{save-CP9_rxYk.js → save-Cpz6BWx9.js} +1 -1
  25. package/dist/chunks/{switch-DXHYEa_J.js → switch-Dhoqe3OE.js} +3336 -3245
  26. package/dist/chunks/switch-otrSiyjH.js +168 -0
  27. package/dist/chunks/{use-create-flow-overlay-state-C77yBFiq.js → use-create-flow-overlay-state-C8WGfC8T.js} +4 -4
  28. package/dist/chunks/{use-create-flow-overlay-state-nhcTzyJQ.js → use-create-flow-overlay-state-DiH6M1Cd.js} +1 -1
  29. package/dist/chunks/{use-visual-utils-Cm2IkP1c.js → use-visual-utils-BeJ73yvV.js} +1 -1
  30. package/dist/chunks/{use-visual-utils-BqljNzWn.js → use-visual-utils-RkPa2gqQ.js} +2 -2
  31. package/dist/dashboard/index.cjs +1 -1
  32. package/dist/dashboard/index.js +1 -1
  33. package/dist/index.cjs +1 -1
  34. package/dist/index.js +7 -7
  35. package/dist/style.css +1 -1
  36. package/dist/surfboard/index.cjs +1 -1
  37. package/dist/surfboard/index.js +2 -2
  38. package/dist/types/dashboard.d.ts +5 -2
  39. package/dist/types/main.d.ts +12 -2
  40. package/dist/types/shared.d.ts +5 -2
  41. package/dist/types/surfboard.d.ts +5 -2
  42. package/dist/types/types.d.ts +5 -2
  43. package/package.json +1 -1
  44. package/dist/chunks/edit-dashboard-visual-Bt6wP1pc.js +0 -183
  45. package/dist/chunks/index-C_mYCH5V.js +0 -1330
  46. package/dist/chunks/switch-BFPV36rd.js +0 -168
@@ -0,0 +1,183 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),C=require("react"),n=require("./index-CGCrm-dj.js"),t=require("./switch-otrSiyjH.js"),ft=require("./use-visual-utils-BeJ73yvV.js"),Oe=require("./use-create-flow-overlay-state-DiH6M1Cd.js"),On=require("./chevrons-up-down-3vBEM7eI.js"),wa=require("react-dom");require("./index-DRlMUglg.js");const Ta=require("./palette-C5o9bLo6.js"),Ea=require("./common-types-C73-Ud1-.js");function Ia(s){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const r in s)if(r!=="default"){const l=Object.getOwnPropertyDescriptor(s,r);Object.defineProperty(a,r,l.get?l:{enumerable:!0,get:()=>s[r]})}}return a.default=s,Object.freeze(a)}const Da=Ia(C);/**
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 ka=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 Aa=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 Pn=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 Bn=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 ys=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 La=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 Vn=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 Ma=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 Fa=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 Ra=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 Oa=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 Pa=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 Ba=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 hn=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 Va=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 _a=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 as=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 rs=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 za=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 qa=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 $a=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 Zt=t.createLucideIcon("Rows3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M21 9H3",key:"1338ky"}],["path",{d:"M21 15H3",key:"9uk58r"}]]);/**
112
+ * @license lucide-react v0.453.0 - ISC
113
+ *
114
+ * This source code is licensed under the ISC license.
115
+ * See the LICENSE file in the root directory of this source tree.
116
+ */const Ka=t.createLucideIcon("SendHorizontal",[["path",{d:"M3.714 3.048a.498.498 0 0 0-.683.627l2.843 7.627a2 2 0 0 1 0 1.396l-2.842 7.627a.498.498 0 0 0 .682.627l18-8.5a.5.5 0 0 0 0-.904z",key:"117uat"}],["path",{d:"M6 12h16",key:"s4cdu5"}]]);/**
117
+ * @license lucide-react v0.453.0 - ISC
118
+ *
119
+ * This source code is licensed under the ISC license.
120
+ * See the LICENSE file in the root directory of this source tree.
121
+ */const Ga=t.createLucideIcon("Shapes",[["path",{d:"M8.3 10a.7.7 0 0 1-.626-1.079L11.4 3a.7.7 0 0 1 1.198-.043L16.3 8.9a.7.7 0 0 1-.572 1.1Z",key:"1bo67w"}],["rect",{x:"3",y:"14",width:"7",height:"7",rx:"1",key:"1bkyp8"}],["circle",{cx:"17.5",cy:"17.5",r:"3.5",key:"w3z12y"}]]);/**
122
+ * @license lucide-react v0.453.0 - ISC
123
+ *
124
+ * This source code is licensed under the ISC license.
125
+ * See the LICENSE file in the root directory of this source tree.
126
+ */const Ua=t.createLucideIcon("Sigma",[["path",{d:"M18 7V5a1 1 0 0 0-1-1H6.5a.5.5 0 0 0-.4.8l4.5 6a2 2 0 0 1 0 2.4l-4.5 6a.5.5 0 0 0 .4.8H17a1 1 0 0 0 1-1v-2",key:"wuwx1p"}]]);/**
127
+ * @license lucide-react v0.453.0 - ISC
128
+ *
129
+ * This source code is licensed under the ISC license.
130
+ * See the LICENSE file in the root directory of this source tree.
131
+ */const Ha=t.createLucideIcon("Spline",[["circle",{cx:"19",cy:"5",r:"2",key:"mhkx31"}],["circle",{cx:"5",cy:"19",r:"2",key:"v8kfzx"}],["path",{d:"M5 17A12 12 0 0 1 17 5",key:"1okkup"}]]);/**
132
+ * @license lucide-react v0.453.0 - ISC
133
+ *
134
+ * This source code is licensed under the ISC license.
135
+ * See the LICENSE file in the root directory of this source tree.
136
+ */const Qa=t.createLucideIcon("SquareFunction",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["path",{d:"M9 17c2 0 2.8-1 2.8-2.8V10c0-2 1-3.3 3.2-3",key:"m1af9g"}],["path",{d:"M9 11.2h5.7",key:"3zgcl2"}]]);/**
137
+ * @license lucide-react v0.453.0 - ISC
138
+ *
139
+ * This source code is licensed under the ISC license.
140
+ * See the LICENSE file in the root directory of this source tree.
141
+ */const Wa=t.createLucideIcon("SquareSplitVertical",[["path",{d:"M5 8V5c0-1 1-2 2-2h10c1 0 2 1 2 2v3",key:"1pi83i"}],["path",{d:"M19 16v3c0 1-1 2-2 2H7c-1 0-2-1-2-2v-3",key:"ido5k7"}],["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}]]);/**
142
+ * @license lucide-react v0.453.0 - ISC
143
+ *
144
+ * This source code is licensed under the ISC license.
145
+ * See the LICENSE file in the root directory of this source tree.
146
+ */const Ya=t.createLucideIcon("Tag",[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]]);/**
147
+ * @license lucide-react v0.453.0 - ISC
148
+ *
149
+ * This source code is licensed under the ISC license.
150
+ * See the LICENSE file in the root directory of this source tree.
151
+ */const Ja=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 Xa({open:s,onOpenChange:a}){const[r,l]=C.useState([]),{updateDataSource:u}=t.useEditorActions(),{selectedEntities:i}=n.useAssistantContextEntities("dashboard");C.useEffect(()=>{s&&l([])},[s]);const o=m=>{l(g=>g.some(f=>n.areContextEntitiesEqual(f,m))?g.filter(f=>!n.areContextEntitiesEqual(f,m)):[...g,m])},d=()=>{l([...i])},c=()=>{l([])},x=()=>{if(r.length===0)return;const m=r[0],g=m.connectionId||"",S=m.connectionType||"",N=r.some(B=>B.type==="dataset")?"semanticDomain":"database";u({connectionId:g,connectionType:S,mode:N,selectedEntities:r}),a(!1)},h=m=>"label"in m&&m.label?m.label:m.name,v=m=>{if("description"in m&&m.description)return m.description;const g=[];return m.database&&g.push(m.database),m.schema&&g.push(m.schema),m.name&&g.push(m.name),g.join(".")},p=m=>r.some(g=>n.areContextEntitiesEqual(g,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:d,disabled:r.length===i.length,children:"Select All"}),e.jsx(t.Button,{variant:"outline",size:"sm",onClick:c,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,g)=>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:()=>o(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:h(m)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:v(m)})]}),e.jsx(n.Badge,{variant:"outline",className:"text-xs",children:m.type})]},`${m.type}-${m.name}-${g}`))})})]}),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:x,disabled:r.length===0,children:["Select"," ",r.length>0?`(${r.length})`:""]})]})})})]})})}function Za({initialJoinPlan:s,availableDataSources:a}){const[r,l]=C.useState(s),[u,i]=C.useState(new Set),o=()=>{const D=r.joins.length>0?Math.max(...r.joins.map(y=>y.sequence))+1:1,E={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:D,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};l({...r,joins:[...r.joins,E]}),i(new Set([...u,E.id]))},d=D=>{l({...r,joins:r.joins.filter(E=>E.id!==D)}),i(new Set([...u].filter(E=>E!==D)))},c=(D,E)=>{var k,F,O,j,T;const y=r.joins.find(L=>L.id===D);if(!y)return;const M={...y,...E};if((k=M.source)!=null&&k.name&&((F=M.target)!=null&&F.name)&&M.source.name===M.target.name){n.ue.error("Self-joins are not yet supported",{description:`Joining ${M.source.name} to itself is not currently supported. Please select a different target table.`});return}const b=r.joins.filter(L=>{var V;return L.id!==D&&L.target.name===((V=M.target)==null?void 0:V.name)});if((O=M.target)!=null&&O.name&&b.length>0){n.ue.error("Duplicate join targets are not supported",{description:`The table ${M.target.name} is already used as a target in another join. Each table can only be joined once.`});return}const R=r.joins.map(L=>L.id===D?M:L);if((j=M.source)!=null&&j.name&&((T=M.target)!=null&&T.name)&&M.joinKeyGroups[0].keys.length===0){const L=a.find(P=>{var q;return P.name===((q=M.source)==null?void 0:q.name)}),V=a.find(P=>{var q;return P.name===((q=M.target)==null?void 0:q.name)}),z={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(L==null?void 0:L.name)||"",entityName:(L==null?void 0:L.name)||"",entityType:(L==null?void 0:L.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(V==null?void 0:V.name)||"",entityName:(V==null?void 0:V.name)||"",entityType:(V==null?void 0:V.type)||"table"},operator:"="},_=[...M.joinKeyGroups];_[0]={..._[0],keys:[z]},M.joinKeyGroups=_,R[R.findIndex(P=>P.id===D)]=M}l({...r,joins:R})};return{joinPlan:r,expandedJoins:u,setJoinPlan:l,addJoin:o,removeJoin:d,updateJoin:c,moveJoinUp:D=>{const E=r.joins.findIndex(y=>y.id===D);if(E>0){const y=[...r.joins],M={...y[E]},b={...y[E-1]};y[E]=b,y[E-1]=M,y.forEach((k,F)=>{k.sequence=F+1});const R={...r,joins:y};l(R)}},moveJoinDown:D=>{const E=r.joins.findIndex(y=>y.id===D);if(E<r.joins.length-1){const y=[...r.joins],M={...y[E]},b={...y[E+1]};y[E]=b,y[E+1]=M,y.forEach((k,F)=>{k.sequence=F+1});const R={...r,joins:y};l(R)}},toggleJoinExpansion:D=>{const E=new Set(u);E.has(D)?E.delete(D):E.add(D),i(E)},getAvailableSourceEntities:D=>{if(r.joins.length===0)return a;const E=r.joins.findIndex(M=>M.id===D);if(E===0)return a.filter(M=>M.name===r.baseEntity.name);const y=new Set;return r.baseEntity.name&&y.add(r.baseEntity.name),r.joins.slice(0,E).forEach(M=>{y.add(M.source.name),y.add(M.target.name)}),a.filter(M=>y.has(M.name))},getAvailableTargetEntities:D=>a.filter(E=>E.name!==D),addJoinKeyGroup:D=>{const E=r.joins.find(M=>M.id===D);if(!E)return;const y=[...E.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];c(D,{joinKeyGroups:y})},updateGroupOperator:(D,E,y)=>{const M=r.joins.find(R=>R.id===D);if(!M)return;const b=[...M.joinKeyGroups];b[E]={...b[E],operator:y},c(D,{joinKeyGroups:b})},removeJoinKeyGroup:(D,E)=>{const y=r.joins.find(b=>b.id===D);if(!y)return;const M=[...y.joinKeyGroups];M.splice(E,1),c(D,{joinKeyGroups:M})},addJoinKey:(D,E)=>{const y=r.joins.find(F=>F.id===D);if(!y)return;const M=a.find(F=>F.name===y.source.name),b=a.find(F=>F.name===y.target.name),R=[...y.joinKeyGroups],k={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(M==null?void 0:M.name)||"",entityName:(M==null?void 0:M.name)||"",entityType:(M==null?void 0:M.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(b==null?void 0:b.name)||"",entityName:(b==null?void 0:b.name)||"",entityType:(b==null?void 0:b.type)||"table"},operator:"="};R[E]={...R[E],keys:[...R[E].keys,k]},c(D,{joinKeyGroups:R})},updateJoinKey:(D,E,y,M,b)=>{const R=r.joins.find(T=>T.id===D);if(!R)return;const k=a.find(T=>T.name===R.source.name),F=a.find(T=>T.name===R.target.name),O=[...R.joinKeyGroups],j=O[E].keys[y];M==="sourceColumnName"&&k?O[E].keys[y]={...j,source:{...j.source,name:b}}:M==="targetColumnName"&&F?O[E].keys[y]={...j,target:{...j.target,name:b}}:M==="operator"&&(O[E].keys[y]={...j,operator:b}),c(D,{joinKeyGroups:O})},removeJoinKey:(D,E,y)=>{const M=r.joins.find(R=>R.id===D);if(!M)return;const b=[...M.joinKeyGroups];b[E].keys.splice(y,1),c(D,{joinKeyGroups:b})},generateSQLPreview:()=>{const D=[...r.joins].sort((M,b)=>M.sequence-b.sequence),E=r.baseEntity;if(!E.name)return"SELECT * FROM table -- Please select a base entity";let y=`SELECT *
152
+ FROM ${E.name}`;return D.forEach(M=>{const b=a.find(F=>F.name===M.target.name);if(!b)return;const R=M.joinKeyGroups.filter(F=>F.keys&&F.keys.length>0).map(F=>{const O=F.keys.filter(j=>{var T,L,V,z;return((T=j.source)==null?void 0:T.name)&&((L=j.target)==null?void 0:L.name)&&((V=j.source)==null?void 0:V.entityName)&&((z=j.target)==null?void 0:z.entityName)}).map(j=>`${j.source.entityName}.${j.source.name} ${j.operator} ${j.target.entityName}.${j.target.name}`);return O.length>1?`(${O.join(` ${F.operator} `)})`:O[0]}).filter(Boolean),k=R.length>1?R.join(" OR "):R[0]||"condition_here";y+=`
153
+ ${M.joinType} JOIN ${b.name}
154
+ ON ${k}`}),y},isValidConfiguration:()=>!(!r.baseEntity.name||r.joins.some(M=>!M.source.name||!M.target.name)||r.joins.some(M=>M.joinKeyGroups.some(b=>b.keys.length===0))||r.joins.some(M=>M.joinKeyGroups.some(b=>b.keys.some(R=>!R.source.name||!R.target.name||!R.operator))))}}function er({joinPlan:s,availableDataSources:a,onSave:r,onRemove:l,onCancel:u}){const{setCardConfig:i}=t.useEditorActions();t.useEditorStore(k=>k.card.config);const{columnGroups:o}=n.useColumns(),d=o.filter(k=>k.entityName!==t.CALCULATED_FIELDS_GROUP_NAME),{joinPlan:c,expandedJoins:x,setJoinPlan:h,addJoin:v,removeJoin:p,updateJoin:m,moveJoinUp:g,moveJoinDown:S,toggleJoinExpansion:f,getAvailableSourceEntities:N,getAvailableTargetEntities:A,addJoinKeyGroup:B,updateGroupOperator:w,removeJoinKeyGroup:I,addJoinKey:D,updateJoinKey:E,removeJoinKey:y,generateSQLPreview:M,isValidConfiguration:b}=Za({initialJoinPlan:s,availableDataSources:a}),R=k=>{const F=d.find(O=>O.entityName===k);return(F==null?void 0:F.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(t.Select,{value:c.baseEntity.name,onValueChange:k=>{const F=a.find(O=>O.name===k);h({...c,baseEntity:{connectionId:(F==null?void 0:F.connectionId)||"",connectionType:(F==null?void 0:F.connectionType)||"none",type:(F==null?void 0:F.type)||"table",name:k,database:F==null?void 0:F.database,schema:F==null?void 0:F.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(t.SelectContent,{children:a.map(k=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:k.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Badge,{variant:"outline",className:"text-xs",children:k.type}),k.name,e.jsx(n.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},k.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:M()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(t.Label,{children:["Joins Configuration (",c.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:v,children:[e.jsx(n.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),c.joins.length===0?e.jsx("div",{className:"rounded-lg border border-dashed py-8 text-center text-muted-foreground",children:e.jsx("p",{children:"No joins configured. Add a join to connect multiple data sources."})}):e.jsx("div",{className:"max-h-[300px] space-y-4 overflow-y-auto",children:c.joins.map(k=>{const F=a.find(T=>T.name===k.source.name),O=a.find(T=>T.name===k.target.name),j=x.has(k.id);return e.jsxs(n.Card,{className:"border",children:[e.jsx(n.CardHeader,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Badge,{children:k.sequence}),e.jsxs(n.CardTitle,{className:"text-sm",children:["Join ",k.sequence,F&&O&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",F.name," → ",O.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>g(k.id),disabled:k.sequence===1,children:e.jsx(n.ArrowUp,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>S(k.id),disabled:k.sequence===c.joins.length,children:e.jsx(n.ArrowDown,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>f(k.id),children:j?e.jsx(t.ChevronUp,{className:"h-4 w-4"}):e.jsx(t.ChevronDown,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>p(k.id),children:e.jsx(t.X,{className:"h-4 w-4"})})]})]})}),j&&e.jsxs(n.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Source"}),e.jsxs(t.Select,{value:k.source.name,onValueChange:T=>{const L=a.find(V=>V.name===T);m(k.id,{source:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:T,database:L==null?void 0:L.database,schema:L==null?void 0:L.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select source..."})}),e.jsx(t.SelectContent,{children:N(k.id).map(T=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:T.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Badge,{variant:"outline",className:"text-xs",children:T.type}),T.name]})},T.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Join Type"}),e.jsxs(t.Select,{value:k.joinType,onValueChange:T=>m(k.id,{joinType:T}),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Target"}),e.jsxs(t.Select,{value:k.target.name,onValueChange:T=>{const L=a.find(V=>V.name===T);m(k.id,{target:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:T,database:L==null?void 0:L.database,schema:L==null?void 0:L.schema}})},disabled:!k.source.name,children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select target..."})}),e.jsx(t.SelectContent,{children:k.source.name?A(k.source.name).map(T=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:T.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Badge,{variant:"outline",className:"text-xs",children:T.type}),T.name,T.name===k.source.name&&e.jsx(n.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},T.name)):[]})]})]})]}),k.source.name&&k.target.name&&F&&O&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{children:"Join Conditions"}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>B(k.id),children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),k.joinKeyGroups.length===0?e.jsx("div",{className:"rounded-md border p-3 text-center text-sm text-gray-500",children:"No join conditions defined. Add condition groups to specify how data sources should be joined."}):e.jsx("div",{className:"space-y-4",children:k.joinKeyGroups.map((T,L)=>e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Label,{children:["Group ",L+1]}),L>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(t.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Select,{value:T.operator,onValueChange:V=>w(k.id,L,V),children:[e.jsx(t.SelectTrigger,{className:"w-[100px]",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>I(k.id,L),children:e.jsx(n.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[T.keys.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-sm text-gray-500",children:"No conditions in this group. Add conditions to specify join criteria."}):e.jsx("div",{className:"space-y-2",children:T.keys.map((V,z)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[z>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:T.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:V.source.name,onValueChange:_=>E(k.id,L,z,"sourceColumnName",_),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Source column"})}),e.jsx(t.SelectContent,{children:R(k.source.name).map(_=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:_.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:_.name}),e.jsx(n.Badge,{variant:"outline",className:"ml-2 text-xs",children:_.dataType})]})},_.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(t.Select,{value:V.operator,onValueChange:_=>E(k.id,L,z,"operator",_),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:V.target.name,onValueChange:_=>E(k.id,L,z,"targetColumnName",_),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Target column"})}),e.jsx(t.SelectContent,{children:R(k.target.name).map(_=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:_.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:_.name}),e.jsx(n.Badge,{variant:"outline",className:"ml-2 text-xs",children:_.dataType})]})},_.name))})]})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>y(k.id,L,z),children:e.jsx(t.X,{className:"size-3.5"})})]},V.id||z))}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>D(k.id,L),children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},T.id))})]})]})]},k.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>{l(),u()},children:"Remove All"}),e.jsx(t.Button,{variant:"outline",onClick:u,children:"Cancel"}),e.jsx(t.Button,{onClick:()=>r(c),disabled:!b(),children:"Save"})]})]})}function _n({children:s,open:a,onOpenChange:r,joinPlan:l,availableDataSources:u,onRemove:i,onSave:o,onCancel:d}){return e.jsxs(n.Dialog,{open:a,onOpenChange:r,children:[e.jsxs(n.DialogContent,{className:"max-w-4xl",children:[e.jsxs(n.DialogHeader,{children:[e.jsx(n.DialogTitle,{children:"Join Configuration"}),e.jsx(n.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(er,{joinPlan:l,availableDataSources:u,onSave:o,onCancel:d,onRemove:i})]}),s]})}function tr({joins:s,baseEntityId:a,availableDataSources:r,generateSQLPreview:l}){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((o,d)=>o.sequence-d.sequence),i=r.find(o=>o.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(o=>{const d=r.find(c=>c.name===o.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:o.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:d==null?void 0:d.type}),e.jsx("span",{className:"text-xs font-medium",children:d==null?void 0:d.name})]})]},o.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 o=r.find(x=>x.name===u.source.name),d=r.find(x=>x.name===u.target.name),c=u.joinKeyGroups.reduce((x,h)=>x+h.keys.length,0);return e.jsxs("div",{className:"rounded-md bg-muted p-2 text-left",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(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:[c," condition",c>1?"s":""]})]}),e.jsxs("div",{className:"mt-1 truncate pl-1 text-xs text-muted-foreground",children:[o==null?void 0:o.name," → ",d==null?void 0:d.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:l()})})]})]})}function sr({open:s,onOpenChange:a,variant:r="button"}={}){var A,B;const l=t.useEditorStore(w=>w.card),{autoJoinMetadata:u}=n.useEditorCardQuery(l),i=t.useEditorStore(w=>w.actions.updateCardConfig),o=((A=l==null?void 0:l.config)==null?void 0:A.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[d,c]=C.useState(!1),x=s!==void 0,h=x?s:d,v=x?a:c,p=((B=l==null?void 0:l.dataSource)==null?void 0:B.selectedEntities)||[],m=w=>{i(l.id,{...l==null?void 0:l.config,joinPlan:w}),v(!1)},g=()=>{i(l.id,{...l==null?void 0:l.config,joinPlan:void 0})},S=()=>{v(!1)},f=()=>{const w=[...o.joins].sort((E,y)=>E.sequence-y.sequence),I=o.baseEntity;if(!I.name)return"SELECT * FROM table -- Please select a base entity";let D=`SELECT *
155
+ FROM ${I.name}`;return w.forEach(E=>{const y=p.find(R=>R.name===E.target.name);if(!y)return;const M=E.joinKeyGroups.filter(R=>R.keys&&R.keys.length>0).map(R=>{const k=R.keys.filter(F=>{var O,j,T,L;return((O=F.source)==null?void 0:O.name)&&((j=F.target)==null?void 0:j.name)&&((T=F.source)==null?void 0:T.entityName)&&((L=F.target)==null?void 0:L.entityName)}).map(F=>`${F.source.entityName}.${F.source.name} ${F.operator} ${F.target.entityName}.${F.target.name}`);return k.length>1?`(${k.join(` ${R.operator} `)})`:k[0]}).filter(Boolean),b=M.length>1?M.join(" OR "):M[0]||"condition_here";D+=`
156
+ ${E.joinType} JOIN ${y.name}
157
+ ON ${b}`}),D};if(p.length<2)return null;const N=o.joins.length>0&&e.jsx(t.TooltipContent,{side:"bottom",className:"ml-4 max-w-md overflow-hidden p-0",children:e.jsx(tr,{joins:o.joins,baseEntityId:o.baseEntity.name,availableDataSources:p,generateSQLPreview:f})});return e.jsxs(e.Fragment,{children:[e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children: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:w=>{w.stopPropagation(),v(!0)},children:[e.jsx(n.Link,{className:"h-3 w-3"}),o.joins.length]}):e.jsxs("button",{type:"button",onClick:()=>v(!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:o.joins.length===0?"Configure joins":`${o.joins.length} ${o.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(_n,{open:h,onOpenChange:v,joinPlan:o,availableDataSources:p,onSave:m,onCancel:S,onRemove:g,children:e.jsx("div",{})})]})}function nr(){var w,I,D,E,y,M;const[s,a]=C.useState(!1),[r,l]=C.useState(!1),[u,i]=C.useState(!1),o=t.useEditorStore(b=>b.card.dataSource),d=t.useEditorStore(b=>b.card),c=t.useEditorStore(b=>b.isDevMode),{updateDataSource:x}=t.useEditorActions(),{autoJoinMetadata:h}=n.useEditorCardQuery(d),p={...{connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},...o,selectedEntities:(o==null?void 0:o.selectedEntities)||[]},m=n.toEntityArray(p.selectedEntities),g=m.length,S=g===0?"Choose dataset":g===1?ls(m[0]):`${g} datasets`,f=((D=(I=(w=d==null?void 0:d.config)==null?void 0:w.joinPlan)==null?void 0:I.joins)==null?void 0:D.length)??0,N=!!(h!=null&&h.autoResolved);((y=(E=h==null?void 0:h.resolvedJoinPlan)==null?void 0:E.joins)==null?void 0:y.length)??((M=h==null?void 0:h.relationshipsUsed)==null||M.length);const A=g<2?null:f>0?`${f} join${f===1?"":"s"}`:N?"auto":null,B=b=>{const R=m.filter(k=>!n.areContextEntitiesEqual(k,b));x({...p,selectedEntities:R})};return e.jsxs(e.Fragment,{children:[e.jsxs(t.Popover,{open:s,onOpenChange:a,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex h-7 w-full items-center gap-2 rounded-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:S}),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:g})]}),g===0?e.jsx("div",{className:"px-3 pb-2 text-[12px] text-muted-foreground",children:"No datasets selected."}):e.jsx("ul",{className:"mb-1",children:m.map((b,R)=>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:ls(b)}),e.jsx("p",{className:"truncate text-[11px] text-muted-foreground",children:ar(b)})]}),e.jsx("button",{type:"button",onClick:()=>B(b),"aria-label":`Remove ${ls(b)}`,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"})})]},`${b.connectionId}-${b.name}-${R}`))}),e.jsxs("button",{type:"button",onClick:()=>{a(!1),l(!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"]})]}),g>1&&!c&&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:f>0?`${f} ${f===1?"join":"joins"}`:"Configure joins"}),N&&f===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:(o==null?void 0:o.selectedEntities)||[],dialogMode:"dataSource",open:r,onOpenChange:l,dataSource:p}),g>1&&!c&&e.jsx("div",{className:"hidden",children:e.jsx(sr,{open:u,onOpenChange:i})})]})}function ls(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 zn({isVisible:s}){n.useSyncLegacyEditorState();const[a,r]=C.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(nr,{})}),e.jsx("div",{className:"min-h-0 flex-1",children:e.jsx(n.FieldsSection,{})}),e.jsx(Xa,{open:a,onOpenChange:r})]})}function qn({storeValue:s,defaultValue:a="",onStoreUpdate:r,delay:l=300}){const[u,i]=C.useState(s??a),o=C.useRef(null),d=C.useRef(u),c=C.useRef(s),x=C.useRef(!1),h=C.useCallback(()=>{o.current&&(clearTimeout(o.current),o.current=null),x.current&&d.current!==(c.current??a)&&(r(d.current),c.current=d.current)},[a,r]);C.useEffect(()=>{if(s!==c.current){o.current&&(clearTimeout(o.current),o.current=null);const p=s??a;i(p),d.current=p,c.current=s,x.current=!1}},[s,a]),C.useEffect(()=>{if(x.current)return o.current=setTimeout(()=>{h()},l),()=>{o.current&&(clearTimeout(o.current),o.current=null)}},[l,h,u]),C.useEffect(()=>()=>{o.current&&clearTimeout(o.current)},[]);const v=C.useCallback(p=>{const m=p??a;x.current=!0,d.current=m,i(m)},[a]);return{value:u,onChange:v,flush:h}}const rr=300;function lr(){const s=t.useEditorStore(N=>N.card.sql),a=t.useEditorStore(N=>N.sqlGen),r=t.useEditorStore(N=>N.card),l=Oe.useEffectiveEditorCardType(),{setCardSql:u,setSqlGen:i,setRunSql:o}=t.useEditorActions(),d=C.useMemo(()=>l!==r.type?{...r,type:l}:r,[r,l]),{queryKey:c}=n.useEditorCardQuery(d),x=n.useQueryClient(),h=C.useRef(c);h.current=c;const v=C.useRef(a);v.current=a;const p=C.useCallback(N=>{u(N)},[u]),{value:m,onChange:g,flush:S}=qn({storeValue:s,defaultValue:"",onStoreUpdate:p,delay:rr});C.useEffect(()=>ft.registerPendingEditorDraftFlusher(S),[S]);function f(N){g(N),t.isObjectEmpty(v.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:f,language:"sql-jinja",embedded:!0,flushGutter:!0,wrapLines:!0,onKeyDown:N=>{N.key==="Enter"&&N.shiftKey&&(N.preventDefault(),ft.flushPendingEditorDrafts(),setTimeout(()=>{x.removeQueries({queryKey:h.current,exact:!0}),o(!0)},0))}})]})}const or=300;function ir(){const s=t.useEditorStore(p=>p.card.python),a=t.useEditorStore(p=>p.card),r=Oe.useEffectiveEditorCardType(),{setCardPython:l,setRunSql:u}=t.useEditorActions(),i=C.useMemo(()=>r!==a.type?{...a,type:r}:a,[a,r]),{queryKey:o}=n.useEditorCardQuery(i),d=n.useQueryClient(),c=C.useRef(o);c.current=o;const{value:x,onChange:h,flush:v}=qn({storeValue:s,defaultValue:n.PYTHON_DEFAULT_CODE,onStoreUpdate:l,delay:or});return C.useEffect(()=>ft.registerPendingEditorDraftFlusher(v),[v]),e.jsx(t.CodeEditor,{value:x??"",onValueChange:h,language:"python",embedded:!0,flushGutter:!0,wrapLines:!0,onKeyDown:p=>{p.key==="Enter"&&p.shiftKey&&(p.preventDefault(),ft.flushPendingEditorDrafts(),setTimeout(()=>{d.removeQueries({queryKey:c.current,exact:!0}),u(!0)},0))}})}const cr=/\{\{-?\s*filters\s*\|\s*where\s*-?\}\}/i,dr=/\{\{-?\s*filters\s*\|\s*and\s*-?\}\}/i,ur=/\bwhere\b/i;function mr(s){return s!=null&&s.trim()?cr.test(s)||dr.test(s):!1}function xr(s){return!(s!=null&&s.trim())||mr(s)?null:ur.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 hr(s){const{request:a,mode:r="draft",currentSql:l,selectedTableName:u,selectedSchemaName:i,selectedDatabaseName:o}=s,d=[o?`Database: ${o}`:"",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"&&l?"Mode: Refine existing SQL. Keep the current query structure and only apply the requested changes unless the current query is invalid.":"Mode: Draft new SQL from the request.",d.length>0?`Context:
158
+ ${d.join(`
159
+ `)}`:"",l?r==="refine"?`Current SQL (must refine):
160
+ ${l}`:`Current SQL (revise if useful):
161
+ ${l}`:"",`User request:
162
+ ${a}`].filter(Boolean).join(`
163
+
164
+ `)}function pr(s){const{request:a,failedSql:r,errorMessage:l,errorCode:u,selectedDatabaseName:i,selectedSchemaName:o,selectedTableName:d,contextEntityLabels:c}=s,x=[i?`Database: ${i}`:"",o?`Schema: ${o}`:"",d?`Table: ${d}`:"",c.length>0?`Selected context entities: ${c.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.",x.length>0?`Context:
165
+ ${x.join(`
166
+ `)}`:"",`Original user request:
167
+ ${a}`,`Previous SQL draft:
168
+ ${r}`,`Validation failure${u?` (${u})`:""}:
169
+ ${l}`].filter(Boolean).join(`
170
+
171
+ `)}function fr(s,a){typeof window>"u"||window.dispatchEvent(new CustomEvent("semaphor:inline-query-writer",{detail:{event:s,...a,timestamp:Date.now()}}))}const os={runId:0,phase:"idle",attempt:0,activeStep:"",timelineSteps:[],lastValidation:null,finalOutcome:"idle",hasTools:!1};function gr(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 pn(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 fn(s){return s==="getTableColumns"?"Discovering columns":s==="getDomainRelationships"?"Resolving relationships":s==="getChartSQLSyntax"?"Reviewing SQL syntax":s==="getUserSql"?"Inspecting current query":"Analyzing context"}function br(s,a){return s===n.SELF_HEAL_TIMELINE_STEP&&a>0?`${n.SELF_HEAL_TIMELINE_STEP} ${a}/${n.MAX_SELF_HEAL_ATTEMPTS}`:s}function Wt(s){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`${s}-${crypto.randomUUID()}`:`${s}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function gn(s){var a;for(let r=s.length-1;r>=0;r-=1){const l=s[r];if(l.role!=="user")continue;const u=(a=l.metadata)==null?void 0:a.inlineRunToken;if(typeof u=="string"&&u.length>0)return u}}function jr(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 l=s.match(/```[\w-]*\s*([\s\S]*?)```/i);return l!=null&&l[1]?l[1].trim():/^(select|with|insert|update|delete)\b/i.test(a)?a:""}function bn(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 l=r.parts.length-1;l>=0;l-=1){const u=r.parts[l];if((u==null?void 0:u.type)!=="text"||typeof(u==null?void 0:u.text)!="string")continue;const i=jr(u.text);if(i)return i}}return""}function vr({currentSql:s,currentPython:a,selectedDatabaseName:r,selectedSchemaName:l,selectedTableName:u,onApplySql:i,onOpenFullAssistant:o}){var Ht,Qe;const{authToken:d,tokenProps:c}=n.useSemaphorContext(),x=(Ht=n.useDashboardQuery().data)==null?void 0:Ht.assistantProfileId,h=t.useEditorStore(W=>W.isDevMode),v=t.useEditorStore(W=>W.selectedConnectionId),p=t.useEditorStore(W=>{var ee;return(ee=W.card.dataSource)==null?void 0:ee.selectedEntities}),m=t.useAIInteractionStore(W=>W.currentAIContext.selectedEntities),g=m.length,{setCurrentAIContext:S}=t.useAIActions(),[f,N]=C.useState(""),[A,B]=C.useState(""),[w,I]=C.useState(""),[D,E]=C.useState("draft"),[y,M]=C.useState("draft"),[b,R]=C.useState(""),[k,F]=C.useState(!1),[O,j]=C.useState({status:"idle"}),[T,L]=C.useState(os),[V,z]=C.useState(!1),[_,P]=C.useState(()=>Wt("inline-query-session")),q=C.useRef(null),G=C.useRef(null),Q=C.useRef(null),U=C.useRef(0),J=C.useRef(0),X=C.useRef(Wt("inline-run-token")),se=C.useRef(_),ue=C.useRef(new Set),pe=C.useRef(new Map),xe=C.useRef(0),je=C.useRef(""),Pe=C.useRef(!1),Me=C.useRef(!1),te=C.useRef(os),fe=C.useRef(!1),ke=C.useRef(null),Be=C.useRef(()=>{}),ze=(Qe=c.apiServiceUrl)==null?void 0:Qe.replace(/\/$/,""),ce=ze?`${ze}/v1/sql/validate`:"/v1/sql/validate",ve=C.useCallback(W=>{L(ee=>{const Z=W(ee);return te.current=Z,Z})},[]),ye=C.useCallback((W,ee)=>{ve(Z=>Z.runId===W?ee(Z):Z)},[ve]),re=C.useCallback(W=>J.current===W&&!ue.current.has(W),[]),$=C.useCallback((W,ee,Z)=>{ye(W,ge=>{const oe=ge.timelineSteps.includes(ee)?ge.timelineSteps:[...ge.timelineSteps,ee];return{...ge,phase:(Z==null?void 0:Z.phase)||ge.phase,attempt:typeof(Z==null?void 0:Z.attempt)=="number"?Z.attempt:ge.attempt,activeStep:ee,timelineSteps:oe,finalOutcome:(Z==null?void 0:Z.finalOutcome)||ge.finalOutcome,hasTools:Z!=null&&Z.hasTools?!0:ge.hasTools}})},[ye]),H=C.useCallback(()=>{const W=J.current+1,ee=Wt("inline-run-token"),Z=Wt("inline-query-session");return J.current=W,X.current=ee,se.current=Z,P(Z),ue.current=new Set,pe.current=new Map,xe.current=0,je.current="",fe.current=!1,ve(()=>({runId:W,phase:"drafting",attempt:0,activeStep:"Drafting SQL",timelineSteps:["Drafting SQL"],lastValidation:null,finalOutcome:"drafting",hasTools:!1})),{runId:W,runToken:ee,chatSessionId:Z}},[ve]),ne=C.useCallback(()=>{if(Pe.current||Me.current||g>0)return;const W=p||[];if(W.length===0)return;const ee=t.useAIInteractionStore.getState().currentAIContext;S({...ee,selectedEntities:W}),Me.current=!0},[g,p,S]),he=C.useCallback(()=>{Pe.current=!0},[]),de=C.useCallback((W,ee,Z)=>{fr(W,{runId:ee,attemptCount:typeof(Z==null?void 0:Z.attemptCount)=="number"?Z.attemptCount:xe.current,errorCode:Z==null?void 0:Z.errorCode,hasTools:typeof(Z==null?void 0:Z.hasTools)=="boolean"?Z.hasTools:T.hasTools,entityCount:g,finalOutcome:(Z==null?void 0:Z.finalOutcome)||T.finalOutcome})},[g,T.finalOutcome,T.hasTools]),Te=C.useCallback((W,ee)=>{const Z=Q.current;if(!Z)return;const ge={inlineRunToken:ee};Z({role:"user",parts:[{type:"text",text:W}],metadata:ge},{metadata:ge})},[]);C.useEffect(()=>{const W=ke.current;!W||W.sessionId!==_||(ke.current=null,Te(W.message,W.runToken))},[_,Te]);const De=_,ae=C.useCallback(async({toolCall:W})=>{var Re,We,st,xt,Ve,Ct;if(De!==se.current)return;const ee=String(W.toolName||"").trim();if(!ee)return;const Z=J.current;if(!re(Z)){(Re=G.current)==null||Re.call(G,{tool:ee,toolCallId:W.toolCallId,output:{status:"error",message:"Inline run is no longer active; ignoring tool output."}});return}if(ee==="getUserSql"){$(Z,fn(ee),{hasTools:!0}),de("inline_tool_step",Z,{hasTools:!0}),(We=G.current)==null||We.call(G,{tool:ee,toolCallId:W.toolCallId,output:{status:"success",sql:s||"",python:a||""}});return}const ge=n.INLINE_BLOCKED_MUTATING_TOOLS.has(ee),oe=n.INLINE_ALLOWED_READ_ONLY_TOOLS.has(ee);if(ge||!oe){(st=G.current)==null||st.call(G,{tool:ee,toolCallId:W.toolCallId,output:{status:"error",message:"This action is unavailable in inline draft mode. Open Full Assistant for this action."}});return}const be=fn(ee);$(Z,be,{phase:T.phase==="self-healing"?"self-healing":"drafting",hasTools:!0}),de("inline_tool_step",Z,{hasTools:!0});const we=((xt=W.input)==null?void 0:xt.sql)??((Ve=W.args)==null?void 0:Ve.sql);typeof we=="string"&&we.trim().length>0&&(fe.current=!1,I(we.trim())),(Ct=G.current)==null||Ct.call(G,{tool:ee,toolCallId:W.toolCallId,output:{status:"success",message:"Read-only tool result received."}})},[a,s,de,T.phase,re,De,$]),Ee=C.useCallback(({message:W,messages:ee})=>{if(De!==se.current)return;const Z=gn(ee);if(!Z||Z!==X.current)return;const ge=J.current;if(!re(ge))return;const oe=bn([W])||bn(ee);if(oe){fe.current=!1,I(oe.trim());return}fe.current&&te.current.phase==="self-healing"&&Be.current(ge)},[re,De]),Fe=C.useCallback(W=>{if(De!==se.current)return;const ee=J.current;re(ee)&&fe.current&&te.current.phase==="self-healing"&&Be.current(ee)},[re,De]),{setMessages:Ne,sendMessage:Se,addToolResult:Ke,status:He,stop:le,error:Le,clearError:$e}=n.useChat({id:_,transport:new n.DefaultChatTransport({api:`${c.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${d==null?void 0:d.accessToken}`}),body:()=>{const W=t.useAIInteractionStore.getState();return{assistantId:"editor-assistant",assistantProfileId:x,isDevMode:h,aiContext:W.currentAIContext,reasoningEffort:W.reasoningEffort,showReasoning:!1}},credentials:"omit",prepareSendMessagesRequest:({messages:W,body:ee,requestMetadata:Z})=>{const ge=Z==null?void 0:Z.inlineRunToken,oe=gn(W);return{body:{...ee,inlineRunToken:ge||oe,messages:t.cleanupIncompleteMessages(W)}}}}),onToolCall:ae,onFinish:Ee,onError:Fe,sendAutomaticallyWhen:n.lastAssistantMessageIsCompleteWithToolCalls});G.current=Ke,Q.current=Se;const Ce=!["ready","error"].includes(He),Ze=(Le==null?void 0:Le.message)||"Unable to generate a SQL draft right now. Try again.",Ae=C.useCallback(W=>{const ee=J.current,Z=te.current.phase;if(!(Z==="drafting"||Z==="self-healing"||Z==="validating")){W==="stopped"&&Ce&&le();return}ue.current.add(ee),fe.current=!1,U.current+=1,je.current="",j({status:"idle"}),I(""),$e(),Ne([]),ye(ee,oe=>({...oe,phase:"idle",activeStep:"",finalOutcome:"cancelled"})),de("inline_self_heal_stopped",ee,{finalOutcome:"cancelled"}),(Ce||W==="stopped")&&le()},[$e,de,Ce,Ne,le,ye]),qt=C.useCallback(async(W,ee)=>{var ge;if(!re(ee))return null;const Z=U.current+1;U.current=Z,$(ee,"Validating SQL",{phase:"validating"}),j({status:"validating"});try{const oe=await t.postRequestRegular(ce,(d==null?void 0:d.accessToken)||"",{sql:W,connectionId:v||void 0});if(U.current!==Z||!re(ee))return null;if((oe==null?void 0:oe.valid)===!0)return j({status:"valid",message:"SQL validation passed."}),ye(ee,Re=>({...Re,phase:"ready",finalOutcome:"validated",lastValidation:{valid:!0}})),de("inline_draft_validated",ee,{finalOutcome:"validated"}),{status:"valid"};const be=gr(oe==null?void 0:oe.errorCode)||"UNKNOWN",we=typeof(oe==null?void 0:oe.error)=="string"&&oe.error||typeof((ge=oe==null?void 0:oe.details)==null?void 0:ge.error)=="string"&&oe.details.error||"SQL validation failed. Please revise the query draft.";return j({status:"invalid",message:we,errorCode:be}),ye(ee,Re=>({...Re,lastValidation:{valid:!1,error:we,errorCode:be}})),de("inline_validation_failed",ee,{errorCode:be,finalOutcome:"validation_failed"}),{status:"invalid",error:we,errorCode:be}}catch(oe){if(U.current!==Z||!re(ee))return null;const be=t.getRequestErrorMessage(oe,"Validation service unavailable. You can still replace and run.");return j({status:"error",message:be,errorCode:"SQL_CONNECTION_ERROR"}),ye(ee,we=>({...we,phase:"error",finalOutcome:"error",lastValidation:{valid:!1,error:be,errorCode:"SQL_CONNECTION_ERROR"}})),{status:"error",error:be,errorCode:"SQL_CONNECTION_ERROR"}}},[d==null?void 0:d.accessToken,de,re,v,ce,ye,$]),ct=C.useCallback((W,ee,Z,ge)=>{let oe=Z,be="validation_failed",we="Validating SQL";ee==="attempt_limit"?(oe=`Couldn't auto-fix after ${n.MAX_SELF_HEAL_ATTEMPTS} attempts. ${Z}`,be="self_heal_exhausted",we=`Auto-fix stopped (${n.MAX_SELF_HEAL_ATTEMPTS} attempts)`):ee==="duplicate"&&(oe=`Auto-fix stopped (repeated validation failure). ${Z}`,be="self_heal_duplicate_stopped",we="Auto-fix stopped (repeated failure)"),j({status:"invalid",message:oe,errorCode:ge}),$(W,we,{phase:"error",finalOutcome:be}),ye(W,Re=>({...Re,phase:"error",finalOutcome:be,lastValidation:{valid:!1,error:oe,errorCode:ge}})),ee!=="terminal"&&de("inline_self_heal_stopped",W,{errorCode:ge,finalOutcome:be}),fe.current=!1},[de,ye,$]),Et=C.useCallback(W=>{const ee="Auto-fix stopped (no SQL returned). Open Full Assistant to continue.",Z="self_heal_no_draft";j({status:"invalid",message:ee,errorCode:"UNKNOWN"}),$(W,"Auto-fix stopped (no SQL returned)",{phase:"error",finalOutcome:Z}),ye(W,ge=>({...ge,phase:"error",finalOutcome:Z,lastValidation:{valid:!1,error:ee,errorCode:"UNKNOWN"}})),de("inline_self_heal_stopped",W,{errorCode:"UNKNOWN",finalOutcome:Z}),fe.current=!1},[de,ye,$]);Be.current=Et,C.useEffect(()=>{const W=w.trim(),ee=J.current;if(!W){if(U.current+=1,je.current="",te.current.phase==="error")return;j({status:"idle"});return}if(!re(ee)||Ce)return;const Z=`${ee}:${xe.current}:${pn(W)}`;if(je.current===Z)return;je.current=Z;let ge=!1;return(async()=>{const be=await qt(W,ee);if(!be||ge||!re(ee)||be.status!=="invalid")return;if(!n.RECOVERABLE_SQL_ERROR_CODES.has(be.errorCode)){ct(ee,"terminal",be.error,be.errorCode);return}const we=`${pn(W)}::${be.errorCode}`,Re=(pe.current.get(we)||0)+1;if(pe.current.set(we,Re),Re>=2){ct(ee,"duplicate",be.error,be.errorCode);return}if(xe.current>=n.MAX_SELF_HEAL_ATTEMPTS){ct(ee,"attempt_limit",be.error,be.errorCode);return}const We=xe.current+1;xe.current=We,$(ee,n.SELF_HEAL_TIMELINE_STEP,{phase:"self-healing",attempt:We}),de("inline_self_heal_attempt",ee,{attemptCount:We,errorCode:be.errorCode}),fe.current=!0,$e(),Ne([]),I("");const st=m.map(Ve=>{const Ct=Ve!=null&&Ve.database?`${Ve.database}.`:"",Qt=Ve!=null&&Ve.schema?`${Ve.schema}.`:"",Rt=(Ve==null?void 0:Ve.name)||"unknown";return`${Ct}${Qt}${Rt}`}),xt=pr({request:A,failedSql:W,errorMessage:be.error,errorCode:be.errorCode,selectedDatabaseName:r||"",selectedSchemaName:l||"",selectedTableName:u||"",contextEntityLabels:st});Te(xt,X.current)})(),()=>{ge=!0}},[$e,m,de,Ce,re,A,w,r,l,u,Te,Ne,ct,$,qt]);const et=(s==null?void 0:s.trim())||"",Ue=C.useCallback((W="draft")=>{if(Ce)return;const ee=f.trim();if(!ee)return;const Z=W==="refine"&&et?"refine":"draft",ge=Z==="refine"?et:"",oe=et,{runId:be,runToken:we,chatSessionId:Re}=H();de("inline_draft_started",be,{attemptCount:0,hasTools:!1,finalOutcome:"drafting"}),ne(),$e(),B(ee),I(""),E(Z),R(ge),F(!1),j({status:"idle"}),U.current+=1,Ne([]),z(!0);const We=hr({request:ee,mode:Z,currentSql:oe,selectedTableName:u||"",selectedSchemaName:l||"",selectedDatabaseName:r||""});ke.current={sessionId:Re,message:We,runToken:we}},[H,$e,et,de,Ce,f,ne,r,l,u,Ne]),It=C.useCallback(W=>{const ee=w.trim();ee&&(i(ee,W),W||z(!1))},[i,w]),dt=w.trim().length>0,gt=["valid","invalid","error"].includes(O.status),Dt=dt&&gt,rt=O.status==="invalid",bt=O.status==="validating",kt=dt&&A.length>0&&A===f.trim(),At=et.length>0,$t=f.length>0,jt=kt&&D==="draft",ut=kt&&D==="refine"&&b===et,lt=y==="refine"&&!At?"draft":y,Lt=(lt==="refine"?ut:jt)?"Open composer preview":"Generate composer SQL",tt=f.trim().length>0||A.trim().length>0||dt||O.status!=="idle"||T.timelineSteps.length>0,Mt=C.useCallback((W="draft")=>{if(Ce)return;if((W==="refine"?ut:jt)&&!V){ne(),z(!0);return}Ue(W)},[jt,ut,Ue,Ce,V,ne]),Ft=C.useCallback(()=>{ne(),z(!0)},[ne]),mt=C.useCallback(W=>{Ae("cancelled"),N(W)},[Ae]),Gt=C.useCallback(()=>{Ce||(Ae("cancelled"),fe.current=!1,U.current+=1,je.current="",xe.current=0,N(""),B(""),I(""),E("draft"),M("draft"),R(""),F(!1),j({status:"idle"}),$e(),Ne([]),ve(W=>({...os,runId:W.runId})))},[Ae,$e,Ce,Ne,ve]),Ut=C.useCallback(W=>{W||Ae("cancelled"),z(W)},[Ae]),vt=T.timelineSteps.findIndex(W=>W===T.activeStep),ns=T.phase==="self-healing"?"Fixing validation issue":T.phase==="validating"?"Validating SQL":T.activeStep||"Drafting SQL",yt=O.status==="valid"?{label:"Validation passed",className:"border-emerald-500/30 bg-emerald-500/10 text-emerald-700",detail:O.message}:O.status==="invalid"?{label:"Validation failed",className:"border-destructive/40 bg-destructive/10 text-destructive",detail:O.message}:O.status==="error"?{label:"Validation unavailable",className:"border-border/60 bg-muted/20 text-muted-foreground",detail:O.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:f,onChange:W=>mt(W.target.value),onFocus:Ft,onClick:Ft,onKeyDown:W=>{W.key==="Enter"&&(W.preventDefault(),Mt(lt))},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",$t?"pr-[56px]":"pr-9"].join(" ")}),e.jsxs(t.Popover,{open:V,onOpenChange:Ut,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:[$t&&e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"size-6 p-0",onClick:W=>{W.preventDefault(),Ae("cancelled"),N("")},disabled:Ce,"aria-label":"Clear input",title:"Clear input",children:e.jsx(t.X,{className:"size-3.5"})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"size-6 p-0",onClick:W=>{W.preventDefault(),Mt(lt)},disabled:Ce,"aria-label":Lt,title:Lt,children:e.jsx(Ka,{className:"size-3.5"})})]}),e.jsx(t.PopoverContent,{align:"start",alignOffset:0,side:"bottom",sideOffset:8,className:"w-[min(92vw,var(--radix-popover-trigger-width))] max-w-[760px] p-2.5",onOpenAutoFocus:W=>{W.preventDefault()},onInteractOutside:W=>{var Z;const ee=W.target;ee&&((Z=q.current)!=null&&Z.contains(ee))&&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]",lt==="draft"?"bg-accent text-foreground":"text-muted-foreground hover:text-foreground"].join(" "),onClick:()=>{M("draft"),F(!1)},children:"Draft New"}),e.jsx(t.Button,{type:"button",variant:"ghost",className:["h-6 rounded-[4px] px-2 text-[12px]",lt==="refine"?"bg-accent text-foreground":"text-muted-foreground hover:text-foreground"].join(" "),onClick:()=>M("refine"),disabled:!At,children:"Refine"})]}),e.jsx(n.AssistantContextEntityControls,{mode:"full",compact:!0,inlineLayout:!0,inlineTriggerFirst:!0,triggerVariant:"outline",triggerIconOnly:!1,triggerLabel:"Context",onSelectionChange:he})]}),e.jsxs("div",{className:"flex shrink-0 items-center",children:[Ce&&e.jsx(t.Button,{variant:"ghost",size:"xs",onClick:()=>{Ae("stopped")},children:"Stop"}),!Ce&&e.jsx(t.Button,{variant:"ghost",size:"xs",onClick:Gt,disabled:!tt,children:"Clear"})]})]}),T.timelineSteps.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[T.timelineSteps.map((W,ee)=>{const Z=W===T.activeStep&&["drafting","validating","self-healing"].includes(T.phase),ge=!Z&&vt>=0&&ee<vt;return e.jsx("span",{className:["rounded-full border px-2 py-0.5 text-[11px]",Z?"border-foreground/30 bg-foreground/10 text-foreground":ge?"border-border/60 bg-muted/20 text-muted-foreground":"border-border/50 bg-background text-muted-foreground/80"].join(" "),children:br(W,T.attempt)},`${W}-${ee}`)}),yt&&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]",yt.className].join(" "),children:yt.label})}),e.jsx(t.TooltipContent,{side:"top",align:"start",className:"max-w-[680px] whitespace-pre-wrap break-words text-xs",children:yt.detail})]})})]}),(Ce||T.phase==="self-healing"||O.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"}),ns]}),Le&&e.jsx("div",{className:"rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-xs text-destructive",children:Ze}),D==="refine"&&b&&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:()=>F(W=>!W),children:k?"Hide base SQL":"View base SQL"})]}),k&&e.jsx("div",{className:"max-h-[120px] overflow-auto rounded-[5px] border border-border/60",children:e.jsx(t.CodeEditor,{value:b,onValueChange:()=>{},language:"sql",readOnly:!0,embedded:!0,wrapLines:!0,dense:!0,hideLineNumbers:!0,ariaLabel:"Base SQL"})})]}),Dt?e.jsxs("div",{className:"space-y-1",children:[D==="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:w,onValueChange:()=>{},language:"sql",readOnly:!0,embedded:!0,wrapLines:!0,dense:!0,hideLineNumbers:!0,ariaLabel:"Drafted SQL"})})]}):dt?e.jsx("div",{className:"rounded-[5px] border border-dashed border-border/70 px-3 py-2 text-[11px] text-muted-foreground",children:"Validating SQL draft before preview."}):!Ce&&e.jsx("div",{className:"rounded-[5px] border border-dashed border-border/70 px-3 py-2 text-[11px] text-muted-foreground",children:At?"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:o,children:"Open Full Assistant"}),e.jsx(t.Button,{variant:"secondary",size:"xs",disabled:Ce||!Dt,onClick:()=>It(!1),children:"Replace SQL"}),e.jsx(t.Button,{size:"xs",disabled:Ce||!Dt||bt||rt,onClick:()=>It(!0),children:"Replace & Run"})]})]})})]})]})}function yr(){var Pe,Me;const s=n.useQueryClient(),[a,r]=C.useState(!1),l=t.useEditorStore(te=>te.frame),u=t.useEditorStore(te=>te.card);t.useEditorStore(te=>te.isShowingVisual),t.useEditorStore(te=>te.selectedConnectionId),t.useEditorStore(te=>te.tempQueryData);const i=t.useEditorStore(te=>te.selectedDatabaseName);t.useEditorStore(te=>te.selectedDatamodelId);const o=t.useEditorStore(te=>te.selectedSchemaName);t.useEditorStore(te=>te.showAIDialog);const d=t.useEditorStore(te=>te.selectedTableName),c=t.useDashboardStore(te=>{var fe,ke;return((ke=(fe=te.dashboard)==null?void 0:fe.filters)==null?void 0:ke.length)??0}),x=t.useEditorStore(te=>te.inlineFilterValuesMap[(u==null?void 0:u.id)??""]),h=C.useMemo(()=>n.findCustomVisualConfigCard(l,u),[l,u]),{manifest:v}=n.useCustomVisual(((Pe=h==null?void 0:h.customCardPreferences)==null?void 0:Pe.url)||""),p=C.useMemo(()=>{var te;return(te=v==null?void 0:v.visuals)==null?void 0:te.find(fe=>{var ke;return fe.name===((ke=h==null?void 0:h.customCardPreferences)==null?void 0:ke.componentName)})},[v,(Me=h==null?void 0:h.customCardPreferences)==null?void 0:Me.componentName]),m=n.resolveMultiInputType(h,p),g=C.useMemo(()=>n.getCustomVisualInputCards({frame:l,configCard:h,isMultiInputVisual:m==="multiple"}),[l,h,m]),S=C.useMemo(()=>{const te=g.findIndex(fe=>(fe==null?void 0:fe.id)===(u==null?void 0:u.id));return te<0?-1:n.getSlotIndexForCard(u,te)},[g,u]),f=C.useMemo(()=>!h||m!=="multiple"||S<0?u.type:n.getEffectiveCardTypeForSlot(u,S,p==null?void 0:p.slots)??u.type,[h,m,S,u,p==null?void 0:p.slots]),N=C.useMemo(()=>f!==u.type?{...u,type:f}:u,[u,f]),A=C.useMemo(()=>c===0?null:xr(u==null?void 0:u.sql),[u==null?void 0:u.sql,c]),B=C.useRef(!0),{setCardCustomCfg:w,setQueryResultColumns:I,setCardSql:D,setTempQueryData:E,setPythonStdOut:y,setCardPreferences:M,setCardType:b,setCardPython:R,setShowAIDialog:k,setCard:F,updateCardInFrame:O}=t.useEditorActions();t.useEditorStore(te=>te.onSave),t.useEditorStore(te=>te.onClose),t.useEditorStore(te=>te.actions.setSqlGen);const j=t.useEditorStore(te=>te.runSql),T=t.useEditorStore(te=>te.actions.setRunSql),L=t.useEditorStore(te=>te.actions.setIsSqlRunning),{data:V,isLoading:z,isFetching:_,isSuccess:P,isError:q,error:G,errorSql:Q,queryKey:U,refetch:J,errorMessage:X}=n.useEditorCardQuery(N),se=C.useRef(U);se.current=U,C.useEffect(()=>{if(V&&(V.rowLimitExceeded&&n.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),y((V==null?void 0:V.output)||""),V.records.length>0)){const{dimensionKeys:te}=n.getKeys(V.records);I(te)}},[V,I,y]),C.useEffect(()=>{(z||_)&&L(!0),(q||P)&&L(!1),q&&(I([]),y(""))},[z,_,V,y,q,P,L,I,G]),C.useEffect(()=>{j&&(s.getQueryData(U)||J(),T(!1))},[j,J,T,U,s]);const ue=C.useRef(J);ue.current=J,C.useEffect(()=>{if(B.current){B.current=!1;return}ue.current()},[x]);function pe(te,fe){D(te),fe&&T(!0)}function xe(){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(lr,{})}),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:te=>{te.stopPropagation(),r(!1)},onPointerDown:te=>te.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(ir,{})})]})})]})]})}function je(){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 te;typeof navigator>"u"||!((te=navigator.clipboard)!=null&&te.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:z||_,onClick:()=>{ft.flushPendingEditorDrafts(),setTimeout(()=>{s.removeQueries({queryKey:se.current,exact:!0}),T(!0)},0)},className:"shrink-0",size:"xs",children:[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(Oe.EditorClearButton,{}),e.jsxs(n.Toggle,{pressed:a,onPressedChange:te=>r(te),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(vr,{currentSql:u==null?void 0:u.sql,currentPython:u==null?void 0:u.python,selectedDatabaseName:i,selectedSchemaName:o,selectedTableName:d,onApplySql:pe,onOpenFullAssistant:()=>k(!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:te=>F({...u,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:u})]}),e.jsx(n.EditableText,{value:(u.description||"").trim(),onSave:te=>F({...u,description:te.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:xe()}),je()]})}function Cr(s,a){var i;let r=0,l=0;const u=Math.min(s.length,50);for(let o=0;o<u;o++){const d=(i=s[o])==null?void 0:i[a];if(!(d==null||d==="")){if(l++,typeof d=="number"||typeof d=="bigint")r++;else if(typeof d=="boolean")return"boolean"}}return l===0?"null":r/l>.7?"number":"text"}function Nr(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 Sr({data:s,card:a,paginationMetadata:r,onPaginationChange:l,onPageSizePreferenceChange:u,onSortChange:i,isLoading:o}){var M,b,R,k,F,O;const d=C.useMemo(()=>Object.keys(s[0]??{}),[s]),c=a.sql&&!((b=(M=a.preferences)==null?void 0:M.tablePrefs)!=null&&b.enableDevModePagination)?(k=(R=a.preferences)==null?void 0:R.tablePrefs)==null?void 0:k.pageSize:void 0,x=C.useMemo(()=>{var j;return n.sortByColumnsToSortState((j=a.config)==null?void 0:j.sortByColumns)},[(F=a.config)==null?void 0:F.sortByColumns]),{canSort:h,canUseLocalSorting:v,handlePaginationChange:p,handleSortChange:m,pagination:g,paginationMode:S,sorting:f}=n.useTableQueryState({card:a,dataLength:s.length,onPaginationChange:l,onSortChange:i,pageSize:c,paginationMetadata:r,sortState:x}),N=C.useMemo(()=>f.filter(j=>d.includes(j.id)),[f,d]),A=C.useMemo(()=>{const j={};for(const T of d)j[T]=Cr(s,T);return j},[d,s]),B=C.useMemo(()=>d.map(j=>{const L=A[j]==="number";return{accessorKey:j,enableSorting:h,header:({column:V})=>{const z=V.getIsSorted();return e.jsxs("div",{className:t.cn("flex min-w-0 select-none items-center gap-1.5 transition-colors",V.getCanSort()&&"cursor-pointer hover:text-foreground",L&&"justify-end"),onClick:()=>V.getCanSort()&&V.toggleSorting(V.getIsSorted()==="asc"),children:[e.jsx("span",{className:"min-w-0 truncate",title:j,children:j}),z==="asc"?e.jsx(n.ArrowUpIcon,{className:"h-3.5 w-3.5 shrink-0 text-foreground"}):z==="desc"?e.jsx(n.ArrowDownIcon,{className:"h-3.5 w-3.5 shrink-0 text-foreground"}):V.getCanSort()?e.jsx(On.ChevronsUpDown,{className:"h-3 w-3 shrink-0 opacity-0 transition-opacity group-hover/header:opacity-50"}):null]})},cell:({getValue:V})=>{const z=V(),_=z===null;return e.jsx("div",{className:t.cn("overflow-hidden truncate whitespace-nowrap leading-5",L&&"text-right tabular-nums",_&&"text-muted-foreground/50 italic"),children:Nr(z)})}}}),[h,A,d]),w=Math.max(B.length,1),I=n.useReactTable({data:s,columns:B,getCoreRowModel:n.getCoreRowModel(),getPaginationRowModel:S==="client"?n.getPaginationRowModel():void 0,onSortingChange:m,getSortedRowModel:v?n.getSortedRowModel():void 0,onPaginationChange:S==="disabled"?void 0:p,manualPagination:S==="server"||S==="disabled",manualSorting:!v,pageCount:S==="server"&&r?r.pageCount:void 0,state:{sorting:N,pagination:g}}),D=S==="server"&&r?r.totalCount:s.length,E=S!=="disabled"&&(S==="server"||D>10),y=d.length>0?`${d.length*144}px`:"100%";return e.jsxs("div",{className:"relative flex h-full min-h-0 w-full flex-col",children:[o&&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:y},children:[e.jsx(n.TableHeader,{className:"sticky top-0 z-10 bg-muted [&_tr]:border-b-0",children:I.getHeaderGroups().map(j=>e.jsx(n.TableRow,{className:"border-b-0 hover:bg-transparent",children:j.headers.map(T=>{const V=A[T.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",V&&"text-right"),children:T.isPlaceholder?null:n.flexRender(T.column.columnDef.header,T.getContext())},T.id)})},j.id))}),e.jsx(n.TableBody,{children:(O=I.getRowModel().rows)!=null&&O.length?I.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(T=>{const V=A[T.column.id]==="number";return e.jsx(n.TableCell,{className:t.cn("overflow-hidden px-4 py-2 text-[13px] text-foreground/90",V&&"text-right"),children:n.flexRender(T.column.columnDef.cell,T.getContext())},T.id)})},j.id)):e.jsx(n.TableRow,{children:e.jsx(n.TableCell,{colSpan:w,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:d.length,pageCount:S==="server"&&r?r.pageCount:I.getPageCount(),pageIndex:I.getState().pagination.pageIndex,pageSize:I.getState().pagination.pageSize,rowCount:D,selectedRowCount:0,setPageIndex:I.setPageIndex,setPageSize:I.setPageSize,canPreviousPage:S==="server"&&r?r.hasPrevPage:I.getCanPreviousPage(),canNextPage:S==="server"&&r?r.hasNextPage:I.getCanNextPage(),previousPage:I.previousPage,nextPage:I.nextPage,onPageSizePreferenceChange:u,onClearSelection:()=>{},paginationMode:S,showExport:!1}):e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-[11px] tabular-nums text-muted-foreground",children:[D.toLocaleString()," ",D===1?"row":"rows"," · ",d.length," ",d.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 jn=[{value:"table",label:"Table"},{value:"aggregateTable",label:"Aggregate"},{value:"pivotTable",label:"Pivot"},{value:"detailTable",label:"Detail"}];function wr({className:s}){const a=t.useEditorStore(m=>m.card),r=t.useEditorStore(m=>m.frame),l=t.useEditorStore(m=>m.editorContext),u=Oe.useEffectiveEditorCardType(),{setCard:i,updateCardInFrame:o}=t.useEditorActions(),d=(l==null?void 0:l.type)==="documentSection"?jn.filter(m=>["table","pivotTable"].includes(m.value)):jn,c=["table","aggregateTable","pivotTable","detailTable"].includes(u),x=t.hasValidCardConfig(a.config),h=n.isCustomVisualConfigCard(a,r.cards);if(!c||!x||h)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 v=m=>{if(m===u||h)return;const g=m,S=a.config??{},f=p(u,g,S),N={...a,type:g,config:f};i(N),o(N)},p=(m,g,S)=>{var N;if(m===g)return S;if(g==="detailTable"){const A=D=>D==null?void 0:D.toLowerCase().replace(/\s+/g,"").trim(),B=(D,E)=>{const y=[A(D.label),A(D.qualifiedFieldName),A(D.name)].filter(Boolean),M=[A(E.label),A(E.qualifiedFieldName),A(E.name)].filter(Boolean);return y.some(b=>M.includes(b))},w=(S.groupByColumns||[]).map(D=>({...D,role:"detail"})),I=((N=S.sortByColumns)==null?void 0:N.filter(D=>w.some(E=>B(D,E))))??[];return{...S,detailTableBackup:{groupByColumns:S.groupByColumns,metricColumns:S.metricColumns,pivotByColumns:S.pivotByColumns,sortByColumns:S.sortByColumns,rowAggregates:S.rowAggregates,columnAggregates:S.columnAggregates,comparisonType:S.comparisonType},detailColumns:w,groupByColumns:[],metricColumns:[],pivotByColumns:[],sortByColumns:I,rowAggregates:[],columnAggregates:[],comparisonType:"none"}}let f=S;if(m==="detailTable")if(S.detailTableBackup)f={...S,...S.detailTableBackup,detailColumns:[],detailTableBackup:void 0};else{const A=(S.detailColumns||[]).map(B=>({...B,role:"groupby"}));f={...S,groupByColumns:A,detailColumns:[]}}return g==="aggregateTable"?{...f,pivotByColumns:[]}:f};return e.jsx("div",{role:"tablist",className:t.cn("flex items-center gap-5",s),children:d.map(m=>{const g=u===m.value;return e.jsx("button",{type:"button",role:"tab","aria-selected":g,onClick:()=>v(m.value),className:t.cn("-mb-px flex h-9 items-center border-b-2 text-[12px] transition-colors",g?"border-foreground font-medium text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),children:m.label},m.value)})})}const vn="text-[11px] text-muted-foreground underline-offset-2 hover:text-foreground hover:underline";function Cs({error:s,errorSql:a,errorTitle:r="Unable to load data",onOpenInEditor:l,onDebugWithAssistant:u,onSendFeedback:i,showFeedbackButton:o=!0,className:d}){const[c,x]=C.useState(!1),p=!!u||!!(l&&a);return e.jsxs("div",{className:t.cn("w-full space-y-3 rounded-[6px] border border-border/60 bg-card p-4",d),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(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(Oa,{className:"h-3.5 w-3.5"}),"Debug with Assistant"]}),l&&a&&e.jsxs(t.Button,{variant:"outline",size:"xs",onClick:l,children:[e.jsx(Vn,{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:()=>x(m=>!m),className:vn,children:c?"Hide query details":"Show query details"}),o&&i&&e.jsx("button",{type:"button",onClick:i,className:vn,children:"Report this issue"})]}),a&&e.jsx(n.Collapsible,{open:c,onOpenChange:x,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 $n(s,a){const r=t.useEditorStore(x=>x.card),l=t.useEditorStore(x=>x.isDevMode),{switchEditorMode:u,setRunSql:i,runAssistant:o}=t.useEditorActions();return{isDevMode:l,handleOpenInEditor:l?void 0:()=>{const x=a||r.sql||r.python||"";u("dev",{sqlToLoad:x}),setTimeout(()=>{i(!0)},100)},handleDebugWithAssistant:l?()=>{const x=`Can you help me debug this query?
172
+
173
+ Error:
174
+
175
+ ${s}
176
+
177
+ Error SQL:
178
+
179
+ ${a||r.sql||r.python}
180
+
181
+ `;o(x)}:void 0}}function Kn({className:s,style:a,...r}){var ne,he,de,Te,De;const l=t.useEditorStore(ae=>ae.card),u=n.useDashboardAppearance(),o=t.useEditorStore(ae=>ae.isDevMode)?!1:((ne=l.customCardPreferences)==null?void 0:ne.showCardHeader)??!0,d=((de=(he=l.preferences)==null?void 0:he.displayOptions)==null?void 0:de.showInlineFilterBar)??!0,c=t.useEditorStore(ae=>ae.frame),x=t.useEditorStore(ae=>ae.inlineFilterValuesMap[l.id]),h=t.useDashboardStore(ae=>ae.dashboard.filters),v=t.useDashboardStore(ae=>ae.selectedSheetId),[p,m]=C.useState(!1),{currentUser:g}=n.useCurrentUserInfo(),{tokenProps:S}=C.useContext(n.SemaphorContext),f=t.useEditorStore(ae=>ae.actions.setRunSql),N=t.useEditorStore(ae=>ae.actions.setCardInlineFilterValue),A=t.useEditorStore(ae=>ae.actions.removeCardInlineFilterValue),{updateFilter:B}=t.useDashboardActions(),w=h==null?void 0:h.find(ae=>ae.id===c.filterId),I=C.useMemo(()=>n.findCustomVisualConfigCard(c,l),[c,l]),{manifest:D}=n.useCustomVisual(((Te=I==null?void 0:I.customCardPreferences)==null?void 0:Te.url)||""),E=C.useMemo(()=>{var ae;return(ae=D==null?void 0:D.visuals)==null?void 0:ae.find(Ee=>{var Fe;return Ee.name===((Fe=I==null?void 0:I.customCardPreferences)==null?void 0:Fe.componentName)})},[D,(De=I==null?void 0:I.customCardPreferences)==null?void 0:De.componentName]),y=n.resolveMultiInputType(I,E),M=C.useMemo(()=>n.getCustomVisualInputCards({frame:c,configCard:I,isMultiInputVisual:y==="multiple"}),[c,I,y]),b=C.useMemo(()=>{const ae=M.findIndex(Ee=>(Ee==null?void 0:Ee.id)===(l==null?void 0:l.id));return ae<0?-1:n.getSlotIndexForCard(l,ae)},[M,l]),R=C.useMemo(()=>!I||y!=="multiple"||b<0?l.type:n.getEffectiveCardTypeForSlot(l,b,E==null?void 0:E.slots)??l.type,[I,y,b,l,E==null?void 0:E.slots]),k=R??l.type,F=C.useMemo(()=>k===l.type?l:{...l,type:k},[l,k]),O=F.type==="table"||F.type==="pivotTable"||F.type==="aggregateTable"||F.type==="detailTable",j=C.useMemo(()=>R!==l.type?{...l,type:R}:l,[l,R]),{data:T,isLoading:L,isFetching:V,errorMessage:z,errorSql:_,pagination:P}=n.useEditorCardQuery(j),{handleOpenInEditor:q,handleDebugWithAssistant:G}=$n(z,_||l.sql||l.python),Q=C.useMemo(()=>(T==null?void 0:T.records)||[],[T==null?void 0:T.records]),{setCard:U,updateCardInFrame:J}=t.useEditorActions(),{data:X}=n.useTopoJson(F),se=F.id,ue=F.config,pe=F.interactionConfig,xe=F.customCfg,je=F.preferences,Pe=F.queryConfig,Me=!!F.sql,te=T==null?void 0:T.records,fe=C.useMemo(()=>({id:se,type:k,config:ue,interactionConfig:pe,sql:Me?"__editor_sql__":""}),[se,k,ue,pe,Me]),ke=C.useMemo(()=>{var ae;return k!=="pivotTable"||!((ae=T==null?void 0:T.records)!=null&&ae.length)?null:{records:T.records,columnSubtotalMeta:T.columnSubtotalMeta,subtotalColumns:T.subtotalColumns||[],pivotSchema:T.pivotSchema||[],groupByColumns:T.groupByColumns}},[k,T==null?void 0:T.records,T==null?void 0:T.columnSubtotalMeta,T==null?void 0:T.subtotalColumns,T==null?void 0:T.pivotSchema,T==null?void 0:T.groupByColumns]),Be=n.usePivotTableConfig(F,ke),ze=()=>{m(!0)},ce=C.useMemo(()=>{const ae=typeof window<"u"?window.location.href:"",Ee=typeof navigator<"u"?navigator.userAgent:"",Fe=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:n.FeedbackCategory.QUERY_GENERATION,user:g,tokenContext:S,systemState:{cardConfig:l.config,dataSource:l.dataSource,dashboardFilters:h,errorMessage:z||void 0,errorSql:_||l.sql||l.python,generatedSql:_||l.sql},metadata:{url:ae,userAgent:Ee,timestamp:new Date().toISOString(),viewport:Fe}}},[g,S,l,h,z,_]),ve=(ae,Ee)=>{var Ne,Se;const Fe={...l,paginationConfig:{page:ae+1,pageSize:Ee}};U(Fe),J(Fe),l.sql&&((Se=(Ne=l.preferences)==null?void 0:Ne.tablePrefs)!=null&&Se.enableDevModePagination)&&f(!0)},ye=ae=>{var Ne,Se,Ke,He,le;const Ee=n.sortStateToSortByColumns(ae,(Ne=l.config)==null?void 0:Ne.metricColumns,(Se=l.config)==null?void 0:Se.groupByColumns,(Ke=l.config)==null?void 0:Ke.detailColumns),Fe={...l,config:{...l.config||{},sortByColumns:Ee}};U(Fe),J(Fe),l.sql&&((le=(He=l.preferences)==null?void 0:He.tablePrefs)!=null&&le.enableDevModePagination)&&f(!0)},re=C.useMemo(()=>!se||!te?null:n.createChartConfig({card:fe,data:te,cardType:k,queryConfig:Pe,customCfg:xe,preferences:je,topoJson:X}),[fe,se,xe,je,Pe,te,k,X]);function $(ae){return e.jsx(n.ErrorBoundary,{FallbackComponent:n.FallbackVisual,children:e.jsx(n.EditorCustomVisual,{card:ae})})}function H(){var ae;if(T!=null&&T.records&&(T==null?void 0:T.records.length)===0&&!L&&!V)return z?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(Cs,{error:z,errorSql:_||l.sql||l.python,onOpenInEditor:q,onDebugWithAssistant:G,onSendFeedback:ze,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((L||V)&&(!(T!=null&&T.records)||T.records.length===0))return k==="table"||k==="detailTable"?e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(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(!F.id)return null;if(k==="custom")return $(l);if(!["table","pivotTable","aggregateTable","detailTable","custom"].includes(k)&&re)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:L||V?e.jsx(e.Fragment,{}):e.jsx(n.ChartJsVisual,{cfg:re})});if(k==="table"||k==="detailTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(n.TableVisual,{card:F,data:Q,totalsByColumnId:T==null?void 0:T.tableTotalsByColumnId,comparisonMetadata:(ae=T==null?void 0:T.metadata)==null?void 0:ae.comparisonMetadata,paginationMetadata:P,onPaginationChange:ve,onSortChange:ye,isLoading:L||V})});if(k==="pivotTable"&&Be)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(n.PivotTableTanstack,{card:F,data:Be.data,options:Be.options,onAggregationChange:Ee=>{const Fe=n.handleAggregationChange(Ee,l.config),Ne={...l,config:Fe};U(Ne),J(Ne)},onAggregationLabelChange:Ee=>{const Fe=n.handleAggregationLabelChange(Ee,l.config),Ne={...l,config:Fe};U(Ne),J(Ne)}})});if(k==="aggregateTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(n.AggregateTable,{card:F,data:(T==null?void 0:T.records)||[],groupByColumns:T==null?void 0:T.groupByColumns,pivotSchema:T==null?void 0:T.pivotSchema,paginationMetadata:P,onPaginationChange:ve,onAggregationChange:Ee=>{const Fe=n.handleAggregationChange(Ee,l.config),Ne={...l,config:Fe};U(Ne),J(Ne)},isLoading:L||V})})}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:[(L||V)&&(T==null?void 0:T.records)&&T.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"})}),o&&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:l.title,onSave:ae=>U({...l,title:ae}),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:l}),e.jsx(Oe.VisualBadge,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(wr,{})})]}),e.jsx("div",{className:"min-w-0",children:e.jsx(n.EditableText,{value:(l.description||"").trim(),onSave:ae=>U({...l,description:ae.trim()}),isEditable:!0,placeholder:"Add description",displayClassName:"text-[12px] leading-snug text-muted-foreground",inputClassName:"text-[12px] leading-snug"})})]}),w&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Label,{className:"my-1",children:e.jsx(n.EditableText,{value:w.title||w.column,onSave:ae=>B({...w,title:ae}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(n.FilterComponent,{filter:w})]})]}),d&&l.inlineFilters&&l.inlineFilters.length>0&&e.jsx("div",{className:"px-4 pb-2",style:u.cardGutterStyle,children:e.jsx(n.InlineFilterBar,{card:l,sheetId:v||"",inlineFilterValues:x,setInlineFilterValue:ae=>N(l.id,ae),removeInlineFilterValue:ae=>A(l.id,ae)})}),e.jsxs(n.CardContent,{className:t.cn("flex min-h-0 grow flex-col",O?"p-0 [&_.data-table-scroll-container]:border-0 [&_.data-table-scroll-container]:bg-transparent":"px-4"),style:O?void 0:u.cardGutterStyle,children:[e.jsx("div",{className:"min-h-0 flex-1 grow basis-0",children:H()}),n.isCardSummaryVisibleOnCard(F)&&e.jsx("div",{className:t.cn("pt-3",O&&"px-4"),children:e.jsx(n.CardSummary,{card:F,mode:"editor"})})]}),e.jsx(n.FeedbackDialog,{open:p,onOpenChange:m,feedbackData:ce,showDebugInfo:!0})]})}const is=({language:s,value:a,onChange:r,readonly:l})=>e.jsx(t.CodeEditor,{className:"h-full w-full text-xs",language:s,value:a,onValueChange:r,readOnly:l,embedded:!0}),Tr=()=>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."})]})]}),Er=({customCode:s,cardCustomCfgString:a,mergedConfig:r,onConfigChange:l,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(is,{language:"json",value:r,onChange:l})}),e.jsx(t.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(is,{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(is,{language:"javascript",value:s,onChange:u})})]}),Ir=({error:s,hasCardCustomConfig:a,onReset:r,onApply:l,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:l,variant:"outline",children:"Apply"}),e.jsx(t.Button,{onClick:u,variant:"outline",children:"Close"})]});function Dr({triggerVariant:s="icon",className:a,label:r="Customize Visual"}={}){const[l,u]=C.useState(!1),[i,o]=C.useState(""),[d,c]=C.useState(""),[x,h]=C.useState(""),[v,p]=C.useState(""),m=t.useEditorStore(b=>b.card),g=Oe.useEffectiveEditorCardType(),S=t.useEditorStore(b=>b.card.customCfg),f=S?JSON.stringify(S,null,2):"",N=C.useMemo(()=>g!==m.type?{...m,type:g}:m,[m,g]),{data:A}=n.useEditorCardQuery(N),{data:B}=n.useTopoJson(m),{setCardCustomCfg:w,setCustomVisualCode:I}=t.useEditorActions(),D=b=>{var R,k;return JSON.stringify({...b,data:{...b.data,datasets:(k=(R=b.data)==null?void 0:R.datasets)==null?void 0:k.map(F=>({...F,data:[]}))}},null,2)},E=()=>{var R,k;if(!((R=A==null?void 0:A.records)!=null&&R.length))return;const b=n.createChartConfig({card:m,data:A.records,cardType:m.type,queryConfig:m.queryConfig,preferences:m.preferences,topoJson:B});if(b){o(D(b)),h(((k=m.preferences)==null?void 0:k.customVisualCode)||"");const F=n.merge(b,S);c(D(F))}},y=()=>{try{if(x&&I(x),d){const b=JSON.parse(d),R=n.getObjectDiff(JSON.parse(i),b);w(R),p("")}}catch{p("Invalid JSON configuration")}},M=Object.keys(S||{}).length===0;return e.jsxs(n.Dialog,{open:l,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",M?"":"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(M?"":"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(Tr,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(n.ErrorBoundary,{FallbackComponent:n.FallbackVisual,children:e.jsx(Kn,{className:"w-1/2 rounded shadow-none"})}),e.jsx(Er,{customCode:x,cardCustomCfgString:f,mergedConfig:d,onConfigChange:b=>c(b??""),onCodeChange:b=>h(b??"")})]}),e.jsx(Ir,{error:v,hasCardCustomConfig:!!S,onReset:()=>{c(i),w(null)},onApply:y,onClose:()=>u(!1)})]})]})}function kr(s){let a=0;for(let l=0;l<s.length;l++)a=s.charCodeAt(l)+((a<<5)-a);return`hsl(${Math.abs(a%360)}, 65%, 45%)`}function Ar(s){const a=s.trim().split(/\s+/);return a.length>1?(a[0][0]+a[1][0]).toUpperCase():s.slice(0,2).toUpperCase()}function Ns({chartType:s,chartName:a,isCustom:r=!1,className:l="h-6 w-6"}){if(!r&&s)return n.getChartIconByType(s,l);const u=n.getAutoDetectedChartIcon(a);if(u)return C.cloneElement(u,{className:l});const i=Ar(a),o=kr(a);return e.jsx("div",{className:t.cn("flex items-center justify-center rounded text-white font-semibold text-xs",l),style:{backgroundColor:o},children:i})}function Lr({isStarred:s,onClick:a,className:r}){const l=u=>{u.stopPropagation(),u.preventDefault(),a(u)};return e.jsx("button",{type:"button",onClick:l,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 yn({chartType:s,chartName:a,isCustom:r=!1,pluginName:l,isStarred:u,showStar:i=!0,isSelected:o=!1,onSelect:d,onToggleStar:c}){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(Lr,{isStarred:u,onClick:()=>c()})}),r&&l&&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:l})]})}),e.jsxs("button",{type:"button",onClick:d,"aria-pressed":o,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",o&&"border-foreground/50 bg-muted/50 hover:border-foreground/50"),children:[e.jsx(Ns,{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})]})]})}const Cn=[{id:"table",name:"Table"},{id:"bar",name:"Bar Chart"},{id:"line",name:"Line Chart"},{id:"area",name:"Area Chart"},{id:"combo",name:"Combo Chart"},{id:"stackedBar",name:"Stacked Bar"},{id:"stackedArea",name:"Stacked Area"},{id:"stackedLine",name:"Stacked Line"},{id:"scatter",name:"Scatter"},{id:"bubble",name:"Bubble"},{id:"pie",name:"Pie Chart"},{id:"doughnut",name:"Doughnut"},{id:"funnel",name:"Funnel"},{id:"radar",name:"Radar"},{id:"polarArea",name:"Polar Area"},{id:"tornado",name:"Tornado"},{id:"range",name:"Range"},{id:"bullet",name:"Bullet Chart"},{id:"treemap",name:"Treemap"},{id:"heatmap",name:"Heatmap"},{id:"kpi",name:"KPI"},{id:"text",name:"Text"},{id:"map",name:"Map"}];function Gn({onChartSelect:s,onClose:a}){const[r,l]=C.useState(""),{starredCharts:u,isStarred:i,toggleStar:o}=n.useStarredChartsStore(),{data:d=[],isLoading:c}=n.useCustomVisualsQuery(),{setCardType:x,setCardPreferences:h,setIsDevMode:v}=t.useEditorStore(b=>b.actions),p=t.useEditorStore(b=>b.card),{setCardCustomCfg:m,setCustomCardPreferences:g,setVisualizationMode:S,setQueryConfig:f,replaceFrameCards:N,clearModeDrafts:A,initializeModeDrafts:B}=t.useEditorActions(),w=C.useMemo(()=>{if(!r)return Cn;const b=r.toLowerCase();return Cn.filter(R=>R.name.toLowerCase().includes(b))},[r]),I=C.useMemo(()=>{const b=d.filter(k=>k.componentType==="chart"&&k.pluginType!=="standard");if(!r)return b;const R=r.toLowerCase();return b.filter(k=>k.name.toLowerCase().includes(R))},[d,r]),D=b=>{m(null),h({}),S("builtin"),x(b),["custom","text","map"].includes(b)&&(v(!0),f(void 0)),s==null||s(b),a==null||a()},E=b=>{m(null),h({}),S("builtin"),f(void 0);const R=n.resolveMultiInputTypeFromVisual(b);if(R==="multiple"&&b.slots&&b.slots.length>0){A();const F=n.createCardsFromSlots(b.slots,b,p);N(F),F[0]&&B(F[0]),a==null||a();return}else x("custom"),g({type:"component",visualType:R,url:b.url,componentName:b.name,icon:b.icon,pluginChartType:b.chartType,minInputs:b.minInputs,maxInputs:b.maxInputs});s==null||s("custom",b),a==null||a()},y=b=>{const R={type:"default",id:b.id,name:b.name};o(R)},M=b=>{const R={type:"custom",id:b.name,url:b.url,icon:b.icon,name:b.name};o(R)};return e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"mb-2 flex h-7 items-center gap-1.5 rounded-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:b=>l(b.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:[w.length>0&&e.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:w.map(b=>e.jsx(yn,{chartType:b.id,chartName:b.name,isCustom:!1,isStarred:i("default",b.id),onSelect:()=>D(b.id),onToggleStar:()=>y(b)},b.id))}),I.length>0&&e.jsxs(e.Fragment,{children:[w.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((b,R)=>e.jsx(yn,{chartName:b.name,isCustom:!0,pluginName:b.pluginName,isStarred:i("custom",b.name),onSelect:()=>E(b),onToggleStar:()=>M(b)},`${b.url}-${b.name}-${R}`))})]}),c&&e.jsx("div",{className:"mt-3 py-4 text-center text-[11px] text-muted-foreground",children:"Loading custom charts…"}),w.length===0&&I.length===0&&!c&&e.jsx("div",{className:"py-8 text-center text-[11px] text-muted-foreground",children:"No charts found"})]})]})}function Mr({selectedChart:s,onChartChange:a}){var D,E,y,M;const r=t.useEditorStore(b=>b.card),l=t.useEditorStore(b=>b.frame),u=t.useEditorStore(b=>b.isDevMode),{replaceFrameCards:i,clearModeDrafts:o,initializeModeDrafts:d,setIsDevMode:c}=t.useEditorActions(),x=C.useMemo(()=>n.findCustomVisualConfigCard(l,r),[l,r]),{manifest:h}=n.useCustomVisual(((D=x==null?void 0:x.customCardPreferences)==null?void 0:D.url)||""),v=C.useMemo(()=>{var b;return(b=h==null?void 0:h.visuals)==null?void 0:b.find(R=>{var k;return R.name===((k=x==null?void 0:x.customCardPreferences)==null?void 0:k.componentName)})},[h,(E=x==null?void 0:x.customCardPreferences)==null?void 0:E.componentName]),p=n.resolveMultiInputType(x,v)==="multiple",m=Oe.useEffectiveEditorCardType(),g=p?m:s??r.type,S=(y=r==null?void 0:r.customCardPreferences)==null?void 0:y.componentName,f=(M=x==null?void 0:x.customCardPreferences)==null?void 0:M.componentName,N=p&&!!f,A=C.useMemo(()=>{const b=n.chartTypes.find(R=>R.id===g);return b?b.label:g==="custom"?S||"Custom Visual":"Select chart type"},[g,S]),B=C.useMemo(()=>{const b=n.chartTypes.find(R=>R.id===g);if(b){const R=b.icon;return e.jsx(R,{className:"h-4 w-4"})}if(g==="custom"&&S){const R=n.getAutoDetectedChartIcon(S);return R||e.jsx(Ns,{chartName:S,isCustom:!0,className:"h-4 w-4"})}return e.jsx(Ga,{className:"h-4 w-4"})},[g,S]);return{displayChartType:g,displayLabel:A,displayIcon:B,showBadge:N,badgeLabel:f,isMultiInputContext:p,handleChartSelect:b=>{a==null||a(b)},handleClearCustomVisual:b=>{b.stopPropagation();const R={...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([R]),o(),d(R),u&&c(!0),a==null||a("bar")}}}function Fr({selectedChart:s,onChartChange:a,variant:r="ghost",className:l}){const[u,i]=C.useState(!1),{displayLabel:o,displayIcon:d,showBadge:c,badgeLabel:x,handleChartSelect:h,handleClearCustomVisual:v}=Mr({selectedChart:s,onChartChange:a}),p=r==="header";return e.jsxs("div",{className:t.cn("relative w-full",l),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:[d,e.jsx("span",{className:"truncate text-[12px] font-medium text-foreground",children:o})]}),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:[d,e.jsx("span",{className:"truncate",children:o})]}),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(Gn,{onChartSelect:m=>h(m),onClose:()=>i(!1)})})]}),c&&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:x,children:[e.jsx(n.Layers,{className:"h-2.5 w-2.5 shrink-0"}),e.jsx("span",{className:"truncate",children:x}),e.jsx("button",{onClick:v,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 wt={table:t.Table2,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},zt={table:"Table",bar:"Bar Chart",line:"Line Chart",stackedBar:"Stacked Bar",stackedLine:"Stacked Line",scatter:"Scatter",bubble:"Bubble",pie:"Pie Chart",doughnut:"Donut",kpi:"KPI",treemap:"Treemap",bullet:"Bullet",funnel:"Funnel",tornado:"Tornado",heatmap:"Heatmap",range:"Range",radar:"Radar",polarArea:"Polar Area",text:"Text",map:"Map"},Un=[{id:"table"},{id:"bar"},{id:"line"},{id:"pie"},{id:"kpi"},{id:"doughnut"}],Hn=6;function Rr({selectedChart:s,onChartChange:a}){var A,B;const[r,l]=C.useState(!1),u=t.useEditorStore(w=>w.card),{setCardType:i,setCardPreferences:o}=t.useEditorStore(w=>w.actions),{setCardCustomCfg:d,setCustomCardPreferences:c,setQueryConfig:x,replaceFrameCards:h,clearModeDrafts:v,initializeModeDrafts:p}=t.useEditorActions(),{starredCharts:m}=n.useStarredChartsStore(),{data:g=[]}=n.useCustomVisualsQuery(),S=C.useMemo(()=>{const w=m.filter(y=>y.type==="default"?!0:g.some(M=>M.name===y.id)),I=new Set(w.map(y=>y.id)),D=Un.filter(y=>!I.has(y.id));return[...w.map(y=>({id:y.id,label:y.name,icon:y.type==="default"?wt[y.id]:void 0,isCustom:y.type==="custom",url:y.url})),...D.map(y=>({id:y.id,label:zt[y.id]??y.id,icon:wt[y.id],isCustom:!1}))].slice(0,Hn)},[m,g]),f=s==="custom"&&((A=u==null?void 0:u.customCardPreferences)==null?void 0:A.componentName);return S.some(w=>{var I;return w.isCustom?f&&((I=u==null?void 0:u.customCardPreferences)==null?void 0:I.componentName)===w.id:s===w.id})||(s==="custom"?(B=u==null?void 0:u.customCardPreferences)!=null&&B.componentName:zt[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(Qn,{selectedChart:s,onChartChange:a,compactMore:!0})]})}function Qn({selectedChart:s,onChartChange:a,compactMore:r=!1}){var D,E;const[l,u]=C.useState(!1),i=t.useEditorStore(y=>y.card),{setCardType:o,setCardPreferences:d}=t.useEditorStore(y=>y.actions),{setCardCustomCfg:c,setCustomCardPreferences:x,setQueryConfig:h,replaceFrameCards:v,clearModeDrafts:p,initializeModeDrafts:m}=t.useEditorActions(),{starredCharts:g}=n.useStarredChartsStore(),{data:S=[]}=n.useCustomVisualsQuery(),f=((D=i==null?void 0:i.customCardPreferences)==null?void 0:D.componentName)??null,N=C.useMemo(()=>{const y=g.filter(F=>F.type==="default"?!0:S.some(O=>O.name===F.id)),M=new Set(y.map(F=>F.id)),b=Un.filter(F=>!M.has(F.id)),R=[...y.map(F=>({id:F.id,label:F.name,icon:F.type==="default"?wt[F.id]:void 0,isCustom:F.type==="custom",url:F.url})),...b.map(F=>({id:F.id,label:zt[F.id]??F.id,icon:wt[F.id],isCustom:!1}))];if(!R.some(F=>F.isCustom?s==="custom"&&F.id===f:F.id===s))if(s==="custom"&&f){const F=S.find(O=>O.name===f);F&&R.unshift({id:F.name,label:F.name,icon:void 0,isCustom:!0,url:F.url})}else s&&wt[s]&&R.unshift({id:s,label:zt[s]??s,icon:wt[s],isCustom:!1});return R.slice(0,Hn)},[g,S,s,f]),A=s==="custom"&&f,B=y=>{if(y.isCustom){const M=S.find(k=>k.name===y.id);if(!M)return;c(null),d({}),h(void 0);const b=n.resolveMultiInputTypeFromVisual(M);if(b==="multiple"&&M.slots&&M.slots.length>0){p();const k=n.createCardsFromSlots(M.slots,M,i);v(k),k[0]&&m(k[0]);return}o("custom"),x({type:"component",visualType:b,url:M.url,componentName:M.name,icon:M.icon,pluginChartType:M.chartType,minInputs:M.minInputs,maxInputs:M.maxInputs}),a("custom");return}a(y.id)},w=N.some(y=>{var M;return y.isCustom?A&&((M=i==null?void 0:i.customCardPreferences)==null?void 0:M.componentName)===y.id:s===y.id}),I=w?"More":s==="custom"?((E=i==null?void 0:i.customCardPreferences)==null?void 0:E.componentName)||"Custom":zt[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:N.map(y=>{var R;const M=y.icon,b=y.isCustom?A&&((R=i==null?void 0:i.customCardPreferences)==null?void 0:R.componentName)===y.id:s===y.id;return e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>B(y),"aria-label":y.label,"aria-pressed":!!b,className:t.cn("flex h-full w-7 items-center justify-center text-foreground/65 transition-colors hover:bg-muted/50 hover:text-foreground",b&&"bg-foreground/[0.08] font-medium text-foreground"),children:[M?e.jsx(M,{className:"h-3.5 w-3.5"}):e.jsx(Ns,{chartName:y.label,isCustom:!0,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"sr-only",children:y.label})]})}),e.jsx(t.TooltipContent,{side:"bottom",children:y.label})]},`${y.isCustom?"custom":"default"}-${y.id}`)})}),e.jsxs(t.Popover,{open:l,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&&(w?"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",l&&"rotate-180"),strokeWidth:1.75})]})}),e.jsx(t.PopoverContent,{className:"w-[360px] p-3",align:"end",onOpenAutoFocus:y=>y.preventDefault(),children:e.jsx(Gn,{onChartSelect:y=>{a(y),u(!1)},onClose:()=>u(!1)})})]})]})}function Or(){const s=t.useEditorStore(c=>{var x,h;return(h=(x=c.card.preferences)==null?void 0:x.chartOptions)==null?void 0:h.indexAxis}),a=t.useEditorStore(c=>c.card.type),{setChartOrientation:r,setCardPreferences:l}=t.useEditorStore(c=>c.actions),u=c=>{if(r(c),a!=="bullet")return;const x=c==="y"?"horizontal":"vertical",h=t.useEditorStore.getState().card.preferences,v={...h||{},bulletConfig:{...(h==null?void 0:h.bulletConfig)||{},orientation:x}};l(v)};function i(){const c=s??"x",x=()=>{u(c==="x"?"y":"x")};return e.jsx(n.IconButton,{onClick:x,tooltip:"Chart Orientation",className:"h-7 w-7 px-0",children:c==="x"?e.jsx(rs,{className:"h-3.5 w-3.5"}):e.jsx(as,{className:"h-3.5 w-3.5"})})}function o(){const c=()=>{u(s==="y"||s===void 0?"x":"y")};return e.jsx(n.IconButton,{onClick:c,tooltip:"Chart Orientation",className:"h-7 w-7 px-0",children:s==="y"||s===void 0?e.jsx(rs,{className:"h-3.5 w-3.5"}):e.jsx(as,{className:"h-3.5 w-3.5"})})}function d(){const c=s??"y",x=()=>{u(c==="y"?"x":"y")};return e.jsx(n.IconButton,{onClick:x,tooltip:"Chart Orientation",className:"h-7 w-7 px-0",children:c==="y"?e.jsx(as,{className:"h-3.5 w-3.5"}):e.jsx(rs,{className:"h-3.5 w-3.5"})})}return e.jsx(e.Fragment,{children:a==="funnel"?o():a==="bullet"?d():i()})}function Ss({className:s,triggerVariant:a="icon",label:r="Display Options"}){var S,f,N,A,B,w,I,D,E,y;const l=t.useEditorStore(M=>M.card),{setCardPreferences:u,updateCardInFrame:i,setCard:o}=t.useEditorActions(),[d,c]=C.useState(!1),x=((f=(S=l.preferences)==null?void 0:S.displayOptions)==null?void 0:f.showFilterInfo)??!0,h=((A=(N=l.preferences)==null?void 0:N.displayOptions)==null?void 0:A.showCardToolbar)??!0,v=((w=(B=l.preferences)==null?void 0:B.displayOptions)==null?void 0:w.showChrome)??!0,p=((D=(I=l.preferences)==null?void 0:I.displayOptions)==null?void 0:D.allowScroll)??!0,m=((y=(E=l.preferences)==null?void 0:E.displayOptions)==null?void 0:y.showInlineFilterBar)??!0,g=(M,b)=>{var F;const R={...l.preferences,displayOptions:{...(F=l.preferences)==null?void 0:F.displayOptions,[M]:b}};u(R);const k={...l,preferences:R};o(k),i(k)};return e.jsx("div",{className:t.cn("flex items-center",s),children:e.jsxs(n.DropdownMenu,{modal:!1,open:d,onOpenChange:c,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:x,onCheckedChange:M=>{g("showFilterInfo",M)},onSelect:M=>M.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Filter Info"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Badge"})]}),e.jsxs(n.DropdownMenuCheckboxItem,{checked:h,onCheckedChange:M=>{g("showCardToolbar",M)},onSelect:M=>M.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Toolbar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Hover actions"})]}),e.jsxs(n.DropdownMenuCheckboxItem,{checked:v,onCheckedChange:M=>{g("showChrome",M)},onSelect:M=>M.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Chrome"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Frame & padding"})]}),e.jsxs(n.DropdownMenuCheckboxItem,{checked:p,onCheckedChange:M=>{g("allowScroll",M)},onSelect:M=>M.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Allow Scroll"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card content scroll"})]}),e.jsxs(n.DropdownMenuCheckboxItem,{checked:m,onCheckedChange:M=>{g("showInlineFilterBar",M)},onSelect:M=>M.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Inline Filter Bar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card filters"})]})]})]})})}function ws({className:s,triggerVariant:a="icon",label:r="Inline Filters"}){var I,D,E;const[l,u]=C.useState(!1),i=t.useEditorStore(y=>y.card),o=t.useEditorStore(y=>y.selectedConnectionId),{tokenProps:d}=n.useSemaphorContext(),{setCard:c}=t.useEditorActions(),x=t.useDashboardStore(y=>y.actions.removeCardInlineFilterValue),h=t.useDashboardStore(y=>y.actions.setCardInlineFilterValue),v=t.useEditorStore(y=>y.actions.removeCardInlineFilterValue),p=t.useEditorStore(y=>y.actions.setCardInlineFilterValue),m=t.useDashboardStore(y=>y.isVisualEditing),g=(i==null?void 0:i.inlineFilters)||[],S=((D=(I=d==null?void 0:d.params)==null?void 0:I.calendarContext)==null?void 0:D.tz)||((E=d==null?void 0:d.params)==null?void 0:E.timezone)||Intl.DateTimeFormat().resolvedOptions().timeZone;function f(y){var _,P,q,G,Q,U,J;const M=((q=(P=(_=i==null?void 0:i.dataSource)==null?void 0:_.selectedEntities)==null?void 0:P[0])==null?void 0:q.database)||"",b=y.qualifiedFieldName||y.name;if(g.find(X=>n.doesStoredFilterMatchField(X,y)))return;const k=y.qualifiedFieldName?y.qualifiedFieldName.split(".").slice(0,-1).join("."):y.qualifiedEntityName||y.entityName,O=t.fmt(y.name),j=n.buildFilterFieldMeta(y),T=n.buildFilterSemanticContext(i==null?void 0:i.dataSource,{connectionId:o||((G=i==null?void 0:i.dataSource)==null?void 0:G.connectionId),connectionType:(Q=i==null?void 0:i.dataSource)==null?void 0:Q.connectionType}),L=n.isCalculatedFilterField(j),V=!!(((U=i==null?void 0:i.dataSource)==null?void 0:U.mode)==="semanticDomain"&&((J=T==null?void 0:T.selectedEntities)!=null&&J.length||T!=null&&T.semanticDomainId)),z={id:t.v4(),column:b,title:y.label||y.name,dataType:y.dataType,table:y.entityName||"",database:M,qualifiedTableName:k,connectionId:o||"",operation:"in",sql:L||V?"":n.getDefaultFilterSql(y.dataType,k,O),fieldMeta:j,semanticContext:T,width:250};c({...i,inlineFilters:[...g,z]})}function N(y){const M=g.filter(b=>b.id!==y);c({...i,inlineFilters:M}),m?v(i.id,y):x(i.id,y)}function A(y,M){const b=g.map(O=>O.id===y?{...O,...M}:O);if(c({...i,inlineFilters:b}),!(Object.prototype.hasOwnProperty.call(M,"defaultValues")||Object.prototype.hasOwnProperty.call(M,"defaultDateFilter")))return;const k=b.find(O=>O.id===y);if(!k)return;const F=t.buildFilterValueFromDefaults(k,S);F?m?p(i.id,F):h(i.id,F):m?v(i.id,y):x(i.id,y)}if(!["bar","line","pie","doughnut","table","detailTable","stackedBar","stackedLine","horizontalBar","radar","polarArea","scatter","bubble","funnel","aggregateTable","custom"].includes(i==null?void 0:i.type))return null;const w=a==="menu";return e.jsx("div",{className:t.cn("flex items-center gap-1",w&&"w-full",s),children:e.jsxs(t.Popover,{open:l,onOpenChange:u,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:w?e.jsxs(t.Button,{variant:"ghost",className:t.cn("h-7 w-full justify-start gap-2 px-2 text-[13px]",g.length>0&&"text-primary"),children:[e.jsx(hn,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:r}),g.length>0&&e.jsx("span",{className:"ml-auto inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-[4px] bg-primary text-[10px] font-medium leading-none text-primary-foreground",children:g.length})]}):e.jsxs(n.IconButton,{tooltip:"Add Inline Filter",className:t.cn("relative h-7 w-7 px-0",{"text-primary":g.length>0}),children:[e.jsx(hn,{className:"h-3.5 w-3.5"}),g.length>0&&e.jsx("span",{className:"absolute -right-1 -top-1 flex h-4 w-4 items-center justify-center rounded-full bg-primary text-[10px] font-medium text-primary-foreground",children:g.length})]})}),e.jsx(t.PopoverContent,{align:"end",className:t.cn("w-80 p-0",w&&"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:f,inlineFilters:g})})})}),g.length>0&&e.jsxs("div",{className:"border-t px-4 py-3",children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Active Filters"}),e.jsx("div",{className:"space-y-1",children:g.map(y=>e.jsx(Pr,{filter:y,onUpdate:M=>A(y.id,M),onRemove:()=>N(y.id)},y.id))})]})]})})]})})}function Pr({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:l=>a(l),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 Br={metric_selector:"Displayed metric",field_selector:"Group by field",aggregation_selector:"Aggregation",grain_selector:"Time grain"};function Vr(s,a){return s&&typeof s=="object"&&"label"in s&&typeof s.label=="string"&&s.label.trim().length>0?s.label:a||null}const _r={metric_selector:"config_metric_selector",field_selector:"config_field_selector",aggregation_selector:"config_aggregation",grain_selector:"config_grain"};function Xt(s,a){return`${s}:${a}`}function zr(s,a,r){const l=new Set(r.filter(i=>i.target!=="sql_param").map(i=>Xt(i.controlId,i.target))),u=a.map(i=>{const o=t.getCompatibleBindingTargetOptions({card:s,control:i}).map(h=>h.value),d=_r[i.type],x=[...d?[d]:[],...o.filter(h=>h!==d)].find(h=>!l.has(Xt(i.id,h)));return x?{controlId:i.id,target:x}:null}).find(Boolean);return u?{controlId:u.controlId,target:u.target,mapping:{}}:null}function qr({card:s,dashboardControls:a,bindings:r,onChange:l,availableFieldChoices:u,availableMetricChoices:i,suppressTransientStaleState:o=!1}){const d=[...a,...s.controls||[]],[c,x]=C.useState({}),h=n.extractSqlParamReferences({sql:s.sql,controlBindings:s.controlBindings}),v=t.getBindingTargetSuggestions(s),p=new Set(r.map(B=>Xt(B.controlId,B.target))),m=d.some(B=>t.getCompatibleBindingTargetOptions({card:s,control:B}).some(w=>!p.has(Xt(B.id,w.value)))),g=o?0:r.reduce((B,w)=>{const I=S(w.target),D=Object.values(w.mapping).filter(E=>{const y=w.target==="config_metric_selector"||w.target==="config_field_selector"?typeof E=="string"?E:E==null?void 0:E.id:typeof E=="string"?E:void 0;return typeof y=="string"&&!I.some(M=>M.value===y)}).length;return B+D},0);function S(B){var w,I,D,E;switch(B){case"config_metric_selector":return i?i.filter(y=>!!y.target).map(y=>({value:y.target.id,label:y.target.label||y.option.label,target:y.target})):((I=(w=s.config)==null?void 0:w.metricColumns)==null?void 0:I.map(y=>({value:y.id,label:y.label||y.id,target:y})))||[];case"config_field_selector":return u?u.filter(y=>!!y.target).map(y=>({value:y.target.id,label:y.target.label||y.option.label,target:y.target})):((E=(D=s.config)==null?void 0:D.groupByColumns)==null?void 0:E.map(y=>({value:y.id,label:y.label||y.id,target:y})))||[];case"config_aggregation":return(v.config_aggregation||[]).map(y=>({value:y,label:y}));case"config_grain":return(v.config_grain||[]).map(y=>({value:y,label:y.charAt(0).toUpperCase()+y.slice(1)}));default:return[]}}const f=(B,w)=>{l(r.map((I,D)=>D!==B?I:w(I)))},N=B=>{l(r.filter((w,I)=>I!==B))},A=()=>{const B=zr(s,d,r);B&&l([...r,B])};if(typeof s.sql=="string"&&s.sql.trim().length>0){const B=h.map(({controlId:w,paramId:I})=>{const D=d.find(E=>E.id===w);return D?{id:w,paramId:I,label:D.label,reference:`[[param.${I}]]`}:{id:w,paramId:I,label:w,reference:`[[param.${I}]]`}});return e.jsx("div",{className:"space-y-2",children:B.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-sm text-muted-foreground",children:"This card is currently using raw SQL. Reference a control directly in the SQL editor with syntax like `[[param.metric]]`."}):B.map(w=>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:w.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:w.reference}),e.jsx(n.CopyButton,{text:w.reference,ariaLabel:`Copy ${w.reference}`})]})]})},`${w.id}:${w.paramId}`))})}return e.jsxs("div",{className:"space-y-4",children:[g>0?e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-950",children:[e.jsx(n.CircleAlert,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{children:[g," ",g===1?"mapping needs":"mappings need"," attention before save. Replace each missing target or choose Not mapped."]})]}):null,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((B,w)=>{const I=v[B.target]||[],D=d.find(j=>j.id===B.controlId),E=D?t.ensureManualSource(D):null,y=(E==null?void 0:E.source.kind)==="manual"?E.source.options:[],M=S(B.target),b=Array.from(new Set([...y.map(j=>j.value),...Object.keys(B.mapping)])).map(j=>{const T=y.find(L=>L.value===j);return{value:j,label:(T==null?void 0:T.label)||j}}),R=`${B.controlId}-${B.target}-${w}`,k=c[R]??w===0,F=Object.keys(B.mapping).length,O=D!=null&&D.type?Br[D.type]||D.type:null;return e.jsxs(n.Collapsible,{open:k,onOpenChange:j=>x(T=>({...T,[R]: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:[k?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:(D==null?void 0:D.label)||"Control"}),O?e.jsx(n.Badge,{variant:"secondary",className:"shrink-0 text-[11px] font-normal text-muted-foreground",children:O}):null]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:F>0?`${F} mapped`:"No mappings yet"})]})]})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>N(w),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:b.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-sm text-muted-foreground",children:"Add choices to this control first so you can decide what each choice changes in the card."}):M.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-sm text-muted-foreground",children:"No matching targets are available for this binding yet."}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs",children:"Map each choice"}),e.jsx("div",{className:"space-y-2",children:b.map(j=>{const T=B.mapping[j.value],L=B.target==="config_metric_selector"||B.target==="config_field_selector"?typeof T=="string"?T:T==null?void 0:T.id:typeof T=="string"?T:void 0,V=!o&&typeof L=="string"&&!M.some(P=>P.value===L),z=Vr(T,L),_=L&&V?[...M,{value:L,label:"Needs remap",target:T}]:M;return e.jsxs("div",{className:"grid gap-2 rounded-md border p-2 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-[11px] text-muted-foreground",children:"Viewer picks"}),e.jsx("div",{className:"rounded-md bg-muted/50 px-3 py-2 text-sm",children: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:L||"__none__",onValueChange:P=>f(w,q=>{if(q.target==="config_metric_selector"){const Q={...q.mapping};if(P==="__none__")delete Q[j.value];else{const U=_.find(J=>J.value===P);U!=null&&U.target?Q[j.value]=U.target:delete Q[j.value]}return{...q,mapping:Q}}if(q.target==="config_field_selector"){const Q={...q.mapping};if(P==="__none__")delete Q[j.value];else{const U=_.find(J=>J.value===P);U!=null&&U.target?Q[j.value]=U.target:delete Q[j.value]}return{...q,mapping:Q}}const G={...q.mapping};return P==="__none__"?delete G[j.value]:G[j.value]=P,{...q,mapping:G}}),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Choose what this should use"})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"__none__",children:"Not mapped"}),_.map(P=>e.jsx(t.SelectItem,{value:P.value,children:P.label},P.value))]})]}),V?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",z?` · Previously: ${z}`:""]})]}):null]})]},`${B.controlId}-${B.target}-${j.value}`)})}),I.length>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Available choices for this card: ",I.join(", ")]})]})})]},R)}),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 $r=[];function Ts({className:s,triggerVariant:a="icon",label:r="Controls"}){var k,F;const{handleOpenChange:l,preventPassiveDismissDuringCreate:u,resolvedOpen:i,setIsCreateFlowActive:o}=Oe.useCreateFlowOverlayState({}),d=t.useEditorStore(O=>O.card),c=t.useEditorStore(O=>O.frame),x=t.useDashboardStore(O=>O.dashboard),v=t.useDashboardStore(O=>O.dashboard.controls)||$r,{setCard:p,updateCardInFrame:m}=t.useEditorActions(),[g,S]=C.useState(null);C.useEffect(()=>{i&&!g&&(d!=null&&d.id)&&S(d.id)},[d==null?void 0:d.id,i,g]),C.useEffect(()=>{!i&&g!==null&&S(null)},[i,g]);const f=C.useMemo(()=>g?(c==null?void 0:c.cards.find(O=>O.id===g))||((d==null?void 0:d.id)===g?d:void 0):d,[d,c==null?void 0:c.cards,g]),N=(f==null?void 0:f.controls)||[],A=f?t.collectDashboardControlIds(x,{excludeCardId:f.id}):v.map(O=>O.id),B=((f==null?void 0:f.controlBindings)||[]).filter(O=>O.target!=="sql_param"),w=n.buildCardControlUsageById({card:f,controls:N}),I={choices:t.getFieldSelectorChoicesForCard(f),targetMap:Object.fromEntries((((k=f==null?void 0:f.config)==null?void 0:k.groupByColumns)||[]).map(O=>[O.id,O]))},D={choices:t.getMetricSelectorChoicesForCard(f),targetMap:Object.fromEntries((((F=f==null?void 0:f.config)==null?void 0:F.metricColumns)||[]).map(O=>[O.id,O]))},E=I.choices.map(O=>({option:O,target:I.targetMap[O.value]})),y=D.choices.map(O=>({option:O,target:D.targetMap[O.value]})),M=(O,j)=>{if(!f)return;const T=(j==null?void 0:j.type)==="rename"?t.applyControlMutationToCard(f,{type:"rename",oldId:j.oldId,newId:j.newId}):(j==null?void 0:j.type)==="remove"?t.applyControlMutationToCard(f,{type:"remove",controlId:j.controlId}):f,L={...T,controls:O,controlBindings:t.syncStructuralBindingsWithControls(T.controlBindings,O)};m(L),(d==null?void 0:d.id)===L.id&&p(L)},b=O=>{if(!f)return;const j={...f,controlBindings:t.mergeConfigBindingsWithSqlParamBindings(O,f.controlBindings)};m(j),(d==null?void 0:d.id)===j.id&&p(j)},R=a==="menu";return e.jsx("div",{className:t.cn("flex items-center gap-1",R&&"w-full",s),children:e.jsxs(t.Popover,{modal:!0,open:i,onOpenChange:l,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:R?e.jsxs(t.Button,{variant:"ghost",className:t.cn("h-7 w-full justify-start gap-2 px-2 text-[13px]",(N.length>0||B.length>0)&&"text-primary"),children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:r}),N.length+B.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+B.length})]}):e.jsxs(n.IconButton,{tooltip:"Configure Controls",className:t.cn("relative h-7 w-7 px-0",{"text-primary":N.length>0||B.length>0}),children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"}),N.length+B.length>0&&e.jsx("span",{className:"absolute -right-1 -top-1 inline-flex h-4 min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[10px] font-medium text-primary-foreground",children:N.length+B.length})]})}),e.jsxs(t.PopoverContent,{className:t.cn("flex max-h-[85vh] w-[560px] max-w-[95vw] flex-col",R&&"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."}),f!=null&&f.sql?e.jsx("p",{className:"text-xs text-muted-foreground",children:"SQL cards reference controls explicitly with syntax like `[[param.wac_type]]`."}):null]}),e.jsx("div",{className:"flex-1 overflow-y-auto pt-5",children:e.jsxs("div",{className:"space-y-5 pr-1",children:[e.jsx(Oe.ControlDefinitionListEditor,{scope:"card",card:f,controls:N,reservedControlIds:A,usageByControlId:w,availableFieldChoices:E,availableMetricChoices:y,onCreateFlowActiveChange:o,onChange:(O,j,T)=>M(O,T),emptyMessage:"No card-scoped controls yet."}),e.jsxs("div",{className:"space-y-1 border-t pt-4",children:[e.jsx("h4",{className:"text-sm font-medium",children:"How this card uses controls"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Choose what each control changes in this card."})]}),f?e.jsx(qr,{card:f,dashboardControls:v,bindings:B,onChange:b,availableFieldChoices:E,availableMetricChoices:y}):null]})})]})]})})}function Wn({showOrientation:s=!0,showGridStyle:a=!0,showInlineFilters:r=!0,showControls:l=!0,showDisplayOptions:u=!0}={}){const i=t.useEditorStore(m=>m.card),o=t.useEditorStore(m=>{var g,S;return(S=(g=m.card)==null?void 0:g.preferences)==null?void 0:S.chartOptions}),d=n.getChartGridStyle(o),{setChartGrid:c}=t.useEditorActions();function x(){const m=["xy","none","x","y"],S=(m.indexOf(d)+1)%m.length;c(m[S])}const h=s&&["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel","bullet"].includes(i.type),v=a&&!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(i.type);return h||v||r||l||u?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[h&&e.jsx(e.Fragment,{children:e.jsx(Or,{})}),v&&e.jsxs(n.IconButton,{tooltip:"Grid Style",onClick:x,className:"h-7 w-7 px-0",children:[(d==="xy"||!d)&&e.jsx(n.Grid3x3,{className:"h-3.5 w-3.5"}),d==="x"&&e.jsx(ys,{className:"h-3.5 w-3.5"}),d==="y"&&e.jsx(Zt,{className:"h-3.5 w-3.5"}),d==="none"&&e.jsx(n.Square,{className:"h-3.5 w-3.5"})]}),r&&e.jsx(ws,{}),l&&e.jsx(Ts,{}),u&&e.jsx(Ss,{})]}):null}function Kr({visible:s}){const a=t.useDashboardStore(o=>o.selectedFrameId),r=n.useManagementStore(o=>o.selectedVisual),l=t.useEditorStore(o=>o.frame),i=!!!(l!=null&&l.visualId||r!=null&&r.id)&&!!a;return!s||i?null:e.jsx("div",{className:"mb-2 flex",children:e.jsx(Oe.VisualBadge,{showLabel:!0,className:"h-6 w-fit px-2 py-0.5 text-[11px]"})})}function Gr({isPreviewMode:s,onPreviewToggle:a,configCard:r}){var T,L,V,z,_;const l=t.useEditorStore(P=>P.frame),u=t.useEditorStore(P=>P.card),i=t.useEditorStore(P=>P.editorContext),o=(i==null?void 0:i.type)==="documentSection",{setFrame:d,setActiveTabCardId:c,setCard:x,updateCardInFrame:h,clearModeDrafts:v,initializeModeDrafts:p}=t.useEditorActions(),{manifest:m}=n.useCustomVisual(((T=r==null?void 0:r.customCardPreferences)==null?void 0:T.url)||""),g=(L=m==null?void 0:m.visuals)==null?void 0:L.find(P=>{var q;return P.name===((q=r==null?void 0:r.customCardPreferences)==null?void 0:q.componentName)}),f=n.resolveMultiInputType(r,g)==="multiple",N=(g==null?void 0:g.minInputs)??((V=r==null?void 0:r.customCardPreferences)==null?void 0:V.minInputs)??1,A=(g==null?void 0:g.maxInputs)??((z=r==null?void 0:r.customCardPreferences)==null?void 0:z.maxInputs),B=C.useMemo(()=>n.getCustomVisualInputCards({frame:l,configCard:r,isMultiInputVisual:f}),[l,r,f]),w=f?B.filter(Boolean).length:l.cards.length,I=o?!1:A?w<A:!0,D=w>Math.max(N||1,1),E=!!((_=r==null?void 0:r.customCardPreferences)!=null&&_.dataInputCardIds),y=(P,q)=>{P.dataTransfer.setData("tabIndex",q.toString())},M=P=>{P.preventDefault()},b=(P,q)=>{const G=P.dataTransfer.getData("tabIndex");if(G===q.toString())return;const Q=Array.from(l.cards),[U]=Q.splice(parseInt(G),1);Q.splice(q,0,U),d({...l,cards:Q})};function R(P){const q=(r==null?void 0:r.id)===P;if(!(E&&q?l.cards.length>1:D))return;let Q=l.cards.filter(se=>se.id!==P);f&&!E&&(Q=n.reindexSlotCards(Q));const U=Q[0],J={...l,cards:Q,activeCardId:U.id},X=P===u.id;X&&v(),d(J),c(U.id),x(U),X&&p(U)}function k(P,q){if(!I)return;const G={...l,cards:[...l.cards,q],activeCardId:P.id};d(G),c(q.id)}function F(){if(o)return;if(f&&(r==null?void 0:r.id)===u.id){O(u);return}const P={...u,id:t.v4(),title:`${u.title} Copy`,tabTitle:`${u.tabTitle||u.title} Copy`,customCardPreferences:u.customCardPreferences?{...u.customCardPreferences,slotIndex:f?Math.max(-1,...B.map((q,G)=>n.getSlotIndexForCard(q,G)))+1:u.customCardPreferences.slotIndex}:void 0};k(u,P)}function O(P){var X;if(o||!I)return;let q=f?"table":"bar",G="Title",Q="";const U=f?Math.max(-1,...B.map((se,ue)=>n.getSlotIndexForCard(se,ue)))+1:w;if(f&&((X=g==null?void 0:g.slots)!=null&&X.length)){const se=n.getSlotDefinitionForIndex(g.slots,U);se&&(q=n.getSlotExpectedChartType(se),G=se.label||`Tab ${U+1}`,Q=se.description||"")}const J={dataSource:P.dataSource,connectionId:P.connectionId,lastSelectedDatabase:P.lastSelectedDatabase,lastSelectedSchema:P.lastSelectedSchema,lastSelectedTable:P.lastSelectedTable,lastSelectedDatamodelId:P.lastSelectedDatamodelId,id:t.v4(),title:G,tabTitle:G,description:Q,preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:q,sql:"",data:[],mode:"explorer",...f&&{customCardPreferences:{slotIndex:U}}};k(P,J)}function j(P,q){return P.cards.length===1&&(q.displayTab===!0||q.displayTab===void 0)||P.activeCardId!==q.id&&(q.displayTab===!0||q.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const G=q.displayTab===void 0?!1:!q.displayTab;x({...q,displayTab:G}),h({...q,displayTab:G})},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:[l.cards.map((P,q)=>{var X,se;const G=f?n.getSlotIndexForCard(P,q):-1,Q=f&&((X=g==null?void 0:g.slots)!=null&&X.length)&&G>=0?n.getSlotDefinitionForIndex(g.slots,G):null,U=Q?(Array.isArray(Q.expectedType)?Q.expectedType[0]:Q.expectedType)||"table":P.type,J=f&&((se=g==null?void 0:g.slots)==null?void 0:se.length)&&g.slots.every(ue=>typeof ue.position=="number"||typeof ue.position=="string"&&!ue.position.includes("+"));return e.jsxs(t.TabsTrigger,{draggable:!f&&!o,onDragStart:f||o?void 0:ue=>y(ue,q),onDragOver:f||o?void 0:M,onDrop:f||o?void 0:ue=>b(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:P.id,children:[f&&Q?e.jsx(t.TooltipProvider,{delayDuration:0,children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:n.getChartIconByType(U,"size-3.5")}),e.jsx("span",{children:Q.label||`Tab ${G+1}`})]})}),e.jsx(t.TooltipContent,{side:"bottom",className:"w-64 p-3 text-left",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium",children:Q.label}),Q.description&&e.jsx("p",{className:"whitespace-normal break-words text-xs text-muted-foreground",children:Q.description}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[Q.expectedType&&e.jsx("span",{className:"inline-flex items-center rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground",children:Array.isArray(Q.expectedType)?Q.expectedType.join(" / "):Q.expectedType}),Q.required&&e.jsx("span",{className:"inline-flex items-center rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground",children:"Required"})]})]})})]})}):e.jsxs(e.Fragment,{children:[j(l,P),e.jsx(n.Editable,{enabled:l.activeCardId===P.id,text:P.tabTitle||P.title,onSave:ue=>{x({...u,tabTitle:ue}),h({...u,tabTitle:ue})},children:P.tabTitle||P.title},P.id)]}),!o&&l.activeCardId===P.id&&!J&&e.jsx(n.CopyPlus,{className:"h-3 w-3 text-muted-foreground hover:text-foreground",onClick:ue=>{ue.stopPropagation(),F()}}),!o&&l.activeCardId===P.id&&(E&&(r==null?void 0:r.id)===P.id?l.cards.length>1:D)&&e.jsx(t.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground",onClick:()=>R(P.id)})]},P.id)}),!o&&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:()=>O(u),disabled:!I,children:e.jsx(n.Plus,{className:"h-3 w-3"})}),f&&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 pt({renderCardOverride:s,alwaysRenderOverride:a=!1}={}){var ye,re,$;const r=t.useEditorStore(H=>H.frame),l=t.useEditorStore(H=>H.card),[u,i]=C.useState(!1),o=C.useMemo(()=>n.findCustomVisualConfigCard(r,l),[r,l]),d=t.useEditorStore(H=>H.isSqlRunning);t.useEditorStore(H=>H.isDevMode);const{setFrame:c,setActiveTabCardId:x,setCard:h,setRunSql:v,mergeDraftsIntoCard:p,clearModeDrafts:m,initializeModeDrafts:g}=t.useEditorActions(),[S,f]=C.useState({}),[N,A]=C.useState(()=>new Set),{authToken:B}=n.useSemaphorContext(),w=t.getTokenParams(B==null?void 0:B.accessToken),{compiledAppearance:I}=t.useAppearance(),D=C.useMemo(()=>n.buildCustomCardTheme(I),[I]),{getCard:E,manifest:y,isLoading:M}=n.useCustomVisual(((ye=o==null?void 0:o.customCardPreferences)==null?void 0:ye.url)||""),b=(re=o==null?void 0:o.customCardPreferences)==null?void 0:re.componentName,R=b?E(b):null,k=($=y==null?void 0:y.visuals)==null?void 0:$.find(H=>H.name===b),F=n.resolveMultiInputType(o,k),O=u&&F==="multiple"&&!!o,j=C.useMemo(()=>n.getCustomVisualInputCards({frame:r,configCard:o,isMultiInputVisual:!0}).map(ne=>(ne==null?void 0:ne.id)===l.id?l:ne),[r,o,l]),T=C.useMemo(()=>n.buildSlotOrderedCards(j),[j]),L=C.useMemo(()=>{const H=j.findIndex(ne=>(ne==null?void 0:ne.id)===l.id);return H<0?-1:n.getSlotIndexForCard(l,H)},[j,l]),V=C.useMemo(()=>!o||F!=="multiple"||L<0?l.type:n.getEffectiveCardTypeForSlot(l,L,k==null?void 0:k.slots)??l.type,[o,F,L,l,k==null?void 0:k.slots]),z=C.useMemo(()=>O?{...l,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:V!==l.type?{...l,type:V}:l,[l,V,O]),{data:_,isLoading:P,isFetching:q,isError:G}=n.useEditorCardQuery(z),Q=C.useCallback((H,ne)=>{const he=n.normalizeMultiInputPayload(ne);f(de=>({...de,[H]:he}))},[]),U=C.useCallback((H,ne)=>{A(he=>{const de=new Set(he);return ne?de.add(H):de.delete(H),de})},[]),J=N.size>0,X=t.useInteractionStore(H=>H.interactionStates),se=t.useDashboardStore(H=>{var ne;return(ne=H.dashboard)==null?void 0:ne.id}),ue=t.useDashboardStore(H=>H.dashboard.filters),pe=t.useDashboardStore(H=>H.filterValues),xe=t.useDashboardStore(H=>H.selectedSheetId),je=t.useEditorStore(H=>H.inlineFilterValuesMap[(o==null?void 0:o.id)||""]),Pe=t.useEditorStore(H=>H.actions.setCardInlineFilterValue),Me=t.useEditorStore(H=>H.actions.removeCardInlineFilterValue),te=C.useMemo(()=>o?n.buildInlineFilterNodes({card:o,sheetId:xe||"",inlineFilterValues:je,setInlineFilterValue:H=>Pe(o.id,H),removeInlineFilterValue:H=>Me(o.id,H)}):[],[o,xe,je,Pe,Me]),{cardFilters:fe,cardFilterValues:ke}=C.useMemo(()=>o?n.calculateContextAwareFilters({card:o,interactionStates:X,currentDashboardId:se,filters:ue,filterValues:pe,selectedSheetId:xe}):{cardFilters:[],cardFilterValues:[]},[o,X,se,ue,pe,xe]);function Be(H){const ne=r.cards.find(he=>he.id===H);ne&&(ft.flushPendingEditorDrafts(),p(),ze(H),x(H),m(),g(ne))}function ze(H){const ne=t.useEditorStore.getState().card,he=t.useEditorStore.getState().frame,de={...he,cards:he.cards.map(De=>De.id===ne.id?ne:De),activeCardId:H};c(de);const Te=de.cards.find(De=>De.id===H);Te.sql&&v(!0),h(Te)}function ce(){if(M)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(!R)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 ne=T.map((he,de)=>n.getEffectiveCardTypeForSlot(he,de,k==null?void 0:k.slots));return e.jsxs("div",{className:"relative flex h-full flex-col pl-2 pr-4",children:[j.map((he,de)=>{if(!he)return null;const Te=n.getSlotIndexForCard(he,de),De=n.getEffectiveCardTypeForSlot(he,Te,k==null?void 0:k.slots);return e.jsx(n.MultiInputEmptyRenderer,{onLoadingStatus:U,onDataChange:Q,card:he,effectiveCardType:De},`${he.id}-${Te}`)}),J&&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",J&&"opacity-50"),children:e.jsx(C.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(R,{editing:!0,...n.buildMultiInputCustomVisualProps({configCard:o,slotOrderedCards:T,slotTypes:ne,multiInputData:S,params:w,theme:D,filters:fe,filterValues:[...ke||[],...je||[]],inlineFilters:te})})})})]})}function ve(){var H;return O?ce():s&&(a||!P&&!q&&!G)?s({card:l,data:_,isLoading:P,isFetching:q,isError:G}):l.type==="kpi"?P||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(Kr,{visible:!0}),e.jsx("div",{className:"rounded-md border border-border",children:e.jsx(n.KPICard,{card:l,data:_==null?void 0:_.records,isPending:P||q,isError:G,comparisonMetadata:(H=_==null?void 0:_.metadata)==null?void 0:H.comparisonMetadata})}),n.isCardSummaryVisibleOnCard(l)&&e.jsx(n.CardSummary,{card:l,mode:"editor"})]})}):l.type==="text"?P||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.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(t.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(n.TextCard,{isLoading:d,card:l,data:_==null?void 0:_.records})})})}):e.jsx(n.ErrorBoundary,{FallbackComponent:n.FallbackVisual,children:e.jsx(Kn,{className:"grow border-none shadow-none"})})}return e.jsxs(t.Tabs,{onValueChange:Be,value:r.activeCardId,className:"flex grow flex-col",children:[O?e.jsx("div",{className:"mt-0 grow",children:ve()}):r.cards.map(H=>e.jsx(t.TabsContent,{className:"mt-0 grow focus-visible:ring-0 focus-visible:ring-offset-0",value:H.id,children:ve()},H.id)),e.jsx(Gr,{isPreviewMode:O,onPreviewToggle:i,configCard:o})]})}function Ur({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 Yn({fallbackPreview:s,records:a,title:r,isInspectorOpen:l,onInspectorOpenChange:u}){var F;const i=t.useEditorStore(O=>O.card),o=t.useEditorStore(O=>O.actions.setCard),d=t.useEditorStore(O=>O.actions.updateCardInFrame),c=t.normalizeDynamicRendererSource((F=i.dynamicCardPreferences)==null?void 0:F.rendererCode),[x,h]=C.useState(c),[v,p]=C.useState(c);C.useEffect(()=>{h(c),p(c)},[c,i.id]);const m=C.useMemo(()=>t.normalizeDynamicRendererSource(x),[x]),g=C.useMemo(()=>t.validateDynamicRendererSource(m),[m]),S=!!c,f=C.useMemo(()=>{var O;return t.buildCardWithVisualizationMode(i,v?"dynamic":"builtin",{rendererCode:v||void 0,artifactId:((O=i.dynamicCardPreferences)==null?void 0:O.artifactId)||i.id,title:r||i.title})},[i,v,r]),N=!!v,A=m!==v,B=v!==c,w=!m||!g.valid||A||B,I=m?g.valid?A?"Unapplied changes":"Pending save":"Needs attention":"Draft",D=!m||A||B?"outline":"destructive",E=m?g.valid?A?"The preview still reflects the last applied code until you apply this draft.":B?"Preview reflects pending changes. Accept changes to save them.":"":g.error||"Visual code is invalid.":"Paste visual code or generate one before saving this card.";function y(){if(!g.valid){n.ue.error(g.error||"Visual code is invalid.");return}p(m),n.ue.success("Dynamic preview updated.")}function M(){h(v)}function b(){var j;const O=t.buildCardWithVisualizationMode(i,v?"dynamic":"builtin",{rendererCode:v||void 0,artifactId:((j=i.dynamicCardPreferences)==null?void 0:j.artifactId)||t.v4(),title:r||i.title});o(O),d(O),u(!1),n.ue.success(v?"Dynamic visual changes saved.":"Dynamic visual cleared.")}function R(){h(c),p(c),u(!1)}function k(){h(""),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:S?e.jsx(n.PersistedDynamicVisual,{card:i,records:a,title:r,layoutMode:"fill",fallback:s},c||"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(Ur,{onClick:()=>u(!0)})]})}),e.jsx(n.Dialog,{open:l,onOpenChange:O=>{if(!O){R();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."})]}),w&&e.jsx(n.Badge,{className:"mr-4 shrink-0",variant:D,children:I})]})}),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:f,records:a,title:r,layoutMode:"fill",fallback:s},v||"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:!S&&!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:k,children:"Clear"})]})]})]}),e.jsxs(t.Button,{type:"button",size:"sm",variant:"outline",className:"h-8 gap-1.5 px-2.5 text-xs",onClick:M,disabled:!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:y,disabled:!A||!g.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",g.valid?"text-muted-foreground":"text-destructive"),children:E}),e.jsx("div",{className:t.cn("min-h-0 flex-1 overflow-hidden rounded-md border",!g.valid&&m&&"border-destructive"),children:e.jsx(t.CodeEditor,{value:x,onValueChange:O=>h(O||""),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:R,children:"Cancel"}),e.jsx(t.Button,{type:"button",size:"sm",className:"h-8 px-3 text-xs",onClick:b,disabled:!B,children:"Accept changes"})]})]})]})})]})}function Jn({onCustomize:s}){const a=t.useEditorStore(x=>x.card),r=t.useEditorStore(x=>x.frame),l=t.useEditorStore(x=>x.actions.setIsShowingVisual),{setVisualizationMode:u,setDynamicCardPreferences:i}=t.useEditorActions(),d=t.getVisualizationMode(a)==="dynamic";if(r.cards.length!==1||t.isCustomVisualizationCard(a))return null;const c=x=>{var h;x==="dynamic"&&!a.dynamicCardPreferences&&i(t.createEmptyDynamicCardPreferences(a.type,(h=a.preferences)==null?void 0:h.displayOptions)),u(x),l(!0)};return e.jsxs(e.Fragment,{children:[e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuItem,{onSelect:x=>{x.preventDefault(),c(d?"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:d,onCheckedChange:x=>c(x?"dynamic":"builtin"),onClick:x=>x.stopPropagation()})]}),d&&s?e.jsxs(n.DropdownMenuItem,{onSelect:x=>{x.preventDefault(),s()},className:"gap-2 text-[13px]",children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"}),"Customize Visual"]}):null]})}const Hr={async writeTextToClipboard(s){return typeof navigator>"u"||!navigator.clipboard?!1:(await navigator.clipboard.writeText(s),!0)}},Yt=50,Qr=[{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 Nn(s){try{return JSON.stringify(s,null,2)}catch(a){return console.error("Unable to stringify debug payload",a),null}}function St(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 Wr(s){if(!s||typeof s!="object")return{value:s};const a=s.records;return!Array.isArray(a)||a.length<=Yt?{value:s}:{value:{...s,records:a.slice(0,Yt),previewMeta:{truncatedRecords:!0,displayedRecords:Yt,totalRecords:a.length}},truncationMessage:`Preview showing first ${Yt} records of ${a.length}. Copy actions include full payload.`}}function Xn({sql:s,showCardDetails:a=!1,debugPayloads:r,className:l}){const[u,i]=C.useState(!1),[o,d]=C.useState(null),c=t.useEditorStore(b=>b.card),x=t.useEditorStore(b=>b.frame),h=t.useEditorStore(b=>b.isDevMode),v=t.useDashboardStore(b=>b.selectedSheetId),p=t.useDashboardStore(b=>{var R;return(R=b.dashboard)==null?void 0:R.id}),{switchEditorMode:m,setRunSql:g}=t.useEditorActions(),S=C.useMemo(()=>({cardId:c.id||null,frameId:x.id||null,sheetId:v||null,dashboardId:p||null}),[c.id,x.id,v,p]),f=C.useMemo(()=>({queryRequest:r==null?void 0:r.queryRequest,queryResponse:r==null?void 0:r.queryResponse,cardConfig:c.config,dataSource:c.dataSource,columns:r==null?void 0:r.columns,dashboardFilters:r==null?void 0:r.dashboardFilters,cardMetadata:S}),[r==null?void 0:r.queryRequest,r==null?void 0:r.queryResponse,r==null?void 0:r.columns,r==null?void 0:r.dashboardFilters,c.config,c.dataSource,S]),N=a&&u&&!!r,A=C.useMemo(()=>[{label:"Card ID",value:c.id||""},{label:"Frame ID",value:x.id||""},{label:"Sheet ID",value:v||""},{label:"Dashboard ID",value:p||""}],[c.id,x.id,v,p]),B=()=>{m("dev",{sqlToLoad:s}),setTimeout(()=>{g(!0)},100)},w=b=>f[b]!==void 0,I=C.useMemo(()=>{if(!o)return null;const b=f[o];if(b===void 0)return null;const R=o==="queryResponse"?Wr(b):{value:b},k=Nn(R.value);return k?{target:o,title:St(o),json:k,truncationMessage:R.truncationMessage}:null},[o,f]),D=I?I.title:"Preview Payload",E=async b=>{const R=f[b];if(R===void 0)return n.ue.error(`No ${St(b).toLowerCase()} available`),!1;const k=Nn(R);if(!k)return n.ue.error(`Unable to serialize ${St(b).toLowerCase()}`),!1;try{return await Hr.writeTextToClipboard(k)?(n.ue.success(`${St(b)} copied`),!0):(n.ue.error("Clipboard is not available"),!1)}catch(F){return console.error("Failed to copy debug payload",F),n.ue.error(`Unable to copy ${St(b).toLowerCase()}`),!1}},y=async()=>I?E(I.target):!1,M=b=>{if(f[b]===void 0){n.ue.error(`No ${St(b).toLowerCase()} available`);return}d(b)};return e.jsxs("div",{className:t.cn("flex max-h-full min-h-0 flex-1 flex-col overflow-hidden pt-3",l),children:[!h&&e.jsxs("div",{className:"mb-3 flex items-center gap-1.5",children:[e.jsxs(t.Button,{onClick:B,variant:"outline",size:"xs",children:[e.jsx(Vn,{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(Oe.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(b=>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:b.label}),e.jsx(n.CopyButton,{text:b.value,className:"h-6 w-6 shrink-0"})]}),e.jsx("code",{title:b.value||"N/A",className:"mt-1 block whitespace-normal break-all font-mono text-xs",children:b.value||"N/A"})]},b.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"}),D,e.jsx(t.ChevronDown,{className:"ml-1.5 h-3.5 w-3.5"})]})}),e.jsx(n.DropdownMenuContent,{align:"start",className:"w-56",children:Qr.map(b=>e.jsx(n.DropdownMenuItem,{disabled:!w(b.target),onSelect:()=>M(b.target),className:t.cn(o===b.target&&"bg-accent"),children:b.label},`preview-${b.target}`))})]})}),I&&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:[I.title," Preview"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(n.CopyButton,{text:I.json,className:"h-6 w-6",ariaLabel:"Copy Payload",onCopy:y}),e.jsxs(t.Button,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>d(null),children:[e.jsx(Oe.CircleX,{className:"mr-1 h-3.5 w-3.5"}),"Hide"]})]})]}),I.truncationMessage&&e.jsx("p",{className:"text-xs text-muted-foreground",children:I.truncationMessage}),e.jsx("div",{className:"max-h-80 overflow-auto",children:e.jsx(n.CodeHighlighter,{code:I.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 cs({children:s,visualAsideControl:a,mode:r="both",isDynamicInspectorOpen:l,onDynamicInspectorOpenChange:u}){var ye;const i=n.useQueryClient(),o=t.useEditorStore(re=>re.frame),d=t.useEditorStore(re=>re.card),c=t.useEditorStore(re=>re.isDevMode),x=t.useEditorStore(re=>re.editorContext),h=(x==null?void 0:x.type)==="documentSection",v=t.useEditorStore(re=>re.isShowingVisual),p=t.useEditorStore(re=>re.actions.setIsShowingVisual),m=t.useDashboardStore(re=>re.isVisualEditing),{isConsoleMode:g}=n.useDashboardPreferences(),S=t.useEditorStore(re=>re.pythonStdOut),f=t.useEditorStore(re=>re.actions.setRunSql),N=Oe.useEffectiveEditorCardType(),A=N==="table"||N==="detailTable",B=["table","detailTable","aggregateTable","pivotTable"].includes(N||""),w=B&&!!(a!=null&&a.onOpen),D=t.getVisualizationMode(d)==="dynamic",[E,y]=C.useState(!1),M=l??E,b=u??y,{setFrame:R,setCard:k,setActiveTabCardId:F,setCardPreferences:O,mergeDraftsIntoCard:j,clearModeDrafts:T,initializeModeDrafts:L,updatePageSize:V,setCardType:z}=t.useEditorActions(),_=C.useMemo(()=>N!==d.type?{...d,type:N}:d,[d,N]),{data:P,isLoading:q,isFetching:G,errorMessage:Q,errorSql:U,refetch:J,queryKey:X,pagination:se}=n.useEditorCardQuery(_),ue=C.useRef(X);ue.current=X;const{handleDebugWithAssistant:pe}=$n(Q,U),xe=C.useMemo(()=>(P==null?void 0:P.records)||[],[P==null?void 0:P.records]),{cardFilterValues:je}=n.useCardFilterValues((d==null?void 0:d.id)??""),[Pe,Me]=C.useState(!1);C.useEffect(()=>{G||Me(!1)},[G]),C.useEffect(()=>{A&&!v&&!c&&!g&&p(!0)},[g,c,A,v,p]);function te(re,$){var he,de;const H={...d,paginationConfig:{page:re+1,pageSize:$}};k(H);const ne={...o,cards:o.cards.map(Te=>Te.id===d.id?H:Te)};R(ne),d.sql&&((de=(he=d.preferences)==null?void 0:he.tablePrefs)!=null&&de.enableDevModePagination)&&f(!0)}function fe(re){var he,de,Te,De,ae;const $=n.sortStateToSortByColumns(re,(he=d.config)==null?void 0:he.metricColumns,(de=d.config)==null?void 0:de.groupByColumns,(Te=d.config)==null?void 0:Te.detailColumns),H={...d,config:{...d.config||{},sortByColumns:$}};k(H);const ne={...o,cards:o.cards.map(Ee=>Ee.id===d.id?H:Ee)};R(ne),d.sql&&((ae=(De=d.preferences)==null?void 0:De.tablePrefs)!=null&&ae.enableDevModePagination)&&f(!0)}function ke(){var $;const re=JSON.stringify(P==null?void 0:P.records,null,2);typeof navigator>"u"||!(($=navigator.clipboard)!=null&&$.writeText)||navigator.clipboard.writeText(re).catch(H=>{console.error("Failed to copy JSON",H)})}function Be(){const re=JSON.stringify(P==null?void 0:P.records,null,2),$=new Blob([re],{type:"application/json"}),H=URL.createObjectURL($),ne=document.createElement("a");ne.href=H,ne.download=`${d.title}.json`,ne.click()}function ze(){const $=[Object.keys(P==null?void 0:P.records.reduce((de,Te)=>({...de,...Te}),{})).join(","),...((P==null?void 0:P.records)||[]).map(de=>Object.values(de).join(","))].join(`
182
+ `),H=new Blob([$],{type:"text/csv"}),ne=URL.createObjectURL(H),he=document.createElement("a");he.href=ne,he.download=`${d.title}.csv`,he.click()}if(!d)return e.jsx(e.Fragment,{children:"No Active Card"});const ce=r==="both"||r==="toolbar",ve=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:[ce&&e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center gap-2 px-4",children:[v&&e.jsx("div",{className:"flex grow items-center gap-4",children:e.jsx("div",{className:"flex items-center gap-3",children:!h&&!D&&e.jsx(Qn,{selectedChart:d.type,onChartChange:re=>z(re),compactMore:!0})})}),!v&&e.jsx("div",{className:"grow"}),!q&&!G&&!Q&&(P==null?void 0:P.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(Xn,{sql:P.sql})})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[s,je&&je.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:je.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(je,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||G,className:"h-7 w-7 px-0",onClick:()=>{if(Me(!0),c){ft.flushPendingEditorDrafts(),setTimeout(()=>{i.removeQueries({queryKey:ue.current,exact:!0}),f(!0)},0);return}J()},children:e.jsx(n.RefreshCcw,{className:t.cn("h-3.5 w-3.5",{"animate-spin":Pe})})}),!D&&e.jsx(Wn,{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}),B?"Table settings":"Chart settings"]}),(c||g)&&e.jsx(Xr,{}),(c||g)&&A&&e.jsx(Jr,{}),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"}),!D&&!["table","detailTable","custom"].includes(d.type)&&m&&e.jsx(Dr,{triggerVariant:"menu",className:"w-full"}),e.jsx(ws,{triggerVariant:"menu",className:"w-full"}),e.jsx(Ts,{triggerVariant:"menu",className:"w-full"}),e.jsx(Ss,{triggerVariant:"menu",className:"w-full"}),w&&e.jsxs(n.DropdownMenuItem,{onSelect:()=>{var re;return(re=a==null?void 0:a.onOpen)==null?void 0:re.call(a,"style")},className:"gap-2 text-[13px]",children:[e.jsx(za,{className:"h-3.5 w-3.5"}),"Table settings"]}),e.jsx(Jn,{onCustomize:()=>b(!0)}),e.jsx(n.DropdownMenuSeparator,{}),e.jsx(n.DropdownMenuLabel,{children:"Export"}),e.jsxs(n.DropdownMenuItem,{onSelect:ze,className:"gap-2 text-[13px]",children:[e.jsx(n.Download,{className:"h-3.5 w-3.5"}),"Download CSV"]}),e.jsxs(n.DropdownMenuItem,{onSelect:Be,className:"gap-2 text-[13px]",children:[e.jsx(Ma,{className:"h-3.5 w-3.5"}),"Download JSON"]}),e.jsxs(n.DropdownMenuItem,{onSelect:ke,className:"gap-2 text-[13px]",children:[e.jsx(n.Copy,{className:"h-3.5 w-3.5"}),"Copy JSON"]})]})]})]})]}),ve&&(v?D?e.jsx(pt,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(Yn,{fallbackPreview:e.jsx(pt,{}),records:xe,title:d.title,isInspectorOpen:M,onInspectorOpenChange:b})}):e.jsx(pt,{}):e.jsxs(n.ResizablePanelGroup,{className:t.cn(S&&"py-2 pl-2 pr-6"),direction:"horizontal",children:[S&&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:S&&e.jsx(Yr,{})}),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":S}),children:[Array.isArray(P==null?void 0:P.records)&&!Q&&(c?e.jsx(Sr,{data:P.records,card:_,paginationMetadata:se,onPaginationChange:te,onPageSizePreferenceChange:V,onSortChange:fe,isLoading:q||G}):P.records.length>0?e.jsx(n.TableVisual,{card:d,data:xe,totalsByColumnId:P==null?void 0:P.tableTotalsByColumnId,comparisonMetadata:(ye=P==null?void 0:P.metadata)==null?void 0:ye.comparisonMetadata,paginationMetadata:se,onPaginationChange:te,onSortChange:fe,isLoading:q||G}):null),Q&&e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(Cs,{error:Q,errorSql:U||d.sql||d.python,onDebugWithAssistant:pe,showFeedbackButton:!1})})]})]}))]})}function Yr(){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 Jr(){var d,c,x,h,v,p,m,g;const s=t.useEditorStore(S=>S.card),a=t.useEditorStore(S=>S.actions.setCard),r=t.useEditorStore(S=>S.actions.setRunSql),l=t.useEditorStore(S=>S.actions.setCardPreferences),u=t.useEditorStore(S=>S.actions.updateCardInFrame),i=C.useMemo(()=>{var S,f;return n.getTablePageSizeOptions((f=(S=s.preferences)==null?void 0:S.tablePrefs)==null?void 0:f.pageSize)},[(c=(d=s.preferences)==null?void 0:d.tablePrefs)==null?void 0:c.pageSize]),o=n.resolveTablePageSize((h=(x=s.preferences)==null?void 0:x.tablePrefs)==null?void 0:h.pageSize);return s.type!=="table"&&s.type!=="detailTable"?null:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Checkbox,{id:"dev-pagination",checked:((p=(v=s.preferences)==null?void 0:v.tablePrefs)==null?void 0:p.enableDevModePagination)??!1,onCheckedChange:S=>{var f;l({...s.preferences,tablePrefs:{...(f=s.preferences)==null?void 0:f.tablePrefs,enableDevModePagination:S}})}}),e.jsx(t.Label,{htmlFor:"dev-pagination",className:"cursor-pointer text-[13px]",children:"Paginate"}),((g=(m=s.preferences)==null?void 0:m.tablePrefs)==null?void 0:g.enableDevModePagination)&&e.jsxs(t.Select,{value:String(o),onValueChange:S=>{var A,B,w;const f=Number(S),N={...s,preferences:{...s.preferences,tablePrefs:{...(A=s.preferences)==null?void 0:A.tablePrefs,pageSize:f}},paginationConfig:{page:1,pageSize:f}};a(N),u(N),s.sql&&((w=(B=s.preferences)==null?void 0:B.tablePrefs)!=null&&w.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(S=>e.jsx(t.SelectItem,{value:String(S),children:S},S))})]})]})}function Xr(){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 raw output",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:"Raw output"})]})}function Ge({value:s,onCommit:a,type:r="text",placeholder:l,className:u}){const[i,o]=C.useState(s),d=C.useRef(!1);C.useEffect(()=>{o(s)},[s]);const c=()=>{if(d.current){d.current=!1;return}i!==s&&a(i)},x=h=>{if(h.key==="Enter"){h.currentTarget.blur();return}h.key==="Escape"&&(d.current=!0,o(s),h.currentTarget.blur())};return e.jsx(t.Input,{type:r,placeholder:l,value:i,onChange:h=>o(h.target.value),onBlur:c,onKeyDown:x,className:u})}function it({defaultValue:s,label:a,options:r,value:l,onValueChange:u,className:i,icon:o,showPlaceholderLabel:d=!0}){return e.jsxs(t.Select,{defaultValue:s,value:l,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:[o&&e.jsx("span",{children:o}),d&&e.jsx(t.SelectValue,{placeholder:a})]})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:a}),r.map(c=>e.jsx(t.SelectItem,{value:c.value,children:c.label},c.value))]})})]})}function Zr(s,a){return n.getSlotDefinitionForIndex(s,a)||null}function Bt(s){if(typeof s=="number")return`Tab ${s+1}`;const a=s.match(/^(\d+)-(\d+)$/);if(a){const[,l,u]=a;return`Tabs ${Number(l)+1}-${Number(u)+1}`}const r=s.match(/^(\d+)\+$/);return r?`Tabs ${Number(r[1])+1}+`:`Tab ${s}`}function el(s){return s?Array.isArray(s)?s:[s]:[]}function ds(s){var l,u;if(!s)return!1;if(s.type==="text")return!!((l=s.description)!=null&&l.trim());const a=!!((u=s.sql)!=null&&u.trim()),r=t.hasValidCardConfig(s.config);return a||r}function tl({slots:s,cards:a,minInputs:r}){const l=[],u=a.filter(Boolean).length;return r&&u<r&&l.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 c=a[i.position];ds(c)||l.push({type:"missing-required",message:`${Bt(i.position)} ("${i.label}") is required but has no data configured.`});return}const o=i.position.match(/^(\d+)-(\d+)$/);if(o){const[,c,x]=o.map(Number);for(let h=c;h<=x;h+=1){const v=a[h];if(!ds(v)){l.push({type:"missing-required",message:`${Bt(h)} ("${i.label}") is required but has no data configured.`});break}}return}const d=i.position.match(/^(\d+)\+$/);if(d){const c=Number(d[1]);if(a.length<=c){l.push({type:"missing-required",message:`${Bt(c)} ("${i.label}") is required but has no data configured.`});return}for(let x=c;x<a.length;x+=1){const h=a[x];if(!ds(h)){l.push({type:"missing-required",message:`${Bt(x)} ("${i.label}") is required but has no data configured.`});break}}}}),a.forEach((i,o)=>{if(!i)return;const d=Zr(s,o);if(!d||!d.expectedType)return;const c=el(d.expectedType);c.length!==0&&(c.includes(i.type)||l.push({type:"wrong-type",message:`${Bt(o)} ("${d.label}") expects ${c.join(", ")}, but is configured as ${i.type}.`}))})),l}const sl={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 Zn(){var k,F,O;const s=t.useEditorStore(j=>j.card.customCardPreferences),{data:a}=n.usePluginQuery(),r=(a==null?void 0:a.plugins)||[],l=t.useEditorStore(j=>j.card),u=t.useEditorStore(j=>j.frame),{setCustomCardPreferences:i}=t.useEditorActions(),o=C.useMemo(()=>n.findCustomVisualConfigCard(u,l),[u,l]),d=o==null?void 0:o.customCardPreferences,{components:c,manifest:x}=n.useCustomVisual((d==null?void 0:d.url)||(s==null?void 0:s.url)||""),h=(k=x==null?void 0:x.visuals)==null?void 0:k.find(j=>j.name===((d==null?void 0:d.componentName)||(s==null?void 0:s.componentName))),p=n.resolveMultiInputType(o||l,h)==="multiple",m=!!o&&o.id===l.id,g=(h==null?void 0:h.minInputs)??((F=o==null?void 0:o.customCardPreferences)==null?void 0:F.minInputs),S=(h==null?void 0:h.maxInputs)??((O=o==null?void 0:o.customCardPreferences)==null?void 0:O.maxInputs),f=C.useMemo(()=>n.getCustomVisualInputCards({frame:u,configCard:o||l,isMultiInputVisual:p}),[u,o,l,p]),N=C.useMemo(()=>n.buildSlotOrderedCards(f),[f]),A=C.useMemo(()=>N.map((j,T)=>{if(!j)return null;const L=n.getSlotIndexForCard(j,T),V=n.getEffectiveCardTypeForSlot(j,L,h==null?void 0:h.slots);return{...j,type:V??j.type}}),[N,h==null?void 0:h.slots]),B=C.useMemo(()=>tl({slots:h==null?void 0:h.slots,cards:A,minInputs:g}),[h==null?void 0:h.slots,A,g]),w=C.useMemo(()=>{const j=f.findIndex(T=>(T==null?void 0:T.id)===l.id);return j<0?-1:n.getSlotIndexForCard(l,j)},[f,l]);function I(j){if(typeof j=="number")return`Tab ${j+1}`;const T=j.match(/^(\d+)-(\d+)$/);if(T){const[,V,z]=T;return`Tabs ${Number(V)+1}-${Number(z)+1}`}const L=j.match(/^(\d+)\+$/);return L?`Tabs ${Number(L[1])+1}+`:`Tab ${j}`}function D(j){return j?(Array.isArray(j)?j:[j]).join(", "):null}function E(j,T,L=[],V="",z,_,P){const q=y({key:T,defaultValue:V,settingsValue:_,sourceCard:P});return j==="input"?e.jsx(Ge,{className:`h-8 w-full ${t.removeRing}`,value:String(q??""),onCommit:G=>{M({key:T,value:G,settingsField:z,settingsValue:_,sourceCard:P})}},T):j==="select"?e.jsx(it,{className:"h-8 w-full",label:"",options:L,value:String(q!==void 0?q:V??""),onValueChange:G=>{M({key:T,value:G,settingsField:z,settingsValue:_,sourceCard:P})}}):null}function y({key:j,defaultValue:T,settingsValue:L,sourceCard:V}){const z=L==null?void 0:L[j];return z!==void 0?z:j==="title"&&(V==null?void 0:V.title)!==void 0?V.title:j==="description"&&(V==null?void 0:V.description)!==void 0?V.description:T}function M({key:j,value:T,settingsField:L,settingsValue:V,sourceCard:z}){const _={...V||{}},P=j==="title"&&(z==null?void 0:z.title)!==void 0,q=j==="description"&&(z==null?void 0:z.description)!==void 0;P&&T===String((z==null?void 0:z.title)??"")||q&&T===String((z==null?void 0:z.description)??"")?delete _[j]:_[j]=T,i({...s||{},[L]:_})}function b({settingsSchema:j,settingsField:T,settingsValue:L,sourceCard:V,headerLabel:z}){const _=Object.entries(j||{});return e.jsxs("div",{className:"space-y-3",children:[z&&e.jsx(t.Label,{children:z}),_.map(([P,q])=>{var G;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{children:q.title}),((G=q.docs)==null?void 0:G.description)&&e.jsx(t.TooltipProvider,{delayDuration:0,children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{className:"text-xs",children:q.docs.description})})]})})]}),E(q.ui,P,q.options,q.defaultValue,T,L,V)]},P)})]})}function R(){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:h!=null&&h.slots&&h.slots.length>0?e.jsx("div",{className:"space-y-3",children:h.slots.map((j,T)=>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:I(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:[D(j.expectedType)&&e.jsxs("span",{children:["Expected: ",D(j.expectedType)]}),j.required&&e.jsx("span",{children:"Required"})]})]},`${j.label}-${T}`))}):e.jsxs("div",{className:"space-y-1 text-muted-foreground",children:[e.jsx("p",{children:"This visual renders all tabs in a flexible layout. Add as many tabs as needed."}),(g||S)&&e.jsxs("p",{children:[g?`Min ${g} tabs`:"",g&&S?" • ":"",S?`Max ${S} tabs`:""]})]})})]}),p&&B.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:B.map((j,T)=>e.jsx("li",{children:j.message},`${j.type}-${T}`))})})}),h&&!p&&h.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:b({settingsSchema:h.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:l})})}),h&&p&&(h.settings||h.slotSettings)&&e.jsxs("div",{className:"mt-4 space-y-4",children:[m&&h.settings&&e.jsx("div",{className:"px-2",children:b({settingsSchema:h.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:o||l,headerLabel:"Global Settings"})}),h.slotSettings&&e.jsx("div",{className:"px-2",children:b({settingsSchema:h.slotSettings,settingsField:"slotSettings",settingsValue:s==null?void 0:s.slotSettings,sourceCard:l,headerLabel:(()=>{const j=l.tabTitle||l.title,T=w>=0?w:0,L=m?"Slot 0":`Slot ${T}`;return j?`${L}: ${j} Settings`:`${L} 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(it,{icon:e.jsx(Bn,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:r,value:(d==null?void 0:d.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:c&&e.jsx(it,{icon:e.jsx(La,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(c==null?void 0:c.map(j=>({value:j.name,label:j.name})))||[],value:s.componentName||"",onValueChange:j=>{var V;const T=(V=x==null?void 0:x.visuals)==null?void 0:V.find(z=>z.name===j),L=c==null?void 0:c.find(z=>z.name===j);i({...s,componentName:j,visualType:(T==null?void 0:T.visualType)||(L==null?void 0:L.type)||"single",minInputs:T==null?void 0:T.minInputs,maxInputs:T==null?void 0:T.maxInputs,pluginChartType:T==null?void 0:T.chartType})}})})]})})]}),((d==null?void 0:d.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:(h==null?void 0:h.name)||"Settings"}),(h==null?void 0:h.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:[h.docs.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:h.docs.description}),h.docs.dataSchema&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Data Schema"}),e.jsx("div",{className:"prose prose-sm dark:prose-invert prose-pre:bg-muted prose-pre:text-xs max-w-none",children:e.jsx(n.Markdown,{remarkPlugins:[n.remarkGfm],components:sl,children:h.docs.dataSchema})})]}),(()=>{var T;const j=(T=h.docs)==null?void 0:T.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((L,V)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1 text-primary",children:"•"}),e.jsx("span",{children:L})]},V))})]})})()]})})]})]})}),e.jsx(n.AccordionContent,{children:R()})]})]})}function nl({colorRanges:s,setColorRanges:a}){const r={start:-1/0,end:100,color:""};function l(o,d,c){const x=[...s];x[o]={...x[o],[d]:c},a(x)}function u(o){const d=[...s];d.splice(o,1),a(d)}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((o,d)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(t.Input,{onChange:c=>l(d,"start",c.target.value),value:o.start,className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(t.Input,{value:o.end,onChange:c=>l(d,"end",c.target.value),className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx(t.Input,{onChange:c=>l(d,"color",c.target.value),value:o.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(d),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(t.X,{className:"size-3"})})]},d))]})}function al(){var h,v,p,m,g;const s=t.useEditorStore(S=>S.card.preferences),a=t.useEditorStore(S=>S.actions.setCardPreferences),r=t.useEditorStore(S=>S.card),l=t.hasValidCardConfig(r.config),u=t.useEditorStore(S=>S.actions.setNumberFormat);t.useEditorStore(S=>{var f,N;return(N=(f=S.card.preferences)==null?void 0:f.formatNumber)==null?void 0:N.decimalPlaces});const i=t.useEditorStore(S=>{var f,N;return(N=(f=S.card.preferences)==null?void 0:f.formatNumber)==null?void 0:N.locale}),o=t.useEditorStore(S=>{var f,N;return(N=(f=S.card.preferences)==null?void 0:f.formatNumber)==null?void 0:N.currency});t.useEditorStore(S=>S.actions.setFilterOnClickField);const d=t.useEditorStore(S=>{var f,N;return(N=(f=S.card.preferences)==null?void 0:f.formatNumber)==null?void 0:N.colorRanges})||[],c=t.useEditorStore(S=>S.actions.setColorRanges),x=[...new Set(t.LOCALE_CURRENCY_PAIRS.map(S=>S.currency))];return e.jsxs("div",{children:[!l&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(n.Checkbox,{checked:!!((h=s==null?void 0:s.formatNumber)!=null&&h.enabled),onCheckedChange:S=>{a({...s,formatNumber:{...s==null?void 0:s.formatNumber,enabled:S}})}}),e.jsx(t.Label,{children:"Format Number"})]}),(((v=s==null?void 0:s.formatNumber)==null?void 0:v.enabled)===!0||l)&&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:S=>{var f,N,A;return u(((f=s==null?void 0:s.formatNumber)==null?void 0:f.decimalPlaces)||0,((N=s==null?void 0:s.formatNumber)==null?void 0:N.currency)||"",S,((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(S=>e.jsx(t.SelectItem,{value:S.locale,children:S.locale},S.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Currency"}),e.jsxs(t.Select,{value:o||"none",onValueChange:S=>{var f,N,A;console.log("currency",S),u(((f=s==null?void 0:s.formatNumber)==null?void 0:f.decimalPlaces)||0,S==="none"?"":S,((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"),x.map(S=>e.jsx(t.SelectItem,{value:S,children:S},S))]})})]})]})]}),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:S=>{var f,N,A;return u(Number(S),((f=s==null?void 0:s.formatNumber)==null?void 0:f.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(S=>e.jsx(t.SelectItem,{value:S,children:S},S))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Suffix"}),e.jsx(t.Input,{value:((g=s==null?void 0:s.formatNumber)==null?void 0:g.suffix)||"",className:"h-8 font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"K, M, B, %",onChange:S=>{var f,N,A;return u(((f=s==null?void 0:s.formatNumber)==null?void 0:f.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)||"",S.target.value)}})]})]})]})}),e.jsx(t.Separator,{className:"my-3"}),e.jsx(nl,{colorRanges:d,setColorRanges:c})]})]})}const rl={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 ea(s){return rl[s]}function ll({chartType:s,showDocsLink:a=!0}){const r=ea(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((l,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:[l.name,l.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:l.type}),e.jsx("td",{className:"px-2.5 py-1.5 text-muted-foreground",children:l.description||"—"})]},l.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:l=>l.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 ol({chartType:s}){return ea(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(ll,{chartType:s})})]}):null}function es({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(ol,{chartType:s})]})}function il(){return e.jsxs("div",{className:"space-y-6 px-6 py-4",children:[e.jsx(es,{chartType:"kpi"}),e.jsx("section",{children:e.jsx(al,{})})]})}function Sn({children:s,summary:a,open:r,className:l}){return e.jsxs("details",{open:r,className:t.cn("space-y-4 [&_summary>svg]:open:-rotate-180",l),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 cl(){const[s,a]=C.useState([]),r=t.useEditorStore(x=>x.card.preferences),{setFilterOnClickColumnIndex:l,setCardPreferences:u}=t.useEditorStore(x=>x.actions),i=t.useEditorStore(x=>x.queryResultColumns);t.useEditorStore(x=>{var h;return(h=x.card.preferences)==null?void 0:h.filterOnClickColumnIndex}),C.useEffect(()=>{i&&a(new Array(i.length).fill(!1))},[i]);function o(x,h){var v,p;h?r!=null&&r.onClickFilter&&((v=r==null?void 0:r.onClickFilter)==null?void 0:v.length)>0?u({...r,onClickFilter:[...r.onClickFilter,{columnIndex:x,expression:""}]}):u({...r,onClickFilter:[{columnIndex:x,expression:""}]}):(u({...r,onClickFilter:(p=r==null?void 0:r.onClickFilter)==null?void 0:p.filter(m=>m.columnIndex!==x)}),a(m=>{const g=[...m];return g[x]=!1,g}))}function d(x,h){var p;const v=(p=r==null?void 0:r.onClickFilter)==null?void 0:p.map(m=>m.columnIndex===x?{...m,expression:h.target.value}:m);u({...r,onClickFilter:v})}function c(x){var h,v,p,m;if(s!=null&&s[x]||(v=(h=r==null?void 0:r.onClickFilter)==null?void 0:h.find(g=>g.columnIndex===x))!=null&&v.expression)return e.jsx(t.Input,{value:(m=(p=r==null?void 0:r.onClickFilter)==null?void 0:p.find(g=>g.columnIndex===x))==null?void 0:m.expression,onChange:g=>d(x,g),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsx("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:i==null?void 0:i.map((x,h)=>{var v,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:!!((v=r==null?void 0:r.onClickFilter)!=null&&v.find(m=>m.columnIndex===h)),onCheckedChange:m=>o(h,m)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:x}),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===h))&&e.jsx(n.Pencil,{onClick:()=>{a(m=>{const g=[...m];return g[h]=!m[h],g})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),c(h)]})},x)})})}const dl=[{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"}],ul=["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"],ml=ul.map(s=>({label:s,value:s}));function xl(){var c,x,h,v,p,m,g,S,f,N,A,B,w,I,D,E,y,M;const s=t.useEditorStore(b=>b.card),a=(x=(c=s==null?void 0:s.preferences)==null?void 0:c.mapVisualOptions)==null?void 0:x.topoJsonUrl,[r,l]=C.useState(((v=(h=s==null?void 0:s.preferences)==null?void 0:h.mapVisualOptions)==null?void 0:v.customTopoJsonUrl)||""),{setCardPreferences:u}=t.useEditorActions(),{data:i}=n.useTopoJson(s),o=Object.keys((i==null?void 0:i.objects)||{}).map(b=>({label:b,value:b}))||[],d=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(es,{chartType:"map"}),e.jsx(Sn,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(it,{className:"h-9",options:d,onValueChange:b=>{console.log("value",b),u({...s.preferences,mapVisualOptions:{topoJsonUrl:b}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(t.Input,{onChange:b=>{l(b.target.value)},onBlur:()=>{var b;console.log("onBlur",r),u({...s.preferences,mapVisualOptions:{...(b=s.preferences)==null?void 0:b.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(it,{className:"h-9",options:o,value:((m=(p=s.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:m.objectKey)||"",label:"Map Object",onValueChange:b=>{var R;u({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,objectKey:b}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Projection"}),e.jsx(it,{className:"h-9",options:dl,value:((S=(g=s.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:S.projection)||"",label:"Projection",onValueChange:b=>{var R;u({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,projection:b}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Colors"}),e.jsx(it,{className:"h-9",options:ml,value:((N=(f=s.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:N.colorScale)||"",label:"Select Color Scale",onValueChange:b=>{var R;u({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,colorScale:b}})}})]})]})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(Sn,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:.1,value:((B=(A=s.preferences)==null?void 0:A.mapVisualOptions)==null?void 0:B.projectionScale)||1,onChange:b=>{var R;u({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,projectionScale:Number(b.target.value)}})}}),e.jsx(t.Label,{children:"X"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((D=(I=(w=s.preferences)==null?void 0:w.mapVisualOptions)==null?void 0:I.projectionOffset)==null?void 0:D[0])||0,onChange:b=>{var R,k,F,O;u({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,projectionOffset:[Number(b.target.value),((O=(F=(k=s.preferences)==null?void 0:k.mapVisualOptions)==null?void 0:F.projectionOffset)==null?void 0:O[1])||0]}})}}),e.jsx(t.Label,{children:"Y"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((M=(y=(E=s.preferences)==null?void 0:E.mapVisualOptions)==null?void 0:y.projectionOffset)==null?void 0:M[1])||0,onChange:b=>{var R,k,F,O;u({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,projectionOffset:[((O=(F=(k=s.preferences)==null?void 0:k.mapVisualOptions)==null?void 0:F.projectionOffset)==null?void 0:O[0])||0,Number(b.target.value)]}})}})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(cl,{})]})}function Jt(s){return s==="currency"?2:s==="percent"?1:s==="scientific"?2:0}function wn(s,a){if(!a||a==="auto")return{type:"auto"};const r={...s,type:a,multiplyBy:a==="percent"?s.multiplyBy:void 0,percentValueMode:a==="percent"?s.percentValueMode:void 0};return a&&["number","currency","percent","scientific"].includes(a)&&s.decimalPlaces===void 0&&s.minimumFractionDigits===void 0&&s.maximumFractionDigits===void 0?vs(r,Jt(a)):r}function vs(s,a){return{...s,decimalPlaces:a,minimumFractionDigits:a,maximumFractionDigits:a}}const hl=["auto","number","currency","percent","scientific","date"],pl=[{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"}],fl=[{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"}],gl=s=>s.charAt(0).toUpperCase()+s.slice(1);function Tt({formatOptions:s={},onFormatOptionsChange:a,showTitle:r=!0,title:l="NUMBER FORMAT"}){const u=s.type||"auto",i=u==="auto"?s:wn(s,u),o=m=>{m.stopPropagation()},d=(m,g)=>{a({...i,[m]:g})},[c,x]=C.useState(()=>String(i.decimalPlaces??Jt(u))),[h,v]=C.useState(()=>i.multiplyBy!==void 0?String(i.multiplyBy):""),p=m=>{a(wn(s,m))};return C.useEffect(()=>{x(String(i.decimalPlaces??Jt(u)))},[i.decimalPlaces,u]),C.useEffect(()=>{v(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-xs font-medium text-muted-foreground",children:l}),e.jsxs(t.Select,{value:u,onValueChange:m=>p(m),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",onClick:o,onPointerDown:o,onKeyDown:o,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:hl.map(m=>e.jsx(t.SelectItem,{value:m,className:"text-xs",children:m==="auto"?"Auto (Default)":gl(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:c,onClick:o,onPointerDown:o,onKeyDown:o,onChange:m=>{const g=m.target.value.replace(/[^\d]/g,"");x(g),g!==""&&a(vs(i,Math.max(0,Math.min(10,parseInt(g,10)))))},onBlur:()=>{if(c!=="")return;const m=Jt(u);x(String(m)),a(vs(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=>d("currency",m),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:o,onPointerDown:o,onKeyDown:o,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:pl.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=>d("useSuffix",m)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(t.Select,{value:s.locale||"en-US",onValueChange:m=>d("locale",m),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:o,onPointerDown:o,onKeyDown:o,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:fl.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:o,onPointerDown:o,onKeyDown:o,onChange:m=>d("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:o,onPointerDown:o,onKeyDown:o,onChange:m=>d("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=>d("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:h,onClick:o,onPointerDown:o,onKeyDown:o,onChange:m=>{const g=m.target.value.replace(/[^0-9.]/g,"");v(g),d("multiplyBy",g?parseFloat(g):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:o,onPointerDown:o,onKeyDown:o,onChange:m=>d("dateFormat",m.target.value),className:"h-8 text-xs"})})]})]})]})}const bl=[{value:"difference",label:"Difference"},{value:"change",label:"Change (%)"},{value:"change_difference",label:"Change + Difference"},{value:"ratio",label:"Ratio"}],jl=[{value:"arrow_badge",label:"Arrow + Badge"},{value:"arrow",label:"Arrow Only"},{value:"badge",label:"Badge Only"},{value:"none",label:"None"}];function ta({cardType:s,queryResultColumns:a,focusSection:r,focusRequestId:l}){var z,_,P,q,G,Q,U;const u=t.useEditorStore(J=>J.card),i=t.useEditorStore(J=>J.queryResultColumns),o=t.useEditorStore(J=>{var X;return(X=J.card)==null?void 0:X.preferences}),d=o==null?void 0:o.tablePrefs,c=t.useEditorStore(J=>J.actions.setCardPreferences),x=t.useEditorStore(J=>J.actions.updateTableConditionalFormatting),h=((z=u.config)==null?void 0:z.metricColumns)||[],v=s??u.type,p=a??i,m=u.type===v?u:{...u,type:v},g=n.getTableConditionalFormattingColumnOptions(m,p),S=n.supportsTableConditionalFormatting(v),f=v==="table",N=((_=g[0])==null?void 0:_.value)||"",A=n.normalizeConditionalFormatting((P=o==null?void 0:o.tablePrefs)==null?void 0:P.conditionalFormatting),B=n.resolveTablePresentationStyle(d),w=n.isEligibleFlatTableTotalsCard(m),I=n.hasFlatTableTotalsBehavior(m),[D,E]=C.useState("style");C.useEffect(()=>{if(r==="style"){E("style");return}r==="conditional-formatting"&&S&&E("conditional-formatting")},[S,l,r]);const y=h.some(J=>J.comparisonType&&J.comparisonType!=="none"),M=((q=o==null?void 0:o.tableVisualOptions)==null?void 0:q.metricComparison)||{},b=J=>{c({...o,tableVisualOptions:{...o==null?void 0:o.tableVisualOptions,metricComparison:{...M,...J}}})},R={increase:((G=M.colors)==null?void 0:G.increase)||"green",decrease:((Q=M.colors)==null?void 0:Q.decrease)||"red",neutral:((U=M.colors)==null?void 0:U.neutral)||"neutral"},k=J=>{x({version:1,rules:J})},F=J=>{c({...o,tablePrefs:{...d,density:J}})},O=J=>{c({...o,tablePrefs:{...d,tableStyle:{...d==null?void 0:d.tableStyle,...J}}})},j=J=>{var X;O({totals:{...(X=d==null?void 0:d.tableStyle)==null?void 0:X.totals,...J}})},T=J=>{var X;c({...o,tablePrefs:{...d,tableStyle:{...d==null?void 0:d.tableStyle,totals:{...(X=d==null?void 0:d.tableStyle)==null?void 0:X.totals,enabled:J}}}})},L=()=>{c({...o,tablePrefs:{...d,density:n.TABLE_PRESENTATION_DEFAULT_STYLE.density,tableStyle:{headerStyle:n.TABLE_PRESENTATION_DEFAULT_STYLE.headerStyle,stripedRows:n.TABLE_PRESENTATION_DEFAULT_STYLE.stripedRows,wrapText:n.TABLE_PRESENTATION_DEFAULT_STYLE.wrapText,totals:{enabled:w?I: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}}}})},V=y?e.jsx(vl,{calculatedAs:M.calculatedAs??"change_difference",indicatorStyle:M.indicatorStyle??"arrow_badge",formatOptions:M.formatOptions??{},colors:R,lowerIsBetter:M.lowerIsBetter??!1,onUpdate:b}):null;return e.jsx("div",{className:"px-4 py-3",children:e.jsxs(t.Tabs,{value:D,onValueChange:J=>E(J),className:"space-y-4",children:[e.jsxs(t.TabsList,{variant:"underline",children:[e.jsx(t.TabsTrigger,{value:"style",children:"Appearance"}),e.jsx(t.TabsTrigger,{value:"conditional-formatting",disabled:!S,children:"Conditional formatting"})]}),e.jsx(t.TabsContent,{value:"style",className:"mt-0",children:e.jsx(n.TablePresentationSettings,{style:B,onDensityChange:F,onStyleChange:O,showFullStyle:f,showBorderStyle:!1,totals:f&&w?{enabled:I,onEnabledChange:T,onStyleChange:j}:void 0,extraSection:V,onReset:f?L:void 0})}),e.jsx(t.TabsContent,{value:"conditional-formatting",className:"mt-0",children:S?N?e.jsx(n.DataTableConditionalFormattingSettings,{columnId:N,availableColumns:g,conditionalRules:A.rules,onConditionalRulesChange:k,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 vl({calculatedAs:s,indicatorStyle:a,formatOptions:r,colors:l,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(Vt,{label:"Calc as",children:e.jsxs(t.Select,{value:s,onValueChange:o=>i({calculatedAs:o}),children:[e.jsx(t.SelectTrigger,{size:"xs",className:"w-full",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:bl.map(o=>e.jsx(t.SelectItem,{value:o.value,children:o.label},o.value))})]})}),e.jsx(Vt,{label:"Indicator",children:e.jsxs(t.Select,{value:a,onValueChange:o=>i({indicatorStyle:o}),children:[e.jsx(t.SelectTrigger,{size:"xs",className:"w-full",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:jl.map(o=>e.jsx(t.SelectItem,{value:o.value,children:o.label},o.value))})]})}),e.jsx(Vt,{label:"Format",align:"start",children:e.jsx(Tt,{formatOptions:r,onFormatOptionsChange:o=>i({formatOptions:o}),showTitle:!1})}),e.jsx(Vt,{label:"Colors",align:"start",children:e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ms,{label:"Increase",value:us(l.increase),defaultValue:"#16a34a",onChange:o=>i({colors:{...l,increase:o??"#16a34a"}})}),e.jsx(ms,{label:"Decrease",value:us(l.decrease),defaultValue:"#dc2626",onChange:o=>i({colors:{...l,decrease:o??"#dc2626"}})}),e.jsx(ms,{label:"No change",value:us(l.neutral),defaultValue:"#6b7280",onChange:o=>i({colors:{...l,neutral:o??"#6b7280"}})})]})}),e.jsx(Vt,{label:"Lower is better",children:e.jsx(n.Checkbox,{checked:u,onCheckedChange:o=>i({lowerIsBetter:!!o})})})]})]})}function Vt({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 yl={green:"#16a34a",red:"#dc2626",neutral:"#6b7280"};function us(s){return s&&(yl[s]??s)}function ms({label:s,value:a,onChange:r,defaultValue:l}){return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.ColorField,{value:a,onChange:r,defaultValue:l,ariaLabel:s,allowEmpty:!1}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:s})]})}function Cl(){var l;const s=t.useEditorStore(u=>u.card.preferences),{setCardPreferences:a}=t.useEditorStore(u=>u.actions);function r(u){a({...s,textVisualOptions:{...s==null?void 0:s.textVisualOptions,isDynamicText:u==="dynamic"}})}return e.jsxs(n.RadioGroup,{value:(l=s==null?void 0:s.textVisualOptions)!=null&&l.isDynamicText?"dynamic":"static",onValueChange:r,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(n.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(n.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function Nl(){return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(es,{chartType:"text"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Text Type"}),e.jsx(Cl,{})]})]})}function Sl({color:s,onColorChange:a,onClose:r}){const[l,u]=C.useState(0),[i,o]=C.useState(100),[d,c]=C.useState(50),[x,h]=C.useState(s);C.useEffect(()=>{const f=Tn(s);if(f){const N=En(f.r,f.g,f.b);u(N.h),o(N.s),c(N.l),h(s)}},[s]);const v=f=>{u(f),m(f,i,d)},p=f=>{const N=f.currentTarget.getBoundingClientRect(),A=Math.max(0,Math.min(1,(f.clientX-N.left)/N.width)),B=Math.max(0,Math.min(1,(f.clientY-N.top)/N.height)),w=A*100,I=(1-B)*100;o(w),c(I),m(l,w,I)},m=(f,N,A)=>{const B=Tl(f,N,A),w=wl(B.r,B.g,B.b);h(w)},g=f=>{if(h(f),/^#[0-9A-Fa-f]{6}$/.test(f)){const N=Tn(f);if(N){const A=En(N.r,N.g,N.b);u(A.h),o(A.s),c(A.l)}}},S=()=>{/^#[0-9A-Fa-f]{6}$/.test(x)&&(a(x),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(${l}, 100%, 50%)`},onClick:p,onMouseMove:f=>{f.buttons===1&&p(f)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${i}%`,top:`${100-d}%`,backgroundColor:x}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:l,onChange:f=>v(Number(f.target.value)),className:"w-full h-4 rounded-lg appearance-none cursor-pointer",style:{background:"linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"}})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"HEX"}),e.jsx(t.Input,{value:x,onChange:f=>g(f.target.value),placeholder:"#000000",className:"font-mono"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:s}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:x}}),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:S,children:"OK"})]})]})}function Tn(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 wl(s,a,r){return"#"+((1<<24)+(s<<16)+(a<<8)+r).toString(16).slice(1)}function En(s,a,r){s/=255,a/=255,r/=255;const l=Math.max(s,a,r),u=Math.min(s,a,r);let i=0,o=0;const d=(l+u)/2;if(l!==u){const c=l-u;switch(o=d>.5?c/(2-l-u):c/(l+u),l){case s:i=((a-r)/c+(a<r?6:0))/6;break;case a:i=((r-s)/c+2)/6;break;case r:i=((s-a)/c+4)/6;break}}return{h:Math.round(i*360),s:Math.round(o*100),l:Math.round(d*100)}}function Tl(s,a,r){s/=360,a/=100,r/=100;let l,u,i;if(a===0)l=u=i=r;else{const o=(x,h,v)=>(v<0&&(v+=1),v>1&&(v-=1),v<.16666666666666666?x+(h-x)*6*v:v<.5?h:v<.6666666666666666?x+(h-x)*(.6666666666666666-v)*6:x),d=r<.5?r*(1+a):r+a-r*a,c=2*r-d;l=o(c,d,s+1/3),u=o(c,d,s),i=o(c,d,s-1/3)}return{r:Math.round(l*255),g:Math.round(u*255),b:Math.round(i*255)}}const El=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function Il(){var I,D,E,y,M,b,R,k,F,O;const s=t.useEditorStore(j=>j.card),a=t.useEditorStore(j=>{var T;return(T=j.card)==null?void 0:T.preferences}),r=Oe.useEffectiveEditorCardType(),{setCardPreferences:l,updateCardInFrame:u}=t.useEditorActions(),i=C.useMemo(()=>r!==s.type?{...s,type:r}:s,[s,r]),{data:o}=n.useEditorCardQuery(i),[d,c]=C.useState({}),[x,h]=C.useState(null),[v,p]=C.useState(null),m=C.useMemo(()=>{var V,z,_,P,q,G,Q;if(!(o!=null&&o.records)||o.records.length===0)return[];const j=r==="stackedBar"||r==="stackedLine",T=r==="bar"||r==="line"||r==="horizontalBar"||r==="bullet"||r==="combo"||r==="area"||r==="stackedArea",L=((V=s==null?void 0:s.config)==null?void 0:V.pivotByColumns)&&s.config.pivotByColumns.length>0;if((j||T)&&L){if(o.pivotSchema&&Array.isArray(o.pivotSchema)){const U=new Set;return o.pivotSchema.forEach(J=>{J.alias&&U.add(J.alias)}),Array.from(U)}if(o.records.length>0){const U=o.records[0],J=Object.keys(U),X=new Set;(z=s==null?void 0:s.config)!=null&&z.groupByColumns&&s.config.groupByColumns.forEach(pe=>{X.add(pe.label||pe.name),X.add(pe.alias||pe.name)});const se=new Set;return(_=s==null?void 0:s.config)!=null&&_.metricColumns&&s.config.metricColumns.forEach(pe=>{const xe=pe.alias||pe.name;se.add(xe),se.add(`${xe}_count`),se.add(`${xe}_sum`),se.add(`${xe}_avg`),se.add(`${xe}_min`),se.add(`${xe}_max`);const je=pe.entityName||pe.qualifiedEntityName;je&&(se.add(`${je}_${xe}`),se.add(`${je}_${xe}_count`))}),J.filter(pe=>!X.has(pe)&&!se.has(pe))}}if((T||j)&&!L&&((q=(P=s==null?void 0:s.config)==null?void 0:P.metricColumns)!=null&&q.length))return s.config.metricColumns.map(U=>U.alias||U.label||U.name);if((Q=(G=s==null?void 0:s.config)==null?void 0:G.groupByColumns)!=null&&Q.length){const U=s.config.groupByColumns[0],J=U.label||U.name,X=new Set;return o.records.forEach(se=>{const ue=se[J];ue!=null&&X.add(String(ue))}),Array.from(X)}return[]},[o,(I=s==null?void 0:s.config)==null?void 0:I.groupByColumns,(D=s==null?void 0:s.config)==null?void 0:D.pivotByColumns,(E=s==null?void 0:s.config)==null?void 0:E.metricColumns,r]),g=C.useMemo(()=>n.getDefaultChartColors(),[]);C.useEffect(()=>{const j={};m.forEach((T,L)=>{j[T]=n.getColorForValue(T,L,a==null?void 0:a.colorConfig)}),c(j)},[m,a==null?void 0:a.colorConfig,g]);const S=(j,T)=>{const L={...d,[j]:T};c(L);const V={...a||{},colorConfig:{segments:L}};l(V);const z={...s,preferences:V};u(z)},f=(j,T)=>{var q;const L=g[T%g.length],{[j]:V,...z}=((q=a==null?void 0:a.colorConfig)==null?void 0:q.segments)||{},_={...a||{},colorConfig:{segments:z}};l(_);const P={...s,preferences:_};u(P),c(G=>({...G,[j]:L}))};if(!m.length||!((s==null?void 0:s.type)==="stackedBar"||(s==null?void 0:s.type)==="stackedLine"?((M=(y=s==null?void 0:s.config)==null?void 0:y.groupByColumns)==null?void 0:M.length)||((R=(b=s==null?void 0:s.config)==null?void 0:b.pivotByColumns)==null?void 0:R.length):(F=(k=s==null?void 0:s.config)==null?void 0:k.groupByColumns)==null?void 0:F.length)||["table","kpi","text","custom","heatmap"].includes(r))return null;const B=()=>{const j={...a||{},colorConfig:{segments:{}}};l(j);const T={...s,preferences:j};u(T);const L={};m.forEach((V,z)=>{L[V]=n.getColorForValue(V,z,void 0)}),c(L)},w=Object.keys(((O=a==null?void 0:a.colorConfig)==null?void 0:O.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(Ta.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:w&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:B,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,T)=>{const L=n.isDefaultColor(d[j],T),V=!L;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Popover,{open:x===j,onOpenChange:z=>h(z?j:null),children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"h-5 w-5 shrink-0 rounded border border-input shadow-sm transition-colors hover:border-gray-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",style:{backgroundColor:d[j]}})}),e.jsx(t.PopoverContent,{align:"start",className:"w-auto p-3",children:e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Theme Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:g.slice(0,10).map((z,_)=>e.jsxs("button",{className:t.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",d[j]===z?"border-gray-900":"border-transparent"),style:{backgroundColor:z},onClick:()=>{S(j,z),h(null)},children:[_===T%g.length&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-white/90 px-0.5 text-[8px] font-bold text-gray-900 shadow-sm",children:"D"})}),e.jsx("span",{className:"sr-only",children:z})]},`default-${_}`))})]}),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:El.map((z,_)=>e.jsx("button",{className:t.cn("h-5 w-5 rounded border transition-all hover:scale-110",d[j]===z?"border-2 border-gray-900":z==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:z},onClick:()=>{S(j,z),h(null)},children:e.jsx("span",{className:"sr-only",children:z})},`preset-${_}`))})]}),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:d[j]}),h(null)},children:"Custom color"}),!L&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{f(j,T),h(null)},children:[e.jsx(t.RotateCcw,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:j}),V&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},j)})}),v&&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(Sl,{color:v.color,onColorChange:j=>{S(v.value,j),p(null)},onClose:()=>p(null)})})]})]})})]})}function Xe({value:s,onSave:a,placeholder:r="",type:l="text",className:u=""}){const[i,o]=C.useState(s??""),[d,c]=C.useState(!1);C.useEffect(()=>{o(s??"")},[s]);const x=()=>{a(i),c(!1)},h=()=>{o(s??""),c(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${u}`,children:[e.jsx(t.Input,{placeholder:r,type:l,value:d?i:s??"",onChange:v=>{o(v.target.value),c(!0)},onFocus:()=>c(!0),onClick:v=>v.stopPropagation(),className:"h-8 text-xs",onPointerDown:v=>v.stopPropagation(),onKeyDown:v=>{v.stopPropagation(),v.key==="Enter"&&d&&i!==s?x():v.key==="Escape"&&h()},"aria-label":r||"Edit field"}),d&&i!==s&&e.jsxs(e.Fragment,{children:[e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:x,children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:h,children:e.jsx(t.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function xs({axis:s,label:a,type:r,config:l,onChange:u,defaultTitle:i,hidePosition:o}){var g,S,f,N,A,B,w,I,D,E,y,M,b,R;const d=n.normalizeContextFormatMode({formatMode:l==null?void 0:l.formatMode,formatOptions:l==null?void 0:l.formatOptions}),c=(k,F)=>{u({...l??{},[k]:F})},x=(k,F)=>{var L,V,z,_;const O=k==="enabled"&&F===!0,j=(L=l==null?void 0:l.name)==null?void 0:L.text,T=O&&!j&&i;u({...l??{},name:{...l==null?void 0:l.name,enabled:k==="enabled"?F:((V=l==null?void 0:l.name)==null?void 0:V.enabled)??!1,text:k==="text"?F:T?i:j,fontSize:k==="fontSize"?F:(z=l==null?void 0:l.name)==null?void 0:z.fontSize,fontWeight:k==="fontWeight"?F:(_=l==null?void 0:l.name)==null?void 0:_.fontWeight}})},h=(k,F)=>{var O,j;u({...l??{},labels:{enabled:k==="enabled"?F:((O=l==null?void 0:l.labels)==null?void 0:O.enabled)??!0,rotation:k==="rotation"?F:(j=l==null?void 0:l.labels)==null?void 0:j.rotation}})},v=(k,F)=>{u({...l??{},scale:{...l==null?void 0:l.scale,[k]:F===""?"auto":Number(F)}})},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:(l==null?void 0:l.enabled)!==!1,onCheckedChange:k=>c("enabled",k),onClick:k=>k.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:((g=l==null?void 0:l.name)==null?void 0:g.enabled)??!1,onCheckedChange:k=>x("enabled",k===!0)}),e.jsx(t.Label,{htmlFor:`${s}-title-enabled`,className:"text-xs font-medium cursor-pointer",children:"TITLE"})]}),((S=l==null?void 0:l.name)==null?void 0:S.enabled)&&e.jsxs("div",{className:"space-y-2 pl-6",children:[e.jsx(Xe,{placeholder:`${a} title`,value:((f=l==null?void 0:l.name)==null?void 0:f.text)||"",onSave:k=>x("text",k),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(Xe,{type:"number",placeholder:"12",value:String(((N=l==null?void 0:l.name)==null?void 0:N.fontSize)||12),onSave:k=>x("fontSize",Number(k)||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=l==null?void 0:l.name)==null?void 0:A.fontWeight)||"normal",onValueChange:k=>x("fontWeight",k),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"})]})]})]})]})]})]}),!o&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(t.Select,{value:(l==null?void 0:l.position)||"auto",onValueChange:k=>c("position",k),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:p.map(k=>e.jsx(t.SelectItem,{value:k,className:"text-xs",children:k==="auto"?"Auto (Default)":t.titleCase(k)},k))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(t.Switch,{size:"sm",checked:((B=l==null?void 0:l.labels)==null?void 0:B.enabled)!==!1,onCheckedChange:k=>h("enabled",k)})]}),((w=l==null?void 0:l.labels)==null?void 0:w.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(((I=l==null?void 0:l.labels)==null?void 0:I.rotation)||"auto"),onValueChange:k=>h("rotation",k==="auto"?"auto":Number(k)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:m.map(k=>e.jsx(t.SelectItem,{value:k,className:"text-xs",children:k==="auto"?"Auto (Default)":`${k}°`},k))})]})]})]}),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:d==="override",onCheckedChange:k=>u({...l,formatMode:k?"override":"inherit"})})]}),d==="override"&&e.jsx(Tt,{formatOptions:(l==null?void 0:l.formatOptions)||{},onFormatOptionsChange:k=>u({...l,formatMode:"override",formatOptions:k}),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(Xe,{type:"number",placeholder:"auto",value:((D=l==null?void 0:l.scale)==null?void 0:D.min)==="auto"||((E=l==null?void 0:l.scale)==null?void 0:E.min)===void 0?"":String(l.scale.min),onSave:k=>v("min",k),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(Xe,{type:"number",placeholder:"auto",value:((y=l==null?void 0:l.scale)==null?void 0:y.max)==="auto"||((M=l==null?void 0:l.scale)==null?void 0:M.max)===void 0?"":String(l.scale.max),onSave:k=>v("max",k),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(Xe,{type:"number",placeholder:"auto",value:((b=l==null?void 0:l.scale)==null?void 0:b.stepSize)==="auto"||((R=l==null?void 0:l.scale)==null?void 0:R.stepSize)===void 0?"":String(l.scale.stepSize),onSave:k=>v("stepSize",k),className:""})})]})]})]})]})]})}function hs(s,a,r){var i,o,d;if(s==="x"){const c=(o=(i=a==null?void 0:a.config)==null?void 0:i.groupByColumns)==null?void 0:o[0];return(c==null?void 0:c.label)||(c==null?void 0:c.name)||""}const l=((d=a==null?void 0:a.config)==null?void 0:d.metricColumns)||[],u=(r==null?void 0:r.datasetOptions)||[];if(s==="y"){const c=l.filter((x,h)=>{const v=u.find(p=>p.idx===h);return!v||v.yAxisId!=="y2"});return c.length===1&&(c[0].label||c[0].name)||""}if(s==="y2"){const c=l.filter((x,h)=>{const v=u.find(p=>p.idx===h);return(v==null?void 0:v.yAxisId)==="y2"});return c.length===1&&(c[0].label||c[0].name)||""}return""}function Dl(){const s=t.useEditorStore(c=>c.card),a=t.useEditorStore(c=>{var x;return(x=c.card)==null?void 0:x.preferences}),{setCardPreferences:r,updateCardInFrame:l}=t.useEditorActions(),u=Oe.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 o=(c,x)=>{let h;c==="x"?h="xAxisConfig":c==="y"?h="yAxisConfig":h="secondaryYAxisConfig";const v={...a||{},[h]:x};r(v);const p={...s,preferences:v};l(p)},d=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(xs,{axis:"x",label:"X-Axis",type:i.xAxisType,config:n.mergeAxisConfig(n.getDefaultAxisConfig(u,"x"),a==null?void 0:a.xAxisConfig),onChange:c=>o("x",c),defaultTitle:hs("x",s,a)}),i.hasYAxis&&e.jsx(xs,{axis:"y",label:d?"Y-Axis (Left)":"Y-Axis",type:i.yAxisType,config:n.mergeAxisConfig(n.getDefaultAxisConfig(u,"y"),a==null?void 0:a.yAxisConfig),onChange:c=>o("y",c),defaultTitle:hs("y",s,a)}),d&&e.jsx(xs,{axis:"y2",label:"Y2-Axis (Right)",type:"value",config:n.mergeAxisConfig({enabled:!0,position:"right"},a==null?void 0:a.secondaryYAxisConfig),onChange:c=>o("y2",c),defaultTitle:hs("y2",s,a),hidePosition:!0})]})})]})}function kl(){const s=t.useEditorStore(v=>v.card),a=Oe.useEffectiveEditorCardType(),r=t.useEditorStore(v=>{var p,m,g,S;return(S=(g=(m=(p=v.card)==null?void 0:p.preferences)==null?void 0:m.chartOptions)==null?void 0:g.plugins)==null?void 0:S.legend}),{setLegendOptions:l}=t.useEditorActions();if(!s||!n.chartSupportsLegend(a))return null;const u=n.getDefaultLegendConfig(a),i=(u==null?void 0:u.display)??!0,o=(u==null?void 0:u.position)??"top",d=(u==null?void 0:u.align)??"center",c=(v,p)=>{const m={...r,[v]:p};l(m)},x=["top","bottom","left","right"],h=["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(Pa,{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:v=>c("display",v)})]}),((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)||o,onValueChange:v=>c("position",v),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:x.map(v=>e.jsx(t.SelectItem,{value:v,className:"text-xs",children:t.titleCase(v)},v))})]})]}),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)||d,onValueChange:v=>c("align",v),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:h.map(v=>e.jsx(t.SelectItem,{value:v,className:"text-xs",children:t.titleCase(v)},v))})]})]})]})]})})]})}function Al(){var F,O,j,T,L,V,z;const s=t.useEditorStore(_=>_.card),a=Oe.useEffectiveEditorCardType(),r=t.useEditorStore(_=>{var P,q;return(q=(P=_.card)==null?void 0:P.preferences)==null?void 0:q.dataLabelsConfig}),l=t.useEditorStore(_=>{var P;return(P=_.card)==null?void 0:P.preferences}),{setCardPreferences:u,updateCardInFrame:i}=t.useEditorActions();if(!s||!n.chartSupportsDataLabels(a))return null;const o=a==="bullet"?((F=l==null?void 0:l.bulletConfig)==null?void 0:F.orientation)??(((O=l==null?void 0:l.chartOptions)==null?void 0:O.indexAxis)==="x"?"vertical":"horizontal"):void 0,d=o!=null?o==="horizontal":((j=l==null?void 0:l.chartOptions)==null?void 0:j.indexAxis)==="y",c=a==="stackedBar"||a==="stackedLine",x=a==="pie"||a==="doughnut"||a==="polarArea"||a==="funnel",h=a==="bubble"||a==="scatter",v=(L=(T=l==null?void 0:l.chartOptions)==null?void 0:T.plugins)==null?void 0:L.datalabels,p=(v==null?void 0:v.display)!==!1&&((v==null?void 0:v.anchor)||(v==null?void 0:v.align)),m=n.getDefaultDataLabelsConfig(a,s.preferences),g=r??m,S=(m==null?void 0:m.enabled)??p??!1,f=(r==null?void 0:r.enabled)!==void 0?r.enabled:S,N=(_,P)=>{const Q={...m??{},...r??{},[_]:P};_==="enabled"&&(Q.display=P,P&&h&&!Q.position&&(Q.position="bottom")),_==="position"&&h&&(Q.position="bottom"),_==="formatMode"&&P==="inherit"&&(Q.format=void 0,Q.formatOptions=void 0);const U={...s.preferences||{},dataLabelsConfig:Q};u(U);const J={...s,preferences:U};i(J)},A=(_,P)=>{const q=r??{},Q={...m??{},...q,font:{...q.font||{},[_]:P}},U={...s.preferences||{},dataLabelsConfig:Q};u(U);const J={...s,preferences:U};i(J)},B=()=>{const _=a;return _==="stackedBar"||_==="stackedLine"||_==="pie"||_==="doughnut"?"center":d?"right":"top"},w=a!=="treemap"&&a!=="heatmap",I=a!=="treemap",D=B();let E=[];if(w)if(h)E=["bottom"];else if(c||x)E=["center"];else{const _=d?["center","left","right"]:["center","top","bottom"];E=["auto",...a==="bullet"?_:_.filter(q=>q!==D),"custom"]}const y=()=>t.titleCase(D),M=["center","start","end"],b=["center","start","end","top","bottom"],R=(g==null?void 0:g.formatMode)||(g!=null&&g.format&&!["auto"].includes(g.format)?"override":"inherit"),k=(g==null?void 0:g.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(Ja,{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:f,onCheckedChange:_=>N("enabled",_)})]}),f&&e.jsxs(e.Fragment,{children:[w&&!c&&!x&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(t.Select,{value:h?(g==null?void 0:g.position)||"bottom":(g==null?void 0:g.position)||"auto",onValueChange:_=>N("position",_),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:E.map(_=>e.jsx(t.SelectItem,{value:_,className:"text-xs",children:_==="auto"?y():_==="custom"?"Custom (Advanced)":t.titleCase(_)},_))})]})]}),c&&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:_=>N("showTotal",_)})]}),(g==null?void 0:g.position)==="custom"&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground w-16",children:"Anchor"}),e.jsxs(t.Select,{value:(g==null?void 0:g.anchor)||"center",onValueChange:_=>N("anchor",_),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:M.map(_=>e.jsx(t.SelectItem,{value:_,className:"text-xs",children:t.titleCase(_)},_))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground w-16",children:"Align"}),e.jsxs(t.Select,{value:String((g==null?void 0:g.align)||"center"),onValueChange:_=>N("align",_),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:b.map(_=>e.jsx(t.SelectItem,{value:_,className:"text-xs",children:t.titleCase(_)},_))})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Format"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Keep this off to inherit from the bound metric."})]}),e.jsx(t.Switch,{size:"sm",checked:R==="override",onCheckedChange:_=>N("formatMode",_?"override":"inherit")})]}),R==="override"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Raw Value"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Show the unformatted numeric value."})]}),e.jsx(t.Switch,{size:"sm",checked:k,onCheckedChange:_=>{const P=r??{},G={...m??{},...P,formatMode:"override",format:_?"none":void 0,formatOptions:_?void 0:P.formatOptions},Q={...s.preferences||{},dataLabelsConfig:G};u(Q),i({...s,preferences:Q})}})]}),!k&&e.jsx(Tt,{formatOptions:(g==null?void 0:g.formatOptions)||{},onFormatOptionsChange:_=>{const G={...m??{},...r??{},formatMode:"override",format:_.type&&_.type!=="auto"?_.type:void 0,formatOptions:_},Q={...s.preferences||{},dataLabelsConfig:G};u(Q),i({...s,preferences:Q})},showTitle:!1})]})]}),I&&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(Xe,{type:"number",placeholder:"12",value:String(((V=g==null?void 0:g.font)==null?void 0:V.size)||12),onSave:_=>A("size",Number(_)),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground w-20",children:"Weight"}),e.jsxs(t.Select,{value:((z=g==null?void 0:g.font)==null?void 0:z.weight)||"normal",onValueChange:_=>A("weight",_),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(t.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground w-20",children:"Color"}),e.jsxs(t.Select,{value:(g==null?void 0:g.color)==="auto"||!(g!=null&&g.color)?"auto":"custom",onValueChange:_=>{_==="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(Xe,{type:"number",placeholder:"0",value:String((g==null?void 0:g.rotation)||0),onSave:_=>N("rotation",Number(_)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}const Ll={green:"#16a34a",red:"#dc2626",neutral:"#6b7280"};function ps(s){return s&&(Ll[s]??s)}const In={difference:{label:"Difference",description:"Shows the exact difference between two values.",formula:"Primary - Secondary",example:"Sales increased by $5,000 compared to last year."},change:{label:"Change",description:"Shows the percentage increase or decrease between two values.",formula:"(Primary - Secondary) / Secondary × 100%",example:"Year-over-year sales change of 25%."},change_difference:{label:"Change (difference)",description:"Shows both the percentage change and the exact difference between two values.",formula:`% Change: (Primary - Secondary) / Secondary × 100%
183
+ Difference: Primary - Secondary`,example:"Sales grew by 25% ($5,000) compared to last year."},ratio:{label:"Ratio",description:"Shows how much of one value is covered by another — useful for quotas and benchmarks.",formula:"Primary / Secondary × 100%",example:"You've achieved 80% of your sales quota."}};function Ml(){var p,m,g,S,f,N,A,B,w,I;const s=t.useEditorStore(D=>D.card),{setCardPreferences:a}=t.useEditorActions(),r=Oe.useEffectiveEditorCardType(),l=((p=s.config)==null?void 0:p.metricColumns)||[],u=((m=s.config)==null?void 0:m.groupByColumns)||[],i=l.length===2&&u.length===0,o=l.some(D=>D.comparisonType&&D.comparisonType!=="none");if(!(r==="kpi"&&(i||o)))return null;const c=((S=(g=s.preferences)==null?void 0:g.kpiVisualOptions)==null?void 0:S.metricComparison)||{},x=D=>{var y;const E={...s.preferences,kpiVisualOptions:{...(y=s.preferences)==null?void 0:y.kpiVisualOptions,metricComparison:{...c,...D}}};a(E)},h=o||c.enabled,v=l.some(D=>D.comparisonType==="previous_period"||D.comparisonType==="same_period_last_year"||D.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",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ra,{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&&l.length===2&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(t.Switch,{size:"sm",id:"enable-comparison",checked:c.enabled||!1,onCheckedChange:D=>x({enabled:D,...D&&!c.calculationType?{calculationType:"difference"}:{}})})]}),h&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(t.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.Info,{className:"h-3 w-3 cursor-help text-muted-foreground"})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:(()=>{const D=c.calculationType||"difference",E=In[D];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:E==null?void 0:E.label}),e.jsx("p",{children:E==null?void 0:E.description}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Formula:"})," ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-[10px]",children:E==null?void 0:E.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",E==null?void 0:E.example]})]})})()})]})]}),e.jsxs(t.Select,{value:c.calculationType||"difference",onValueChange:D=>x({calculationType:D}),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(In).map(([D,E])=>e.jsx(t.SelectItem,{value:D,className:"text-xs",children:E.label},D))})]})]}),e.jsx(Tt,{formatOptions:c.formatOptions||{},onFormatOptionsChange:D=>x({formatOptions:D}),showTitle:!0,title:"COMPARISON FORMAT"}),(v||i)&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator"}),i&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(t.Select,{value:c.position||"right",onValueChange:D=>x({position:D}),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"right",className:"text-xs",children:"Right"}),e.jsx(t.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(t.SelectItem,{value:"top",className:"text-xs",children:"Top"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Checkbox,{id:"show-arrow",checked:c.showArrow!==!1,onCheckedChange:D=>x({showArrow:D})}),e.jsx(t.Label,{htmlFor:"show-arrow",className:"cursor-pointer text-xs text-muted-foreground",children:"Arrow"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Checkbox,{id:"show-color",checked:c.showColor!==!1,onCheckedChange:D=>x({showColor:D})}),e.jsx(t.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),c.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(fs,{label:"Primary > Secondary",children:e.jsx(n.ColorField,{value:ps(((f=c.colorConfig)==null?void 0:f.increase)||"green"),onChange:D=>x({colorConfig:{...c.colorConfig,increase:D??"#16a34a"}}),defaultValue:"#16a34a",ariaLabel:"Increase color",allowEmpty:!1})}),e.jsx(fs,{label:"Primary < Secondary",children:e.jsx(n.ColorField,{value:ps(((N=c.colorConfig)==null?void 0:N.decrease)||"red"),onChange:D=>x({colorConfig:{...c.colorConfig,decrease:D??"#dc2626"}}),defaultValue:"#dc2626",ariaLabel:"Decrease color",allowEmpty:!1})}),e.jsx(fs,{label:"Primary = Secondary",children:e.jsx(n.ColorField,{value:ps(((A=c.colorConfig)==null?void 0:A.noChange)||"neutral"),onChange:D=>x({colorConfig:{...c.colorConfig,noChange:D??"#6b7280"}}),defaultValue:"#6b7280",ariaLabel:"No change color",allowEmpty:!1})})]})]}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Checkbox,{id:"conditional-label",checked:c.conditionalLabel||!1,onCheckedChange:D=>x({conditionalLabel:D})}),e.jsx(t.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),c.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(t.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(t.Input,{id:"label-increase",type:"text",value:((B=c.conditionalLabels)==null?void 0:B.increase)??"Increase",onChange:D=>x({conditionalLabels:{...c.conditionalLabels,increase:D.target.value}}),placeholder:"Increase",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(t.Label,{htmlFor:"label-decrease",className:"text-xs text-muted-foreground",children:["Primary ","<"," Secondary"]}),e.jsx(t.Input,{id:"label-decrease",type:"text",value:((w=c.conditionalLabels)==null?void 0:w.decrease)??"Decrease",onChange:D=>x({conditionalLabels:{...c.conditionalLabels,decrease:D.target.value}}),placeholder:"Decrease",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{htmlFor:"label-no-change",className:"text-xs text-muted-foreground",children:"Primary = Secondary"}),e.jsx(t.Input,{id:"label-no-change",type:"text",value:((I=c.conditionalLabels)==null?void 0:I.noChange)??"No change",onChange:D=>x({conditionalLabels:{...c.conditionalLabels,noChange:D.target.value}}),placeholder:"No change",className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{htmlFor:"label-name",className:"text-xs text-muted-foreground",children:"Previous Label"}),e.jsx(t.Input,{id:"label-name",type:"text",value:c.labelName??"",onChange:D=>x({labelName:D.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function fs({label:s,children:a}){return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"min-w-0 shrink-0",children:a}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:s})]})}function Fl(){var i;const s=t.useEditorStore(o=>{var d;return(d=o.card)==null?void 0:d.type}),a=t.useEditorStore(o=>{var d;return(d=o.card)==null?void 0:d.preferences}),{setCardPreferences:r}=t.useEditorActions();if(s!=="treemap")return null;const l=((i=a==null?void 0:a.chartOptions)==null?void 0:i.treemapColorMode)??"branch",u=o=>{const d={...a||{},chartOptions:{...a==null?void 0:a.chartOptions,treemapColorMode:o}};r(d)};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:l,onValueChange:o=>u(o??"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 Rl=Object.keys(n.HEATMAP_PRESET_PALETTES);function Ol(){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(),l=(s==null?void 0:s.type)==="heatmap",u=(a==null?void 0:a.heatmapConfig)||{},i=u.colorPalette??"green",o=u.legendPosition??"bottom",d=C.useMemo(()=>u.colorRange&&u.colorRange[0]&&u.colorRange[1]?[u.colorRange[0],u.colorRange[1]]:[...n.DEFAULT_HEATMAP_CUSTOM_RANGE],[u.colorRange]),c=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})},x=p=>{c({colorPalette:p,colorRange:p==="custom"?u.colorRange??[...n.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},h=(p,m)=>{const g=[...d];g[p]=m,c({colorPalette:"custom",colorRange:g})},v=p=>{c({legendPosition:p})};return l?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=>x(p??"blue"),className:"space-y-3",children:[Rl.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:d[0],onChange:p=>h(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:d[1],onChange:p=>h(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:o,onValueChange:p=>v(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 Dn=["poor","satisfactory","good"];function kn(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 Pl(){var F,O;const s=t.useEditorStore(j=>j.card.preferences),a=t.useEditorStore(j=>j.card),r=t.useEditorStore(j=>j.isDevMode),{setCardPreferences:l,setChartOrientation:u}=t.useEditorActions(),i=C.useMemo(()=>(s==null?void 0:s.bulletConfig)||{},[s==null?void 0:s.bulletConfig]),d=t.hasValidCardConfig(a==null?void 0:a.config)&&!r,[c,x]=C.useState(i.showRanges??!1),[h,v]=C.useState(i.rangesArePercentages??!1),p=i.disableAutoComparative?!1:i.comparativeMetricKey!==void 0||!d,[m,g]=C.useState(p);C.useEffect(()=>{x(i.showRanges??!1)},[i.showRanges]),C.useEffect(()=>{v(i.rangesArePercentages??!1)},[i.rangesArePercentages]);const S=i.targetValue===void 0?"":String(i.targetValue);C.useEffect(()=>{const j=i.disableAutoComparative?!1:i.comparativeMetricKey!==void 0||!d;g(j)},[i.disableAutoComparative,i.comparativeMetricKey,d]);const f=C.useMemo(()=>{var j,T;return((T=(j=a==null?void 0:a.config)==null?void 0:j.metricColumns)==null?void 0:T.map(L=>{const V=L.label||L.name||L.alias||"";return{value:V,label:V}}))||[]},[(F=a==null?void 0:a.config)==null?void 0:F.metricColumns]);C.useEffect(()=>{var q,G;if(!s||f.length===0)return;const j={};let T=!1;const L=(q=f[1])==null?void 0:q.value;!i.targetMetricKey&&L&&(j.targetMetricKey=L,T=!0);const V=(G=f[2])==null?void 0:G.value;!i.comparativeMetricKey&&!i.disableAutoComparative&&V&&(j.comparativeMetricKey=V,T=!0);const z=f.slice(3),_={...i.rangeKeys||{}};let P=!1;if(Dn.forEach((Q,U)=>{!_[Q]&&z[U]&&(_[Q]=z[U].value,P=!0)}),P&&(j.rangeKeys=_,T=!0,i.showRanges===void 0&&(j.showRanges=!0)),T){const Q=kn({...i,...j});l({...s,bulletConfig:Q})}},[f,i,s,l]);const N=j=>{const T=kn({...i,...j});l({...s,bulletConfig:T})},A=(j,T)=>{const L={...i.rangeKeys||{},[j]:T.trim()};T.trim()||delete L[j],N({rangeKeys:Object.keys(L).length>0?L:void 0})},B=(j,T)=>{const L=T===""?void 0:Number(T),V={...i.ranges||{}};L===void 0||Number.isNaN(L)?delete V[j]:V[j]=L,N({ranges:Object.keys(V).length?V:void 0})},w=j=>{if(j===""){N({targetValue:void 0});return}const T=Number(j);N({targetValue:Number.isNaN(T)?void 0:T})},I=(j,T)=>{const L=T.trim(),V={...i.rangeLabels||{}};L?V[j]=L:delete V[j],N({rangeLabels:Object.keys(V).length>0?V:void 0})},D=j=>{x(j),N({showRanges:j})},E=j=>{v(j),N({rangesArePercentages:j})},y=i.orientation||(((O=s==null?void 0:s.chartOptions)==null?void 0:O.indexAxis)==="y"?"horizontal":"vertical"),M=j=>{N({orientation:j}),u(j==="horizontal"?"y":"x")},b=[{value:"__none",label:"None"},...f.map(j=>({value:j.value,label:j.label}))],R=b,k=j=>{if(g(j),!j){N({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!d){N({disableAutoComparative:!1});return}if(i.comparativeMetricKey)N({disableAutoComparative:!1});else{const T=f.find(L=>L.value!==i.targetMetricKey);N({comparativeMetricKey:T==null?void 0:T.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:y,onValueChange:j=>M(j),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"horizontal",className:"text-xs",children:"Horizontal"}),e.jsx(t.SelectItem,{value:"vertical",className:"text-xs",children:"Vertical"})]})]})]}),d&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"TARGET METRIC"}),e.jsxs(t.Select,{value:i.targetMetricKey||"__none",onValueChange:j=>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"}),f.map(j=>e.jsx(t.SelectItem,{value:j.value,className:"text-xs",children:j.label},j.value))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"COMPARATIVE METRIC"}),d?e.jsxs(t.Select,{value:i.comparativeMetricKey||"__none",onValueChange:j=>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:b.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=>k(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(Ge,{type:"number",className:"h-8 text-xs",value:S,onCommit:w,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:c,onCheckedChange:D})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:h,disabled:!c,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"})]})]}),c&&e.jsx("div",{className:"space-y-3",children:Dn.map(j=>{var T,L,V,z,_;return e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-muted/40 p-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[j," LABEL"]}),e.jsx(Ge,{placeholder:`Display label (${j})`,value:((T=i.rangeLabels)==null?void 0:T[j])||"",onCommit:P=>I(j,P),className:"h-8 text-xs"})]}),d?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[j," COLUMN"]}),e.jsxs(t.Select,{value:((L=i.rangeKeys)==null?void 0:L[j])||"__none",onValueChange:P=>{P==="__none"?A(j,""):A(j,P)},children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select column"})}),e.jsx(t.SelectContent,{children:R.map(P=>e.jsx(t.SelectItem,{value:P.value,className:"text-xs",children:P.label},P.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(Ge,{placeholder:"Column key",value:((V=i.rangeKeys)==null?void 0:V[j])||"",onCommit:P=>A(j,P),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(Ge,{type:"number",placeholder:h?"0.80":"Static value",value:((z=i.ranges)==null?void 0:z[j])===void 0?"":String((_=i.ranges)==null?void 0:_[j]),onCommit:P=>B(j,P),className:"h-8 text-xs"})]})]},j)})})]})]})]})}function An(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 Bl(){var I,D,E,y,M,b,R,k,F,O,j,T;const s=t.useEditorStore(L=>L.card.preferences),a=t.useEditorStore(L=>L.card),r=Oe.useEffectiveEditorCardType(),l=t.useEditorStore(L=>L.isDevMode),{setCardPreferences:u,updateCardInFrame:i}=t.useEditorActions(),o=r==="bubble",d=r==="scatter",c=C.useMemo(()=>(s==null?void 0:s.bubbleScatterConfig)||{},[s==null?void 0:s.bubbleScatterConfig]),h=t.hasValidCardConfig(a==null?void 0:a.config)&&!l,v=C.useMemo(()=>{var L,V;return((V=(L=a==null?void 0:a.config)==null?void 0:L.metricColumns)==null?void 0:V.map(z=>{const _=z.label||z.name||z.alias||"";return{value:_,label:_}}))||[]},[(I=a==null?void 0:a.config)==null?void 0:I.metricColumns]),p=C.useMemo(()=>{var L,V;return((V=(L=a==null?void 0:a.config)==null?void 0:L.groupByColumns)==null?void 0:V.map(z=>{const _=z.label||z.name||z.alias||"";return{value:_,label:_}}))||[]},[(D=a==null?void 0:a.config)==null?void 0:D.groupByColumns]),m=C.useMemo(()=>c.enableGrouping!==void 0?c.enableGrouping:!l&&p.length>=2,[c.enableGrouping,l,p.length]),[g,S]=C.useState(m);C.useEffect(()=>{S(m)},[m]);const f=L=>{const V={...s||{},bubbleScatterConfig:L};u(V),a&&i({...a,preferences:V})},N=L=>{u(L),a&&i({...a,preferences:L})};C.useEffect(()=>{if(!s||v.length===0)return;const L={};let V=!1;if(!c.xMetricKey&&v[0]&&(L.xMetricKey=v[0].value,V=!0),!c.yMetricKey&&v[1]&&(L.yMetricKey=v[1].value,V=!0),o&&!c.radiusMetricKey&&v[2]&&(L.radiusMetricKey=v[2].value,V=!0),!c.labelKey&&p[0]&&(L.labelKey=p[0].value,V=!0),m&&!c.groupKey&&p[1]&&(L.groupKey=p[1].value,L.enableGrouping=!0,V=!0),V){const z=An({...c,...L});f(z)}},[v,p,c,s,u,o,m]);const A=L=>{const V=An({...c,...L});f(V)},B=L=>{S(L),A({enableGrouping:L,groupKey:L?c.groupKey:void 0})};if(!o&&!d)return null;const w=o?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(w,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsxs("span",{children:[o?"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"}),h?e.jsxs(t.Select,{value:c.labelKey||"",onValueChange:L=>A({labelKey:L}),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(L=>e.jsx(t.SelectItem,{value:L.value,children:L.label},L.value))})]}):e.jsx(Ge,{className:"h-8 text-xs",placeholder:"Column name for labels",value:c.labelKey||"",onCommit:L=>A({labelKey:L})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Group points into series"}),e.jsx(t.Switch,{size:"sm",checked:g,onCheckedChange:B})]}),g&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Group By"}),h?e.jsxs(t.Select,{value:c.groupKey||"",onValueChange:L=>A({groupKey:L}),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(L=>e.jsx(t.SelectItem,{value:L.value,children:L.label},L.value))})]}):e.jsx(Ge,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:c.groupKey||"",onCommit:L=>A({groupKey:L})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Metrics"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"X Axis"}),h?e.jsxs(t.Select,{value:c.xMetricKey||"",onValueChange:L=>A({xMetricKey:L}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select X metric"})}),e.jsx(t.SelectContent,{children:v.map(L=>e.jsx(t.SelectItem,{value:L.value,children:L.label},L.value))})]}):e.jsx(Ge,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:c.xMetricKey||"",onCommit:L=>A({xMetricKey:L})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Axis"}),h?e.jsxs(t.Select,{value:c.yMetricKey||"",onValueChange:L=>A({yMetricKey:L}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select Y metric"})}),e.jsx(t.SelectContent,{children:v.map(L=>e.jsx(t.SelectItem,{value:L.value,children:L.label},L.value))})]}):e.jsx(Ge,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:c.yMetricKey||"",onCommit:L=>A({yMetricKey:L})})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Radius"}),h?e.jsxs(t.Select,{value:c.radiusMetricKey||"",onValueChange:L=>A({radiusMetricKey:L}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select radius metric"})}),e.jsx(t.SelectContent,{children:v.map(L=>e.jsx(t.SelectItem,{value:L.value,children:L.label},L.value))})]}):e.jsx(Ge,{className:"h-8 text-xs",placeholder:"Column name for radius",value:c.radiusMetricKey||"",onCommit:L=>A({radiusMetricKey:L})})]})]}),o&&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:c.radiusScale||"sqrt",onValueChange:L=>A({radiusScale:L}),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"})]})]})]}),c.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(Ge,{className:"h-8 text-xs",type:"number",placeholder:"5",value:((E=c.minRadius)==null?void 0:E.toString())||"",onCommit:L=>A({minRadius:L?Number(L):void 0})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Max Radius"}),e.jsx(Ge,{className:"h-8 text-xs",type:"number",placeholder:"30",value:((y=c.maxRadius)==null?void 0:y.toString())||"",onCommit:L=>A({maxRadius:L?Number(L):void 0})})]})]}),c.radiusScale==="fixed"&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs(t.Label,{className:"text-xs",children:["Fixed Radius: ",c.fixedRadius||10]}),e.jsx(n.Slider,{value:[c.fixedRadius||10],onValueChange:([L])=>A({fixedRadius:L}),min:3,max:30,step:1,className:"py-2"})]})]}),d&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Point Settings"}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(t.Label,{className:"text-xs",children:["Point Size: ",c.fixedRadius||5]}),e.jsx(n.Slider,{value:[c.fixedRadius||5],onValueChange:([L])=>A({fixedRadius:L}),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:((b=(M=s==null?void 0:s.xAxisConfig)==null?void 0:M.name)==null?void 0:b.enabled)??!1,onCheckedChange:L=>{var _,P,q,G;const V=c.xMetricKey||"X Axis",z=c.yMetricKey||"Y Axis";N({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{enabled:L,text:((P=(_=s==null?void 0:s.xAxisConfig)==null?void 0:_.name)==null?void 0:P.text)||V}},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{enabled:L,text:((G=(q=s==null?void 0:s.yAxisConfig)==null?void 0:q.name)==null?void 0:G.text)||z}}})}})]}),((k=(R=s==null?void 0:s.xAxisConfig)==null?void 0:R.name)==null?void 0:k.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(Ge,{className:"h-8 text-xs",placeholder:c.xMetricKey||"X Axis",value:((O=(F=s==null?void 0:s.xAxisConfig)==null?void 0:F.name)==null?void 0:O.text)||"",onCommit:L=>{var V;N({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{...(V=s==null?void 0:s.xAxisConfig)==null?void 0:V.name,enabled:!0,text:L||c.xMetricKey||"X Axis"}}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Title"}),e.jsx(Ge,{className:"h-8 text-xs",placeholder:c.yMetricKey||"Y Axis",value:((T=(j=s==null?void 0:s.yAxisConfig)==null?void 0:j.name)==null?void 0:T.text)||"",onCommit:L=>{var V;N({...s??{},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{...(V=s==null?void 0:s.yAxisConfig)==null?void 0:V.name,enabled:!0,text:L||c.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const Vl=[{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 _l(){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(),l=(s==null?void 0:s.type)==="funnel",u=(a==null?void 0:a.funnelConfig)||{},i=u.percentMode??"percentOfTotal",o=u.shrinkFraction??1,d=u.labelThreshold??0,c=p=>{const m={...u,...p};r({...a||{},funnelConfig:m})},x=p=>{c({percentMode:p})},h=p=>{c({shrinkFraction:p[0]})},v=p=>{c({labelThreshold:p[0]})};return l?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=>x(p),className:"space-y-2",children:Vl.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:[o],onValueChange:h,min:0,max:1,step:.1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Full Shrink"})]}),e.jsxs("p",{className:"text-center text-xs text-muted-foreground",children:["Current: ",Math.round(o*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:[d],onValueChange:v,min:0,max:25,step:1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Hide Small"})]}),e.jsx("p",{className:"text-center text-xs text-muted-foreground",children:d===0?"Showing all labels":`Hide labels below ${d}%`})]})]})]}):null}function ts(){const s=t.useEditorStore(i=>i.card),{data:a}=n.useEditorCardQuery(s),{keys:r}=n.getKeys((a==null?void 0:a.records)||[]),l=r.slice(1).filter(i=>!t.METADATA_KEYS.includes(i));let u=l;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:o}=n.getKeys(i);u=o.slice(1)}return{transformedMetricKeys:u,dimensionKeys:r.slice(0,1),keys:r,defaultMetricKeys:l}}const zl=[{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"}],ql=[{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)"}],$l=["center","start","end"],Kl=["center","start","end","top","bottom"];function ss({config:s,onChange:a,isHorizontal:r=!1,showAutoFormat:l=!0,positionOptions:u,showAppearance:i=!0}){var g,S,f,N,A,B;const o=u??(r?["auto","center","left","right","custom"]:["auto","center","top","bottom","custom"]),d=l?["auto","number","currency","percent","none"]:["number","currency","percent","none"],c=(w,I)=>{const D={...s,[w]:I};a(D)},x=(w,I)=>{const D={...s,font:{...(s==null?void 0:s.font)||{},[w]:I}};a(D)},h=(w,I)=>{const D={...s,formatOptions:{...(s==null?void 0:s.formatOptions)||{},[w]:I}};a(D)},v=()=>r?"Right":"Top",p=s||{},m=p.format||(l?"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:w=>c("position",w),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:o.map(w=>e.jsx(t.SelectItem,{value:w,className:"text-xs",children:w==="auto"?v():w==="custom"?"Custom (Advanced)":t.titleCase(w)},w))})]})]}),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:w=>c("anchor",w),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:$l.map(w=>e.jsx(t.SelectItem,{value:w,className:"text-xs",children:t.titleCase(w)},w))})]})]}),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:w=>c("align",w),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Kl.map(w=>e.jsx(t.SelectItem,{value:w,className:"text-xs",children:t.titleCase(w)},w))})]})]})]}),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:w=>c("format",w),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:d.map(w=>e.jsx(t.SelectItem,{value:w,className:"text-xs",children:w==="auto"&&l?"Auto (Use Axis)":w==="none"?"None (Raw Value)":t.titleCase(w)},w))})]})]}),!["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(Xe,{type:"number",placeholder:"0",value:String(((g=p.formatOptions)==null?void 0:g.decimalPlaces)??(m==="currency"?2:m==="percent"?1:0)),onSave:w=>h("decimalPlaces",Number(w)),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:((S=p.formatOptions)==null?void 0:S.currency)||"USD",onValueChange:w=>h("currency",w),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:zl.map(w=>e.jsx(t.SelectItem,{value:w.value,className:"text-xs",children:w.label},w.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:((f=p.formatOptions)==null?void 0:f.useSuffix)??!1,onCheckedChange:w=>h("useSuffix",w)})]}),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:w=>h("locale",w),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ql.map(w=>e.jsx(t.SelectItem,{value:w.value,className:"text-xs",children:w.label},w.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(Xe,{type:"number",placeholder:"12",value:String(((A=p.font)==null?void 0:A.size)||12),onSave:w=>x("size",Number(w)),className:""})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Weight"}),e.jsxs(t.Select,{value:((B=p.font)==null?void 0:B.weight)||"normal",onValueChange:w=>x("weight",w),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:w=>{w==="auto"&&c("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(Xe,{type:"number",placeholder:"0",value:String(p.rotation||0),onSave:w=>c("rotation",Number(w)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"°"})]})]})]})]})]})}const Gl=[{type:"bar",icon:n.ChartColumnIncreasing,label:"Bar"},{type:"line",icon:n.ChartLine,label:"Line"}],Ul=[0,1,2,3,4,5,6,8,10],Hl=[{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 │"}],Ql=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Wl(){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(Yl,{})})]})}function Yl(){const{transformedMetricKeys:s}=ts();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(Jl,{metricKey:a,idx:r},a))})}function Jl({metricKey:s,idx:a}){var N;const[r,l]=C.useState(!1),u=t.useEditorStore(A=>{var B;return(B=A.card)==null?void 0:B.preferences}),i=t.useEditorStore(A=>{var B,w;return(w=(B=A.card)==null?void 0:B.preferences)==null?void 0:w.datasetOptions}),o=i==null?void 0:i.find(A=>A.idx===a),{setCardPreferences:d}=t.useEditorStore(A=>A.actions),c=(o==null?void 0:o.type)||"bar",x=(o==null?void 0:o.yAxisId)||"y",h=((N=o==null?void 0:o.dataLabels)==null?void 0:N.enabled)??!1,v=c==="line"?n.ChartLine:n.ChartColumnIncreasing;function p(A){const B={idx:a,type:c,yAxisId:x,dataLabels:o==null?void 0:o.dataLabels,...A};if(!o)d({...u||{},datasetOptions:[...i||[],B]});else{const w=i==null?void 0:i.map(I=>I.idx===a?{...I,...B}:I);d({...u||{},datasetOptions:w})}}function m(A){p({type:A})}function g(A){p({yAxisId:A})}function S(A){p({dataLabels:{...o==null?void 0:o.dataLabels,enabled:A}})}function f(A){p({dataLabels:A})}return e.jsx(n.Collapsible,{open:r,onOpenChange:l,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(v,{className:"h-3 w-3"}),c==="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:x==="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:Gl.map(({type:A,icon:B,label:w})=>{const I=c===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",I?"border-primary bg-primary/10 text-primary":"border-border bg-background text-muted-foreground hover:bg-muted"),children:[e.jsx(B,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:w})]},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:x,onValueChange:A=>g(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)"})]})]})]})]}),c==="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:(o==null?void 0:o.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:Ql.map(({value:A,label:B})=>e.jsx(t.SelectItem,{value:A,className:"text-xs",children:B},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((o==null?void 0:o.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:Ul.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:(o==null?void 0:o.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:Hl.map(({value:A,label:B})=>e.jsx(t.SelectItem,{value:A,className:"text-xs",children:B},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:h,onCheckedChange:S})]}),h&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(ss,{config:o==null?void 0:o.dataLabels,onChange:f,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const gs=[{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"}],Xl=[0,1,2,3,4,5,6,8,10],Zl=[{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 │"}],eo=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function to(s){return s==null?"origin":s===!1?"false":s}function so(){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(no,{})})]})}function no(){const{transformedMetricKeys:s}=ts();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(ao,{metricKey:a,idx:r},a))})}function ao({metricKey:s,idx:a}){var S;const[r,l]=C.useState(!1),u=t.useEditorStore(f=>{var N;return(N=f.card)==null?void 0:N.preferences}),i=t.useEditorStore(f=>{var N,A;return(A=(N=f.card)==null?void 0:N.preferences)==null?void 0:A.datasetOptions}),o=i==null?void 0:i.find(f=>f.idx===a),{setCardPreferences:d}=t.useEditorStore(f=>f.actions),c=to(o==null?void 0:o.fill),x=((S=o==null?void 0:o.dataLabels)==null?void 0:S.enabled)??!1,h=gs.find(f=>f.value===c)||gs[0];function v(f){const N={idx:a,fill:c,dataLabels:o==null?void 0:o.dataLabels,...f};if(!o)d({...u||{},datasetOptions:[...i||[],N]});else{const A=i==null?void 0:i.map(B=>B.idx===a?{...B,...N}:B);d({...u||{},datasetOptions:A})}}function p(f){v({fill:f==="false"?!1:f})}function m(f){v({dataLabels:{...o==null?void 0:o.dataLabels,enabled:f}})}function g(f){v({dataLabels:f})}return e.jsx(n.Collapsible,{open:r,onOpenChange:l,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"}),h.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:c,onValueChange:f=>p(f),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:gs.map(f=>e.jsx(t.SelectItem,{value:f.value,className:"text-xs",children:e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{children:f.label})})},f.value))})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(t.Select,{value:(o==null?void 0:o.lineStyle)||"solid",onValueChange:f=>v({lineStyle:f}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:eo.map(({value:f,label:N})=>e.jsx(t.SelectItem,{value:f,className:"text-xs",children:N},f))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(t.Select,{value:String((o==null?void 0:o.pointRadius)??3),onValueChange:f=>v({pointRadius:Number(f)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Xl.map(f=>e.jsx(t.SelectItem,{value:String(f),className:"text-xs",children:f===0?"None":f},f))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(t.Select,{value:(o==null?void 0:o.pointStyle)||"circle",onValueChange:f=>v({pointStyle:f}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Zl.map(({value:f,label:N})=>e.jsx(t.SelectItem,{value:f,className:"text-xs",children:N},f))})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(t.Switch,{size:"sm",checked:x,onCheckedChange:m})]}),x&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(ss,{config:o==null?void 0:o.dataLabels,onChange:g,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const ro=[0,1,2,3,4,5,6,8,10],lo=[{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 │"}],bs=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function oo(){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(io,{})})]})}function io(){const{transformedMetricKeys:s}=ts();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(co,{metricKey:a,idx:r},a))})}function co({metricKey:s,idx:a}){var f;const[r,l]=C.useState(!1),u=t.useEditorStore(N=>{var A;return(A=N.card)==null?void 0:A.preferences}),i=t.useEditorStore(N=>{var A,B;return(B=(A=N.card)==null?void 0:A.preferences)==null?void 0:B.datasetOptions}),o=i==null?void 0:i.find(N=>N.idx===a),{setCardPreferences:d}=t.useEditorStore(N=>N.actions),c=(o==null?void 0:o.lineStyle)||"solid",x=(o==null?void 0:o.pointRadius)??3,h=(o==null?void 0:o.pointStyle)||"circle",v=((f=o==null?void 0:o.dataLabels)==null?void 0:f.enabled)??!1,p=bs.find(N=>N.value===c)||bs[0];function m(N){const A={idx:a,lineStyle:c,pointRadius:x,pointStyle:h,dataLabels:o==null?void 0:o.dataLabels,...N};if(!o)d({...u||{},datasetOptions:[...i||[],A]});else{const B=i==null?void 0:i.map(w=>w.idx===a?{...w,...A}:w);d({...u||{},datasetOptions:B})}}function g(N){m({dataLabels:{...o==null?void 0:o.dataLabels,enabled:N}})}function S(N){m({dataLabels:N})}return e.jsx(n.Collapsible,{open:r,onOpenChange:l,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:c,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:bs.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(x),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:ro.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:h,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:lo.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:v,onCheckedChange:g})]}),v&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(ss,{config:o==null?void 0:o.dataLabels,onChange:S,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const uo=[0,2,4,6,8,10,12,16,20];function mo(){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(xo,{})})]})}function xo(){const{transformedMetricKeys:s}=ts();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(ho,{metricKey:a,idx:r},a))})}function ho({metricKey:s,idx:a}){var g;const[r,l]=C.useState(!1),u=t.useEditorStore(S=>{var f;return(f=S.card)==null?void 0:f.type}),i=t.useEditorStore(S=>{var f;return(f=S.card)==null?void 0:f.preferences}),o=t.useEditorStore(S=>{var f,N;return(N=(f=S.card)==null?void 0:f.preferences)==null?void 0:N.datasetOptions}),d=o==null?void 0:o.find(S=>S.idx===a),{setCardPreferences:c}=t.useEditorStore(S=>S.actions),x=(d==null?void 0:d.borderRadius)??0,h=((g=d==null?void 0:d.dataLabels)==null?void 0:g.enabled)??!1;function v(S){const f={idx:a,borderRadius:x,dataLabels:d==null?void 0:d.dataLabels,...S};if(!d)c({...i||{},datasetOptions:[...o||[],f]});else{const N=o==null?void 0:o.map(A=>A.idx===a?{...A,...f}:A);c({...i||{},datasetOptions:N})}}function p(S){v({dataLabels:{...d==null?void 0:d.dataLabels,enabled:S}})}function m(S){v({dataLabels:S})}return e.jsx(n.Collapsible,{open:r,onOpenChange:l,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:x>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:",x]})})]})}),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(x),onValueChange:S=>v({borderRadius:Number(S)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:uo.map(S=>e.jsx(t.SelectItem,{value:String(S),className:"text-xs",children:S===0?"None":`${S}px`},S))})]})]})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(t.Switch,{size:"sm",checked:h,onCheckedChange:p})]}),h&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(ss,{config:d==null?void 0:d.dataLabels,onChange:m,isHorizontal:u==="horizontalBar",showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const po=[0,1,2,3,4,5,6,8,10],fo=[{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 │"}],go=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function bo(){const s=t.useEditorStore(d=>d.card),a=t.useEditorStore(d=>{var c;return(c=d.card)==null?void 0:c.preferences}),r=Oe.useEffectiveEditorCardType(),l=a==null?void 0:a.lineStyleConfig,{setCardPreferences:u,updateCardInFrame:i}=t.useEditorActions();if(!s||!["line","area","stackedArea"].includes(r))return null;const o=(d,c)=>{const x={...a||{},lineStyleConfig:{...l,[d]:c}};u(x),i({...s,preferences:x})};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(Ha,{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:(l==null?void 0:l.lineStyle)||"solid",onValueChange:d=>o("lineStyle",d),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:go.map(({value:d,label:c})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:c},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Point Size"}),e.jsxs(t.Select,{value:String((l==null?void 0:l.pointRadius)??3),onValueChange:d=>o("pointRadius",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:po.map(d=>e.jsx(t.SelectItem,{value:String(d),className:"text-xs",children:d===0?"None":d},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Point Shape"}),e.jsxs(t.Select,{value:(l==null?void 0:l.pointStyle)||"circle",onValueChange:d=>o("pointStyle",d),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:fo.map(({value:d,label:c})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:c},d))})]})]})]})})]})}const jo=[0,2,4,6,8,10,12,16,20],vo=[{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%"}],yo=[{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 Co(){const s=t.useEditorStore(d=>d.card),a=t.useEditorStore(d=>{var c;return(c=d.card)==null?void 0:c.preferences}),r=Oe.useEffectiveEditorCardType(),l=a==null?void 0:a.barStyleConfig,{setCardPreferences:u,updateCardInFrame:i}=t.useEditorActions();if(!s||!["bar","horizontalBar","stackedBar"].includes(r))return null;const o=(d,c)=>{const x={...a||{},barStyleConfig:{...l,[d]:c}};u(x),i({...s,preferences:x})};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((l==null?void 0:l.borderRadius)??0),onValueChange:d=>o("borderRadius",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:jo.map(d=>e.jsx(t.SelectItem,{value:String(d),className:"text-xs",children:d===0?"None":`${d}px`},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Bar Width"}),e.jsxs(t.Select,{value:String((l==null?void 0:l.barPercentage)??.9),onValueChange:d=>o("barPercentage",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:vo.map(({value:d,label:c})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:c},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Category Width"}),e.jsxs(t.Select,{value:String((l==null?void 0:l.categoryPercentage)??.8),onValueChange:d=>o("categoryPercentage",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:yo.map(({value:d,label:c})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:c},d))})]})]})]})})]})}function No(){const s=t.useEditorStore(r=>{var l,u;return(u=(l=r==null?void 0:r.card)==null?void 0:l.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(Pn,{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(it,{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 So=["kpi"],Ln={none:"None",previous_period:"Previous Period",same_period_last_year:"Same Period Last Year",start_vs_end:"Start vs End",target:"Target"},js=2;function ht(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 wo(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 To(s){return{...s,role:"groupby"}}function Eo(){var A,B;const s=t.useEditorStore(w=>w.card),a=t.useEditorStore(w=>w.actions.updateCardConfig),r=Oe.useEffectiveEditorCardType(),{scopedFields:l}=n.useScopedFields(),u=((A=s.config)==null?void 0:A.metricColumns)||[],i=((B=s.config)==null?void 0:B.summary)||{},o=i.breakdownDimensions||[],d=So.includes(r),c=u.length>0,x=i.enabled===!0,h=d&&c,{comparisonType:v}=n.getEffectiveComparisonSettings(s.config,r),p=Ln[v]||Ln.none,m=Array.from(new Map(l.filter(wo).map(w=>[ht(w),To(w)])).values()),g=new Set(m.map(w=>ht(w))),S=new Set(o.map(w=>ht(w)).filter(w=>w&&g.has(w)));if(!d)return null;const f=w=>{a(s.id,{summary:{...i,...w}})},N=(w,I)=>{const D=ht(w),E=m.filter(M=>S.has(ht(M))),y=I?S.has(D)?E:[...E,w].slice(0,js):E.filter(M=>ht(M)!==D);f({breakdownDimensions:y})};return e.jsxs(n.AccordionItem,{value:"summary",className:"border-none",children:[e.jsx(n.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-[12px] hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.FileText,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:"Summary"})]})}),e.jsxs(n.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{htmlFor:"summary-enabled",className:"text-xs",children:"Enable Summary"}),!c&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Add at least one metric to enable summary."})]}),e.jsx(t.Switch,{size:"sm",id:"summary-enabled",checked:x,disabled:!h,onCheckedChange:w=>{if(!w){f({enabled:!1,showOnCard:!1,includeInDashboardSummary:!1});return}f({enabled:!0,showOnCard:i.showOnCard??!0,includeInDashboardSummary:i.includeInDashboardSummary??!0,anomalyEnabled:i.anomalyEnabled??!0})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Comparison"}),e.jsxs("p",{className:"rounded-md border border-border bg-muted/40 px-2 py-1.5 text-xs",children:["Using: ",p]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Comparison is configured from card/metric comparison settings."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"summary-show-on-card",className:"text-xs",children:"Show summary on card"}),e.jsx(t.Switch,{size:"sm",id:"summary-show-on-card",checked:i.showOnCard===!0,disabled:!x,onCheckedChange:w=>f({showOnCard:w})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"summary-include-rollup",className:"text-xs",children:"Include in dashboard summary"}),e.jsx(t.Switch,{size:"sm",id:"summary-include-rollup",checked:i.includeInDashboardSummary===!0,disabled:!x,onCheckedChange:w=>f({includeInDashboardSummary:w})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Breakdown Dimensions"}),e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[o.length,"/",js]})]}),m.length===0?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"No dimension fields available for breakdown."}):e.jsx("div",{className:"max-h-40 space-y-2 overflow-y-auto rounded-md border border-border p-2",children:m.map(w=>{const I=ht(w),D=S.has(I),E=S.size>=js,y=!x||!D&&E;return e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx(n.Checkbox,{id:`summary-breakdown-${I}`,checked:D,disabled:y,onCheckedChange:M=>N(w,M===!0)}),e.jsx(t.Label,{htmlFor:`summary-breakdown-${I}`,className:"cursor-pointer text-xs",children:w.label||w.name})]},I)})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"summary-anomaly",className:"text-xs",children:"Detect anomalies"}),e.jsx(t.Switch,{size:"sm",id:"summary-anomaly",checked:i.anomalyEnabled!==!1,disabled:!x,onCheckedChange:w=>f({anomalyEnabled:w})})]})]})]})}const Io=new Set(["area","bar","bubble","bullet","combo","doughnut","funnel","horizontalBar","line","pie","polarArea","radar","scatter","stackedArea","stackedBar","stackedLine","tornado"]);function Do(){const s=t.useEditorStore(c=>c.card),a=t.useEditorStore(c=>{var x;return(x=c.card)==null?void 0:x.preferences}),r=Oe.useEffectiveEditorCardType(),{setCardPreferences:l,updateCardInFrame:u}=t.useEditorActions();if(!s||!Io.has(r||""))return null;const i=a==null?void 0:a.tooltipConfig,o=(i==null?void 0:i.formatMode)||(i==null?void 0:i.mode)||"inherit",d=c=>{const x={...a||{},tooltipConfig:{...i||{},...c}};l(x),u({...s,preferences:x})};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:o==="override",onCheckedChange:c=>d({formatMode:c?"override":"inherit",mode:c?"override":"inherit"})})]}),o==="override"&&e.jsx(Tt,{formatOptions:(i==null?void 0:i.formatOptions)||{},onFormatOptionsChange:c=>d({formatMode:"override",mode:"override",formatOptions:c}),showTitle:!1})]})]})}function sa({mode:s}){const a=t.useEditorStore(r=>{var l;return(l=r.card)==null?void 0:l.type});return e.jsxs(e.Fragment,{children:[a==="combo"&&e.jsx(Wl,{}),(a==="area"||a==="stackedArea")&&e.jsx(so,{}),a==="line"&&e.jsx(oo,{}),(a==="bar"||a==="horizontalBar"||a==="stackedBar")&&e.jsx(mo,{}),e.jsx(bo,{}),e.jsx(Co,{}),e.jsx(Fl,{}),s==="config"&&e.jsx(Ml,{}),s==="config"&&e.jsx(Eo,{}),e.jsx(Ol,{}),a==="bullet"&&e.jsx(Pl,{}),a==="funnel"&&e.jsx(_l,{}),(a==="bubble"||a==="scatter")&&e.jsx(Bl,{}),(a==="stackedBar"||a==="stackedLine")&&e.jsx(No,{}),e.jsx(Il,{}),e.jsx(Dl,{}),e.jsx(kl,{}),e.jsx(Al,{}),e.jsx(Do,{})]})}function ko(){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(es,{chartType:a}),e.jsx(n.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:e.jsx(sa,{mode:"dev"})})]}):null}function Ao({focusSection:s,focusRequestId:a}){const r=t.useEditorStore(o=>o.card),l=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(l){case"kpi":return e.jsx(il,{});case"table":case"detailTable":case"aggregateTable":case"pivotTable":return e.jsx(ta,{cardType:l,focusSection:s,focusRequestId:a});case"map":return e.jsx(xl,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(Zn,{})});case"text":return e.jsx(Nl,{});default:return e.jsx(ko,{})}}return e.jsxs(t.ScrollArea,{className:"h-full w-full text-sm",children:[i(),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}function Lo(){const s=C.useRef(null),a=C.useRef(null),r=t.useEditorStore(N=>N.isShowingVisual),l=t.useEditorStore(N=>N.isDevMode),u=t.useEditorStore(N=>N.showAIDialog),[i,o]=C.useState(!1),[d,c]=C.useState({section:null,id:0}),x=r&&!u,h=x&&(!l||i),v=l&&x,p=()=>o(N=>!N),m=N=>{N&&c(A=>({section:N,id:A.id+1})),l&&o(!0)};C.useEffect(()=>{var N,A,B,w;u?((N=s.current)==null||N.resize(0),(A=a.current)==null||A.resize(0)):((B=s.current)==null||B.resize(25),(w=a.current)==null||w.resize(25))},[u]);const[g,S]=C.useState(!1),f=x?{show:v,isOpen:h,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(yr,{})}),e.jsx(cs,{mode:"toolbar",visualAsideControl:f,isDynamicInspectorOpen:g,onDynamicInspectorOpenChange:S})]})}),e.jsx(n.ResizableHandle,{}),e.jsx(n.ResizablePanel,{role:"visual-section",minSize:0,defaultSize:50,children:h?e.jsxs(n.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(n.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(cs,{mode:"canvas",visualAsideControl:f,isDynamicInspectorOpen:g,onDynamicInspectorOpenChange:S})}),!u&&e.jsx(n.ResizableHandle,{}),e.jsx(n.ResizablePanel,{ref:s,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(Ao,{focusSection:d.section,focusRequestId:d.id})})]}):e.jsx(cs,{mode:"canvas",visualAsideControl:f,isDynamicInspectorOpen:g,onDynamicInspectorOpenChange:S})})]})}function Mo(s){var re;t.useAIInteractionStore($=>$.currentAIContext);const[a,r]=C.useState(""),[l,u]=C.useState(null),{authToken:i,tokenProps:o}=n.useSemaphorContext(),d=t.useEditorStore($=>$.card.id),c=t.useEditorStore($=>{var H;return(H=$==null?void 0:$.card)==null?void 0:H.sql}),x=t.useEditorStore($=>$.isDevMode),h=t.useEditorStore($=>{var H;return(H=$==null?void 0:$.card)==null?void 0:H.python}),{setCardPython:v,setCardSql:p,setRunSql:m,switchCardType:g,setQueryConfig:S}=t.useEditorActions(),f=t.useEditorStore($=>$.currentAssitantScope)||[],N=t.useEditorStore($=>$.userInputForAI),A=t.useEditorStore($=>$.triggerAIRun),B=t.useEditorStore($=>$.card),w=t.useEditorStore($=>$.selectedDatabaseName),I=t.useEditorStore($=>$.selectedTableName),D=t.useEditorStore($=>$.selectedConnectionId),E=t.useEditorStore($=>$.selectedSchemaName),y=t.useDashboardStore($=>$.dashboard.aiScopeTables),{errorMessage:M,refetch:b,data:R}=n.useEditorCardQuery(B),{setTriggerAIRun:k,setCurrentAssitantScope:F,setCardConfig:O}=t.useEditorActions(),{selectedDatamodelName:j,connectionType:T,selectedDatamodelId:L}=n.useEditorAside(),V=(re=n.useDashboardQuery().data)==null?void 0:re.assistantProfileId,z=C.useRef(n.createAssistantConversationId()),_=C.useRef(null),P=C.useRef(d),q=C.useRef(!1),G=()=>{const $=_.current;$&&(_.current=null,z.current=n.createAssistantConversationId(),$==="clear"&&U([]))},{messages:Q,setMessages:U,regenerate:J,error:X,sendMessage:se,status:ue,addToolResult:pe,stop:xe,clearError:je}=n.useChat({transport:new n.DefaultChatTransport({api:`${o.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${i==null?void 0:i.accessToken}`}),body:()=>{const $=t.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:V,conversationId:z.current,assistantRequestId:n.createAssistantRequestId(),isDevMode:x,aiContext:$.currentAIContext,reasoningEffort:$.reasoningEffort,showReasoning:$.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:$,body:H})=>({body:{...H,messages:t.cleanupIncompleteMessages($)}})}),onError:$=>{var H;if(q.current=!1,$.name==="AbortError"||(H=$.message)!=null&&H.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)"),G();return}console.error("[Editor Assistant] Stream error:",$),G()},onToolCall:fe,onFinish({isAbort:$,isDisconnect:H,isError:ne}){q.current=!1,r(""),console.log($?"[Editor Assistant] Stream aborted by user":H?"[Editor Assistant] Stream disconnected (network error)":ne?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully"),G()}}),Pe=C.useCallback($=>{q.current=!0;try{const H=se($);return n.isPromiseLike(H)?H.catch(ne=>{throw q.current=!1,ne}):H}catch(H){throw q.current=!1,H}},[se]),Me=C.useCallback(()=>{q.current=!0;try{const $=J();return n.isPromiseLike($)?$.catch(H=>{throw q.current=!1,H}):$}catch($){throw q.current=!1,$}},[J]),te=$=>{let H=!1;U(ne=>{const he=typeof $=="function"?$(ne):$;if(he.length===0){if(q.current)return _.current="clear",H=!0,ne;_.current=null,z.current=n.createAssistantConversationId()}return he}),H&&xe()};C.useEffect(()=>{if(P.current!==d){if(P.current=d,q.current){_.current!=="clear"&&(_.current="rotate"),xe();return}_.current=null,z.current=n.createAssistantConversationId()}},[d,xe]),C.useEffect(()=>{A&&N&&(Pe({role:"user",parts:[{type:"text",text:N}]}),k(!1))},[A,N,Pe,k]);async function fe({toolCall:$}){var H,ne,he,de,Te,De,ae,Ee,Fe,Ne,Se,Ke,He,le,Le,$e;if(["createChartFromSql","createForecast"].includes($.toolName)){const Ce=((H=$.input)==null?void 0:H.sql)??((ne=$.args)==null?void 0:ne.sql),Ze=((he=$.input)==null?void 0:he.python)??((de=$.args)==null?void 0:de.python),Ae=((Te=$.input)==null?void 0:Te.chartType)??((De=$.args)==null?void 0:De.chartType);g(Ae),p(Ce),v(Ze),m(!0),pe({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if($.toolName==="getUserSql"){if(!c){pe({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",message:"No SQL found"}});return}pe({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",sql:c,python:h||""}})}else if($.toolName==="generateQueryConfig"){r("Generating query config...");const Ce=((ae=$.input)==null?void 0:ae.chartType)??((Ee=$.args)==null?void 0:Ee.chartType),Ze=((Fe=$.input)==null?void 0:Fe.queryConfig)??((Ne=$.args)==null?void 0:Ne.queryConfig);((Se=$.input)==null?void 0:Se.cardConfig)??((Ke=$.args)==null||Ke.cardConfig),g(Ce),O(Ze),p(void 0),v(void 0);const Ae=await b();if((He=Ae==null?void 0:Ae.data)!=null&&He.error){pe({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",queryConfig:Ze,message:(le=Ae==null?void 0:Ae.data)==null?void 0:le.error.message}});return}if((Le=Ae==null?void 0:Ae.data)!=null&&Le.records){pe({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:Ze,message:"The data has been visualized"}});return}pe({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:Ze,message:"The data has been visualized",records:($e=Ae==null?void 0:Ae.data)==null?void 0:$e.records}})}else r("Analyzing...")}function ke($){const H=n.removeFromScopeArray(f,$);Be(H)}function Be($){const H=n.sanitizeAIScope($);F(H),U(ne=>[...ne,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(H)}`}]}])}function ze(){const $={databaseName:w||"",schemaName:E||"",tableName:I||"",datamodelId:L||"",datamodelName:t.resolveDatamodelName(j),connectionId:D||"",connectionType:T||""},H=n.dedup([...f,$]);Be(H)}function ce(){const $={databaseName:w||"",schemaName:E||"",tableName:I||"",datamodelName:t.resolveDatamodelName(j),connectionId:D||"",connectionType:T||"",datamodelId:L||""};if(!n.isInAiScopeArray([...y||[],...f],$)||f.length===0){const ne=n.dedup([...y||[],...f,$]).filter(he=>he.connectionId===$.connectionId);Be(ne)}}const ve=!["ready","error"].includes(ue),ye=n.getErrorMessage(X);return{messages:Q,setMessages:te,sendMessage:Pe,regenerate:Me,isLoading:ve,handleSetAIScope:ce,handleAddCurrentTableToScope:ze,removeFromCurrentSelections:ke,currentAssitantScope:f,setCurrentAssitantScope:F,stop:xe,status:ue,toolStatus:a,llmUsage:l,onFinish:s,errorMessage:ye,clearError:je}}const Fo=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Mn({isFullscreen:s,onFullscreenChange:a,fullscreenContainer:r}){const l=C.useRef(null),u=C.useRef(!1),[i,o]=C.useState(!1),[d,c]=C.useState(t.isDevEnv),[x,h]=C.useState(!1),[v,p]=C.useState(!1),[m,g]=C.useState(!1),S=s??m,f=t.useCurrentAIContext(),{setCurrentAIContext:N,setHasEditorEntitySelectionOverride:A}=t.useAIActions(),{clearQueue:B}=t.useQueueActions(),{clearFileAttachments:w}=t.useFileActions(),I=t.useFileAttachments("editor"),{selectedEntities:D}=n.useAssistantContextEntities("editor"),E=t.useEditorStore(le=>le.card.id),y=t.useEditorStore(le=>le.card.dataSource),M=t.useEditorStore(le=>{var Le;return(Le=le.card.dataSource)==null?void 0:Le.selectedEntities}),b=t.useEditorStore(le=>le.actions.setCardSql),R=t.useEditorStore(le=>le.actions.setRunSql),k=t.useEditorStore(le=>le.showAIDialog),F=t.useDashboardStore(le=>le.handleOpenAssistantProfile),{setShowAIDialog:O,setCardPython:j}=t.useEditorActions(),{setDataSource:T}=t.useEditorActions(),{assistantProfile:L}=n.useAssistantProfile(),{messages:V,setMessages:z,sendMessage:_,isLoading:P,stop:q,status:G,llmUsage:Q,errorMessage:U,clearError:J}=Mo(),[X,se]=C.useState(""),ue=le=>{se(le.target.value)},pe=le=>{le.preventDefault();const Le=X.trim();if(!Le&&I.length===0)return;const $e=[];Le&&$e.push({type:"text",text:Le}),I.forEach(Ce=>{Ce.data&&$e.push({type:"file",mediaType:Ce.type,filename:Ce.name,url:`data:${Ce.type};base64,${Ce.data}`})}),_({role:"user",parts:$e}),se(""),w("editor"),ve({force:!0})},{visibleMessages:xe,hasMoreMessages:je,totalMessageCount:Pe,loadMoreMessages:Me,resetMessageWindow:te}=n.useMessageWindow(V,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:fe,contentRef:ke,isAtBottom:Be,hasNewMessages:ze,newMessageCount:ce,scrollToBottom:ve,handleScroll:ye,resetNewMessageCount:re}=n.useAutoScroll(xe,{threshold:40,behavior:"smooth",isStreaming:P});C.useEffect(()=>{var le;k&&!u.current&&((le=l.current)==null||le.focus()),u.current=k},[k]),C.useEffect(()=>{k&&(A(!1),N({selectedEntities:M||[]}))},[E,M,N,A,k]),n.useAutoSubmitQueue({assistantType:"editor",status:G,isLoading:P,sendMessage:_});const{hasActiveTools:$,activeToolText:H}=n.useActiveToolStatus(V),ne=C.useCallback(le=>{a==null||a(le),s===void 0&&g(le)},[s,a]);C.useEffect(()=>{if(!S)return;function le(Le){Le.key==="Escape"&&ne(!1)}return window.addEventListener("keydown",le),()=>{window.removeEventListener("keydown",le)}},[S,ne]);const he=C.useCallback(le=>{_({role:"user",parts:[{type:"text",text:le}]}),ve({force:!0})},[_,ve]),de=C.useCallback(async()=>{const le=JSON.stringify(V??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(le),n.ue.success("Conversation copied")}catch(Le){console.error("Failed to copy conversation",Le),n.ue.error("Unable to copy conversation")}},[V]),Te=C.useCallback(()=>{ne(!S)},[S,ne]);function De(le,Le){Le==="sql"?(b(le),R(!0)):Le==="python"&&(j(le),R(!0))}function ae(){f.selectedEntities.length===0&&N({selectedEntities:D})}function Ee(le){ae();const Le={role:"user",parts:[{type:"text",text:le.title+" "+le.subtitle}]};_(Le)}function Fe(le){ae(),_({role:"user",parts:[{type:"text",text:le}]})}function Ne(){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:o,children:"Token Usage"}),e.jsx(n.DropdownMenuCheckboxItem,{checked:d,onCheckedChange:c,children:"Tool Invocations"}),e.jsx(n.DropdownMenuCheckboxItem,{checked:x,onCheckedChange:h,children:"System Message"})]})]})}function Se(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const Ke=(X==null?void 0:X.length)===0&&(V==null?void 0:V.filter(le=>le.role==="user").length)===0,He=e.jsxs("div",{"data-role":"editor-assistant",className:t.cn("flex h-full w-full flex-col justify-between px-6 py-4",S&&"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:[Se(),F&&e.jsx(t.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:F,children:(L==null?void 0:L.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[Ne(),d&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:de,children:"Copy Conversation"}),e.jsx(n.IconButton,{tooltip:S?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:Te,children:S?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([]),B("editor"),J(),te()},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:()=>{O(!1)},children:e.jsx(t.X,{className:"size-4"})})]})]}),e.jsx(n.CustomScrollArea,{ref:fe,className:"mt-2 flex min-w-0 w-full grow basis-0",onScroll:ye,children:e.jsxs("div",{ref:ke,className:"min-w-0 space-y-4 py-2 pr-3","data-role":"messages",children:[je&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:Me,className:"text-xs",children:["Load ",Math.min(5,Pe-xe.length)," ","more messages (",Pe-xe.length," ","hidden)"]})}),e.jsx(n.PrintMessages,{messages:xe,showTools:d,handleRun:De,showSystemMessage:x,onQuickReply:he,disableQuickReplies:P}),e.jsx(n.AssistantStatus,{status:G,errorMessage:U,activeToolText:P&&$?H:void 0})]})}),k&&!Be&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(t.Button,{onClick:()=>{ve({force:!0}),re()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(t.ChevronDown,{className:"h-4 w-4"}),ze&&ce>0&&e.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:ce>9?"9+":ce})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[Ke&&!L&&e.jsx(n.Placeholders,{onClick:Ee,placeholders:Fo}),e.jsx("div",{children:Ke&&L&&e.jsx(n.SeedQuestions,{seedQuestions:L.seedQuestions||[],handleSeedQuestionClick:Fe})})]}),e.jsx(n.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(n.ChatInputWithContext,{ref:l,setInput:se,stop:q,input:X,handleInputChange:ue,handleSubmit:le=>{ae(),pe(le),ve({force:!0})},isLoading:P,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:v,onOpenChange:p,dataSource:y||n.EMPTY_DATA_SOURCE,dialogMode:"aiContext",onSaveSelectedEntities:le=>{A(!0),N({...f,selectedEntities:le})}})]});return S&&r?wa.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:He})}),r):He}function Ro(s,a,r){if(!a)return!1;const l=a.qualifiedFieldName,u=a.qualifiedEntityName,i=u&&a.name?`${u}.${a.name}`:l;return s.some(o=>{if(!(t.getDataType(o.dataType||"")==="date"))return!1;const c=n.getSelectedDateFilterColumn(o,r),x=c.split("."),h=x[x.length-1]||c,v=x.length>1?x.slice(0,-1).join("."):void 0,p=o.qualifiedTableName||v,m=p?`${p}.${h}`:void 0;return l?m?m===i||m.endsWith(`.${l}`):h===a.name:m?m===i:h===a.name})}function Oo({aliasTemplate:s,onAliasTemplateChange:a}){var c;const[r,l]=C.useState(s),[u,i]=C.useState(!1),o=(c=t.useEditorStore(x=>{var h;return(h=x.card.config)==null?void 0:h.pivotByColumns}))==null?void 0:c[0],d=o?`e.g. Min Sales in {{${o.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Input,{placeholder:d,value:u?r:s,onChange:x=>{l(x.target.value),i(!0)},onFocus:()=>i(!0),onPointerDown:x=>x.stopPropagation(),className:"h-8 text-xs",onKeyDown:x=>{x.key==="Enter"&&u&&r!==s?(a(r),i(!1)):x.key==="Escape"&&(l(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:()=>{l(s),i(!1)},children:e.jsx(t.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function Po({valueAliases:s,onValueAliasesChange:a}){const[r,l]=C.useState(null),[u,i]=C.useState(""),[o,d]=C.useState(""),c=()=>{a({...s,"":""})},x=v=>{const p={...s};delete p[v],a(p)},h=v=>{const p={...s};delete p[v],p[u]=o,a(p),l(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(([v,p],m)=>e.jsx("div",{className:"flex items-center gap-2",children:r===v?e.jsxs(e.Fragment,{children:[e.jsx(t.Input,{placeholder:"Value key",value:u,onChange:g=>i(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?h(v):g.key==="Escape"&&l(null)},"aria-label":"Edit value alias key"}),e.jsx(t.Input,{placeholder:"Alias label",value:o,onChange:g=>d(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?h(v):g.key==="Escape"&&l(null)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>h(v),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:()=>l(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:v,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{l(v),i(v),d(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:()=>{l(v),i(v),d(p)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>x(v),"aria-label":"Remove value alias",children:e.jsx(t.X,{className:"h-3 w-3"})})]})},v+m)),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:c,children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function Bo({idx:s}){var d;const a=t.useEditorStore(c=>{var x;return(x=c.card)==null?void 0:x.preferences}),r=t.useEditorStore(c=>{var x;return(x=c.card.preferences)==null?void 0:x.datasetOptions}),l=t.useEditorStore(c=>c.actions.setCardPreferences),u=(d=a==null?void 0:a.chartOptions)==null?void 0:d.indexAxis,i=r==null?void 0:r.find(c=>c.idx===s);function o(c,x){(c==="end"||c==="start")&&t.getContrastColor(t.getCanvasBackgroundColor());const h={display:c!=="none",align:c,anchor:c,clamp:!0};if(!i)l({...a,datasetOptions:[...r||[],{idx:x,datalabels:h}]});else{const v={...i};v.datalabels=h;const p=r==null?void 0:r.map(m=>m.idx===x?v:m);l({...a,datasetOptions:p})}}return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{children:e.jsx(Ya,{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:()=>o("none",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(t.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>o("start",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Ba,{className:t.cn("h-4 w-4",{"rotate-90":u==="y"})})}),e.jsx("button",{onClick:()=>o("center",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(_a,{className:t.cn("h-4 w-4",{"rotate-90":u==="y"})})}),e.jsx("button",{onClick:()=>o("end",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Va,{className:t.cn("h-4 w-4",{"rotate-90":u==="y"})})})]})})]})}function Es({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 Vo(s,a=30){return s.length>a?s.slice(0,a)+"...":s}function _o({col:s,idx:a,className:r,iconClassName:l,children:u}){const i=t.useEditorStore(h=>{var v;return(v=h.card)==null?void 0:v.preferences}),o=t.useEditorStore(h=>{var v,p;return(p=(v=h.card)==null?void 0:v.preferences)==null?void 0:p.datasetOptions}),d=o==null?void 0:o.find(h=>h.idx===a),{setCardPreferences:c}=t.useEditorStore(h=>h.actions);function x(h){if(!d)c({...i,datasetOptions:[...o||[],{idx:a,type:h==="area"?"line":h,fill:h==="area"?"origin":""}]});else{const v={...d};v.type=h==="area"?"line":h,v.fill=h==="area"?"origin":"";const p=o==null?void 0:o.map(m=>m.idx===a?v:m);c({...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(Es,{className:"max-w-[100px]",title:s,children:Vo(s)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(n.ChartColumnIncreasing,{onClick:()=>x("bar"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",l)}),e.jsx(n.ChartLine,{onClick:()=>x("line"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",l)}),e.jsx(n.ChartArea,{onClick:()=>x("area"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",l)}),e.jsx(Bo,{idx:a})]})]})}function zo(){const s=t.useEditorStore(d=>d.card.type),a=t.useEditorStore(d=>d.isDevMode),r=t.useEditorStore(d=>d.card.preferences),{setCardPreferences:l}=t.useEditorStore(d=>d.actions);function u(d){var h;const c={datalabels:{display:d!=="none",align:d,anchor:d,clamp:!0}},x={...r,chartOptions:{...r==null?void 0:r.chartOptions,plugins:{...(h=r==null?void 0:r.chartOptions)==null?void 0:h.plugins,...c}}};l(x)}function i(){var d,c,x;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(t.Select,{value:((x=(c=(d=r==null?void 0:r.chartOptions)==null?void 0:d.plugins)==null?void 0:c.datalabels)==null?void 0:x.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 o(){var d,c,x;return e.jsx("div",{children:e.jsxs(t.Select,{value:((x=(c=(d=r==null?void 0:r.chartOptions)==null?void 0:d.plugins)==null?void 0:c.datalabels)==null?void 0:x.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():o()})}function qo({column:s}){const a=t.useEditorStore(c=>c.card.type),r=t.useEditorStore(c=>{var x,h;return(h=(x=c.card)==null?void 0:x.config)==null?void 0:h.metricColumns}),l=(r==null?void 0:r.map(c=>c.label))||[],u=l==null?void 0:l.find(c=>c===s.label||c===s.name),i=u?l.indexOf(u):-1;function o(){return e.jsx("div",{className:"pr-1",children:u&&e.jsx(_o,{idx:i,col:u,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function d(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(zo,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&o(),["pie","doughnut"].includes(a)&&d()]})}function $o({field:s,searchQuery:a="",limit:r=500}){const{authToken:l,tokenProps:u}=n.useSemaphorContext(),i=t.useEditorStore(x=>x.card),o=i==null?void 0:i.dataSource,d=["attribute-values",s.entityName,s.name,a,r],c=n.useQuery({queryKey:d,queryFn:async()=>{if(!(o!=null&&o.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const x={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},h={connection_id:o.connectionId,cardConfig:x,cardDataSource:o,cache_config:t.getCacheConfig({card:i})};console.log("requestBody",h);const v=await t.postRequestRegular(`${u.apiServiceUrl}/v1/query`,(l==null?void 0:l.accessToken)||"",h);if(v!=null&&v.error)return console.error("Error fetching attribute values:",v.error),[];const p=s.name;return((v==null?void 0:v.records)||[]).map(g=>{const S=g[p]||g[s.alias||p]||g[s.label];return{id:S||"",value:S||"",label:String(S||"(empty)")}})}catch(x){return console.error("Error fetching attribute values:",x),[]}},enabled:!!s&&!!(o!=null&&o.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:c.data||[],isLoading:c.isLoading,isFetching:c.isFetching,isError:c.isError,error:c.error,refetch:c.refetch}}function na({open:s,onOpenChange:a,availableFields:r,existingFilters:l,editingCondition:u,onSave:i}){var B,w;const o=!!u,[d,c]=C.useState(o?"values":"fields"),[x,h]=C.useState(""),[v,p]=C.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(I=>{var E;return o?!1:!((E=l==null?void 0:l.conditions)==null?void 0:E.some(y=>y.field.id===I.id))&&I.label.toLowerCase().includes(x.toLowerCase())}),g=I=>{p({...v,field:I}),c("values")},S=()=>{if(v.field&&v.selectedValues.length>0){const I={id:v.id,field:v.field,operator:"in",value:v.selectedValues};let D;if(o){const E=((l==null?void 0:l.conditions)||[]).map(y=>y.id===u.id?I:y);D={...l,conditions:E}}else{const E=(l==null?void 0:l.conditions)||[];D={id:(l==null?void 0:l.id)||t.v4(),logicalOperator:"AND",negate:!1,conditions:[...E,I],groups:[]}}i(D),a(!1)}},f=()=>{if(!o||!u)return;const I=((l==null?void 0:l.conditions)||[]).filter(D=>D.id!==u.id);if(I.length>0){const D={...l,conditions:I};i(D)}else i(void 0);a(!1)},N=I=>{p({...v,selectedValues:I})},A=()=>{o&&u?(p({id:u.id,field:u.field,selectedValues:Array.isArray(u.value)?u.value:[u.value]}),c("values")):(p({id:t.v4(),field:null,selectedValues:[]}),c("fields")),h("")};return C.useEffect(()=>{s&&A()},[s,o,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:o?`Edit Filter: ${(B=v.field)==null?void 0:B.label}`:d==="fields"?"Select Field to Filter":`Select Values for ${(w=v.field)==null?void 0:w.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!o&&(l==null?void 0:l.conditions)&&l.conditions.length>0&&d==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Current Filters:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l.conditions.map(I=>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:[I.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(I.value)?`${I.value.length} values`:String(I.value)})]},I.id))})]}),d==="fields"&&!o?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:x,onChange:I=>h(I.target.value),className:"h-full w-full bg-transparent text-[12px] text-foreground placeholder:text-muted-foreground focus:outline-none"}),x&&e.jsx("button",{type:"button","aria-label":"Clear search",onClick:()=>h(""),className:"inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground hover:bg-muted hover:text-foreground",children:e.jsx(t.X,{className:"h-3 w-3"})})]}),e.jsx("div",{className:"grid max-h-[400px] grid-cols-2 gap-1 overflow-y-auto",children:m.map(I=>e.jsxs("button",{type:"button",onClick:()=>g(I),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(I.dataType)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-[13px] text-foreground",children:I.label}),e.jsxs("div",{className:"truncate font-mono text-[10px] text-muted-foreground",children:[I.entityName,".",I.name]})]})]},I.id))}),m.length===0&&x&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',x,'"']}),m.length===0&&!x&&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(Ko,{field:v.field,selectedValues:v.selectedValues,onValuesChange:N,onBack:o?void 0:()=>c("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:o?e.jsx(t.Button,{variant:"destructive",onClick:f,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:S,disabled:!v.field||v.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function Ko({field:s,selectedValues:a,onValuesChange:r,onBack:l}){const[u,i]=C.useState(""),{values:o,isLoading:d,isFetching:c}=$o({field:s,searchQuery:u,limit:500}),x=u?o.filter(p=>String(p.value).toLowerCase().includes(u.toLowerCase())):o,h=p=>{const m=a.includes(p);r(m?a.filter(g=>g!==p):[...a,p])},v=()=>{a.length===x.length&&x.length>0?r([]):r(x.map(p=>p.value))};return e.jsxs("div",{className:"space-y-4",children:[l&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:l,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"})]}),d||c?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===x.length&&x.length>0,onCheckedChange:v}),e.jsxs(t.Label,{className:"text-sm",children:["Select All (",x.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:x.map(p=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>h(p.value),children:[e.jsx(n.Checkbox,{checked:a.includes(p.value),onCheckedChange:()=>h(p.value)}),e.jsx(Es,{className:"text-sm",children:p.label})]},p.id))})]})]})}function Go({value:s,onChange:a,showTitle:r=!0,title:l="NUMBER FORMAT"}){const u=t.toTFormatOptions(t.fromSemanticFormat(s))||{},i=o=>{a(t.fromTFormatOptions(o))};return e.jsx(Tt,{formatOptions:u,onFormatOptionsChange:i,showTitle:r,title:l})}const Uo=[];function Ho({field:s,zone:a,index:r,sortDirection:l,onSortDirectionChange:u,hasPivotColumns:i=!1,cardType:o}){var Rs,Os,Ps,Bs,Vs,_s,zs,qs,$s,Ks,Gs,Us,Hs,Qs,Ws,Ys,Js,Xs,Zs,en,tn,sn,nn,an,rn,ln,on,cn,dn,un,mn,xn;const{attributes:d,listeners:c,setNodeRef:x,transform:h,transition:v,isDragging:p}=n.useSortable({id:s.id}),m=t.useEditorStore(K=>K.card),g=t.useEditorStore(K=>K.frame),S=t.useDashboardStore(K=>K.isVisualEditing),f=t.useDashboardStore(K=>K.selectedSheetId),N=t.useDashboardStore(K=>K.actions.updateSheetCalculatedFields),A=t.useDashboardStore(K=>K.actions.updateDashboardCalculatedFields),w=t.useDashboardStore(K=>{var Y;return K.visualEditPendingDashboardCalculatedFields??((Y=K.dashboard)==null?void 0:Y.calculatedFields)})??Uo,{scopedFields:I,valuePickFilterableFields:D,isLoading:E}=n.useFilterableFields(),{userContext:y}=n.useCurrentUserInfo(),M=(y==null?void 0:y.type)==="organization",{updateLabel:b,handleAggregationChange:R,handleDateFormatChange:k,handleGranularityChange:F,handleAliasTemplateChange:O,handleValueAliasesChange:j,handleMetricFormatChange:T,removeField:L,handleMetricComparisonChange:V,handleMetricWindowTransformChange:z,handleMetricWindowOrderByChange:_,handleMetricWindowDirectionChange:P,handleMetricWindowPartitionToggle:q,handleMetricMovingAverageWindowSizeChange:G,handleMetricMovingAverageMinPeriodsChange:Q,handleMetricPreviousPeriodDeltaModeChange:U,handleMetricPercentOfTotalScopeChange:J,handleMetricPercentOfTotalOutputChange:X,handleKpiShowTrendlineChange:se,handleKpiTrendlineWindowChange:ue,handleKpiTrendlineGranularityChange:pe,handleMetricTargetValueChange:xe}=n.useFieldManagement(m),[je,Pe]=C.useState(!1),[Me,te]=C.useState(()=>{var K;return!!((K=s.parameters)!=null&&K.windowTransform)}),[fe,ke]=C.useState(!1),[Be,ze]=C.useState(!1),[ce,ve]=C.useState(null),ye=C.useMemo(()=>{const K=ie=>ie!=null&&ie.startsWith("card-source-")?ie.replace("card-source-",""):ie,Y=K(s.id),me=I.find(ie=>{if(s.qualifiedFieldName&&ie.qualifiedFieldName&&ie.qualifiedFieldName===s.qualifiedFieldName||s.qualifiedEntityName&&ie.qualifiedEntityName&&ie.qualifiedEntityName===s.qualifiedEntityName&&ie.name===s.name)return!0;const Ie=K(ie.id);return!!(Y&&Ie&&Y===Ie)});return{dataType:(me==null?void 0:me.dataType)||s.dataType,resolvedFromScopedField:!!me}},[s.dataType,s.id,s.name,s.qualifiedEntityName,s.qualifiedFieldName,I]),re=n.getGranularityOptionsForFieldType(ye.dataType),[$,H]=C.useState(s.dateFormat||"YYYY-MM-DD"),[ne,he]=C.useState(s.customFormat||""),[de,Te]=C.useState(!!s.customFormat),De=C.useRef(null),[ae,Ee]=C.useState(s.aliasTemplate||""),[Fe,Ne]=C.useState(s.valueAliases||{}),[Se,Ke]=C.useState((Rs=s.parameters)==null?void 0:Rs.filters),He=K=>{K==="custom"?Te(!0):(Te(!1),H(K),(a==="groupBy"||Kt)&&k(r,K,"",a))},le=K=>{he(K),(a==="groupBy"||Kt)&&k(r,"custom",K,a)},Le=K=>{var ie;const me=(ie=n.getDateFormatOptionsForGranularity(K)[0])==null?void 0:ie.value;me&&!de&&(H(me),a==="groupBy"&&k(r,me,"",a)),a==="groupBy"&&F(r,K)},$e=K=>{Ee(K),a==="metrics"&&O(r,K)},Ce=K=>{Ne(K),a==="metrics"&&j(r,K)},Ze=K=>{b(a,r,K)},Ae=n.getExpressionFieldKind(s),qt=n.getFieldExpressionAnnotation(s),ct=n.isManagedCalculatedExpressionField(s),Et=s.role==="metric"&&ct,et=ct&&(Ae==="user_calculated"||Ae==="inline_expression"&&s.fieldScope!=="domain"),Ue=et?t.resolveLocalCalculatedFieldScope({field:s,sheetFields:(g==null?void 0:g.calculatedFields)||[],dashboardFields:w}):void 0,It=et&&(Ue==null?void 0:Ue.scope)==="sheet",dt=et&&(Ue==null?void 0:Ue.scope)==="dashboard",gt=Ae==="domain_calculated"||s.fieldScope==="domain",Dt=gt?n.resolveDomainCalculatedFieldForEdit(s,I):void 0,rt=gt?"domain":It?"sheet":dt?"dashboard":"card",bt=gt?Dt||s:(It||dt)&&(Ue!=null&&Ue.matchedField)?Ue.matchedField:s,kt=K=>{var Y;if(Ke(K),a==="metrics"){const me={...s,parameters:{...s.parameters,filters:K}},ie=[...((Y=m.config)==null?void 0:Y.metricColumns)||[]];ie[r]=me,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:ie})}ke(!1)},At=()=>{L(a,r)},$t={transform:n.CSS.Transform.toString(h),transition:v},jt=t.getDataType(ye.dataType||s.dataType),ut=jt==="date",lt=o==="kpi",Kt=a==="detailColumns",Lt=(Os=m.config)==null?void 0:Os.metricColumns,tt=(Ps=m.config)==null?void 0:Ps.groupByColumns,Mt=t.useDashboardStore(K=>{var Y;return(Y=K.dashboard)==null?void 0:Y.filters}),Ft=t.useDashboardStore(K=>K.filterValues),mt=s.granularity||"day",Gt=re.includes(mt)?mt:"day",Ut=a==="groupBy"&&!re.includes(mt),vt=n.getDateFormatOptionsForGranularity(Gt),ns=de?"custom":vt.some(K=>K.value===$)?$:((Bs=vt[0])==null?void 0:Bs.value)??"YYYY-MM-DD";C.useEffect(()=>{var me;if(E||!Ut){De.current=null;return}const K=`${s.id}:${mt}:${ye.dataType||s.dataType||""}:${r}`;if(De.current===K)return;De.current=K;const Y="day";if(F(r,Y),!de){const ie=(me=n.getDateFormatOptionsForGranularity(Y)[0])==null?void 0:me.value;ie&&(H(ie),k(r,ie,"",a))}},[s.dataType,s.id,k,F,Ut,r,de,E,mt,ye.dataType,a]);const yt=!!o&&t.COMPARISON_SUPPORTED_CHART_TYPES.includes(o),Ht=o==="kpi"||o==="table",Qe=C.useMemo(()=>tt==null?void 0:tt.find(K=>t.getDataType(K.dataType||"")==="date"),[tt]),W=C.useMemo(()=>(tt||[]).some(K=>t.getDataType(K.dataType||"")==="date"),[tt]),ee=C.useMemo(()=>{var ie;if(!Qe)return!1;const K=(ie=m.config)==null?void 0:ie.filters;if(!K)return!1;const Y=Ie=>{const _e=Ie.field;return _e?Qe.id&&_e.id===Qe.id||Qe.qualifiedFieldName&&_e.qualifiedFieldName===Qe.qualifiedFieldName?!0:_e.name===Qe.name:!1},me=Ie=>Ie.conditions.some(qe=>t.getDataType(qe.field.dataType||"")==="date"&&Y(qe))?!0:Ie.groups.some(qe=>me(qe));return me(K)},[(Vs=m.config)==null?void 0:Vs.filters,Qe]),Z=C.useMemo(()=>Ro(Mt||[],Qe,Ft),[Mt,Ft,Qe]),ge=ee||Z,oe=s,be=((zs=(_s=oe.parameters)==null?void 0:_s.windowTransform)==null?void 0:zs.function)||"none",we=n.isMetricTransformEnabled(oe),Re=we?be:null,We=n.supportsMetricTransformForMetric({cardType:o||"table",cardConfig:m.config||{},metric:oe,transformMode:Re||"running_total"}),st=!!oe.comparisonType&&oe.comparisonType!=="none",xt=n.getRunningTotalOrderByCandidates(tt||[]),Ve=((Ks=($s=(qs=oe.parameters)==null?void 0:qs.windowTransform)==null?void 0:$s.orderBy)==null?void 0:Ks.fieldId)||"",Ct=((Hs=(Us=(Gs=oe.parameters)==null?void 0:Gs.windowTransform)==null?void 0:Us.orderBy)==null?void 0:Hs.direction)||"asc",Qt=xt.find(K=>K.id===Ve),Rt=Re==="running_total"||Re==="moving_average"||Re==="previous_period_delta",ra=we&&Rt&&!!Qt&&t.getDataType(Qt.dataType||"")!=="date",la=n.getDefaultRunningTotalPartitionByFieldIds({cardType:o||"table",cardConfig:m.config||{},orderByFieldId:Ve||void 0}),oa=new Set(((Ws=(Qs=oe.parameters)==null?void 0:Qs.windowTransform)==null?void 0:Ws.partitionByFieldIds)||la),ia=o==="pivotTable"||n.isSubtotalEnabledAggregateTable(o||"table",m.config||{}),ks=[...(tt||[]).filter(K=>K.id&&(!Rt||K.id!==Ve)),...ia?(((Ys=m.config)==null?void 0:Ys.pivotByColumns)||[]).filter(K=>K.id):[]],As=((Zs=(Xs=(Js=oe.parameters)==null?void 0:Js.windowTransform)==null?void 0:Xs.movingAverage)==null?void 0:Zs.windowSize)||7,ca=((sn=(tn=(en=oe.parameters)==null?void 0:en.windowTransform)==null?void 0:tn.movingAverage)==null?void 0:sn.minPeriods)||1,da=((rn=(an=(nn=oe.parameters)==null?void 0:nn.windowTransform)==null?void 0:an.previousPeriodDelta)==null?void 0:rn.mode)||"absolute",Ls=((cn=(on=(ln=oe.parameters)==null?void 0:ln.windowTransform)==null?void 0:on.percentOfTotal)==null?void 0:cn.scope)||"grand_total",ua=((mn=(un=(dn=oe.parameters)==null?void 0:dn.windowTransform)==null?void 0:un.percentOfTotal)==null?void 0:mn.output)||"percent",ma=C.useMemo(()=>(Lt||[]).some(K=>K.comparisonType==="start_vs_end"),[Lt]);C.useEffect(()=>{we&&te(!0)},[we]);const xa=a!=="pivotBy"&&a!=="sortBy",ha=ut&&a==="groupBy"&&(!lt||ma),pa=!lt&&ut&&(a==="groupBy"||Kt),fa=o==="kpi"&&ut&&a==="groupBy",ga=a==="metrics",Ms=yt&&a==="metrics",ba=()=>{const K=s,Y=a==="metrics"&&Et;return e.jsxs("div",{className:"space-y-1",children:[!Y&&e.jsx("div",{title:`${s.entityName}.${s.name}`,onPointerDown:me=>{me.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-muted-foreground/80",children:`${s.entityName}.${s.name}`}),Y&&K.calculatedFormula&&e.jsxs("div",{title:n.formatDisplayFormula(K.calculatedFormula),onPointerDown:me=>{me.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)]})]})},ja=()=>xa?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(Xe,{value:s.label??"",onSave:Ze,placeholder:"Display label...",type:"text"})]}):null,va=()=>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:l||"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"})]})]})]}),Fs=()=>ha?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:Gt,onValueChange:Le,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:re.map(K=>e.jsx(t.SelectItem,{className:"text-xs",value:K,children:t.toTitleCase(K)},K))})]})]}):null,ya=()=>pa?e.jsxs(e.Fragment,{children:[Fs(),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:ns,onValueChange:He,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:vt.map(K=>e.jsx(t.SelectItem,{className:"text-xs",value:K.value,children:K.label},K.value))})]}),de&&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:ne,onChange:K=>{K.stopPropagation(),le(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,Ca=()=>{var Y,me,ie,Ie;const K=fa;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:((Y=m.config)==null?void 0:Y.showTrendline)||!1,onCheckedChange:se})]})}),((me=m.config)==null?void 0:me.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(t.Input,{type:"number",min:"1",max:"365",value:((ie=m.config)==null?void 0:ie.trendlineWindow)||30,onChange:_e=>{const qe=parseInt(_e.target.value)||30;ue(qe)},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:((Ie=m.config)==null?void 0:Ie.trendlineGranularity)||"day",onValueChange:pe,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},Na=()=>{if(!ga)return null;const K=Et;return e.jsxs(e.Fragment,{children:[K&&M&&!gt&&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:()=>ze(!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:Y=>{R(r,Y)},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(Go,{value:oe.format,onChange:Y=>T(r,Y),showTitle:!1})]}),e.jsx(n.Collapsible,{open:Me,onOpenChange:te,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:[!Me&&e.jsx("span",{className:"mr-2",children:we?t.toTitleCase(be.replace(/_/g," ")):"None"}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 transition-transform",Me?"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:we?be:"none",onValueChange:Y=>z(r,Y),disabled:!We.supported&&!we,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:st,children:"Running Total"}),e.jsx(t.SelectItem,{value:"moving_average",disabled:st,children:"Moving Average"}),e.jsx(t.SelectItem,{value:"previous_period_delta",disabled:st,children:"Previous Period Delta"}),e.jsx(t.SelectItem,{value:"percent_of_total",disabled:st,children:"Percent of Total"})]})]}),!We.supported&&!we&&e.jsx("div",{className:"text-xs text-muted-foreground",children:We.reason}),st&&!we&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"Disable comparison to enable metric transforms."})]}),we&&e.jsxs(e.Fragment,{children:[Rt&&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:Ve,onValueChange:Y=>_(r,Y),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select order field..."})}),e.jsx(t.SelectContent,{children:xt.filter(Y=>!!Y.id).map(Y=>e.jsx(t.SelectItem,{value:Y.id,className:"text-xs",children:Y.label||Y.name},Y.id))})]}),!Ve&&e.jsx("div",{className:"text-xs text-amber-700",children:"No date trend detected. Select an order field."}),ra&&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:Ct,onValueChange:Y=>P(r,Y),disabled:!Ve,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"})]})]})]})]}),Re==="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:As,onChange:Y=>G(r,Number(Y.target.value))}),e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Min Periods"}),e.jsx(t.Input,{type:"number",min:1,max:As,className:"h-8 text-xs",value:ca,onChange:Y=>Q(r,Number(Y.target.value))})]}),Re==="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:da,onValueChange:Y=>U(r,Y),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select output..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"absolute",children:"Absolute Delta"}),e.jsx(t.SelectItem,{value:"percent",children:"Percent Delta"})]})]})]}),Re==="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:Ls,onValueChange:Y=>J(r,Y),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select scope..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"grand_total",children:"Grand Total"}),e.jsx(t.SelectItem,{value:"partition_total",children:"Partition Total"})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Output"}),e.jsxs(t.Select,{value:ua,onValueChange:Y=>X(r,Y),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select output..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"percent",children:"Percent"}),e.jsx(t.SelectItem,{value:"fraction",children:"Fraction"})]})]})]})]}),(Re==="running_total"||Re==="moving_average"||Re==="previous_period_delta"||Re==="percent_of_total"&&Ls==="partition_total")&&ks.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:ks.map(Y=>{const me=!!Y.id&&oa.has(Y.id);return e.jsxs("button",{type:"button",onClick:()=>Y.id&&q(r,Y.id),className:t.cn("flex h-7 w-full items-center justify-between rounded border px-2 text-xs",me?"border-primary bg-primary/5 text-primary":"border-border text-muted-foreground"),children:[e.jsx("span",{children:Y.label||Y.name}),me?e.jsx(t.Check,{className:"h-3 w-3"}):null]},Y.id)})})]})]})]})]})}),Ms&&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:oe.comparisonType||"none",disabled:we,onValueChange:Y=>V(r,Y),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"none",children:"No Comparison"}),(()=>{const Y=!W||!ge,me=W?ge?void 0:"Add a date filter to enable":"Add a date groupBy to enable",ie=(Ie,_e)=>e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.SelectItem,{value:Ie,disabled:Y,title:me,children:_e})}),Y&&me&&e.jsx(t.TooltipContent,{side:"right",children:me})]})});return e.jsxs(e.Fragment,{children:[ie("previous_period","Previous Period"),ie("same_period_last_year","Same Period Last Year"),ie("start_vs_end","Start vs End")]})})(),Ht&&e.jsx(t.SelectItem,{value:"target",children:"Target"})]})]})]}),Ms&&oe.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:oe.targetValue!==void 0&&oe.targetValue!==null?String(oe.targetValue):"",onChange:Y=>{const me=Y.target.value;if(me===""){xe(r,void 0);return}const ie=Number(me);xe(r,Number.isFinite(ie)?ie:void 0)},className:"h-8 text-xs",placeholder:"Enter target value..."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(Se==null?void 0:Se.conditions)&&Se.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:Se.conditions.map(Y=>e.jsxs("div",{className:"flex cursor-pointer items-center gap-2 rounded bg-muted/50 p-2 text-xs transition-colors hover:bg-muted/70",onClick:()=>{ve(Y),ke(!0)},children:[e.jsxs("span",{className:"font-medium",children:[Y.field.label,":"]}),e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"cursor-help text-muted-foreground",children:Array.isArray(Y.value)?Y.value.length===1?String(Y.value[0]):Y.value.length<=2?Y.value.join(", "):`${Y.value.slice(0,2).join(", ")} +${Y.value.length-2}`:String(Y.value)})}),Array.isArray(Y.value)&&Y.value.length>1&&e.jsx(t.TooltipContent,{side:"top",className:"max-w-[300px]",children:e.jsxs("div",{className:"text-xs",children:[e.jsxs("div",{className:"mb-1 font-medium",children:["Selected values (",Y.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:Y.value.map((me,ie)=>e.jsx("div",{children:String(me)},ie))})]})})]})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:me=>{var Ie;me.stopPropagation();const ie=Se.conditions.filter(_e=>_e.id!==Y.id);if(ie.length>0){const _e={...Se,conditions:ie};kt(_e)}else if(Ke(void 0),a==="metrics"){const _e={...s,parameters:{...s.parameters,filters:void 0}},qe=[...((Ie=m.config)==null?void 0:Ie.metricColumns)||[]];qe[r]=_e,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:qe})}},children:e.jsx(t.X,{className:"h-3 w-3"})})]},Y.id))}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{ve(null),ke(!0)},children:[e.jsx(n.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(qo,{column:s}),i&&e.jsxs(e.Fragment,{children:[e.jsx(Oo,{aliasTemplate:ae,onAliasTemplateChange:$e}),e.jsx(Po,{valueAliases:Fe,onValueAliasesChange:Ce})]})]})};Se!=null&&Se.conditions&&Se.conditions.length>0;const Sa=a!=="sortBy";return e.jsxs(e.Fragment,{children:[e.jsxs(t.Popover,{open:je,onOpenChange:Pe,children:[e.jsxs("div",{ref:x,style:$t,className:t.cn("group flex h-7 w-full items-center gap-1.5 rounded-control border bg-background px-1.5 transition-colors",je?"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",...d,...c,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:jt,calculated:!!qt}),e.jsx(Es,{className:"block w-0 min-w-0 flex-1 text-[12px] text-foreground",children:n.getMetricDisplayLabel(s)}),a==="metrics"&&((xn=Se==null?void 0:Se.conditions)==null?void 0:xn.length)&&!je&&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:Se.conditions.length})]})}),e.jsx(t.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:Se.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":l==="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(l==="asc"?"desc":"asc")},children:l==="asc"?e.jsx(n.ArrowUp,{className:"h-3 w-3"}):e.jsx(n.ArrowDown,{className:"h-3 w-3"})}),Sa&&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(),At()},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:[ba(),va(),ja(),o==="kpi"&&Fs(),ya(),Ca(),Na()]})})]}),fe&&e.jsx(na,{open:fe,onOpenChange:K=>{ke(K),K||ve(null)},availableFields:D,existingFilters:Se,editingCondition:ce,onSave:K=>{var Y;if(K)kt(K);else if(Ke(void 0),a==="metrics"){const me={...s,parameters:{...s.parameters,filters:void 0}},ie=[...((Y=m.config)==null?void 0:Y.metricColumns)||[]];ie[r]=me,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:ie})}ve(null)}}),Be&&a==="metrics"&&Et&&e.jsx(n.CalculatedFieldEditor,{open:Be,onOpenChange:ze,availableFields:I,existingField:bt,existingFieldScope:rt,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:K=>{var Nt,nt;if(K.role!=="metric")return;const{card:Y,frame:me,actions:ie}=t.useEditorStore.getState(),Ie=((Nt=Y.config)==null?void 0:Nt.metricColumns)||[],_e=((nt=Y.config)==null?void 0:nt.sortByColumns)||[],qe=rt==="dashboard"?w:me.calculatedFields||[],{nextActiveFields:Ye,nextSortByFields:Je,nextStoredFields:at,nextSharedFields:ot}=n.saveCalculatedFieldToCardScope({activeFields:Ie,sortByFields:_e,storedFields:Y.calculatedFields||[],sharedFields:qe,updatedField:K,editingField:bt,previousScope:rt});(Ye||Je)&&ie.updateCardConfig(m.id,{...Ye?{metricColumns:Ye}:{},...Je?{sortByColumns:Je}:{}}),ie.updateCard(m.id,{calculatedFields:at}),rt==="dashboard"&&ot!==qe?A(ot):ot!==qe&&n.commitSharedCalculatedFields({nextSharedFields:ot,currentSharedFields:qe,isVisualEditing:S,selectedSheetId:f,updateFrame:ie.updateFrame,updateSheetCalculatedFields:N})},onSaveToSheet:K=>{var Ot,Pt;if(K.role!=="metric")return;const{card:Y,frame:me,actions:ie}=t.useEditorStore.getState(),Ie=s,_e=((Ot=Y.config)==null?void 0:Ot.metricColumns)||[],qe=((Pt=Y.config)==null?void 0:Pt.sortByColumns)||[],Ye=me.calculatedFields||[],{nextActiveFields:Je,nextSortByFields:at,nextStoredFields:ot,nextSheetFields:Nt,nextDashboardFields:nt}=n.saveCalculatedFieldToSheetScope({activeFields:_e,sortByFields:qe,storedFields:Y.calculatedFields||[],sheetFields:Ye,dashboardFields:w,updatedField:{...K,id:Ie.id,aliasTemplate:Ie.aliasTemplate,valueAliases:Ie.valueAliases,parameters:Ie.parameters,customFormat:Ie.customFormat},editingField:bt,previousScope:rt});n.commitSharedCalculatedFields({nextSharedFields:Nt,currentSharedFields:Ye,isVisualEditing:S,selectedSheetId:f,updateFrame:ie.updateFrame,updateSheetCalculatedFields:N}),nt&&nt!==w&&A(nt),(Je||at)&&ie.updateCardConfig(m.id,{...Je?{metricColumns:Je}:{},...at?{sortByColumns:at}:{}}),ie.updateCard(m.id,{calculatedFields:ot})},onSaveToDashboard:K=>{var Ot,Pt;if(K.role!=="metric")return;const{card:Y,frame:me,actions:ie}=t.useEditorStore.getState(),Ie=s,_e=((Ot=Y.config)==null?void 0:Ot.metricColumns)||[],qe=((Pt=Y.config)==null?void 0:Pt.sortByColumns)||[],Ye=me.calculatedFields||[],{nextActiveFields:Je,nextSortByFields:at,nextStoredFields:ot,nextSharedFields:Nt,nextSheetFields:nt}=n.saveCalculatedFieldToSharedScope({activeFields:_e,sortByFields:qe,storedFields:Y.calculatedFields||[],sharedFields:w,sheetFields:Ye,updatedField:{...K,id:Ie.id,aliasTemplate:Ie.aliasTemplate,valueAliases:Ie.valueAliases,parameters:Ie.parameters,customFormat:Ie.customFormat},editingField:bt,previousScope:rt});A(Nt),nt&&nt!==Ye&&n.commitSharedCalculatedFields({nextSharedFields:nt,currentSharedFields:Ye,isVisualEditing:S,selectedSheetId:f,updateFrame:ie.updateFrame,updateSheetCalculatedFields:N}),(Je||at)&&ie.updateCardConfig(m.id,{...Je?{metricColumns:Je}:{},...at?{sortByColumns:at}:{}}),ie.updateCard(m.id,{calculatedFields:ot})},cardId:m.id})]})}function Qo({concept:s}){const{title:a,description:r}=Wo[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(Yo,{highlight:s})]})]})}const Wo={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 Yo({highlight:s}){const a=s==="pivotBy",r=s==="groupBy",l=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:Fn.map((i,o)=>e.jsxs("tr",{className:t.cn(o!==Fn.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((d,c)=>e.jsx("td",{className:t.cn("px-1.5 py-1 text-right font-mono tabular-nums text-muted-foreground",l&&u),children:d},c))]},i.label))})]})})}const Fn=[{label:"Electronics",values:["2,300","1,800","3,400"]},{label:"Clothing",values:["1,300","620","480"]}],Jo={groupBy:Zt,pivotBy:ys,metrics:Ua,detailColumns:t.Table2,sortBy:Pn};function _t({zone:s,fields:a,label:r,placeholder:l,shouldShow:u,hasPivotColumns:i=!1,activeField:o=null}){const{isOver:d,setNodeRef:c}=n.useDroppable({id:s}),{updateSortByColumn:x}=t.useEditorActions(),h=t.useEditorStore(N=>N.card),v=t.useEditorStore(N=>N.card.type),p=a.length>0,m=C.useMemo(()=>!o||!d?!0:n.validateFieldForChartType(o,s,v).isValid,[o,d,s,v]),g=(N,A)=>{var w;!((w=h.config)!=null&&w.sortByColumns)||h.config.sortByColumns.findIndex(I=>I.id===N)===-1||x(h.id,N,{direction:A})};if(s==="sortBy"&&u===!1)return null;const S=s!=="sortBy"&&v!=="kpi",f=Jo[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:c,className:t.cn("rounded-control transition-colors",{"border border-foreground/40 bg-muted/50":d&&m,"border border-destructive/40 bg-destructive/5":d&&!m,"border border-dashed border-border/50 bg-background":!d&&!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(f,{className:"h-3 w-3 shrink-0 text-muted-foreground/60"}),e.jsx("span",{children:l}),S&&e.jsx(Qo,{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 w=N.direction;return e.jsx(Ho,{field:N,zone:s,index:A,sortDirection:w,onSortDirectionChange:I=>g(N.id,I),hasPivotColumns:i,cardType:v},N.id)})})})})]})}const Xo=[];function Zo({groupByFields:s,pivotByFields:a,metricsFields:r,sortByFields:l,detailFields:u,activeField:i}){var Q,U,J;const[o,d]=C.useState(!1);t.useEditorStore(X=>{var se;return!!((se=X.card.customCardPreferences)!=null&&se.url)});const c=t.useEditorStore(X=>X.card),x=t.useEditorStore(X=>X.frame),h=n.findCustomVisualConfigCard(x,c),{manifest:v}=n.useCustomVisual(((Q=h==null?void 0:h.customCardPreferences)==null?void 0:Q.url)||""),p=(U=v==null?void 0:v.visuals)==null?void 0:U.find(X=>{var se;return X.name===((se=h==null?void 0:h.customCardPreferences)==null?void 0:se.componentName)}),m=n.resolveMultiInputType(h,p)==="multiple";m&&((J=h==null?void 0:h.customCardPreferences)!=null&&J.url);const g=n.getConfigSlotExpectedType(p==null?void 0:p.slots),S=t.useEditorStore(X=>X.actions.updateCardConfig),f=t.useEditorStore(X=>X.actions.updateCard),N=t.useEditorStore(X=>X.actions.updateFrame),A=t.useDashboardStore(X=>X.isVisualEditing),B=t.useDashboardStore(X=>X.selectedSheetId),w=t.useDashboardStore(X=>X.actions.updateSheetCalculatedFields),I=t.useDashboardStore(X=>X.actions.updateDashboardCalculatedFields),E=t.useDashboardStore(X=>{var se;return X.visualEditPendingDashboardCalculatedFields??((se=X.dashboard)==null?void 0:se.calculatedFields)})??Xo,{scopedFields:y}=n.useScopedFields(),{userContext:M}=n.useCurrentUserInfo(),b=m&&(h==null?void 0:h.id)===c.id&&g?g:c==null?void 0:c.type,R=b==="detailTable",k=s.length>0||r.length>0||u.length>0,F=!R&&(b!=="kpi"||r.length<=2),O=!R,j=!R&&b!=="kpi",T=b!=="kpi"&&k,L=R,V="Drop sort fields here",z=(M==null?void 0:M.type)==="organization",_=["pie","doughnut","polar","funnel","aggregateTable","bubble","scatter"].includes(b),P=j&&!_,q=()=>b==="kpi"?{label:"Trend By",placeholder:"Drop trend field here"}:{label:"Rows",placeholder:"Drop dimensions here"},G=()=>b==="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"}),k&&e.jsx("button",{type:"button","aria-label":"Reset all field selections",onClick:()=>{S(c.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:[F&&e.jsx(_t,{zone:"groupBy",fields:s,label:q().label,placeholder:q().placeholder,activeField:i}),P&&e.jsx(_t,{zone:"pivotBy",fields:a,label:"Pivot Columns",placeholder:"Drop pivot fields here",activeField:i}),O&&e.jsx(_t,{zone:"metrics",fields:r,label:G().label,placeholder:G().placeholder,hasPivotColumns:a.length>0,activeField:i}),L&&e.jsx(_t,{zone:"detailColumns",fields:u,label:"Columns",placeholder:"Drop columns here"}),r.length>=1&&z&&e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:()=>d(!0),className:"mt-1.5 w-full justify-start border-border/60 border-dashed bg-background text-xs text-foreground/70 hover:bg-muted/40 hover:text-foreground",children:[e.jsx(n.Calculator,{className:"mr-2 h-4 w-4"}),"Create Metric"]}),T&&e.jsx(_t,{zone:"sortBy",fields:l,label:"Sort By",placeholder:V,activeField:i})]}),e.jsx(n.CalculatedFieldEditor,{open:o,onOpenChange:d,availableFields:y,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:X=>{if(X.role!=="metric")return;const{nextStoredFields:se}=n.saveCalculatedFieldToCardScope({activeFields:r,storedFields:c.calculatedFields||[],sharedFields:x.calculatedFields||[],updatedField:X,previousScope:"card"});f(c.id,{calculatedFields:se})},onSaveToSheet:X=>{if(X.role!=="metric")return;const se=x.calculatedFields||[],{nextSheetFields:ue}=n.saveCalculatedFieldToSheetScope({activeFields:r,storedFields:c.calculatedFields||[],sheetFields:se,updatedField:X,previousScope:"sheet"});n.commitSharedCalculatedFields({nextSharedFields:ue,currentSharedFields:se,isVisualEditing:A,selectedSheetId:B,updateFrame:N,updateSheetCalculatedFields:w})},onSaveToDashboard:X=>{if(X.role!=="metric")return;const{nextSharedFields:se}=n.saveCalculatedFieldToSharedScope({activeFields:r,storedFields:c.calculatedFields||[],sharedFields:E,updatedField:X,previousScope:"dashboard"});I(se)},cardId:c.id})]})}function ei(){var g,S,f;const[s,a]=C.useState(!1),[r,l]=C.useState(!1),u=t.useEditorStore(N=>{var A;return!!((A=N.card.customCardPreferences)!=null&&A.url)}),i=t.useEditorStore(N=>N.card),o=t.useEditorStore(N=>N.frame),d=n.findCustomVisualConfigCard(o,i),{manifest:c}=n.useCustomVisual(((g=d==null?void 0:d.customCardPreferences)==null?void 0:g.url)||""),x=(S=c==null?void 0:c.visuals)==null?void 0:S.find(N=>{var A;return N.name===((A=d==null?void 0:d.customCardPreferences)==null?void 0:A.componentName)}),v=n.resolveMultiInputType(d,x)==="multiple"&&!!((f=d==null?void 0:d.customCardPreferences)!=null&&f.url),p=!u||v,m=u||v;return!p&&!m?null:e.jsxs("div",{className:"shrink-0 border-t border-border bg-background",children:[p&&s&&e.jsx("div",{className:"max-h-[40vh] overflow-y-auto border-b border-border px-4",children:e.jsx(n.Accordion,{type:"single",collapsible:!0,className:"w-full divide-y divide-border/60",children:e.jsx(sa,{mode:"config"})})}),p&&e.jsxs("button",{type:"button",onClick:()=>a(N=>!N),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:"Chart settings"})]}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 text-muted-foreground transition-transform",s&&"rotate-180"),strokeWidth:1.75})]}),m&&r&&e.jsx("div",{className:"max-h-[40vh] overflow-y-auto border-b border-t border-border px-4",children:e.jsx(Zn,{})}),m&&e.jsxs("button",{type:"button",onClick:()=>l(N=>!N),className:t.cn("flex w-full items-center justify-between px-4 py-2.5 text-left transition-colors hover:bg-muted/50",p&&"border-t border-border"),children:[e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Bn,{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",r&&"rotate-180"),strokeWidth:1.75})]})]})}function ti({onEditJoins:s}){const a=t.useEditorStore(c=>c.card),{autoJoinMetadata:r}=n.useEditorCardQuery(a);if(!(r!=null&&r.autoResolved))return null;const{resolvedJoinPlan:l}=r,u=(l==null?void 0:l.joins)||[];if(u.length===0)return null;const i=c=>!c||c.length===0?"No conditions":c.map(x=>{var m,g,S,f;const h=`${(m=x.source)==null?void 0:m.entityName}.${(g=x.source)==null?void 0:g.name}`,v=`${(S=x.target)==null?void 0:S.entityName}.${(f=x.target)==null?void 0:f.name}`,p=x.operator||"=";return`${h} ${p} ${v}`}).join(" AND "),o=c=>!c.joinKeyGroups||c.joinKeyGroups.length===0?"No conditions defined":c.joinKeyGroups.length===1?i(c.joinKeyGroups[0].keys):c.joinKeyGroups.map((x,h)=>({id:h,operator:x.operator,condition:i(x.keys)})),d=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((c,x)=>{const h=o(c),v=Array.isArray(h);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:c.source.name}),e.jsx(n.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:c.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:c.joinType})]}),e.jsx("div",{className:"mt-1 space-y-1",children:v?h.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:h})})})]},c.id||x)})})})]})});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"}),d,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 si({selectedChart:s,onChartChange:a,isVisible:r=!0,onToggleVisibility:l,groupByFields:u,pivotByFields:i,metricsFields:o,sortByFields:d,detailFields:c,activeField:x}){var E,y;const[h,v]=C.useState(!1),p=t.useEditorStore(M=>M.card),m=t.useEditorStore(M=>M.editorContext),g=t.useEditorStore(M=>M.actions.updateCardConfig),S=(m==null?void 0:m.type)==="documentSection",{autoJoinMetadata:f}=n.useEditorCardQuery(p),N=((E=p==null?void 0:p.config)==null?void 0:E.joinPlan)||(f!=null&&f.autoResolved?f.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),A=((y=p==null?void 0:p.dataSource)==null?void 0:y.selectedEntities)||[],B=M=>{g(p.id,{...p==null?void 0:p.config,joinPlan:M}),v(!1)},w=()=>{g(p.id,{...p==null?void 0:p.config,joinPlan:void 0}),v(!1)},I=()=>{v(!1)},D=()=>{v(!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:[!S&&e.jsxs("div",{className:"flex items-start",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(Rr,{selectedChart:s,onChartChange:a})}),l&&e.jsx("div",{className:"px-2 pt-4",children:e.jsx(n.IconButton,{tooltip:"Hide chart configuration","aria-label":"Hide chart configuration",onClick:l,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(ti,{onEditJoins:D})}),e.jsx(Zo,{groupByFields:u,pivotByFields:i,metricsFields:o,sortByFields:d,detailFields:c,activeField:x})]}),e.jsx(ei,{}),e.jsx(_n,{open:h,onOpenChange:v,joinPlan:N,availableDataSources:A,onSave:B,onCancel:I,onRemove:w,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:l&&e.jsx(n.IconButton,{tooltip:"Show chart configuration","aria-label":"Show chart configuration",onClick:l,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 ni({initialFilters:s,availableFields:a}={}){const[r,l]=C.useState(s||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});t.useEditorStore(w=>w.card.dataSource);const{filterableFields:u,isLoading:i}=n.useFilterableFields(),o=a||u||[],d={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},c=w=>{const I=D=>{if(D.id===w){const E=o[0]||d,y=t.getDataType(E.dataType)==="date";return{...D,conditions:[...D.conditions,{id:`condition-${Date.now()}`,field:E,operator:y?"between":"=",value:y?[]:""}]}}return{...D,groups:D.groups.map(I)}};l(I(r))},x=w=>{const I=D=>{if(D.id===w){const E=o[0]||d,y=t.getDataType(E.dataType)==="date";return{...D,groups:[...D.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:E,operator:y?"between":"=",value:y?[]:""}],groups:[]}]}}return{...D,groups:D.groups.map(I)}};l(I(r))},h=(w,I)=>{const D=E=>E.id===w?{...E,conditions:E.conditions.filter(y=>y.id!==I)}:{...E,groups:E.groups.map(D)};l(D(r))},v=(w,I)=>{const D=E=>E.id===w?{...E,groups:E.groups.filter(y=>y.id!==I)}:{...E,groups:E.groups.map(D)};l(D(r))},p=(w,I,D,E)=>{if(D==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const y=M=>M.id===w?{...M,conditions:M.conditions.map(b=>b.id===I?{...b,[D]:E}:b)}:{...M,groups:M.groups.map(y)};l(y(r))},m=(w,I,D)=>{const E=y=>y.id===w?{...y,conditions:y.conditions.map(M=>M.id===I?{...M,...D}:M)}:{...y,groups:y.groups.map(E)};l(E(r))},g=(w,I)=>{const D=E=>E.id===w?{...E,logicalOperator:I}:{...E,groups:E.groups.map(D)};l(D(r))},S=(w,I)=>{const D=E=>E.id===w?{...E,negate:I}:{...E,groups:E.groups.map(D)};l(D(r))},f=(w,I,D)=>{const E=y=>y.id===w?{...y,conditions:n.arrayMove(y.conditions,I,D)}:{...y,groups:y.groups.map(E)};l(E(r))},N=(w,I,D)=>{const E=y=>y.id===w?{...y,groups:n.arrayMove(y.groups,I,D)}:{...y,groups:y.groups.map(E)};l(E(r))},A=w=>{if(!w||w.conditions.length===0&&w.groups.length===0)return"-- No filters defined";const I=E=>{let y="";typeof E.field=="object"?y=E.field.entityName?`${E.field.entityName}.${E.field.name}`:E.field.name:y=String(E.field);const M=E.operator;let b=E.value;if(E.field.dataType==="string"&&!["in","not in"].includes(E.operator))typeof b=="string"?b=`'${b}'`:Array.isArray(b)&&(b=`'${b.join(", ")}'`);else if(E.field.dataType==="date"||E.field.dataType==="datetime"||E.field.dataType==="timestamp")if(E.operator==="between"&&Array.isArray(b)&&b.length===2){const R=b[0]?`'${b[0]}'`:"NULL",k=b[1]?`'${b[1]}'`:"NULL";return`${y} BETWEEN ${R} AND ${k}`}else if((E.operator==="in"||E.operator==="not in")&&Array.isArray(b)){const R=b.map(k=>k?`'${k}'`:"NULL").join(", ");return`${y} ${M} (${R})`}else typeof b=="string"||b instanceof Date?b=`'${b}'`:Array.isArray(b)&&b.length>0&&(b=`'${b[0]}'`);else if(["in","not in"].includes(E.operator)){let R=[];Array.isArray(b)?R=b.map(k=>typeof k=="string"?`'${k}'`:String(k)):typeof b=="string"?R=b.split(",").map(k=>{const F=k.trim();return E.field.dataType==="string"?`'${F}'`:F}):typeof b=="number"&&(R=[String(b)]),b=`(${R.join(", ")})`}switch(M){case"contains":return typeof b=="string"?`${y} LIKE '%${b.replace(/'/g,"")}'`:`${y} LIKE '%${String(b)}'`;case"startsWith":return typeof b=="string"?`${y} LIKE '${b.replace(/'/g,"")}%'`:`${y} LIKE '${String(b)}%'`;case"endsWith":return typeof b=="string"?`${y} LIKE '%${b.replace(/'/g,"")}'`:`${y} LIKE '%${String(b)}'`;case"isNull":return`${y} IS NULL`;case"isNotNull":return`${y} IS NOT NULL`;default:return`${y} ${M} ${b}`}},D=E=>{const y=E.conditions.map(I),M=E.groups.map(F=>D(F)),b=[...y,...M].filter(Boolean);if(b.length===0)return"";const R=b.join(` ${E.logicalOperator} `),k=b.length>1?`(${R})`:R;return E.negate?`NOT ${k}`:k};return D(w)},B=r.conditions.length>0||r.groups.length>0;return{currentFilters:r,setCurrentFilters:l,availableFields:o,isLoading:i,addCondition:c,addGroup:x,removeCondition:h,removeGroup:v,updateCondition:p,updateConditionFields:m,updateGroupOperator:g,updateGroupNegate:S,reorderConditions:f,reorderGroups:N,generateSQLPreview:A,hasAnyFilters:B}}function ai({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 li({value:s,onValueChange:a,availableFields:r,placeholder:l="Select field",className:u="w-64"}){const[i,o]=C.useState(!1),d=C.useMemo(()=>{const c={};return r.forEach(x=>{const h=ri(x);c[h]||(c[h]={}),c[h][x.entityId]||(c[h][x.entityId]=[]),c[h][x.entityId].push(x)}),c},[r]);return e.jsxs(t.Popover,{modal:!0,open:i,onOpenChange:o,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(ai,{children:[s.entityName,".",s.name]})}):l,e.jsx(On.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(d).map(([c,x])=>e.jsx(n.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Database,{className:"h-3 w-3"}),c]}),children:Object.entries(x).map(([h,v])=>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(v[0].entityType,{size:"h-3 w-3"}),e.jsx("span",{children:v[0].entityName})]}),v.map((p,m)=>e.jsxs(n.CommandItem,{value:p.id,onSelect:()=>{a(p),o(!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))]},`${c}-${h}`))},c))})]})})]})}function Is(s){var S;const a=t.useEditorStore(f=>f.card),{authToken:r,tokenProps:l}=n.useSemaphorContext(),u=t.useEditorStore(f=>f.card.config),i=u==null?void 0:u.joinPlan,o={...s,alias:s.name,label:"value",role:"groupby"},d={...s,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},c={...o,role:"sortby",direction:"asc"},x={joinPlan:i,groupByColumns:[o],metricColumns:[d],sortByColumns:[c]},h=((S=a.dataSource)==null?void 0:S.connectionId)||a.connectionId,{data:v,isPending:p,error:m}=n.useQuery({queryKey:["filterValues",s.entityId,s.name,s.qualifiedEntityName],queryFn:async()=>{try{return await t.postRequestRegular(`${l.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",{connection_id:h,cardConfig:x,cardDataSource:a.dataSource})}catch(f){console.log(s),console.error("error",f)}},enabled:!!h,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((v==null?void 0:v.records)||[]).map(f=>({label:f.value||"BLANK",value:f.value||"BLANK",count:(f==null?void 0:f.count)||0})),isPending:p,error:m}}function oi({field:s,selected:a,onChange:r,placeholder:l="Select items...",className:u}){const[i,o]=Da.useState(!1),{filterValues:d}=Is(s),c=h=>{r(a.filter(v=>v!==h))},x=h=>{a.includes(h)?r(a.filter(v=>v!==h)):r([...a,h])};return e.jsx("div",{className:t.cn("w-full",u),children:e.jsxs(t.Popover,{open:i,onOpenChange:o,modal:!0,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(h=>{const v=d.find(p=>p.value===h);return e.jsxs(n.Badge,{variant:"secondary",className:"text-xs",children:[v==null?void 0:v.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"&&c(h)},onMouseDown:p=>{p.preventDefault(),p.stopPropagation()},onClick:p=>{p.stopPropagation(),c(h)},children:e.jsx(t.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},h)}):e.jsx("span",{className:"text-muted-foreground",children:l})}),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:d.map((h,v)=>e.jsxs(n.CommandItem,{onSelect:()=>x(h.value),children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",a.includes(h.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:h.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:h.count})]})]},h.value+v))})]})]})})]})})}function ii({field:s,value:a,onChange:r,placeholder:l="Select value...",className:u}){const{filterValues:i,isPending:o,error:d}=Is(s);return o?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(t.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):d?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(t.Select,{value:a,onValueChange:r,children:[e.jsx(t.SelectTrigger,{className:u||"flex-1",children:e.jsx(t.SelectValue,{placeholder:l,children:a})}),e.jsx(t.SelectContent,{children:i.map((c,x)=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:c.value,children:c.label},c.value+x))})]})}function ci({value:s,operator:a,onChange:r,className:l}){var m,g,S;const{tokenProps:u}=n.useSemaphorContext(),i=((g=(m=u==null?void 0:u.params)==null?void 0:m.calendarContext)==null?void 0:g.tz)||((S=u==null?void 0:u.params)==null?void 0:S.timezone),o=i||Intl.DateTimeFormat().resolvedOptions().timeZone,d=a==="between"||a==="not between",c=C.useMemo(()=>{if(!(!s||!d)&&Array.isArray(s)&&s.length===2){const f=s[0]?new Date(s[0]):void 0,N=s[1]?new Date(s[1]):void 0;if(f&&N)return{from:f,to:N}}},[s,d]),x=C.useMemo(()=>{if(!s||d)return;const f=Array.isArray(s)?s[0]:s;if(!f)return;const N=new Date(f);if(!isNaN(N.getTime()))return N},[s,d]),h=f=>a==="<="||a===">"?t.endOfDayInTimezone(f,o):t.startOfDayInTimezone(f,o),v=f=>{if(!f){r([]);return}if(f.from&&f.to){r([f.from.toISOString(),f.to.toISOString()]);return}r([])},p=f=>{if(!f){r("");return}const N=h(f);r(N.toISOString())};return e.jsx(n.DateRangePicker,{value:d?c:void 0,selectionMode:d?"range":"single",singleValue:d?void 0:x,onChange:v,onSingleChange:p,timezone:i,showRelativeTab:d,className:l,placeholder:"Select date..."})}const Ds=["contains","startsWith","endsWith","like","not like"],di=["=","!=",">",">=","<","<=",...Ds,"in","not in","isNull","isNotNull"],ui=["=","!=",...Ds,"in","not in","isNull","isNotNull"],mi=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],xi=["=","!=","isNull","isNotNull"],hi=["between","=","!=","<","<=",">",">=","isNull","isNotNull"],pi={"=":"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 Rn(s){return pi[s]||t.titleCase(s)}function fi(s){switch(s){case"string":return ui;case"number":return mi;case"boolean":return xi;case"date":return hi;default:return di}}function aa({condition:s,index:a,groupId:r,groupLogicalOperator:l,onUpdateCondition:u,onRemoveCondition:i,onUpdateGroupOperator:o,availableFields:d,updateConditionFields:c}){const{attributes:x,listeners:h,setNodeRef:v,transform:p,transition:m,isDragging:g}=n.useSortable({id:s.id}),{isPending:S,error:f}=Is(s.field),N={transform:n.CSS.Transform.toString(p),transition:m};return e.jsxs("div",{ref:v,style:N,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${g?"z-50 opacity-50":""}`,children:[e.jsx("div",{...x,...h,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:l,onValueChange:A=>o(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(li,{value:s.field,onValueChange:A=>{const B=A,w=t.getDataType(B.dataType)==="date";c(r,s.id,{field:B,value:"",operator:w?"between":"="})},availableFields:d,placeholder:"Select field",className:"w-64"}),e.jsxs(t.Select,{value:s.operator,onValueChange:A=>{A==="in"||A==="not in"?c(r,s.id,{operator:A,value:[]}):A==="isNull"||A==="isNotNull"?c(r,s.id,{operator:A,value:null}):A==="between"||A==="not between"?c(r,s.id,{operator:A,value:[]}):c(r,s.id,{operator:A,value:""})},children:[e.jsx(t.SelectTrigger,{className:"w-32",children:e.jsx(t.SelectValue,{children:s.operator?Rn(s.operator):""})}),e.jsx(t.SelectContent,{children:fi(t.getDataType(s.field.dataType)).map(A=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:A,children:Rn(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"?S?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(t.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):f?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(oi,{field:s.field,selected:Array.isArray(s.value)&&s.value.every(A=>typeof A=="string")?s.value:[],onChange:A=>c(r,s.id,{value:A}),placeholder:`Select values for ${s.operator}...`,className:"flex-1"}):Ds.includes(s.operator)?e.jsx(t.Input,{value:typeof s.value=="string"?s.value:"",onChange:A=>c(r,s.id,{value:A.target.value}),className:"flex-1",placeholder:s.operator.charAt(0).toUpperCase()+s.operator.slice(1)+"..."}):e.jsx(ii,{field:s.field,value:typeof s.value=="string"?s.value:"",onChange:A=>c(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=>c(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(ci,{value:s.value,operator:s.operator,onChange:A=>c(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 gi({group:s,depth:a,parentGroupId:r,onUpdateGroupOperator:l,onUpdateGroupNegate:u,onRemoveGroup:i,onUpdateCondition:o,onUpdateField:d,onRemoveCondition:c,onReorderConditions:x,onReorderGroups:h,onAddCondition:v,onAddGroup:p,availableFields:m,renderFilterGroup:g,updateConditionFields:S}){const{attributes:f,listeners:N,setNodeRef:A,transform:B,transition:w,isDragging:I}=n.useSortable({id:s.id}),D={transform:n.CSS.Transform.toString(B),transition:w},E=M=>{const{active:b,over:R}=M;if(R&&b.id!==R.id){const k=s.conditions.findIndex(O=>O.id===b.id),F=s.conditions.findIndex(O=>O.id===R.id);k!==-1&&F!==-1&&x(s.id,k,F)}},y=M=>{const{active:b,over:R}=M;if(R&&b.id!==R.id&&r){const k=s.groups.findIndex(O=>O.id===b.id),F=s.groups.findIndex(O=>O.id===R.id);k!==-1&&F!==-1&&h(r,k,F)}};return e.jsxs("div",{ref:A,style:D,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${I?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...f,...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:M=>l(s.id,M),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>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(M=>M.id),strategy:n.verticalListSortingStrategy,children:s.conditions.map((M,b)=>e.jsx(aa,{condition:M,index:b,groupId:s.id,groupLogicalOperator:s.logicalOperator,onUpdateCondition:o,onUpdateField:d,onRemoveCondition:c,onUpdateGroupOperator:l,availableFields:m,updateConditionFields:S},M.id))})}),e.jsx(n.DndContext,{sensors:n.useSensors(n.useSensor(n.PointerSensor),n.useSensor(n.KeyboardSensor,{coordinateGetter:n.sortableKeyboardCoordinates})),collisionDetection:n.closestCenter,onDragEnd:y,children:e.jsx(n.SortableContext,{items:s.groups.map(M=>M.id),strategy:n.verticalListSortingStrategy,children:s.groups.map(M=>g(M,a+1,s.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(t.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>v(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 bi({filters:s,availableFields:a,onSave:r,onClearAll:l,onCancel:u}){const{currentFilters:i,availableFields:o,isLoading:d,addCondition:c,addGroup:x,removeCondition:h,removeGroup:v,updateCondition:p,updateConditionFields:m,updateGroupOperator:g,updateGroupNegate:S,reorderConditions:f,reorderGroups:N,generateSQLPreview:A,hasAnyFilters:B,setCurrentFilters:w}=ni({initialFilters:s,availableFields:a}),I=n.useSensors(n.useSensor(n.PointerSensor),n.useSensor(n.KeyboardSensor,{coordinateGetter:n.sortableKeyboardCoordinates})),[D,E]=C.useState(!1),y=(R,k,F)=>{const O=j=>j.id===R?{...j,conditions:j.conditions.map(T=>T.id===k?{...T,field:F,dataType:F.dataType}:T)}:{...j,groups:j.groups.map(O)};w(O(i))},M=(R,k=0,F)=>k===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(n.DndContext,{sensors:I,collisionDetection:n.closestCenter,onDragEnd:O=>{const{active:j,over:T}=O;if(T&&j.id!==T.id){const L=R.conditions.findIndex(z=>z.id===j.id),V=R.conditions.findIndex(z=>z.id===T.id);L!==-1&&V!==-1&&f(R.id,L,V)}},children:e.jsx(n.SortableContext,{items:R.conditions.map(O=>O.id),strategy:n.verticalListSortingStrategy,children:R.conditions.map((O,j)=>e.jsx(aa,{condition:O,index:j,groupId:R.id,groupLogicalOperator:R.logicalOperator,onUpdateCondition:p,onUpdateField:y,onRemoveCondition:h,onUpdateGroupOperator:g,availableFields:o,updateConditionFields:m},O.id))})}),e.jsx(n.DndContext,{sensors:I,collisionDetection:n.closestCenter,onDragEnd:O=>{const{active:j,over:T}=O;if(T&&j.id!==T.id){const L=R.groups.findIndex(z=>z.id===j.id),V=R.groups.findIndex(z=>z.id===T.id);L!==-1&&V!==-1&&N(R.id,L,V)}},children:e.jsx(n.SortableContext,{items:R.groups.map(O=>O.id),strategy:n.verticalListSortingStrategy,children:R.groups.map(O=>M(O,k+1,R.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(t.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>c(R.id),children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),D&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>x(R.id),children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},R.id):e.jsx(gi,{group:R,depth:k,parentGroupId:F,onUpdateGroupOperator:g,onUpdateGroupNegate:S,onRemoveGroup:v,onUpdateCondition:p,onUpdateField:y,onRemoveCondition:h,onReorderConditions:f,onReorderGroups:N,onAddCondition:c,onAddGroup:x,availableFields:o,renderFilterGroup:M,updateConditionFields:m},R.id),b=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:[d?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):M(i),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Switch,{size:"sm",id:"advanced-mode",checked:D,onCheckedChange:R=>E(R)}),e.jsx(t.Label,{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),B&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:A(i)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(t.Button,{size:"sm",variant:"outline",onClick:u,children:"Cancel"}),b>0&&e.jsx(t.Button,{variant:"outline",size:"sm",onClick:l,children:"Clear All"}),e.jsx(t.Button,{size:"sm",onClick:()=>r(B?i:null),children:"Apply Filters"})]})]})}function ji({cardId:s,filters:a,onFiltersChange:r,onClearFilters:l,availableFields:u,isOpen:i,onOpenChange:o}){const d=x=>{r(s,x),o(!1)},c=()=>{l(s),o(!1)};return e.jsxs(n.Dialog,{modal:!1,open:i,onOpenChange:o,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:x=>{x.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(bi,{filters:a,availableFields:u,onSave:d,onCancel:()=>o(!1),onClearAll:c})]})]})}function vi({activeCardId:s,sourceFields:a,getFieldsForContainer:r,setFieldsForContainer:l}){var A,B;const[u,i]=C.useState(null),o=t.useEditorStore(w=>w.card),d=t.useEditorStore(w=>w.actions.updateCardConfig),c=t.useEditorStore(w=>w.actions.setCardPreferences),x=(A=o==null?void 0:o.config)==null?void 0:A.joinPlan,h=C.useCallback(w=>w.entityName===Ea.CALCULATED_FIELD_ENTITY_MARKER||w.entityName==="calculated_fields"||w.qualifiedEntityName==="calculated_fields",[]),v=(B=o==null?void 0:o.dataSource)==null?void 0:B.semanticDomainId,{data:p}=n.useJoinabilityMap(v),m=[...a,...r("groupBy"),...r("pivotBy"),...r("metrics"),...r("sortBy"),...r("detailColumns")],g=C.useCallback(w=>w.startsWith("card-source-")?"source":w.startsWith("card-")?null:w.startsWith("source-")||a.find(I=>I.id===w)?"source":r("groupBy").find(I=>I.id===w)?"groupBy":r("metrics").find(I=>I.id===w)?"metrics":r("pivotBy").find(I=>I.id===w)?"pivotBy":r("sortBy").find(I=>I.id===w)?"sortBy":r("detailColumns").find(I=>I.id===w)?"detailColumns":null,[a,r]),S=C.useCallback(w=>{i(w.active.id)},[]),f=C.useCallback(w=>{var R;const{active:I,over:D}=w;if(!D||!s){i(null);return}const E=I.id,y=D.id,M=g(E),b=g(y)||y;if(b==="sortBy"){if(M==="source"){const k=a.find(O=>O.id===E);if(!k){i(null);return}if(!(r("groupBy").some(O=>O.name===k.name&&O.qualifiedEntityName===k.qualifiedEntityName)||r("metrics").some(O=>O.name===k.name&&O.qualifiedEntityName===k.qualifiedEntityName)||r("detailColumns").some(O=>O.name===k.name&&O.qualifiedEntityName===k.qualifiedEntityName))){i(null);return}}else if(M==="pivotBy"){i(null);return}else if(M!=="groupBy"&&M!=="metrics"&&M!=="sortBy"&&M!=="detailColumns"){i(null);return}}if(M==="source"&&b==="sortBy"){const k=[...a].find(T=>T.id===E);if(!k){i(null);return}const F=r("sortBy");if(n.fieldAlreadyExists(k,F)){i(null);return}const O=n.validateFieldForChartType(k,"sortBy",o.type);if(!O.isValid){n.ue.error("Invalid Field Type",{description:O.reason,position:"top-center",duration:3e3}),i(null);return}const j=n.getNewField(k,"sortBy",F);i(null),l("sortBy",[...F,j]);return}if(M==="source"&&b!=="source"&&b!=="sortBy"){const k=[...a].find(z=>z.id===E);if(!k){i(null);return}const F=[...r("groupBy"),...r("pivotBy"),...r("metrics"),...r("sortBy"),...r("detailColumns")],O=F.filter(z=>!h(z));if(O.length>0){const z=O[0].qualifiedEntityName;if(!z){i(null);return}if(z!==k.qualifiedEntityName&&!h(k)&&k.qualifiedEntityName)if(v&&(p!=null&&p.joinabilityMap)){if(n.calculateFieldState(k,{joinabilityMap:p.joinabilityMap,selectedFields:F,baseEntityName:(R=x==null?void 0:x.baseEntity)==null?void 0:R.name}).state==="unreachable"){n.showJoinRequiredNotification(),i(null);return}}else{if(!x){n.showJoinRequiredNotification(),i(null);return}if(!n.areEntitiesJoined(z,k.qualifiedEntityName,x)){n.showJoinRequiredNotification(),i(null);return}}}const j=r(b);if(n.fieldAlreadyExists(k,j)){i(null);return}const T=n.validateFieldForChartType(k,b,o.type);if(!T.isValid){n.ue.error("Invalid Field Type",{description:T.reason,position:"top-center",duration:3e3}),i(null);return}const L=n.getNewField(k,b,j),V=[...j,L];if(i(null),l(b,V),b==="metrics"&&s){const z=n.seedSemanticMetricFormatDefaults(o,L,o.preferences);z&&c(z),n.cleanupKpiMetricComparisonMode(o.type,o.config,d,s,V)}return}if(M&&b&&M!=="source"&&b!=="source"&&M!==b){const k=r(M),F=r(b),O=k.find(z=>z.id===E);if(!O){i(null);return}const j=n.validateFieldForChartType(O,b,o.type);if(!j.isValid){n.ue.error("Invalid Field Type",{description:j.reason,position:"top-center",duration:3e3}),i(null);return}const T=n.getNewField(O,b,F);if(i(null),b==="sortBy"){n.fieldAlreadyExists(O,F)||l(b,[...F,T]);return}const L=k.filter(z=>z.id!==E),V=[...F,T];if(l(M,L),l(b,V),b==="metrics"&&s){const z=n.seedSemanticMetricFormatDefaults(o,T,o.preferences);z&&c(z),n.cleanupKpiMetricComparisonMode(o.type,o.config,d,s,V)}return}if(M&&b&&M===b&&M!=="source"){const k=r(M),F=k.findIndex(j=>j.id===E),O=k.findIndex(j=>j.id===y);if(F!==O){const j=n.arrayMove(k,F,O);l(M,j)}}i(null)},[s,a,r,l,g,x,v,p,h,o,d,c]),N=u?m.find(w=>w.id===u):null;return{activeId:u,activeField:N,handleDragStart:S,handleDragEnd:f}}function yi({activeView:s,onViewChange:a,splitViewEnabled:r}){const l=t.useEditorStore(c=>c.card),{config:u}=C.useContext(n.SemaphorContext).tokenProps,i=(u==null?void 0:u.showInfoTab)!==!1,o=()=>r?!1:t.getVisualizationMode(l)==="dynamic"?!0:!["table","pivotTable","aggregateTable","detailTable"].includes(l.type),d=[{id:"chart",label:"Chart"}];return o()&&d.push({id:"table",label:"Results"}),l.type!=="kpi"&&i&&d.push({id:"info",label:"Info",icon:t.Info}),e.jsx(t.Tabs,{value:s,onValueChange:c=>a(c),children:e.jsx(t.TabsList,{variant:"underline",className:"gap-5 border-b-0",children:d.map(c=>{const x=c.icon;return e.jsxs(t.TabsTrigger,{value:c.id,className:"gap-1.5 px-0 text-[13px]",children:[x&&e.jsx(x,{className:"h-3 w-3",strokeWidth:1.75}),c.label]},c.id)})})})}const Ci=[{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 Ni(){var c,x;const s=t.useEditorStore(h=>h.card),{updateRowLimit:a}=t.useEditorActions(),[r,l]=C.useState(!1),[u,i]=C.useState(""),o=h=>{if(h==="custom"){l(!0);return}l(!1),a(s.id,parseInt(h))},d=h=>{const v=h.target.value;i(v),v&&!isNaN(parseInt(v))&&a(s.id,parseInt(v))};return e.jsx("div",{className:"flex items-center gap-2",children:r?e.jsx(t.Input,{type:"number",value:u,onChange:d,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(t.Select,{value:((x=(c=s.config)==null?void 0:c.rowLimit)==null?void 0:x.toString())||"100",onValueChange:o,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:Ci.map(h=>e.jsx(t.SelectItem,{value:h.value,children:h.label},h.value))})]})})}function Si({card:s,queryData:a,isLoading:r,isFetching:l,pagination:u,onPaginationChange:i,onSortChange:o,sortState:d,splitViewEnabled:c,isDynamicInspectorOpen:x,onDynamicInspectorOpenChange:h}){const v=C.useMemo(()=>(a==null?void 0:a.records)||[],[a==null?void 0:a.records]),p=t.getVisualizationMode(s)==="dynamic",m=e.jsx(pt,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(Yn,{fallbackPreview:e.jsx(pt,{}),records:v,title:s.title,isInspectorOpen:x,onInspectorOpenChange:h})});return p?c?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||l)&&(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:v,totalsByColumnId:a==null?void 0:a.tableTotalsByColumnId,paginationMetadata:u,onPaginationChange:i,isLoading:r||l,onSortChange:o,sortState:d})]})})]}):m:!c||["table","pivotTable","aggregateTable","detailTable"].includes(s.type)?e.jsx(pt,{}):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(pt,{})}),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||l)&&(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:v,totalsByColumnId:a==null?void 0:a.tableTotalsByColumnId,paginationMetadata:u,onPaginationChange:i,isLoading:r||l,onSortChange:o,sortState:d})]})})]})}function wi(s,a){const[r,l]=C.useState(()=>{const u=localStorage.getItem(s);return u?JSON.parse(u):a});return C.useEffect(()=>{localStorage.setItem(s,JSON.stringify(r))},[r,s]),[r,l]}const Ti="semaphor-split-view-enabled";function Ei(){return wi(Ti,!0)}function Ii({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(ta,{cardType:a,queryResultColumns:r,focusSection:"style"})})]})]}):null}function Di({activeView:s,onViewChange:a,onFiltersClick:r,activeCard:l,columns:u}){var ke,Be,ze;const i=t.useEditorStore(ce=>ce.card),o=t.useEditorStore(ce=>ce.editorContext),d=t.useEditorStore(ce=>ce.inlineFilterValuesMap[(l==null?void 0:l.id)||""]),c=t.useEditorStore(ce=>ce.actions.removeCardInlineFilterValue),x=t.useDashboardStore(ce=>ce.filterValues),h=t.useDashboardStore(ce=>ce.selectedSheetId),{updateCardConfig:v,setCard:p,updateCardInFrame:m,setShowAIDialog:g}=t.useEditorActions(),S=t.useEditorStore(ce=>ce.showAIDialog),f=t.useEditorStore(ce=>ce.isDevMode),N=t.useDashboardStore(ce=>ce.isVisualEditing),[A,B]=C.useState(!1),[w,I]=C.useState(!1),[D,E]=C.useState(!1),[y,M]=C.useState(null),{config:b}=C.useContext(n.SemaphorContext).tokenProps,R=(b==null?void 0:b.showInfoTab)!==!1,k=(b==null?void 0:b.showQueryDebugTools)!==!1,[F,O]=Ei();t.useEditorStore(ce=>{var ve;return!!((ve=ce.card.customCardPreferences)!=null&&ve.url)});const T=t.getVisualizationMode(i)==="dynamic",L=(o==null?void 0:o.type)==="documentSection",V=Oe.useEffectiveEditorCardType(),{data:z,errorMessage:_,isLoading:P,isFetching:q,errorSql:G,pagination:Q,refetch:U,comparisonMetadata:J,queryRequestPayload:X,resolvedPrimaryDateField:se}=n.useEditorCardQuery(l),ue=C.useMemo(()=>(z==null?void 0:z.records)||[],[z==null?void 0:z.records]),pe=C.useMemo(()=>ue.length>0?Object.keys(ue[0]):[],[ue]),[xe,je]=C.useState(!1);C.useEffect(()=>{q||je(!1)},[q]);const Pe=()=>{const ce=!F;ce&&s==="table"&&a("chart"),O(ce)},Me=(ce,ve)=>{const ye={...l,paginationConfig:{page:ce+1,pageSize:ve}};p(ye),m(ye)},te=ce=>{if(!i.config)return;const ve=n.sortStateToSortByColumns(ce,i.config.metricColumns,i.config.groupByColumns,i.config.detailColumns);v(i.id,{...i.config,sortByColumns:ve})},fe=C.useMemo(()=>{var ce;return n.sortByColumnsToSortState((ce=i.config)==null?void 0:ce.sortByColumns)},[(ke=i.config)==null?void 0:ke.sortByColumns]);return e.jsx("div",{className:t.cn("relative flex w-0 grow flex-col",{"border-l":S&&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"&&S&&!L&&!T&&e.jsx("div",{className:"w-[200px]",children:e.jsx(Fr,{variant:f?"secondary":"ghost"})}),e.jsxs("div",{className:"flex h-11 items-end gap-5 self-stretch",children:[e.jsx(yi,{activeView:s,onViewChange:a,splitViewEnabled:F}),e.jsx(Ni,{})]}),J&&i.type!=="table"&&e.jsx(n.ComparisonMetadataBadge,{metadata:J,variant:"compact"}),S&&e.jsx(Oe.EditorClearButton,{})]}),e.jsxs("div",{className:"flex grow items-center justify-end gap-1",children:[e.jsx(n.FilterInfo,{cardId:l.id,cardFilters:(Be=l.config)==null?void 0:Be.filters,cardFilterCount:n.getFilterCount(((ze=l.config)==null?void 0:ze.filters)||null),onFiltersClick:r,inlineFilters:l.inlineFilters,inlineFilterValues:d,sheetId:h||"",removeInlineFilterValue:ce=>c(l.id,ce),resolvedPrimaryDateField:se}),e.jsx(n.IconButton,{tooltip:"Refresh",className:"h-7 w-7 rounded-[5px] p-0",disabled:P||q,onClick:()=>{je(!0),U()},children:e.jsx(n.RefreshCcw,{className:t.cn("h-3.5 w-3.5",{"animate-spin":xe})})}),s==="chart"&&e.jsx(Ii,{card:l,effectiveCardType:V,queryResultColumns:pe}),s==="chart"&&!T&&e.jsx(Wn,{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:Pe,children:[F?e.jsx(Fa,{className:"mr-2 h-4 w-4"}):e.jsx(Wa,{className:"mr-2 h-4 w-4"}),F?"Hide Results Table":"Show Results Table"]}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs("div",{className:"px-1 py-1",children:[e.jsx(ws,{triggerVariant:"menu",className:"w-full"}),e.jsx(Ts,{triggerVariant:"menu",className:"w-full"}),e.jsx(Ss,{triggerVariant:"menu",className:"w-full"})]}),e.jsx(Jn,{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(Si,{card:l,queryData:z,isLoading:P,isFetching:q,pagination:Q,onPaginationChange:Me,onSortChange:te,sortState:fe,splitViewEnabled:F,isDynamicInspectorOpen:D,onDynamicInspectorOpenChange:E})}),s==="table"&&(z==null?void 0:z.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:[(P||q)&&(z==null?void 0:z.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:l,data:ue,totalsByColumnId:z==null?void 0:z.tableTotalsByColumnId,comparisonMetadata:J,paginationMetadata:Q,onPaginationChange:Me,isLoading:P||q,onSortChange:te,sortState:fe})]}),s==="info"&&R&&e.jsx("div",{className:"flex min-h-0 flex-1 flex-col pb-2",children:e.jsx("div",{className:"flex min-h-0 flex-1 flex-col rounded-md bg-background px-4",children:_?e.jsx(Cs,{error:_,errorSql:G,onSendFeedback:()=>{const ce=n.prepareFeedbackData(n.FeedbackCategory.QUERY_GENERATION,{cardConfig:i.config,dataSource:l.dataSource,dashboardFilters:x,errorMessage:_,errorSql:G,generatedSql:z==null?void 0:z.sql});M(ce),I(!0)},onOpenInEditor:()=>{g(!0),setTimeout(()=>{const ce=t.useEditorStore.getState().actions;ce.setIsDevMode(!0),ce.setCardSql(G||""),setTimeout(()=>{ce.setRunSql(!0)},100)},100)}}):(z==null?void 0:z.sql)&&e.jsx(Xn,{sql:z.sql,showCardDetails:!0,debugPayloads:k?{queryRequest:X,queryResponse:z,columns:u,dashboardFilters:x}:void 0})})})]}),y&&e.jsx(n.FeedbackDialog,{open:w,onOpenChange:I,feedbackData:y})]})})}function ki({activeField:s}){const[a,r]=C.useState(!0);if(C.useEffect(()=>{s&&r(!0)},[s]),!s)return null;const l=!!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:l}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap",children:s.label||s.name})]})}const Ai=()=>{const s=console.error;console.error=(...l)=>{l.length>0&&typeof l[0]=="string"&&l[0].includes("ResizeObserver loop completed with undelivered notifications")||s.apply(console,l)};const a=l=>{if(l.message&&(l.message.includes("ResizeObserver loop completed with undelivered notifications")||l.message.includes("ResizeObserver loop limit exceeded")))return l.preventDefault(),l.stopPropagation(),!1},r=l=>{var u;if((u=l.reason)!=null&&u.message&&(l.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||l.reason.message.includes("ResizeObserver loop limit exceeded")))return l.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 Li({column:s,isSelected:a,onSelect:r,availableFields:l,width:u,onWidthChange:i}){var z,_,P;const o=t.useEditorStore(q=>q.card),{updateCardConfig:d,removeGroupByColumn:c,removeMetricColumn:x,updateFilters:h}=t.useEditorActions(),[v,p]=C.useState(!1),[m,g]=C.useState(!1),S=C.useRef(null),f=C.useCallback(q=>{q.preventDefault(),q.stopPropagation(),g(!0),S.current={startX:q.clientX,startWidth:u||150};const G=U=>{if(!S.current)return;const J=U.clientX-S.current.startX,X=Math.max(80,S.current.startWidth+J);i==null||i(s.id,X)},Q=()=>{g(!1),S.current=null,document.removeEventListener("mousemove",G),document.removeEventListener("mouseup",Q)};document.addEventListener("mousemove",G),document.addEventListener("mouseup",Q)},[u,s.id,i]),N=(z=o==null?void 0:o.config)==null?void 0:z.filters,A=(_=N==null?void 0:N.conditions)==null?void 0:_.some(q=>q.field.name===s.name&&q.field.qualifiedEntityName===s.qualifiedEntityName),B=q=>{q?h(o.id,q):d(o.id,{filters:void 0})},{attributes:w,listeners:I,setNodeRef:D,transform:E,transition:y,isDragging:M}=n.useSortable({id:s.id}),b={transform:n.CSS.Transform.toString(E),transition:y},R=t.getDataType(s.dataType),k=Mi(R),F=()=>{var Q;const q=((Q=o==null?void 0:o.config)==null?void 0:Q.sortByColumns)||[],G=q.findIndex(U=>U.name===s.name);if(G!==-1){const U=[...q];U[G]={...U[G],direction:"asc"},d(o.id,{sortByColumns:U})}else d(o.id,{sortByColumns:[...q,{...s,id:`sort-${s.id}`,role:"sortby",direction:"asc"}]})},O=()=>{var Q;const q=((Q=o==null?void 0:o.config)==null?void 0:Q.sortByColumns)||[],G=q.findIndex(U=>U.name===s.name);if(G!==-1){const U=[...q];U[G]={...U[G],direction:"desc"},d(o.id,{sortByColumns:U})}else d(o.id,{sortByColumns:[...q,{...s,id:`sort-${s.id}`,role:"sortby",direction:"desc"}]})},j=()=>{var Q;const q=((Q=o==null?void 0:o.config)==null?void 0:Q.groupByColumns)||[];if(!q.some(U=>U.name===s.name)){const U={...s,id:`groupby-${s.id}-${Date.now()}`,role:"groupby"};d(o.id,{groupByColumns:[...q,U]})}},T=q=>{var U;const G=((U=o==null?void 0:o.config)==null?void 0:U.metricColumns)||[];if(!G.some(J=>J.name===s.name&&J.aggregate===q)){const J={...s,id:`metric-${s.id}-${q}-${Date.now()}`,label:`${q} of ${s.label||s.name}`,role:"metric",aggregate:q};d(o.id,{metricColumns:[...G,J]})}},L=()=>{s.role==="groupby"?c(o.id,s.id):s.role==="metric"&&x(o.id,s.id)},V={...b,width:u?`${u}px`:void 0,minWidth:u?`${u}px`:"120px"};return e.jsxs("th",{ref:D,style:V,className:t.cn("group relative border-r border-border bg-background px-1 py-0",M&&"opacity-50",a&&"bg-primary/10",m&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...w,...I,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(k,{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:F,children:[e.jsx(Aa,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(n.DropdownMenuItem,{onClick:O,children:[e.jsx(ka,{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:()=>T("SUM"),children:"Sum"}),e.jsx(n.DropdownMenuItem,{onClick:()=>T("AVG"),children:"Average"}),e.jsx(n.DropdownMenuItem,{onClick:()=>T("COUNT"),children:"Count"}),e.jsx(n.DropdownMenuItem,{onClick:()=>T("DISTINCT"),children:"Count Distinct"}),e.jsx(n.DropdownMenuItem,{onClick:()=>T("MIN"),children:"Min"}),e.jsx(n.DropdownMenuItem,{onClick:()=>T("MAX"),children:"Max"})]})]}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuItem,{onClick:j,children:[e.jsx(Zt,{className:"mr-2 h-4 w-4"}),"Group by this column"]}),e.jsxs(n.DropdownMenuItem,{disabled:!0,children:[e.jsx(ys,{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:L,className:"text-destructive focus:text-destructive",children:[e.jsx(n.Trash2,{className:"mr-2 h-4 w-4"}),"Remove column"]})]})]})]}),e.jsx("div",{onMouseDown:f,className:t.cn("absolute right-0 top-0 h-full w-1 cursor-col-resize bg-transparent hover:bg-primary/50",m&&"bg-primary")}),e.jsx(na,{open:v,onOpenChange:p,availableFields:l.length>0?l:[s],existingFilters:N,editingCondition:A?(P=N==null?void 0:N.conditions)==null?void 0:P.find(q=>q.field.name===s.name&&q.field.qualifiedEntityName===s.qualifiedEntityName):void 0,onSave:B})]})}function Mi(s){switch(s){case"number":return n.Hash;case"date":return n.Calendar;case"string":default:return t.Type}}function Fi({selectedColumn:s,onColumnSelect:a,isLoading:r=!1,sourceFields:l=[],filterableFields:u=l}){var M,b,R,k;const i=t.useEditorStore(F=>F.card),{updateCardConfig:o}=t.useEditorActions(),[d,c]=C.useState(null),[x,h]=C.useState({}),[v,p]=C.useState(!1),m=C.useMemo(()=>{var j,T;const F=((j=i==null?void 0:i.config)==null?void 0:j.groupByColumns)||[],O=((T=i==null?void 0:i.config)==null?void 0:T.metricColumns)||[];return[...F,...O]},[(M=i==null?void 0:i.config)==null?void 0:M.groupByColumns,(b=i==null?void 0:i.config)==null?void 0:b.metricColumns]),g=C.useMemo(()=>{const F=new Set(m.map(O=>`${O.qualifiedEntityName}.${O.name}`));return l.filter(O=>!F.has(`${O.qualifiedEntityName}.${O.name}`))},[l,m]),{data:S,isLoading:f}=n.useEditorCardQuery(i),N=(S==null?void 0:S.records)||[],A=C.useCallback((F,O)=>{h(j=>({...j,[F]:O}))},[]),B=C.useCallback(F=>{var L,V;const O=t.getDataType(F.dataType),j=((L=i==null?void 0:i.config)==null?void 0:L.groupByColumns)||[],T=((V=i==null?void 0:i.config)==null?void 0:V.metricColumns)||[];if(O==="number"){const z={...F,id:`metric-${F.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};o(i.id,{metricColumns:[...T,z]})}else{const z={...F,id:`groupby-${F.id}-${Date.now()}`,role:"groupby"};o(i.id,{groupByColumns:[...j,z]})}p(!1)},[(R=i==null?void 0:i.config)==null?void 0:R.groupByColumns,(k=i==null?void 0:i.config)==null?void 0:k.metricColumns,i.id,o]),w=n.useSensors(n.useSensor(n.PointerSensor,{activationConstraint:{distance:8}})),I=F=>{c(F.active.id)},D=F=>{const{active:O,over:j}=F;if(c(null),!j||O.id===j.id)return;const T=m.findIndex(V=>V.id===O.id),L=m.findIndex(V=>V.id===j.id);if(T!==-1&&L!==-1){const V=n.arrayMove(m,T,L),z=V.filter(P=>P.role==="groupby"),_=V.filter(P=>P.role==="metric");o(i.id,{groupByColumns:z,metricColumns:_})}},E=d?m.find(F=>F.id===d):null,y=F=>{let O="";for(;F>=0;)O=String.fromCharCode(F%26+65)+O,F=Math.floor(F/26)-1;return O};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:w,collisionDetection:n.closestCenter,onDragStart:I,onDragEnd:D,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(F=>F.id),strategy:n.horizontalListSortingStrategy,children:m.map((F,O)=>e.jsx("th",{style:{width:x[F.id]?`${x[F.id]}px`:void 0,minWidth:x[F.id]?`${x[F.id]}px`:"120px"},className:"border-r border-border bg-muted/30 px-2 py-1 text-center text-xs font-medium text-muted-foreground",children:y(O)},`letter-${F.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(F=>F.id),strategy:n.horizontalListSortingStrategy,children:m.map(F=>e.jsx(Li,{column:F,isSelected:(s==null?void 0:s.id)===F.id,onSelect:()=>a(F),availableFields:u,width:x[F.id],onWidthChange:A},F.id))}),e.jsx("th",{className:"w-10 border-r border-border bg-background px-1 py-2",children:e.jsxs(t.Popover,{open:v,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:g.map(F=>{const O=t.getDataType(F.dataType),j=O==="number"?n.Hash:O==="date"?n.Calendar:t.Type;return e.jsxs(n.CommandItem,{value:F.label||F.name,onSelect:()=>B(F),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:F.label||F.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:F.entityName})]})]},F.id)})})]})]})})]})})]})]}),e.jsx("tbody",{children:f?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((F,O)=>e.jsxs("tr",{className:t.cn("border-b border-border transition-colors hover:bg-muted/50",O%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:O+1}),m.map(j=>{const T=F[j.name]??F[j.label??""];return e.jsx("td",{style:{width:x[j.id]?`${x[j.id]}px`:void 0,minWidth:x[j.id]?`${x[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:Ri(T,j)})},`${O}-${j.id}`)}),e.jsx("td",{className:"w-10 border-r border-border"})]},O))})]}),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 Ri(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 Oi({entityGroups:s,isLoading:a=!1}){var B,w;const r=t.useEditorStore(I=>I.card),{updateCardConfig:l,removeGroupByColumn:u,removeMetricColumn:i}=t.useEditorActions(),[o,d]=C.useState(!0),[c,x]=C.useState(""),[h,v]=C.useState(new Set),p=((B=r==null?void 0:r.config)==null?void 0:B.groupByColumns)||[],m=((w=r==null?void 0:r.config)==null?void 0:w.metricColumns)||[],g=I=>{const D=new Set(h);D.has(I)?D.delete(I):D.add(I),v(D)},S=I=>p.some(D=>D.name===I.name&&D.qualifiedEntityName===I.qualifiedEntityName)||m.some(D=>D.name===I.name&&D.qualifiedEntityName===I.qualifiedEntityName),f=(I,D)=>{if(D)if(t.getDataType(I.dataType)==="number"){const y={...I,id:`metric-${I.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};l(r.id,{metricColumns:[...m,y]})}else{const y={...I,id:`groupby-${I.id}-${Date.now()}`,role:"groupby"};l(r.id,{groupByColumns:[...p,y]})}else{const E=p.findIndex(M=>M.name===I.name&&M.qualifiedEntityName===I.qualifiedEntityName),y=m.findIndex(M=>M.name===I.name&&M.qualifiedEntityName===I.qualifiedEntityName);E!==-1&&u(r.id,p[E].id),y!==-1&&i(r.id,m[y].id)}},N=I=>{if(!c)return I;const D=c.toLowerCase();return I.filter(E=>E.name.toLowerCase().includes(D)||E.label&&E.label.toLowerCase().includes(D))},A=I=>{switch(t.getDataType(I)){case"number":return n.Hash;case"date":return n.Calendar;default:return t.Type}};return o?e.jsxs("div",{className:"flex h-full w-72 flex-col border-l border-border bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border px-3 py-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Columns"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:()=>d(!1),title:"Close panel",children:e.jsx(qa,{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:c,onChange:I=>x(I.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(Zt,{className:"h-3.5 w-3.5 text-blue-500"}),e.jsx("span",{children:"Groupings"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:p.length})]}),e.jsx(n.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:p.map(I=>{const D=A(I.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(D,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:I.label||I.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,I.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]},I.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(I=>{const D=A(I.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(D,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:I.label||I.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:I.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,I.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]},I.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(I=>{const D=N(I.columns);if(D.length===0)return null;const E=h.has(I.entityId)||c.length>0;return e.jsxs(n.Collapsible,{open:E,onOpenChange:()=>g(I.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:I.label||I.entityName}),e.jsx("span",{className:"text-xs text-muted-foreground",children:D.length})]}),e.jsx(n.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:D.map(y=>{const M=A(y.dataType),b=S(y);return e.jsxs("label",{className:t.cn("flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-sm transition-colors hover:bg-muted/50",b&&"bg-primary/5"),children:[e.jsx(n.Checkbox,{checked:b,onCheckedChange:R=>f(y,R),className:"h-3.5 w-3.5"}),e.jsx(M,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:y.label||y.name})]},y.id)})})})]},I.entityId)})})})]}):e.jsx("div",{className:"flex h-full items-start border-l border-border bg-muted/30 p-2",children:e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>d(!0),title:"Open panel",children:e.jsx($a,{className:"h-4 w-4"})})})}const Pi=[{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 Bi({value:s,onChange:a,onSubmit:r,onCancel:l,selectedColumn:u,availableColumns:i}){const[o,d]=C.useState(!1),[c,x]=C.useState("column"),h=C.useRef(null);C.useEffect(()=>{const g=S=>{S.key==="Escape"&&s?l():S.key==="Enter"&&s&&!o&&r(s)};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[s,l,r,o]);const v=g=>{const S=`[${g.label||g.name}]`,f=h.current;if(f){const N=f.selectionStart||0,A=f.selectionEnd||0,B=s.slice(0,N)+S+s.slice(A);a(B),setTimeout(()=>{f.setSelectionRange(N+S.length,N+S.length),f.focus()},0)}else a(s+S);d(!1)},p=g=>{const S=h.current;if(S){const f=S.selectionStart||0,N=S.selectionEnd||0,A=s.slice(0,f)+g.syntax+s.slice(N);a(A),setTimeout(()=>{S.setSelectionRange(f+g.name.length+1,f+g.syntax.length-1),S.focus()},0)}else a(s+g.syntax);d(!1)},m=g=>{switch(t.getDataType(g)){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:o&&c==="function",onOpenChange:g=>{d(g),g&&x("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(Qa,{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:Pi.map(g=>e.jsx(n.CommandItem,{value:g.name,onSelect:()=>p(g),children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-sm font-medium",children:g.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:g.description})]}),e.jsx("span",{className:"font-mono text-xs text-muted-foreground/75",children:g.syntax})]})},g.name))})]})]})})]}),e.jsxs(t.Popover,{open:o&&c==="column",onOpenChange:g=>{d(g),g&&x("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(g=>{const S=m(g.dataType);return e.jsxs(n.CommandItem,{value:g.label||g.name,onSelect:()=>v(g),children:[e.jsx(S,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:g.label||g.name})]},g.id)})})]})]})})]}),e.jsx("div",{className:"relative flex-1",children:e.jsx(t.Input,{ref:h,value:s,onChange:g=>a(g.target.value),placeholder:"Enter a formula or select a column...",className:"h-7 border-border bg-background font-mono text-sm"})}),s&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-destructive hover:bg-destructive/10 hover:text-destructive",onClick:l,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 Vi({className:s}){var m,g,S,f;const a=t.useEditorStore(N=>N.card),[r,l]=C.useState(null),[u,i]=C.useState(""),{columns:o=[],columnGroups:d=[],isLoading:c}=n.useColumns(),{valuePickFilterableFields:x=[]}=n.useFilterableFields();(m=a==null?void 0:a.config)!=null&&m.groupByColumns,(g=a==null?void 0:a.config)!=null&&g.metricColumns,(S=a==null?void 0:a.config)!=null&&S.groupByColumns,(f=a==null?void 0:a.config)!=null&&f.pivotByColumns;const h=N=>{l(N),i(N?`[${N.label||N.name}]`:"")},v=N=>{console.log("Formula submitted:",N),i(""),l(null)},p=()=>{i(""),l(null)};return e.jsxs("div",{className:t.cn("flex h-full w-full flex-col",s),children:[e.jsx(Bi,{value:u,onChange:i,onSubmit:v,onCancel:p,selectedColumn:r,availableColumns:o}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(Fi,{selectedColumn:r,onColumnSelect:h,isLoading:c,sourceFields:o,filterableFields:x})}),e.jsx(Oi,{entityGroups:d,isLoading:c})]})]})}function _i(){var z,_;const[s,a]=C.useState("chart"),[r,l]=C.useState(!1),[u,i]=C.useState(!0),[o,d]=C.useState(!0),c=t.useEditorStore(P=>P.showAIDialog),x=t.useDashboardStore(P=>P.isVisualEditing),{setCardType:h}=t.useEditorActions(),v=t.useEditorStore(P=>P.card.type);C.useEffect(()=>Ai(),[]);const p=P=>{h(P)},m=t.useEditorStore(P=>P.frame),g=t.useEditorStore(P=>P.card);t.useEditorStore(P=>P.activeTabCardId),t.useEditorStore(P=>P.actions.getAvailableFields);const{addCard:S,removeCard:f,updateCard:N,setActiveCard:A,updateFilters:B}=t.useEditorActions(),{columnFields:w=[],scopedFields:I=[],filterableFields:D=[]}=n.useFilterableFields(),E=n.useSensors(n.useSensor(n.PointerSensor,{activationConstraint:{distance:8}})),y=g,{getFieldsForContainer:M,setFieldsForContainer:b}=n.useFieldManagement(y),{activeField:R,handleDragStart:k,handleDragEnd:F}=vi({activeCardId:m.activeCardId,sourceFields:I,getFieldsForContainer:M,setFieldsForContainer:b}),O=(P,q)=>{q&&B(P,q)},j=P=>{var q;N(P,{config:{...(q=m.cards.find(G=>G.id===P))==null?void 0:q.config,filters:void 0}})},T=D,L=P=>{if(!P)return 0;let q=P.conditions.length;return P.groups.forEach(G=>{q+=L(G)}),q},V=L(((z=y==null?void 0:y.config)==null?void 0:z.filters)||null);return e.jsxs(n.DndContext,{sensors:E,collisionDetection:n.closestCenter,onDragStart:k,onDragEnd:F,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(zn,{isVisible:u,onToggleVisibility:()=>i(!u)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:v==="tableBuilder"?e.jsx(Vi,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!c&&e.jsx(si,{selectedChart:v,onChartChange:p,groupByFields:M("groupBy"),pivotByFields:M("pivotBy"),metricsFields:M("metrics"),sortByFields:M("sortBy"),detailFields:M("detailColumns"),activeField:R,isVisible:o,onToggleVisibility:()=>d(!o)}),e.jsx(Di,{selectedChart:v,activeView:s,onViewChange:a,onFiltersClick:()=>l(!0),filterCount:V,activeCard:y,columns:w,getFieldsForContainer:M,cards:m.cards,activeCardId:m.activeCardId,addCard:S,setActiveCard:A})]})}),!u&&x&&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"})})})]}),y&&e.jsx(ji,{cardId:y.id,filters:((_=y.config)==null?void 0:_.filters)||null,onFiltersChange:O,onClearFilters:j,availableFields:T,isOpen:r,onOpenChange:l}),e.jsx(n.DragOverlay,{dropAnimation:null,children:e.jsx(ki,{activeField:R||null})})]})}function zi({authToken:s,onSave:a,onClose:r}){const l=C.useRef(null),u=t.useEditorStore(E=>E.showAIDialog),i=t.useEditorStore(E=>E.isDevMode),o=n.useAssistantLayoutStore(E=>E.setFullscreen),d=n.useAssistantLayoutStore(E=>E.setPanelOpen),c=n.useAssistantLayoutStore(E=>E.setContainer),x=n.useAssistantPanel("editor"),h=n.useFullscreenAssistant(),v=n.useAssistantContainer("editor"),p=h==="editor",m=n.useDashboardAppearance(),g=C.useCallback(E=>{c("editor",E)},[c]),{setAuthToken:S}=t.useDashboardActions(),{setShowAIDialog:f,setOnSave:N,setOnClose:A}=t.useEditorActions(),{setActiveAssistantType:B}=t.useAIActions();C.useEffect(()=>{a&&N(a),r&&A(r)},[a,N,r,A]),C.useEffect(()=>{s&&s.accessToken&&S(s)},[s,S]),C.useEffect(()=>{var E,y;u?((E=l.current)==null||E.resize(40),d("editor",!0),B("editor")):((y=l.current)==null||y.resize(0),d("editor",!1),h==="editor"&&o(null),B(null))},[u,d,B,o,h]);function w(E){var y;E<1?(f(!1),d("editor",!1),h==="editor"&&o(null),B(null),(y=l.current)==null||y.resize(0)):(u||(f(!0),B("editor")),x.isOpen||d("editor",!0))}function I(){return e.jsxs(e.Fragment,{children:[e.jsx(zn,{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(Lo,{})}),e.jsx(n.ResizableHandle,{disabled:!u}),e.jsx(n.ResizablePanel,{"data-role":"editor-assistant-panel",ref:l,onResize:w,defaultSize:x.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Mn,{isFullscreen:p,onFullscreenChange:E=>o(E?"editor":null),fullscreenContainer:v})})})]}),e.jsx("div",{ref:g,className:t.cn("absolute inset-0",!p&&"pointer-events-none")})]})]})}function D(){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(_i,{})}),e.jsx(n.ResizableHandle,{disabled:!u}),e.jsx(n.ResizablePanel,{"data-role":"editor-assistant-panel",ref:l,onResize:w,defaultSize:x.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Mn,{isFullscreen:p,onFullscreenChange:E=>o(E?"editor":null),fullscreenContainer:v})})})]}),e.jsx("div",{ref:g,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:I()}):e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",style:m.dashboardContainerStyle,children:D()})})}function qi(){t.useDashboardStore(m=>m.selectedCardId);const s=t.useDashboardStore(m=>m.selectedSheetId),a=t.useDashboardStore(m=>m.dashboard),{setIsVisualEditing:r,setSelectedSheetId:l}=t.useDashboardStore(m=>m.actions),u=t.useEditorStore(m=>m.editorContext),{clearEditorContext:i}=t.useEditorStore(m=>m.actions),o=n.useDashboardAppearance(),d=t.useDashboardStore(m=>m.isVisualEditing),c=t.useDashboardStore(m=>m.actions.updateFrame),x=t.useDashboardStore(m=>m.actions.updateDocumentSectionCard),h=n.useResolveExistingFrameSemanticExecutionPayload();async function v(m){var A,B,w;if((u==null?void 0:u.type)==="documentSection"){const I=n.getDocumentSectionEditorCard(m,u.cardId);if(!I){n.ue.error("No document section card found");return}if(!n.isSupportedDocumentTableCardType(I)){n.ue.error("Document table sections support Table and Pivot Table");return}x(u.sheetId,u.sectionId,I,{calculatedFields:m.calculatedFields}),i(),r(!1);return}const g=s?(A=a==null?void 0:a.sheets)==null?void 0:A.some(I=>{var D;return I.id===s&&((D=I.frames)==null?void 0:D.some(E=>E.id===m.id))}):!1,S=(w=(B=a==null?void 0:a.sheets)==null?void 0:B.find(I=>{var D;return(D=I.frames)==null?void 0:D.some(E=>E.id===m.id)}))==null?void 0:w.id,f=g?s:S||null;if(!f)return;const N=n.findDashboardFrameById(a,m.id);try{const I=await h(m,{previousFrame:N});c(f,m,{semanticExecutionPayload:I}),s!==f&&l(f),r(!1)}catch(I){console.error("Failed to resolve semantic metadata on save:",I),n.ue.error(I instanceof Error?I.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":!d}),style:o.dashboardContainerStyle,children:e.jsx(zi,{onSave:v,onClose:p})})}exports.default=qi;