react-semaphor 0.1.260 → 0.1.261

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/chunks/dashboard-controls-0hbftZxY.js +42 -0
  2. package/dist/chunks/dashboard-controls-BYi_r2lH.js +1971 -0
  3. package/dist/chunks/dashboard-filter-controls-button-BPCw1GMh.js +1066 -0
  4. package/dist/chunks/dashboard-filter-controls-button-f4pDkDUL.js +11 -0
  5. package/dist/chunks/{dashboard-json-U7VmojaR.js → dashboard-json-2NJCXsDD.js} +1 -1
  6. package/dist/chunks/{dashboard-json-BUrApiYl.js → dashboard-json-Dpy-zKf2.js} +1 -1
  7. package/dist/chunks/{dashboard-summary-settings-dialog-DlVBUQmC.js → dashboard-summary-settings-dialog-B9zRCvc-.js} +1 -1
  8. package/dist/chunks/{dashboard-summary-settings-dialog-CaxmCNyy.js → dashboard-summary-settings-dialog-Be3JilRI.js} +1 -1
  9. package/dist/chunks/edit-dashboard-visual-Bon08erH.js +188 -0
  10. package/dist/chunks/{edit-dashboard-visual-N2r5ObJ_.js → edit-dashboard-visual-CqTlmuYL.js} +5970 -5492
  11. package/dist/chunks/index-BoJEr_9F.js +1114 -0
  12. package/dist/chunks/{index-BNdZjo5d.js → index-C2c-_lPE.js} +48333 -44824
  13. package/dist/chunks/{normalize-dashboard-for-dirty-check-Bn27S0PN.js → normalize-dashboard-for-dirty-check-5KpZN8xr.js} +20 -19
  14. package/dist/chunks/normalize-dashboard-for-dirty-check-BXRUMVb2.js +1 -0
  15. package/dist/chunks/{resource-management-panel-C_ZqsVMH.js → resource-management-panel-BtLPW2b4.js} +1 -1
  16. package/dist/chunks/{resource-management-panel-zF23gLOJ.js → resource-management-panel-Bva2_0OU.js} +70 -70
  17. package/dist/chunks/use-create-flow-overlay-state-9X7GyUzl.js +21 -0
  18. package/dist/chunks/use-create-flow-overlay-state-Vyd5mSnf.js +1445 -0
  19. package/dist/chunks/{use-visual-utils-BBTQGDdB.js → use-visual-utils-Jv4hWSLm.js} +1 -1
  20. package/dist/chunks/{use-visual-utils-K1k39w2U.js → use-visual-utils-OPk_1t4I.js} +1 -1
  21. package/dist/dashboard/index.cjs +1 -1
  22. package/dist/dashboard/index.js +5 -4
  23. package/dist/index.cjs +1 -1
  24. package/dist/index.js +102 -99
  25. package/dist/shared/index.cjs +1 -1
  26. package/dist/shared/index.js +1 -1
  27. package/dist/style.css +1 -1
  28. package/dist/surfboard/index.cjs +1 -1
  29. package/dist/surfboard/index.js +5 -4
  30. package/dist/types/dashboard.d.ts +105 -0
  31. package/dist/types/index.cjs +1 -1
  32. package/dist/types/index.js +4 -3
  33. package/dist/types/main.d.ts +175 -1
  34. package/dist/types/shared.d.ts +89 -0
  35. package/dist/types/surfboard.d.ts +105 -0
  36. package/dist/types/types.d.ts +113 -0
  37. package/package.json +1 -1
  38. package/dist/chunks/dashboard-controls-CIdYp98a.js +0 -47
  39. package/dist/chunks/dashboard-controls-DOqBYrkB.js +0 -1847
  40. package/dist/chunks/edit-dashboard-visual-uA-0wLnR.js +0 -193
  41. package/dist/chunks/editor-action-buttons-B6lABkRB.js +0 -412
  42. package/dist/chunks/editor-action-buttons-Dh7Xndgk.js +0 -21
  43. package/dist/chunks/index-DOeggx0V.js +0 -1109
  44. package/dist/chunks/normalize-dashboard-for-dirty-check-B7NQDI1H.js +0 -1
  45. package/dist/chunks/notification-bell-BxyeaeRc.js +0 -839
  46. package/dist/chunks/notification-bell-tJRds5JJ.js +0 -6
@@ -0,0 +1,188 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),t=require("./index-BoJEr_9F.js"),N=require("react"),De=require("./use-create-flow-overlay-state-9X7GyUzl.js"),on=require("react-dom");function cn(s){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const a in s)if(a!=="default"){const r=Object.getOwnPropertyDescriptor(s,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:()=>s[a]})}}return n.default=s,Object.freeze(n)}const rs=cn(N);/**
2
+ * @license lucide-react v0.453.0 - ISC
3
+ *
4
+ * This source code is licensed under the ISC license.
5
+ * See the LICENSE file in the root directory of this source tree.
6
+ */const dn=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 un=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 Sa=t.createLucideIcon("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]);/**
17
+ * @license lucide-react v0.453.0 - ISC
18
+ *
19
+ * This source code is licensed under the ISC license.
20
+ * See the LICENSE file in the root directory of this source tree.
21
+ */const mn=t.createLucideIcon("Braces",[["path",{d:"M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1",key:"ezmyqa"}],["path",{d:"M16 21h1a2 2 0 0 0 2-2v-5c0-1.1.9-2 2-2a2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1",key:"e1hn23"}]]);/**
22
+ * @license lucide-react v0.453.0 - ISC
23
+ *
24
+ * This source code is licensed under the ISC license.
25
+ * See the LICENSE file in the root directory of this source tree.
26
+ */const is=t.createLucideIcon("Columns3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
27
+ * @license lucide-react v0.453.0 - ISC
28
+ *
29
+ * This source code is licensed under the ISC license.
30
+ * See the LICENSE file in the root directory of this source tree.
31
+ */const xn=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 wa=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 hn=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 pn=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 Ta=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 fn=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 gn=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 jn=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 Zs=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 bn=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 vn=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 Jt=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 Yt=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 yn=t.createLucideIcon("Palette",[["circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor",key:"1okk4w"}],["circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor",key:"f64h9f"}],["circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor",key:"fotxhn"}],["circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor",key:"qy21gx"}],["path",{d:"M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z",key:"12rzf8"}]]);/**
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 Nn=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 Cn=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 ea=t.createLucideIcon("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/**
112
+ * @license lucide-react v0.453.0 - ISC
113
+ *
114
+ * This source code is licensed under the ISC license.
115
+ * See the LICENSE file in the root directory of this source tree.
116
+ */const Vt=t.createLucideIcon("Rows3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M21 9H3",key:"1338ky"}],["path",{d:"M21 15H3",key:"9uk58r"}]]);/**
117
+ * @license lucide-react v0.453.0 - ISC
118
+ *
119
+ * This source code is licensed under the ISC license.
120
+ * See the LICENSE file in the root directory of this source tree.
121
+ */const Sn=t.createLucideIcon("SendHorizontal",[["path",{d:"M3.714 3.048a.498.498 0 0 0-.683.627l2.843 7.627a2 2 0 0 1 0 1.396l-2.842 7.627a.498.498 0 0 0 .682.627l18-8.5a.5.5 0 0 0 0-.904z",key:"117uat"}],["path",{d:"M6 12h16",key:"s4cdu5"}]]);/**
122
+ * @license lucide-react v0.453.0 - ISC
123
+ *
124
+ * This source code is licensed under the ISC license.
125
+ * See the LICENSE file in the root directory of this source tree.
126
+ */const wn=t.createLucideIcon("Shapes",[["path",{d:"M8.3 10a.7.7 0 0 1-.626-1.079L11.4 3a.7.7 0 0 1 1.198-.043L16.3 8.9a.7.7 0 0 1-.572 1.1Z",key:"1bo67w"}],["rect",{x:"3",y:"14",width:"7",height:"7",rx:"1",key:"1bkyp8"}],["circle",{cx:"17.5",cy:"17.5",r:"3.5",key:"w3z12y"}]]);/**
127
+ * @license lucide-react v0.453.0 - ISC
128
+ *
129
+ * This source code is licensed under the ISC license.
130
+ * See the LICENSE file in the root directory of this source tree.
131
+ */const Tn=t.createLucideIcon("Sigma",[["path",{d:"M18 7V5a1 1 0 0 0-1-1H6.5a.5.5 0 0 0-.4.8l4.5 6a2 2 0 0 1 0 2.4l-4.5 6a.5.5 0 0 0 .4.8H17a1 1 0 0 0 1-1v-2",key:"wuwx1p"}]]);/**
132
+ * @license lucide-react v0.453.0 - ISC
133
+ *
134
+ * This source code is licensed under the ISC license.
135
+ * See the LICENSE file in the root directory of this source tree.
136
+ */const En=t.createLucideIcon("Spline",[["circle",{cx:"19",cy:"5",r:"2",key:"mhkx31"}],["circle",{cx:"5",cy:"19",r:"2",key:"v8kfzx"}],["path",{d:"M5 17A12 12 0 0 1 17 5",key:"1okkup"}]]);/**
137
+ * @license lucide-react v0.453.0 - ISC
138
+ *
139
+ * This source code is licensed under the ISC license.
140
+ * See the LICENSE file in the root directory of this source tree.
141
+ */const In=t.createLucideIcon("SquareFunction",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["path",{d:"M9 17c2 0 2.8-1 2.8-2.8V10c0-2 1-3.3 3.2-3",key:"m1af9g"}],["path",{d:"M9 11.2h5.7",key:"3zgcl2"}]]);/**
142
+ * @license lucide-react v0.453.0 - ISC
143
+ *
144
+ * This source code is licensed under the ISC license.
145
+ * See the LICENSE file in the root directory of this source tree.
146
+ */const kn=t.createLucideIcon("SquareSplitVertical",[["path",{d:"M5 8V5c0-1 1-2 2-2h10c1 0 2 1 2 2v3",key:"1pi83i"}],["path",{d:"M19 16v3c0 1-1 2-2 2H7c-1 0-2-1-2-2v-3",key:"ido5k7"}],["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}]]);/**
147
+ * @license lucide-react v0.453.0 - ISC
148
+ *
149
+ * This source code is licensed under the ISC license.
150
+ * See the LICENSE file in the root directory of this source tree.
151
+ */const Dn=t.createLucideIcon("Tags",[["path",{d:"m15 5 6.3 6.3a2.4 2.4 0 0 1 0 3.4L17 19",key:"1cbfv1"}],["path",{d:"M9.586 5.586A2 2 0 0 0 8.172 5H3a1 1 0 0 0-1 1v5.172a2 2 0 0 0 .586 1.414L8.29 18.29a2.426 2.426 0 0 0 3.42 0l3.58-3.58a2.426 2.426 0 0 0 0-3.42z",key:"135mg7"}],["circle",{cx:"6.5",cy:"9.5",r:".5",fill:"currentColor",key:"5pm5xn"}]]);/**
152
+ * @license lucide-react v0.453.0 - ISC
153
+ *
154
+ * This source code is licensed under the ISC license.
155
+ * See the LICENSE file in the root directory of this source tree.
156
+ */const An=t.createLucideIcon("Wand",[["path",{d:"M15 4V2",key:"z1p9b7"}],["path",{d:"M15 16v-2",key:"px0unx"}],["path",{d:"M8 9h2",key:"1g203m"}],["path",{d:"M20 9h2",key:"19tzq7"}],["path",{d:"M17.8 11.8 19 13",key:"yihg8r"}],["path",{d:"M15 9h.01",key:"x1ddxp"}],["path",{d:"M17.8 6.2 19 5",key:"fd4us0"}],["path",{d:"m3 21 9-9",key:"1jfql5"}],["path",{d:"M12.2 6.2 11 5",key:"i3da3b"}]]);function Ea({storeValue:s,defaultValue:n="",onStoreUpdate:a,delay:r=300}){const[i,c]=N.useState(s??n),o=t.useDebounce(i,r),d=N.useRef(s),l=N.useRef(!1);N.useEffect(()=>{s!==d.current&&(c(s??n),d.current=s)},[s,n]),N.useEffect(()=>{l.current&&o!==d.current&&(a(o),d.current=o)},[o,a]);const m=N.useCallback(p=>{l.current=!0,c(p??n)},[n]);return{value:i,onChange:m}}function Mn({initialJoinPlan:s,availableDataSources:n}){const[a,r]=N.useState(s),[i,c]=N.useState(new Set),o=()=>{const T=a.joins.length>0?Math.max(...a.joins.map(S=>S.sequence))+1:1,A={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:T,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...a,joins:[...a.joins,A]}),c(new Set([...i,A.id]))},d=T=>{r({...a,joins:a.joins.filter(A=>A.id!==T)}),c(new Set([...i].filter(A=>A!==T)))},l=(T,A)=>{var f,O,F,b,L;const S=a.joins.find(C=>C.id===T);if(!S)return;const v={...S,...A};if((f=v.source)!=null&&f.name&&((O=v.target)!=null&&O.name)&&v.source.name===v.target.name){t.ue.error("Self-joins are not yet supported",{description:`Joining ${v.source.name} to itself is not currently supported. Please select a different target table.`});return}const k=a.joins.filter(C=>{var P;return C.id!==T&&C.target.name===((P=v.target)==null?void 0:P.name)});if((F=v.target)!=null&&F.name&&k.length>0){t.ue.error("Duplicate join targets are not supported",{description:`The table ${v.target.name} is already used as a target in another join. Each table can only be joined once.`});return}const M=a.joins.map(C=>C.id===T?v:C);if((b=v.source)!=null&&b.name&&((L=v.target)!=null&&L.name)&&v.joinKeyGroups[0].keys.length===0){const C=n.find(z=>{var _;return z.name===((_=v.source)==null?void 0:_.name)}),P=n.find(z=>{var _;return z.name===((_=v.target)==null?void 0:_.name)}),R={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(C==null?void 0:C.name)||"",entityName:(C==null?void 0:C.name)||"",entityType:(C==null?void 0:C.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(P==null?void 0:P.name)||"",entityName:(P==null?void 0:P.name)||"",entityType:(P==null?void 0:P.type)||"table"},operator:"="},B=[...v.joinKeyGroups];B[0]={...B[0],keys:[R]},v.joinKeyGroups=B,M[M.findIndex(z=>z.id===T)]=v}r({...a,joins:M})};return{joinPlan:a,expandedJoins:i,setJoinPlan:r,addJoin:o,removeJoin:d,updateJoin:l,moveJoinUp:T=>{const A=a.joins.findIndex(S=>S.id===T);if(A>0){const S=[...a.joins],v={...S[A]},k={...S[A-1]};S[A]=k,S[A-1]=v,S.forEach((f,O)=>{f.sequence=O+1});const M={...a,joins:S};r(M)}},moveJoinDown:T=>{const A=a.joins.findIndex(S=>S.id===T);if(A<a.joins.length-1){const S=[...a.joins],v={...S[A]},k={...S[A+1]};S[A]=k,S[A+1]=v,S.forEach((f,O)=>{f.sequence=O+1});const M={...a,joins:S};r(M)}},toggleJoinExpansion:T=>{const A=new Set(i);A.has(T)?A.delete(T):A.add(T),c(A)},getAvailableSourceEntities:T=>{if(a.joins.length===0)return n;const A=a.joins.findIndex(v=>v.id===T);if(A===0)return n.filter(v=>v.name===a.baseEntity.name);const S=new Set;return a.baseEntity.name&&S.add(a.baseEntity.name),a.joins.slice(0,A).forEach(v=>{S.add(v.source.name),S.add(v.target.name)}),n.filter(v=>S.has(v.name))},getAvailableTargetEntities:T=>n.filter(A=>A.name!==T),addJoinKeyGroup:T=>{const A=a.joins.find(v=>v.id===T);if(!A)return;const S=[...A.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];l(T,{joinKeyGroups:S})},updateGroupOperator:(T,A,S)=>{const v=a.joins.find(M=>M.id===T);if(!v)return;const k=[...v.joinKeyGroups];k[A]={...k[A],operator:S},l(T,{joinKeyGroups:k})},removeJoinKeyGroup:(T,A)=>{const S=a.joins.find(k=>k.id===T);if(!S)return;const v=[...S.joinKeyGroups];v.splice(A,1),l(T,{joinKeyGroups:v})},addJoinKey:(T,A)=>{const S=a.joins.find(O=>O.id===T);if(!S)return;const v=n.find(O=>O.name===S.source.name),k=n.find(O=>O.name===S.target.name),M=[...S.joinKeyGroups],f={id:`key-${Date.now()}`,source:{id:`source-${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"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(k==null?void 0:k.name)||"",entityName:(k==null?void 0:k.name)||"",entityType:(k==null?void 0:k.type)||"table"},operator:"="};M[A]={...M[A],keys:[...M[A].keys,f]},l(T,{joinKeyGroups:M})},updateJoinKey:(T,A,S,v,k)=>{const M=a.joins.find(L=>L.id===T);if(!M)return;const f=n.find(L=>L.name===M.source.name),O=n.find(L=>L.name===M.target.name),F=[...M.joinKeyGroups],b=F[A].keys[S];v==="sourceColumnName"&&f?F[A].keys[S]={...b,source:{...b.source,name:k}}:v==="targetColumnName"&&O?F[A].keys[S]={...b,target:{...b.target,name:k}}:v==="operator"&&(F[A].keys[S]={...b,operator:k}),l(T,{joinKeyGroups:F})},removeJoinKey:(T,A,S)=>{const v=a.joins.find(M=>M.id===T);if(!v)return;const k=[...v.joinKeyGroups];k[A].keys.splice(S,1),l(T,{joinKeyGroups:k})},generateSQLPreview:()=>{const T=[...a.joins].sort((v,k)=>v.sequence-k.sequence),A=a.baseEntity;if(!A.name)return"SELECT * FROM table -- Please select a base entity";let S=`SELECT *
157
+ FROM ${A.name}`;return T.forEach(v=>{const k=n.find(O=>O.name===v.target.name);if(!k)return;const M=v.joinKeyGroups.filter(O=>O.keys&&O.keys.length>0).map(O=>{const F=O.keys.filter(b=>{var L,C,P,R;return((L=b.source)==null?void 0:L.name)&&((C=b.target)==null?void 0:C.name)&&((P=b.source)==null?void 0:P.entityName)&&((R=b.target)==null?void 0:R.entityName)}).map(b=>`${b.source.entityName}.${b.source.name} ${b.operator} ${b.target.entityName}.${b.target.name}`);return F.length>1?`(${F.join(` ${O.operator} `)})`:F[0]}).filter(Boolean),f=M.length>1?M.join(" OR "):M[0]||"condition_here";S+=`
158
+ ${v.joinType} JOIN ${k.name}
159
+ ON ${f}`}),S},isValidConfiguration:()=>!(!a.baseEntity.name||a.joins.some(v=>!v.source.name||!v.target.name)||a.joins.some(v=>v.joinKeyGroups.some(k=>k.keys.length===0))||a.joins.some(v=>v.joinKeyGroups.some(k=>k.keys.some(M=>!M.source.name||!M.target.name||!M.operator))))}}function Ln({joinPlan:s,availableDataSources:n,onSave:a,onRemove:r,onCancel:i}){const{setCardConfig:c}=t.useEditorActions();t.useEditorStore(f=>f.card.config);const{columnGroups:o}=t.useColumns(),d=o.filter(f=>f.entityName!==t.CALCULATED_FIELDS_GROUP_NAME),{joinPlan:l,expandedJoins:m,setJoinPlan:p,addJoin:x,removeJoin:u,updateJoin:h,moveJoinUp:g,moveJoinDown:y,toggleJoinExpansion:j,getAvailableSourceEntities:I,getAvailableTargetEntities:D,addJoinKeyGroup:V,updateGroupOperator:E,removeJoinKeyGroup:w,addJoinKey:T,updateJoinKey:A,removeJoinKey:S,generateSQLPreview:v,isValidConfiguration:k}=Mn({initialJoinPlan:s,availableDataSources:n}),M=f=>{const O=d.find(F=>F.entityName===f);return(O==null?void 0:O.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:l.baseEntity.name,onValueChange:f=>{const O=n.find(F=>F.name===f);p({...l,baseEntity:{connectionId:(O==null?void 0:O.connectionId)||"",connectionType:(O==null?void 0:O.connectionType)||"none",type:(O==null?void 0:O.type)||"table",name:f,database:O==null?void 0:O.database,schema:O==null?void 0:O.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(t.SelectContent,{children:n.map(f=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:f.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:f.type}),f.name,e.jsx(t.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},f.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:v()})]}),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 (",l.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:x,children:[e.jsx(t.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),l.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:l.joins.map(f=>{const O=n.find(L=>L.name===f.source.name),F=n.find(L=>L.name===f.target.name),b=m.has(f.id);return e.jsxs(t.Card,{className:"border",children:[e.jsx(t.CardHeader,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{children:f.sequence}),e.jsxs(t.CardTitle,{className:"text-sm",children:["Join ",f.sequence,O&&F&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",O.name," → ",F.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>g(f.id),disabled:f.sequence===1,children:e.jsx(t.ArrowUp,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>y(f.id),disabled:f.sequence===l.joins.length,children:e.jsx(t.ArrowDown,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>j(f.id),children:b?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:()=>u(f.id),children:e.jsx(t.X,{className:"h-4 w-4"})})]})]})}),b&&e.jsxs(t.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Source"}),e.jsxs(t.Select,{value:f.source.name,onValueChange:L=>{const C=n.find(P=>P.name===L);h(f.id,{source:{connectionId:(C==null?void 0:C.connectionId)||"",connectionType:(C==null?void 0:C.connectionType)||"none",type:(C==null?void 0:C.type)||"table",name:L,database:C==null?void 0:C.database,schema:C==null?void 0:C.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select source..."})}),e.jsx(t.SelectContent,{children:I(f.id).map(L=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:L.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:L.type}),L.name]})},L.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Join Type"}),e.jsxs(t.Select,{value:f.joinType,onValueChange:L=>h(f.id,{joinType:L}),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Target"}),e.jsxs(t.Select,{value:f.target.name,onValueChange:L=>{const C=n.find(P=>P.name===L);h(f.id,{target:{connectionId:(C==null?void 0:C.connectionId)||"",connectionType:(C==null?void 0:C.connectionType)||"none",type:(C==null?void 0:C.type)||"table",name:L,database:C==null?void 0:C.database,schema:C==null?void 0:C.schema}})},disabled:!f.source.name,children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select target..."})}),e.jsx(t.SelectContent,{children:f.source.name?D(f.source.name).map(L=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:L.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:L.type}),L.name,L.name===f.source.name&&e.jsx(t.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},L.name)):[]})]})]})]}),f.source.name&&f.target.name&&O&&F&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{children:"Join Conditions"}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>V(f.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),f.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:f.joinKeyGroups.map((L,C)=>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 ",C+1]}),C>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(t.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Select,{value:L.operator,onValueChange:P=>E(f.id,C,P),children:[e.jsx(t.SelectTrigger,{className:"w-[100px]",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>w(f.id,C),children:e.jsx(t.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[L.keys.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-sm text-gray-500",children:"No conditions in this group. Add conditions to specify join criteria."}):e.jsx("div",{className:"space-y-2",children:L.keys.map((P,R)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[R>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:L.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:P.source.name,onValueChange:B=>A(f.id,C,R,"sourceColumnName",B),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Source column"})}),e.jsx(t.SelectContent,{children:M(f.source.name).map(B=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:B.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:B.name}),e.jsx(t.Badge,{variant:"outline",className:"ml-2 text-xs",children:B.dataType})]})},B.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(t.Select,{value:P.operator,onValueChange:B=>A(f.id,C,R,"operator",B),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:P.target.name,onValueChange:B=>A(f.id,C,R,"targetColumnName",B),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Target column"})}),e.jsx(t.SelectContent,{children:M(f.target.name).map(B=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:B.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:B.name}),e.jsx(t.Badge,{variant:"outline",className:"ml-2 text-xs",children:B.dataType})]})},B.name))})]})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>S(f.id,C,R),children:e.jsx(t.X,{className:"size-3.5"})})]},P.id||R))}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>T(f.id,C),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},L.id))})]})]})]},f.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>{r(),i()},children:"Remove All"}),e.jsx(t.Button,{variant:"outline",onClick:i,children:"Cancel"}),e.jsx(t.Button,{onClick:()=>a(l),disabled:!k(),children:"Save"})]})]})}function Ia({children:s,open:n,onOpenChange:a,joinPlan:r,availableDataSources:i,onRemove:c,onSave:o,onCancel:d}){return e.jsxs(t.Dialog,{open:n,onOpenChange:a,children:[e.jsxs(t.DialogContent,{className:"max-w-4xl",children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Join Configuration"}),e.jsx(t.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(Ln,{joinPlan:r,availableDataSources:i,onSave:o,onCancel:d,onRemove:c})]}),s]})}function On({joins:s,baseEntityId:n,availableDataSources:a,generateSQLPreview:r}){return e.jsxs("div",{className:"my-2 max-h-[400px] divide-y divide-border overflow-y-auto",children:[s.length>0&&e.jsxs("div",{className:"px-4 py-2",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const i=[...s].sort((o,d)=>o.sequence-d.sequence),c=a.find(o=>o.name===n);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(t.Badge,{variant:"secondary",className:"text-xs",children:c==null?void 0:c.type}),e.jsx("span",{className:"text-xs font-medium",children:c==null?void 0:c.name}),e.jsx(t.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),i.map(o=>{const d=a.find(l=>l.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(t.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(t.Badge,{variant:"secondary",className:"text-xs",children:d==null?void 0:d.type}),e.jsx("span",{className:"text-xs font-medium",children:d==null?void 0:d.name})]})]},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((i,c)=>i.sequence-c.sequence).map((i,c)=>{const o=a.find(m=>m.name===i.source.name),d=a.find(m=>m.name===i.target.name),l=i.joinKeyGroups.reduce((m,p)=>m+p.keys.length,0);return e.jsxs("div",{className:"rounded-md bg-muted p-2 text-left",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:c+1}),e.jsx(t.Badge,{variant:"outline",className:"shrink-0 text-xs",children:i.joinType}),e.jsxs(t.Badge,{variant:"outline",className:"ml-auto shrink-0 text-xs",children:[l," condition",l>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]})]},i.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function ta({open:s,onOpenChange:n,variant:a="button"}={}){var D,V;const r=t.useEditorStore(E=>E.card),{autoJoinMetadata:i}=t.useDashboardCardQuery(r),c=t.useEditorStore(E=>E.actions.updateCardConfig),o=((D=r==null?void 0:r.config)==null?void 0:D.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[d,l]=N.useState(!1),m=s!==void 0,p=m?s:d,x=m?n:l,u=((V=r==null?void 0:r.dataSource)==null?void 0:V.selectedEntities)||[],h=E=>{c(r.id,{...r==null?void 0:r.config,joinPlan:E}),x(!1)},g=()=>{c(r.id,{...r==null?void 0:r.config,joinPlan:void 0})},y=()=>{x(!1)},j=()=>{const E=[...o.joins].sort((A,S)=>A.sequence-S.sequence),w=o.baseEntity;if(!w.name)return"SELECT * FROM table -- Please select a base entity";let T=`SELECT *
160
+ FROM ${w.name}`;return E.forEach(A=>{const S=u.find(M=>M.name===A.target.name);if(!S)return;const v=A.joinKeyGroups.filter(M=>M.keys&&M.keys.length>0).map(M=>{const f=M.keys.filter(O=>{var F,b,L,C;return((F=O.source)==null?void 0:F.name)&&((b=O.target)==null?void 0:b.name)&&((L=O.source)==null?void 0:L.entityName)&&((C=O.target)==null?void 0:C.entityName)}).map(O=>`${O.source.entityName}.${O.source.name} ${O.operator} ${O.target.entityName}.${O.target.name}`);return f.length>1?`(${f.join(` ${M.operator} `)})`:f[0]}).filter(Boolean),k=v.length>1?v.join(" OR "):v[0]||"condition_here";T+=`
161
+ ${A.joinType} JOIN ${S.name}
162
+ ON ${k}`}),T};if(u.length<2)return null;const I=o.joins.length>0&&e.jsx(t.TooltipContent,{side:"bottom",className:"ml-4 max-w-md overflow-hidden p-0",children:e.jsx(On,{joins:o.joins,baseEntityId:o.baseEntity.name,availableDataSources:u,generateSQLPreview:j})});return e.jsxs(e.Fragment,{children:[e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:a==="badge"?e.jsxs(t.Badge,{variant:"secondary",className:"h-5 cursor-pointer gap-1 px-1.5 text-xs transition-colors hover:bg-secondary/80",onClick:E=>{E.stopPropagation(),x(!0)},children:[e.jsx(t.Link,{className:"h-3 w-3"}),o.joins.length]}):e.jsxs(t.Button,{onClick:()=>x(!0),variant:"outline",className:"w-full bg-muted/50",children:[e.jsx(t.Link,{className:"mr-2 h-3.5 w-3.5"}),o.joins.length===0?"Configure Joins":o.joins.length===1?"Join":"Joins",o.joins.length>0&&e.jsx("span",{className:"ml-2 flex h-5 min-w-5 items-center justify-center rounded-full border bg-muted-foreground px-1.5 text-xs font-medium text-background",children:o.joins.length}),(i==null?void 0:i.autoResolved)&&e.jsxs(t.Badge,{variant:"secondary",className:"ml-2 h-5 gap-1 bg-blue-50 text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:[e.jsx(t.Sparkles,{className:"h-3 w-3"}),"Auto"]})]})}),I]})}),e.jsx(Ia,{open:p,onOpenChange:x,joinPlan:o,availableDataSources:u,onSave:h,onCancel:y,onRemove:g,children:e.jsx("div",{})})]})}function Fn({open:s,onOpenChange:n}){const[a,r]=N.useState([]),{updateDataSource:i}=t.useEditorActions(),{selectedEntities:c}=t.useAssistantContextEntities("dashboard");N.useEffect(()=>{s&&r([])},[s]);const o=h=>{r(g=>g.some(j=>t.areContextEntitiesEqual(j,h))?g.filter(j=>!t.areContextEntitiesEqual(j,h)):[...g,h])},d=()=>{r([...c])},l=()=>{r([])},m=()=>{if(a.length===0)return;const h=a[0],g=h.connectionId||"",y=h.connectionType||"",I=a.some(V=>V.type==="dataset")?"semanticDomain":"database";i({connectionId:g,connectionType:y,mode:I,selectedEntities:a}),n(!1)},p=h=>"label"in h&&h.label?h.label:h.name,x=h=>{if("description"in h&&h.description)return h.description;const g=[];return h.database&&g.push(h.database),h.schema&&g.push(h.schema),h.name&&g.push(h.name),g.join(".")},u=h=>a.some(g=>t.areContextEntitiesEqual(g,h));return c.length===0?e.jsx(t.Dialog,{open:s,onOpenChange:n,children:e.jsxs(t.DialogContent,{className:"max-w-md",children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"No Data Available"}),e.jsx(t.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(t.DialogFooter,{children:e.jsx(t.Button,{onClick:()=>n(!1),children:"Close"})})]})}):e.jsx(t.Dialog,{open:s,onOpenChange:n,children:e.jsxs(t.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(t.DialogDescription,{children:"Choose entities from the dashboard's context"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"outline",size:"sm",onClick:d,disabled:a.length===c.length,children:"Select All"}),e.jsx(t.Button,{variant:"outline",size:"sm",onClick:l,disabled:a.length===0,children:"Clear All"})]}),e.jsxs(t.Badge,{variant:"secondary",children:[a.length," of ",c.length," selected"]})]}),e.jsx(t.Separator,{}),e.jsx(t.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:c.map((h,g)=>e.jsxs("div",{className:t.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",u(h)&&"border-primary bg-primary/5"),children:[e.jsx(t.Checkbox,{checked:u(h),onCheckedChange:()=>o(h)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:t.getEntityIcon(h.type)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:p(h)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:x(h)})]}),e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:h.type})]},`${h.type}-${h.name}-${g}`))})})]}),e.jsx(t.DialogFooter,{children:e.jsx("div",{className:"flex w-full justify-between",children:e.jsxs("div",{className:"flex grow justify-end gap-2",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsxs(t.Button,{onClick:m,disabled:a.length===0,children:["Select"," ",a.length>0?`(${a.length})`:""]})]})})})]})})}function sa({entities:s,title:n}){const{isConsoleMode:a}=t.useDashboardPreferences();return e.jsx(t.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:n??`${s.length} more entities`}),e.jsx("div",{className:"space-y-1",children:s.map((r,i)=>{const c=t.getEntityDetails(r),o=c.find(l=>l.label==="Description"&&l.value),d=c.filter(l=>l.label==="Description"?!1:a?!0:!["Connection","Database","Schema"].includes(l.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:t.getDisplayName(r)}),o&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:o.value})]}),d.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:d.map((l,m)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[l.label,":"]}),e.jsx("span",{className:"font-mono",children:l.value})]},m))})]},`remaining-${r.type}-${r.name}-${i}`)})})]})})}function ka(s,n){const[a,r]=N.useState(()=>{const i=localStorage.getItem(s);return i?JSON.parse(i):n});return N.useEffect(()=>{localStorage.setItem(s,JSON.stringify(a))},[a,s]),[a,r]}function Da({isVisible:s}){var y,j;const n=t.useEditorStore(I=>I.isDevMode);t.useSyncLegacyEditorState();const[a,r]=N.useState(!1),[i,c]=N.useState(!1),[o,d]=ka("semaphor:data-source-collapsed",!1),l=t.useEditorStore(I=>I.card.dataSource),m=t.useEditorStore(I=>{var D,V;return(V=(D=I.card)==null?void 0:D.config)==null?void 0:V.joinPlan}),{updateDataSource:p}=t.useEditorActions(),x=((y=l==null?void 0:l.selectedEntities)==null?void 0:y.length)||0,u=((j=m==null?void 0:m.joins)==null?void 0:j.length)||0,g={...{connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},...l,selectedEntities:(l==null?void 0:l.selectedEntities)||[]};return e.jsxs("div",{className:t.cn("flex shrink-0 flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":s,"min-w-[325px]":s,"w-0":!s,"min-w-0":!s}),children:[x===0&&u===0?e.jsx("div",{className:"px-4 pt-4",children:e.jsx("div",{className:"rounded-xl border border-border/55 bg-card p-3 shadow-[0_1px_2px_rgba(15,23,42,0.05)]",children:e.jsxs(t.Button,{className:"w-full bg-background",variant:"outline",onClick:()=>r(!0),children:[e.jsx(t.Database,{className:"mr-2 h-3.5 w-3.5"}),"Choose Dataset"]})})}):e.jsx("div",{className:"px-4 pt-4",children:e.jsxs("div",{className:"rounded-xl border border-border/55 bg-card p-3 shadow-[0_1px_2px_rgba(15,23,42,0.05)]",children:[e.jsxs("div",{className:t.cn("flex cursor-pointer items-center justify-between px-1",o?"pb-0":"pb-3"),onClick:()=>d(!o),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:"Data Source"}),o&&e.jsxs("div",{className:"flex items-center gap-1.5",onClick:I=>I.stopPropagation(),children:[x>0&&e.jsx(t.TooltipProvider,{delayDuration:100,children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs(t.Badge,{variant:"secondary",className:"h-5 cursor-pointer gap-1 px-1.5 text-xs transition-colors hover:bg-secondary/80",onClick:()=>r(!0),children:[e.jsx(t.Database,{className:"h-3 w-3"}),x]})}),e.jsx(sa,{entities:g.selectedEntities,title:`${x} selected ${x===1?"entity":"entities"}`})]})}),u>0&&!n&&e.jsx(ta,{variant:"badge"})]})]}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:I=>{I.stopPropagation(),d(!o)},children:o?e.jsx(t.ChevronDown,{className:"h-4 w-4"}):e.jsx(t.ChevronUp,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:t.cn("flex flex-col overflow-hidden transition-all duration-200 ease-in-out",o?"max-h-0 opacity-0":"max-h-96 opacity-100"),children:[e.jsx("div",{className:"px-1",children:e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs(t.Button,{className:"w-full bg-background",variant:"outline",onClick:()=>r(!0),children:[e.jsx(t.Database,{className:"mr-2 h-3.5 w-3.5"}),x===1?"Dataset":"Datasets",e.jsx("span",{className:"ml-2 flex h-5 min-w-5 items-center justify-center rounded-full border bg-muted-foreground px-1.5 text-xs font-medium text-background",children:x})]})}),e.jsx(sa,{entities:g.selectedEntities,title:`${x} selected ${x===1?"entity":"entities"}`})]})})}),!n&&x>1&&e.jsx("div",{className:"mt-3 px-1",children:e.jsx(ta,{})})]})]})}),e.jsx("div",{className:"min-h-0 flex-1 px-4 pb-4 pt-2",children:e.jsx("div",{className:"h-full overflow-hidden rounded-xl border border-border/55 bg-card shadow-[0_1px_2px_rgba(15,23,42,0.05)]",children:e.jsx(t.FieldsSection,{})})}),e.jsx(t.DataSourceDialog,{incomingSelectedEntities:(l==null?void 0:l.selectedEntities)||[],dialogMode:"dataSource",open:a,onOpenChange:r,dataSource:g}),e.jsx(Fn,{open:i,onOpenChange:c})]})}function Rn(s){return t.GenIcon({attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M439.8 200.5c-7.7-30.9-22.3-54.2-53.4-54.2h-40.1v47.4c0 36.8-31.2 67.8-66.8 67.8H172.7c-29.2 0-53.4 25-53.4 54.3v101.8c0 29 25.2 46 53.4 54.3 33.8 9.9 66.3 11.7 106.8 0 26.9-7.8 53.4-23.5 53.4-54.3v-40.7H226.2v-13.6h160.2c31.1 0 42.6-21.7 53.4-54.2 11.2-33.5 10.7-65.7 0-108.6zM286.2 404c11.1 0 20.1 9.1 20.1 20.3 0 11.3-9 20.4-20.1 20.4-11 0-20.1-9.2-20.1-20.4.1-11.3 9.1-20.3 20.1-20.3zM167.8 248.1h106.8c29.7 0 53.4-24.5 53.4-54.3V91.9c0-29-24.4-50.7-53.4-55.6-35.8-5.9-74.7-5.6-106.8.1-45.2 8-53.4 24.7-53.4 55.6v40.7h106.9v13.6h-147c-31.1 0-58.3 18.7-66.8 54.2-9.8 40.7-10.2 66.1 0 108.6 7.6 31.6 25.7 54.2 56.8 54.2H101v-48.8c0-35.3 30.5-66.4 66.8-66.4zm-6.7-142.6c-11.1 0-20.1-9.1-20.1-20.3.1-11.3 9-20.4 20.1-20.4 11 0 20.1 9.2 20.1 20.4s-9 20.3-20.1 20.3z"},child:[]}]})(s)}function Aa(s){const{theme:n}=t.useTheme(),a=t.useDashboardStore(y=>y.theme),r=t.useEditorStore(y=>y.frame),i=t.useEditorStore(y=>y.card),c=t.useEditorStore(y=>y.activeTabCardId),o=t.Le(),{refetch:d}=t.useDashboardCardQuery(i),{updateCardTab:l,setRunSql:m}=t.useEditorActions(),p=N.useRef(void 0),x=N.useRef({}),u=r.cards.find(y=>y.id===c),h=N.useCallback(()=>{let y="";return s==="python"&&(y=(u==null?void 0:u.python)||t.PYTHON_DEFAULT_CODE),s==="sql"&&(y=(u==null?void 0:u.sql)||""),y},[s,u]);N.useEffect(()=>{if(c&&i.id&&i.id!==c){if(p.current&&o){const y=p.current.getModel();y&&(x.current[i.id]=y);let j=x.current[c];if(!j){const I=h();j=o.editor.createModel(I,s),x.current[c]=j}p.current.setModel(j)}l(c,i),m(!0)}},[c,i,l,o,m,s,h]),N.useEffect(()=>{if(!o)return;const y=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",j=a==="system"?y:a;o.editor.defineTheme("default",{base:j==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":j==="light"?"#ffffff":t.hslStringToHex("240 10% 10%")}}),o.editor.setTheme("default")},[n,a,o]),N.useEffect(()=>{const y=p.current;y&&o&&i&&y.addCommand(o.KeyMod.Shift|o.KeyCode.Enter,function(){return d(),!1})},[o,d,i]);function g(y,j){if(p.current=y,!x.current[i.id]){const I=y.getModel(),D=h();x.current[i.id]=I||(j==null?void 0:j.editor.createModel(D,s))||y.getModel()}y.setModel(x.current[i.id])}return{handleEditorDidMount:g}}const Bn=300;function Pn(){const s=t.useEditorStore(p=>p.card.sql),n=t.useEditorStore(p=>p.sqlGen),{setCardSql:a,setSqlGen:r}=t.useEditorActions(),{handleEditorDidMount:i}=Aa("sql"),c=N.useRef(n);c.current=n;const o=N.useCallback(p=>{a(p)},[a]),{value:d,onChange:l}=Ea({storeValue:s,defaultValue:"",onStoreUpdate:o,delay:Bn});function m(p){l(p),t.isObjectEmpty(c.current)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!d&&e.jsx("div",{className:"pointer-events-none absolute left-[36px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(t.Ft,{theme:"default",className:"pt-3",onChange:m,value:d,options:{minimap:{enabled:!1},glyphMargin:!1,lineNumbersMinChars:2,lineDecorationsWidth:0,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:i})]})}const Vn=300;function _n(){const s=t.useEditorStore(c=>c.card.python),{setCardPython:n}=t.useEditorActions(),{handleEditorDidMount:a}=Aa("python"),{value:r,onChange:i}=Ea({storeValue:s,defaultValue:t.PYTHON_DEFAULT_CODE,onStoreUpdate:n,delay:Vn});return e.jsx(t.Ft,{className:"pt-3",theme:"default",onChange:i,value:r,options:{minimap:{enabled:!1},glyphMargin:!1,lineNumbersMinChars:2,lineDecorationsWidth:0,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:a})}const zn={async writeTextToClipboard(s){return typeof navigator>"u"||!navigator.clipboard?!1:(await navigator.clipboard.writeText(s),!0)}},Ft=50,qn=[{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 aa(s){try{return JSON.stringify(s,null,2)}catch(n){return console.error("Unable to stringify debug payload",n),null}}function ft(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 $n(s){if(!s||typeof s!="object")return{value:s};const n=s.records;return!Array.isArray(n)||n.length<=Ft?{value:s}:{value:{...s,records:n.slice(0,Ft),previewMeta:{truncatedRecords:!0,displayedRecords:Ft,totalRecords:n.length}},truncationMessage:`Preview showing first ${Ft} records of ${n.length}. Copy actions include full payload.`}}function Ma({sql:s,showCardDetails:n=!1,debugPayloads:a,className:r}){const[i,c]=N.useState(!1),[o,d]=N.useState(null),l=t.useEditorStore(k=>k.card),m=t.useEditorStore(k=>k.frame),p=t.useEditorStore(k=>k.isDevMode),x=t.useDashboardStore(k=>k.selectedSheetId),u=t.useDashboardStore(k=>{var M;return(M=k.dashboard)==null?void 0:M.id}),{switchEditorMode:h,setRunSql:g}=t.useEditorActions(),y=N.useMemo(()=>({cardId:l.id||null,frameId:m.id||null,sheetId:x||null,dashboardId:u||null}),[l.id,m.id,x,u]),j=N.useMemo(()=>({queryRequest:a==null?void 0:a.queryRequest,queryResponse:a==null?void 0:a.queryResponse,cardConfig:l.config,dataSource:l.dataSource,columns:a==null?void 0:a.columns,dashboardFilters:a==null?void 0:a.dashboardFilters,cardMetadata:y}),[a==null?void 0:a.queryRequest,a==null?void 0:a.queryResponse,a==null?void 0:a.columns,a==null?void 0:a.dashboardFilters,l.config,l.dataSource,y]),I=n&&i&&!!a,D=N.useMemo(()=>[{label:"Card ID",value:l.id||""},{label:"Frame ID",value:m.id||""},{label:"Sheet ID",value:x||""},{label:"Dashboard ID",value:u||""}],[l.id,m.id,x,u]),V=()=>{h("dev",{sqlToLoad:s}),setTimeout(()=>{g(!0)},100)},E=k=>j[k]!==void 0,w=N.useMemo(()=>{if(!o)return null;const k=j[o];if(k===void 0)return null;const M=o==="queryResponse"?$n(k):{value:k},f=aa(M.value);return f?{target:o,title:ft(o),json:f,truncationMessage:M.truncationMessage}:null},[o,j]),T=w?w.title:"Preview Payload",A=async k=>{const M=j[k];if(M===void 0)return t.ue.error(`No ${ft(k).toLowerCase()} available`),!1;const f=aa(M);if(!f)return t.ue.error(`Unable to serialize ${ft(k).toLowerCase()}`),!1;try{return await zn.writeTextToClipboard(f)?(t.ue.success(`${ft(k)} copied`),!0):(t.ue.error("Clipboard is not available"),!1)}catch(O){return console.error("Failed to copy debug payload",O),t.ue.error(`Unable to copy ${ft(k).toLowerCase()}`),!1}},S=async()=>w?A(w.target):!1,v=k=>{if(j[k]===void 0){t.ue.error(`No ${ft(k).toLowerCase()} available`);return}d(k)};return e.jsxs("div",{className:t.cn("flex min-h-0 flex-1 flex-col",r),children:[!p&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsxs(t.Button,{onClick:V,variant:"secondary",size:"sm",children:[e.jsx(wa,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),n&&e.jsxs(t.Button,{onClick:()=>c(!i),variant:"outline",size:"sm",children:[e.jsx(t.Info,{className:"mr-2 h-4 w-4"}),"Card Details"]})]}),i&&n&&e.jsx("div",{className:"mb-3 rounded-lg border border-border bg-muted/30 p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Card Information"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>c(!1),children:e.jsx(De.CircleX,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"grid grid-cols-1 gap-2 md:grid-cols-2",children:D.map(k=>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:k.label}),e.jsx(t.CopyButton,{text:k.value,className:"h-6 w-6 shrink-0"})]}),e.jsx("code",{title:k.value||"N/A",className:"mt-1 block whitespace-normal break-all font-mono text-xs",children:k.value||"N/A"})]},k.label))}),I&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-background/70 p-3",children:[e.jsx("p",{className:"text-xs font-semibold text-muted-foreground",children:"Debug Tools"}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(t.DropdownMenu,{children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8","aria-label":"Preview Payload Menu",children:[e.jsx(t.Eye,{className:"mr-1.5 h-3.5 w-3.5"}),T,e.jsx(t.ChevronDown,{className:"ml-1.5 h-3.5 w-3.5"})]})}),e.jsx(t.DropdownMenuContent,{align:"start",className:"w-56",children:qn.map(k=>e.jsx(t.DropdownMenuItem,{disabled:!E(k.target),onSelect:()=>v(k.target),className:t.cn(o===k.target&&"bg-accent"),children:k.label},`preview-${k.target}`))})]})}),w&&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:[w.title," Preview"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(t.CopyButton,{text:w.json,className:"h-6 w-6",ariaLabel:"Copy Payload",onCopy:S}),e.jsxs(t.Button,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>d(null),children:[e.jsx(De.CircleX,{className:"mr-1 h-3.5 w-3.5"}),"Hide"]})]})]}),w.truncationMessage&&e.jsx("p",{className:"text-xs text-muted-foreground",children:w.truncationMessage}),e.jsx("div",{className:"max-h-80 overflow-auto",children:e.jsx(t.CodeHighlighter,{code:w.json,language:"json"})})]})]})]})}),e.jsx("div",{className:"min-h-0 flex-1 overflow-auto",children:e.jsxs("div",{className:"overflow-hidden rounded-xl border border-border/60 bg-gradient-to-b from-background to-muted/[0.18] shadow-sm",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border/50 bg-background/80 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"rounded-md border border-border/60 bg-muted/60 px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.12em] text-muted-foreground",children:"SQL"}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Generated query"})]}),e.jsx("div",{className:"rounded-md border border-border/60 bg-background/85 p-0.5 shadow-sm backdrop-blur-sm",children:e.jsx(t.CopyButton,{text:s,className:"h-6 w-6 px-0 text-muted-foreground/80 hover:text-foreground"})})]}),e.jsx("div",{className:"group relative overflow-auto px-1 py-1 text-xs leading-relaxed text-foreground/80",children:e.jsx(t.CodeHighlighter,{code:s,language:"sql",wrapLongLines:!0})})]})})]})}function Kn(s){const{request:n,mode:a="draft",currentSql:r,selectedTableName:i,selectedSchemaName:c,selectedDatabaseName:o}=s,d=[o?`Database: ${o}`:"",c?`Schema: ${c}`:"",i?`Table: ${i}`:""].filter(Boolean);return["You are an expert SQL writing assistant embedded in a query editor.",`Write SQL only. You may call only read-only tools when needed: ${t.INLINE_ALLOWED_TOOL_LIST}.`,"Do not call mutation tools or chart-creation tools; those require Full Assistant.","Return exactly one SQL statement inside a single ```sql fenced block.","After the code block, optionally include one short sentence.",a==="refine"&&r?"Mode: Refine existing SQL. Keep the current query structure and only apply the requested changes unless the current query is invalid.":"Mode: Draft new SQL from the request.",d.length>0?`Context:
163
+ ${d.join(`
164
+ `)}`:"",r?a==="refine"?`Current SQL (must refine):
165
+ ${r}`:`Current SQL (revise if useful):
166
+ ${r}`:"",`User request:
167
+ ${n}`].filter(Boolean).join(`
168
+
169
+ `)}function Gn(s){const{request:n,failedSql:a,errorMessage:r,errorCode:i,selectedDatabaseName:c,selectedSchemaName:o,selectedTableName:d,contextEntityLabels:l}=s,m=[c?`Database: ${c}`:"",o?`Schema: ${o}`:"",d?`Table: ${d}`:"",l.length>0?`Selected context entities: ${l.join(", ")}`:""].filter(Boolean);return["You are fixing SQL after validation failed.","Return one read-only SQL statement in a single ```sql fenced block.","Do not call mutation tools.",m.length>0?`Context:
170
+ ${m.join(`
171
+ `)}`:"",`Original user request:
172
+ ${n}`,`Previous SQL draft:
173
+ ${a}`,`Validation failure${i?` (${i})`:""}:
174
+ ${r}`].filter(Boolean).join(`
175
+
176
+ `)}function Un(s,n){typeof window>"u"||window.dispatchEvent(new CustomEvent("semaphor:inline-query-writer",{detail:{event:s,...n,timestamp:Date.now()}}))}const Wt={runId:0,phase:"idle",attempt:0,activeStep:"",timelineSteps:[],lastValidation:null,finalOutcome:"idle",hasTools:!1};function Hn(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 na(s){let n=0;for(let a=0;a<s.length;a+=1)n=(n<<5)-n+s.charCodeAt(a),n|=0;return String(n)}function ra(s){return s==="getTableColumns"?"Discovering columns":s==="getDomainRelationships"?"Resolving relationships":s==="getChartSQLSyntax"?"Reviewing SQL syntax":s==="getUserSql"?"Inspecting current query":"Analyzing context"}function Qn(s,n){return s===t.SELF_HEAL_TIMELINE_STEP&&n>0?`${t.SELF_HEAL_TIMELINE_STEP} ${n}/${t.MAX_SELF_HEAL_ATTEMPTS}`:s}function Rt(s){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`${s}-${crypto.randomUUID()}`:`${s}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function la(s){var n;for(let a=s.length-1;a>=0;a-=1){const r=s[a];if(r.role!=="user")continue;const i=(n=r.metadata)==null?void 0:n.inlineRunToken;if(typeof i=="string"&&i.length>0)return i}}function Jn(s){if(!s)return"";const n=s.trim(),a=s.match(/```sql\s*([\s\S]*?)```/i);if(a!=null&&a[1])return a[1].trim();const r=s.match(/```[\w-]*\s*([\s\S]*?)```/i);return r!=null&&r[1]?r[1].trim():/^(select|with|insert|update|delete)\b/i.test(n)?n:""}function oa(s){for(let n=s.length-1;n>=0;n-=1){const a=s[n];if(!(a.role!=="assistant"||!Array.isArray(a.parts)))for(let r=a.parts.length-1;r>=0;r-=1){const i=a.parts[r];if((i==null?void 0:i.type)!=="text"||typeof(i==null?void 0:i.text)!="string")continue;const c=Jn(i.text);if(c)return c}}return""}function Yn({currentSql:s,currentPython:n,selectedDatabaseName:a,selectedSchemaName:r,selectedTableName:i,onApplySql:c,onOpenFullAssistant:o}){var Ae,ut;const{authToken:d,tokenProps:l}=t.useSemaphorContext(),m=(Ae=t.useDashboardQuery().data)==null?void 0:Ae.assistantProfileId,p=t.useEditorStore($=>$.isDevMode),x=t.useEditorStore($=>$.selectedConnectionId),u=t.useEditorStore($=>{var Q;return(Q=$.card.dataSource)==null?void 0:Q.selectedEntities}),h=t.useAIInteractionStore($=>$.currentAIContext.selectedEntities),g=h.length,{setCurrentAIContext:y}=t.useAIActions(),[j,I]=N.useState(""),[D,V]=N.useState(""),[E,w]=N.useState(""),[T,A]=N.useState("draft"),[S,v]=N.useState("draft"),[k,M]=N.useState(""),[f,O]=N.useState(!1),[F,b]=N.useState({status:"idle"}),[L,C]=N.useState(Wt),[P,R]=N.useState(!1),[B,z]=N.useState(()=>Rt("inline-query-session")),_=N.useRef(null),K=N.useRef(null),H=N.useRef(null),G=N.useRef(0),X=N.useRef(0),ae=N.useRef(Rt("inline-run-token")),ee=N.useRef(B),de=N.useRef(new Set),ce=N.useRef(new Map),W=N.useRef(0),pe=N.useRef(""),Z=N.useRef(!1),we=N.useRef(!1),U=N.useRef(Wt),ne=N.useRef(!1),ye=N.useRef(null),se=N.useRef(()=>{}),be=(ut=l.apiServiceUrl)==null?void 0:ut.replace(/\/$/,""),ge=be?`${be}/v1/sql/validate`:"/v1/sql/validate",fe=N.useCallback($=>{C(Q=>{const Y=$(Q);return U.current=Y,Y})},[]),Ne=N.useCallback(($,Q)=>{fe(Y=>Y.runId===$?Q(Y):Y)},[fe]),ve=N.useCallback($=>X.current===$&&!de.current.has($),[]),Te=N.useCallback(($,Q,Y)=>{Ne($,ue=>{const oe=ue.timelineSteps.includes(Q)?ue.timelineSteps:[...ue.timelineSteps,Q];return{...ue,phase:(Y==null?void 0:Y.phase)||ue.phase,attempt:typeof(Y==null?void 0:Y.attempt)=="number"?Y.attempt:ue.attempt,activeStep:Q,timelineSteps:oe,finalOutcome:(Y==null?void 0:Y.finalOutcome)||ue.finalOutcome,hasTools:Y!=null&&Y.hasTools?!0:ue.hasTools}})},[Ne]),Le=N.useCallback(()=>{const $=X.current+1,Q=Rt("inline-run-token"),Y=Rt("inline-query-session");return X.current=$,ae.current=Q,ee.current=Y,z(Y),de.current=new Set,ce.current=new Map,W.current=0,pe.current="",ne.current=!1,fe(()=>({runId:$,phase:"drafting",attempt:0,activeStep:"Drafting SQL",timelineSteps:["Drafting SQL"],lastValidation:null,finalOutcome:"drafting",hasTools:!1})),{runId:$,runToken:Q,chatSessionId:Y}},[fe]),te=N.useCallback(()=>{if(Z.current||we.current||g>0)return;const $=u||[];if($.length===0)return;const Q=t.useAIInteractionStore.getState().currentAIContext;y({...Q,selectedEntities:$}),we.current=!0},[g,u,y]),je=N.useCallback(()=>{Z.current=!0},[]),me=N.useCallback(($,Q,Y)=>{Un($,{runId:Q,attemptCount:typeof(Y==null?void 0:Y.attemptCount)=="number"?Y.attemptCount:W.current,errorCode:Y==null?void 0:Y.errorCode,hasTools:typeof(Y==null?void 0:Y.hasTools)=="boolean"?Y.hasTools:L.hasTools,entityCount:g,finalOutcome:(Y==null?void 0:Y.finalOutcome)||L.finalOutcome})},[g,L.finalOutcome,L.hasTools]),Ee=N.useCallback(($,Q)=>{const Y=H.current;if(!Y)return;const ue={inlineRunToken:Q};Y({role:"user",parts:[{type:"text",text:$}],metadata:ue},{metadata:ue})},[]);N.useEffect(()=>{const $=ye.current;!$||$.sessionId!==B||(ye.current=null,Ee($.message,$.runToken))},[B,Ee]);const he=B,Re=N.useCallback(async({toolCall:$})=>{var Be,Ke,mt,xt,Pe,ht;if(he!==ee.current)return;const Q=String($.toolName||"").trim();if(!Q)return;const Y=X.current;if(!ve(Y)){(Be=K.current)==null||Be.call(K,{tool:Q,toolCallId:$.toolCallId,output:{status:"error",message:"Inline run is no longer active; ignoring tool output."}});return}if(Q==="getUserSql"){Te(Y,ra(Q),{hasTools:!0}),me("inline_tool_step",Y,{hasTools:!0}),(Ke=K.current)==null||Ke.call(K,{tool:Q,toolCallId:$.toolCallId,output:{status:"success",sql:s||"",python:n||""}});return}const ue=t.INLINE_BLOCKED_MUTATING_TOOLS.has(Q),oe=t.INLINE_ALLOWED_READ_ONLY_TOOLS.has(Q);if(ue||!oe){(mt=K.current)==null||mt.call(K,{tool:Q,toolCallId:$.toolCallId,output:{status:"error",message:"This action is unavailable in inline draft mode. Open Full Assistant for this action."}});return}const xe=ra(Q);Te(Y,xe,{phase:L.phase==="self-healing"?"self-healing":"drafting",hasTools:!0}),me("inline_tool_step",Y,{hasTools:!0});const Fe=((xt=$.input)==null?void 0:xt.sql)??((Pe=$.args)==null?void 0:Pe.sql);typeof Fe=="string"&&Fe.trim().length>0&&(ne.current=!1,w(Fe.trim())),(ht=K.current)==null||ht.call(K,{tool:Q,toolCallId:$.toolCallId,output:{status:"success",message:"Read-only tool result received."}})},[n,s,me,L.phase,ve,he,Te]),Ye=N.useCallback(({message:$,messages:Q})=>{if(he!==ee.current)return;const Y=la(Q);if(!Y||Y!==ae.current)return;const ue=X.current;if(!ve(ue))return;const oe=oa([$])||oa(Q);if(oe){ne.current=!1,w(oe.trim());return}ne.current&&U.current.phase==="self-healing"&&se.current(ue)},[ve,he]),qe=N.useCallback($=>{if(he!==ee.current)return;const Q=X.current;ve(Q)&&ne.current&&U.current.phase==="self-healing"&&se.current(Q)},[ve,he]),{setMessages:Se,sendMessage:at,addToolResult:nt,status:le,stop:Ie,error:Ge,clearError:Oe}=t.useChat({id:B,transport:new t.DefaultChatTransport({api:`${l.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${d==null?void 0:d.accessToken}`}),body:()=>{const $=t.useAIInteractionStore.getState();return{assistantId:"editor-assistant",assistantProfileId:m,isDevMode:p,aiContext:$.currentAIContext,reasoningEffort:$.reasoningEffort,showReasoning:!1}},credentials:"omit",prepareSendMessagesRequest:({messages:$,body:Q,requestMetadata:Y})=>{const ue=Y==null?void 0:Y.inlineRunToken,oe=la($);return{body:{...Q,inlineRunToken:ue||oe,messages:t.cleanupIncompleteMessages($)}}}}),onToolCall:Re,onFinish:Ye,onError:qe,sendAutomaticallyWhen:t.lastAssistantMessageIsCompleteWithToolCalls});K.current=nt,H.current=at;const ke=!["ready","error"].includes(le),jt=(Ge==null?void 0:Ge.message)||"Unable to generate a SQL draft right now. Try again.",$e=N.useCallback($=>{const Q=X.current,Y=U.current.phase;if(!(Y==="drafting"||Y==="self-healing"||Y==="validating")){$==="stopped"&&ke&&Ie();return}de.current.add(Q),ne.current=!1,G.current+=1,pe.current="",b({status:"idle"}),w(""),Oe(),Se([]),Ne(Q,oe=>({...oe,phase:"idle",activeStep:"",finalOutcome:"cancelled"})),me("inline_self_heal_stopped",Q,{finalOutcome:"cancelled"}),(ke||$==="stopped")&&Ie()},[Oe,me,ke,Se,Ie,Ne]),bt=N.useCallback(async($,Q)=>{var ue;if(!ve(Q))return null;const Y=G.current+1;G.current=Y,Te(Q,"Validating SQL",{phase:"validating"}),b({status:"validating"});try{const oe=await t.postRequestRegular(ge,(d==null?void 0:d.accessToken)||"",{sql:$,connectionId:x||void 0});if(G.current!==Y||!ve(Q))return null;if((oe==null?void 0:oe.valid)===!0)return b({status:"valid",message:"SQL validation passed."}),Ne(Q,Be=>({...Be,phase:"ready",finalOutcome:"validated",lastValidation:{valid:!0}})),me("inline_draft_validated",Q,{finalOutcome:"validated"}),{status:"valid"};const xe=Hn(oe==null?void 0:oe.errorCode)||"UNKNOWN",Fe=typeof(oe==null?void 0:oe.error)=="string"&&oe.error||typeof((ue=oe==null?void 0:oe.details)==null?void 0:ue.error)=="string"&&oe.details.error||"SQL validation failed. Please revise the query draft.";return b({status:"invalid",message:Fe,errorCode:xe}),Ne(Q,Be=>({...Be,lastValidation:{valid:!1,error:Fe,errorCode:xe}})),me("inline_validation_failed",Q,{errorCode:xe,finalOutcome:"validation_failed"}),{status:"invalid",error:Fe,errorCode:xe}}catch(oe){if(G.current!==Y||!ve(Q))return null;const xe=typeof(oe==null?void 0:oe.error)=="string"&&oe.error||typeof(oe==null?void 0:oe.detail)=="string"&&oe.detail||"Validation service unavailable. You can still replace and run.";return b({status:"error",message:xe,errorCode:"SQL_CONNECTION_ERROR"}),Ne(Q,Fe=>({...Fe,phase:"error",finalOutcome:"error",lastValidation:{valid:!1,error:xe,errorCode:"SQL_CONNECTION_ERROR"}})),{status:"error",error:xe,errorCode:"SQL_CONNECTION_ERROR"}}},[d==null?void 0:d.accessToken,me,ve,x,ge,Ne,Te]),et=N.useCallback(($,Q,Y,ue)=>{let oe=Y,xe="validation_failed",Fe="Validating SQL";Q==="attempt_limit"?(oe=`Couldn't auto-fix after ${t.MAX_SELF_HEAL_ATTEMPTS} attempts. ${Y}`,xe="self_heal_exhausted",Fe=`Auto-fix stopped (${t.MAX_SELF_HEAL_ATTEMPTS} attempts)`):Q==="duplicate"&&(oe=`Auto-fix stopped (repeated validation failure). ${Y}`,xe="self_heal_duplicate_stopped",Fe="Auto-fix stopped (repeated failure)"),b({status:"invalid",message:oe,errorCode:ue}),Te($,Fe,{phase:"error",finalOutcome:xe}),Ne($,Be=>({...Be,phase:"error",finalOutcome:xe,lastValidation:{valid:!1,error:oe,errorCode:ue}})),Q!=="terminal"&&me("inline_self_heal_stopped",$,{errorCode:ue,finalOutcome:xe}),ne.current=!1},[me,Ne,Te]),$t=N.useCallback($=>{const Q="Auto-fix stopped (no SQL returned). Open Full Assistant to continue.",Y="self_heal_no_draft";b({status:"invalid",message:Q,errorCode:"UNKNOWN"}),Te($,"Auto-fix stopped (no SQL returned)",{phase:"error",finalOutcome:Y}),Ne($,ue=>({...ue,phase:"error",finalOutcome:Y,lastValidation:{valid:!1,error:Q,errorCode:"UNKNOWN"}})),me("inline_self_heal_stopped",$,{errorCode:"UNKNOWN",finalOutcome:Y}),ne.current=!1},[me,Ne,Te]);se.current=$t,N.useEffect(()=>{const $=E.trim(),Q=X.current;if(!$){if(G.current+=1,pe.current="",U.current.phase==="error")return;b({status:"idle"});return}if(!ve(Q)||ke)return;const Y=`${Q}:${W.current}:${na($)}`;if(pe.current===Y)return;pe.current=Y;let ue=!1;return(async()=>{const xe=await bt($,Q);if(!xe||ue||!ve(Q)||xe.status!=="invalid")return;if(!t.RECOVERABLE_SQL_ERROR_CODES.has(xe.errorCode)){et(Q,"terminal",xe.error,xe.errorCode);return}const Fe=`${na($)}::${xe.errorCode}`,Be=(ce.current.get(Fe)||0)+1;if(ce.current.set(Fe,Be),Be>=2){et(Q,"duplicate",xe.error,xe.errorCode);return}if(W.current>=t.MAX_SELF_HEAL_ATTEMPTS){et(Q,"attempt_limit",xe.error,xe.errorCode);return}const Ke=W.current+1;W.current=Ke,Te(Q,t.SELF_HEAL_TIMELINE_STEP,{phase:"self-healing",attempt:Ke}),me("inline_self_heal_attempt",Q,{attemptCount:Ke,errorCode:xe.errorCode}),ne.current=!0,Oe(),Se([]),w("");const mt=h.map(Pe=>{const ht=Pe!=null&&Pe.database?`${Pe.database}.`:"",Mt=Pe!=null&&Pe.schema?`${Pe.schema}.`:"",Lt=(Pe==null?void 0:Pe.name)||"unknown";return`${ht}${Mt}${Lt}`}),xt=Gn({request:D,failedSql:$,errorMessage:xe.error,errorCode:xe.errorCode,selectedDatabaseName:a||"",selectedSchemaName:r||"",selectedTableName:i||"",contextEntityLabels:mt});Ee(xt,ae.current)})(),()=>{ue=!0}},[Oe,h,me,ke,ve,D,E,a,r,i,Ee,Se,et,Te,bt]);const We=(s==null?void 0:s.trim())||"",vt=N.useCallback(($="draft")=>{if(ke)return;const Q=j.trim();if(!Q)return;const Y=$==="refine"&&We?"refine":"draft",ue=Y==="refine"?We:"",oe=We,{runId:xe,runToken:Fe,chatSessionId:Be}=Le();me("inline_draft_started",xe,{attemptCount:0,hasTools:!1,finalOutcome:"drafting"}),te(),Oe(),V(Q),w(""),A(Y),M(ue),O(!1),b({status:"idle"}),G.current+=1,Se([]),R(!0);const Ke=Kn({request:Q,mode:Y,currentSql:oe,selectedTableName:i||"",selectedSchemaName:r||"",selectedDatabaseName:a||""});ye.current={sessionId:Be,message:Ke,runToken:Fe}},[Le,Oe,We,me,ke,j,te,a,r,i,Se]),Tt=N.useCallback($=>{const Q=E.trim();Q&&(c(Q,$),$||R(!1))},[c,E]),rt=E.trim().length>0,Kt=["valid","invalid","error"].includes(F.status),lt=rt&&Kt,yt=F.status==="invalid",Et=F.status==="validating",ot=rt&&D.length>0&&D===j.trim(),it=We.length>0,Ue=j.length>0,ct=ot&&T==="draft",dt=ot&&T==="refine"&&k===We,_e=S==="refine"&&!it?"draft":S,Nt=(_e==="refine"?dt:ct)?"Open composer preview":"Generate composer SQL",Ct=j.trim().length>0||D.trim().length>0||rt||F.status!=="idle"||L.timelineSteps.length>0,It=N.useCallback(($="draft")=>{if(ke)return;if(($==="refine"?dt:ct)&&!P){te(),R(!0);return}vt($)},[ct,dt,vt,ke,P,te]),kt=N.useCallback(()=>{te(),R(!0)},[te]),Ut=N.useCallback($=>{$e("cancelled"),I($)},[$e]),He=N.useCallback(()=>{ke||($e("cancelled"),ne.current=!1,G.current+=1,pe.current="",W.current=0,I(""),V(""),w(""),A("draft"),v("draft"),M(""),O(!1),b({status:"idle"}),Oe(),Se([]),fe($=>({...Wt,runId:$.runId})))},[$e,Oe,ke,Se,fe]),Dt=N.useCallback($=>{$||$e("cancelled"),R($)},[$e]),At=L.timelineSteps.findIndex($=>$===L.activeStep),Ht=L.phase==="self-healing"?"Fixing validation issue":L.phase==="validating"?"Validating SQL":L.activeStep||"Drafting SQL",tt=F.status==="valid"?{label:"Validation passed",className:"border-emerald-500/30 bg-emerald-500/10 text-emerald-700",detail:F.message}:F.status==="invalid"?{label:"Validation failed",className:"border-destructive/40 bg-destructive/10 text-destructive",detail:F.message}:F.status==="error"?{label:"Validation unavailable",className:"border-border/60 bg-muted/20 text-muted-foreground",detail:F.message}:null;return e.jsxs("div",{ref:_,className:"relative flex h-8 min-w-[320px] flex-1 items-center",children:[e.jsx(t.Input,{value:j,onChange:$=>Ut($.target.value),onFocus:kt,onClick:kt,onKeyDown:$=>{$.key==="Enter"&&($.preventDefault(),It(_e))},placeholder:"Type your question...",className:["h-8 border-transparent bg-muted/45 shadow-none focus-visible:border-border focus-visible:bg-background focus-visible:ring-0",Ue?"pr-[60px]":"pr-10"].join(" ")}),e.jsxs(t.Popover,{open:P,onOpenChange:Dt,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:[Ue&&e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"size-6 p-0",onClick:$=>{$.preventDefault(),$e("cancelled"),I("")},disabled:ke,"aria-label":"Clear input",title:"Clear input",children:e.jsx(t.X,{className:"size-3.5"})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"size-6 p-0",onClick:$=>{$.preventDefault(),It(_e)},disabled:ke,"aria-label":Nt,title:Nt,children:e.jsx(Sn,{className:"size-3.5"})})]}),e.jsx(t.PopoverContent,{align:"start",alignOffset:0,side:"bottom",sideOffset:8,className:"w-[min(92vw,var(--radix-popover-trigger-width))] max-w-[760px] p-2.5",onOpenAutoFocus:$=>{$.preventDefault()},onInteractOutside:$=>{var Y;const Q=$.target;Q&&((Y=_.current)!=null&&Y.contains(Q))&&$.preventDefault()},children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Composer"}),D&&e.jsx("p",{className:"line-clamp-2 text-xs text-muted-foreground",children:D})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"inline-flex h-7 items-center rounded-md border border-border/60 bg-background p-0.5 shadow-sm",children:[e.jsx(t.Button,{type:"button",size:"sm",variant:_e==="draft"?"secondary":"ghost",className:["h-6 rounded-[6px] px-2 text-xs",_e!=="draft"?"text-muted-foreground hover:text-foreground":""].join(" "),onClick:()=>{v("draft"),O(!1)},children:"Draft New"}),e.jsx(t.Button,{type:"button",size:"sm",variant:_e==="refine"?"secondary":"ghost",className:["h-6 rounded-[6px] px-2 text-xs",_e!=="refine"?"text-muted-foreground hover:text-foreground":""].join(" "),onClick:()=>v("refine"),disabled:!it,children:"Refine Current"})]}),e.jsx("div",{className:"h-4 w-px bg-border/70"}),ke&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>{$e("stopped")},children:"Stop"}),!ke&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:He,disabled:!Ct,children:"Clear"})]})]}),L.timelineSteps.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[L.timelineSteps.map(($,Q)=>{const Y=$===L.activeStep&&["drafting","validating","self-healing"].includes(L.phase),ue=!Y&&At>=0&&Q<At;return e.jsx("span",{className:["rounded-full border px-2 py-0.5 text-[11px]",Y?"border-foreground/30 bg-foreground/10 text-foreground":ue?"border-border/60 bg-muted/20 text-muted-foreground":"border-border/50 bg-background text-muted-foreground/80"].join(" "),children:Qn($,L.attempt)},`${$}-${Q}`)}),tt&&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]",tt.className].join(" "),children:tt.label})}),e.jsx(t.TooltipContent,{side:"top",align:"start",className:"max-w-[680px] whitespace-pre-wrap break-words text-xs",children:tt.detail})]})})]}),e.jsx("div",{className:"py-0.5",children:e.jsx(t.AssistantContextEntityControls,{mode:"full",compact:!0,inlineLayout:!0,inlineTriggerFirst:!0,triggerVariant:"outline",triggerIconOnly:!1,triggerLabel:"Context",onSelectionChange:je})}),(ke||L.phase==="self-healing"||F.status==="validating")&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border/60 bg-muted/20 px-3 py-2 text-xs text-muted-foreground",children:[e.jsx(t.LoaderCircle,{className:"size-3.5 animate-spin"}),Ht]}),Ge&&e.jsx("div",{className:"rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-xs text-destructive",children:jt}),T==="refine"&&k&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-md border border-border/60 bg-muted/20 px-2.5 py-1.5 text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Refining editor SQL"}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>O($=>!$),children:f?"Hide base SQL":"View base SQL"})]}),f&&e.jsx("div",{className:"max-h-[120px] overflow-auto rounded-md border border-border/60",children:e.jsx(t.CodeHighlighter,{code:k,language:"sql"})})]}),lt?e.jsxs("div",{className:"space-y-1",children:[T==="refine"&&e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Refined SQL"}),e.jsx("div",{className:"max-h-[200px] overflow-auto rounded-md border border-border/60",children:e.jsx(t.CodeHighlighter,{code:E,language:"sql"})})]}):rt?e.jsx("div",{className:"rounded-md border border-dashed border-border/70 px-3 py-2 text-xs text-muted-foreground",children:"Validating SQL draft before preview."}):!ke&&e.jsx("div",{className:"rounded-md border border-dashed border-border/70 px-3 py-2 text-xs text-muted-foreground",children:it?"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-2",children:[e.jsx(t.Button,{variant:"outline",size:"sm",className:"h-8",onClick:o,children:"Open Full Assistant"}),e.jsx(t.Button,{variant:"secondary",size:"sm",className:"h-8",disabled:ke||!lt,onClick:()=>Tt(!1),children:"Replace SQL"}),e.jsx(t.Button,{size:"sm",className:"h-8",disabled:ke||!lt||Et||yt,onClick:()=>Tt(!0),children:"Replace & Run"})]})]})})]})]})}function Wn(){var W,pe;const s=t.useQueryClient(),[n,a]=N.useState(!1),r=t.useEditorStore(Z=>Z.frame),i=t.useEditorStore(Z=>Z.card);t.useEditorStore(Z=>Z.isShowingVisual),t.useEditorStore(Z=>Z.selectedConnectionId),t.useEditorStore(Z=>Z.tempQueryData);const c=t.useEditorStore(Z=>Z.selectedDatabaseName);t.useEditorStore(Z=>Z.selectedDatamodelId);const o=t.useEditorStore(Z=>Z.selectedSchemaName);t.useEditorStore(Z=>Z.showAIDialog);const d=t.useEditorStore(Z=>Z.selectedTableName),{cardFilterValues:l}=t.useCardFilterValues((i==null?void 0:i.id)??""),m=t.useEditorStore(Z=>Z.inlineFilterValuesMap[(i==null?void 0:i.id)??""]),p=N.useMemo(()=>t.findCustomVisualConfigCard(r,i),[r,i]),{manifest:x}=t.useCustomVisual(((W=p==null?void 0:p.customCardPreferences)==null?void 0:W.url)||""),u=N.useMemo(()=>{var Z;return(Z=x==null?void 0:x.visuals)==null?void 0:Z.find(we=>{var U;return we.name===((U=p==null?void 0:p.customCardPreferences)==null?void 0:U.componentName)})},[x,(pe=p==null?void 0:p.customCardPreferences)==null?void 0:pe.componentName]),h=t.resolveMultiInputType(p,u),g=N.useMemo(()=>t.getCustomVisualInputCards({frame:r,configCard:p,isMultiInputVisual:h==="multiple"}),[r,p,h]),y=N.useMemo(()=>{const Z=g.findIndex(we=>(we==null?void 0:we.id)===(i==null?void 0:i.id));return Z<0?-1:t.getSlotIndexForCard(i,Z)},[g,i]),j=N.useMemo(()=>!p||h!=="multiple"||y<0?i.type:t.getEffectiveCardTypeForSlot(i,y,u==null?void 0:u.slots)??i.type,[p,h,y,i,u==null?void 0:u.slots]),I=N.useMemo(()=>j!==i.type?{...i,type:j}:i,[i,j]),D=N.useRef(!0),{setCardCustomCfg:V,setQueryResultColumns:E,setCardSql:w,setTempQueryData:T,setPythonStdOut:A,setCardPreferences:S,setCardType:v,setCardPython:k,setShowAIDialog:M,setCard:f,updateCardInFrame:O}=t.useEditorActions();t.useEditorStore(Z=>Z.onSave),t.useEditorStore(Z=>Z.onClose),t.useEditorStore(Z=>Z.actions.setSqlGen);const F=t.useEditorStore(Z=>Z.runSql),b=t.useEditorStore(Z=>Z.actions.setRunSql),L=t.useEditorStore(Z=>Z.actions.setIsSqlRunning),{data:C,isLoading:P,isFetching:R,isSuccess:B,isError:z,error:_,errorSql:K,queryKey:H,refetch:G,errorMessage:X}=t.useDashboardCardQuery(I);N.useEffect(()=>{if(C&&(C.rowLimitExceeded&&t.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),A((C==null?void 0:C.output)||""),C.records.length>0)){const{dimensionKeys:Z}=t.getKeys(C.records);E(Z)}},[C,E,A]),N.useEffect(()=>{(P||R)&&L(!0),(z||B)&&L(!1),z&&(E([]),A(""))},[P,R,C,A,z,B,L,E,_]),N.useEffect(()=>{F&&(s.getQueryData(H)||G(),b(!1))},[F,G,b,H,s]);const ae=N.useRef(G);ae.current=G,N.useEffect(()=>{if(D.current){D.current=!1;return}ae.current()},[m]);function ee(Z,we){w(Z),we&&b(!0)}function de(){return e.jsxs(t.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(t.ResizablePanel,{id:"1",order:1,defaultSize:n?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(Pn,{})}),n&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),n&&e.jsxs(e.Fragment,{children:[e.jsx(t.ResizableHandle,{withHandle:!0,className:"data-[panel-group-direction=vertical]:ml-2 data-[panel-group-direction=vertical]:mr-6 data-[panel-group-direction=vertical]:w-auto"}),e.jsxs(t.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:[e.jsx("div",{id:"python-container",className:"relative flex w-[99%] pt-0",children:e.jsx(_n,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function ce(){return e.jsx("div",{role:"editor-controls",className:"item-center flex w-full flex-wrap items-center gap-2 py-3 pl-2 pr-6",children:e.jsxs("div",{className:"flex w-full items-center gap-3",children:[e.jsxs(t.Button,{title:"Shift + Enter",disabled:P||R,onClick:()=>{G()},className:"h-8 shrink-0",size:"sm",children:[P||R?e.jsx(t.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(t.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),(C==null?void 0:C.sql)&&!X&&e.jsxs(t.HoverCard,{openDelay:300,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,children:e.jsx(t.Info,{className:"h-4 w-4 shrink-0 cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(t.HoverCardContent,{align:"start",className:"w-[500px] p-0",children:e.jsx(Ma,{sql:C.sql})})]}),e.jsx(De.EditorClearButton,{}),e.jsxs(t.Toggle,{pressed:n,onPressedChange:Z=>a(Z),className:"h-8",size:"sm",variant:"outline",children:[e.jsx(Rn,{className:"mr-2 size-4 text-foreground/70"}),"Python"]}),e.jsx(Yn,{currentSql:i==null?void 0:i.sql,currentPython:i==null?void 0:i.python,selectedDatabaseName:c,selectedSchemaName:o,selectedTableName:d,onApplySql:ee,onOpenFullAssistant:()=>M(!0)}),e.jsx("div",{className:"ml-auto flex shrink-0 items-center gap-3",children:l&&l.length>0&&e.jsxs(t.HoverCard,{openDelay:200,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",className:"h-8 gap-2 px-2",children:[e.jsx(t.Filter,{className:"size-4"}),e.jsx(t.Badge,{className:"h-5 min-w-5 bg-purple-100 px-1.5 text-purple-700 hover:bg-purple-100 dark:bg-purple-950 dark:text-purple-300",children:l.length})]})}),e.jsx(t.HoverCardContent,{className:"mr-4 max-h-[400px] w-[500px] overflow-auto p-0",children:e.jsxs("div",{className:"p-3",children:[e.jsx("div",{className:"mb-2 text-sm font-semibold",children:"Active Dashboard Filters"}),e.jsx(t.CodeHighlighter,{code:JSON.stringify(l,null,2),language:"json"})]})})]})})]})})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsx("div",{className:"relative flex grow overflow-y-scroll",children:de()}),ce()]})}const Xn=[{value:"table",label:"Table",icon:t.Table2},{value:"aggregateTable",label:"Aggregate",icon:t.Layers},{value:"pivotTable",label:"Pivot",icon:t.Grid3x3},{value:"detailTable",label:"Detail",icon:t.List}];function Zn({className:s}){const n=t.useEditorStore(x=>x.card),a=t.useEditorStore(x=>x.frame),r=De.useEffectiveEditorCardType(),{setCard:i,updateCardInFrame:c}=t.useEditorActions(),o=["table","aggregateTable","pivotTable","detailTable"].includes(r),d=t.hasValidCardConfig(n.config),l=t.isCustomVisualConfigCard(n,a.cards);if(!o||!d||l)return null;const m=x=>{if(l)return;const u=x,h=n.config??{},g=p(r,u,h),y={...n,type:u,config:g};i(y),c(y)},p=(x,u,h)=>{var y;if(u==="detailTable"){const j=E=>E==null?void 0:E.toLowerCase().replace(/\s+/g,"").trim(),I=(E,w)=>{const T=[j(E.label),j(E.qualifiedFieldName),j(E.name)].filter(Boolean),A=[j(w.label),j(w.qualifiedFieldName),j(w.name)].filter(Boolean);return T.some(S=>A.includes(S))},D=(h.groupByColumns||[]).map(E=>({...E,role:"detail"})),V=((y=h.sortByColumns)==null?void 0:y.filter(E=>D.some(w=>I(E,w))))??[];return{...h,detailTableBackup:{groupByColumns:h.groupByColumns,metricColumns:h.metricColumns,pivotByColumns:h.pivotByColumns,sortByColumns:h.sortByColumns,rowAggregates:h.rowAggregates,columnAggregates:h.columnAggregates,comparisonType:h.comparisonType},detailColumns:D,groupByColumns:[],metricColumns:[],pivotByColumns:[],sortByColumns:V,rowAggregates:[],columnAggregates:[],comparisonType:"none"}}let g=h;if(x==="detailTable")if(h.detailTableBackup)g={...h,...h.detailTableBackup,detailColumns:[],detailTableBackup:void 0};else{const j=(h.detailColumns||[]).map(I=>({...I,role:"groupby"}));g={...h,groupByColumns:j,detailColumns:[]}}return u==="aggregateTable"?{...g,pivotByColumns:[]}:g};return e.jsx("div",{className:t.cn("flex items-center",s),children:e.jsx(t.RadioGroup,{value:r,onValueChange:m,className:"flex flex-row items-center gap-1 border-b border-border/60",children:Xn.map(x=>{const u=x.icon,h=r===x.value;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(t.RadioGroupItem,{value:x.value,id:`table-type-${x.value}`,className:"peer sr-only"}),e.jsxs(t.Label,{htmlFor:`table-type-${x.value}`,className:t.cn("flex h-8 cursor-pointer items-center justify-center gap-1.5 whitespace-nowrap border-b-2 border-transparent px-2 pb-1 text-xs font-medium transition-colors",h?"border-foreground text-foreground":"text-muted-foreground hover:border-foreground/30 hover:text-foreground"),children:[e.jsx(u,{className:t.cn("h-3.5 w-3.5",h?"opacity-100":"opacity-75")}),x.label]})]},x.value)})})})}function cs({error:s,errorSql:n,errorTitle:a="Unable to load data",onOpenInEditor:r,onDebugWithAssistant:i,onSendFeedback:c,showFeedbackButton:o=!0,className:d}){const[l,m]=N.useState(!1);return e.jsx("div",{className:t.cn("rounded-lg border border-border bg-muted/40 p-4",d),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-amber-500/10 dark:bg-amber-500/20",children:e.jsx(t.TriangleAlert,{className:"h-4 w-4 text-amber-600 dark:text-amber-500"})}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:a}),e.jsxs("div",{className:"relative rounded-md border border-border bg-background p-3",children:[e.jsx(t.CopyButton,{text:s,className:"absolute right-2 top-2 z-10 h-6 w-6"}),e.jsx("div",{className:"max-h-40 overflow-auto pr-10",children:e.jsx("p",{className:"break-all font-mono text-xs text-muted-foreground",children:s})})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n&&e.jsx(t.Collapsible,{open:l,onOpenChange:m,children:e.jsx(t.CollapsibleTrigger,{asChild:!0,children:e.jsx(t.Button,{variant:"outline",size:"sm",className:"h-8",children:l?e.jsxs(e.Fragment,{children:[e.jsx(t.ChevronUp,{className:"mr-1.5 h-3.5 w-3.5"}),"Hide Details"]}):e.jsxs(e.Fragment,{children:[e.jsx(t.ChevronDown,{className:"mr-1.5 h-3.5 w-3.5"}),"Show Details"]})})})}),r&&n&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8",onClick:r,children:[e.jsx(wa,{className:"mr-1.5 h-3.5 w-3.5"}),"Open in Editor"]}),o&&c&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8",onClick:c,children:[e.jsx(t.MessageSquareWarning,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]}),i&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8",onClick:i,children:[e.jsx(fn,{className:"mr-1.5 h-3.5 w-3.5"}),"Debug with Assistant"]})]}),n&&e.jsx(t.Collapsible,{open:l,onOpenChange:m,children:e.jsx(t.CollapsibleContent,{className:"space-y-2",children:e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Query"}),e.jsx(t.CopyButton,{text:n,className:"h-6 w-6"})]}),e.jsx("div",{className:"max-h-80 overflow-auto rounded-md border border-border bg-background p-2",children:e.jsx(t.CodeHighlighter,{code:n,language:"sql"})})]})})})]})]})})}function La(s,n){const a=t.useEditorStore(m=>m.card),r=t.useEditorStore(m=>m.isDevMode),{switchEditorMode:i,setRunSql:c,runAssistant:o}=t.useEditorActions();return{isDevMode:r,handleOpenInEditor:r?void 0:()=>{const m=n||a.sql||a.python||"";i("dev",{sqlToLoad:m}),setTimeout(()=>{c(!0)},100)},handleDebugWithAssistant:r?()=>{const m=`Can you help me debug this query?
177
+
178
+ Error:
179
+
180
+ ${s}
181
+
182
+ Error SQL:
183
+
184
+ ${n||a.sql||a.python}
185
+
186
+ `;o(m)}:void 0}}function Oa({className:s,...n}){var Z,we,U,ne,ye;const a=t.useEditorStore(se=>se.card);t.useEditorStore(se=>se.isDevMode);const r=((Z=a.customCardPreferences)==null?void 0:Z.showCardHeader)??!0,i=((U=(we=a.preferences)==null?void 0:we.displayOptions)==null?void 0:U.showInlineFilterBar)??!0,c=t.useEditorStore(se=>se.frame),o=t.useEditorStore(se=>se.inlineFilterValuesMap[a.id]),d=t.useDashboardStore(se=>se.dashboard.filters),l=t.useDashboardStore(se=>se.selectedSheetId),[m,p]=N.useState(!1),{currentUser:x}=t.useCurrentUserInfo(),{tokenProps:u}=N.useContext(t.SemaphorContext),h=t.useEditorStore(se=>se.actions.setRunSql),g=t.useEditorStore(se=>se.actions.setCardInlineFilterValue),y=t.useEditorStore(se=>se.actions.removeCardInlineFilterValue),{updateFilter:j}=t.useDashboardActions(),I=d==null?void 0:d.find(se=>se.id===c.filterId),D=N.useMemo(()=>t.findCustomVisualConfigCard(c,a),[c,a]),{manifest:V}=t.useCustomVisual(((ne=D==null?void 0:D.customCardPreferences)==null?void 0:ne.url)||""),E=N.useMemo(()=>{var se;return(se=V==null?void 0:V.visuals)==null?void 0:se.find(be=>{var ge;return be.name===((ge=D==null?void 0:D.customCardPreferences)==null?void 0:ge.componentName)})},[V,(ye=D==null?void 0:D.customCardPreferences)==null?void 0:ye.componentName]),w=t.resolveMultiInputType(D,E),T=N.useMemo(()=>t.getCustomVisualInputCards({frame:c,configCard:D,isMultiInputVisual:w==="multiple"}),[c,D,w]),A=N.useMemo(()=>{const se=T.findIndex(be=>(be==null?void 0:be.id)===(a==null?void 0:a.id));return se<0?-1:t.getSlotIndexForCard(a,se)},[T,a]),S=N.useMemo(()=>!D||w!=="multiple"||A<0?a.type:t.getEffectiveCardTypeForSlot(a,A,E==null?void 0:E.slots)??a.type,[D,w,A,a,E==null?void 0:E.slots]),v=S??a.type,k=N.useMemo(()=>v===a.type?a:{...a,type:v},[a,v]),M=N.useMemo(()=>S!==a.type?{...a,type:S}:a,[a,S]),{data:f,isLoading:O,isFetching:F,errorMessage:b,errorSql:L,pagination:C}=t.useDashboardCardQuery(M),{handleOpenInEditor:P,handleDebugWithAssistant:R}=La(b,L||a.sql||a.python),B=N.useMemo(()=>(f==null?void 0:f.records)||[],[f==null?void 0:f.records]),{setCard:z,updateCardInFrame:_}=t.useEditorActions(),{data:K}=t.useTopoJson(k),H=N.useMemo(()=>{var se;return v!=="pivotTable"||!((se=f==null?void 0:f.records)!=null&&se.length)?null:{records:f.records,columnSubtotalMeta:f.columnSubtotalMeta,subtotalColumns:f.subtotalColumns||[],pivotSchema:f.pivotSchema||[],groupByColumns:f.groupByColumns}},[v,f==null?void 0:f.records,f==null?void 0:f.columnSubtotalMeta,f==null?void 0:f.subtotalColumns,f==null?void 0:f.pivotSchema,f==null?void 0:f.groupByColumns]),G=t.usePivotTableConfig(k,H),X=()=>{p(!0)},ae=N.useMemo(()=>{const se=typeof window<"u"?window.location.href:"",be=typeof navigator<"u"?navigator.userAgent:"",ge=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:t.FeedbackCategory.QUERY_GENERATION,user:x,tokenContext:u,systemState:{cardConfig:a.config,dataSource:a.dataSource,dashboardFilters:d,errorMessage:b||void 0,errorSql:L||a.sql||a.python,generatedSql:L||a.sql},metadata:{url:se,userAgent:be,timestamp:new Date().toISOString(),viewport:ge}}},[x,u,a,d,b,L]),ee=(se,be)=>{var fe,Ne;const ge={...a,paginationConfig:{page:se+1,pageSize:be}};z(ge),_(ge),a.sql&&((Ne=(fe=a.preferences)==null?void 0:fe.tablePrefs)!=null&&Ne.enableDevModePagination)&&h(!0)},de=se=>{var fe,Ne,ve,Te,Le;const be=t.sortStateToSortByColumns(se,(fe=a.config)==null?void 0:fe.metricColumns,(Ne=a.config)==null?void 0:Ne.groupByColumns,(ve=a.config)==null?void 0:ve.detailColumns),ge={...a,config:{...a.config||{},sortByColumns:be}};z(ge),_(ge),a.sql&&((Le=(Te=a.preferences)==null?void 0:Te.tablePrefs)!=null&&Le.enableDevModePagination)&&h(!0)},ce=N.useMemo(()=>!k.id||!(f!=null&&f.records)?null:t.createChartConfig({card:k,data:f==null?void 0:f.records,cardType:v,queryConfig:k.queryConfig,customCfg:k.customCfg,preferences:k.preferences,topoJson:K}),[k,f==null?void 0:f.records,v,K]);function W(se){return e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackVisual,children:e.jsx(t.EditorCustomVisual,{card:se})})}function pe(){var se;if(f!=null&&f.records&&(f==null?void 0:f.records.length)===0&&!O&&!F)return b?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(cs,{error:b,errorSql:L||a.sql||a.python,onOpenInEditor:P,onDebugWithAssistant:R,onSendFeedback:X,showFeedbackButton:!0})}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(t.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((O||F)&&(!(f!=null&&f.records)||f.records.length===0))return v==="table"||v==="detailTable"?e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(t.TableSkeleton,{})}):e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!k.id)return null;if(v==="custom")return W(a);if(!["table","pivotTable","aggregateTable","detailTable","custom"].includes(v)&&ce)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:O||F?e.jsx(e.Fragment,{}):e.jsx(t.ChartJsVisual,{cfg:ce})});if(v==="table"||v==="detailTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(t.TableVisual,{card:k,data:B,comparisonMetadata:(se=f==null?void 0:f.metadata)==null?void 0:se.comparisonMetadata,paginationMetadata:C,onPaginationChange:ee,onSortChange:de,isLoading:O||F})});if(v==="pivotTable"&&G)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(t.PivotTableTanstack,{card:k,data:G.data,options:G.options,onAggregationChange:be=>{const ge=t.handleAggregationChange(be,a.config),fe={...a,config:ge};z(fe),_(fe)},onAggregationLabelChange:be=>{const ge=t.handleAggregationLabelChange(be,a.config),fe={...a,config:ge};z(fe),_(fe)}})});if(v==="aggregateTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(t.AggregateTable,{card:k,data:(f==null?void 0:f.records)||[],groupByColumns:f==null?void 0:f.groupByColumns,pivotSchema:f==null?void 0:f.pivotSchema,paginationMetadata:C,onPaginationChange:ee,onAggregationChange:be=>{const ge=t.handleAggregationChange(be,a.config),fe={...a,config:ge};z(fe),_(fe)},isLoading:O||F})})}return e.jsxs(t.Card,{role:"editor-visual-card",className:t.cn("relative flex h-full flex-col rounded-none",s),...n,children:[(O||F)&&(f==null?void 0:f.records)&&f.records.length>0&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),r&&e.jsxs(t.CardHeader,{className:t.cn("flex flex-row items-start justify-between py-4 pr-6","pl-2"),children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.CardTitle,{className:"text-base",children:e.jsx(t.EditableText,{value:a.title,onSave:se=>z({...a,title:se}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(t.InfoHover,{card:a}),e.jsx(De.VisualBadge,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(Zn,{})})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(t.EditableText,{value:(a.description||"").trim(),onSave:se=>z({...a,description:se.trim()}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),I&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Label,{className:"my-1",children:e.jsx(t.EditableText,{value:I.title||I.column,onSave:se=>j({...I,title:se}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(t.FilterComponent,{filter:I})]})]}),i&&a.inlineFilters&&a.inlineFilters.length>0&&e.jsx("div",{className:t.cn("pb-3 pr-6","pl-2"),children:e.jsx(t.InlineFilterBar,{card:a,sheetId:l||"",inlineFilterValues:o,setInlineFilterValue:se=>g(a.id,se),removeInlineFilterValue:se=>y(a.id,se)})}),e.jsxs(t.CardContent,{className:t.cn("flex min-h-0 grow flex-col pr-6","pl-2"),children:[e.jsx("div",{className:"min-h-0 flex-1 grow basis-0",children:pe()}),t.isCardSummaryVisibleOnCard(k)&&e.jsx("div",{className:"pt-3",children:e.jsx(t.CardSummary,{card:k,mode:"editor"})})]}),e.jsx(t.FeedbackDialog,{open:m,onOpenChange:p,feedbackData:ae,showDebugInfo:!0})]})}const Xt=({language:s,value:n,onChange:a,readonly:r})=>e.jsx(t.Ft,{className:"h-full w-full overflow-hidden text-xs",theme:"default",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,lineHeight:16,renderLineHighlight:"none",readOnly:r},defaultLanguage:s,value:n,onChange:a}),er=()=>e.jsxs(t.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(t.DialogTitle,{children:"Customize Card"})}),e.jsxs(t.DialogDescription,{children:["See the configuration options and documentation",e.jsx("a",{target:"_blank",className:"ml-1 text-blue-500 underline",href:"https://www.chartjs.org/docs/latest/samples/bar/vertical.html",children:"here."})]})]}),tr=({customCode:s,cardCustomCfgString:n,mergedConfig:a,onConfigChange:r,onCodeChange:i})=>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(Xt,{language:"json",value:a,onChange:r})}),e.jsx(t.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Xt,{readonly:!0,language:"json",value:n,onChange:()=>{}})}),e.jsx(t.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Xt,{language:"javascript",value:s,onChange:i})})]}),sr=({error:s,hasCardCustomConfig:n,onReset:a,onApply:r,onClose:i})=>e.jsxs(t.DialogFooter,{className:"flex items-center",children:[e.jsx(t.Label,{className:"mr-2 text-red-500",children:s}),e.jsx(t.Button,{disabled:!n,onClick:a,variant:"outline",children:"Reset"}),e.jsx(t.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(t.Button,{onClick:i,variant:"outline",children:"Close"})]});function ar({triggerVariant:s="icon",className:n,label:a="Customize Visual"}={}){const[r,i]=N.useState(!1),[c,o]=N.useState(""),[d,l]=N.useState(""),[m,p]=N.useState(""),[x,u]=N.useState(""),h=t.useEditorStore(k=>k.card),g=De.useEffectiveEditorCardType(),y=t.useEditorStore(k=>k.card.customCfg),j=y?JSON.stringify(y,null,2):"",I=N.useMemo(()=>g!==h.type?{...h,type:g}:h,[h,g]),{data:D}=t.useDashboardCardQuery(I),{data:V}=t.useTopoJson(h),{setCardCustomCfg:E,setCustomVisualCode:w}=t.useEditorActions(),T=k=>{var M,f;return JSON.stringify({...k,data:{...k.data,datasets:(f=(M=k.data)==null?void 0:M.datasets)==null?void 0:f.map(O=>({...O,data:[]}))}},null,2)},A=()=>{var M,f;if(!((M=D==null?void 0:D.records)!=null&&M.length))return;const k=t.createChartConfig({card:h,data:D.records,cardType:h.type,queryConfig:h.queryConfig,preferences:h.preferences,topoJson:V});if(k){o(T(k)),p(((f=h.preferences)==null?void 0:f.customVisualCode)||"");const O=t.merge(k,y);l(T(O))}},S=()=>{try{if(m&&w(m),d){const k=JSON.parse(d),M=t.getObjectDiff(JSON.parse(c),k);E(M),u("")}}catch{u("Invalid JSON configuration")}},v=Object.keys(y||{}).length===0;return e.jsxs(t.Dialog,{open:r,onOpenChange:i,children:[e.jsx(t.DialogTrigger,{asChild:!0,children:s==="menu"?e.jsxs(t.Button,{variant:"ghost",onClick:A,className:t.cn("h-8 w-full justify-start gap-2 px-2 text-sm",v?"":"text-green-600 hover:text-green-700",n),children:[e.jsx(t.Settings,{className:"h-4 w-4"}),e.jsx("span",{children:a})]}):e.jsx(t.IconButton,{tooltip:"Customize Visual",onClick:A,className:t.cn(v?"":"text-green-600 hover:text-green-700",n),children:e.jsx(t.Settings,{className:"h-4 w-4"})})}),e.jsxs(t.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(er,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackVisual,children:e.jsx(Oa,{className:"w-1/2 rounded shadow-none"})}),e.jsx(tr,{customCode:m,cardCustomCfgString:j,mergedConfig:d,onConfigChange:k=>l(k??""),onCodeChange:k=>p(k??"")})]}),e.jsx(sr,{error:x,hasCardCustomConfig:!!y,onReset:()=>{l(c),E(null)},onApply:S,onClose:()=>i(!1)})]})]})}function nr({isStarred:s,onClick:n,className:a}){const r=i=>{i.stopPropagation(),i.preventDefault(),n(i)};return e.jsx("button",{type:"button",onClick:r,className:t.cn("flex items-center justify-center rounded-sm p-0.5 transition-all","hover:bg-muted/80",a),"aria-label":s?"Remove from favorites":"Add to favorites",children:e.jsx(t.Star,{className:t.cn("h-3.5 w-3.5 transition-colors",s?"fill-yellow-400 text-yellow-400":"text-muted-foreground hover:text-foreground")})})}function ia({chartType:s,chartName:n,isCustom:a=!1,pluginName:r,isStarred:i,showStar:c=!0,onSelect:o,onToggleStar:d}){return e.jsxs("button",{onClick:o,className:t.cn("group relative flex flex-col items-center gap-2 rounded-lg border border-border","bg-background p-3 transition-all","hover:border-primary/50 hover:bg-muted/50 hover:shadow-sm"),children:[c&&e.jsx("div",{className:t.cn("absolute left-1 top-1 transition-opacity",i?"opacity-100":"opacity-0 group-hover:opacity-100"),children:e.jsx(nr,{isStarred:i,onClick:()=>d()})}),a&&r&&e.jsx("div",{className:"absolute right-1 top-1",children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center justify-center",children:e.jsx(t.Info,{className:"h-3 w-3 text-muted-foreground"})})}),e.jsx(t.TooltipContent,{side:"top",className:"text-xs",children:r})]})}),e.jsx(t.ChartIcon,{chartType:s,chartName:n,isCustom:a,className:"h-6 w-6"}),e.jsx("span",{title:n,className:"line-clamp-2 text-center text-xs font-medium text-foreground",children:n})]})}const ca=[{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 rr({onChartSelect:s,onClose:n}){const[a,r]=N.useState(""),{starredCharts:i,isStarred:c,toggleStar:o}=t.useStarredChartsStore(),{data:d=[],isLoading:l}=t.useCustomVisualsQuery(),{setCardType:m,setCardPreferences:p,setIsDevMode:x}=t.useEditorStore(v=>v.actions),u=t.useEditorStore(v=>v.card),{setCardCustomCfg:h,setCustomCardPreferences:g,setQueryConfig:y,replaceFrameCards:j,clearModeDrafts:I,initializeModeDrafts:D}=t.useEditorActions(),V=N.useMemo(()=>{if(!a)return ca;const v=a.toLowerCase();return ca.filter(k=>k.name.toLowerCase().includes(v))},[a]),E=N.useMemo(()=>{const v=d.filter(M=>M.componentType==="chart"&&M.pluginType!=="standard");if(!a)return v;const k=a.toLowerCase();return v.filter(M=>M.name.toLowerCase().includes(k))},[d,a]),w=v=>{h(null),p({}),m(v),["custom","text","map"].includes(v)&&(x(!0),y(void 0)),s==null||s(v),n==null||n()},T=v=>{h(null),p({}),y(void 0);const k=t.resolveMultiInputTypeFromVisual(v);if(k==="multiple"&&v.slots&&v.slots.length>0){I();const f=t.createCardsFromSlots(v.slots,v,u);j(f),f[0]&&D(f[0]),n==null||n();return}else m("custom"),g({type:"component",visualType:k,url:v.url,componentName:v.name,icon:v.icon,pluginChartType:v.chartType,minInputs:v.minInputs,maxInputs:v.maxInputs});s==null||s("custom",v),n==null||n()},A=v=>{const k={type:"default",id:v.id,name:v.name};o(k)},S=v=>{const k={type:"custom",id:v.name,url:v.url,icon:v.icon,name:v.name};o(k)};return e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2 rounded-sm border border-border bg-background px-3 py-2",children:[e.jsx(t.Search,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(t.Input$1,{placeholder:"Search charts...",value:a,onChange:v=>r(v.target.value),className:"h-auto border-0 p-0 text-sm focus-visible:ring-0 focus-visible:ring-offset-0"})]}),e.jsxs("div",{className:"max-h-[350px] overflow-y-auto",children:[V.length>0&&e.jsx("div",{className:"mb-3",children:e.jsx("div",{className:"grid grid-cols-3 gap-2",children:V.map(v=>e.jsx(ia,{chartType:v.id,chartName:v.name,isCustom:!1,isStarred:c("default",v.id),onSelect:()=>w(v.id),onToggleStar:()=>A(v)},v.id))})}),E.length>0&&e.jsxs(e.Fragment,{children:[V.length>0?e.jsx(t.Separator,{className:"my-3"}):null,e.jsxs("div",{children:[e.jsx("span",{className:"mb-2 block text-xs font-medium text-muted-foreground",children:"Custom Charts"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:E.map((v,k)=>e.jsx(ia,{chartName:v.name,isCustom:!0,pluginName:v.pluginName,isStarred:c("custom",v.name),onSelect:()=>T(v),onToggleStar:()=>S(v)},`${v.url}-${v.name}-${k}`))})]})]}),l&&e.jsxs(e.Fragment,{children:[e.jsx(t.Separator,{className:"my-3"}),e.jsx("div",{className:"py-4 text-center text-sm text-muted-foreground",children:"Loading custom charts..."})]}),V.length===0&&E.length===0&&!l&&e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No charts found"})]})]})}function lr({selectedChart:s,onChartChange:n}){var T,A,S,v;const a=t.useEditorStore(k=>k.card),r=t.useEditorStore(k=>k.frame),i=t.useEditorStore(k=>k.isDevMode),{replaceFrameCards:c,clearModeDrafts:o,initializeModeDrafts:d,setIsDevMode:l}=t.useEditorActions(),m=N.useMemo(()=>t.findCustomVisualConfigCard(r,a),[r,a]),{manifest:p}=t.useCustomVisual(((T=m==null?void 0:m.customCardPreferences)==null?void 0:T.url)||""),x=N.useMemo(()=>{var k;return(k=p==null?void 0:p.visuals)==null?void 0:k.find(M=>{var f;return M.name===((f=m==null?void 0:m.customCardPreferences)==null?void 0:f.componentName)})},[p,(A=m==null?void 0:m.customCardPreferences)==null?void 0:A.componentName]),u=t.resolveMultiInputType(m,x)==="multiple",h=De.useEffectiveEditorCardType(),g=u?h:s??a.type,y=(S=a==null?void 0:a.customCardPreferences)==null?void 0:S.componentName,j=(v=m==null?void 0:m.customCardPreferences)==null?void 0:v.componentName,I=u&&!!j,D=N.useMemo(()=>{const k=t.chartTypes.find(M=>M.id===g);return k?k.label:g==="custom"?y||"Custom Visual":"Select chart type"},[g,y]),V=N.useMemo(()=>{const k=t.chartTypes.find(M=>M.id===g);if(k){const M=k.icon;return e.jsx(M,{className:"h-4 w-4"})}if(g==="custom"&&y){const M=t.getAutoDetectedChartIcon(y);return M||e.jsx(t.ChartIcon,{chartName:y,isCustom:!0,className:"h-4 w-4"})}return e.jsx(wn,{className:"h-4 w-4"})},[g,y]);return{displayChartType:g,displayLabel:D,displayIcon:V,showBadge:I,badgeLabel:j,isMultiInputContext:u,handleChartSelect:k=>{n==null||n(k)},handleClearCustomVisual:k=>{k.stopPropagation();const M={...a,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};c([M]),o(),d(M),i&&l(!0),n==null||n("bar")}}}function ds({selectedChart:s,onChartChange:n,variant:a="ghost",className:r}){const[i,c]=N.useState(!1),{displayLabel:o,displayIcon:d,showBadge:l,badgeLabel:m,handleChartSelect:p,handleClearCustomVisual:x}=lr({selectedChart:s,onChartChange:n});return e.jsxs("div",{className:t.cn("relative w-full",r),children:[e.jsxs(t.Popover,{open:i,onOpenChange:c,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{size:"sm",variant:a,role:"combobox","aria-expanded":i,className:t.cn("w-full justify-between gap-2",a==="ghost"&&"border border-border/70 bg-background text-foreground/90",a==="outline"&&"border-border/70 bg-background text-foreground/90",a==="secondary"&&"text-foreground"),children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[d,e.jsx("span",{className:"truncate",children:o})]}),e.jsx(t.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-70"})]})}),e.jsx(t.PopoverContent,{className:"w-[360px] p-3",align:"start",onOpenAutoFocus:u=>u.preventDefault(),children:e.jsx(rr,{onChartSelect:u=>p(u),onClose:()=>c(!1)})})]}),l&&e.jsxs("div",{className:"absolute right-10 top-1/2 z-10 flex max-w-[140px] -translate-y-1/2 items-center gap-1 rounded-full border bg-background py-0.5 pl-2 pr-1 text-[10px] text-muted-foreground shadow-sm",title:m,children:[e.jsx(t.Layers,{className:"h-2.5 w-2.5 shrink-0"}),e.jsx("span",{className:"truncate",children:m}),e.jsx("button",{onClick:x,className:"rounded-full p-0.5 hover:bg-muted",title:"Clear custom visual",children:e.jsx(t.X,{className:"h-2.5 w-2.5"})})]})]})}function or(){const s=t.useEditorStore(l=>{var m,p;return(p=(m=l.card.preferences)==null?void 0:m.chartOptions)==null?void 0:p.indexAxis}),n=t.useEditorStore(l=>l.card.type),{setChartOrientation:a,setCardPreferences:r}=t.useEditorStore(l=>l.actions),i=l=>{if(a(l),n!=="bullet")return;const m=l==="y"?"horizontal":"vertical",p=t.useEditorStore.getState().card.preferences,x={...p||{},bulletConfig:{...(p==null?void 0:p.bulletConfig)||{},orientation:m}};r(x)};function c(){const l=s??"x",m=()=>{i(l==="x"?"y":"x")};return e.jsx(t.IconButton,{onClick:m,tooltip:"Chart Orientation",children:l==="x"?e.jsx(Yt,{className:"size-4"}):e.jsx(Jt,{className:"size-4"})})}function o(){const l=()=>{i(s==="y"||s===void 0?"x":"y")};return e.jsx(t.IconButton,{onClick:l,tooltip:"Chart Orientation",children:s==="y"||s===void 0?e.jsx(Yt,{className:"size-4"}):e.jsx(Jt,{className:"size-4"})})}function d(){const l=s??"y",m=()=>{i(l==="y"?"x":"y")};return e.jsx(t.IconButton,{onClick:m,tooltip:"Chart Orientation",children:l==="y"?e.jsx(Jt,{className:"size-4"}):e.jsx(Yt,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?o():n==="bullet"?d():c()})}function us({className:s,triggerVariant:n="icon",label:a="Display Options"}){var y,j,I,D,V,E,w,T,A,S;const r=t.useEditorStore(v=>v.card),{setCardPreferences:i,updateCardInFrame:c,setCard:o}=t.useEditorActions(),[d,l]=N.useState(!1),m=((j=(y=r.preferences)==null?void 0:y.displayOptions)==null?void 0:j.showFilterInfo)??!0,p=((D=(I=r.preferences)==null?void 0:I.displayOptions)==null?void 0:D.showCardToolbar)??!0,x=((E=(V=r.preferences)==null?void 0:V.displayOptions)==null?void 0:E.showChrome)??!0,u=((T=(w=r.preferences)==null?void 0:w.displayOptions)==null?void 0:T.allowScroll)??!0,h=((S=(A=r.preferences)==null?void 0:A.displayOptions)==null?void 0:S.showInlineFilterBar)??!0,g=(v,k)=>{var O;const M={...r.preferences,displayOptions:{...(O=r.preferences)==null?void 0:O.displayOptions,[v]:k}};i(M);const f={...r,preferences:M};o(f),c(f)};return e.jsx("div",{className:t.cn("flex items-center",s),children:e.jsxs(t.DropdownMenu,{modal:!1,open:d,onOpenChange:l,children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:n==="menu"?e.jsxs(t.Button,{variant:"ghost",className:"h-8 w-full justify-start gap-2 px-2 text-sm",children:[e.jsx(t.SlidersHorizontal,{className:"h-4 w-4"}),e.jsx("span",{children:a})]}):e.jsx(t.IconButton,{className:"h-8 w-8 p-0",tooltip:"Display Options",children:e.jsx(t.SlidersHorizontal,{className:"h-4 w-4"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(t.DropdownMenuLabel,{children:"Display Options"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsx("div",{className:"px-2 py-1.5",children:e.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"Changes apply to dashboard view only"})}),e.jsxs(t.DropdownMenuCheckboxItem,{checked:m,onCheckedChange:v=>{g("showFilterInfo",v)},onSelect:v=>v.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Filter Info"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Badge"})]}),e.jsxs(t.DropdownMenuCheckboxItem,{checked:p,onCheckedChange:v=>{g("showCardToolbar",v)},onSelect:v=>v.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Toolbar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Hover actions"})]}),e.jsxs(t.DropdownMenuCheckboxItem,{checked:x,onCheckedChange:v=>{g("showChrome",v)},onSelect:v=>v.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Chrome"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Frame & padding"})]}),e.jsxs(t.DropdownMenuCheckboxItem,{checked:u,onCheckedChange:v=>{g("allowScroll",v)},onSelect:v=>v.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Allow Scroll"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card content scroll"})]}),e.jsxs(t.DropdownMenuCheckboxItem,{checked:h,onCheckedChange:v=>{g("showInlineFilterBar",v)},onSelect:v=>v.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 ms({className:s,triggerVariant:n="icon",label:a="Inline Filters"}){var w,T,A;const[r,i]=N.useState(!1),c=t.useEditorStore(S=>S.card),o=t.useEditorStore(S=>S.selectedConnectionId),{tokenProps:d}=t.useSemaphorContext(),{setCard:l}=t.useEditorActions(),m=t.useDashboardStore(S=>S.actions.removeCardInlineFilterValue),p=t.useDashboardStore(S=>S.actions.setCardInlineFilterValue),x=t.useEditorStore(S=>S.actions.removeCardInlineFilterValue),u=t.useEditorStore(S=>S.actions.setCardInlineFilterValue),h=t.useDashboardStore(S=>S.isVisualEditing),g=(c==null?void 0:c.inlineFilters)||[],y=((T=(w=d==null?void 0:d.params)==null?void 0:w.calendarContext)==null?void 0:T.tz)||((A=d==null?void 0:d.params)==null?void 0:A.timezone)||Intl.DateTimeFormat().resolvedOptions().timeZone;function j(S){var R,B,z,_,K;const v=((z=(B=(R=c==null?void 0:c.dataSource)==null?void 0:R.selectedEntities)==null?void 0:B[0])==null?void 0:z.database)||"",k=S.qualifiedFieldName||S.name;if(g.find(H=>H.column===k))return;const f=S.qualifiedFieldName?S.qualifiedFieldName.split(".").slice(0,-1).join("."):S.qualifiedEntityName||S.entityName,F=t.fmt(S.name),b=t.buildFilterFieldMeta(S),L=t.buildFilterSemanticContext(c==null?void 0:c.dataSource,{connectionId:o||((_=c==null?void 0:c.dataSource)==null?void 0:_.connectionId),connectionType:(K=c==null?void 0:c.dataSource)==null?void 0:K.connectionType}),C=t.isCalculatedFilterField(b),P={id:t.v4(),column:k,title:S.label||S.name,dataType:S.dataType,table:S.entityName||"",database:v,connectionId:o||"",operation:"in",sql:C?"":t.getDefaultFilterSql(S.dataType,f,F),fieldMeta:b,semanticContext:L,width:250};l({...c,inlineFilters:[...g,P]})}function I(S){const v=g.filter(k=>k.id!==S);l({...c,inlineFilters:v}),h?x(c.id,S):m(c.id,S)}function D(S,v){const k=g.map(F=>F.id===S?{...F,...v}:F);if(l({...c,inlineFilters:k}),!(Object.prototype.hasOwnProperty.call(v,"defaultValues")||Object.prototype.hasOwnProperty.call(v,"defaultDateFilter")))return;const f=k.find(F=>F.id===S);if(!f)return;const O=t.buildFilterValueFromDefaults(f,y);O?h?u(c.id,O):p(c.id,O):h?x(c.id,S):m(c.id,S)}if(!["bar","line","pie","doughnut","table","detailTable","stackedBar","stackedLine","horizontalBar","radar","polarArea","scatter","bubble","funnel","aggregateTable","custom"].includes(c==null?void 0:c.type))return null;const E=n==="menu";return e.jsx("div",{className:t.cn("flex items-center gap-1",E&&"w-full",s),children:e.jsxs(t.Popover,{open:r,onOpenChange:i,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:E?e.jsxs(t.Button,{variant:"ghost",className:t.cn("h-8 w-full justify-start gap-2 px-2 text-sm",g.length>0&&"text-primary"),children:[e.jsx(Zs,{className:"h-4 w-4"}),e.jsx("span",{children:a}),g.length>0&&e.jsx("span",{className:"ml-auto inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-primary text-[10px] font-medium leading-none text-primary-foreground",children:g.length})]}):e.jsxs(t.IconButton,{tooltip:"Add Inline Filter",className:t.cn("relative",{"text-primary":g.length>0}),children:[e.jsx(Zs,{className:"h-4 w-4"}),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",E&&"z-[60]"),children:e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"border-b px-4 py-3",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Inline Filters"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"On-card filters for fast, focused exploration."})]}),e.jsx("div",{className:"flex h-[320px] min-h-0 flex-col overflow-hidden",children:e.jsx(t.DndContext,{collisionDetection:t.closestCenter,children:e.jsx(t.SortableContext,{items:[],strategy:t.verticalListSortingStrategy,children:e.jsx(t.FieldsList,{context:"inline-filter",onFieldSelect:j,inlineFilters:g})})})}),g.length>0&&e.jsxs("div",{className:"border-t px-4 py-3",children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Active Filters"}),e.jsx("div",{className:"space-y-1",children:g.map(S=>e.jsx(ir,{filter:S,onUpdate:v=>D(S.id,v),onRemove:()=>I(S.id)},S.id))})]})]})})]})})}function ir({filter:s,onUpdate:n,onRemove:a}){return e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-muted px-2 py-1.5 text-sm",children:[e.jsx("span",{className:"truncate",title:s.column,children:s.title}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(t.CustomFilterPopover,{filter:s,variant:"inline",onAccept:r=>n(r),trigger:e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0",title:"Configure filter",children:e.jsx(t.Settings2,{className:"h-3 w-3"})})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0 hover:bg-destructive/10 hover:text-destructive",onClick:a,children:e.jsx(t.X,{className:"h-3 w-3"})})]})]})}const cr={metric_selector:"Displayed metric",field_selector:"Group by field",aggregation_selector:"Aggregation",grain_selector:"Time grain"};function dr(s,n){return s&&typeof s=="object"&&"label"in s&&typeof s.label=="string"&&s.label.trim().length>0?s.label:n||null}const ur={metric_selector:"config_metric_selector",field_selector:"config_field_selector",aggregation_selector:"config_aggregation",grain_selector:"config_grain"};function Pt(s,n){return`${s}:${n}`}function mr(s,n,a){const r=new Set(a.filter(c=>c.target!=="sql_param").map(c=>Pt(c.controlId,c.target))),i=n.map(c=>{const o=t.getCompatibleBindingTargetOptions({card:s,control:c}).map(p=>p.value),d=ur[c.type],m=[...d?[d]:[],...o.filter(p=>p!==d)].find(p=>!r.has(Pt(c.id,p)));return m?{controlId:c.id,target:m}:null}).find(Boolean);return i?{controlId:i.controlId,target:i.target,mapping:{}}:null}function xr({card:s,dashboardControls:n,bindings:a,onChange:r,availableFieldChoices:i,availableMetricChoices:c,suppressTransientStaleState:o=!1}){const d=[...n,...s.controls||[]],[l,m]=N.useState({}),p=t.extractSqlParamReferences({sql:s.sql,controlBindings:s.controlBindings}),x=t.getBindingTargetSuggestions(s),u=new Set(a.map(V=>Pt(V.controlId,V.target))),h=d.some(V=>t.getCompatibleBindingTargetOptions({card:s,control:V}).some(E=>!u.has(Pt(V.id,E.value)))),g=o?0:a.reduce((V,E)=>{const w=y(E.target),T=Object.values(E.mapping).filter(A=>{const S=E.target==="config_metric_selector"||E.target==="config_field_selector"?typeof A=="string"?A:A==null?void 0:A.id:typeof A=="string"?A:void 0;return typeof S=="string"&&!w.some(v=>v.value===S)}).length;return V+T},0);function y(V){var E,w,T,A;switch(V){case"config_metric_selector":return c?c.filter(S=>!!S.target).map(S=>({value:S.target.id,label:S.target.label||S.option.label,target:S.target})):((w=(E=s.config)==null?void 0:E.metricColumns)==null?void 0:w.map(S=>({value:S.id,label:S.label||S.id,target:S})))||[];case"config_field_selector":return i?i.filter(S=>!!S.target).map(S=>({value:S.target.id,label:S.target.label||S.option.label,target:S.target})):((A=(T=s.config)==null?void 0:T.groupByColumns)==null?void 0:A.map(S=>({value:S.id,label:S.label||S.id,target:S})))||[];case"config_aggregation":return(x.config_aggregation||[]).map(S=>({value:S,label:S}));case"config_grain":return(x.config_grain||[]).map(S=>({value:S,label:S.charAt(0).toUpperCase()+S.slice(1)}));default:return[]}}const j=(V,E)=>{r(a.map((w,T)=>T!==V?w:E(w)))},I=V=>{r(a.filter((E,w)=>w!==V))},D=()=>{const V=mr(s,d,a);V&&r([...a,V])};if(typeof s.sql=="string"&&s.sql.trim().length>0){const V=p.map(({controlId:E,paramId:w})=>{const T=d.find(A=>A.id===E);return T?{id:E,paramId:w,label:T.label,reference:`[[param.${w}]]`}:{id:E,paramId:w,label:E,reference:`[[param.${w}]]`}});return e.jsx("div",{className:"space-y-2",children:V.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]]`."}):V.map(E=>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:E.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:E.reference}),e.jsx(t.CopyButton,{text:E.reference,ariaLabel:`Copy ${E.reference}`})]})]})},`${E.id}:${E.paramId}`))})}return e.jsxs("div",{className:"space-y-4",children:[g>0?e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-950",children:[e.jsx(t.CircleAlert,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{children:[g," ",g===1?"mapping needs":"mappings need"," attention before save. Replace each missing target or choose Not mapped."]})]}):null,a.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."}):a.map((V,E)=>{const w=x[V.target]||[],T=d.find(b=>b.id===V.controlId),A=T?t.ensureManualSource(T):null,S=(A==null?void 0:A.source.kind)==="manual"?A.source.options:[],v=y(V.target),k=Array.from(new Set([...S.map(b=>b.value),...Object.keys(V.mapping)])).map(b=>{const L=S.find(C=>C.value===b);return{value:b,label:(L==null?void 0:L.label)||b}}),M=`${V.controlId}-${V.target}-${E}`,f=l[M]??E===0,O=Object.keys(V.mapping).length,F=T!=null&&T.type?cr[T.type]||T.type:null;return e.jsxs(t.Collapsible,{open:f,onOpenChange:b=>m(L=>({...L,[M]:b})),className:"rounded-md border",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 p-3",children:[e.jsx(t.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-start gap-2 text-left",children:[f?e.jsx(t.ChevronDown,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}):e.jsx(t.ChevronRight,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:(T==null?void 0:T.label)||"Control"}),F?e.jsx(t.Badge,{variant:"secondary",className:"shrink-0 text-[11px] font-normal text-muted-foreground",children:F}):null]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:O>0?`${O} mapped`:"No mappings yet"})]})]})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>I(E),children:e.jsx(t.Trash2,{className:"h-4 w-4"})})]}),e.jsx(t.CollapsibleContent,{className:"space-y-3 border-t px-3 pb-3 pt-2",children:k.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."}):v.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:k.map(b=>{const L=V.mapping[b.value],C=V.target==="config_metric_selector"||V.target==="config_field_selector"?typeof L=="string"?L:L==null?void 0:L.id:typeof L=="string"?L:void 0,P=!o&&typeof C=="string"&&!v.some(z=>z.value===C),R=dr(L,C),B=C&&P?[...v,{value:C,label:"Needs remap",target:L}]:v;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:b.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:C||"__none__",onValueChange:z=>j(E,_=>{if(_.target==="config_metric_selector"){const H={..._.mapping};if(z==="__none__")delete H[b.value];else{const G=B.find(X=>X.value===z);G!=null&&G.target?H[b.value]=G.target:delete H[b.value]}return{..._,mapping:H}}if(_.target==="config_field_selector"){const H={..._.mapping};if(z==="__none__")delete H[b.value];else{const G=B.find(X=>X.value===z);G!=null&&G.target?H[b.value]=G.target:delete H[b.value]}return{..._,mapping:H}}const K={..._.mapping};return z==="__none__"?delete K[b.value]:K[b.value]=z,{..._,mapping:K}}),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"}),B.map(z=>e.jsx(t.SelectItem,{value:z.value,children:z.label},z.value))]})]}),P?e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-amber-700",children:[e.jsx(t.CircleAlert,{className:"h-3 w-3 shrink-0"}),e.jsxs("span",{children:["Needs remap",R?` · Previously: ${R}`:""]})]}):null]})]},`${V.controlId}-${V.target}-${b.value}`)})}),w.length>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Available choices for this card: ",w.join(", ")]})]})})]},M)}),h?e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",onClick:D,children:[e.jsx(t.Plus,{className:"mr-2 h-4 w-4"}),"Add another control response"]}):null]})}const hr=[];function pr({className:s,triggerVariant:n="icon",label:a="Controls"}){var f,O;const{handleOpenChange:r,preventPassiveDismissDuringCreate:i,resolvedOpen:c,setIsCreateFlowActive:o}=De.useCreateFlowOverlayState({}),d=t.useEditorStore(F=>F.card),l=t.useEditorStore(F=>F.frame),m=t.useDashboardStore(F=>F.dashboard),x=t.useDashboardStore(F=>F.dashboard.controls)||hr,{setCard:u,updateCardInFrame:h}=t.useEditorActions(),[g,y]=N.useState(null);N.useEffect(()=>{c&&!g&&(d!=null&&d.id)&&y(d.id)},[d==null?void 0:d.id,c,g]),N.useEffect(()=>{!c&&g!==null&&y(null)},[c,g]);const j=N.useMemo(()=>g?(l==null?void 0:l.cards.find(F=>F.id===g))||((d==null?void 0:d.id)===g?d:void 0):d,[d,l==null?void 0:l.cards,g]),I=(j==null?void 0:j.controls)||[],D=j?t.collectDashboardControlIds(m,{excludeCardId:j.id}):x.map(F=>F.id),V=((j==null?void 0:j.controlBindings)||[]).filter(F=>F.target!=="sql_param"),E=t.buildCardControlUsageById({card:j,controls:I}),w={choices:t.getFieldSelectorChoicesForCard(j),targetMap:Object.fromEntries((((f=j==null?void 0:j.config)==null?void 0:f.groupByColumns)||[]).map(F=>[F.id,F]))},T={choices:t.getMetricSelectorChoicesForCard(j),targetMap:Object.fromEntries((((O=j==null?void 0:j.config)==null?void 0:O.metricColumns)||[]).map(F=>[F.id,F]))},A=w.choices.map(F=>({option:F,target:w.targetMap[F.value]})),S=T.choices.map(F=>({option:F,target:T.targetMap[F.value]})),v=(F,b)=>{if(!j)return;const L=(b==null?void 0:b.type)==="rename"?t.applyControlMutationToCard(j,{type:"rename",oldId:b.oldId,newId:b.newId}):(b==null?void 0:b.type)==="remove"?t.applyControlMutationToCard(j,{type:"remove",controlId:b.controlId}):j,C={...L,controls:F,controlBindings:t.syncStructuralBindingsWithControls(L.controlBindings,F)};h(C),(d==null?void 0:d.id)===C.id&&u(C)},k=F=>{if(!j)return;const b={...j,controlBindings:t.mergeConfigBindingsWithSqlParamBindings(F,j.controlBindings)};h(b),(d==null?void 0:d.id)===b.id&&u(b)},M=n==="menu";return e.jsx("div",{className:t.cn("flex items-center gap-1",M&&"w-full",s),children:e.jsxs(t.Popover,{modal:!0,open:c,onOpenChange:r,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:M?e.jsxs(t.Button,{variant:"ghost",className:t.cn("h-8 w-full justify-start gap-2 px-2 text-sm",(I.length>0||V.length>0)&&"text-primary"),children:[e.jsx(t.SlidersHorizontal,{className:"h-4 w-4"}),e.jsx("span",{children:a}),I.length+V.length>0&&e.jsx("span",{className:"ml-auto inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-primary text-[10px] font-medium leading-none text-primary-foreground",children:I.length+V.length})]}):e.jsxs(t.IconButton,{tooltip:"Configure Controls",className:t.cn("relative",{"text-primary":I.length>0||V.length>0}),children:[e.jsx(t.SlidersHorizontal,{className:"h-4 w-4"}),I.length+V.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:I.length+V.length})]})}),e.jsxs(t.PopoverContent,{className:"flex max-h-[85vh] w-[560px] max-w-[95vw] flex-col",align:"end",onEscapeKeyDown:i,onPointerDownOutside:i,children:[e.jsxs("div",{className:"space-y-1 border-b pb-4",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Card-only controls"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add controls that belong only to this card, or decide how this card should respond to shared dashboard controls."}),j!=null&&j.sql?e.jsx("p",{className:"text-xs text-muted-foreground",children:"SQL cards reference controls explicitly with syntax like `[[param.wac_type]]`."}):null]}),e.jsx("div",{className:"flex-1 overflow-y-auto pt-5",children:e.jsxs("div",{className:"space-y-5 pr-1",children:[e.jsx(De.ControlDefinitionListEditor,{scope:"card",card:j,controls:I,reservedControlIds:D,usageByControlId:E,availableFieldChoices:A,availableMetricChoices:S,onCreateFlowActiveChange:o,onChange:(F,b,L)=>v(F,L),emptyMessage:"No card-scoped controls yet."}),e.jsxs("div",{className:"space-y-1 border-t pt-4",children:[e.jsx("h4",{className:"text-sm font-medium",children:"How this card uses controls"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Choose what each control changes in this card."})]}),j?e.jsx(xr,{card:j,dashboardControls:x,bindings:V,onChange:k,availableFieldChoices:A,availableMetricChoices:S}):null]})})]})]})})}function Fa({showOrientation:s=!0,showGridStyle:n=!0,showInlineFilters:a=!0,showControls:r=!0,showDisplayOptions:i=!0}={}){const c=t.useEditorStore(h=>h.card),o=t.useEditorStore(h=>{var g,y;return(y=(g=h.card)==null?void 0:g.preferences)==null?void 0:y.chartOptions}),d=t.getChartGridStyle(o),{setChartGrid:l}=t.useEditorActions();function m(){const h=["xy","none","x","y"],y=(h.indexOf(d)+1)%h.length;l(h[y])}const p=s&&["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel","bullet"].includes(c.type),x=n&&!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(c.type);return p||x||a||r||i?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[p&&e.jsx(e.Fragment,{children:e.jsx(or,{})}),x&&e.jsxs(t.IconButton,{tooltip:"Grid Style",onClick:m,children:[(d==="xy"||!d)&&e.jsx(t.Grid3x3,{className:"size-4"}),d==="x"&&e.jsx(is,{className:"size-4"}),d==="y"&&e.jsx(Vt,{className:"size-4"}),d==="none"&&e.jsx(t.Square,{className:"size-4"})]}),a&&e.jsx(ms,{}),r&&e.jsx(pr,{}),i&&e.jsx(us,{})]}):null}function fr({visible:s}){const n=t.useDashboardStore(o=>o.selectedFrameId),a=t.useManagementStore(o=>o.selectedVisual),r=t.useEditorStore(o=>o.frame),c=!!!(r!=null&&r.visualId||a!=null&&a.id)&&!!n;return!s||c?null:e.jsx("div",{className:"mb-2 flex",children:e.jsx(De.VisualBadge,{showLabel:!0,className:"h-6 w-fit px-2 py-0.5 text-[11px]"})})}function gr({isPreviewMode:s,onPreviewToggle:n,configCard:a}){var F,b,L,C,P;const r=t.useEditorStore(R=>R.frame),i=t.useEditorStore(R=>R.card),{setFrame:c,setActiveTabCardId:o,setCard:d,updateCardInFrame:l,clearModeDrafts:m,initializeModeDrafts:p}=t.useEditorActions(),{manifest:x}=t.useCustomVisual(((F=a==null?void 0:a.customCardPreferences)==null?void 0:F.url)||""),u=(b=x==null?void 0:x.visuals)==null?void 0:b.find(R=>{var B;return R.name===((B=a==null?void 0:a.customCardPreferences)==null?void 0:B.componentName)}),g=t.resolveMultiInputType(a,u)==="multiple",y=(u==null?void 0:u.minInputs)??((L=a==null?void 0:a.customCardPreferences)==null?void 0:L.minInputs)??1,j=(u==null?void 0:u.maxInputs)??((C=a==null?void 0:a.customCardPreferences)==null?void 0:C.maxInputs),I=N.useMemo(()=>t.getCustomVisualInputCards({frame:r,configCard:a,isMultiInputVisual:g}),[r,a,g]),D=g?I.filter(Boolean).length:r.cards.length,V=j?D<j:!0,E=D>Math.max(y||1,1),w=!!((P=a==null?void 0:a.customCardPreferences)!=null&&P.dataInputCardIds),T=(R,B)=>{R.dataTransfer.setData("tabIndex",B.toString())},A=R=>{R.preventDefault()},S=(R,B)=>{const z=R.dataTransfer.getData("tabIndex");if(z===B.toString())return;const _=Array.from(r.cards),[K]=_.splice(parseInt(z),1);_.splice(B,0,K),c({...r,cards:_})};function v(R){const B=(a==null?void 0:a.id)===R;if(!(w&&B?r.cards.length>1:E))return;let _=r.cards.filter(X=>X.id!==R);g&&!w&&(_=t.reindexSlotCards(_));const K=_[0],H={...r,cards:_,activeCardId:K.id},G=R===i.id;G&&m(),c(H),o(K.id),d(K),G&&p(K)}function k(R,B){if(!V)return;const z={...r,cards:[...r.cards,B],activeCardId:R.id};c(z),o(B.id)}function M(){if(g&&(a==null?void 0:a.id)===i.id){f(i);return}const R={...i,id:t.v4(),title:`${i.title} Copy`,tabTitle:`${i.tabTitle||i.title} Copy`,customCardPreferences:i.customCardPreferences?{...i.customCardPreferences,slotIndex:g?Math.max(-1,...I.map((B,z)=>t.getSlotIndexForCard(B,z)))+1:i.customCardPreferences.slotIndex}:void 0};k(i,R)}function f(R){var G;if(!V)return;let B=g?"table":"bar",z="Title",_="";const K=g?Math.max(-1,...I.map((X,ae)=>t.getSlotIndexForCard(X,ae)))+1:D;if(g&&((G=u==null?void 0:u.slots)!=null&&G.length)){const X=t.getSlotDefinitionForIndex(u.slots,K);X&&(B=t.getSlotExpectedChartType(X),z=X.label||`Tab ${K+1}`,_=X.description||"")}const H={dataSource:R.dataSource,connectionId:R.connectionId,lastSelectedDatabase:R.lastSelectedDatabase,lastSelectedSchema:R.lastSelectedSchema,lastSelectedTable:R.lastSelectedTable,lastSelectedDatamodelId:R.lastSelectedDatamodelId,id:t.v4(),title:z,tabTitle:z,description:_,preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:B,sql:"",data:[],mode:"explorer",...g&&{customCardPreferences:{slotIndex:K}}};k(R,H)}function O(R,B){return R.cards.length===1&&(B.displayTab===!0||B.displayTab===void 0)||R.activeCardId!==B.id&&(B.displayTab===!0||B.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const z=B.displayTab===void 0?!1:!B.displayTab;d({...B,displayTab:z}),l({...B,displayTab:z})},children:B.displayTab===!0||B.displayTab===void 0?e.jsx(t.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(t.EyeOff,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(t.TabsList,{className:"group ml-2 mr-6 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[r.cards.map((R,B)=>{var G,X;const z=g?t.getSlotIndexForCard(R,B):-1,_=g&&((G=u==null?void 0:u.slots)!=null&&G.length)&&z>=0?t.getSlotDefinitionForIndex(u.slots,z):null,K=_?(Array.isArray(_.expectedType)?_.expectedType[0]:_.expectedType)||"table":R.type,H=g&&((X=u==null?void 0:u.slots)==null?void 0:X.length)&&u.slots.every(ae=>typeof ae.position=="number"||typeof ae.position=="string"&&!ae.position.includes("+"));return e.jsxs(t.TabsTrigger,{draggable:!g,onDragStart:g?void 0:ae=>T(ae,B),onDragOver:g?void 0:A,onDrop:g?void 0:ae=>S(ae,B),className:"",value:R.id,children:[g&&_?e.jsx(t.TooltipProvider,{delayDuration:0,children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:t.getChartIconByType(K,"size-3.5")}),e.jsx("span",{children:_.label||`Tab ${z+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:_.label}),_.description&&e.jsx("p",{className:"whitespace-normal break-words text-xs text-muted-foreground",children:_.description}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[_.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(_.expectedType)?_.expectedType.join(" / "):_.expectedType}),_.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:[O(r,R),e.jsx(t.Editable,{enabled:r.activeCardId===R.id,text:R.tabTitle||R.title,onSave:ae=>{d({...i,tabTitle:ae}),l({...i,tabTitle:ae})},children:R.tabTitle||R.title},R.id)]}),r.activeCardId===R.id&&!H&&e.jsx(t.CopyPlus,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:ae=>{ae.stopPropagation(),M()}}),r.activeCardId===R.id&&(w&&(a==null?void 0:a.id)===R.id?r.cards.length>1:E)&&e.jsx(t.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>v(R.id)})]},R.id)}),e.jsx(t.IconButton,{tooltip:"Add Card",className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",onClick:()=>f(i),disabled:!V,children:e.jsx(t.Plus,{className:"h-4 w-4"})}),g&&e.jsxs(t.Toggle,{pressed:s,onPressedChange:n,size:"sm",className:"ml-2 h-8 gap-1 px-2 data-[state=on]:bg-background data-[state=on]:text-foreground","aria-label":"Toggle preview",children:[s?e.jsx(t.EyeOff,{className:"h-4 w-4"}):e.jsx(t.Eye,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Preview"})]})]})})}function ls(){var fe,Ne,ve,Te,Le;const s=t.useEditorStore(te=>te.frame),n=t.useEditorStore(te=>te.card),[a,r]=N.useState(!1),i=N.useMemo(()=>t.findCustomVisualConfigCard(s,n),[s,n]),c=t.useEditorStore(te=>te.isSqlRunning);t.useEditorStore(te=>te.isDevMode);const{setFrame:o,setActiveTabCardId:d,setCard:l,setRunSql:m,mergeDraftsIntoCard:p,clearModeDrafts:x,initializeModeDrafts:u}=t.useEditorActions(),[h,g]=N.useState({}),[y,j]=N.useState(()=>new Set),{theme:I}=t.useTheme(),D=t.useDashboardStore(te=>te.themeStyle),{authToken:V}=t.useSemaphorContext(),E=t.getTokenParams(V==null?void 0:V.accessToken),w={mode:I||"system",colors:((Ne=(fe=D==null?void 0:D.chart)==null?void 0:fe.dataset)==null?void 0:Ne.backgroundColor)||[]},{getCard:T,manifest:A,isLoading:S}=t.useCustomVisual(((ve=i==null?void 0:i.customCardPreferences)==null?void 0:ve.url)||""),v=(Te=i==null?void 0:i.customCardPreferences)==null?void 0:Te.componentName,k=v?T(v):null,M=(Le=A==null?void 0:A.visuals)==null?void 0:Le.find(te=>te.name===v),f=t.resolveMultiInputType(i,M),O=a&&f==="multiple"&&!!i,F=N.useMemo(()=>t.getCustomVisualInputCards({frame:s,configCard:i,isMultiInputVisual:!0}).map(je=>(je==null?void 0:je.id)===n.id?n:je),[s,i,n]),b=N.useMemo(()=>t.buildSlotOrderedCards(F),[F]),L=N.useMemo(()=>{const te=F.findIndex(je=>(je==null?void 0:je.id)===n.id);return te<0?-1:t.getSlotIndexForCard(n,te)},[F,n]),C=N.useMemo(()=>!i||f!=="multiple"||L<0?n.type:t.getEffectiveCardTypeForSlot(n,L,M==null?void 0:M.slots)??n.type,[i,f,L,n,M==null?void 0:M.slots]),P=N.useMemo(()=>O?{...n,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:C!==n.type?{...n,type:C}:n,[n,C,O]),{data:R,isLoading:B,isFetching:z,isError:_}=t.useDashboardCardQuery(P),K=N.useCallback((te,je)=>{const me=t.normalizeMultiInputPayload(je);g(Ee=>({...Ee,[te]:me}))},[]),H=N.useCallback((te,je)=>{j(me=>{const Ee=new Set(me);return je?Ee.add(te):Ee.delete(te),Ee})},[]),G=y.size>0,X=t.useInteractionStore(te=>te.interactionStates),ae=t.useDashboardStore(te=>{var je;return(je=te.dashboard)==null?void 0:je.id}),ee=t.useDashboardStore(te=>te.dashboard.filters),de=t.useDashboardStore(te=>te.filterValues),ce=t.useDashboardStore(te=>te.selectedSheetId),W=t.useEditorStore(te=>te.inlineFilterValuesMap[(i==null?void 0:i.id)||""]),pe=t.useEditorStore(te=>te.actions.setCardInlineFilterValue),Z=t.useEditorStore(te=>te.actions.removeCardInlineFilterValue),we=N.useMemo(()=>i?t.buildInlineFilterNodes({card:i,sheetId:ce||"",inlineFilterValues:W,setInlineFilterValue:te=>pe(i.id,te),removeInlineFilterValue:te=>Z(i.id,te)}):[],[i,ce,W,pe,Z]),{cardFilters:U,cardFilterValues:ne}=N.useMemo(()=>i?t.calculateContextAwareFilters({card:i,interactionStates:X,currentDashboardId:ae,filters:ee,filterValues:de,selectedSheetId:ce}):{cardFilters:[],cardFilterValues:[]},[i,X,ae,ee,de,ce]);function ye(te){const je=s.cards.find(me=>me.id===te);je&&(p(),se(te),d(te),x(),u(je))}function se(te){const je=t.useEditorStore.getState().card,me=t.useEditorStore.getState().frame,Ee={...me,cards:me.cards.map(Re=>Re.id===je.id?je:Re),activeCardId:te};o(Ee);const he=Ee.cards.find(Re=>Re.id===te);he.sql&&m(!0),l(he)}function be(){if(S)return e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading manifest"})});if(!k)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 je=b.map((me,Ee)=>t.getEffectiveCardTypeForSlot(me,Ee,M==null?void 0:M.slots));return e.jsxs("div",{className:"relative flex h-full flex-col pl-2 pr-4",children:[F.map((me,Ee)=>{if(!me)return null;const he=t.getSlotIndexForCard(me,Ee),Re=t.getEffectiveCardTypeForSlot(me,he,M==null?void 0:M.slots);return e.jsx(t.MultiInputEmptyRenderer,{onLoadingStatus:H,onDataChange:K,card:me,effectiveCardType:Re},`${me.id}-${he}`)}),G&&e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/50",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading preview"})}),e.jsx("div",{className:t.cn("flex h-full min-h-0 flex-1 flex-col gap-2",G&&"opacity-50"),children:e.jsx(N.Suspense,{fallback:e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(t.LoadingDots,{size:"md",color:"muted"})}),children:e.jsx(k,{editing:!0,...t.buildMultiInputCustomVisualProps({configCard:i,slotOrderedCards:b,slotTypes:je,multiInputData:h,params:E,theme:w,filters:U,filterValues:[...ne||[],...W||[]],inlineFilters:we})})})})]})}function ge(){var te;return O?be():n.type==="kpi"?B||z?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"w-1/2 space-y-3",children:[e.jsx(fr,{visible:!0}),e.jsx("div",{className:"rounded-md border border-border",children:e.jsx(t.KPICard,{card:n,data:R==null?void 0:R.records,isPending:B||z,isError:_,comparisonMetadata:(te=R==null?void 0:R.metadata)==null?void 0:te.comparisonMetadata})}),t.isCardSummaryVisibleOnCard(n)&&e.jsx(t.CardSummary,{card:n,mode:"editor"})]})}):n.type==="text"?B||z?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(t.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(t.TextCard,{isLoading:c,card:n,data:R==null?void 0:R.records})})})}):e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackVisual,children:e.jsx(Oa,{className:"grow border-none shadow-none"})})}return e.jsxs(t.Tabs,{onValueChange:ye,value:s.activeCardId,className:"flex grow flex-col gap-2",children:[O?e.jsx("div",{className:"mt-0 grow",children:ge()}):s.cards.map(te=>e.jsx(t.TabsContent,{className:"mt-0 grow focus-visible:ring-0 focus-visible:ring-offset-0",value:te.id,children:ge()},te.id)),e.jsx(gr,{isPreviewMode:O,onPreviewToggle:r,configCard:i})]})}function da({children:s,visualAsideControl:n}){var z;const a=t.useEditorStore(_=>_.frame),r=t.useEditorStore(_=>_.card),i=r.type==="table"||r.type==="detailTable",c=t.useEditorStore(_=>_.isDevMode),o=t.useEditorStore(_=>_.isShowingVisual),d=t.useEditorStore(_=>_.actions.setIsShowingVisual),l=t.useDashboardStore(_=>_.isVisualEditing),{isConsoleMode:m}=t.useDashboardPreferences(),p=t.useEditorStore(_=>_.pythonStdOut),x=t.useEditorStore(_=>_.actions.setRunSql),u=De.useEffectiveEditorCardType(),{setFrame:h,setCard:g,setActiveTabCardId:y,setCardPreferences:j,mergeDraftsIntoCard:I,clearModeDrafts:D,initializeModeDrafts:V}=t.useEditorActions(),E=N.useMemo(()=>u!==r.type?{...r,type:u}:r,[r,u]),{data:w,isLoading:T,isFetching:A,errorMessage:S,errorSql:v,refetch:k,pagination:M}=t.useDashboardCardQuery(E),{handleDebugWithAssistant:f}=La(S,v),O=N.useMemo(()=>(w==null?void 0:w.records)||[],[w==null?void 0:w.records]),[F,b]=N.useState(!1);N.useEffect(()=>{A||b(!1)},[A]),N.useEffect(()=>{i&&!o&&d(!0)},[i,o,d]);function L(_,K){var X,ae;const H={...r,paginationConfig:{page:_+1,pageSize:K}};g(H);const G={...a,cards:a.cards.map(ee=>ee.id===r.id?H:ee)};h(G),r.sql&&((ae=(X=r.preferences)==null?void 0:X.tablePrefs)!=null&&ae.enableDevModePagination)&&x(!0)}function C(_){var X,ae,ee,de,ce;const K=t.sortStateToSortByColumns(_,(X=r.config)==null?void 0:X.metricColumns,(ae=r.config)==null?void 0:ae.groupByColumns,(ee=r.config)==null?void 0:ee.detailColumns),H={...r,config:{...r.config||{},sortByColumns:K}};g(H);const G={...a,cards:a.cards.map(W=>W.id===r.id?H:W)};h(G),r.sql&&((ce=(de=r.preferences)==null?void 0:de.tablePrefs)!=null&&ce.enableDevModePagination)&&x(!0)}function P(){var K;const _=JSON.stringify(w==null?void 0:w.records,null,2);typeof navigator>"u"||!((K=navigator.clipboard)!=null&&K.writeText)||navigator.clipboard.writeText(_).catch(H=>{console.error("Failed to copy JSON",H)})}function R(){const _=JSON.stringify(w==null?void 0:w.records,null,2),K=new Blob([_],{type:"application/json"}),H=URL.createObjectURL(K),G=document.createElement("a");G.href=H,G.download=`${r.title}.json`,G.click()}function B(){const K=[Object.keys(w==null?void 0:w.records.reduce((ae,ee)=>({...ae,...ee}),{})).join(","),...((w==null?void 0:w.records)||[]).map(ae=>Object.values(ae).join(","))].join(`
187
+ `),H=new Blob([K],{type:"text/csv"}),G=URL.createObjectURL(H),X=document.createElement("a");X.href=G,X.download=`${r.title}.csv`,X.click()}return r?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 pl-2 pr-6",children:[o&&e.jsx("div",{className:"flex grow items-center",children:e.jsxs("div",{className:"flex items-center gap-3",children:[(n==null?void 0:n.show)&&e.jsx(t.IconButton,{tooltip:n.isOpen?"Hide Visual Aside":"Show Visual Aside",className:"h-9 w-9 px-0",buttonProps:{variant:"outline"},onClick:n.onToggle,children:n.isOpen?e.jsx(t.ChevronLeft,{className:"size-4"}):e.jsx(t.ChevronRight,{className:"size-4"})}),e.jsx("div",{className:"w-[200px]",children:e.jsx(ds,{variant:c?"secondary":"ghost"})})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[s,e.jsx(t.IconButton,{tooltip:"Refresh",disabled:T||A,onClick:()=>{b(!0),k()},children:e.jsx(t.RefreshCcw,{className:t.cn("h-4 w-4",{"animate-spin":F})})}),e.jsx(Fa,{showInlineFilters:!1,showDisplayOptions:!1}),(c||m)&&e.jsxs(e.Fragment,{children:[!i&&e.jsx(vr,{}),i&&e.jsx(br,{})]}),e.jsxs(t.DropdownMenu,{modal:!1,children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"More Options",className:"h-8 w-8 px-0","aria-label":"More options",children:e.jsx(t.EllipsisVertical,{className:"size-4"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(t.DropdownMenuLabel,{children:"More Options"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs("div",{className:"px-1 py-1",children:[!["table","detailTable","custom"].includes(r.type)&&l&&e.jsx(ar,{triggerVariant:"menu",className:"w-full"}),e.jsx(ms,{triggerVariant:"menu",className:"w-full"}),e.jsx(us,{triggerVariant:"menu",className:"w-full"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.Button,{variant:"ghost",className:"h-8 w-full justify-start gap-2 px-2 text-sm",onClick:B,children:[e.jsx(t.Download,{className:"h-4 w-4"}),e.jsx("span",{children:"Download CSV"})]}),e.jsxs(t.Button,{variant:"ghost",className:"h-8 w-full justify-start gap-2 px-2 text-sm",onClick:R,children:[e.jsx(hn,{className:"h-4 w-4"}),e.jsx("span",{children:"Download JSON"})]}),e.jsxs(t.Button,{variant:"ghost",className:"h-8 w-full justify-start gap-2 px-2 text-sm",onClick:P,children:[e.jsx(t.Copy,{className:"h-4 w-4"}),e.jsx("span",{children:"Copy JSON"})]})]})]})]})]})]}),o?e.jsx(ls,{}):e.jsxs(t.ResizablePanelGroup,{className:"py-2 pl-2 pr-6",direction:"horizontal",children:[p&&e.jsxs(e.Fragment,{children:[e.jsx(t.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:p&&e.jsx(jr,{})}),e.jsx(t.ResizableHandle,{})]}),e.jsxs(t.ResizablePanel,{id:"2",order:2,minSize:10,className:t.cn("relative flex h-full min-h-0 w-full flex-1 basis-0",{"py-2 pl-2 pr-6":p}),children:[(w==null?void 0:w.records)&&(w==null?void 0:w.records.length)>0&&e.jsx(t.TableVisual,{card:r,data:O,comparisonMetadata:(z=w==null?void 0:w.metadata)==null?void 0:z.comparisonMetadata,paginationMetadata:M,onPaginationChange:L,onSortChange:C,isLoading:T||A}),S&&e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(cs,{error:S,errorSql:v||r.sql||r.python,onDebugWithAssistant:f,showFeedbackButton:!1})})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function jr(){const s=t.useEditorStore(a=>a.pythonStdOut);if(!s)return null;const n=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:n}}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function br(){var c,o,d,l,m,p;const s=t.useEditorStore(x=>x.card),n=t.useEditorStore(x=>x.actions.setCard),a=t.useEditorStore(x=>x.actions.setRunSql),r=t.useEditorStore(x=>x.actions.setCardPreferences),i=t.useEditorStore(x=>x.actions.updateCardInFrame);return s.type!=="table"&&s.type!=="detailTable"?null:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Checkbox,{id:"dev-pagination",checked:((o=(c=s.preferences)==null?void 0:c.tablePrefs)==null?void 0:o.enableDevModePagination)??!1,onCheckedChange:x=>{var u;r({...s.preferences,tablePrefs:{...(u=s.preferences)==null?void 0:u.tablePrefs,enableDevModePagination:x}})}}),e.jsx(t.Label,{htmlFor:"dev-pagination",className:"cursor-pointer text-sm",children:"Paginate"}),((l=(d=s.preferences)==null?void 0:d.tablePrefs)==null?void 0:l.enableDevModePagination)&&e.jsxs(t.Select,{value:String(((p=(m=s.preferences)==null?void 0:m.tablePrefs)==null?void 0:p.pageSize)||50),onValueChange:x=>{var g,y,j;const u=Number(x),h={...s,preferences:{...s.preferences,tablePrefs:{...(g=s.preferences)==null?void 0:g.tablePrefs,pageSize:u}},paginationConfig:{page:1,pageSize:u}};n(h),i(h),s.sql&&((j=(y=s.preferences)==null?void 0:y.tablePrefs)!=null&&j.enableDevModePagination)&&a(!0)},children:[e.jsx(t.SelectTrigger,{className:"h-8 w-20",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"10",children:"10"}),e.jsx(t.SelectItem,{value:"25",children:"25"}),e.jsx(t.SelectItem,{value:"50",children:"50"}),e.jsx(t.SelectItem,{value:"100",children:"100"}),e.jsx(t.SelectItem,{value:"500",children:"500"}),e.jsx(t.SelectItem,{value:"1000",children:"1000"})]})]})]})}function vr(){const s=t.useEditorStore(a=>a.isShowingVisual),n=t.useEditorStore(a=>a.actions.setIsShowingVisual);return e.jsxs(t.Toggle,{pressed:!s,onPressedChange:a=>{n(!a)},variant:"default",size:"sm",className:"h-8 gap-2 border border-transparent 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-4 w-4"}),e.jsx("span",{className:"text-sm",children:"Results"})]})}function Ve({value:s,onCommit:n,type:a="text",placeholder:r,className:i}){const[c,o]=N.useState(s),d=N.useRef(!1);N.useEffect(()=>{o(s)},[s]);const l=()=>{if(d.current){d.current=!1;return}c!==s&&n(c)},m=p=>{if(p.key==="Enter"){p.currentTarget.blur();return}p.key==="Escape"&&(d.current=!0,o(s),p.currentTarget.blur())};return e.jsx(t.Input,{type:a,placeholder:r,value:c,onChange:p=>o(p.target.value),onBlur:l,onKeyDown:m,className:i})}function Xe({defaultValue:s,label:n,options:a,value:r,onValueChange:i,className:c,icon:o,showPlaceholderLabel:d=!0}){return e.jsxs(t.Select,{defaultValue:s,value:r,onValueChange:i,children:[e.jsx(t.SelectTrigger,{className:t.cn("w-full focus:ring-0 focus:ring-offset-0",c),children:e.jsxs("div",{className:"flex items-center gap-2",children:[o&&e.jsx("span",{children:o}),d&&e.jsx(t.SelectValue,{placeholder:n})]})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:n}),a.map(l=>e.jsx(t.SelectItem,{value:l.value,children:l.label},l.value))]})})]})}function yr(s,n){return t.getSlotDefinitionForIndex(s,n)||null}function St(s){if(typeof s=="number")return`Tab ${s+1}`;const n=s.match(/^(\d+)-(\d+)$/);if(n){const[,r,i]=n;return`Tabs ${Number(r)+1}-${Number(i)+1}`}const a=s.match(/^(\d+)\+$/);return a?`Tabs ${Number(a[1])+1}+`:`Tab ${s}`}function Nr(s){return s?Array.isArray(s)?s:[s]:[]}function Zt(s){var r,i;if(!s)return!1;if(s.type==="text")return!!((r=s.description)!=null&&r.trim());const n=!!((i=s.sql)!=null&&i.trim()),a=t.hasValidCardConfig(s.config);return n||a}function Cr({slots:s,cards:n,minInputs:a}){const r=[],i=n.filter(Boolean).length;return a&&i<a&&r.push({type:"too-few-inputs",message:`This visual requires at least ${a} tab${a===1?"":"s"}.`}),!s||s.length===0||(s.forEach(c=>{if(!c.required)return;if(typeof c.position=="number"){const l=n[c.position];Zt(l)||r.push({type:"missing-required",message:`${St(c.position)} ("${c.label}") is required but has no data configured.`});return}const o=c.position.match(/^(\d+)-(\d+)$/);if(o){const[,l,m]=o.map(Number);for(let p=l;p<=m;p+=1){const x=n[p];if(!Zt(x)){r.push({type:"missing-required",message:`${St(p)} ("${c.label}") is required but has no data configured.`});break}}return}const d=c.position.match(/^(\d+)\+$/);if(d){const l=Number(d[1]);if(n.length<=l){r.push({type:"missing-required",message:`${St(l)} ("${c.label}") is required but has no data configured.`});return}for(let m=l;m<n.length;m+=1){const p=n[m];if(!Zt(p)){r.push({type:"missing-required",message:`${St(m)} ("${c.label}") is required but has no data configured.`});break}}}}),n.forEach((c,o)=>{if(!c)return;const d=yr(s,o);if(!d||!d.expectedType)return;const l=Nr(d.expectedType);l.length!==0&&(l.includes(c.type)||r.push({type:"wrong-type",message:`${St(o)} ("${d.label}") expects ${l.join(", ")}, but is configured as ${c.type}.`}))})),r}const Sr={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:n})=>(n==null?void 0:n.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 Ra(){var f,O,F;const s=t.useEditorStore(b=>b.card.customCardPreferences),{data:n}=t.usePluginQuery(),a=(n==null?void 0:n.plugins)||[],r=t.useEditorStore(b=>b.card),i=t.useEditorStore(b=>b.frame),{setCustomCardPreferences:c}=t.useEditorActions(),o=N.useMemo(()=>t.findCustomVisualConfigCard(i,r),[i,r]),d=o==null?void 0:o.customCardPreferences,{components:l,manifest:m}=t.useCustomVisual((d==null?void 0:d.url)||(s==null?void 0:s.url)||""),p=(f=m==null?void 0:m.visuals)==null?void 0:f.find(b=>b.name===((d==null?void 0:d.componentName)||(s==null?void 0:s.componentName))),u=t.resolveMultiInputType(o||r,p)==="multiple",h=!!o&&o.id===r.id,g=(p==null?void 0:p.minInputs)??((O=o==null?void 0:o.customCardPreferences)==null?void 0:O.minInputs),y=(p==null?void 0:p.maxInputs)??((F=o==null?void 0:o.customCardPreferences)==null?void 0:F.maxInputs),j=N.useMemo(()=>t.getCustomVisualInputCards({frame:i,configCard:o||r,isMultiInputVisual:u}),[i,o,r,u]),I=N.useMemo(()=>t.buildSlotOrderedCards(j),[j]),D=N.useMemo(()=>I.map((b,L)=>{if(!b)return null;const C=t.getSlotIndexForCard(b,L),P=t.getEffectiveCardTypeForSlot(b,C,p==null?void 0:p.slots);return{...b,type:P??b.type}}),[I,p==null?void 0:p.slots]),V=N.useMemo(()=>Cr({slots:p==null?void 0:p.slots,cards:D,minInputs:g}),[p==null?void 0:p.slots,D,g]),E=N.useMemo(()=>{const b=j.findIndex(L=>(L==null?void 0:L.id)===r.id);return b<0?-1:t.getSlotIndexForCard(r,b)},[j,r]);function w(b){if(typeof b=="number")return`Tab ${b+1}`;const L=b.match(/^(\d+)-(\d+)$/);if(L){const[,P,R]=L;return`Tabs ${Number(P)+1}-${Number(R)+1}`}const C=b.match(/^(\d+)\+$/);return C?`Tabs ${Number(C[1])+1}+`:`Tab ${b}`}function T(b){return b?(Array.isArray(b)?b:[b]).join(", "):null}function A(b,L,C=[],P="",R,B,z){const _=S({key:L,defaultValue:P,settingsValue:B,sourceCard:z});return b==="input"?e.jsx(Ve,{className:`h-8 w-full ${t.removeRing}`,value:String(_??""),onCommit:K=>{v({key:L,value:K,settingsField:R,settingsValue:B,sourceCard:z})}},L):b==="select"?e.jsx(Xe,{className:"h-8 w-full",label:"",options:C,value:String(_!==void 0?_:P??""),onValueChange:K=>{v({key:L,value:K,settingsField:R,settingsValue:B,sourceCard:z})}}):null}function S({key:b,defaultValue:L,settingsValue:C,sourceCard:P}){const R=C==null?void 0:C[b];return R!==void 0?R:b==="title"&&(P==null?void 0:P.title)!==void 0?P.title:b==="description"&&(P==null?void 0:P.description)!==void 0?P.description:L}function v({key:b,value:L,settingsField:C,settingsValue:P,sourceCard:R}){const B={...P||{}},z=b==="title"&&(R==null?void 0:R.title)!==void 0,_=b==="description"&&(R==null?void 0:R.description)!==void 0;z&&L===String((R==null?void 0:R.title)??"")||_&&L===String((R==null?void 0:R.description)??"")?delete B[b]:B[b]=L,c({...s||{},[C]:B})}function k({settingsSchema:b,settingsField:L,settingsValue:C,sourceCard:P,headerLabel:R}){const B=Object.entries(b||{});return e.jsxs("div",{className:"space-y-3",children:[R&&e.jsx(t.Label,{children:R}),B.map(([z,_])=>{var K;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{children:_.title}),((K=_.docs)==null?void 0:K.description)&&e.jsx(t.TooltipProvider,{delayDuration:0,children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{className:"text-xs",children:_.docs.description})})]})})]}),A(_.ui,z,_.options,_.defaultValue,L,C,P)]},z)})]})}function M(){return e.jsxs(e.Fragment,{children:[u&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Slot Guide"}),e.jsx("div",{className:"space-y-3 rounded-md border border-border bg-muted/40 px-3 py-2 text-xs",children:p!=null&&p.slots&&p.slots.length>0?e.jsx("div",{className:"space-y-3",children:p.slots.map((b,L)=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-foreground",children:[e.jsx("span",{className:"font-medium",children:w(b.position)}),e.jsx("span",{className:"text-muted-foreground",children:"•"}),e.jsx("span",{className:"font-medium",children:b.label})]}),b.description&&e.jsx("p",{className:"text-muted-foreground",children:b.description}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-muted-foreground",children:[T(b.expectedType)&&e.jsxs("span",{children:["Expected: ",T(b.expectedType)]}),b.required&&e.jsx("span",{children:"Required"})]})]},`${b.label}-${L}`))}):e.jsxs("div",{className:"space-y-1 text-muted-foreground",children:[e.jsx("p",{children:"This visual renders all tabs in a flexible layout. Add as many tabs as needed."}),(g||y)&&e.jsxs("p",{children:[g?`Min ${g} tabs`:"",g&&y?" • ":"",y?`Max ${y} tabs`:""]})]})})]}),u&&V.length>0&&e.jsx(t.Alert,{className:"mt-3 border-yellow-500/40 bg-yellow-500/10 text-yellow-900 dark:text-yellow-100",children:e.jsx(t.AlertDescription,{children:e.jsx("ul",{className:"list-disc space-y-1 pl-4 text-xs",children:V.map((b,L)=>e.jsx("li",{children:b.message},`${b.type}-${L}`))})})}),p&&!u&&p.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:k({settingsSchema:p.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:r})})}),p&&u&&(p.settings||p.slotSettings)&&e.jsxs("div",{className:"mt-4 space-y-4",children:[h&&p.settings&&e.jsx("div",{className:"px-2",children:k({settingsSchema:p.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:o||r,headerLabel:"Global Settings"})}),p.slotSettings&&e.jsx("div",{className:"px-2",children:k({settingsSchema:p.slotSettings,settingsField:"slotSettings",settingsValue:s==null?void 0:s.slotSettings,sourceCard:r,headerLabel:(()=>{const b=r.tabTitle||r.title,L=E>=0?E:0,C=h?"Slot 0":`Slot ${L}`;return b?`${C}: ${b} Settings`:`${C} Settings`})()})})]})]})}return e.jsxs(t.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"",children:[e.jsxs(t.AccordionItem,{value:"plugin-settings",children:[e.jsx(t.AccordionTrigger,{children:"Plugin"}),e.jsx(t.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[(!u||h)&&e.jsx(Xe,{icon:e.jsx(Sa,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:a,value:(d==null?void 0:d.url)||"",onValueChange:b=>c({...s||{url:"",componentName:""},url:b})}),u&&!h&&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&&(!u||h)&&e.jsx(e.Fragment,{children:l&&e.jsx(Xe,{icon:e.jsx(xn,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(l==null?void 0:l.map(b=>({value:b.name,label:b.name})))||[],value:s.componentName||"",onValueChange:b=>{var P;const L=(P=m==null?void 0:m.visuals)==null?void 0:P.find(R=>R.name===b),C=l==null?void 0:l.find(R=>R.name===b);c({...s,componentName:b,visualType:(L==null?void 0:L.visualType)||(C==null?void 0:C.type)||"single",minInputs:L==null?void 0:L.minInputs,maxInputs:L==null?void 0:L.maxInputs,pluginChartType:L==null?void 0:L.chartType})}})})]})})]}),((d==null?void 0:d.componentName)||(s==null?void 0:s.componentName))&&e.jsxs(t.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(t.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:(p==null?void 0:p.name)||"Settings"}),(p==null?void 0:p.docs)&&e.jsxs(t.HoverCard,{openDelay:0,closeDelay:100,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,onClick:b=>b.stopPropagation(),children:e.jsx(t.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground transition-colors hover:text-foreground"})}),e.jsx(t.HoverCardContent,{side:"right",align:"start",className:"max-h-[40vh] w-[500px] overflow-y-auto text-left",children:e.jsxs("div",{className:"space-y-4 text-left",children:[p.docs.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:p.docs.description}),p.docs.dataSchema&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Data Schema"}),e.jsx("div",{className:"prose prose-sm dark:prose-invert prose-pre:bg-muted prose-pre:text-xs max-w-none",children:e.jsx(t.Markdown,{remarkPlugins:[t.remarkGfm],components:Sr,children:p.docs.dataSchema})})]}),(()=>{var L;const b=(L=p.docs)==null?void 0:L.useCases;return!b||b.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:b.map((C,P)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1 text-primary",children:"•"}),e.jsx("span",{children:C})]},P))})]})})()]})})]})]})}),e.jsx(t.AccordionContent,{children:M()})]})]})}function wr({colorRanges:s,setColorRanges:n}){const a={start:-1/0,end:100,color:""};function r(o,d,l){const m=[...s];m[o]={...m[o],[d]:l},n(m)}function i(o){const d=[...s];d.splice(o,1),n(d)}function c(){n([...s,a])}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:c,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(t.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:l=>r(d,"start",l.target.value),value:o.start,className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(t.Input,{value:o.end,onChange:l=>r(d,"end",l.target.value),className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx(t.Input,{onChange:l=>r(d,"color",l.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:()=>i(d),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(t.X,{className:"size-3"})})]},d))]})}function Tr(){var p,x,u,h,g;const s=t.useEditorStore(y=>y.card.preferences),n=t.useEditorStore(y=>y.actions.setCardPreferences),a=t.useEditorStore(y=>y.card),r=t.hasValidCardConfig(a.config),i=t.useEditorStore(y=>y.actions.setNumberFormat);t.useEditorStore(y=>{var j,I;return(I=(j=y.card.preferences)==null?void 0:j.formatNumber)==null?void 0:I.decimalPlaces});const c=t.useEditorStore(y=>{var j,I;return(I=(j=y.card.preferences)==null?void 0:j.formatNumber)==null?void 0:I.locale}),o=t.useEditorStore(y=>{var j,I;return(I=(j=y.card.preferences)==null?void 0:j.formatNumber)==null?void 0:I.currency});t.useEditorStore(y=>y.actions.setFilterOnClickField);const d=t.useEditorStore(y=>{var j,I;return(I=(j=y.card.preferences)==null?void 0:j.formatNumber)==null?void 0:I.colorRanges})||[],l=t.useEditorStore(y=>y.actions.setColorRanges),m=[...new Set(t.LOCALE_CURRENCY_PAIRS.map(y=>y.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(t.Checkbox,{checked:!!((p=s==null?void 0:s.formatNumber)!=null&&p.enabled),onCheckedChange:y=>{n({...s,formatNumber:{...s==null?void 0:s.formatNumber,enabled:y}})}}),e.jsx(t.Label,{children:"Format Number"})]}),(((x=s==null?void 0:s.formatNumber)==null?void 0:x.enabled)===!0||r)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Locale"}),e.jsxs(t.Select,{value:c||"none",onValueChange:y=>{var j,I,D;return i(((j=s==null?void 0:s.formatNumber)==null?void 0:j.decimalPlaces)||0,((I=s==null?void 0:s.formatNumber)==null?void 0:I.currency)||"",y,((D=s==null?void 0:s.formatNumber)==null?void 0:D.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(y=>e.jsx(t.SelectItem,{value:y.locale,children:y.locale},y.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:y=>{var j,I,D;console.log("currency",y),i(((j=s==null?void 0:s.formatNumber)==null?void 0:j.decimalPlaces)||0,y==="none"?"":y,((I=s==null?void 0:s.formatNumber)==null?void 0:I.locale)||"",((D=s==null?void 0:s.formatNumber)==null?void 0:D.suffix)||"")},children:[e.jsx(t.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Currency"}),e.jsx(t.SelectItem,{value:"none",children:"None"},"none"),m.map(y=>e.jsx(t.SelectItem,{value:y,children:y},y))]})})]})]})]}),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:((h=(u=s==null?void 0:s.formatNumber)==null?void 0:u.decimalPlaces)==null?void 0:h.toString())||"0",onValueChange:y=>{var j,I,D;return i(Number(y),((j=s==null?void 0:s.formatNumber)==null?void 0:j.currency)||"",((I=s==null?void 0:s.formatNumber)==null?void 0:I.locale)||"",((D=s==null?void 0:s.formatNumber)==null?void 0:D.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(y=>e.jsx(t.SelectItem,{value:y,children:y},y))})]})]}),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:y=>{var j,I,D;return i(((j=s==null?void 0:s.formatNumber)==null?void 0:j.decimalPlaces)||0,((I=s==null?void 0:s.formatNumber)==null?void 0:I.currency)||"",((D=s==null?void 0:s.formatNumber)==null?void 0:D.locale)||"",y.target.value)}})]})]})]})}),e.jsx(t.Separator,{className:"my-3"}),e.jsx(wr,{colorRanges:d,setColorRanges:l})]})]})}const Er={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 Ba(s){return Er[s]}function Ir({chartType:s,showDocsLink:n=!0}){const a=Ba(s);return a?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:a.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:a.fields.map((r,i)=>e.jsxs("tr",{className:i<a.fields.length-1?"border-b":"",children:[e.jsxs("td",{className:"px-2.5 py-1.5 font-medium text-foreground",children:[r.name,r.optional&&e.jsx("span",{className:"ml-1 text-muted-foreground",children:"?"})]}),e.jsx("td",{className:"px-2.5 py-1.5 font-mono text-muted-foreground",children:r.type}),e.jsx("td",{className:"px-2.5 py-1.5 text-muted-foreground",children:r.description||"—"})]},r.name))})]})})]}),e.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:a.description}),n&&a.docsUrl&&e.jsxs("a",{href:a.docsUrl,target:"_blank",rel:"noopener noreferrer",onClick:r=>r.stopPropagation(),className:"inline-flex items-center gap-1.5 text-xs font-medium text-primary hover:underline",children:["View documentation",e.jsx(t.ExternalLink,{className:"h-3 w-3"})]})]}):null}function kr({chartType:s}){return Ba(s)?e.jsxs(t.HoverCard,{openDelay:200,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded bg-muted px-2 py-0.5 font-mono text-[10px] font-semibold uppercase tracking-wider text-muted-foreground transition-colors hover:bg-muted/80 hover:text-foreground",children:"SQL"})}),e.jsx(t.HoverCardContent,{className:"w-80 p-4",side:"left",align:"start",sideOffset:8,children:e.jsx(Ir,{chartType:s})})]}):null}function _t({chartType:s,suffix:n="Configuration"}){return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-medium",children:n}),e.jsx(kr,{chartType:s})]})}function Dr(){return e.jsxs("div",{className:"space-y-6 px-6 py-4",children:[e.jsx(_t,{chartType:"kpi"}),e.jsx("section",{children:e.jsx(Tr,{})})]})}function ua({children:s,summary:n,open:a,className:r}){return e.jsxs("details",{open:a,className:t.cn("space-y-4 [&_summary>svg]:open:-rotate-180",r),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(t.Label,{children:n}),e.jsx(t.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:s})]})}function Pa(){const[s,n]=N.useState([]),a=t.useEditorStore(m=>m.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:i}=t.useEditorStore(m=>m.actions),c=t.useEditorStore(m=>m.queryResultColumns);t.useEditorStore(m=>{var p;return(p=m.card.preferences)==null?void 0:p.filterOnClickColumnIndex}),N.useEffect(()=>{c&&n(new Array(c.length).fill(!1))},[c]);function o(m,p){var x,u;p?a!=null&&a.onClickFilter&&((x=a==null?void 0:a.onClickFilter)==null?void 0:x.length)>0?i({...a,onClickFilter:[...a.onClickFilter,{columnIndex:m,expression:""}]}):i({...a,onClickFilter:[{columnIndex:m,expression:""}]}):(i({...a,onClickFilter:(u=a==null?void 0:a.onClickFilter)==null?void 0:u.filter(h=>h.columnIndex!==m)}),n(h=>{const g=[...h];return g[m]=!1,g}))}function d(m,p){var u;const x=(u=a==null?void 0:a.onClickFilter)==null?void 0:u.map(h=>h.columnIndex===m?{...h,expression:p.target.value}:h);i({...a,onClickFilter:x})}function l(m){var p,x,u,h;if(s!=null&&s[m]||(x=(p=a==null?void 0:a.onClickFilter)==null?void 0:p.find(g=>g.columnIndex===m))!=null&&x.expression)return e.jsx(t.Input,{value:(h=(u=a==null?void 0:a.onClickFilter)==null?void 0:u.find(g=>g.columnIndex===m))==null?void 0:h.expression,onChange:g=>d(m,g),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsx("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:c==null?void 0:c.map((m,p)=>{var x,u;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(t.Checkbox,{checked:!!((x=a==null?void 0:a.onClickFilter)!=null&&x.find(h=>h.columnIndex===p)),onCheckedChange:h=>o(p,h)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:m}),e.jsx("div",{className:"flex items-center gap-2",children:((u=a==null?void 0:a.onClickFilter)==null?void 0:u.find(h=>h.columnIndex===p))&&e.jsx(t.Pencil,{onClick:()=>{n(h=>{const g=[...h];return g[p]=!h[p],g})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),l(p)]})},m)})})}const Ar=[{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"}],Mr=["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"],Lr=Mr.map(s=>({label:s,value:s}));function Or(){var l,m,p,x,u,h,g,y,j,I,D,V,E,w,T,A,S,v;const s=t.useEditorStore(k=>k.card),n=(m=(l=s==null?void 0:s.preferences)==null?void 0:l.mapVisualOptions)==null?void 0:m.topoJsonUrl,[a,r]=N.useState(((x=(p=s==null?void 0:s.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:x.customTopoJsonUrl)||""),{setCardPreferences:i}=t.useEditorActions(),{data:c}=t.useTopoJson(s),o=Object.keys((c==null?void 0:c.objects)||{}).map(k=>({label:k,value:k}))||[],d=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(_t,{chartType:"map"}),e.jsx(ua,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(Xe,{className:"h-9",options:d,onValueChange:k=>{console.log("value",k),i({...s.preferences,mapVisualOptions:{topoJsonUrl:k}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(t.Input,{onChange:k=>{r(k.target.value)},onBlur:()=>{var k;console.log("onBlur",a),i({...s.preferences,mapVisualOptions:{...(k=s.preferences)==null?void 0:k.mapVisualOptions,customTopoJsonUrl:a}})},value:a,className:`h-9 w-full ${t.removeRing}`,placeholder:"Custom URL"}),c&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Map Object"}),e.jsx(Xe,{className:"h-9",options:o,value:((h=(u=s.preferences)==null?void 0:u.mapVisualOptions)==null?void 0:h.objectKey)||"",label:"Map Object",onValueChange:k=>{var M;i({...s.preferences,mapVisualOptions:{...(M=s.preferences)==null?void 0:M.mapVisualOptions,objectKey:k}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Projection"}),e.jsx(Xe,{className:"h-9",options:Ar,value:((y=(g=s.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:y.projection)||"",label:"Projection",onValueChange:k=>{var M;i({...s.preferences,mapVisualOptions:{...(M=s.preferences)==null?void 0:M.mapVisualOptions,projection:k}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Colors"}),e.jsx(Xe,{className:"h-9",options:Lr,value:((I=(j=s.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:I.colorScale)||"",label:"Select Color Scale",onValueChange:k=>{var M;i({...s.preferences,mapVisualOptions:{...(M=s.preferences)==null?void 0:M.mapVisualOptions,colorScale:k}})}})]})]})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(ua,{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:((V=(D=s.preferences)==null?void 0:D.mapVisualOptions)==null?void 0:V.projectionScale)||1,onChange:k=>{var M;i({...s.preferences,mapVisualOptions:{...(M=s.preferences)==null?void 0:M.mapVisualOptions,projectionScale:Number(k.target.value)}})}}),e.jsx(t.Label,{children:"X"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((T=(w=(E=s.preferences)==null?void 0:E.mapVisualOptions)==null?void 0:w.projectionOffset)==null?void 0:T[0])||0,onChange:k=>{var M,f,O,F;i({...s.preferences,mapVisualOptions:{...(M=s.preferences)==null?void 0:M.mapVisualOptions,projectionOffset:[Number(k.target.value),((F=(O=(f=s.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:O.projectionOffset)==null?void 0:F[1])||0]}})}}),e.jsx(t.Label,{children:"Y"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((v=(S=(A=s.preferences)==null?void 0:A.mapVisualOptions)==null?void 0:S.projectionOffset)==null?void 0:v[1])||0,onChange:k=>{var M,f,O,F;i({...s.preferences,mapVisualOptions:{...(M=s.preferences)==null?void 0:M.mapVisualOptions,projectionOffset:[((F=(O=(f=s.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:O.projectionOffset)==null?void 0:F[0])||0,Number(k.target.value)]}})}})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(Pa,{})]})}function Va({color:s,onColorChange:n,onClose:a}){const[r,i]=N.useState(0),[c,o]=N.useState(100),[d,l]=N.useState(50),[m,p]=N.useState(s);N.useEffect(()=>{const j=ma(s);if(j){const I=xa(j.r,j.g,j.b);i(I.h),o(I.s),l(I.l),p(s)}},[s]);const x=j=>{i(j),h(j,c,d)},u=j=>{const I=j.currentTarget.getBoundingClientRect(),D=Math.max(0,Math.min(1,(j.clientX-I.left)/I.width)),V=Math.max(0,Math.min(1,(j.clientY-I.top)/I.height)),E=D*100,w=(1-V)*100;o(E),l(w),h(r,E,w)},h=(j,I,D)=>{const V=Rr(j,I,D),E=Fr(V.r,V.g,V.b);p(E)},g=j=>{if(p(j),/^#[0-9A-Fa-f]{6}$/.test(j)){const I=ma(j);if(I){const D=xa(I.r,I.g,I.b);i(D.h),o(D.s),l(D.l)}}},y=()=>{/^#[0-9A-Fa-f]{6}$/.test(m)&&(n(m),a())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:u,onMouseMove:j=>{j.buttons===1&&u(j)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${c}%`,top:`${100-d}%`,backgroundColor:m}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:j=>x(Number(j.target.value)),className:"w-full h-4 rounded-lg appearance-none cursor-pointer",style:{background:"linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"}})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"HEX"}),e.jsx(t.Input,{value:m,onChange:j=>g(j.target.value),placeholder:"#000000",className:"font-mono"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:s}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:m}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(t.Button,{variant:"outline",onClick:a,children:"Cancel"}),e.jsx(t.Button,{onClick:y,children:"OK"})]})]})}function ma(s){const n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(s);return n?{r:parseInt(n[1],16),g:parseInt(n[2],16),b:parseInt(n[3],16)}:null}function Fr(s,n,a){return"#"+((1<<24)+(s<<16)+(n<<8)+a).toString(16).slice(1)}function xa(s,n,a){s/=255,n/=255,a/=255;const r=Math.max(s,n,a),i=Math.min(s,n,a);let c=0,o=0;const d=(r+i)/2;if(r!==i){const l=r-i;switch(o=d>.5?l/(2-r-i):l/(r+i),r){case s:c=((n-a)/l+(n<a?6:0))/6;break;case n:c=((a-s)/l+2)/6;break;case a:c=((s-n)/l+4)/6;break}}return{h:Math.round(c*360),s:Math.round(o*100),l:Math.round(d*100)}}function Rr(s,n,a){s/=360,n/=100,a/=100;let r,i,c;if(n===0)r=i=c=a;else{const o=(m,p,x)=>(x<0&&(x+=1),x>1&&(x-=1),x<.16666666666666666?m+(p-m)*6*x:x<.5?p:x<.6666666666666666?m+(p-m)*(.6666666666666666-x)*6:m),d=a<.5?a*(1+n):a+n-a*n,l=2*a-d;r=o(l,d,s+1/3),i=o(l,d,s),c=o(l,d,s-1/3)}return{r:Math.round(r*255),g:Math.round(i*255),b:Math.round(c*255)}}const ha=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],Br=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function Ze({value:s,onChange:n,label:a}){const[r,i]=N.useState(!1),[c,o]=N.useState(!1),d=()=>{const l=ha.find(m=>m.value===s);return l?l.color:s.startsWith("#")?s:ha[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Popover,{open:r,onOpenChange:i,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"size-5 rounded border-2 border-input shadow-sm transition-all hover:scale-110 hover:border-gray-400",style:{backgroundColor:d()},"aria-label":`Change color for ${a}`})}),e.jsx(t.PopoverContent,{align:"start",className:"w-auto p-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"grid grid-cols-3 items-center justify-items-center gap-1",children:Br.map(l=>e.jsx("button",{className:t.cn("h-5 w-5 rounded border-2 transition-all",d()===l?"border-gray-900":"border-transparent"),style:{backgroundColor:l},onClick:()=>{n(l),i(!1)},children:e.jsx("span",{className:"sr-only",children:l})},l))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{o(!0),i(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a})]}),c&&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:()=>o(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Va,{color:d(),onColorChange:l=>{n(l),o(!1)},onClose:()=>o(!1)})})]})]})}function Bt(s){return s==="currency"?2:s==="percent"?1:s==="scientific"?2:0}function pa(s,n){if(!n||n==="auto")return{type:"auto"};const a={...s,type:n,multiplyBy:n==="percent"?s.multiplyBy:void 0,percentValueMode:n==="percent"?s.percentValueMode:void 0};return n&&["number","currency","percent","scientific"].includes(n)&&s.decimalPlaces===void 0&&s.minimumFractionDigits===void 0&&s.maximumFractionDigits===void 0?os(a,Bt(n)):a}function os(s,n){return{...s,decimalPlaces:n,minimumFractionDigits:n,maximumFractionDigits:n}}const Pr=["auto","number","currency","percent","scientific","date"],Vr=[{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"}],_r=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"en-IN",label:"English (India)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"},{value:"ja-JP",label:"Japanese"},{value:"ko-KR",label:"Korean"},{value:"ru-RU",label:"Russian"},{value:"ar-SA",label:"Arabic"},{value:"hi-IN",label:"Hindi"},{value:"nl-NL",label:"Dutch"},{value:"sv-SE",label:"Swedish"}],zr=s=>s.charAt(0).toUpperCase()+s.slice(1);function gt({formatOptions:s={},onFormatOptionsChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const i=s.type||"auto",c=i==="auto"?s:pa(s,i),o=h=>{h.stopPropagation()},d=(h,g)=>{n({...c,[h]:g})},[l,m]=N.useState(()=>String(c.decimalPlaces??Bt(i))),[p,x]=N.useState(()=>c.multiplyBy!==void 0?String(c.multiplyBy):""),u=h=>{n(pa(s,h))};return N.useEffect(()=>{m(String(c.decimalPlaces??Bt(i)))},[c.decimalPlaces,i]),N.useEffect(()=>{x(c.multiplyBy!==void 0?String(c.multiplyBy):"")},[c.multiplyBy]),e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[a&&e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(t.Select,{value:i,onValueChange:h=>u(h),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:Pr.map(h=>e.jsx(t.SelectItem,{value:h,className:"text-xs",children:h==="auto"?"Auto (Default)":zr(h)},h))})]})]}),i!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent","scientific"].includes(i)&&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:l,onClick:o,onPointerDown:o,onKeyDown:o,onChange:h=>{const g=h.target.value.replace(/[^\d]/g,"");m(g),g!==""&&n(os(c,Math.max(0,Math.min(10,parseInt(g,10)))))},onBlur:()=>{if(l!=="")return;const h=Bt(i);m(String(h)),n(os(c,h))},className:"h-8 text-xs"})})]}),i==="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:h=>d("currency",h),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:Vr.map(h=>e.jsx(t.SelectItem,{value:h.value,className:"text-xs",children:h.label},h.value))})]})]}),["number","currency"].includes(i)&&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.SmallSwitch,{checked:s.useSuffix??!1,onClick:h=>h.stopPropagation(),onCheckedChange:h=>d("useSuffix",h)})]}),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:h=>d("locale",h),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:_r.map(h=>e.jsx(t.SelectItem,{value:h.value,className:"text-xs",children:h.label},h.value))})]})]}),i==="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:h=>d("prefix",h.target.value),className:"h-8 text-xs"})})]}),i==="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:h=>d("suffix",h.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(i)&&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.SmallSwitch,{checked:s.negativeInParentheses??!1,onClick:h=>h.stopPropagation(),onCheckedChange:h=>d("negativeInParentheses",h)})]}),i==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{type:"text",inputMode:"decimal",placeholder:"100",value:p,onClick:o,onPointerDown:o,onKeyDown:o,onChange:h=>{const g=h.target.value.replace(/[^0-9.]/g,"");x(g),d("multiplyBy",g?parseFloat(g):void 0)},className:"h-8 text-xs"})})]}),i==="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:h=>d("dateFormat",h.target.value),className:"h-8 text-xs"})})]})]})]})}function xs({value:s,onChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const i=t.toTFormatOptions(t.fromSemanticFormat(s))||{},c=o=>{n(t.fromTFormatOptions(o))};return e.jsx(gt,{formatOptions:i,onFormatOptionsChange:c,showTitle:a,title:r})}function qr(){const s=t.useDashboardStore(d=>d.dashboard.filters),n=t.useEditorStore(d=>d.frame),{setFrame:a}=t.useEditorActions(),{columns:r}=t.useColumns(),{assignFilter:i}=t.useAssignFilter();function c(d){const l=i(d,"frame");a({...n,filterId:l})}const o=s==null?void 0:s.find(d=>d.id===n.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Card Filter"}),e.jsx($r,{onSelect:c,columns:r}),o&&e.jsx(t.FilterHeader,{filter:o})]})}function $r({columns:s,onSelect:n}){var o;const[a,r]=rs.useState(!1),[i,c]=rs.useState("");return e.jsxs(t.Popover,{open:a,onOpenChange:r,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between font-normal",children:[i?((o=s.find(d=>d.name===i))==null?void 0:o.label)||i:"Select Column...",e.jsx(t.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No column found."}),e.jsx(t.CommandGroup,{children:s==null?void 0:s.map(d=>e.jsxs(t.CommandItem,{value:d.name,onSelect:l=>{const m=l===i?"":l;c(m),r(!1),m&&n(d)},children:[d.label||d.name,e.jsx(t.CheckIcon,{className:t.cn("ml-auto h-4 w-4",i===d.name?"opacity-100":"opacity-0")})]},d.id))})]})]})})]})}const Kr=[{value:"difference",label:"Difference"},{value:"change",label:"Change (%)"},{value:"change_difference",label:"Change + Difference"},{value:"ratio",label:"Ratio"}],Gr=[{value:"arrow_badge",label:"Arrow + Badge"},{value:"arrow",label:"Arrow Only"},{value:"badge",label:"Badge Only"},{value:"none",label:"None"}];function Ur({cardType:s="table"}){var p,x,u,h,g;const n=t.useEditorStore(y=>y.card),a=t.useEditorStore(y=>{var j;return(j=y.card)==null?void 0:j.preferences}),r=t.useEditorStore(y=>y.actions.setCardPreferences),i=((p=n.config)==null?void 0:p.metricColumns)||[],c=i.some(y=>y.comparisonType&&y.comparisonType!=="none"),o=((x=a==null?void 0:a.tableVisualOptions)==null?void 0:x.metricComparison)||{},d=y=>{r({...a,tableVisualOptions:{...a==null?void 0:a.tableVisualOptions,metricComparison:{...o,...y}}})},l={increase:((u=o.colors)==null?void 0:u.increase)||"green",decrease:((h=o.colors)==null?void 0:h.decrease)||"red",neutral:((g=o.colors)==null?void 0:g.neutral)||"neutral"},m=y=>{r({...a,allowDownload:y})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsxs(t.Accordion,{defaultValue:["item-3"],type:"multiple",children:[c&&e.jsxs(t.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(t.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ta,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison Settings"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated As"}),e.jsxs(t.Select,{value:o.calculatedAs||"change_difference",onValueChange:y=>d({calculatedAs:y}),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Kr.map(y=>e.jsx(t.SelectItem,{value:y.value,className:"text-xs",children:y.label},y.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Number Format"}),e.jsx(gt,{formatOptions:o.formatOptions||{},onFormatOptionsChange:y=>d({formatOptions:y}),showTitle:!1})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator Style"}),e.jsxs(t.Select,{value:o.indicatorStyle||"arrow_badge",onValueChange:y=>d({indicatorStyle:y}),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Gr.map(y=>e.jsx(t.SelectItem,{value:y.value,className:"text-xs",children:y.label},y.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Colors"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ze,{value:l.increase,onChange:y=>d({colors:{...l,increase:y}}),label:"Increase"}),e.jsx(Ze,{value:l.decrease,onChange:y=>d({colors:{...l,decrease:y}}),label:"Decrease"}),e.jsx(Ze,{value:l.neutral,onChange:y=>d({colors:{...l,neutral:y}}),label:"No Change"})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Lower is Better"}),e.jsx(t.Checkbox,{checked:o.lowerIsBetter||!1,onCheckedChange:y=>d({lowerIsBetter:!!y})})]})]})]}),i.length>0&&e.jsxs(t.AccordionItem,{value:"metric-formats",className:"border-none",children:[e.jsx(t.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsx("span",{children:"Metric Formats"})}),e.jsx(t.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:i.map(y=>e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 p-3",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:y.label||y.name}),e.jsx(xs,{value:y.format,onChange:j=>{var D;const I=(((D=n.config)==null?void 0:D.metricColumns)||[]).map(V=>V.id===y.id?{...V,format:j}:V);t.useEditorStore.getState().actions.updateCardConfig(n.id,{metricColumns:I})},showTitle:!1})]},y.id))})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Click Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Pa,{}),e.jsx(qr,{})]})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Checkbox,{onCheckedChange:m,id:"allow-download"}),e.jsx("label",{htmlFor:"allow-download",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Allow Download"})]})]})}function Hr(){var r;const s=t.useEditorStore(i=>i.card.preferences),{setCardPreferences:n}=t.useEditorStore(i=>i.actions);function a(i){n({...s,textVisualOptions:{...s==null?void 0:s.textVisualOptions,isDynamicText:i==="dynamic"}})}return e.jsxs(t.RadioGroup,{value:(r=s==null?void 0:s.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:a,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function Qr(){return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(_t,{chartType:"text"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Text Type"}),e.jsx(Hr,{})]})]})}const Jr=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function Yr(){var w,T,A,S,v,k,M,f,O,F;const s=t.useEditorStore(b=>b.card),n=t.useEditorStore(b=>{var L;return(L=b.card)==null?void 0:L.preferences}),a=De.useEffectiveEditorCardType(),{setCardPreferences:r,updateCardInFrame:i}=t.useEditorActions(),c=N.useMemo(()=>a!==s.type?{...s,type:a}:s,[s,a]),{data:o}=t.useDashboardCardQuery(c),[d,l]=N.useState({}),[m,p]=N.useState(null),[x,u]=N.useState(null),h=N.useMemo(()=>{var P,R,B,z,_,K,H;if(!(o!=null&&o.records)||o.records.length===0)return[];const b=a==="stackedBar"||a==="stackedLine",L=a==="bar"||a==="line"||a==="horizontalBar"||a==="bullet"||a==="combo"||a==="area"||a==="stackedArea",C=((P=s==null?void 0:s.config)==null?void 0:P.pivotByColumns)&&s.config.pivotByColumns.length>0;if((b||L)&&C){if(o.pivotSchema&&Array.isArray(o.pivotSchema)){const G=new Set;return o.pivotSchema.forEach(X=>{X.alias&&G.add(X.alias)}),Array.from(G)}if(o.records.length>0){const G=o.records[0],X=Object.keys(G),ae=new Set;(R=s==null?void 0:s.config)!=null&&R.groupByColumns&&s.config.groupByColumns.forEach(ce=>{ae.add(ce.label||ce.name),ae.add(ce.alias||ce.name)});const ee=new Set;return(B=s==null?void 0:s.config)!=null&&B.metricColumns&&s.config.metricColumns.forEach(ce=>{const W=ce.alias||ce.name;ee.add(W),ee.add(`${W}_count`),ee.add(`${W}_sum`),ee.add(`${W}_avg`),ee.add(`${W}_min`),ee.add(`${W}_max`);const pe=ce.entityName||ce.qualifiedEntityName;pe&&(ee.add(`${pe}_${W}`),ee.add(`${pe}_${W}_count`))}),X.filter(ce=>!ae.has(ce)&&!ee.has(ce))}}if((L||b)&&!C&&((_=(z=s==null?void 0:s.config)==null?void 0:z.metricColumns)!=null&&_.length))return s.config.metricColumns.map(G=>G.alias||G.label||G.name);if((H=(K=s==null?void 0:s.config)==null?void 0:K.groupByColumns)!=null&&H.length){const G=s.config.groupByColumns[0],X=G.label||G.name,ae=new Set;return o.records.forEach(ee=>{const de=ee[X];de!=null&&ae.add(String(de))}),Array.from(ae)}return[]},[o,(w=s==null?void 0:s.config)==null?void 0:w.groupByColumns,(T=s==null?void 0:s.config)==null?void 0:T.pivotByColumns,(A=s==null?void 0:s.config)==null?void 0:A.metricColumns,s==null?void 0:s.type]),g=N.useMemo(()=>t.getDefaultChartColors(),[]);N.useEffect(()=>{const b={};h.forEach((L,C)=>{b[L]=t.getColorForValue(L,C,n==null?void 0:n.colorConfig)}),l(b)},[h,n==null?void 0:n.colorConfig,g]);const y=(b,L)=>{const C={...d,[b]:L};l(C);const P={...n||{},colorConfig:{segments:C}};r(P);const R={...s,preferences:P};i(R)},j=(b,L)=>{var _;const C=g[L%g.length],{[b]:P,...R}=((_=n==null?void 0:n.colorConfig)==null?void 0:_.segments)||{},B={...n||{},colorConfig:{segments:R}};r(B);const z={...s,preferences:B};i(z),l(K=>({...K,[b]:C}))};if(!h.length||!((s==null?void 0:s.type)==="stackedBar"||(s==null?void 0:s.type)==="stackedLine"?((v=(S=s==null?void 0:s.config)==null?void 0:S.groupByColumns)==null?void 0:v.length)||((M=(k=s==null?void 0:s.config)==null?void 0:k.pivotByColumns)==null?void 0:M.length):(O=(f=s==null?void 0:s.config)==null?void 0:f.groupByColumns)==null?void 0:O.length)||["table","kpi","text","custom","heatmap"].includes(a))return null;const V=()=>{const b={...n||{},colorConfig:{segments:{}}};r(b);const L={...s,preferences:b};i(L);const C={};h.forEach((P,R)=>{C[P]=t.getColorForValue(P,R,void 0)}),l(C)},E=Object.keys(((F=n==null?void 0:n.colorConfig)==null?void 0:F.segments)||{}).length>0;return e.jsxs(t.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Colors"})]})}),e.jsx(t.AccordionContent,{className:"",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("div",{className:"flex items-center justify-between",children:E&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:V,children:[e.jsx(ea,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:h.map((b,L)=>{const C=t.isDefaultColor(d[b],L),P=!C;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Popover,{open:m===b,onOpenChange:R=>p(R?b: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[b]}})}),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((R,B)=>e.jsxs("button",{className:t.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",d[b]===R?"border-gray-900":"border-transparent"),style:{backgroundColor:R},onClick:()=>{y(b,R),p(null)},children:[B===L%g.length&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-white/90 px-0.5 text-[8px] font-bold text-gray-900 shadow-sm",children:"D"})}),e.jsx("span",{className:"sr-only",children:R})]},`default-${B}`))})]}),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:Jr.map((R,B)=>e.jsx("button",{className:t.cn("h-5 w-5 rounded border transition-all hover:scale-110",d[b]===R?"border-2 border-gray-900":R==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:R},onClick:()=>{y(b,R),p(null)},children:e.jsx("span",{className:"sr-only",children:R})},`preset-${B}`))})]}),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:()=>{u({value:b,color:d[b]}),p(null)},children:"Custom color"}),!C&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{j(b,L),p(null)},children:[e.jsx(ea,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:b}),P&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},b)})}),x&&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:()=>u(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Va,{color:x.color,onColorChange:b=>{y(x.value,b),u(null)},onClose:()=>u(null)})})]})]})})]})}function Je({value:s,onSave:n,placeholder:a="",type:r="text",className:i=""}){const[c,o]=N.useState(s??""),[d,l]=N.useState(!1);N.useEffect(()=>{o(s??"")},[s]);const m=()=>{n(c),l(!1)},p=()=>{o(s??""),l(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${i}`,children:[e.jsx(t.Input$1,{placeholder:a,type:r,value:d?c:s??"",onChange:x=>{o(x.target.value),l(!0)},onFocus:()=>l(!0),onClick:x=>x.stopPropagation(),className:"h-8 text-xs",onPointerDown:x=>x.stopPropagation(),onKeyDown:x=>{x.stopPropagation(),x.key==="Enter"&&d&&c!==s?m():x.key==="Escape"&&p()},"aria-label":a||"Edit field"}),d&&c!==s&&e.jsxs(e.Fragment,{children:[e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:m,children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:p,children:e.jsx(t.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function es({axis:s,label:n,type:a,config:r,onChange:i,defaultTitle:c,hidePosition:o}){var g,y,j,I,D,V,E,w,T,A,S,v,k,M;const d=t.normalizeContextFormatMode({formatMode:r==null?void 0:r.formatMode,formatOptions:r==null?void 0:r.formatOptions}),l=(f,O)=>{i({...r??{},[f]:O})},m=(f,O)=>{var C,P,R,B;const F=f==="enabled"&&O===!0,b=(C=r==null?void 0:r.name)==null?void 0:C.text,L=F&&!b&&c;i({...r??{},name:{...r==null?void 0:r.name,enabled:f==="enabled"?O:((P=r==null?void 0:r.name)==null?void 0:P.enabled)??!1,text:f==="text"?O:L?c:b,fontSize:f==="fontSize"?O:(R=r==null?void 0:r.name)==null?void 0:R.fontSize,fontWeight:f==="fontWeight"?O:(B=r==null?void 0:r.name)==null?void 0:B.fontWeight}})},p=(f,O)=>{var F,b;i({...r??{},labels:{enabled:f==="enabled"?O:((F=r==null?void 0:r.labels)==null?void 0:F.enabled)??!0,rotation:f==="rotation"?O:(b=r==null?void 0:r.labels)==null?void 0:b.rotation}})},x=(f,O)=>{i({...r??{},scale:{...r==null?void 0:r.scale,[f]:O===""?"auto":Number(O)}})},u=s==="x"?["auto","top","bottom"]:["auto","left","right"],h=["auto","0","45","90","-45","-90"];return e.jsxs(t.AccordionItem,{value:`${s}-axis`,className:"border-b-0",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx(t.AccordionTrigger,{className:"flex grow items-center justify-between gap-3 py-2 text-sm font-medium hover:no-underline",children:e.jsx("div",{className:"flex grow items-center justify-between gap-2",children:e.jsx("span",{children:n})})}),e.jsx(t.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:f=>l("enabled",f),onClick:f=>f.stopPropagation()})]}),e.jsxs(t.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Checkbox,{id:`${s}-title-enabled`,checked:((g=r==null?void 0:r.name)==null?void 0:g.enabled)??!1,onCheckedChange:f=>m("enabled",f===!0)}),e.jsx(t.Label,{htmlFor:`${s}-title-enabled`,className:"text-xs font-medium cursor-pointer",children:"TITLE"})]}),((y=r==null?void 0:r.name)==null?void 0:y.enabled)&&e.jsxs("div",{className:"space-y-2 pl-6",children:[e.jsx(Je,{placeholder:`${n} title`,value:((j=r==null?void 0:r.name)==null?void 0:j.text)||"",onSave:f=>m("text",f),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(Je,{type:"number",placeholder:"12",value:String(((I=r==null?void 0:r.name)==null?void 0:I.fontSize)||12),onSave:f=>m("fontSize",Number(f)||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:((D=r==null?void 0:r.name)==null?void 0:D.fontWeight)||"normal",onValueChange:f=>m("fontWeight",f),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:(r==null?void 0:r.position)||"auto",onValueChange:f=>l("position",f),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:u.map(f=>e.jsx(t.SelectItem,{value:f,className:"text-xs",children:f==="auto"?"Auto (Default)":t.titleCase(f)},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 font-medium",children:"LABELS"}),e.jsx(t.SmallSwitch,{checked:((V=r==null?void 0:r.labels)==null?void 0:V.enabled)!==!1,onCheckedChange:f=>p("enabled",f)})]}),((E=r==null?void 0:r.labels)==null?void 0:E.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(((w=r==null?void 0:r.labels)==null?void 0:w.rotation)||"auto"),onValueChange:f=>p("rotation",f==="auto"?"auto":Number(f)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:h.map(f=>e.jsx(t.SelectItem,{value:f,className:"text-xs",children:f==="auto"?"Auto (Default)":`${f}°`},f))})]})]})]}),a==="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.SmallSwitch,{checked:d==="override",onCheckedChange:f=>i({...r,formatMode:f?"override":"inherit"})})]}),d==="override"&&e.jsx(gt,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:f=>i({...r,formatMode:"override",formatOptions:f}),showTitle:!1})]}),a==="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(Je,{type:"number",placeholder:"auto",value:((T=r==null?void 0:r.scale)==null?void 0:T.min)==="auto"||((A=r==null?void 0:r.scale)==null?void 0:A.min)===void 0?"":String(r.scale.min),onSave:f=>x("min",f),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(Je,{type:"number",placeholder:"auto",value:((S=r==null?void 0:r.scale)==null?void 0:S.max)==="auto"||((v=r==null?void 0:r.scale)==null?void 0:v.max)===void 0?"":String(r.scale.max),onSave:f=>x("max",f),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(Je,{type:"number",placeholder:"auto",value:((k=r==null?void 0:r.scale)==null?void 0:k.stepSize)==="auto"||((M=r==null?void 0:r.scale)==null?void 0:M.stepSize)===void 0?"":String(r.scale.stepSize),onSave:f=>x("stepSize",f),className:""})})]})]})]})]})]})}function ts(s,n,a){var c,o,d;if(s==="x"){const l=(o=(c=n==null?void 0:n.config)==null?void 0:c.groupByColumns)==null?void 0:o[0];return(l==null?void 0:l.label)||(l==null?void 0:l.name)||""}const r=((d=n==null?void 0:n.config)==null?void 0:d.metricColumns)||[],i=(a==null?void 0:a.datasetOptions)||[];if(s==="y"){const l=r.filter((m,p)=>{const x=i.find(u=>u.idx===p);return!x||x.yAxisId!=="y2"});return l.length===1&&(l[0].label||l[0].name)||""}if(s==="y2"){const l=r.filter((m,p)=>{const x=i.find(u=>u.idx===p);return(x==null?void 0:x.yAxisId)==="y2"});return l.length===1&&(l[0].label||l[0].name)||""}return""}function Wr(){const s=t.useEditorStore(l=>l.card),n=t.useEditorStore(l=>{var m;return(m=l.card)==null?void 0:m.preferences}),{setCardPreferences:a,updateCardInFrame:r}=t.useEditorActions(),i=De.useEffectiveEditorCardType();if(!s||["tornado","pyramid","kpi","treemap"].includes(i))return null;const c=t.AxisConfigurator.getAxisInfo(i,n);if(!c.hasXAxis&&!c.hasYAxis)return null;const o=(l,m)=>{let p;l==="x"?p="xAxisConfig":l==="y"?p="yAxisConfig":p="secondaryYAxisConfig";const x={...n||{},[p]:m};a(x);const u={...s,preferences:x};r(u)},d=c.hasY2Axis&&i==="combo";return e.jsxs(t.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.SlidersHorizontal,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Axes"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsxs(t.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[c.hasXAxis&&e.jsx(es,{axis:"x",label:"X-Axis",type:c.xAxisType,config:t.mergeAxisConfig(t.getDefaultAxisConfig(i,"x"),n==null?void 0:n.xAxisConfig),onChange:l=>o("x",l),defaultTitle:ts("x",s,n)}),c.hasYAxis&&e.jsx(es,{axis:"y",label:d?"Y-Axis (Left)":"Y-Axis",type:c.yAxisType,config:t.mergeAxisConfig(t.getDefaultAxisConfig(i,"y"),n==null?void 0:n.yAxisConfig),onChange:l=>o("y",l),defaultTitle:ts("y",s,n)}),d&&e.jsx(es,{axis:"y2",label:"Y2-Axis (Right)",type:"value",config:t.mergeAxisConfig({enabled:!0,position:"right"},n==null?void 0:n.secondaryYAxisConfig),onChange:l=>o("y2",l),defaultTitle:ts("y2",s,n),hidePosition:!0})]})})]})}function Xr(){const s=t.useEditorStore(x=>x.card),n=De.useEffectiveEditorCardType(),a=t.useEditorStore(x=>{var u,h,g,y;return(y=(g=(h=(u=x.card)==null?void 0:u.preferences)==null?void 0:h.chartOptions)==null?void 0:g.plugins)==null?void 0:y.legend}),{setLegendOptions:r}=t.useEditorActions();if(!s||!t.chartSupportsLegend(n))return null;const i=t.getDefaultLegendConfig(n),c=(i==null?void 0:i.display)??!0,o=(i==null?void 0:i.position)??"top",d=(i==null?void 0:i.align)??"center",l=(x,u)=>{const h={...a,[x]:u};r(h)},m=["top","bottom","left","right"],p=["start","center","end"];return e.jsxs(t.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(t.SmallSwitch,{checked:(a==null?void 0:a.display)??c,onCheckedChange:x=>l("display",x)})]}),((a==null?void 0:a.display)??c)&&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:(a==null?void 0:a.position)||o,onValueChange:x=>l("position",x),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:m.map(x=>e.jsx(t.SelectItem,{value:x,className:"text-xs",children:t.titleCase(x)},x))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(t.Select,{value:(a==null?void 0:a.align)||d,onValueChange:x=>l("align",x),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:p.map(x=>e.jsx(t.SelectItem,{value:x,className:"text-xs",children:t.titleCase(x)},x))})]})]})]})]})})]})}function Zr(){var O,F,b,L,C,P,R;const s=t.useEditorStore(B=>B.card),n=De.useEffectiveEditorCardType(),a=t.useEditorStore(B=>{var z,_;return(_=(z=B.card)==null?void 0:z.preferences)==null?void 0:_.dataLabelsConfig}),r=t.useEditorStore(B=>{var z;return(z=B.card)==null?void 0:z.preferences}),{setCardPreferences:i,updateCardInFrame:c}=t.useEditorActions();if(!s||!t.chartSupportsDataLabels(n))return null;const o=n==="bullet"?((O=r==null?void 0:r.bulletConfig)==null?void 0:O.orientation)??(((F=r==null?void 0:r.chartOptions)==null?void 0:F.indexAxis)==="x"?"vertical":"horizontal"):void 0,d=o!=null?o==="horizontal":((b=r==null?void 0:r.chartOptions)==null?void 0:b.indexAxis)==="y",l=n==="stackedBar"||n==="stackedLine",m=n==="pie"||n==="doughnut"||n==="polarArea"||n==="funnel",p=n==="bubble"||n==="scatter",x=(C=(L=r==null?void 0:r.chartOptions)==null?void 0:L.plugins)==null?void 0:C.datalabels,u=(x==null?void 0:x.display)!==!1&&((x==null?void 0:x.anchor)||(x==null?void 0:x.align)),h=t.getDefaultDataLabelsConfig(n,s.preferences),g=a??h,y=(h==null?void 0:h.enabled)??u??!1,j=(a==null?void 0:a.enabled)!==void 0?a.enabled:y,I=(B,z)=>{const H={...h??{},...a??{},[B]:z};B==="enabled"&&(H.display=z,z&&p&&!H.position&&(H.position="bottom")),B==="position"&&p&&(H.position="bottom"),B==="formatMode"&&z==="inherit"&&(H.format=void 0,H.formatOptions=void 0);const G={...s.preferences||{},dataLabelsConfig:H};i(G);const X={...s,preferences:G};c(X)},D=(B,z)=>{const _=a??{},H={...h??{},..._,font:{..._.font||{},[B]:z}},G={...s.preferences||{},dataLabelsConfig:H};i(G);const X={...s,preferences:G};c(X)},V=()=>{const B=n;return B==="stackedBar"||B==="stackedLine"||B==="pie"||B==="doughnut"?"center":d?"right":"top"},E=n!=="treemap"&&n!=="heatmap",w=n!=="treemap",T=V();let A=[];if(E)if(p)A=["bottom"];else if(l||m)A=["center"];else{const B=d?["center","left","right"]:["center","top","bottom"];A=["auto",...n==="bullet"?B:B.filter(_=>_!==T),"custom"]}const S=()=>t.titleCase(T),v=["center","start","end"],k=["center","start","end","top","bottom"],M=(g==null?void 0:g.formatMode)||(g!=null&&g.format&&!["auto"].includes(g.format)?"override":"inherit"),f=(g==null?void 0:g.format)==="none";return e.jsxs(t.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(t.SmallSwitch,{checked:j,onCheckedChange:B=>I("enabled",B)})]}),j&&e.jsxs(e.Fragment,{children:[E&&!l&&!m&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(t.Select,{value:p?(g==null?void 0:g.position)||"bottom":(g==null?void 0:g.position)||"auto",onValueChange:B=>I("position",B),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:A.map(B=>e.jsx(t.SelectItem,{value:B,className:"text-xs",children:B==="auto"?S():B==="custom"?"Custom (Advanced)":t.titleCase(B)},B))})]})]}),l&&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.SmallSwitch,{checked:(a==null?void 0:a.showTotal)??!1,onCheckedChange:B=>I("showTotal",B)})]}),(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:B=>I("anchor",B),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:v.map(B=>e.jsx(t.SelectItem,{value:B,className:"text-xs",children:t.titleCase(B)},B))})]})]}),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:B=>I("align",B),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:k.map(B=>e.jsx(t.SelectItem,{value:B,className:"text-xs",children:t.titleCase(B)},B))})]})]})]}),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.SmallSwitch,{checked:M==="override",onCheckedChange:B=>I("formatMode",B?"override":"inherit")})]}),M==="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.SmallSwitch,{checked:f,onCheckedChange:B=>{const z=a??{},K={...h??{},...z,formatMode:"override",format:B?"none":void 0,formatOptions:B?void 0:z.formatOptions},H={...s.preferences||{},dataLabelsConfig:K};i(H),c({...s,preferences:H})}})]}),!f&&e.jsx(gt,{formatOptions:(g==null?void 0:g.formatOptions)||{},onFormatOptionsChange:B=>{const K={...h??{},...a??{},formatMode:"override",format:B.type&&B.type!=="auto"?B.type:void 0,formatOptions:B},H={...s.preferences||{},dataLabelsConfig:K};i(H),c({...s,preferences:H})},showTitle:!1})]})]}),w&&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(Je,{type:"number",placeholder:"12",value:String(((P=g==null?void 0:g.font)==null?void 0:P.size)||12),onSave:B=>D("size",Number(B)),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:((R=g==null?void 0:g.font)==null?void 0:R.weight)||"normal",onValueChange:B=>D("weight",B),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:B=>{B==="auto"&&I("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(Je,{type:"number",placeholder:"0",value:String((g==null?void 0:g.rotation)||0),onSave:B=>I("rotation",Number(B)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}const fa={difference:{label:"Difference",description:"Shows the exact difference between two values.",formula:"Primary - Secondary",example:"Sales increased by $5,000 compared to last year."},change:{label:"Change",description:"Shows the percentage increase or decrease between two values.",formula:"(Primary - Secondary) / Secondary × 100%",example:"Year-over-year sales change of 25%."},change_difference:{label:"Change (difference)",description:"Shows both the percentage change and the exact difference between two values.",formula:`% Change: (Primary - Secondary) / Secondary × 100%
188
+ Difference: Primary - Secondary`,example:"Sales grew by 25% ($5,000) compared to last year."},ratio:{label:"Ratio",description:"Shows how much of one value is covered by another — useful for quotas and benchmarks.",formula:"Primary / Secondary × 100%",example:"You've achieved 80% of your sales quota."}};function el(){var u,h,g,y,j,I,D,V,E,w;const s=t.useEditorStore(T=>T.card),{setCardPreferences:n}=t.useEditorActions(),a=De.useEffectiveEditorCardType(),r=((u=s.config)==null?void 0:u.metricColumns)||[],i=((h=s.config)==null?void 0:h.groupByColumns)||[],c=r.length===2&&i.length===0,o=r.some(T=>T.comparisonType&&T.comparisonType!=="none");if(!(a==="kpi"&&(c||o)))return null;const l=((y=(g=s.preferences)==null?void 0:g.kpiVisualOptions)==null?void 0:y.metricComparison)||{},m=T=>{var S;const A={...s.preferences,kpiVisualOptions:{...(S=s.preferences)==null?void 0:S.kpiVisualOptions,metricComparison:{...l,...T}}};n(A)},p=o||l.enabled,x=r.some(T=>T.comparisonType==="previous_period"||T.comparisonType==="same_period_last_year"||T.comparisonType==="start_vs_end");return e.jsxs(t.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(t.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ta,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[c&&r.length===2&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(t.SmallSwitch,{id:"enable-comparison",checked:l.enabled||!1,onCheckedChange:T=>m({enabled:T,...T&&!l.calculationType?{calculationType:"difference"}:{}})})]}),p&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(t.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.Info,{className:"h-3 w-3 cursor-help text-muted-foreground"})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:(()=>{const T=l.calculationType||"difference",A=fa[T];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:A==null?void 0:A.label}),e.jsx("p",{children:A==null?void 0:A.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:A==null?void 0:A.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",A==null?void 0:A.example]})]})})()})]})]}),e.jsxs(t.Select,{value:l.calculationType||"difference",onValueChange:T=>m({calculationType:T}),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(fa).map(([T,A])=>e.jsx(t.SelectItem,{value:T,className:"text-xs",children:A.label},T))})]})]}),e.jsx(gt,{formatOptions:l.formatOptions||{},onFormatOptionsChange:T=>m({formatOptions:T}),showTitle:!0,title:"COMPARISON FORMAT"}),(x||c)&&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"}),c&&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:l.position||"right",onValueChange:T=>m({position:T}),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"right",className:"text-xs",children:"Right"}),e.jsx(t.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(t.SelectItem,{value:"top",className:"text-xs",children:"Top"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Checkbox,{id:"show-arrow",checked:l.showArrow!==!1,onCheckedChange:T=>m({showArrow:T})}),e.jsx(t.Label,{htmlFor:"show-arrow",className:"cursor-pointer text-xs text-muted-foreground",children:"Arrow"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Checkbox,{id:"show-color",checked:l.showColor!==!1,onCheckedChange:T=>m({showColor:T})}),e.jsx(t.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),l.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(Ze,{value:((j=l.colorConfig)==null?void 0:j.increase)||"green",onChange:T=>m({colorConfig:{...l.colorConfig,increase:T}}),label:"Primary > Secondary"}),e.jsx(Ze,{value:((I=l.colorConfig)==null?void 0:I.decrease)||"red",onChange:T=>m({colorConfig:{...l.colorConfig,decrease:T}}),label:"Primary < Secondary"}),e.jsx(Ze,{value:((D=l.colorConfig)==null?void 0:D.noChange)||"neutral",onChange:T=>m({colorConfig:{...l.colorConfig,noChange:T}}),label:"Primary = Secondary"})]})]}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Checkbox,{id:"conditional-label",checked:l.conditionalLabel||!1,onCheckedChange:T=>m({conditionalLabel:T})}),e.jsx(t.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),l.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:((V=l.conditionalLabels)==null?void 0:V.increase)??"Increase",onChange:T=>m({conditionalLabels:{...l.conditionalLabels,increase:T.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:((E=l.conditionalLabels)==null?void 0:E.decrease)??"Decrease",onChange:T=>m({conditionalLabels:{...l.conditionalLabels,decrease:T.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:((w=l.conditionalLabels)==null?void 0:w.noChange)??"No change",onChange:T=>m({conditionalLabels:{...l.conditionalLabels,noChange:T.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:l.labelName??"",onChange:T=>m({labelName:T.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function tl(){var c;const s=t.useEditorStore(o=>{var d;return(d=o.card)==null?void 0:d.type}),n=t.useEditorStore(o=>{var d;return(d=o.card)==null?void 0:d.preferences}),{setCardPreferences:a}=t.useEditorActions();if(s!=="treemap")return null;const r=((c=n==null?void 0:n.chartOptions)==null?void 0:c.treemapColorMode)??"branch",i=o=>{const d={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,treemapColorMode:o}};a(d)};return e.jsxs(t.AccordionItem,{value:"treemap-color-mode",className:"border-none",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.TbChartTreemap,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Treemap Colors"})]})}),e.jsx(t.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:e.jsxs(t.RadioGroup,{value:r,onValueChange:o=>i(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(t.RadioGroupItem,{id:"treemap-color-branch",value:"branch"}),e.jsxs(t.Label,{htmlFor:"treemap-color-branch",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Shade by value (default)"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Keeps parent hue and adjusts lightness based on the node's share within the branch."})]})]}),e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(t.RadioGroupItem,{id:"treemap-color-category",value:"category"}),e.jsxs(t.Label,{htmlFor:"treemap-color-category",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Single color per category"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Applies the top-level color to all descendants without lightening/darkening."})]})]})]})})]})}const sl=Object.keys(t.HEATMAP_PRESET_PALETTES);function al(){const s=t.useEditorStore(u=>u.card),n=t.useEditorStore(u=>{var h;return(h=u.card)==null?void 0:h.preferences}),{setCardPreferences:a}=t.useEditorActions(),r=(s==null?void 0:s.type)==="heatmap",i=(n==null?void 0:n.heatmapConfig)||{},c=i.colorPalette??"green",o=i.legendPosition??"bottom",d=N.useMemo(()=>i.colorRange&&i.colorRange[0]&&i.colorRange[1]?[i.colorRange[0],i.colorRange[1]]:[...t.DEFAULT_HEATMAP_CUSTOM_RANGE],[i.colorRange]),l=u=>{const h={...i,...u};h.colorPalette!=="custom"?delete h.colorRange:(!h.colorRange||!h.colorRange[0]||!h.colorRange[1])&&(h.colorRange=[...t.DEFAULT_HEATMAP_CUSTOM_RANGE]),a({...n||{},heatmapConfig:h})},m=u=>{l({colorPalette:u,colorRange:u==="custom"?i.colorRange??[...t.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},p=(u,h)=>{const g=[...d];g[u]=h,l({colorPalette:"custom",colorRange:g})},x=u=>{l({legendPosition:u})};return r?e.jsxs(t.AccordionItem,{value:"heatmap-color-config",className:"border-none",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Grid3x3,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Heatmap Settings"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs(t.RadioGroup,{value:c,onValueChange:u=>m(u??"blue"),className:"space-y-3",children:[sl.map(u=>{const h=t.HEATMAP_PRESET_PALETTES[u];return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(t.RadioGroupItem,{id:`heatmap-${u}`,value:u}),e.jsxs(t.Label,{htmlFor:`heatmap-${u}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:h.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${h.start}, ${h.end})`}})]})]},u)}),e.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.RadioGroupItem,{id:"heatmap-custom",value:"custom"}),e.jsx(t.Label,{htmlFor:"heatmap-custom",className:"text-sm font-medium",children:"Custom colors"})]}),c==="custom"&&e.jsxs("div",{className:"flex flex-col gap-3 pl-6",children:[e.jsx(Ze,{value:d[0],onChange:u=>p(0,u),label:"Start color"}),e.jsx(Ze,{value:d[1],onChange:u=>p(1,u),label:"End color"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Color scale position"}),e.jsxs(t.Select,{value:o,onValueChange:u=>x(u??"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(u=>e.jsx(t.SelectItem,{value:u,className:"text-xs",children:u[0].toUpperCase()+u.slice(1)},u))})]})]})]})]}):null}const ga=["poor","satisfactory","good"];function ja(s){if(!s)return;const n={...s};return n.targetMetricKey||delete n.targetMetricKey,n.comparativeMetricKey||delete n.comparativeMetricKey,!n.targetValue&&n.targetValue!==0&&delete n.targetValue,(!n.rangeKeys||Object.keys(n.rangeKeys).length===0)&&delete n.rangeKeys,(!n.ranges||Object.keys(n.ranges).length===0)&&delete n.ranges,(!n.rangeLabels||Object.keys(n.rangeLabels).length===0)&&delete n.rangeLabels,n}function nl(){var O,F;const s=t.useEditorStore(b=>b.card.preferences),n=t.useEditorStore(b=>b.card),a=t.useEditorStore(b=>b.isDevMode),{setCardPreferences:r,setChartOrientation:i}=t.useEditorActions(),c=N.useMemo(()=>(s==null?void 0:s.bulletConfig)||{},[s==null?void 0:s.bulletConfig]),d=t.hasValidCardConfig(n==null?void 0:n.config)&&!a,[l,m]=N.useState(c.showRanges??!1),[p,x]=N.useState(c.rangesArePercentages??!1),u=c.disableAutoComparative?!1:c.comparativeMetricKey!==void 0||!d,[h,g]=N.useState(u);N.useEffect(()=>{m(c.showRanges??!1)},[c.showRanges]),N.useEffect(()=>{x(c.rangesArePercentages??!1)},[c.rangesArePercentages]);const y=c.targetValue===void 0?"":String(c.targetValue);N.useEffect(()=>{const b=c.disableAutoComparative?!1:c.comparativeMetricKey!==void 0||!d;g(b)},[c.disableAutoComparative,c.comparativeMetricKey,d]);const j=N.useMemo(()=>{var b,L;return((L=(b=n==null?void 0:n.config)==null?void 0:b.metricColumns)==null?void 0:L.map(C=>{const P=C.label||C.name||C.alias||"";return{value:P,label:P}}))||[]},[(O=n==null?void 0:n.config)==null?void 0:O.metricColumns]);N.useEffect(()=>{var _,K;if(!s||j.length===0)return;const b={};let L=!1;const C=(_=j[1])==null?void 0:_.value;!c.targetMetricKey&&C&&(b.targetMetricKey=C,L=!0);const P=(K=j[2])==null?void 0:K.value;!c.comparativeMetricKey&&!c.disableAutoComparative&&P&&(b.comparativeMetricKey=P,L=!0);const R=j.slice(3),B={...c.rangeKeys||{}};let z=!1;if(ga.forEach((H,G)=>{!B[H]&&R[G]&&(B[H]=R[G].value,z=!0)}),z&&(b.rangeKeys=B,L=!0,c.showRanges===void 0&&(b.showRanges=!0)),L){const H=ja({...c,...b});r({...s,bulletConfig:H})}},[j,c,s,r]);const I=b=>{const L=ja({...c,...b});r({...s,bulletConfig:L})},D=(b,L)=>{const C={...c.rangeKeys||{},[b]:L.trim()};L.trim()||delete C[b],I({rangeKeys:Object.keys(C).length>0?C:void 0})},V=(b,L)=>{const C=L===""?void 0:Number(L),P={...c.ranges||{}};C===void 0||Number.isNaN(C)?delete P[b]:P[b]=C,I({ranges:Object.keys(P).length?P:void 0})},E=b=>{if(b===""){I({targetValue:void 0});return}const L=Number(b);I({targetValue:Number.isNaN(L)?void 0:L})},w=(b,L)=>{const C=L.trim(),P={...c.rangeLabels||{}};C?P[b]=C:delete P[b],I({rangeLabels:Object.keys(P).length>0?P:void 0})},T=b=>{m(b),I({showRanges:b})},A=b=>{x(b),I({rangesArePercentages:b})},S=c.orientation||(((F=s==null?void 0:s.chartOptions)==null?void 0:F.indexAxis)==="y"?"horizontal":"vertical"),v=b=>{I({orientation:b}),i(b==="horizontal"?"y":"x")},k=[{value:"__none",label:"None"},...j.map(b=>({value:b.value,label:b.label}))],M=k,f=b=>{if(g(b),!b){I({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!d){I({disableAutoComparative:!1});return}if(c.comparativeMetricKey)I({disableAutoComparative:!1});else{const L=j.find(C=>C.value!==c.targetMetricKey);I({comparativeMetricKey:L==null?void 0:L.value,disableAutoComparative:!1})}};return e.jsxs(t.AccordionItem,{value:"bullet-config",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.BulletChartIcon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bullet Chart"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-6 border-t border-border/50 py-4",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"ORIENTATION"}),e.jsxs(t.Select,{value:S,onValueChange:b=>v(b),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:c.targetMetricKey||"__none",onValueChange:b=>I({targetMetricKey:b==="__none"?void 0:b}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select metric"})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"__none",className:"text-xs",children:"None"}),j.map(b=>e.jsx(t.SelectItem,{value:b.value,className:"text-xs",children:b.label},b.value))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"COMPARATIVE METRIC"}),d?e.jsxs(t.Select,{value:c.comparativeMetricKey||"__none",onValueChange:b=>I({comparativeMetricKey:b==="__none"?void 0:b,disableAutoComparative:b==="__none"}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select metric"})}),e.jsx(t.SelectContent,{children:k.map(b=>e.jsx(t.SelectItem,{value:b.value,className:"text-xs",children:b.label},b.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.SmallSwitch,{checked:h,onCheckedChange:b=>f(b)})]}),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(Ve,{type:"number",className:"h-8 text-xs",value:y,onCommit:E,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.SmallSwitch,{checked:l,onCheckedChange:T})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:p,disabled:!l,onChange:b=>A(b.target.checked),className:"h-3.5 w-3.5 accent-primary disabled:opacity-50"}),e.jsx("span",{children:"Use % of value"})]})]}),l&&e.jsx("div",{className:"space-y-3",children:ga.map(b=>{var L,C,P,R,B;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:[b," LABEL"]}),e.jsx(Ve,{placeholder:`Display label (${b})`,value:((L=c.rangeLabels)==null?void 0:L[b])||"",onCommit:z=>w(b,z),className:"h-8 text-xs"})]}),d?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[b," COLUMN"]}),e.jsxs(t.Select,{value:((C=c.rangeKeys)==null?void 0:C[b])||"__none",onValueChange:z=>{z==="__none"?D(b,""):D(b,z)},children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select column"})}),e.jsx(t.SelectContent,{children:M.map(z=>e.jsx(t.SelectItem,{value:z.value,className:"text-xs",children:z.label},z.value))})]})]}):e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[b," COLUMN KEY"]}),e.jsx(Ve,{placeholder:"Column key",value:((P=c.rangeKeys)==null?void 0:P[b])||"",onCommit:z=>D(b,z),className:"h-8 text-xs"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[b," VALUE"]}),e.jsx(Ve,{type:"number",placeholder:p?"0.80":"Static value",value:((R=c.ranges)==null?void 0:R[b])===void 0?"":String((B=c.ranges)==null?void 0:B[b]),onCommit:z=>V(b,z),className:"h-8 text-xs"})]})]},b)})})]})]})]})}function ba(s){if(!s)return;const n={...s};if(n.xMetricKey||delete n.xMetricKey,n.yMetricKey||delete n.yMetricKey,n.radiusMetricKey||delete n.radiusMetricKey,n.labelKey||delete n.labelKey,n.groupKey||delete n.groupKey,n.enableGrouping===void 0&&delete n.enableGrouping,n.radiusScale||delete n.radiusScale,n.fixedRadius===void 0&&delete n.fixedRadius,n.minRadius===void 0&&delete n.minRadius,n.maxRadius===void 0&&delete n.maxRadius,Object.keys(n).length!==0)return n}function rl(){var w,T,A,S,v,k,M,f,O,F,b,L;const s=t.useEditorStore(C=>C.card.preferences),n=t.useEditorStore(C=>C.card),a=De.useEffectiveEditorCardType(),r=t.useEditorStore(C=>C.isDevMode),{setCardPreferences:i,updateCardInFrame:c}=t.useEditorActions(),o=a==="bubble",d=a==="scatter",l=N.useMemo(()=>(s==null?void 0:s.bubbleScatterConfig)||{},[s==null?void 0:s.bubbleScatterConfig]),p=t.hasValidCardConfig(n==null?void 0:n.config)&&!r,x=N.useMemo(()=>{var C,P;return((P=(C=n==null?void 0:n.config)==null?void 0:C.metricColumns)==null?void 0:P.map(R=>{const B=R.label||R.name||R.alias||"";return{value:B,label:B}}))||[]},[(w=n==null?void 0:n.config)==null?void 0:w.metricColumns]),u=N.useMemo(()=>{var C,P;return((P=(C=n==null?void 0:n.config)==null?void 0:C.groupByColumns)==null?void 0:P.map(R=>{const B=R.label||R.name||R.alias||"";return{value:B,label:B}}))||[]},[(T=n==null?void 0:n.config)==null?void 0:T.groupByColumns]),h=N.useMemo(()=>l.enableGrouping!==void 0?l.enableGrouping:!r&&u.length>=2,[l.enableGrouping,r,u.length]),[g,y]=N.useState(h);N.useEffect(()=>{y(h)},[h]);const j=C=>{const P={...s||{},bubbleScatterConfig:C};i(P),n&&c({...n,preferences:P})},I=C=>{i(C),n&&c({...n,preferences:C})};N.useEffect(()=>{if(!s||x.length===0)return;const C={};let P=!1;if(!l.xMetricKey&&x[0]&&(C.xMetricKey=x[0].value,P=!0),!l.yMetricKey&&x[1]&&(C.yMetricKey=x[1].value,P=!0),o&&!l.radiusMetricKey&&x[2]&&(C.radiusMetricKey=x[2].value,P=!0),!l.labelKey&&u[0]&&(C.labelKey=u[0].value,P=!0),h&&!l.groupKey&&u[1]&&(C.groupKey=u[1].value,C.enableGrouping=!0,P=!0),P){const R=ba({...l,...C});j(R)}},[x,u,l,s,i,o,h]);const D=C=>{const P=ba({...l,...C});j(P)},V=C=>{y(C),D({enableGrouping:C,groupKey:C?l.groupKey:void 0})};if(!o&&!d)return null;const E=o?t.Circle:t.ChartScatter;return e.jsxs(t.AccordionItem,{value:"bubble-scatter-config",children:[e.jsx(t.AccordionTrigger,{className:"py-2 text-sm",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(E,{className:"h-4 w-4"}),e.jsxs("span",{children:[o?"Bubble":"Scatter"," Configuration"]})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-1 pb-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-1 text-xs font-medium text-muted-foreground",children:["Dimensions",e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{children:e.jsx(t.Info,{className:"h-3 w-3"})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{children:"Label identifies each point. Group creates separate series in the legend."})})]})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Label Column"}),p?e.jsxs(t.Select,{value:l.labelKey||"",onValueChange:C=>D({labelKey:C}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select label column"})}),e.jsx(t.SelectContent,{children:u.map(C=>e.jsx(t.SelectItem,{value:C.value,children:C.label},C.value))})]}):e.jsx(Ve,{className:"h-8 text-xs",placeholder:"Column name for labels",value:l.labelKey||"",onCommit:C=>D({labelKey:C})})]}),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.SmallSwitch,{checked:g,onCheckedChange:V})]}),g&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Group By"}),p?e.jsxs(t.Select,{value:l.groupKey||"",onValueChange:C=>D({groupKey:C}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select group column"})}),e.jsx(t.SelectContent,{children:u.map(C=>e.jsx(t.SelectItem,{value:C.value,children:C.label},C.value))})]}):e.jsx(Ve,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:l.groupKey||"",onCommit:C=>D({groupKey:C})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Metrics"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"X Axis"}),p?e.jsxs(t.Select,{value:l.xMetricKey||"",onValueChange:C=>D({xMetricKey:C}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select X metric"})}),e.jsx(t.SelectContent,{children:x.map(C=>e.jsx(t.SelectItem,{value:C.value,children:C.label},C.value))})]}):e.jsx(Ve,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:l.xMetricKey||"",onCommit:C=>D({xMetricKey:C})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Axis"}),p?e.jsxs(t.Select,{value:l.yMetricKey||"",onValueChange:C=>D({yMetricKey:C}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select Y metric"})}),e.jsx(t.SelectContent,{children:x.map(C=>e.jsx(t.SelectItem,{value:C.value,children:C.label},C.value))})]}):e.jsx(Ve,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:l.yMetricKey||"",onCommit:C=>D({yMetricKey:C})})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Radius"}),p?e.jsxs(t.Select,{value:l.radiusMetricKey||"",onValueChange:C=>D({radiusMetricKey:C}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select radius metric"})}),e.jsx(t.SelectContent,{children:x.map(C=>e.jsx(t.SelectItem,{value:C.value,children:C.label},C.value))})]}):e.jsx(Ve,{className:"h-8 text-xs",placeholder:"Column name for radius",value:l.radiusMetricKey||"",onCommit:C=>D({radiusMetricKey:C})})]})]}),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:l.radiusScale||"sqrt",onValueChange:C=>D({radiusScale:C}),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"})]})]})]}),l.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(Ve,{className:"h-8 text-xs",type:"number",placeholder:"5",value:((A=l.minRadius)==null?void 0:A.toString())||"",onCommit:C=>D({minRadius:C?Number(C):void 0})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Max Radius"}),e.jsx(Ve,{className:"h-8 text-xs",type:"number",placeholder:"30",value:((S=l.maxRadius)==null?void 0:S.toString())||"",onCommit:C=>D({maxRadius:C?Number(C):void 0})})]})]}),l.radiusScale==="fixed"&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs(t.Label,{className:"text-xs",children:["Fixed Radius: ",l.fixedRadius||10]}),e.jsx(t.Slider,{value:[l.fixedRadius||10],onValueChange:([C])=>D({fixedRadius:C}),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: ",l.fixedRadius||5]}),e.jsx(t.Slider,{value:[l.fixedRadius||5],onValueChange:([C])=>D({fixedRadius:C}),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.SmallSwitch,{checked:((k=(v=s==null?void 0:s.xAxisConfig)==null?void 0:v.name)==null?void 0:k.enabled)??!1,onCheckedChange:C=>{var B,z,_,K;const P=l.xMetricKey||"X Axis",R=l.yMetricKey||"Y Axis";I({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{enabled:C,text:((z=(B=s==null?void 0:s.xAxisConfig)==null?void 0:B.name)==null?void 0:z.text)||P}},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{enabled:C,text:((K=(_=s==null?void 0:s.yAxisConfig)==null?void 0:_.name)==null?void 0:K.text)||R}}})}})]}),((f=(M=s==null?void 0:s.xAxisConfig)==null?void 0:M.name)==null?void 0:f.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(Ve,{className:"h-8 text-xs",placeholder:l.xMetricKey||"X Axis",value:((F=(O=s==null?void 0:s.xAxisConfig)==null?void 0:O.name)==null?void 0:F.text)||"",onCommit:C=>{var P;I({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{...(P=s==null?void 0:s.xAxisConfig)==null?void 0:P.name,enabled:!0,text:C||l.xMetricKey||"X Axis"}}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Title"}),e.jsx(Ve,{className:"h-8 text-xs",placeholder:l.yMetricKey||"Y Axis",value:((L=(b=s==null?void 0:s.yAxisConfig)==null?void 0:b.name)==null?void 0:L.text)||"",onCommit:C=>{var P;I({...s??{},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{...(P=s==null?void 0:s.yAxisConfig)==null?void 0:P.name,enabled:!0,text:C||l.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const ll=[{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 ol(){const s=t.useEditorStore(u=>u.card),n=t.useEditorStore(u=>{var h;return(h=u.card)==null?void 0:h.preferences}),{setCardPreferences:a}=t.useEditorActions(),r=(s==null?void 0:s.type)==="funnel",i=(n==null?void 0:n.funnelConfig)||{},c=i.percentMode??"percentOfTotal",o=i.shrinkFraction??1,d=i.labelThreshold??0,l=u=>{const h={...i,...u};a({...n||{},funnelConfig:h})},m=u=>{l({percentMode:u})},p=u=>{l({shrinkFraction:u[0]})},x=u=>{l({labelThreshold:u[0]})};return r?e.jsxs(t.AccordionItem,{value:"funnel-config",className:"border-none",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Filter,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Funnel Settings"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"PERCENTAGE MODE"}),e.jsx(t.RadioGroup,{value:c,onValueChange:u=>m(u),className:"space-y-2",children:ll.map(u=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(t.RadioGroupItem,{id:`funnel-${u.value}`,value:u.value,className:"mt-0.5"}),e.jsxs(t.Label,{htmlFor:`funnel-${u.value}`,className:"flex flex-col gap-0.5 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.description})]})]},u.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"SEGMENT SHRINK"}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Same Width"}),e.jsx(t.Slider,{value:[o],onValueChange:p,min:0,max:1,step:.1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Full Shrink"})]}),e.jsxs("p",{className:"text-center text-xs text-muted-foreground",children:["Current: ",Math.round(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(t.Slider,{value:[d],onValueChange:x,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 zt(){const s=t.useEditorStore(c=>c.card),{data:n}=t.useDashboardCardQuery(s),{keys:a}=t.getKeys((n==null?void 0:n.records)||[]),r=a.slice(1).filter(c=>!t.METADATA_KEYS.includes(c));let i=r;if(["stackedBar","stackedLine"].includes(s.type)){const c=t.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:o}=t.getKeys(c);i=o.slice(1)}return{transformedMetricKeys:i,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}const il=[{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"}],cl=[{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)"}],dl=["center","start","end"],ul=["center","start","end","top","bottom"];function qt({config:s,onChange:n,isHorizontal:a=!1,showAutoFormat:r=!0,positionOptions:i,showAppearance:c=!0}){var g,y,j,I,D,V;const o=i??(a?["auto","center","left","right","custom"]:["auto","center","top","bottom","custom"]),d=r?["auto","number","currency","percent","none"]:["number","currency","percent","none"],l=(E,w)=>{const T={...s,[E]:w};n(T)},m=(E,w)=>{const T={...s,font:{...(s==null?void 0:s.font)||{},[E]:w}};n(T)},p=(E,w)=>{const T={...s,formatOptions:{...(s==null?void 0:s.formatOptions)||{},[E]:w}};n(T)},x=()=>a?"Right":"Top",u=s||{},h=u.format||(r?"auto":"number");return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(t.Select,{value:u.position||"auto",onValueChange:E=>l("position",E),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:o.map(E=>e.jsx(t.SelectItem,{value:E,className:"text-xs",children:E==="auto"?x():E==="custom"?"Custom (Advanced)":t.titleCase(E)},E))})]})]}),u.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:u.anchor||"center",onValueChange:E=>l("anchor",E),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:dl.map(E=>e.jsx(t.SelectItem,{value:E,className:"text-xs",children:t.titleCase(E)},E))})]})]}),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(u.align||"center"),onValueChange:E=>l("align",E),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ul.map(E=>e.jsx(t.SelectItem,{value:E,className:"text-xs",children:t.titleCase(E)},E))})]})]})]}),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:h,onValueChange:E=>l("format",E),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:d.map(E=>e.jsx(t.SelectItem,{value:E,className:"text-xs",children:E==="auto"&&r?"Auto (Use Axis)":E==="none"?"None (Raw Value)":t.titleCase(E)},E))})]})]}),!["auto","none"].includes(h)&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[["number","currency","percent"].includes(h)&&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(Je,{type:"number",placeholder:"0",value:String(((g=u.formatOptions)==null?void 0:g.decimalPlaces)??(h==="currency"?2:h==="percent"?1:0)),onSave:E=>p("decimalPlaces",Number(E)),className:""})})]}),h==="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:((y=u.formatOptions)==null?void 0:y.currency)||"USD",onValueChange:E=>p("currency",E),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:il.map(E=>e.jsx(t.SelectItem,{value:E.value,className:"text-xs",children:E.label},E.value))})]})]}),["number","currency"].includes(h)&&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.SmallSwitch,{checked:((j=u.formatOptions)==null?void 0:j.useSuffix)??!1,onCheckedChange:E=>p("useSuffix",E)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Locale"}),e.jsxs(t.Select,{value:((I=u.formatOptions)==null?void 0:I.locale)||"en-US",onValueChange:E=>p("locale",E),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:cl.map(E=>e.jsx(t.SelectItem,{value:E.value,className:"text-xs",children:E.label},E.value))})]})]})]}),c&&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(Je,{type:"number",placeholder:"12",value:String(((D=u.font)==null?void 0:D.size)||12),onSave:E=>m("size",Number(E)),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:((V=u.font)==null?void 0:V.weight)||"normal",onValueChange:E=>m("weight",E),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:u.color==="auto"||!u.color?"auto":"custom",onValueChange:E=>{E==="auto"&&l("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(Je,{type:"number",placeholder:"0",value:String(u.rotation||0),onSave:E=>l("rotation",Number(E)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"°"})]})]})]})]})]})}const ml=[{type:"bar",icon:t.ChartColumnIncreasing,label:"Bar"},{type:"line",icon:t.ChartLine,label:"Line"}],xl=[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 │"}],pl=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function fl(){return t.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type})!=="combo"?null:e.jsxs(t.AccordionItem,{value:"combo-series",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsx(gl,{})})]})}function gl(){const{transformedMetricKeys:s}=zt();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((n,a)=>e.jsx(jl,{metricKey:n,idx:a},n))})}function jl({metricKey:s,idx:n}){var I;const[a,r]=N.useState(!1),i=t.useEditorStore(D=>{var V;return(V=D.card)==null?void 0:V.preferences}),c=t.useEditorStore(D=>{var V,E;return(E=(V=D.card)==null?void 0:V.preferences)==null?void 0:E.datasetOptions}),o=c==null?void 0:c.find(D=>D.idx===n),{setCardPreferences:d}=t.useEditorStore(D=>D.actions),l=(o==null?void 0:o.type)||"bar",m=(o==null?void 0:o.yAxisId)||"y",p=((I=o==null?void 0:o.dataLabels)==null?void 0:I.enabled)??!1,x=l==="line"?t.ChartLine:t.ChartColumnIncreasing;function u(D){const V={idx:n,type:l,yAxisId:m,dataLabels:o==null?void 0:o.dataLabels,...D};if(!o)d({...i||{},datasetOptions:[...c||[],V]});else{const E=c==null?void 0:c.map(w=>w.idx===n?{...w,...V}:w);d({...i||{},datasetOptions:E})}}function h(D){u({type:D})}function g(D){u({yAxisId:D})}function y(D){u({dataLabels:{...o==null?void 0:o.dataLabels,enabled:D}})}function j(D){u({dataLabels:D})}return e.jsx(t.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(t.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(t.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"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(x,{className:"h-3 w-3"}),l==="line"?"Line":"Bar"]}),e.jsx("span",{className:t.cn("rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:m==="y2"?"Y2":"Y1"})]})]})}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"flex items-end gap-4",children:[e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Chart Type"}),e.jsx("div",{className:"flex gap-2",children:ml.map(({type:D,icon:V,label:E})=>{const w=l===D;return e.jsxs("button",{onClick:()=>h(D),className:t.cn("flex items-center gap-2 rounded-md border px-3 py-1.5 text-xs transition-colors",w?"border-primary bg-primary/10 text-primary":"border-border bg-background text-muted-foreground hover:bg-muted"),children:[e.jsx(V,{className:"h-4 w-4"}),e.jsx("span",{children:E})]},D)})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Axis"}),e.jsxs(t.Select,{value:m,onValueChange:D=>g(D),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)"})]})]})]})]}),l==="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:D=>u({lineStyle:D}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:pl.map(({value:D,label:V})=>e.jsx(t.SelectItem,{value:D,className:"text-xs",children:V},D))})]})]}),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:D=>u({pointRadius:Number(D)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:xl.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 text-muted-foreground",children:"Point Shape"}),e.jsxs(t.Select,{value:(o==null?void 0:o.pointStyle)||"circle",onValueChange:D=>u({pointStyle:D}),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:D,label:V})=>e.jsx(t.SelectItem,{value:D,className:"text-xs",children:V},D))})]})]})]})]}),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.SmallSwitch,{checked:p,onCheckedChange:y})]}),p&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(qt,{config:o==null?void 0:o.dataLabels,onChange:j,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const ss=[{value:"origin",label:"Origin (X-axis)",description:"Fill to the X-axis (y=0)"},{value:"start",label:"Start (Top)",description:"Fill to the top of chart area"},{value:"end",label:"End (Bottom)",description:"Fill to the bottom of chart area"},{value:"-1",label:"Previous Series",description:"Fill to the series below"},{value:"+1",label:"Next Series",description:"Fill to the series above"},{value:"false",label:"No Fill (Line)",description:"Show as line without fill"}],bl=[0,1,2,3,4,5,6,8,10],vl=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],yl=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Nl(s){return s==null?"origin":s===!1?"false":s}function Cl(){const s=t.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type});return s!=="area"&&s!=="stackedArea"?null:e.jsxs(t.AccordionItem,{value:"area-series",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsx(Sl,{})})]})}function Sl(){const{transformedMetricKeys:s}=zt();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((n,a)=>e.jsx(wl,{metricKey:n,idx:a},n))})}function wl({metricKey:s,idx:n}){var y;const[a,r]=N.useState(!1),i=t.useEditorStore(j=>{var I;return(I=j.card)==null?void 0:I.preferences}),c=t.useEditorStore(j=>{var I,D;return(D=(I=j.card)==null?void 0:I.preferences)==null?void 0:D.datasetOptions}),o=c==null?void 0:c.find(j=>j.idx===n),{setCardPreferences:d}=t.useEditorStore(j=>j.actions),l=Nl(o==null?void 0:o.fill),m=((y=o==null?void 0:o.dataLabels)==null?void 0:y.enabled)??!1,p=ss.find(j=>j.value===l)||ss[0];function x(j){const I={idx:n,fill:l,dataLabels:o==null?void 0:o.dataLabels,...j};if(!o)d({...i||{},datasetOptions:[...c||[],I]});else{const D=c==null?void 0:c.map(V=>V.idx===n?{...V,...I}:V);d({...i||{},datasetOptions:D})}}function u(j){x({fill:j==="false"?!1:j})}function h(j){x({dataLabels:{...o==null?void 0:o.dataLabels,enabled:j}})}function g(j){x({dataLabels:j})}return e.jsx(t.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(t.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(t.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:s,children:s})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:e.jsxs("span",{className:t.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(t.ChartArea,{className:"h-3 w-3"}),p.label.split(" ")[0]]})})]})}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Fill Target"}),e.jsxs(t.Select,{value:l,onValueChange:j=>u(j),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ss.map(j=>e.jsx(t.SelectItem,{value:j.value,className:"text-xs",children:e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{children:j.label})})},j.value))})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(t.Select,{value:(o==null?void 0:o.lineStyle)||"solid",onValueChange:j=>x({lineStyle:j}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:yl.map(({value:j,label:I})=>e.jsx(t.SelectItem,{value:j,className:"text-xs",children:I},j))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(t.Select,{value:String((o==null?void 0:o.pointRadius)??3),onValueChange:j=>x({pointRadius:Number(j)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:bl.map(j=>e.jsx(t.SelectItem,{value:String(j),className:"text-xs",children:j===0?"None":j},j))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(t.Select,{value:(o==null?void 0:o.pointStyle)||"circle",onValueChange:j=>x({pointStyle:j}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:vl.map(({value:j,label:I})=>e.jsx(t.SelectItem,{value:j,className:"text-xs",children:I},j))})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(t.SmallSwitch,{checked:m,onCheckedChange:h})]}),m&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(qt,{config:o==null?void 0:o.dataLabels,onChange:g,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Tl=[0,1,2,3,4,5,6,8,10],El=[{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 │"}],as=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Il(){return t.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type})!=="line"?null:e.jsxs(t.AccordionItem,{value:"line-series",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsx(kl,{})})]})}function kl(){const{transformedMetricKeys:s}=zt();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((n,a)=>e.jsx(Dl,{metricKey:n,idx:a},n))})}function Dl({metricKey:s,idx:n}){var j;const[a,r]=N.useState(!1),i=t.useEditorStore(I=>{var D;return(D=I.card)==null?void 0:D.preferences}),c=t.useEditorStore(I=>{var D,V;return(V=(D=I.card)==null?void 0:D.preferences)==null?void 0:V.datasetOptions}),o=c==null?void 0:c.find(I=>I.idx===n),{setCardPreferences:d}=t.useEditorStore(I=>I.actions),l=(o==null?void 0:o.lineStyle)||"solid",m=(o==null?void 0:o.pointRadius)??3,p=(o==null?void 0:o.pointStyle)||"circle",x=((j=o==null?void 0:o.dataLabels)==null?void 0:j.enabled)??!1,u=as.find(I=>I.value===l)||as[0];function h(I){const D={idx:n,lineStyle:l,pointRadius:m,pointStyle:p,dataLabels:o==null?void 0:o.dataLabels,...I};if(!o)d({...i||{},datasetOptions:[...c||[],D]});else{const V=c==null?void 0:c.map(E=>E.idx===n?{...E,...D}:E);d({...i||{},datasetOptions:V})}}function g(I){h({dataLabels:{...o==null?void 0:o.dataLabels,enabled:I}})}function y(I){h({dataLabels:I})}return e.jsx(t.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(t.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(t.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:s,children:s})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:e.jsxs("span",{className:t.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(t.TrendingUp,{className:"h-3 w-3"}),u.label.split(" ")[0]]})})]})}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(t.Select,{value:l,onValueChange:I=>h({lineStyle:I}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:as.map(({value:I,label:D})=>e.jsx(t.SelectItem,{value:I,className:"text-xs",children:D},I))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(t.Select,{value:String(m),onValueChange:I=>h({pointRadius:Number(I)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Tl.map(I=>e.jsx(t.SelectItem,{value:String(I),className:"text-xs",children:I===0?"None":I},I))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(t.Select,{value:p,onValueChange:I=>h({pointStyle:I}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:El.map(({value:I,label:D})=>e.jsx(t.SelectItem,{value:I,className:"text-xs",children:D},I))})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(t.SmallSwitch,{checked:x,onCheckedChange:g})]}),x&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(qt,{config:o==null?void 0:o.dataLabels,onChange:y,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Al=[0,2,4,6,8,10,12,16,20];function Ml(){const s=t.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type});return!s||!["bar","horizontalBar","stackedBar"].includes(s)?null:e.jsxs(t.AccordionItem,{value:"bar-series",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsx(Ll,{})})]})}function Ll(){const{transformedMetricKeys:s}=zt();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((n,a)=>e.jsx(Ol,{metricKey:n,idx:a},n))})}function Ol({metricKey:s,idx:n}){var g;const[a,r]=N.useState(!1),i=t.useEditorStore(y=>{var j;return(j=y.card)==null?void 0:j.type}),c=t.useEditorStore(y=>{var j;return(j=y.card)==null?void 0:j.preferences}),o=t.useEditorStore(y=>{var j,I;return(I=(j=y.card)==null?void 0:j.preferences)==null?void 0:I.datasetOptions}),d=o==null?void 0:o.find(y=>y.idx===n),{setCardPreferences:l}=t.useEditorStore(y=>y.actions),m=(d==null?void 0:d.borderRadius)??0,p=((g=d==null?void 0:d.dataLabels)==null?void 0:g.enabled)??!1;function x(y){const j={idx:n,borderRadius:m,dataLabels:d==null?void 0:d.dataLabels,...y};if(!d)l({...c||{},datasetOptions:[...o||[],j]});else{const I=o==null?void 0:o.map(D=>D.idx===n?{...D,...j}:D);l({...c||{},datasetOptions:I})}}function u(y){x({dataLabels:{...d==null?void 0:d.dataLabels,enabled:y}})}function h(y){x({dataLabels:y})}return e.jsx(t.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(t.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(t.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:s,children:s})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:m>0&&e.jsxs("span",{className:t.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(t.ChartColumn,{className:"h-3 w-3"}),"r:",m]})})]})}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Bar Style"}),e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Corner Radius"}),e.jsxs(t.Select,{value:String(m),onValueChange:y=>x({borderRadius:Number(y)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Al.map(y=>e.jsx(t.SelectItem,{value:String(y),className:"text-xs",children:y===0?"None":`${y}px`},y))})]})]})})]}),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.SmallSwitch,{checked:p,onCheckedChange:u})]}),p&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(qt,{config:d==null?void 0:d.dataLabels,onChange:h,isHorizontal:i==="horizontalBar",showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Fl=[0,1,2,3,4,5,6,8,10],Rl=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],Bl=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Pl(){const s=t.useEditorStore(d=>d.card),n=t.useEditorStore(d=>{var l;return(l=d.card)==null?void 0:l.preferences}),a=De.useEffectiveEditorCardType(),r=n==null?void 0:n.lineStyleConfig,{setCardPreferences:i,updateCardInFrame:c}=t.useEditorActions();if(!s||!["line","area","stackedArea"].includes(a))return null;const o=(d,l)=>{const m={...n||{},lineStyleConfig:{...r,[d]:l}};i(m),c({...s,preferences:m})};return e.jsxs(t.AccordionItem,{value:"line-style",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(En,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Line Style"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Default styles for all series. Override per-series in the Series section."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Line Pattern"}),e.jsxs(t.Select,{value:(r==null?void 0:r.lineStyle)||"solid",onValueChange:d=>o("lineStyle",d),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Bl.map(({value:d,label:l})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:l},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Point Size"}),e.jsxs(t.Select,{value:String((r==null?void 0:r.pointRadius)??3),onValueChange:d=>o("pointRadius",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Fl.map(d=>e.jsx(t.SelectItem,{value:String(d),className:"text-xs",children:d===0?"None":d},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Point Shape"}),e.jsxs(t.Select,{value:(r==null?void 0:r.pointStyle)||"circle",onValueChange:d=>o("pointStyle",d),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Rl.map(({value:d,label:l})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:l},d))})]})]})]})})]})}const Vl=[0,2,4,6,8,10,12,16,20],_l=[{value:"0.5",label:"50%"},{value:"0.6",label:"60%"},{value:"0.7",label:"70%"},{value:"0.8",label:"80%"},{value:"0.9",label:"90%"},{value:"1",label:"100%"}],zl=[{value:"0.5",label:"50%"},{value:"0.6",label:"60%"},{value:"0.7",label:"70%"},{value:"0.8",label:"80%"},{value:"0.9",label:"90%"},{value:"1",label:"100%"}];function ql(){const s=t.useEditorStore(d=>d.card),n=t.useEditorStore(d=>{var l;return(l=d.card)==null?void 0:l.preferences}),a=De.useEffectiveEditorCardType(),r=n==null?void 0:n.barStyleConfig,{setCardPreferences:i,updateCardInFrame:c}=t.useEditorActions();if(!s||!["bar","horizontalBar","stackedBar"].includes(a))return null;const o=(d,l)=>{const m={...n||{},barStyleConfig:{...r,[d]:l}};i(m),c({...s,preferences:m})};return e.jsxs(t.AccordionItem,{value:"bar-style",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.ChartColumn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bar Style"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Default styles for all bars. Override per-series in the Series section."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Corner Radius"}),e.jsxs(t.Select,{value:String((r==null?void 0:r.borderRadius)??0),onValueChange:d=>o("borderRadius",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Vl.map(d=>e.jsx(t.SelectItem,{value:String(d),className:"text-xs",children:d===0?"None":`${d}px`},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Bar Width"}),e.jsxs(t.Select,{value:String((r==null?void 0:r.barPercentage)??.9),onValueChange:d=>o("barPercentage",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:_l.map(({value:d,label:l})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:l},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Category Width"}),e.jsxs(t.Select,{value:String((r==null?void 0:r.categoryPercentage)??.8),onValueChange:d=>o("categoryPercentage",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:zl.map(({value:d,label:l})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:l},d))})]})]})]})})]})}function $l(){const s=t.useEditorStore(a=>{var r,i;return(i=(r=a==null?void 0:a.card)==null?void 0:r.preferences)==null?void 0:i.sortChart}),{setSortChart:n}=t.useEditorActions();return e.jsxs(t.AccordionItem,{value:"stacked-sort",children:[e.jsx(t.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.ArrowUpDown,{className:"h-4 w-4"}),"Sort"]})}),e.jsx(t.AccordionContent,{className:"space-y-4 px-1",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Sort Order"}),e.jsx(Xe,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"Ascending",value:"asc"},{label:"Descending",value:"desc"}],value:s||"none",onValueChange:a=>{n(a)}})]})})]})}const Kl=["kpi"],va={none:"None",previous_period:"Previous Period",same_period_last_year:"Same Period Last Year",start_vs_end:"Start vs End",target:"Target"},ns=2;function st(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 Gl(s){if(!(s!=null&&s.name)||!(s!=null&&s.dataType)||s.role==="metric")return!1;const n=t.getDataType(s.dataType);return["date","string","boolean"].includes(n)}function Ul(s){return{...s,role:"groupby"}}function Hl(){var D,V;const s=t.useEditorStore(E=>E.card),n=t.useEditorStore(E=>E.actions.updateCardConfig),a=De.useEffectiveEditorCardType(),{scopedFields:r}=t.useScopedFields(),i=((D=s.config)==null?void 0:D.metricColumns)||[],c=((V=s.config)==null?void 0:V.summary)||{},o=c.breakdownDimensions||[],d=Kl.includes(a),l=i.length>0,m=c.enabled===!0,p=d&&l,{comparisonType:x}=t.getEffectiveComparisonSettings(s.config,a),u=va[x]||va.none,h=Array.from(new Map(r.filter(Gl).map(E=>[st(E),Ul(E)])).values()),g=new Set(h.map(E=>st(E))),y=new Set(o.map(E=>st(E)).filter(E=>E&&g.has(E)));if(!d)return null;const j=E=>{n(s.id,{summary:{...c,...E}})},I=(E,w)=>{const T=st(E),A=h.filter(v=>y.has(st(v))),S=w?y.has(T)?A:[...A,E].slice(0,ns):A.filter(v=>st(v)!==T);j({breakdownDimensions:S})};return e.jsxs(t.AccordionItem,{value:"summary",className:"border-none",children:[e.jsx(t.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.FileText,{className:"h-4 w-4"}),e.jsx("span",{children:"Summary"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{htmlFor:"summary-enabled",className:"text-xs",children:"Enable Summary"}),!l&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Add at least one metric to enable summary."})]}),e.jsx(t.SmallSwitch,{id:"summary-enabled",checked:m,disabled:!p,onCheckedChange:E=>{if(!E){j({enabled:!1,showOnCard:!1,includeInDashboardSummary:!1});return}j({enabled:!0,showOnCard:c.showOnCard??!0,includeInDashboardSummary:c.includeInDashboardSummary??!0,anomalyEnabled:c.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: ",u]}),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.SmallSwitch,{id:"summary-show-on-card",checked:c.showOnCard===!0,disabled:!m,onCheckedChange:E=>j({showOnCard:E})})]}),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.SmallSwitch,{id:"summary-include-rollup",checked:c.includeInDashboardSummary===!0,disabled:!m,onCheckedChange:E=>j({includeInDashboardSummary:E})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Breakdown Dimensions"}),e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[o.length,"/",ns]})]}),h.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:h.map(E=>{const w=st(E),T=y.has(w),A=y.size>=ns,S=!m||!T&&A;return e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx(t.Checkbox,{id:`summary-breakdown-${w}`,checked:T,disabled:S,onCheckedChange:v=>I(E,v===!0)}),e.jsx(t.Label,{htmlFor:`summary-breakdown-${w}`,className:"cursor-pointer text-xs",children:E.label||E.name})]},w)})})]}),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.SmallSwitch,{id:"summary-anomaly",checked:c.anomalyEnabled!==!1,disabled:!m,onCheckedChange:E=>j({anomalyEnabled:E})})]})]})]})}const Ql=[];function Jl(){var i;const s=t.useEditorStore(c=>c.card),n=((i=s==null?void 0:s.config)==null?void 0:i.metricColumns)??Ql,{updateMetricColumn:a,updateCardInFrame:r}=t.useEditorActions();return!s||s.type==="kpi"||n.length===0?null:e.jsxs(t.AccordionItem,{value:"metric-formats",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-4 w-4"}),e.jsx("span",{children:"Metric Formats"})]})}),e.jsx(t.AccordionContent,{className:"space-y-4 pt-2",children:n.map(c=>e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 p-3",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:c.label||c.name}),e.jsx(xs,{value:c.format,onChange:o=>{var d;a(s.id,c.id,{format:o}),r({...s,config:{...s.config,metricColumns:(((d=s.config)==null?void 0:d.metricColumns)||[]).map(l=>l.id===c.id?{...l,format:o}:l)}})}})]},c.id))})]})}const Yl=new Set(["area","bar","bubble","bullet","combo","doughnut","funnel","horizontalBar","line","pie","polarArea","radar","scatter","stackedArea","stackedBar","stackedLine","tornado"]);function Wl(){const s=t.useEditorStore(l=>l.card),n=t.useEditorStore(l=>{var m;return(m=l.card)==null?void 0:m.preferences}),a=De.useEffectiveEditorCardType(),{setCardPreferences:r,updateCardInFrame:i}=t.useEditorActions();if(!s||!Yl.has(a||""))return null;const c=n==null?void 0:n.tooltipConfig,o=(c==null?void 0:c.formatMode)||(c==null?void 0:c.mode)||"inherit",d=l=>{const m={...n||{},tooltipConfig:{...c||{},...l}};r(m),i({...s,preferences:m})};return e.jsxs(t.AccordionItem,{value:"tooltip-format",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Info,{className:"h-4 w-4"}),e.jsx("span",{children:"Tooltip Format"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Override metric format"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Keep this off to inherit from each metric."})]}),e.jsx(t.SmallSwitch,{checked:o==="override",onCheckedChange:l=>d({formatMode:l?"override":"inherit",mode:l?"override":"inherit"})})]}),o==="override"&&e.jsx(gt,{formatOptions:(c==null?void 0:c.formatOptions)||{},onFormatOptionsChange:l=>d({formatMode:"override",mode:"override",formatOptions:l}),showTitle:!1})]})]})}function _a({mode:s}){const n=t.useEditorStore(a=>{var r;return(r=a.card)==null?void 0:r.type});return e.jsxs(e.Fragment,{children:[n==="combo"&&e.jsx(fl,{}),(n==="area"||n==="stackedArea")&&e.jsx(Cl,{}),n==="line"&&e.jsx(Il,{}),(n==="bar"||n==="horizontalBar"||n==="stackedBar")&&e.jsx(Ml,{}),e.jsx(Pl,{}),e.jsx(ql,{}),e.jsx(tl,{}),s==="config"&&e.jsx(el,{}),s==="config"&&e.jsx(Hl,{}),e.jsx(al,{}),n==="bullet"&&e.jsx(nl,{}),n==="funnel"&&e.jsx(ol,{}),(n==="bubble"||n==="scatter")&&e.jsx(rl,{}),(n==="stackedBar"||n==="stackedLine")&&e.jsx($l,{}),e.jsx(Jl,{}),e.jsx(Yr,{}),e.jsx(Wr,{}),e.jsx(Xr,{}),e.jsx(Zr,{}),e.jsx(Wl,{})]})}function Xl(){const s=t.useEditorStore(a=>a.card),n=s==null?void 0:s.type;return n?e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(_t,{chartType:n}),e.jsx(t.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:e.jsx(_a,{mode:"dev"})})]}):null}function Zl(){const s=t.useEditorStore(a=>a.card.type);function n(){switch(s){case"kpi":return e.jsx(Dr,{});case"table":return e.jsx(Ur,{});case"map":return e.jsx(Or,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(Ra,{})});case"text":return e.jsx(Qr,{});default:return e.jsx(Xl,{})}}return e.jsxs(t.ScrollArea,{className:"h-full w-full text-sm",children:[n(),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}function eo(){const s=N.useRef(null),n=N.useRef(null),a=t.useEditorStore(x=>x.isShowingVisual),r=t.useEditorStore(x=>x.isDevMode),i=t.useEditorStore(x=>x.showAIDialog),[c,o]=N.useState(!1),d=a&&!i,l=d&&(!r||c),m=r&&d,p=()=>o(x=>!x);return N.useEffect(()=>{var x,u,h,g;i?((x=s.current)==null||x.resize(0),(u=n.current)==null||u.resize(0)):((h=s.current)==null||h.resize(25),(g=n.current)==null||g.resize(25))},[i]),e.jsxs(t.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:[e.jsx(t.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(Wn,{})}),e.jsx(t.ResizableHandle,{withHandle:!0,className:"data-[panel-group-direction=vertical]:ml-2 data-[panel-group-direction=vertical]:mr-6 data-[panel-group-direction=vertical]:w-auto"}),e.jsx(t.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:l?e.jsxs(t.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(t.ResizablePanel,{ref:s,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(Zl,{})})}),!i&&e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(da,{visualAsideControl:m?{show:!0,isOpen:c,onToggle:p}:void 0})})]}):e.jsx(da,{visualAsideControl:m?{show:!0,isOpen:c,onToggle:p}:void 0})})]})}function to(s){var we;t.useAIInteractionStore(U=>U.currentAIContext);const[n,a]=N.useState(""),[r,i]=N.useState(null),{authToken:c,tokenProps:o}=t.useSemaphorContext(),d=t.useEditorStore(U=>{var ne;return(ne=U==null?void 0:U.card)==null?void 0:ne.sql}),l=t.useEditorStore(U=>U.isDevMode),m=t.useEditorStore(U=>{var ne;return(ne=U==null?void 0:U.card)==null?void 0:ne.python}),{setCardPython:p,setCardSql:x,setRunSql:u,switchCardType:h,setQueryConfig:g}=t.useEditorActions(),y=t.useEditorStore(U=>U.currentAssitantScope)||[],j=t.useEditorStore(U=>U.userInputForAI),I=t.useEditorStore(U=>U.triggerAIRun),D=t.useEditorStore(U=>U.card),V=t.useEditorStore(U=>U.selectedDatabaseName),E=t.useEditorStore(U=>U.selectedTableName),w=t.useEditorStore(U=>U.selectedConnectionId),T=t.useEditorStore(U=>U.selectedSchemaName),A=t.useDashboardStore(U=>U.dashboard.aiScopeTables),{errorMessage:S,refetch:v,data:k}=t.useDashboardCardQuery(D),{setTriggerAIRun:M,setCurrentAssitantScope:f,setCardConfig:O}=t.useEditorActions(),{selectedDatamodelName:F,connectionType:b,selectedDatamodelId:L}=t.useEditorAside(),C=(we=t.useDashboardQuery().data)==null?void 0:we.assistantProfileId,{messages:P,setMessages:R,regenerate:B,error:z,sendMessage:_,status:K,addToolResult:H,stop:G,clearError:X}=t.useChat({transport:new t.DefaultChatTransport({api:`${o.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${c==null?void 0:c.accessToken}`}),body:()=>{const U=t.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:C,isDevMode:l,aiContext:U.currentAIContext,reasoningEffort:U.reasoningEffort,showReasoning:U.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:U,body:ne})=>({body:{...ne,messages:t.cleanupIncompleteMessages(U)}})}),onError:U=>{var ne;if(U.name==="AbortError"||(ne=U.message)!=null&&ne.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)");return}console.error("[Editor Assistant] Stream error:",U)},onToolCall:ae,onFinish({isAbort:U,isDisconnect:ne,isError:ye}){a(""),console.log(U?"[Editor Assistant] Stream aborted by user":ne?"[Editor Assistant] Stream disconnected (network error)":ye?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully")}});N.useEffect(()=>{I&&j&&(_({role:"user",parts:[{type:"text",text:j}]}),M(!1))},[I,j,_,M]);async function ae({toolCall:U}){var ne,ye,se,be,ge,fe,Ne,ve,Te,Le,te,je,me,Ee,he,Re;if(["createChartFromSql","createForecast"].includes(U.toolName)){const Ye=((ne=U.input)==null?void 0:ne.sql)??((ye=U.args)==null?void 0:ye.sql),qe=((se=U.input)==null?void 0:se.python)??((be=U.args)==null?void 0:be.python),Se=((ge=U.input)==null?void 0:ge.chartType)??((fe=U.args)==null?void 0:fe.chartType);h(Se),x(Ye),p(qe),u(!0),H({tool:U.toolName,toolCallId:U.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(U.toolName==="getUserSql"){if(!d){H({tool:U.toolName,toolCallId:U.toolCallId,output:{status:"error",message:"No SQL found"}});return}H({tool:U.toolName,toolCallId:U.toolCallId,output:{status:"success",sql:d,python:m||""}})}else if(U.toolName==="generateQueryConfig"){a("Generating query config...");const Ye=((Ne=U.input)==null?void 0:Ne.chartType)??((ve=U.args)==null?void 0:ve.chartType),qe=((Te=U.input)==null?void 0:Te.queryConfig)??((Le=U.args)==null?void 0:Le.queryConfig);((te=U.input)==null?void 0:te.cardConfig)??((je=U.args)==null||je.cardConfig),h(Ye),O(qe),x(void 0),p(void 0);const Se=await v();if((me=Se==null?void 0:Se.data)!=null&&me.error){H({tool:U.toolName,toolCallId:U.toolCallId,output:{status:"error",queryConfig:qe,message:(Ee=Se==null?void 0:Se.data)==null?void 0:Ee.error.message}});return}if((he=Se==null?void 0:Se.data)!=null&&he.records){H({tool:U.toolName,toolCallId:U.toolCallId,output:{status:"success",queryConfig:qe,message:"The data has been visualized"}});return}H({tool:U.toolName,toolCallId:U.toolCallId,output:{status:"success",queryConfig:qe,message:"The data has been visualized",records:(Re=Se==null?void 0:Se.data)==null?void 0:Re.records}})}else a("Analyzing...")}function ee(U){const ne=t.removeFromScopeArray(y,U);de(ne)}function de(U){const ne=t.sanitizeAIScope(U);f(ne),R(ye=>[...ye,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(ne)}`}]}])}function ce(){const U={databaseName:V||"",schemaName:T||"",tableName:E||"",datamodelId:L||"",datamodelName:t.resolveDatamodelName(F),connectionId:w||"",connectionType:b||""},ne=t.dedup([...y,U]);de(ne)}function W(){const U={databaseName:V||"",schemaName:T||"",tableName:E||"",datamodelName:t.resolveDatamodelName(F),connectionId:w||"",connectionType:b||"",datamodelId:L||""};if(!t.isInAiScopeArray([...A||[],...y],U)||y.length===0){const ye=t.dedup([...A||[],...y,U]).filter(se=>se.connectionId===U.connectionId);de(ye)}}const pe=!["ready","error"].includes(K),Z=t.getErrorMessage(z);return{messages:P,setMessages:R,sendMessage:_,regenerate:B,isLoading:pe,handleSetAIScope:W,handleAddCurrentTableToScope:ce,removeFromCurrentSelections:ee,currentAssitantScope:y,setCurrentAssitantScope:f,stop:G,status:K,toolStatus:n,llmUsage:r,onFinish:s,errorMessage:Z,clearError:X}}const so=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function ya({isFullscreen:s,onFullscreenChange:n,fullscreenContainer:a}){const r=N.useRef(null),i=N.useRef(!1),[c,o]=N.useState(!1),[d,l]=N.useState(t.isDevEnv),[m,p]=N.useState(!1),[x,u]=N.useState(!1),[h,g]=N.useState(!1),y=s??h,j=t.useCurrentAIContext(),{setCurrentAIContext:I,setHasEditorEntitySelectionOverride:D}=t.useAIActions(),{clearQueue:V}=t.useQueueActions(),{clearFileAttachments:E}=t.useFileActions(),w=t.useFileAttachments("editor"),{selectedEntities:T}=t.useAssistantContextEntities("editor"),A=t.useEditorStore(le=>le.card.id),S=t.useEditorStore(le=>le.card.dataSource),v=t.useEditorStore(le=>{var Ie;return(Ie=le.card.dataSource)==null?void 0:Ie.selectedEntities}),k=t.useEditorStore(le=>le.actions.setCardSql),M=t.useEditorStore(le=>le.actions.setRunSql),f=t.useEditorStore(le=>le.showAIDialog),O=t.useDashboardStore(le=>le.handleOpenAssistantProfile),{setShowAIDialog:F,setCardPython:b}=t.useEditorActions(),{setDataSource:L}=t.useEditorActions(),{assistantProfile:C}=t.useAssistantProfile(),{messages:P,setMessages:R,sendMessage:B,isLoading:z,stop:_,status:K,llmUsage:H,errorMessage:G,clearError:X}=to(),[ae,ee]=N.useState(""),de=le=>{ee(le.target.value)},ce=le=>{le.preventDefault();const Ie=ae.trim();if(!Ie&&w.length===0)return;const Ge=[];Ie&&Ge.push({type:"text",text:Ie}),w.forEach(Oe=>{Oe.data&&Ge.push({type:"file",mediaType:Oe.type,filename:Oe.name,url:`data:${Oe.type};base64,${Oe.data}`})}),B({role:"user",parts:Ge}),ee(""),E("editor"),fe({force:!0})},{visibleMessages:W,hasMoreMessages:pe,totalMessageCount:Z,loadMoreMessages:we,resetMessageWindow:U}=t.useMessageWindow(P,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:ne,contentRef:ye,isAtBottom:se,hasNewMessages:be,newMessageCount:ge,scrollToBottom:fe,handleScroll:Ne,resetNewMessageCount:ve}=t.useAutoScroll(W,{threshold:40,behavior:"smooth",isStreaming:z});N.useEffect(()=>{var le;f&&!i.current&&((le=r.current)==null||le.focus()),i.current=f},[f]),N.useEffect(()=>{f&&(D(!1),I({selectedEntities:v||[]}))},[A,v,I,D,f]),t.useAutoSubmitQueue({assistantType:"editor",status:K,isLoading:z,sendMessage:B});const{hasActiveTools:Te}=t.useActiveToolStatus(P),Le=N.useCallback(le=>{n==null||n(le),s===void 0&&g(le)},[s,n]);N.useEffect(()=>{if(!y)return;function le(Ie){Ie.key==="Escape"&&Le(!1)}return window.addEventListener("keydown",le),()=>{window.removeEventListener("keydown",le)}},[y,Le]);const te=N.useCallback(le=>{B({role:"user",parts:[{type:"text",text:le}]}),fe({force:!0})},[B,fe]),je=N.useCallback(async()=>{const le=JSON.stringify(P??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(le),t.ue.success("Conversation copied")}catch(Ie){console.error("Failed to copy conversation",Ie),t.ue.error("Unable to copy conversation")}},[P]),me=N.useCallback(()=>{Le(!y)},[y,Le]);function Ee(le,Ie){Ie==="sql"?(k(le),M(!0)):Ie==="python"&&(b(le),M(!0))}function he(){j.selectedEntities.length===0&&I({selectedEntities:T})}function Re(le){he();const Ie={role:"user",parts:[{type:"text",text:le.title+" "+le.subtitle}]};B(Ie)}function Ye(le){he(),B({role:"user",parts:[{type:"text",text:le}]})}function qe(){return e.jsxs(t.DropdownMenu,{children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.Button,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(t.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",children:[e.jsx(t.DropdownMenuLabel,{children:"Options"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsx(t.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:o,children:"Token Usage"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:d,onCheckedChange:l,children:"Tool Invocations"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:m,onCheckedChange:p,children:"System Message"})]})]})}function Se(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const at=(ae==null?void 0:ae.length)===0&&(P==null?void 0:P.filter(le=>le.role==="user").length)===0,nt=e.jsxs("div",{"data-role":"editor-assistant",className:t.cn("flex h-full w-full flex-col justify-between px-6 py-4",y&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Se(),O&&e.jsx(t.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:O,children:(C==null?void 0:C.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[qe(),d&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:je,children:"Copy Conversation"}),e.jsx(t.IconButton,{tooltip:y?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:me,children:y?e.jsx(t.Minimize2,{className:"size-4"}):e.jsx(t.Maximize2,{className:"size-4"})}),e.jsx(t.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{R([]),V("editor"),X(),U()},children:e.jsx(t.SquarePen,{className:"size-4"})}),e.jsx(t.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{F(!1)},children:e.jsx(t.X,{className:"size-4"})})]})]}),e.jsx(t.CustomScrollArea,{ref:ne,className:"mt-2 flex min-w-0 w-full grow basis-0",onScroll:Ne,children:e.jsxs("div",{ref:ye,className:"min-w-0 space-y-4 py-2 pr-3","data-role":"messages",children:[pe&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:we,className:"text-xs",children:["Load ",Math.min(5,Z-W.length)," ","more messages (",Z-W.length," ","hidden)"]})}),e.jsx(t.PrintMessages,{messages:W,showTools:d,handleRun:Ee,showSystemMessage:m,onQuickReply:te,disableQuickReplies:z}),!Te&&e.jsx(t.AssistantStatus,{status:K,errorMessage:G})]})}),f&&!se&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(t.Button,{onClick:()=>{fe({force:!0}),ve()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(t.ChevronDown,{className:"h-4 w-4"}),be&&ge>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:ge>9?"9+":ge})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[at&&!C&&e.jsx(t.Placeholders,{onClick:Re,placeholders:so}),e.jsx("div",{children:at&&C&&e.jsx(t.SeedQuestions,{seedQuestions:C.seedQuestions||[],handleSeedQuestionClick:Ye})})]}),e.jsx(t.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(t.ChatInputWithContext,{ref:r,setInput:ee,stop:_,input:ae,handleInputChange:de,handleSubmit:le=>{he(),ce(le),fe({force:!0})},isLoading:z,status:K,assistantType:"editor",onFocus:()=>{}})]}),H&&c&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",H.inputTokens," prompt tokens, ",H.outputTokens," ","completion tokens, ",H.totalTokens," total tokens"]})}),e.jsx(t.DataSourceDialog,{incomingSelectedEntities:T,open:x,onOpenChange:u,dataSource:S||t.EMPTY_DATA_SOURCE,dialogMode:"aiContext",onSaveSelectedEntities:le=>{D(!0),I({...j,selectedEntities:le})}})]});return y&&a?on.createPortal(e.jsx("div",{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:e.jsx("div",{className:"flex h-full w-full",children:nt})}),a):nt}function ao(s,n,a){if(!n)return!1;const r=n.qualifiedFieldName,i=n.qualifiedEntityName,c=i&&n.name?`${i}.${n.name}`:r;return s.some(o=>{if(!(t.getDataType(o.dataType||"")==="date"))return!1;const l=t.getSelectedDateFilterColumn(o,a),m=l.split("."),p=m[m.length-1]||l,x=m.length>1?m.slice(0,-1).join("."):void 0,u=o.qualifiedTableName||x,h=u?`${u}.${p}`:void 0;return r?h?h===c||h.endsWith(`.${r}`):p===n.name:h?h===c:p===n.name})}function no({aliasTemplate:s,onAliasTemplateChange:n}){var l;const[a,r]=N.useState(s),[i,c]=N.useState(!1),o=(l=t.useEditorStore(m=>{var p;return(p=m.card.config)==null?void 0:p.pivotByColumns}))==null?void 0:l[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$1,{placeholder:d,value:i?a:s,onChange:m=>{r(m.target.value),c(!0)},onFocus:()=>c(!0),onPointerDown:m=>m.stopPropagation(),className:"h-8 text-xs",onKeyDown:m=>{m.key==="Enter"&&i&&a!==s?(n(a),c(!1)):m.key==="Escape"&&(r(s),c(!1))},"aria-label":"Edit alias template"}),i&&a!==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:()=>{n(a),c(!1)},children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(s),c(!1)},children:e.jsx(t.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function ro({valueAliases:s,onValueAliasesChange:n}){const[a,r]=N.useState(null),[i,c]=N.useState(""),[o,d]=N.useState(""),l=()=>{n({...s,"":""})},m=x=>{const u={...s};delete u[x],n(u)},p=x=>{const u={...s};delete u[x],u[i]=o,n(u),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(s).map(([x,u],h)=>e.jsx("div",{className:"flex items-center gap-2",children:a===x?e.jsxs(e.Fragment,{children:[e.jsx(t.Input$1,{placeholder:"Value key",value:i,onChange:g=>c(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?p(x):g.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(t.Input$1,{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"?p(x):g.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>p(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 value alias edit",onClick:()=>r(null),children:e.jsx(t.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(t.Input$1,{placeholder:"Value key",value:x,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(x),c(x),d(u)},"aria-label":"Edit value alias key"}),e.jsx(t.Input$1,{placeholder:"Alias label",value:u,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(x),c(x),d(u)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>m(x),"aria-label":"Remove value alias",children:e.jsx(t.X,{className:"h-3 w-3"})})]})},x+h)),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:l,children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function lo({idx:s}){var d;const n=t.useEditorStore(l=>{var m;return(m=l.card)==null?void 0:m.preferences}),a=t.useEditorStore(l=>{var m;return(m=l.card.preferences)==null?void 0:m.datasetOptions}),r=t.useEditorStore(l=>l.actions.setCardPreferences),i=(d=n==null?void 0:n.chartOptions)==null?void 0:d.indexAxis,c=a==null?void 0:a.find(l=>l.idx===s);function o(l,m){(l==="end"||l==="start")&&t.getContrastColor(t.getCanvasBackgroundColor());const p={display:l!=="none",align:l,anchor:l,clamp:!0};if(!c)r({...n,datasetOptions:[...a||[],{idx:m,datalabels:p}]});else{const x={...c};x.datalabels=p;const u=a==null?void 0:a.map(h=>h.idx===m?x:h);r({...n,datasetOptions:u})}}return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{children:e.jsx(t.Tag,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(t.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>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(jn,{className:t.cn("h-4 w-4",{"rotate-90":i==="y"})})}),e.jsx("button",{onClick:()=>o("center",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(vn,{className:t.cn("h-4 w-4",{"rotate-90":i==="y"})})}),e.jsx("button",{onClick:()=>o("end",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(bn,{className:t.cn("h-4 w-4",{"rotate-90":i==="y"})})})]})})]})}function hs({children:s,className:n,delayDuration:a}){return e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:a,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:t.cn("overflow-hidden text-ellipsis whitespace-nowrap",n),children:s})}),e.jsx(t.TooltipContent,{children:s})]})})}function oo(s,n=30){return s.length>n?s.slice(0,n)+"...":s}function io({col:s,idx:n,className:a,iconClassName:r,children:i}){const c=t.useEditorStore(p=>{var x;return(x=p.card)==null?void 0:x.preferences}),o=t.useEditorStore(p=>{var x,u;return(u=(x=p.card)==null?void 0:x.preferences)==null?void 0:u.datasetOptions}),d=o==null?void 0:o.find(p=>p.idx===n),{setCardPreferences:l}=t.useEditorStore(p=>p.actions);function m(p){if(!d)l({...c,datasetOptions:[...o||[],{idx:n,type:p==="area"?"line":p,fill:p==="area"?"origin":""}]});else{const x={...d};x.type=p==="area"?"line":p,x.fill=p==="area"?"origin":"";const u=o==null?void 0:o.map(h=>h.idx===n?x:h);l({...c,datasetOptions:u})}}return e.jsxs("div",{className:t.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[i||e.jsx(hs,{className:"max-w-[100px]",title:s,children:oo(s)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(t.ChartColumnIncreasing,{onClick:()=>m("bar"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(t.ChartLine,{onClick:()=>m("line"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(t.ChartArea,{onClick:()=>m("area"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(lo,{idx:n})]})]})}function co(){const s=t.useEditorStore(d=>d.card.type),n=t.useEditorStore(d=>d.isDevMode),a=t.useEditorStore(d=>d.card.preferences),{setCardPreferences:r}=t.useEditorStore(d=>d.actions);function i(d){var p;const l={datalabels:{display:d!=="none",align:d,anchor:d,clamp:!0}},m={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(p=a==null?void 0:a.chartOptions)==null?void 0:p.plugins,...l}}};r(m)}function c(){var d,l,m;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(t.Select,{value:((m=(l=(d=a==null?void 0:a.chartOptions)==null?void 0:d.plugins)==null?void 0:l.datalabels)==null?void 0:m.anchor)||"none",onValueChange:i,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,l,m;return e.jsx("div",{children:e.jsxs(t.Select,{value:((m=(l=(d=a==null?void 0:a.chartOptions)==null?void 0:d.plugins)==null?void 0:l.datalabels)==null?void 0:m.anchor)||"none",onValueChange:i,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:n?c():o()})}function uo({column:s}){const n=t.useEditorStore(l=>l.card.type),a=t.useEditorStore(l=>{var m,p;return(p=(m=l.card)==null?void 0:m.config)==null?void 0:p.metricColumns}),r=(a==null?void 0:a.map(l=>l.label))||[],i=r==null?void 0:r.find(l=>l===s.label||l===s.name),c=i?r.indexOf(i):-1;function o(){return e.jsx("div",{className:"pr-1",children:i&&e.jsx(io,{idx:c,col:i,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(co,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&o(),["pie","doughnut"].includes(n)&&d()]})}function mo({field:s,searchQuery:n="",limit:a=500}){const{authToken:r,tokenProps:i}=t.useSemaphorContext(),c=t.useEditorStore(m=>m.card),o=c==null?void 0:c.dataSource,d=["attribute-values",s.entityName,s.name,n,a],l=t.useQuery({queryKey:d,queryFn:async()=>{if(!(o!=null&&o.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const m={groupByColumns:[{...s,role:"groupby"}],metricColumns:[],filters:n?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:s,operator:"contains",value:n}],groups:[]}:void 0,rowLimit:a},p={connection_id:o.connectionId,cardConfig:m,cardDataSource:o,cache_config:t.getCacheConfig({card:c})};console.log("requestBody",p);const x=await t.postRequestRegular(`${i.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",p);if(x!=null&&x.error)return console.error("Error fetching attribute values:",x.error),[];const u=s.name;return((x==null?void 0:x.records)||[]).map(g=>{const y=g[u]||g[s.alias||u]||g[s.label];return{id:y||"",value:y||"",label:String(y||"(empty)")}})}catch(m){return console.error("Error fetching attribute values:",m),[]}},enabled:!!s&&!!(o!=null&&o.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:l.data||[],isLoading:l.isLoading,isFetching:l.isFetching,isError:l.isError,error:l.error,refetch:l.refetch}}function za({open:s,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:i,onSave:c}){var V,E;const o=!!i,[d,l]=N.useState(o?"values":"fields"),[m,p]=N.useState(""),[x,u]=N.useState({id:(i==null?void 0:i.id)||t.v4(),field:(i==null?void 0:i.field)||null,selectedValues:i?Array.isArray(i.value)?i.value:[i.value]:[]}),h=a.filter(w=>{var A;return o?!1:!((A=r==null?void 0:r.conditions)==null?void 0:A.some(S=>S.field.id===w.id))&&w.label.toLowerCase().includes(m.toLowerCase())}),g=w=>{u({...x,field:w}),l("values")},y=()=>{if(x.field&&x.selectedValues.length>0){const w={id:x.id,field:x.field,operator:"in",value:x.selectedValues};let T;if(o){const A=((r==null?void 0:r.conditions)||[]).map(S=>S.id===i.id?w:S);T={...r,conditions:A}}else{const A=(r==null?void 0:r.conditions)||[];T={id:(r==null?void 0:r.id)||t.v4(),logicalOperator:"AND",negate:!1,conditions:[...A,w],groups:[]}}c(T),n(!1)}},j=()=>{if(!o||!i)return;const w=((r==null?void 0:r.conditions)||[]).filter(T=>T.id!==i.id);if(w.length>0){const T={...r,conditions:w};c(T)}else c(void 0);n(!1)},I=w=>{u({...x,selectedValues:w})},D=()=>{o&&i?(u({id:i.id,field:i.field,selectedValues:Array.isArray(i.value)?i.value:[i.value]}),l("values")):(u({id:t.v4(),field:null,selectedValues:[]}),l("fields")),p("")};return N.useEffect(()=>{s&&D()},[s,o,i]),e.jsx(t.Dialog,{open:s,onOpenChange:n,children:e.jsxs(t.DialogContent,{className:"max-w-2xl",children:[e.jsx(t.DialogHeader,{children:e.jsx(t.DialogTitle,{children:o?`Edit Filter: ${(V=x.field)==null?void 0:V.label}`:d==="fields"?"Select Field to Filter":`Select Values for ${(E=x.field)==null?void 0:E.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!o&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&d==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Current Filters:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.conditions.map(w=>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:[w.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(w.value)?`${w.value.length} values`:String(w.value)})]},w.id))})]}),d==="fields"&&!o?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(t.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(t.Input$1,{placeholder:"Search fields...",value:m,onChange:w=>p(w.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:h.map(w=>e.jsxs(t.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>g(w),children:[e.jsx(t.IconForFieldType,{dataType:t.getDataType(w.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:w.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[w.entityName,".",w.name]})]})]},w.id))}),h.length===0&&m&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',m,'"']}),h.length===0&&!m&&a.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(xo,{field:x.field,selectedValues:x.selectedValues,onValuesChange:I,onBack:o?void 0:()=>l("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:j,children:"Delete Filter"}):e.jsx(t.Button,{variant:"outline",onClick:D,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(t.Button,{onClick:y,disabled:!x.field||x.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function xo({field:s,selectedValues:n,onValuesChange:a,onBack:r}){const[i,c]=N.useState(""),{values:o,isLoading:d,isFetching:l}=mo({field:s,searchQuery:i,limit:500}),m=i?o.filter(u=>String(u.value).toLowerCase().includes(i.toLowerCase())):o,p=u=>{const h=n.includes(u);a(h?n.filter(g=>g!==u):[...n,u])},x=()=>{n.length===m.length&&m.length>0?a([]):a(m.map(u=>u.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:r,children:"← Back"}),e.jsxs(t.Label,{className:"text-sm font-medium",children:["Select values for ",s.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(t.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(t.Input$1,{placeholder:"Search values...",value:i,onChange:u=>c(u.target.value),className:"pl-10"})]}),d||l?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(t.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx(t.Checkbox,{checked:n.length===m.length&&m.length>0,onCheckedChange:x}),e.jsxs(t.Label,{className:"text-sm",children:["Select All (",m.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:m.map(u=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>p(u.value),children:[e.jsx(t.Checkbox,{checked:n.includes(u.value),onCheckedChange:()=>p(u.value)}),e.jsx(hs,{className:"text-sm",children:u.label})]},u.id))})]})]})}function ho({field:s,zone:n,index:a,sortDirection:r,onSortDirectionChange:i,hasPivotColumns:c=!1,cardType:o}){var bs,vs,ys,Ns,Cs,Ss,ws,Ts,Es,Is,ks,Ds,As,Ms,Ls,Os,Fs,Rs,Bs,Ps,Vs,_s,zs,qs,$s,Ks,Gs,Us,Hs,Qs,Js,Ys,Ws,Xs;const{attributes:d,listeners:l,setNodeRef:m,transform:p,transition:x,isDragging:u}=t.useSortable({id:s.id}),h=t.useEditorStore(q=>q.card),g=t.useEditorStore(q=>q.frame),{scopedFields:y,isLoading:j}=t.useScopedFields(),{userContext:I}=t.useCurrentUserInfo(),D=(I==null?void 0:I.type)==="organization",V=(bs=h.dataSource)==null?void 0:bs.semanticDomainId,{promoteMetric:E}=t.usePromoteCalculatedMetricToDomain({domainId:V}),{updateLabel:w,handleAggregationChange:T,handleDateFormatChange:A,handleGranularityChange:S,handleAliasTemplateChange:v,handleValueAliasesChange:k,handleMetricFormatChange:M,removeField:f,handleMetricComparisonChange:O,handleMetricWindowTransformChange:F,handleMetricWindowOrderByChange:b,handleMetricWindowDirectionChange:L,handleMetricWindowPartitionToggle:C,handleMetricMovingAverageWindowSizeChange:P,handleMetricMovingAverageMinPeriodsChange:R,handleMetricPreviousPeriodDeltaModeChange:B,handleMetricPercentOfTotalScopeChange:z,handleMetricPercentOfTotalOutputChange:_,handleKpiShowTrendlineChange:K,handleKpiTrendlineWindowChange:H,handleKpiTrendlineGranularityChange:G,handleMetricTargetValueChange:X}=t.useFieldManagement(h),[ae,ee]=N.useState(!1),[de,ce]=N.useState(()=>{var q;return!!((q=s.parameters)!=null&&q.windowTransform)}),[W,pe]=N.useState(!1),[Z,we]=N.useState(!1),[U,ne]=N.useState(null),ye=N.useMemo(()=>{const q=re=>re!=null&&re.startsWith("card-source-")?re.replace("card-source-",""):re,J=q(s.id),ie=y.find(re=>{if(s.qualifiedFieldName&&re.qualifiedFieldName&&re.qualifiedFieldName===s.qualifiedFieldName||s.qualifiedEntityName&&re.qualifiedEntityName&&re.qualifiedEntityName===s.qualifiedEntityName&&re.name===s.name)return!0;const Ce=q(re.id);return!!(J&&Ce&&J===Ce)});return{dataType:(ie==null?void 0:ie.dataType)||s.dataType,resolvedFromScopedField:!!ie}},[s.dataType,s.id,s.name,s.qualifiedEntityName,s.qualifiedFieldName,y]),se=t.getGranularityOptionsForFieldType(ye.dataType),[be,ge]=N.useState(s.dateFormat||"YYYY-MM-DD"),[fe,Ne]=N.useState(s.customFormat||""),[ve,Te]=N.useState(!!s.customFormat),Le=N.useRef(null),[te,je]=N.useState(s.aliasTemplate||""),[me,Ee]=N.useState(s.valueAliases||{}),[he,Re]=N.useState((vs=s.parameters)==null?void 0:vs.filters),Ye=q=>{q==="custom"?Te(!0):(Te(!1),ge(q),(n==="groupBy"||ot)&&A(a,q,"",n))},qe=q=>{Ne(q),(n==="groupBy"||ot)&&A(a,"custom",q,n)},Se=q=>{var re;const ie=(re=t.getDateFormatOptionsForGranularity(q)[0])==null?void 0:re.value;ie&&!ve&&(ge(ie),n==="groupBy"&&A(a,ie,"",n)),n==="groupBy"&&S(a,q)},at=q=>{je(q),n==="metrics"&&v(a,q)},nt=q=>{Ee(q),n==="metrics"&&k(a,q)},le=q=>{w(n,a,q)},Ie=q=>q!=null&&q.startsWith("card-source-")?q.replace("card-source-",""):q,Ge=(q,J,ie)=>{const re=Ie(q.id),Ce=Ie(J.id);return re&&Ce&&re===Ce?!0:q.name===J.name&&q.role===J.role},Oe=t.getExpressionFieldKind(s),ke=t.getFieldExpressionAnnotation(s),jt=Oe==="domain_calculated"||Oe==="user_calculated",$e=Oe==="user_calculated"?(ys=g==null?void 0:g.calculatedFields)==null?void 0:ys.find(q=>Ge(q,s)):void 0,bt=Oe==="user_calculated"&&(s.fieldScope==="dashboard"||s.fieldScope===void 0&&!!$e),et=Oe==="domain_calculated",$t=et?"domain":bt?"dashboard":"card",We=et?s:bt&&$e?$e:s,vt=q=>{var J;if(Re(q),n==="metrics"){const ie={...s,parameters:{...s.parameters,filters:q}},re=[...((J=h.config)==null?void 0:J.metricColumns)||[]];re[a]=ie,t.useEditorStore.getState().actions.updateCardConfig(h.id,{metricColumns:re})}pe(!1)},Tt=async q=>{await E(q),nn()},rt=()=>{f(n,a)},Kt={transform:t.CSS.Transform.toString(p),transition:x},lt=t.getDataType(ye.dataType||s.dataType),yt=lt==="date",Et=o==="kpi",ot=n==="detailColumns",it=(Ns=h.config)==null?void 0:Ns.metricColumns,Ue=(Cs=h.config)==null?void 0:Cs.groupByColumns,ct=t.useDashboardStore(q=>{var J;return(J=q.dashboard)==null?void 0:J.filters}),dt=t.useDashboardStore(q=>q.filterValues),_e=s.granularity||"day",Gt=se.includes(_e)?_e:"day",Nt=n==="groupBy"&&!se.includes(_e),Ct=t.getDateFormatOptionsForGranularity(Gt),It=ve?"custom":Ct.some(q=>q.value===be)?be:((Ss=Ct[0])==null?void 0:Ss.value)??"YYYY-MM-DD";N.useEffect(()=>{var ie;if(j||!Nt){Le.current=null;return}const q=`${s.id}:${_e}:${ye.dataType||s.dataType||""}:${a}`;if(Le.current===q)return;Le.current=q;const J="day";if(S(a,J),!ve){const re=(ie=t.getDateFormatOptionsForGranularity(J)[0])==null?void 0:ie.value;re&&(ge(re),A(a,re,"",n))}},[s.dataType,s.id,A,S,Nt,a,ve,j,_e,ye.dataType,n]);const kt=!!o&&t.COMPARISON_SUPPORTED_CHART_TYPES.includes(o),Ut=o==="kpi"||o==="table",He=N.useMemo(()=>Ue==null?void 0:Ue.find(q=>t.getDataType(q.dataType||"")==="date"),[Ue]),Dt=N.useMemo(()=>(Ue||[]).some(q=>t.getDataType(q.dataType||"")==="date"),[Ue]),At=N.useMemo(()=>{var re;if(!He)return!1;const q=(re=h.config)==null?void 0:re.filters;if(!q)return!1;const J=Ce=>{const Me=Ce.field;return Me?He.id&&Me.id===He.id||He.qualifiedFieldName&&Me.qualifiedFieldName===He.qualifiedFieldName?!0:Me.name===He.name:!1},ie=Ce=>Ce.conditions.some(ze=>t.getDataType(ze.field.dataType||"")==="date"&&J(ze))?!0:Ce.groups.some(ze=>ie(ze));return ie(q)},[(ws=h.config)==null?void 0:ws.filters,He]),Ht=N.useMemo(()=>ao(ct||[],He,dt),[ct,dt,He]),tt=At||Ht,Ae=s,ut=((Es=(Ts=Ae.parameters)==null?void 0:Ts.windowTransform)==null?void 0:Es.function)||"none",$=t.isMetricTransformEnabled(Ae),Q=$?ut:null,Y=t.supportsMetricTransformForMetric({cardType:o||"table",cardConfig:h.config||{},metric:Ae,transformMode:Q||"running_total"}),ue=!!Ae.comparisonType&&Ae.comparisonType!=="none",oe=t.getRunningTotalOrderByCandidates(Ue||[]),xe=((Ds=(ks=(Is=Ae.parameters)==null?void 0:Is.windowTransform)==null?void 0:ks.orderBy)==null?void 0:Ds.fieldId)||"",Fe=((Ls=(Ms=(As=Ae.parameters)==null?void 0:As.windowTransform)==null?void 0:Ms.orderBy)==null?void 0:Ls.direction)||"asc",Be=oe.find(q=>q.id===xe),Ke=Q==="running_total"||Q==="moving_average"||Q==="previous_period_delta",mt=$&&Ke&&!!Be&&t.getDataType(Be.dataType||"")!=="date",xt=t.getDefaultRunningTotalPartitionByFieldIds({cardType:o||"table",cardConfig:h.config||{},orderByFieldId:xe||void 0}),Pe=new Set(((Fs=(Os=Ae.parameters)==null?void 0:Os.windowTransform)==null?void 0:Fs.partitionByFieldIds)||xt),ht=o==="pivotTable"||t.isSubtotalEnabledAggregateTable(o||"table",h.config||{}),Mt=[...(Ue||[]).filter(q=>q.id&&(!Ke||q.id!==xe)),...ht?(((Rs=h.config)==null?void 0:Rs.pivotByColumns)||[]).filter(q=>q.id):[]],Lt=((Vs=(Ps=(Bs=Ae.parameters)==null?void 0:Bs.windowTransform)==null?void 0:Ps.movingAverage)==null?void 0:Vs.windowSize)||7,$a=((qs=(zs=(_s=Ae.parameters)==null?void 0:_s.windowTransform)==null?void 0:zs.movingAverage)==null?void 0:qs.minPeriods)||1,Ka=((Gs=(Ks=($s=Ae.parameters)==null?void 0:$s.windowTransform)==null?void 0:Ks.previousPeriodDelta)==null?void 0:Gs.mode)||"absolute",fs=((Qs=(Hs=(Us=Ae.parameters)==null?void 0:Us.windowTransform)==null?void 0:Hs.percentOfTotal)==null?void 0:Qs.scope)||"grand_total",Ga=((Ws=(Ys=(Js=Ae.parameters)==null?void 0:Js.windowTransform)==null?void 0:Ys.percentOfTotal)==null?void 0:Ws.output)||"percent",Ua=N.useMemo(()=>(it||[]).some(q=>q.comparisonType==="start_vs_end"),[it]);N.useEffect(()=>{$&&ce(!0)},[$]);const Ha=n!=="pivotBy",Qa=yt&&n==="groupBy"&&(!Et||Ua),Ja=!Et&&yt&&(n==="groupBy"||ot),Ya=o==="kpi"&&yt&&n==="groupBy",Wa=n==="metrics",gs=kt&&n==="metrics",Xa=()=>{const q=s,J=n==="metrics"&&jt;return e.jsxs("div",{className:"space-y-1",children:[!J&&e.jsx("div",{title:`${s.entityName}.${s.name}`,onPointerDown:ie=>{ie.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-muted-foreground/80",children:`${s.entityName}.${s.name}`}),J&&q.calculatedFormula&&e.jsxs("div",{title:t.formatDisplayFormula(q.calculatedFormula),onPointerDown:ie=>{ie.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap rounded bg-muted/50 px-1.5 py-0.5 font-mono text-xs text-primary",children:["= ",t.formatDisplayFormula(q.calculatedFormula)]})]})},Za=()=>Ha?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(Je,{value:s.label??"",onSave:le,placeholder:"Display label...",type:"text"})]}):null,js=()=>Qa?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:Se,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:se.map(q=>e.jsx(t.SelectItem,{className:"text-xs",value:q,children:t.toTitleCase(q)},q))})]})]}):null,en=()=>Ja?e.jsxs(e.Fragment,{children:[js(),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:It,onValueChange:Ye,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:Ct.map(q=>e.jsx(t.SelectItem,{className:"text-xs",value:q.value,children:q.label},q.value))})]}),ve&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(t.Input$1,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:fe,onChange:q=>{q.stopPropagation(),qe(q.target.value)},onClick:q=>q.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}):null,tn=()=>{var J,ie,re,Ce;const q=Ya;return q?e.jsx(e.Fragment,{children:q&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(t.SmallSwitch,{checked:((J=h.config)==null?void 0:J.showTrendline)||!1,onCheckedChange:K})]})}),((ie=h.config)==null?void 0:ie.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$1,{type:"number",min:"1",max:"365",value:((re=h.config)==null?void 0:re.trendlineWindow)||30,onChange:Me=>{const ze=parseInt(Me.target.value)||30;H(ze)},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:((Ce=h.config)==null?void 0:Ce.trendlineGranularity)||"day",onValueChange:G,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},sn=()=>{if(!Wa)return null;const q=jt;return e.jsxs(e.Fragment,{children:[q&&D&&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:()=>we(!0),children:[e.jsx(t.Pencil,{className:"mr-2 h-3 w-3"}),"Edit Formula"]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(t.Select,{value:s.aggregate,onValueChange:J=>{T(a,J)},disabled:q,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select function..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(t.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),t.getDataType(s.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(t.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(t.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(t.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(t.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Number Format"}),e.jsx(xs,{value:Ae.format,onChange:J=>M(a,J),showTitle:!1})]}),e.jsx(t.Collapsible,{open:de,onOpenChange:ce,children:e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-muted/20 p-2.5",children:[e.jsx(t.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between rounded-sm px-0.5 py-0.5 text-left",children:[e.jsx("div",{className:"text-xs font-medium text-foreground",children:"Metric Transform"}),e.jsxs("div",{className:"flex items-center text-[11px] text-muted-foreground",children:[!de&&e.jsx("span",{className:"mr-2",children:$?t.toTitleCase(ut.replace(/_/g," ")):"None"}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 transition-transform",de?"rotate-180":"")})]})]})}),e.jsxs(t.CollapsibleContent,{className:"space-y-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Transform"}),e.jsxs(t.Select,{value:$?ut:"none",onValueChange:J=>F(a,J),disabled:!Y.supported&&!$,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:ue,children:"Running Total"}),e.jsx(t.SelectItem,{value:"moving_average",disabled:ue,children:"Moving Average"}),e.jsx(t.SelectItem,{value:"previous_period_delta",disabled:ue,children:"Previous Period Delta"}),e.jsx(t.SelectItem,{value:"percent_of_total",disabled:ue,children:"Percent of Total"})]})]}),!Y.supported&&!$&&e.jsx("div",{className:"text-xs text-muted-foreground",children:Y.reason}),ue&&!$&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"Disable comparison to enable metric transforms."})]}),$&&e.jsxs(e.Fragment,{children:[Ke&&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:xe,onValueChange:J=>b(a,J),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select order field..."})}),e.jsx(t.SelectContent,{children:oe.filter(J=>!!J.id).map(J=>e.jsx(t.SelectItem,{value:J.id,className:"text-xs",children:J.label||J.name},J.id))})]}),!xe&&e.jsx("div",{className:"text-xs text-amber-700",children:"No date trend detected. Select an order field."}),mt&&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:Fe,onValueChange:J=>L(a,J),disabled:!xe,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"})]})]})]})]}),Q==="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$1,{type:"number",min:1,className:"h-8 text-xs",value:Lt,onChange:J=>P(a,Number(J.target.value))}),e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Min Periods"}),e.jsx(t.Input$1,{type:"number",min:1,max:Lt,className:"h-8 text-xs",value:$a,onChange:J=>R(a,Number(J.target.value))})]}),Q==="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:Ka,onValueChange:J=>B(a,J),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select output..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"absolute",children:"Absolute Delta"}),e.jsx(t.SelectItem,{value:"percent",children:"Percent Delta"})]})]})]}),Q==="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:fs,onValueChange:J=>z(a,J),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select scope..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"grand_total",children:"Grand Total"}),e.jsx(t.SelectItem,{value:"partition_total",children:"Partition Total"})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Output"}),e.jsxs(t.Select,{value:Ga,onValueChange:J=>_(a,J),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select output..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"percent",children:"Percent"}),e.jsx(t.SelectItem,{value:"fraction",children:"Fraction"})]})]})]})]}),(Q==="running_total"||Q==="moving_average"||Q==="previous_period_delta"||Q==="percent_of_total"&&fs==="partition_total")&&Mt.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:Mt.map(J=>{const ie=!!J.id&&Pe.has(J.id);return e.jsxs("button",{type:"button",onClick:()=>J.id&&C(a,J.id),className:t.cn("flex h-7 w-full items-center justify-between rounded border px-2 text-xs",ie?"border-primary bg-primary/5 text-primary":"border-border text-muted-foreground"),children:[e.jsx("span",{children:J.label||J.name}),ie?e.jsx(t.Check,{className:"h-3 w-3"}):null]},J.id)})})]})]})]})]})}),gs&&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:Ae.comparisonType||"none",disabled:$,onValueChange:J=>O(a,J),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"none",children:"No Comparison"}),(()=>{const J=!Dt||!tt,ie=Dt?tt?void 0:"Add a date filter to enable":"Add a date groupBy to enable",re=(Ce,Me)=>e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.SelectItem,{value:Ce,disabled:J,title:ie,children:Me})}),J&&ie&&e.jsx(t.TooltipContent,{side:"right",children:ie})]})});return e.jsxs(e.Fragment,{children:[re("previous_period","Previous Period"),re("same_period_last_year","Same Period Last Year"),re("start_vs_end","Start vs End")]})})(),Ut&&e.jsx(t.SelectItem,{value:"target",children:"Target"})]})]})]}),gs&&Ae.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$1,{type:"number",value:Ae.targetValue!==void 0&&Ae.targetValue!==null?String(Ae.targetValue):"",onChange:J=>{const ie=J.target.value;if(ie===""){X(a,void 0);return}const re=Number(ie);X(a,Number.isFinite(re)?re:void 0)},className:"h-8 text-xs",placeholder:"Enter target value..."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(he==null?void 0:he.conditions)&&he.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:he.conditions.map(J=>e.jsxs("div",{className:"flex cursor-pointer items-center gap-2 rounded bg-muted/50 p-2 text-xs transition-colors hover:bg-muted/70",onClick:()=>{ne(J),pe(!0)},children:[e.jsxs("span",{className:"font-medium",children:[J.field.label,":"]}),e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"cursor-help text-muted-foreground",children:Array.isArray(J.value)?J.value.length===1?String(J.value[0]):J.value.length<=2?J.value.join(", "):`${J.value.slice(0,2).join(", ")} +${J.value.length-2}`:String(J.value)})}),Array.isArray(J.value)&&J.value.length>1&&e.jsx(t.TooltipContent,{side:"top",className:"max-w-[300px]",children:e.jsxs("div",{className:"text-xs",children:[e.jsxs("div",{className:"mb-1 font-medium",children:["Selected values (",J.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:J.value.map((ie,re)=>e.jsx("div",{children:String(ie)},re))})]})})]})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:ie=>{var Ce;ie.stopPropagation();const re=he.conditions.filter(Me=>Me.id!==J.id);if(re.length>0){const Me={...he,conditions:re};vt(Me)}else if(Re(void 0),n==="metrics"){const Me={...s,parameters:{...s.parameters,filters:void 0}},ze=[...((Ce=h.config)==null?void 0:Ce.metricColumns)||[]];ze[a]=Me,t.useEditorStore.getState().actions.updateCardConfig(h.id,{metricColumns:ze})}},children:e.jsx(t.X,{className:"h-3 w-3"})})]},J.id))}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{ne(null),pe(!0)},children:[e.jsx(t.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(uo,{column:s}),c&&e.jsxs(e.Fragment,{children:[e.jsx(no,{aliasTemplate:te,onAliasTemplateChange:at}),e.jsx(ro,{valueAliases:me,onValueAliasesChange:nt})]})]})},{columns:an=[],refetch:nn}=t.useColumns(),rn=(he==null?void 0:he.conditions)&&he.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:m,style:Kt,className:t.cn("group mx-auto flex w-full flex-col gap-2 rounded-md border border-border/55 bg-background p-2 transition-colors duration-150","hover:border-border/80 hover:bg-muted/20",ae&&"border-border/80 bg-muted/20 shadow-[inset_0_1px_0_rgba(255,255,255,0.35)]",u&&"z-50 scale-95 opacity-50","cursor-default"),children:[e.jsxs("div",{className:"flex min-w-0 grow items-center gap-2",children:[e.jsx("button",{type:"button",...d,...l,className:"flex shrink-0 cursor-grab items-center rounded-sm p-0.5 text-muted-foreground transition-colors hover:text-foreground active:cursor-grabbing","aria-label":`Drag ${t.getMetricDisplayLabel(s)}`,onClick:q=>{q.stopPropagation()},children:e.jsx(t.GripVertical,{className:"h-3.5 w-3.5"})}),e.jsxs("div",{className:"relative shrink-0",children:[e.jsx(t.IconForFieldType,{dataType:lt}),ke&&e.jsx("span",{className:t.cn(t.FIELD_EXPRESSION_BADGE_BASE_CLASS,ke.badgeClassName),children:ke.label})]}),e.jsx(hs,{className:t.cn("w-[140px] min-w-0 flex-1 text-sm text-foreground/95",rn&&"w-[120px] min-w-0"),children:t.getMetricDisplayLabel(s)}),n==="metrics"&&((Xs=he==null?void 0:he.conditions)==null?void 0:Xs.length)&&!ae&&e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 text-xs text-primary/90",children:[e.jsx(t.Filter,{className:"h-3 w-3"}),e.jsx("span",{children:he.conditions.length})]})}),e.jsx(t.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:he.conditions.map(q=>e.jsxs("div",{children:[q.field.label,":"," ",Array.isArray(q.value)?`${q.value.length} values`:String(q.value)]},q.id))})})]})}),n!=="sortBy"&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-foreground/55 hover:text-foreground",onClick:q=>{q.stopPropagation(),ee(!ae)},children:e.jsx(t.ChevronDown,{className:`h-3 w-3 transition-transform ${ae?"rotate-180":""}`})}),n==="sortBy"&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-foreground/55 hover:text-foreground",onClick:q=>{q.stopPropagation(),i(r==="asc"?"desc":"asc")},children:r==="asc"?e.jsx(t.ArrowUp,{className:"h-3 w-3"}):e.jsx(t.ArrowDown,{className:"h-3 w-3"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-foreground/55 hover:text-foreground",onClick:q=>{q.stopPropagation(),rt()},children:e.jsx(t.X,{className:"h-2.5 w-2.5"})})]}),ae&&e.jsxs("div",{className:"space-y-3 rounded-md bg-muted/20 p-2.5",children:[Xa(),Za(),o==="kpi"&&js(),en(),tn(),sn()]})]}),W&&e.jsx(za,{open:W,onOpenChange:q=>{pe(q),q||ne(null)},availableFields:an,existingFilters:he,editingCondition:U,onSave:q=>{var J;if(q)vt(q);else if(Re(void 0),n==="metrics"){const ie={...s,parameters:{...s.parameters,filters:void 0}},re=[...((J=h.config)==null?void 0:J.metricColumns)||[]];re[a]=ie,t.useEditorStore.getState().actions.updateCardConfig(h.id,{metricColumns:re})}ne(null)}}),Z&&n==="metrics"&&jt&&e.jsx(t.CalculatedFieldEditor,{open:Z,onOpenChange:we,availableFields:y,existingField:We,existingFieldScope:$t,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:q=>{var pt;if(q.role!=="metric")return;const J=[...((pt=h.config)==null?void 0:pt.metricColumns)||[]];J[a]=q;const{frame:ie,actions:re}=t.useEditorStore.getState();if(re.updateCardConfig(h.id,{metricColumns:J}),!t.isCalculatedMetric(q))return;const Ce=ie.calculatedFields||[],Me=Ce.findIndex(Qe=>Qe.name===s.name&&Qe.role===s.role);if(Me<0)return;const ze=Ce.map((Qe,Ot)=>Ot===Me?{...q,id:Qe.id}:Qe);re.updateFrame({calculatedFields:ze})},onSaveToDashboard:q=>{var Ot;if(q.role!=="metric")return;const{frame:J,actions:ie}=t.useEditorStore.getState(),re=J.calculatedFields||[],Ce=re.findIndex(Qt=>Ge(Qt,q)),Me=Ce>=0&&re[Ce].id!==q.id?{...q,id:re[Ce].id}:q,ze=Ce>=0?re.map((Qt,ln)=>ln===Ce?Me:Qt):[...re,Me];ie.updateFrame({calculatedFields:ze});const pt=[...((Ot=h.config)==null?void 0:Ot.metricColumns)||[]],Qe=s;pt[a]={...Me,id:Qe.id,aliasTemplate:Qe.aliasTemplate,valueAliases:Qe.valueAliases,parameters:Qe.parameters,customFormat:Qe.customFormat},ie.updateCardConfig(h.id,{metricColumns:pt})},onPromoteMetricToDomain:V&&D?Tt:void 0,domainId:V,cardId:h.id})]})}function po({concept:s}){const n=()=>{switch(s){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-100 text-xs font-medium dark:bg-blue-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/50 text-xs font-medium dark:bg-blue-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/30 text-xs font-medium dark:bg-blue-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/20 text-xs font-medium dark:bg-blue-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Pivot Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metric Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});case"detailColumns":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields to display as columns in the detail table. No aggregation applied - shows raw values from the database."})]});default:return null}};return e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:300,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(t.TooltipContent,{side:"right",align:"start",className:"p-3",children:n()})]})})}const fo={groupBy:Vt,pivotBy:is,metrics:Tn,detailColumns:t.Table2,sortBy:t.ArrowUpDown};function wt({zone:s,fields:n,label:a,placeholder:r,shouldShow:i,hasPivotColumns:c=!1,activeField:o=null}){const{isOver:d,setNodeRef:l}=t.useDroppable({id:s}),{updateSortByColumn:m}=t.useEditorActions(),p=t.useEditorStore(I=>I.card),x=t.useEditorStore(I=>I.card.type),u=n.length>0,h=N.useMemo(()=>!o||!d?!0:t.validateFieldForChartType(o,s,x).isValid,[o,d,s,x]),g=(I,D)=>{var E;!((E=p.config)!=null&&E.sortByColumns)||p.config.sortByColumns.findIndex(w=>w.id===I)===-1||m(p.id,I,{direction:D})};if(s==="sortBy"&&i===!1)return null;const y=s!=="sortBy"&&x!=="kpi",j=fo[s]||t.Plus;return e.jsxs("div",{className:"mb-3 w-full",children:[e.jsx("div",{className:"mb-1.5 flex items-center gap-2",children:e.jsx(t.Label,{className:t.cn("block text-sm font-medium text-foreground",{}),children:a})}),e.jsx("div",{ref:l,className:t.cn("rounded-lg border p-0.5 transition-colors duration-150",{"border-green-500 bg-green-50 shadow-[0_0_0_1px_rgba(34,197,94,0.18)] dark:bg-green-950":d&&h,"border-red-500 bg-red-50 shadow-[0_0_0_1px_rgba(239,68,68,0.18)] dark:bg-red-950":d&&!h,"border-solid border-border/55 bg-background":!d&&u,"min-h-[56px] border-dashed border-border/60 bg-background":!d&&!u}),children:n.length===0?e.jsxs("div",{className:"flex min-h-[56px] items-center justify-center gap-2 text-sm text-muted-foreground/85",children:[e.jsx(j,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground/80"}),e.jsx("span",{children:r}),y&&e.jsx(po,{concept:s})]}):e.jsx(t.SortableContext,{id:s,items:n.map(I=>I.id),strategy:t.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map((I,D)=>{const E=I.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(ho,{field:I,zone:s,index:D,sortDirection:E,onSortDirectionChange:w=>g(I.id,w),hasPivotColumns:c,cardType:x})})},I.id)})})})})]})}function go({groupByFields:s,pivotByFields:n,metricsFields:a,sortByFields:r,detailFields:i,activeField:c}){var H,G,X,ae;const[o,d]=N.useState(!1),l=t.useEditorStore(ee=>{var de;return!!((de=ee.card.customCardPreferences)!=null&&de.url)}),m=t.useEditorStore(ee=>ee.card),p=t.useEditorStore(ee=>ee.frame),x=t.findCustomVisualConfigCard(p,m),{manifest:u}=t.useCustomVisual(((H=x==null?void 0:x.customCardPreferences)==null?void 0:H.url)||""),h=(G=u==null?void 0:u.visuals)==null?void 0:G.find(ee=>{var de;return ee.name===((de=x==null?void 0:x.customCardPreferences)==null?void 0:de.componentName)}),g=t.resolveMultiInputType(x,h)==="multiple",y=g&&!!((X=x==null?void 0:x.customCardPreferences)!=null&&X.url),j=t.getConfigSlotExpectedType(h==null?void 0:h.slots),I=t.useEditorStore(ee=>ee.actions.updateCardConfig),D=t.useEditorStore(ee=>ee.actions.updateFrame),{scopedFields:V,refetch:E}=t.useScopedFields(),{userContext:w}=t.useCurrentUserInfo(),T=g&&(x==null?void 0:x.id)===m.id&&j?j:m==null?void 0:m.type,A=T==="detailTable",S=s.length>0||a.length>0||i.length>0,v=!A&&(T!=="kpi"||a.length<=2),k=!A,M=!A&&T!=="kpi",f=T!=="kpi"&&S,O=A,F="Drop sort fields here",b=(ae=m.dataSource)==null?void 0:ae.semanticDomainId,{promoteMetric:L}=t.usePromoteCalculatedMetricToDomain({domainId:b}),C=(w==null?void 0:w.type)==="organization",P=ee=>{const de=p.calculatedFields||[],ce=de.findIndex(ne=>ne.name===ee.name&&ne.role===ee.role),W=ce>=0?{...ee,id:de[ce].id}:ee,pe=ce>=0?de.map((ne,ye)=>ye===ce?W:ne):[...de,W];D({calculatedFields:pe});const Z=t.getNewField(W,"metrics",a),we=a.findIndex(ne=>ne.name===Z.name&&ne.role===Z.role),U=we>=0?a.map((ne,ye)=>ye===we?{...ne,...Z,id:ne.id}:ne):[...a,Z];I(m.id,{metricColumns:U})},R=async ee=>{await L(ee),E()},B=["pie","doughnut","polar","funnel","aggregateTable","bubble","scatter"].includes(T),z=M&&!B,_=()=>T==="kpi"?{label:"Trend By",placeholder:"Drop trend field here"}:{label:"Rows",placeholder:"Drop dimensions here"},K=()=>T==="kpi"?{label:"Metric",placeholder:"Drop metric here"}:{label:"Metrics",placeholder:"Drop metrics here"};return e.jsxs(e.Fragment,{children:[e.jsxs(t.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full space-y-2.5",children:[e.jsxs(t.AccordionItem,{value:"fields",className:"rounded-xl border border-border/55 border-b-0 bg-card px-3 shadow-[0_1px_2px_rgba(15,23,42,0.04)]",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2.5 text-xs font-semibold tracking-wide text-foreground/70 hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.List,{className:"h-4 w-4 text-foreground/60"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-3 pt-1.5",children:[v&&e.jsx(wt,{zone:"groupBy",fields:s,label:_().label,placeholder:_().placeholder,activeField:c}),z&&e.jsx(wt,{zone:"pivotBy",fields:n,label:"Pivot Columns",placeholder:"Drop pivot fields here",activeField:c}),k&&e.jsx(wt,{zone:"metrics",fields:a,label:K().label,placeholder:K().placeholder,hasPivotColumns:n.length>0,activeField:c}),O&&e.jsx(wt,{zone:"detailColumns",fields:i,label:"Columns",placeholder:"Drop columns here"}),a.length>=1&&C&&e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:()=>d(!0),className:"mt-1.5 w-full justify-start border-border/60 border-dashed bg-background text-xs text-foreground/70 hover:bg-muted/40 hover:text-foreground",children:[e.jsx(t.Calculator,{className:"mr-2 h-4 w-4"}),"Create Metric"]}),f&&e.jsx(wt,{zone:"sortBy",fields:r,label:"Sort By",placeholder:F,activeField:c})]})]}),(!l||y)&&e.jsxs(t.AccordionItem,{value:"configuration",className:"rounded-xl border border-border/55 border-b-0 bg-card px-3 shadow-[0_1px_2px_rgba(15,23,42,0.04)]",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2.5 text-xs font-semibold tracking-wide text-foreground/70 hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Settings2,{className:"h-4 w-4 text-foreground/60"}),e.jsx("span",{children:"CHART SETTINGS"})]})}),e.jsx(t.AccordionContent,{className:"mb-2 rounded-md bg-muted/20 px-3 py-0.5",children:e.jsx(t.Accordion,{type:"single",collapsible:!0,className:"w-full",children:e.jsx(_a,{mode:"config"})})})]}),(l||y)&&e.jsxs(t.AccordionItem,{value:"plugin",className:"rounded-xl border border-border/55 border-b-0 bg-card px-3 shadow-[0_1px_2px_rgba(15,23,42,0.04)]",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2.5 text-xs font-semibold tracking-wide text-foreground/70 outline-none ring-0 hover:no-underline focus:outline-none focus-visible:outline-none focus-visible:ring-0 focus-visible:ring-offset-0",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sa,{className:"h-4 w-4 text-foreground/60"}),e.jsx("span",{children:"COMPONENT SETTINGS"})]})}),e.jsx(t.AccordionContent,{className:"mb-2 rounded-md bg-muted/20 px-3 py-0.5",children:e.jsx(Ra,{})})]})]}),e.jsx(t.CalculatedFieldEditor,{open:o,onOpenChange:d,availableFields:V,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:ee=>{ee.role==="metric"&&I(m.id,{metricColumns:[...a,ee]})},onSaveToDashboard:ee=>{ee.role==="metric"&&P(ee)},onPromoteMetricToDomain:b&&C?R:void 0,domainId:b,cardId:m.id})]})}function jo({onEditJoins:s}){const n=t.useEditorStore(d=>d.card),{autoJoinMetadata:a}=t.useDashboardCardQuery(n);if(!(a!=null&&a.autoResolved))return null;const{resolvedJoinPlan:r}=a,i=(r==null?void 0:r.joins)||[];if(i.length===0)return null;const c=d=>!d||d.length===0?"No conditions":d.map(l=>{var u,h,g,y;const m=`${(u=l.source)==null?void 0:u.entityName}.${(h=l.source)==null?void 0:h.name}`,p=`${(g=l.target)==null?void 0:g.entityName}.${(y=l.target)==null?void 0:y.name}`,x=l.operator||"=";return`${m} ${x} ${p}`}).join(" AND "),o=d=>!d.joinKeyGroups||d.joinKeyGroups.length===0?"No conditions defined":d.joinKeyGroups.length===1?c(d.joinKeyGroups[0].keys):d.joinKeyGroups.map((l,m)=>({id:m,operator:l.operator,condition:c(l.keys)}));return e.jsx(t.Card,{className:"border-blue-500/20 bg-blue-50/15 shadow-sm dark:bg-blue-950/10",children:e.jsxs("div",{className:"flex items-center justify-between p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(An,{className:"size-4 text-blue-600/90 dark:text-blue-400"}),e.jsx("h3",{className:"text-xs font-semibold tracking-wide text-blue-900/90 dark:text-blue-100",children:"Resolved Joins"}),e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.Badge,{variant:"secondary",className:"cursor-help bg-blue-100/80 text-xs text-blue-700 dark:bg-blue-900/70 dark:text-blue-300",children:i.length})}),e.jsx(t.TooltipContent,{side:"bottom",align:"start",className:"max-w-md p-3",children:e.jsx("div",{className:"space-y-2",children:i.map((d,l)=>{const m=o(d),p=Array.isArray(m);return e.jsxs("div",{className:"rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"font-medium text-foreground",children:d.source.name}),e.jsx(t.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:d.target.name})]}),e.jsx(t.Badge,{variant:"outline",className:"border-green-500/40 bg-green-50/30 text-xs text-green-700 dark:bg-green-950/30 dark:text-green-300",children:d.joinType})]}),e.jsx("div",{className:"mt-1 space-y-1",children:p?m.map(x=>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:x.condition}),x.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",x.operator,")"]})]},x.id)):e.jsx("div",{className:"rounded bg-muted/30 px-2 py-1",children:e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:m})})})]},d.id||l)})})})]})})]}),s&&e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:s,className:"h-7 gap-1 p-2 text-xs text-blue-700/80 hover:text-blue-900 dark:text-blue-300 dark:hover:text-blue-100",children:e.jsx(t.SquarePen,{className:"size-3.5"})})]})})}const Na={getItem(s){if(typeof window>"u")return null;try{return localStorage.getItem(s)}catch(n){return console.warn(`Failed to read from localStorage (${s}):`,n),null}},setItem(s,n){if(!(typeof window>"u"))try{localStorage.setItem(s,n)}catch(a){console.warn(`Failed to write to localStorage (${s}):`,a)}}};function bo({selectedChart:s,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:i,sortByFields:c,detailFields:o,activeField:d}){var v,k;const[l,m]=N.useState(()=>Na.getItem("chart-selector-expanded")==="true"),[p,x]=N.useState(!1),u=t.useEditorStore(M=>M.card),h=t.useEditorStore(M=>M.actions.updateCardConfig),g=a.length>0||r.length>0||i.length>0||o.length>0,{data:y,autoJoinMetadata:j}=t.useDashboardCardQuery(u),I=g||!!y,D=((v=u==null?void 0:u.config)==null?void 0:v.joinPlan)||(j!=null&&j.autoResolved?j.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),V=((k=u==null?void 0:u.dataSource)==null?void 0:k.selectedEntities)||[],E=M=>{h(u.id,{...u==null?void 0:u.config,joinPlan:M}),x(!1)},w=()=>{h(u.id,{...u==null?void 0:u.config,joinPlan:void 0}),x(!1)},T=()=>{x(!1)},A=()=>{x(!0)};N.useEffect(()=>{Na.setItem("chart-selector-expanded",String(l))},[l]);const S=()=>{m(M=>!M)};return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col bg-background",children:[e.jsx("div",{className:"pl-2 pr-4 pt-4",children:e.jsxs("div",{className:"rounded-xl border border-border/60 bg-card p-3 shadow-[0_1px_2px_rgba(15,23,42,0.05)]",children:[e.jsx("div",{className:t.cn("overflow-hidden transition-all duration-300 ease-in-out",l?"max-h-[210px] opacity-100":"max-h-0 opacity-0"),children:l&&e.jsx(ds,{selectedChart:s,onChartChange:n,variant:"outline"})}),e.jsx("div",{"data-content":"Chart Quick Selector",className:t.cn("flex items-center justify-center",{"mt-3":l,"mt-2":!l}),children:e.jsx(t.ChartQuickSelector,{selectedChart:s,onChartChange:n,isDropdownExpanded:l,onToggleDropdown:S})})]})}),I&&e.jsx("div",{className:"pl-2 pr-4 py-3",children:e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(De.EditorClearButton,{label:"Reset",variant:"secondary",className:"h-7 px-2 text-xs"})})}),e.jsx(t.ScrollArea,{className:"min-h-0 w-full flex-1 basis-0",children:e.jsxs("div",{className:t.cn("space-y-3 pl-2 pr-4 pb-6",I?"pt-1":"pt-4"),children:[e.jsx(jo,{onEditJoins:A}),e.jsx(go,{groupByFields:a,pivotByFields:r,metricsFields:i,sortByFields:c,detailFields:o,activeField:d})]})}),e.jsx(Ia,{open:p,onOpenChange:x,joinPlan:D,availableDataSources:V,onSave:E,onCancel:T,onRemove:w,children:e.jsx("div",{})})]})}function vo({initialFilters:s,availableFields:n}={}){const[a,r]=N.useState(s||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});t.useEditorStore(w=>w.card.dataSource);const{columns:i,isLoading:c}=t.useColumns(),d=n||i||[],l={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},m=w=>{const T=A=>{if(A.id===w){const S=d[0]||l,v=t.getDataType(S.dataType)==="date";return{...A,conditions:[...A.conditions,{id:`condition-${Date.now()}`,field:S,operator:v?"between":"=",value:v?[]:""}]}}return{...A,groups:A.groups.map(T)}};r(T(a))},p=w=>{const T=A=>{if(A.id===w){const S=d[0]||l,v=t.getDataType(S.dataType)==="date";return{...A,groups:[...A.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:S,operator:v?"between":"=",value:v?[]:""}],groups:[]}]}}return{...A,groups:A.groups.map(T)}};r(T(a))},x=(w,T)=>{const A=S=>S.id===w?{...S,conditions:S.conditions.filter(v=>v.id!==T)}:{...S,groups:S.groups.map(A)};r(A(a))},u=(w,T)=>{const A=S=>S.id===w?{...S,groups:S.groups.filter(v=>v.id!==T)}:{...S,groups:S.groups.map(A)};r(A(a))},h=(w,T,A,S)=>{if(A==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const v=k=>k.id===w?{...k,conditions:k.conditions.map(M=>M.id===T?{...M,[A]:S}:M)}:{...k,groups:k.groups.map(v)};r(v(a))},g=(w,T,A)=>{const S=v=>v.id===w?{...v,conditions:v.conditions.map(k=>k.id===T?{...k,...A}:k)}:{...v,groups:v.groups.map(S)};r(S(a))},y=(w,T)=>{const A=S=>S.id===w?{...S,logicalOperator:T}:{...S,groups:S.groups.map(A)};r(A(a))},j=(w,T)=>{const A=S=>S.id===w?{...S,negate:T}:{...S,groups:S.groups.map(A)};r(A(a))},I=(w,T,A)=>{const S=v=>v.id===w?{...v,conditions:t.arrayMove(v.conditions,T,A)}:{...v,groups:v.groups.map(S)};r(S(a))},D=(w,T,A)=>{const S=v=>v.id===w?{...v,groups:t.arrayMove(v.groups,T,A)}:{...v,groups:v.groups.map(S)};r(S(a))},V=w=>{if(!w||w.conditions.length===0&&w.groups.length===0)return"-- No filters defined";const T=S=>{let v="";typeof S.field=="object"?v=S.field.entityName?`${S.field.entityName}.${S.field.name}`:S.field.name:v=String(S.field);const k=S.operator;let M=S.value;if(S.field.dataType==="string"&&!["in","not in"].includes(S.operator))typeof M=="string"?M=`'${M}'`:Array.isArray(M)&&(M=`'${M.join(", ")}'`);else if(S.field.dataType==="date"||S.field.dataType==="datetime"||S.field.dataType==="timestamp")if(S.operator==="between"&&Array.isArray(M)&&M.length===2){const f=M[0]?`'${M[0]}'`:"NULL",O=M[1]?`'${M[1]}'`:"NULL";return`${v} BETWEEN ${f} AND ${O}`}else if((S.operator==="in"||S.operator==="not in")&&Array.isArray(M)){const f=M.map(O=>O?`'${O}'`:"NULL").join(", ");return`${v} ${k} (${f})`}else typeof M=="string"||M instanceof Date?M=`'${M}'`:Array.isArray(M)&&M.length>0&&(M=`'${M[0]}'`);else if(["in","not in"].includes(S.operator)){let f=[];Array.isArray(M)?f=M.map(O=>typeof O=="string"?`'${O}'`:String(O)):typeof M=="string"?f=M.split(",").map(O=>{const F=O.trim();return S.field.dataType==="string"?`'${F}'`:F}):typeof M=="number"&&(f=[String(M)]),M=`(${f.join(", ")})`}switch(k){case"contains":return typeof M=="string"?`${v} LIKE '%${M.replace(/'/g,"")}'`:`${v} LIKE '%${String(M)}'`;case"startsWith":return typeof M=="string"?`${v} LIKE '${M.replace(/'/g,"")}%'`:`${v} LIKE '${String(M)}%'`;case"endsWith":return typeof M=="string"?`${v} LIKE '%${M.replace(/'/g,"")}'`:`${v} LIKE '%${String(M)}'`;case"isNull":return`${v} IS NULL`;case"isNotNull":return`${v} IS NOT NULL`;default:return`${v} ${k} ${M}`}},A=S=>{const v=S.conditions.map(T),k=S.groups.map(F=>A(F)),M=[...v,...k].filter(Boolean);if(M.length===0)return"";const f=M.join(` ${S.logicalOperator} `),O=M.length>1?`(${f})`:f;return S.negate?`NOT ${O}`:O};return A(w)},E=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:d,isLoading:c,addCondition:m,addGroup:p,removeCondition:x,removeGroup:u,updateCondition:h,updateConditionFields:g,updateGroupOperator:y,updateGroupNegate:j,reorderConditions:I,reorderGroups:D,generateSQLPreview:V,hasAnyFilters:E}}function yo({children:s,className:n,delayDuration:a}){return e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:a,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:t.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",n),children:s})}),e.jsx(t.PortalTooltipContent,{children:s})]})})}const No=s=>{if(s.qualifiedEntityName){const n=s.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function Co({value:s,onValueChange:n,availableFields:a,placeholder:r="Select field",className:i="w-64"}){const[c,o]=N.useState(!1),d=N.useMemo(()=>{const l={};return a.forEach(m=>{const p=No(m);l[p]||(l[p]={}),l[p][m.entityId]||(l[p][m.entityId]=[]),l[p][m.entityId].push(m)}),l},[a]);return e.jsxs(t.Popover,{modal:!0,open:c,onOpenChange:o,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":c,className:t.cn("justify-between",!s&&"text-muted-foreground",i),children:[s?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(yo,{children:[s.entityName,".",s.name]})}):r,e.jsx(t.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(t.CommandEmpty,{children:"No fields found."}),e.jsx(t.CommandList,{className:"max-h-80",children:Object.entries(d).map(([l,m])=>e.jsx(t.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Database,{className:"h-3 w-3"}),l]}),children:Object.entries(m).map(([p,x])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[t.getEntityIcon(x[0].entityType,{size:"h-3 w-3"}),e.jsx("span",{children:x[0].entityName})]}),x.map((u,h)=>e.jsxs(t.CommandItem,{value:u.id,onSelect:()=>{n(u),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)===u.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:u.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:u.description&&e.jsx("span",{children:u.description})})]})]},u.id+h))]},`${l}-${p}`))},l))})]})})]})}function ps(s){var y;const n=t.useEditorStore(j=>j.card),{authToken:a,tokenProps:r}=t.useSemaphorContext(),i=t.useEditorStore(j=>j.card.config),c=i==null?void 0:i.joinPlan,o={...s,alias:s.name,label:"value",role:"groupby"},d={...s,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},l={...o,role:"sortby",direction:"asc"},m={joinPlan:c,groupByColumns:[o],metricColumns:[d],sortByColumns:[l]},p=((y=n.dataSource)==null?void 0:y.connectionId)||n.connectionId,{data:x,isPending:u,error:h}=t.useQuery({queryKey:["filterValues",s.entityId,s.name,s.qualifiedEntityName],queryFn:async()=>{try{return await t.postRequestRegular(`${r.apiServiceUrl}/v1/query`,(a==null?void 0:a.accessToken)||"",{connection_id:p,cardConfig:m,cardDataSource:n.dataSource})}catch(j){console.log(s),console.error("error",j)}},enabled:!!p,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((x==null?void 0:x.records)||[]).map(j=>({label:j.value||"BLANK",value:j.value||"BLANK",count:(j==null?void 0:j.count)||0})),isPending:u,error:h}}function So({field:s,selected:n,onChange:a,placeholder:r="Select items...",className:i}){const[c,o]=rs.useState(!1),{filterValues:d}=ps(s),l=p=>{a(n.filter(x=>x!==p))},m=p=>{n.includes(p)?a(n.filter(x=>x!==p)):a([...n,p])};return e.jsx("div",{className:t.cn("w-full",i),children:e.jsxs(t.Popover,{open:c,onOpenChange:o,modal:!0,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":c,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:n.length>0?n.map(p=>{const x=d.find(u=>u.value===p);return e.jsxs(t.Badge,{variant:"secondary",className:"text-xs",children:[x==null?void 0:x.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:u=>{u.key==="Enter"&&l(p)},onMouseDown:u=>{u.preventDefault(),u.stopPropagation()},onClick:u=>{u.stopPropagation(),l(p)},children:e.jsx(t.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},p)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(t.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No results found."}),e.jsx(t.CommandGroup,{children:d.map((p,x)=>e.jsxs(t.CommandItem,{onSelect:()=>m(p.value),children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",n.includes(p.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:p.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:p.count})]})]},p.value+x))})]})]})})]})})}function wo({field:s,value:n,onChange:a,placeholder:r="Select value...",className:i}){const{filterValues:c,isPending:o,error:d}=ps(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:n,onValueChange:a,children:[e.jsx(t.SelectTrigger,{className:i||"flex-1",children:e.jsx(t.SelectValue,{placeholder:r,children:n})}),e.jsx(t.SelectContent,{children:c.map((l,m)=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:l.value,children:l.label},l.value+m))})]})}function To({value:s,operator:n,onChange:a,className:r}){var h,g,y;const{tokenProps:i}=t.useSemaphorContext(),c=((g=(h=i==null?void 0:i.params)==null?void 0:h.calendarContext)==null?void 0:g.tz)||((y=i==null?void 0:i.params)==null?void 0:y.timezone),o=c||Intl.DateTimeFormat().resolvedOptions().timeZone,d=n==="between"||n==="not between",l=N.useMemo(()=>{if(!(!s||!d)&&Array.isArray(s)&&s.length===2){const j=s[0]?new Date(s[0]):void 0,I=s[1]?new Date(s[1]):void 0;if(j&&I)return{from:j,to:I}}},[s,d]),m=N.useMemo(()=>{if(!s||d)return;const j=Array.isArray(s)?s[0]:s;if(!j)return;const I=new Date(j);if(!isNaN(I.getTime()))return I},[s,d]),p=j=>n==="<="||n===">"?t.endOfDayInTimezone(j,o):t.startOfDayInTimezone(j,o),x=j=>{if(!j){a([]);return}if(j.from&&j.to){a([j.from.toISOString(),j.to.toISOString()]);return}a([])},u=j=>{if(!j){a("");return}const I=p(j);a(I.toISOString())};return e.jsx(t.DateRangePicker,{value:d?l:void 0,selectionMode:d?"range":"single",singleValue:d?void 0:m,onChange:x,onSingleChange:u,timezone:c,showRelativeTab:d,className:r,placeholder:"Select date..."})}const Eo=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Io=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],ko=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],Do=["=","!=","isNull","isNotNull"],Ao=["between","=","!=","<","<=",">",">=","isNull","isNotNull"],Mo={"=":"Equals","!=":"Not Equals",">":"Greater Than",">=":"Greater Than or Equal","<":"Less Than","<=":"Less Than or Equal",contains:"Contains",startsWith:"Starts With",endsWith:"Ends With",in:"In","not in":"Not In",between:"Between",isNull:"Is Null",isNotNull:"Is Not Null","not between":"Not Between"};function Ca(s){return Mo[s]||t.titleCase(s)}function Lo(s){switch(s){case"string":return Io;case"number":return ko;case"boolean":return Do;case"date":return Ao;default:return Eo}}function qa({condition:s,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:i,onRemoveCondition:c,onUpdateGroupOperator:o,availableFields:d,updateConditionFields:l}){const{attributes:m,listeners:p,setNodeRef:x,transform:u,transition:h,isDragging:g}=t.useSortable({id:s.id}),{isPending:y,error:j}=ps(s.field),I={transform:t.CSS.Transform.toString(u),transition:h};return e.jsxs("div",{ref:x,style:I,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${g?"z-50 opacity-50":""}`,children:[e.jsx("div",{...m,...p,className:"cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),n>0&&e.jsxs(t.Select,{value:r,onValueChange:D=>o(a,D),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"})]})]}),n===0&&e.jsx("div",{className:"w-24"}),e.jsx(Co,{value:s.field,onValueChange:D=>{const V=D,E=t.getDataType(V.dataType)==="date";l(a,s.id,{field:V,value:"",operator:E?"between":"="})},availableFields:d,placeholder:"Select field",className:"w-64"}),e.jsxs(t.Select,{value:s.operator,onValueChange:D=>{D==="in"||D==="not in"?l(a,s.id,{operator:D,value:[]}):D==="isNull"||D==="isNotNull"?l(a,s.id,{operator:D,value:null}):D==="between"||D==="not between"?l(a,s.id,{operator:D,value:[]}):l(a,s.id,{operator:D,value:""})},children:[e.jsx(t.SelectTrigger,{className:"w-32",children:e.jsx(t.SelectValue,{children:s.operator?Ca(s.operator):""})}),e.jsx(t.SelectContent,{children:Lo(t.getDataType(s.field.dataType)).map(D=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:D,children:Ca(D)},D))})]}),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"?y?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(t.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):j?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(So,{field:s.field,selected:Array.isArray(s.value)&&s.value.every(D=>typeof D=="string")?s.value:[],onChange:D=>l(a,s.id,{value:D}),placeholder:`Select values for ${s.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(s.operator)?e.jsx(t.Input$1,{value:typeof s.value=="string"?s.value:"",onChange:D=>l(a,s.id,{value:D.target.value}),className:"flex-1",placeholder:s.operator.charAt(0).toUpperCase()+s.operator.slice(1)+"..."}):e.jsx(wo,{field:s.field,value:typeof s.value=="string"?s.value:"",onChange:D=>l(a,s.id,{value:D}),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:D=>l(a,s.id,{value:D==="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(To,{value:s.value,operator:s.operator,onChange:D=>l(a,s.id,{value:D}),className:"flex-1"}):e.jsx(t.Input$1,{value:typeof s.value=="string"||typeof s.value=="number"?s.value:"",onChange:D=>i(a,s.id,"value",D.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:()=>c(a,s.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]})}function Oo({group:s,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:i,onRemoveGroup:c,onUpdateCondition:o,onUpdateField:d,onRemoveCondition:l,onReorderConditions:m,onReorderGroups:p,onAddCondition:x,onAddGroup:u,availableFields:h,renderFilterGroup:g,updateConditionFields:y}){const{attributes:j,listeners:I,setNodeRef:D,transform:V,transition:E,isDragging:w}=t.useSortable({id:s.id}),T={transform:t.CSS.Transform.toString(V),transition:E},A=v=>{const{active:k,over:M}=v;if(M&&k.id!==M.id){const f=s.conditions.findIndex(F=>F.id===k.id),O=s.conditions.findIndex(F=>F.id===M.id);f!==-1&&O!==-1&&m(s.id,f,O)}},S=v=>{const{active:k,over:M}=v;if(M&&k.id!==M.id&&a){const f=s.groups.findIndex(F=>F.id===k.id),O=s.groups.findIndex(F=>F.id===M.id);f!==-1&&O!==-1&&p(a,f,O)}};return e.jsxs("div",{ref:D,style:T,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${w?"z-50 opacity-50":""}`,children:[n>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...j,...I,className:"cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(t.Button,{variant:s.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>i(s.id,!s.negate),children:"NOT"}),e.jsxs(t.Select,{value:s.logicalOperator,onValueChange:v=>r(s.id,v),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:()=>a&&c(a,s.id),children:e.jsx(t.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${n>0?"":"px-0"}`,children:[e.jsx(t.DndContext,{sensors:t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),collisionDetection:t.closestCenter,onDragEnd:A,children:e.jsx(t.SortableContext,{items:s.conditions.map(v=>v.id),strategy:t.verticalListSortingStrategy,children:s.conditions.map((v,k)=>e.jsx(qa,{condition:v,index:k,groupId:s.id,groupLogicalOperator:s.logicalOperator,onUpdateCondition:o,onUpdateField:d,onRemoveCondition:l,onUpdateGroupOperator:r,availableFields:h,updateConditionFields:y},v.id))})}),e.jsx(t.DndContext,{sensors:t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),collisionDetection:t.closestCenter,onDragEnd:S,children:e.jsx(t.SortableContext,{items:s.groups.map(v=>v.id),strategy:t.verticalListSortingStrategy,children:s.groups.map(v=>g(v,n+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:()=>x(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Fo({filters:s,availableFields:n,onSave:a,onClearAll:r,onCancel:i}){const{currentFilters:c,availableFields:o,isLoading:d,addCondition:l,addGroup:m,removeCondition:p,removeGroup:x,updateCondition:u,updateConditionFields:h,updateGroupOperator:g,updateGroupNegate:y,reorderConditions:j,reorderGroups:I,generateSQLPreview:D,hasAnyFilters:V,setCurrentFilters:E}=vo({initialFilters:s,availableFields:n}),w=t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),[T,A]=N.useState(!1),S=(M,f,O)=>{const F=b=>b.id===M?{...b,conditions:b.conditions.map(L=>L.id===f?{...L,field:O,dataType:O.dataType}:L)}:{...b,groups:b.groups.map(F)};E(F(c))},v=(M,f=0,O)=>f===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(t.DndContext,{sensors:w,collisionDetection:t.closestCenter,onDragEnd:F=>{const{active:b,over:L}=F;if(L&&b.id!==L.id){const C=M.conditions.findIndex(R=>R.id===b.id),P=M.conditions.findIndex(R=>R.id===L.id);C!==-1&&P!==-1&&j(M.id,C,P)}},children:e.jsx(t.SortableContext,{items:M.conditions.map(F=>F.id),strategy:t.verticalListSortingStrategy,children:M.conditions.map((F,b)=>e.jsx(qa,{condition:F,index:b,groupId:M.id,groupLogicalOperator:M.logicalOperator,onUpdateCondition:u,onUpdateField:S,onRemoveCondition:p,onUpdateGroupOperator:g,availableFields:o,updateConditionFields:h},F.id))})}),e.jsx(t.DndContext,{sensors:w,collisionDetection:t.closestCenter,onDragEnd:F=>{const{active:b,over:L}=F;if(L&&b.id!==L.id){const C=M.groups.findIndex(R=>R.id===b.id),P=M.groups.findIndex(R=>R.id===L.id);C!==-1&&P!==-1&&I(M.id,C,P)}},children:e.jsx(t.SortableContext,{items:M.groups.map(F=>F.id),strategy:t.verticalListSortingStrategy,children:M.groups.map(F=>v(F,f+1,M.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:()=>l(M.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),T&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>m(M.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},M.id):e.jsx(Oo,{group:M,depth:f,parentGroupId:O,onUpdateGroupOperator:g,onUpdateGroupNegate:y,onRemoveGroup:x,onUpdateCondition:u,onUpdateField:S,onRemoveCondition:p,onReorderConditions:j,onReorderGroups:I,onAddCondition:l,onAddGroup:m,availableFields:o,renderFilterGroup:v,updateConditionFields:h},M.id),k=t.getFilterCount(s);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(t.Card,{children:e.jsx(t.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[d?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):v(c),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.SmallSwitch,{id:"advanced-mode",checked:T,onCheckedChange:M=>A(M)}),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)"})]})}),V&&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:D(c)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(t.Button,{size:"sm",variant:"outline",onClick:i,children:"Cancel"}),k>0&&e.jsx(t.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(t.Button,{size:"sm",onClick:()=>a(V?c:null),children:"Apply Filters"})]})]})}function Ro({cardId:s,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:i,isOpen:c,onOpenChange:o}){const d=m=>{a(s,m),o(!1)},l=()=>{r(s),o(!1)};return e.jsxs(t.Dialog,{modal:!1,open:c,onOpenChange:o,children:[c&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(t.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:m=>{m.preventDefault()},children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Card Filters"}),e.jsx(t.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(Fo,{filters:n,availableFields:i,onSave:d,onCancel:()=>o(!1),onClearAll:l})]})]})}function Bo({activeCardId:s,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var D,V;const[i,c]=N.useState(null),o=t.useEditorStore(E=>E.card),d=t.useEditorStore(E=>E.actions.updateCardConfig),l=t.useEditorStore(E=>E.actions.setCardPreferences),m=(D=o==null?void 0:o.config)==null?void 0:D.joinPlan,p=N.useCallback(E=>E.entityName===t.CALCULATED_FIELD_ENTITY_MARKER||E.entityName==="calculated_fields"||E.qualifiedEntityName==="calculated_fields",[]),x=(V=o==null?void 0:o.dataSource)==null?void 0:V.semanticDomainId,{data:u}=t.useJoinabilityMap(x),h=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy"),...a("detailColumns")],g=N.useCallback(E=>E.startsWith("card-source-")?"source":E.startsWith("card-")?null:E.startsWith("source-")||n.find(w=>w.id===E)?"source":a("groupBy").find(w=>w.id===E)?"groupBy":a("metrics").find(w=>w.id===E)?"metrics":a("pivotBy").find(w=>w.id===E)?"pivotBy":a("sortBy").find(w=>w.id===E)?"sortBy":a("detailColumns").find(w=>w.id===E)?"detailColumns":null,[n,a]),y=N.useCallback(E=>{c(E.active.id)},[]),j=N.useCallback(E=>{var M;const{active:w,over:T}=E;if(!T||!s){c(null);return}const A=w.id,S=T.id,v=g(A),k=g(S)||S;if(k==="sortBy"){if(v==="source"){const f=n.find(F=>F.id===A);if(!f){c(null);return}if(!(a("groupBy").some(F=>F.name===f.name&&F.qualifiedEntityName===f.qualifiedEntityName)||a("metrics").some(F=>F.name===f.name&&F.qualifiedEntityName===f.qualifiedEntityName)||a("detailColumns").some(F=>F.name===f.name&&F.qualifiedEntityName===f.qualifiedEntityName))){c(null);return}}else if(v==="pivotBy"){c(null);return}else if(v!=="groupBy"&&v!=="metrics"&&v!=="sortBy"&&v!=="detailColumns"){c(null);return}}if(v==="source"&&k==="sortBy"){const f=[...n].find(L=>L.id===A);if(!f){c(null);return}const O=a("sortBy");if(t.fieldAlreadyExists(f,O)){c(null);return}const F=t.validateFieldForChartType(f,"sortBy",o.type);if(!F.isValid){t.ue.error("Invalid Field Type",{description:F.reason,position:"top-center",duration:3e3}),c(null);return}const b=t.getNewField(f,"sortBy",O);c(null),r("sortBy",[...O,b]);return}if(v==="source"&&k!=="source"&&k!=="sortBy"){const f=[...n].find(R=>R.id===A);if(!f){c(null);return}const O=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy"),...a("detailColumns")],F=O.filter(R=>!p(R));if(F.length>0){const R=F[0].qualifiedEntityName;if(!R){c(null);return}if(R!==f.qualifiedEntityName&&!p(f)&&f.qualifiedEntityName)if(x&&(u!=null&&u.joinabilityMap)){if(t.calculateFieldState(f,{joinabilityMap:u.joinabilityMap,selectedFields:O,baseEntityName:(M=m==null?void 0:m.baseEntity)==null?void 0:M.name}).state==="unreachable"){t.showJoinRequiredNotification(),c(null);return}}else{if(!m){t.showJoinRequiredNotification(),c(null);return}if(!t.areEntitiesJoined(R,f.qualifiedEntityName,m)){t.showJoinRequiredNotification(),c(null);return}}}const b=a(k);if(t.fieldAlreadyExists(f,b)){c(null);return}const L=t.validateFieldForChartType(f,k,o.type);if(!L.isValid){t.ue.error("Invalid Field Type",{description:L.reason,position:"top-center",duration:3e3}),c(null);return}const C=t.getNewField(f,k,b),P=[...b,C];if(c(null),r(k,P),k==="metrics"&&s){const R=t.seedSemanticMetricFormatDefaults(o,C,o.preferences);R&&l(R),t.cleanupKpiMetricComparisonMode(o.type,o.config,d,s,P)}return}if(v&&k&&v!=="source"&&k!=="source"&&v!==k){const f=a(v),O=a(k),F=f.find(R=>R.id===A);if(!F){c(null);return}const b=t.validateFieldForChartType(F,k,o.type);if(!b.isValid){t.ue.error("Invalid Field Type",{description:b.reason,position:"top-center",duration:3e3}),c(null);return}const L=t.getNewField(F,k,O);if(c(null),k==="sortBy"){t.fieldAlreadyExists(F,O)||r(k,[...O,L]);return}const C=f.filter(R=>R.id!==A),P=[...O,L];if(r(v,C),r(k,P),k==="metrics"&&s){const R=t.seedSemanticMetricFormatDefaults(o,L,o.preferences);R&&l(R),t.cleanupKpiMetricComparisonMode(o.type,o.config,d,s,P)}return}if(v&&k&&v===k&&v!=="source"){const f=a(v),O=f.findIndex(b=>b.id===A),F=f.findIndex(b=>b.id===S);if(O!==F){const b=t.arrayMove(f,O,F);r(v,b)}}c(null)},[s,n,a,r,g,m,x,u,p,o,d,l]),I=i?h.find(E=>E.id===i):null;return{activeId:i,activeField:I,handleDragStart:y,handleDragEnd:j}}function Po({activeView:s,onViewChange:n,splitViewEnabled:a}){const r=t.useEditorStore(d=>d.card),{config:i}=N.useContext(t.SemaphorContext).tokenProps,c=(i==null?void 0:i.showInfoTab)!==!1,o=()=>a?!1:!["table","pivotTable","aggregateTable","detailTable"].includes(r.type);return e.jsx(t.Tabs,{value:s,onValueChange:d=>n(d),children:e.jsxs(t.TabsList,{className:"h-9 w-fit gap-1 bg-background p-0",children:[e.jsx(t.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),o()&&e.jsx(t.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),r.type!=="kpi"&&c&&e.jsx(t.TabsTrigger,{value:"info",className:"rounded-md transition data-[state=active]:bg-muted",children:"Info"})]})})}const Vo=[{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 _o(){var l,m;const s=t.useEditorStore(p=>p.card),{updateRowLimit:n}=t.useEditorActions(),[a,r]=N.useState(!1),[i,c]=N.useState(""),o=p=>{if(p==="custom"){r(!0);return}r(!1),n(s.id,parseInt(p))},d=p=>{const x=p.target.value;c(x),x&&!isNaN(parseInt(x))&&n(s.id,parseInt(x))};return e.jsx("div",{className:"flex items-center gap-2",children:a?e.jsx(t.Input,{type:"number",value:i,onChange:d,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(t.Select,{value:((m=(l=s.config)==null?void 0:l.rowLimit)==null?void 0:m.toString())||"100",onValueChange:o,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(t.SelectValue,{placeholder:"Select limit"})}),e.jsx(t.SelectContent,{children:Vo.map(p=>e.jsx(t.SelectItem,{value:p.value,children:p.label},p.value))})]})})}function zo({card:s,queryData:n,isLoading:a,isFetching:r,pagination:i,onPaginationChange:c,onSortChange:o,sortState:d,splitViewEnabled:l}){const m=N.useMemo(()=>(n==null?void 0:n.records)||[],[n==null?void 0:n.records]);return!l||["table","pivotTable","aggregateTable","detailTable"].includes(s.type)?e.jsx(ls,{}):e.jsxs(t.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(t.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:e.jsx(ls,{})}),e.jsx(t.ResizableHandle,{withHandle:!0}),e.jsx(t.ResizablePanel,{defaultSize:40,minSize:20,role:"results-section",className:"flex flex-col",children:e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 py-4 pl-2 pr-4",children:[(a||r)&&(n==null?void 0:n.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),(n==null?void 0:n.records)&&e.jsx(t.TableVisual,{card:s,data:m,paginationMetadata:i,onPaginationChange:c,isLoading:a||r,onSortChange:o,sortState:d})]})})]})}const qo="semaphor-split-view-enabled";function $o(){return ka(qo,!0)}function Ko({activeView:s,onViewChange:n,onFiltersClick:a,activeCard:r,columns:i}){var ee,de,ce;const c=t.useEditorStore(W=>W.card),o=t.useEditorStore(W=>W.inlineFilterValuesMap[(r==null?void 0:r.id)||""]),d=t.useEditorStore(W=>W.actions.removeCardInlineFilterValue),l=t.useDashboardStore(W=>W.filterValues),m=t.useDashboardStore(W=>W.selectedSheetId),{updateCardConfig:p,setCard:x,updateCardInFrame:u,setShowAIDialog:h}=t.useEditorActions(),g=t.useEditorStore(W=>W.showAIDialog),y=t.useEditorStore(W=>W.isDevMode),j=t.useDashboardStore(W=>W.isVisualEditing),[I,D]=N.useState(!1),[V,E]=N.useState(!1),[w,T]=N.useState(null),{config:A}=N.useContext(t.SemaphorContext).tokenProps,S=(A==null?void 0:A.showInfoTab)!==!1,v=(A==null?void 0:A.showQueryDebugTools)!==!1,[k,M]=$o();t.useEditorStore(W=>{var pe;return!!((pe=W.card.customCardPreferences)!=null&&pe.url)});const{data:f,errorMessage:O,isLoading:F,isFetching:b,errorSql:L,pagination:C,refetch:P,comparisonMetadata:R,queryRequestPayload:B}=t.useDashboardCardQuery(r),z=N.useMemo(()=>(f==null?void 0:f.records)||[],[f==null?void 0:f.records]),[_,K]=N.useState(!1);N.useEffect(()=>{b||K(!1)},[b]);const H=()=>{const W=!k;W&&s==="table"&&n("chart"),M(W)},G=(W,pe)=>{const Z={...r,paginationConfig:{page:W+1,pageSize:pe}};x(Z),u(Z)},X=W=>{if(!c.config)return;const pe=t.sortStateToSortByColumns(W,c.config.metricColumns,c.config.groupByColumns,c.config.detailColumns);p(c.id,{...c.config,sortByColumns:pe})},ae=N.useMemo(()=>{var W;return t.sortByColumnsToSortState((W=c.config)==null?void 0:W.sortByColumns)},[(ee=c.config)==null?void 0:ee.sortByColumns]);return e.jsx("div",{className:t.cn("relative flex w-0 grow flex-col",{"border-l":g&&j}),children:e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-3",children:[e.jsxs("div",{className:"flex items-center gap-2 pl-2 pr-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s==="chart"&&g&&e.jsx("div",{className:"w-[200px]",children:e.jsx(ds,{variant:y?"secondary":"ghost"})}),e.jsx(Po,{activeView:s,onViewChange:n,splitViewEnabled:k}),e.jsx(t.FilterInfo,{cardId:r.id,cardFilters:(de=r.config)==null?void 0:de.filters,cardFilterCount:t.getFilterCount(((ce=r.config)==null?void 0:ce.filters)||null),onFiltersClick:a,inlineFilters:r.inlineFilters,inlineFilterValues:o,sheetId:m||"",removeInlineFilterValue:W=>d(r.id,W)}),R&&c.type!=="table"&&e.jsx(t.ComparisonMetadataBadge,{metadata:R,variant:"compact"}),e.jsx("div",{className:"ml-2",children:e.jsx(_o,{})}),g&&e.jsx(De.EditorClearButton,{})]}),e.jsxs("div",{className:t.cn("flex grow items-center justify-end gap-2"),children:[e.jsx(t.IconButton,{tooltip:"Refresh",disabled:F||b,onClick:()=>{K(!0),P()},children:e.jsx(t.RefreshCcw,{className:t.cn("h-4 w-4",{"animate-spin":_})})}),s==="chart"&&e.jsx(Fa,{showInlineFilters:!1,showDisplayOptions:!1}),!g&&e.jsx(t.IconButton,{onClick:()=>h(!g),tooltip:"AI",className:"h-8","aria-label":"AI",children:e.jsx(t.Sparkles,{className:"size-4"})}),s==="chart"&&e.jsxs(t.DropdownMenu,{modal:!1,children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"More Options",className:"h-8","aria-label":"More options",children:e.jsx(t.EllipsisVertical,{className:"size-4"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(t.DropdownMenuLabel,{children:"More Options"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{onClick:H,children:[k?e.jsx(pn,{className:"mr-2 h-4 w-4"}):e.jsx(kn,{className:"mr-2 h-4 w-4"}),k?"Hide Results Table":"Show Results Table"]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs("div",{className:"px-1 py-1",children:[e.jsx(ms,{triggerVariant:"menu",className:"w-full"}),e.jsx(us,{triggerVariant:"menu",className:"w-full"})]})]})]})]})]}),e.jsxs("div",{className:"mt-2 flex min-h-0 grow flex-col",children:[s==="chart"&&e.jsx("div",{className:t.cn("flex grow flex-col pb-4",{"pb-0":k&&!["table","pivotTable","aggregateTable","detailTable"].includes(r.type)}),children:e.jsx(zo,{card:r,queryData:f,isLoading:F,isFetching:b,pagination:C,onPaginationChange:G,onSortChange:X,sortState:ae,splitViewEnabled:k})}),s==="table"&&(f==null?void 0:f.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 py-4 pl-2 pr-4",children:[(F||b)&&(f==null?void 0:f.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),e.jsx(t.TableVisual,{card:r,data:z,comparisonMetadata:R,paginationMetadata:C,onPaginationChange:G,isLoading:F||b,onSortChange:X,sortState:ae})]}),s==="info"&&S&&e.jsx("div",{className:"flex min-h-0 flex-1 flex-col pb-4",children:e.jsx("div",{className:"flex min-h-0 flex-1 flex-col rounded-md bg-background pl-2 pr-4",children:O?e.jsx(cs,{error:O,errorSql:L,onSendFeedback:()=>{const W=t.prepareFeedbackData(t.FeedbackCategory.QUERY_GENERATION,{cardConfig:c.config,dataSource:r.dataSource,dashboardFilters:l,errorMessage:O,errorSql:L,generatedSql:f==null?void 0:f.sql});T(W),E(!0)},onOpenInEditor:()=>{h(!0),setTimeout(()=>{const W=t.useEditorStore.getState().actions;W.setIsDevMode(!0),W.setCardSql(L||""),setTimeout(()=>{W.setRunSql(!0)},100)},100)}}):(f==null?void 0:f.sql)&&e.jsx(Ma,{sql:f.sql,showCardDetails:!0,debugPayloads:v?{queryRequest:B,queryResponse:f,columns:i,dashboardFilters:l}:void 0})})})]}),w&&e.jsx(t.FeedbackDialog,{open:V,onOpenChange:E,feedbackData:w})]})})}function Go({activeField:s}){const[n,a]=N.useState(!0);return N.useEffect(()=>{s&&a(!0)},[s]),s?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${n?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(t.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(t.IconForFieldType,{dataType:s.dataType}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-sm dark:text-muted-foreground",children:s.label||s.name})]}):null}const Uo=()=>{const s=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||s.apply(console,r)};const n=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},a=r=>{var i;if((i=r.reason)!=null&&i.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",n,!0),window.addEventListener("unhandledrejection",a,!0),()=>{console.error=s,window.removeEventListener("error",n,!0),window.removeEventListener("unhandledrejection",a,!0)}};function Ho({column:s,isSelected:n,onSelect:a,availableFields:r,width:i,onWidthChange:c}){var R,B,z;const o=t.useEditorStore(_=>_.card),{updateCardConfig:d,removeGroupByColumn:l,removeMetricColumn:m,updateFilters:p}=t.useEditorActions(),[x,u]=N.useState(!1),[h,g]=N.useState(!1),y=N.useRef(null),j=N.useCallback(_=>{_.preventDefault(),_.stopPropagation(),g(!0),y.current={startX:_.clientX,startWidth:i||150};const K=G=>{if(!y.current)return;const X=G.clientX-y.current.startX,ae=Math.max(80,y.current.startWidth+X);c==null||c(s.id,ae)},H=()=>{g(!1),y.current=null,document.removeEventListener("mousemove",K),document.removeEventListener("mouseup",H)};document.addEventListener("mousemove",K),document.addEventListener("mouseup",H)},[i,s.id,c]),I=(R=o==null?void 0:o.config)==null?void 0:R.filters,D=(B=I==null?void 0:I.conditions)==null?void 0:B.some(_=>_.field.name===s.name&&_.field.qualifiedEntityName===s.qualifiedEntityName),V=_=>{_?p(o.id,_):d(o.id,{filters:void 0})},{attributes:E,listeners:w,setNodeRef:T,transform:A,transition:S,isDragging:v}=t.useSortable({id:s.id}),k={transform:t.CSS.Transform.toString(A),transition:S},M=t.getDataType(s.dataType),f=Qo(M),O=()=>{var H;const _=((H=o==null?void 0:o.config)==null?void 0:H.sortByColumns)||[],K=_.findIndex(G=>G.name===s.name);if(K!==-1){const G=[..._];G[K]={...G[K],direction:"asc"},d(o.id,{sortByColumns:G})}else d(o.id,{sortByColumns:[..._,{...s,id:`sort-${s.id}`,role:"sortby",direction:"asc"}]})},F=()=>{var H;const _=((H=o==null?void 0:o.config)==null?void 0:H.sortByColumns)||[],K=_.findIndex(G=>G.name===s.name);if(K!==-1){const G=[..._];G[K]={...G[K],direction:"desc"},d(o.id,{sortByColumns:G})}else d(o.id,{sortByColumns:[..._,{...s,id:`sort-${s.id}`,role:"sortby",direction:"desc"}]})},b=()=>{var H;const _=((H=o==null?void 0:o.config)==null?void 0:H.groupByColumns)||[];if(!_.some(G=>G.name===s.name)){const G={...s,id:`groupby-${s.id}-${Date.now()}`,role:"groupby"};d(o.id,{groupByColumns:[..._,G]})}},L=_=>{var G;const K=((G=o==null?void 0:o.config)==null?void 0:G.metricColumns)||[];if(!K.some(X=>X.name===s.name&&X.aggregate===_)){const X={...s,id:`metric-${s.id}-${_}-${Date.now()}`,label:`${_} of ${s.label||s.name}`,role:"metric",aggregate:_};d(o.id,{metricColumns:[...K,X]})}},C=()=>{s.role==="groupby"?l(o.id,s.id):s.role==="metric"&&m(o.id,s.id)},P={...k,width:i?`${i}px`:void 0,minWidth:i?`${i}px`:"120px"};return e.jsxs("th",{ref:T,style:P,className:t.cn("group relative border-r border-border bg-background px-1 py-0",v&&"opacity-50",n&&"bg-primary/10",h&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...E,...w,className:"cursor-grab p-1 text-muted-foreground opacity-0 transition-opacity hover:text-foreground group-hover:opacity-100 active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-3 w-3"})}),e.jsxs(t.DropdownMenu,{children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsxs("button",{onClick:a,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",n&&"bg-primary/10"),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(f,{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,")"]}),D&&e.jsx(t.Filter,{className:"h-3 w-3 text-primary"})]}),e.jsx(t.ChevronDown,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsxs(t.DropdownMenuContent,{align:"start",className:"w-48",children:[e.jsxs(t.DropdownMenuItem,{onClick:()=>u(!0),children:[e.jsx(t.Filter,{className:t.cn("mr-2 h-4 w-4",D&&"text-primary")}),D?"Edit Filter":"Filter"]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{onClick:O,children:[e.jsx(un,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(t.DropdownMenuItem,{onClick:F,children:[e.jsx(dn,{className:"mr-2 h-4 w-4"}),"Sort Z → A"]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuSub,{children:[e.jsxs(t.DropdownMenuSubTrigger,{children:[e.jsx(t.Calculator,{className:"mr-2 h-4 w-4"}),"Summarize"]}),e.jsxs(t.DropdownMenuSubContent,{children:[e.jsx(t.DropdownMenuItem,{onClick:()=>L("SUM"),children:"Sum"}),e.jsx(t.DropdownMenuItem,{onClick:()=>L("AVG"),children:"Average"}),e.jsx(t.DropdownMenuItem,{onClick:()=>L("COUNT"),children:"Count"}),e.jsx(t.DropdownMenuItem,{onClick:()=>L("DISTINCT"),children:"Count Distinct"}),e.jsx(t.DropdownMenuItem,{onClick:()=>L("MIN"),children:"Min"}),e.jsx(t.DropdownMenuItem,{onClick:()=>L("MAX"),children:"Max"})]})]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{onClick:b,children:[e.jsx(Vt,{className:"mr-2 h-4 w-4"}),"Group by this column"]}),e.jsxs(t.DropdownMenuItem,{disabled:!0,children:[e.jsx(is,{className:"mr-2 h-4 w-4"}),"Pivot by this column"]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{disabled:!0,children:[e.jsx(t.EyeOff,{className:"mr-2 h-4 w-4"}),"Hide column"]}),e.jsxs(t.DropdownMenuItem,{onClick:C,className:"text-destructive focus:text-destructive",children:[e.jsx(t.Trash2,{className:"mr-2 h-4 w-4"}),"Remove column"]})]})]})]}),e.jsx("div",{onMouseDown:j,className:t.cn("absolute right-0 top-0 h-full w-1 cursor-col-resize bg-transparent hover:bg-primary/50",h&&"bg-primary")}),e.jsx(za,{open:x,onOpenChange:u,availableFields:r.length>0?r:[s],existingFilters:I,editingCondition:D?(z=I==null?void 0:I.conditions)==null?void 0:z.find(_=>_.field.name===s.name&&_.field.qualifiedEntityName===s.qualifiedEntityName):void 0,onSave:V})]})}function Qo(s){switch(s){case"number":return t.Hash;case"date":return t.Calendar;case"string":default:return t.Type}}function Jo({selectedColumn:s,onColumnSelect:n,isLoading:a=!1,sourceFields:r=[]}){var S,v,k,M;const i=t.useEditorStore(f=>f.card),{updateCardConfig:c}=t.useEditorActions(),[o,d]=N.useState(null),[l,m]=N.useState({}),[p,x]=N.useState(!1),u=N.useMemo(()=>{var F,b;const f=((F=i==null?void 0:i.config)==null?void 0:F.groupByColumns)||[],O=((b=i==null?void 0:i.config)==null?void 0:b.metricColumns)||[];return[...f,...O]},[(S=i==null?void 0:i.config)==null?void 0:S.groupByColumns,(v=i==null?void 0:i.config)==null?void 0:v.metricColumns]),h=N.useMemo(()=>{const f=new Set(u.map(O=>`${O.qualifiedEntityName}.${O.name}`));return r.filter(O=>!f.has(`${O.qualifiedEntityName}.${O.name}`))},[r,u]),{data:g,isLoading:y}=t.useDashboardCardQuery(i),j=(g==null?void 0:g.records)||[],I=N.useCallback((f,O)=>{m(F=>({...F,[f]:O}))},[]),D=N.useCallback(f=>{var L,C;const O=t.getDataType(f.dataType),F=((L=i==null?void 0:i.config)==null?void 0:L.groupByColumns)||[],b=((C=i==null?void 0:i.config)==null?void 0:C.metricColumns)||[];if(O==="number"){const P={...f,id:`metric-${f.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};c(i.id,{metricColumns:[...b,P]})}else{const P={...f,id:`groupby-${f.id}-${Date.now()}`,role:"groupby"};c(i.id,{groupByColumns:[...F,P]})}x(!1)},[(k=i==null?void 0:i.config)==null?void 0:k.groupByColumns,(M=i==null?void 0:i.config)==null?void 0:M.metricColumns,i.id,c]),V=t.useSensors(t.useSensor(t.PointerSensor,{activationConstraint:{distance:8}})),E=f=>{d(f.active.id)},w=f=>{const{active:O,over:F}=f;if(d(null),!F||O.id===F.id)return;const b=u.findIndex(C=>C.id===O.id),L=u.findIndex(C=>C.id===F.id);if(b!==-1&&L!==-1){const C=t.arrayMove(u,b,L),P=C.filter(B=>B.role==="groupby"),R=C.filter(B=>B.role==="metric");c(i.id,{groupByColumns:P,metricColumns:R})}},T=o?u.find(f=>f.id===o):null,A=f=>{let O="";for(;f>=0;)O=String.fromCharCode(f%26+65)+O,f=Math.floor(f/26)-1;return O};return a?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(t.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):u.length===0?e.jsx("div",{className:"flex h-full flex-col items-center justify-center gap-4 p-8 text-center",children:e.jsxs("div",{className:"rounded-lg border-2 border-dashed border-muted-foreground/25 p-12",children:[e.jsx("h3",{className:"text-lg font-medium text-muted-foreground",children:"No columns selected"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground/75",children:"Select columns from the panel on the right to build your table"})]})}):e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsxs(t.DndContext,{sensors:V,collisionDetection:t.closestCenter,onDragStart:E,onDragEnd:w,children:[e.jsxs("table",{className:"w-full border-collapse",children:[e.jsxs("thead",{children:[e.jsxs("tr",{className:"border-b border-border bg-muted/30",children:[e.jsx("th",{className:"sticky left-0 z-20 w-12 border-r border-border bg-muted/50 px-2 py-1 text-center text-xs font-medium text-muted-foreground"}),e.jsx(t.SortableContext,{items:u.map(f=>f.id),strategy:t.horizontalListSortingStrategy,children:u.map((f,O)=>e.jsx("th",{style:{width:l[f.id]?`${l[f.id]}px`:void 0,minWidth:l[f.id]?`${l[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:A(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(t.SortableContext,{items:u.map(f=>f.id),strategy:t.horizontalListSortingStrategy,children:u.map(f=>e.jsx(Ho,{column:f,isSelected:(s==null?void 0:s.id)===f.id,onSelect:()=>n(f),availableFields:r,width:l[f.id],onWidthChange:I},f.id))}),e.jsx("th",{className:"w-10 border-r border-border bg-background px-1 py-2",children:e.jsxs(t.Popover,{open:p,onOpenChange:x,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Add column",children:e.jsx(t.Plus,{className:"h-4 w-4"})})}),e.jsx(t.PopoverContent,{className:"w-[280px] p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search columns..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No columns available."}),e.jsx(t.CommandGroup,{heading:"Available Columns",children:h.map(f=>{const O=t.getDataType(f.dataType),F=O==="number"?t.Hash:O==="date"?t.Calendar:t.Type;return e.jsxs(t.CommandItem,{value:f.label||f.name,onSelect:()=>D(f),children:[e.jsx(F,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm",children:f.label||f.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:f.entityName})]})]},f.id)})})]})]})})]})})]})]}),e.jsx("tbody",{children:y?e.jsx("tr",{children:e.jsx("td",{colSpan:u.length+2,className:"h-32 text-center",children:e.jsx(t.LoaderCircle,{className:"mx-auto h-6 w-6 animate-spin text-muted-foreground"})})}):j.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:u.length+2,className:"h-32 text-center text-muted-foreground",children:"No data available"})}):j.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}),u.map(F=>{const b=f[F.name]??f[F.label??""];return e.jsx("td",{style:{width:l[F.id]?`${l[F.id]}px`:void 0,minWidth:l[F.id]?`${l[F.id]}px`:"120px"},className:t.cn("border-r border-border px-3 py-2 text-sm",(s==null?void 0:s.id)===F.id&&"bg-primary/5"),children:e.jsx("span",{className:"block truncate",children:Yo(b,F)})},`${O}-${F.id}`)}),e.jsx("td",{className:"w-10 border-r border-border"})]},O))})]}),e.jsx(t.DragOverlay,{children:T&&e.jsx("div",{className:"rounded border border-primary bg-background px-3 py-2 text-sm font-medium shadow-lg",children:T.label||T.name})})]})}),e.jsxs("div",{className:"flex items-center justify-between border-t border-border bg-muted/30 px-4 py-2 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Showing ",Math.min(j.length,100)," of ",j.length," rows"]}),e.jsxs("span",{children:[u.length," columns"]})]})]})}function Yo(s,n){if(s==null)return"—";if(typeof s=="number")return n.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 a=new Date(s);if(!isNaN(a.getTime()))return a.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}return String(s)}function Wo({entityGroups:s,isLoading:n=!1}){var V,E;const a=t.useEditorStore(w=>w.card),{updateCardConfig:r,removeGroupByColumn:i,removeMetricColumn:c}=t.useEditorActions(),[o,d]=N.useState(!0),[l,m]=N.useState(""),[p,x]=N.useState(new Set),u=((V=a==null?void 0:a.config)==null?void 0:V.groupByColumns)||[],h=((E=a==null?void 0:a.config)==null?void 0:E.metricColumns)||[],g=w=>{const T=new Set(p);T.has(w)?T.delete(w):T.add(w),x(T)},y=w=>u.some(T=>T.name===w.name&&T.qualifiedEntityName===w.qualifiedEntityName)||h.some(T=>T.name===w.name&&T.qualifiedEntityName===w.qualifiedEntityName),j=(w,T)=>{if(T)if(t.getDataType(w.dataType)==="number"){const S={...w,id:`metric-${w.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};r(a.id,{metricColumns:[...h,S]})}else{const S={...w,id:`groupby-${w.id}-${Date.now()}`,role:"groupby"};r(a.id,{groupByColumns:[...u,S]})}else{const A=u.findIndex(v=>v.name===w.name&&v.qualifiedEntityName===w.qualifiedEntityName),S=h.findIndex(v=>v.name===w.name&&v.qualifiedEntityName===w.qualifiedEntityName);A!==-1&&i(a.id,u[A].id),S!==-1&&c(a.id,h[S].id)}},I=w=>{if(!l)return w;const T=l.toLowerCase();return w.filter(A=>A.name.toLowerCase().includes(T)||A.label&&A.label.toLowerCase().includes(T))},D=w=>{switch(t.getDataType(w)){case"number":return t.Hash;case"date":return t.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(Nn,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"border-b border-border p-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(t.Search,{className:"absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),e.jsx(t.Input,{placeholder:"Search columns...",value:l,onChange:w=>m(w.target.value),className:"h-8 pl-8 text-sm"})]})}),(u.length>0||h.length>0)&&e.jsxs("div",{className:"border-b border-border",children:[u.length>0&&e.jsxs(t.Collapsible,{defaultOpen:!0,children:[e.jsxs(t.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(t.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(Vt,{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:u.length})]}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:u.map(w=>{const T=D(w.dataType);return e.jsxs("div",{className:"group flex items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted/50",children:[e.jsx(t.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(T,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:w.label||w.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:()=>i(a.id,w.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]},w.id)})})})]}),h.length>0&&e.jsxs(t.Collapsible,{defaultOpen:!0,children:[e.jsxs(t.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(t.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(t.Calculator,{className:"h-3.5 w-3.5 text-green-500"}),e.jsx("span",{children:"Metrics"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:h.length})]}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:h.map(w=>{const T=D(w.dataType);return e.jsxs("div",{className:"group flex items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted/50",children:[e.jsx(t.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(T,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:w.label||w.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:w.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:()=>c(a.id,w.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]},w.id)})})})]})]}),e.jsx(t.ScrollArea,{className:"flex-1",children:e.jsx("div",{className:"p-2",children:n?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(w=>{const T=I(w.columns);if(T.length===0)return null;const A=p.has(w.entityId)||l.length>0;return e.jsxs(t.Collapsible,{open:A,onOpenChange:()=>g(w.entityId),children:[e.jsxs(t.CollapsibleTrigger,{className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm font-medium hover:bg-muted/50",children:[e.jsx(t.ChevronRight,{className:t.cn("h-3.5 w-3.5 transition-transform duration-200",A&&"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:w.label||w.entityName}),e.jsx("span",{className:"text-xs text-muted-foreground",children:T.length})]}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:T.map(S=>{const v=D(S.dataType),k=y(S);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",k&&"bg-primary/5"),children:[e.jsx(t.Checkbox,{checked:k,onCheckedChange:M=>j(S,M),className:"h-3.5 w-3.5"}),e.jsx(v,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:S.label||S.name})]},S.id)})})})]},w.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(Cn,{className:"h-4 w-4"})})})}const Xo=[{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 Zo({value:s,onChange:n,onSubmit:a,onCancel:r,selectedColumn:i,availableColumns:c}){const[o,d]=N.useState(!1),[l,m]=N.useState("column"),p=N.useRef(null);N.useEffect(()=>{const g=y=>{y.key==="Escape"&&s?r():y.key==="Enter"&&s&&!o&&a(s)};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[s,r,a,o]);const x=g=>{const y=`[${g.label||g.name}]`,j=p.current;if(j){const I=j.selectionStart||0,D=j.selectionEnd||0,V=s.slice(0,I)+y+s.slice(D);n(V),setTimeout(()=>{j.setSelectionRange(I+y.length,I+y.length),j.focus()},0)}else n(s+y);d(!1)},u=g=>{const y=p.current;if(y){const j=y.selectionStart||0,I=y.selectionEnd||0,D=s.slice(0,j)+g.syntax+s.slice(I);n(D),setTimeout(()=>{y.setSelectionRange(j+g.name.length+1,j+g.syntax.length-1),y.focus()},0)}else n(s+g.syntax);d(!1)},h=g=>{switch(t.getDataType(g)){case"number":return t.Hash;case"date":return t.Calendar;default:return t.Type}};return e.jsxs("div",{className:"flex items-center gap-2 border-b border-border bg-muted/30 px-3 py-1.5",children:[e.jsx("div",{className:"flex min-w-[100px] items-center justify-center rounded border border-border bg-background px-2 py-1 text-xs font-medium text-muted-foreground",children:i?e.jsx("span",{className:"truncate",children:i.label||i.name}):e.jsx("span",{children:"—"})}),e.jsxs(t.Popover,{open:o&&l==="function",onOpenChange:g=>{d(g),g&&m("function")},children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Insert function",children:e.jsx(In,{className:"h-4 w-4"})})}),e.jsx(t.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search functions..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No functions found."}),e.jsx(t.CommandGroup,{heading:"Functions",children:Xo.map(g=>e.jsx(t.CommandItem,{value:g.name,onSelect:()=>u(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&&l==="column",onOpenChange:g=>{d(g),g&&m("column")},children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"ghost",size:"sm",className:"h-7 gap-1 px-2 text-xs text-muted-foreground hover:text-foreground",title:"Insert column reference",children:[e.jsx("span",{children:"Columns"}),e.jsx(t.ChevronDown,{className:"h-3 w-3"})]})}),e.jsx(t.PopoverContent,{className:"w-[250px] p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search columns..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No columns found."}),e.jsx(t.CommandGroup,{heading:"Available Columns",children:c.map(g=>{const y=h(g.dataType);return e.jsxs(t.CommandItem,{value:g.label||g.name,onSelect:()=>x(g),children:[e.jsx(y,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:g.label||g.name})]},g.id)})})]})]})})]}),e.jsx("div",{className:"relative flex-1",children:e.jsx(t.Input,{ref:p,value:s,onChange:g=>n(g.target.value),placeholder:"Enter a formula or select a column...",className:"h-7 border-border bg-background font-mono text-sm"})}),s&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-destructive hover:bg-destructive/10 hover:text-destructive",onClick:r,title:"Cancel (Esc)",children:e.jsx(t.X,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-green-600 hover:bg-green-600/10 hover:text-green-600",onClick:()=>a(s),title:"Apply (Enter)",children:e.jsx(t.Check,{className:"h-4 w-4"})})]})]})}function ei({className:s}){var u,h,g,y;const n=t.useEditorStore(j=>j.card),[a,r]=N.useState(null),[i,c]=N.useState(""),{columns:o=[],columnGroups:d=[],isLoading:l}=t.useColumns();(u=n==null?void 0:n.config)!=null&&u.groupByColumns,(h=n==null?void 0:n.config)!=null&&h.metricColumns,(g=n==null?void 0:n.config)!=null&&g.groupByColumns,(y=n==null?void 0:n.config)!=null&&y.pivotByColumns;const m=j=>{r(j),c(j?`[${j.label||j.name}]`:"")},p=j=>{console.log("Formula submitted:",j),c(""),r(null)},x=()=>{c(""),r(null)};return e.jsxs("div",{className:t.cn("flex h-full w-full flex-col",s),children:[e.jsx(Zo,{value:i,onChange:c,onSubmit:p,onCancel:x,selectedColumn:a,availableColumns:o}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(Jo,{selectedColumn:a,onColumnSelect:m,isLoading:l,sourceFields:o})}),e.jsx(Wo,{entityGroups:d,isLoading:l})]})]})}function ti(){var L,C;const[s,n]=N.useState("chart"),[a,r]=N.useState(!1),[i,c]=N.useState(!0),o=t.useEditorStore(P=>P.showAIDialog),d=t.useDashboardStore(P=>P.isVisualEditing),{setCardType:l}=t.useEditorActions(),m=t.useEditorStore(P=>P.card.type);N.useEffect(()=>Uo(),[]);const p=P=>{l(P)},x=t.useEditorStore(P=>P.frame),u=t.useEditorStore(P=>P.card);t.useEditorStore(P=>P.activeTabCardId),t.useEditorStore(P=>P.actions.getAvailableFields);const{addCard:h,removeCard:g,updateCard:y,setActiveCard:j,updateFilters:I}=t.useEditorActions(),{columnFields:D=[],scopedFields:V=[]}=t.useScopedFields(),E=t.useSensors(t.useSensor(t.PointerSensor,{activationConstraint:{distance:8}})),w=u,{getFieldsForContainer:T,setFieldsForContainer:A}=t.useFieldManagement(w),{activeField:S,handleDragStart:v,handleDragEnd:k}=Bo({activeCardId:x.activeCardId,sourceFields:V,getFieldsForContainer:T,setFieldsForContainer:A}),M=(P,R)=>{R&&I(P,R)},f=P=>{var R;y(P,{config:{...(R=x.cards.find(B=>B.id===P))==null?void 0:R.config,filters:void 0}})},O=D,F=P=>{if(!P)return 0;let R=P.conditions.length;return P.groups.forEach(B=>{R+=F(B)}),R},b=F(((L=w==null?void 0:w.config)==null?void 0:L.filters)||null);return e.jsxs(t.DndContext,{sensors:E,collisionDetection:t.closestCenter,onDragStart:v,onDragEnd:k,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Da,{isVisible:i,onToggleVisibility:()=>c(!i)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:m==="tableBuilder"?e.jsx(ei,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!o&&e.jsx(bo,{selectedChart:m,onChartChange:p,groupByFields:T("groupBy"),pivotByFields:T("pivotBy"),metricsFields:T("metrics"),sortByFields:T("sortBy"),detailFields:T("detailColumns"),activeField:S}),e.jsx(Ko,{selectedChart:m,activeView:s,onViewChange:n,onFiltersClick:()=>r(!0),filterCount:b,activeCard:w,columns:D,getFieldsForContainer:T,cards:x.cards,activeCardId:x.activeCardId,addCard:h,setActiveCard:j})]})}),!i&&d&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(t.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>c(!0),title:"Show Data Source Panel",children:e.jsx(t.Database,{className:"h-4 w-4"})})})]}),w&&e.jsx(Ro,{cardId:w.id,filters:((C=w.config)==null?void 0:C.filters)||null,onFiltersChange:M,onClearFilters:f,availableFields:O,isOpen:a,onOpenChange:r}),e.jsx(t.DragOverlay,{dropAnimation:null,children:e.jsx(Go,{activeField:S||null})})]})}function si({authToken:s,onSave:n,onClose:a}){const r=N.useRef(null),i=t.useEditorStore(T=>T.showAIDialog),c=t.useEditorStore(T=>T.isDevMode),o=t.useAssistantLayoutStore(T=>T.setFullscreen),d=t.useAssistantLayoutStore(T=>T.setPanelOpen),l=t.useAssistantLayoutStore(T=>T.setContainer),m=t.useAssistantPanel("editor"),p=t.useFullscreenAssistant(),x=t.useAssistantContainer("editor"),u=p==="editor",h=N.useCallback(T=>{l("editor",T)},[l]),{setAuthToken:g}=t.useDashboardActions(),{setShowAIDialog:y,setOnSave:j,setOnClose:I}=t.useEditorActions(),{setActiveAssistantType:D}=t.useAIActions();N.useEffect(()=>{n&&j(n),a&&I(a)},[n,j,a,I]),N.useEffect(()=>{s&&s.accessToken&&g(s)},[s,g]),N.useEffect(()=>{var T,A;i?((T=r.current)==null||T.resize(40),d("editor",!0),D("editor")):((A=r.current)==null||A.resize(0),d("editor",!1),p==="editor"&&o(null),D(null))},[i,d,D,o,p]);function V(T){var A;T<1?(y(!1),d("editor",!1),p==="editor"&&o(null),D(null),(A=r.current)==null||A.resize(0)):(i||(y(!0),D("editor")),m.isOpen||d("editor",!0))}function E(){return e.jsxs(e.Fragment,{children:[e.jsx(Da,{isVisible:!0,onToggleVisibility:()=>{}}),e.jsxs("div",{className:"relative flex grow",children:[e.jsxs(t.ResizablePanelGroup,{"data-content":"editor-main",className:t.cn("grow transition-opacity",u&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(eo,{})}),e.jsx(t.ResizableHandle,{disabled:!i}),e.jsx(t.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:V,defaultSize:m.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(ya,{isFullscreen:u,onFullscreenChange:T=>o(T?"editor":null),fullscreenContainer:x})})})]}),e.jsx("div",{ref:h,className:t.cn("absolute inset-0",!u&&"pointer-events-none")})]})]})}function w(){return e.jsxs("div",{className:"relative flex h-full grow",children:[e.jsxs(t.ResizablePanelGroup,{"data-content":"explorer",className:t.cn("flex grow transition-opacity",u&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(ti,{})}),e.jsx(t.ResizableHandle,{disabled:!i}),e.jsx(t.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:V,defaultSize:m.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(ya,{isFullscreen:u,onFullscreenChange:T=>o(T?"editor":null),fullscreenContainer:x})})})]}),e.jsx("div",{ref:h,className:t.cn("absolute inset-0",!u&&"pointer-events-none")})]})}return e.jsx(t.ErrorBoundary,{FallbackComponent:t.Fallback,children:c?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:E()}):w()})}function ai(){t.useDashboardStore(l=>l.selectedCardId);const s=t.useDashboardStore(l=>l.selectedSheetId),n=t.useDashboardStore(l=>l.dashboard),{setIsVisualEditing:a,setSelectedSheetId:r}=t.useDashboardStore(l=>l.actions),i=t.useDashboardStore(l=>l.isVisualEditing),c=t.useDashboardStore(l=>l.actions.updateFrame);function o(l){var u,h,g;const m=s?(u=n==null?void 0:n.sheets)==null?void 0:u.some(y=>{var j;return y.id===s&&((j=y.frames)==null?void 0:j.some(I=>I.id===l.id))}):!1,p=(g=(h=n==null?void 0:n.sheets)==null?void 0:h.find(y=>{var j;return(j=y.frames)==null?void 0:j.some(I=>I.id===l.id)}))==null?void 0:g.id,x=m?s:p||null;x&&(c(x,l),s!==x&&r(x),a(!1))}function d(){a(!1)}return e.jsx("div",{role:"editor-container",className:t.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!i}),children:e.jsx(si,{onSave:o,onClose:d})})}exports.default=ai;