react-semaphor 0.1.153 → 0.1.154

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 (24) hide show
  1. package/dist/chunks/{dashboard-controls-kx_4Nico.js → dashboard-controls-BQN37S-Z.js} +3 -3
  2. package/dist/chunks/{dashboard-controls-lIo_URy7.js → dashboard-controls-CfwJmqIk.js} +1 -1
  3. package/dist/chunks/{dashboard-export-dialog-CRVQk6ax.js → dashboard-export-dialog-Bk40DbBa.js} +3 -3
  4. package/dist/chunks/{dashboard-export-dialog-C8xysbOI.js → dashboard-export-dialog-CleOul_2.js} +1 -1
  5. package/dist/chunks/{dashboard-json-C1tJ7tz7.js → dashboard-json-DoH7BzSp.js} +1 -1
  6. package/dist/chunks/{dashboard-json-ZMgeJTRk.js → dashboard-json-DvDujj0u.js} +1 -1
  7. package/dist/chunks/{edit-dashboard-visual-C3qTOeby.js → edit-dashboard-visual-6Dbv7mp-.js} +25 -35
  8. package/dist/chunks/{edit-dashboard-visual-BpFQUvAT.js → edit-dashboard-visual-DHRzXa1_.js} +27 -32
  9. package/dist/chunks/{editor-action-buttons-ypKWmpAH.js → editor-action-buttons-B9rrfO6d.js} +2 -2
  10. package/dist/chunks/{editor-action-buttons-DvGk6NFy.js → editor-action-buttons-D7XJarSH.js} +1 -1
  11. package/dist/chunks/{index-CCdyoQxh.js → index-4FLL7B4z.js} +238 -228
  12. package/dist/chunks/{index-BB5hIN4X.js → index-B57nSymH.js} +26502 -26589
  13. package/dist/chunks/{resource-management-panel-BGSGpS9O.js → resource-management-panel-DJ7ZIbbt.js} +2 -2
  14. package/dist/chunks/{resource-management-panel-CvHAyeCH.js → resource-management-panel-DdtlZ9Cm.js} +1 -1
  15. package/dist/chunks/{use-visual-utils-mgLJuo_U.js → use-visual-utils-BX99ssnb.js} +1 -1
  16. package/dist/chunks/{use-visual-utils-DkaBs9Wi.js → use-visual-utils-CuGAdqrL.js} +1 -1
  17. package/dist/dashboard/index.cjs +1 -1
  18. package/dist/dashboard/index.js +1 -1
  19. package/dist/index.cjs +1 -1
  20. package/dist/index.js +4 -4
  21. package/dist/style.css +1 -1
  22. package/dist/surfboard/index.cjs +1 -1
  23. package/dist/surfboard/index.js +1 -1
  24. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),s=require("./index-CCdyoQxh.js"),D=require("react"),qe=require("./editor-action-buttons-DvGk6NFy.js"),nt=require("react-dom");function at(t){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(a,n,r.get?r:{enumerable:!0,get:()=>t[n]})}}return a.default=t,Object.freeze(a)}const Ke=at(D);/**
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),s=require("./index-4FLL7B4z.js"),D=require("react"),qe=require("./editor-action-buttons-D7XJarSH.js"),nt=require("react-dom");function at(t){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(a,n,r.get?r:{enumerable:!0,get:()=>t[n]})}}return a.default=t,Object.freeze(a)}const Ke=at(D);/**
2
2
  * @license lucide-react v0.453.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -23,11 +23,6 @@
23
23
  *
24
24
  * This source code is licensed under the ISC license.
25
25
  * See the LICENSE file in the root directory of this source tree.
26
- */const it=s.createLucideIcon("ChevronsUpDown",[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]]);/**
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
26
  */const ys=s.createLucideIcon("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/**
32
27
  * @license lucide-react v0.453.0 - ISC
33
28
  *
@@ -38,12 +33,12 @@
38
33
  *
39
34
  * This source code is licensed under the ISC license.
40
35
  * See the LICENSE file in the root directory of this source tree.
41
- */const ct=s.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"}]]);/**
36
+ */const it=s.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"}]]);/**
42
37
  * @license lucide-react v0.453.0 - ISC
43
38
  *
44
39
  * This source code is licensed under the ISC license.
45
40
  * See the LICENSE file in the root directory of this source tree.
46
- */const dt=s.createLucideIcon("EyeClosed",[["path",{d:"m15 18-.722-3.25",key:"1j64jw"}],["path",{d:"M2 8a10.645 10.645 0 0 0 20 0",key:"1e7gxb"}],["path",{d:"m20 15-1.726-2.05",key:"1cnuld"}],["path",{d:"m4 15 1.726-2.05",key:"1dsqqd"}],["path",{d:"m9 18 .722-3.25",key:"ypw2yx"}]]);/**
41
+ */const ct=s.createLucideIcon("EyeClosed",[["path",{d:"m15 18-.722-3.25",key:"1j64jw"}],["path",{d:"M2 8a10.645 10.645 0 0 0 20 0",key:"1e7gxb"}],["path",{d:"m20 15-1.726-2.05",key:"1cnuld"}],["path",{d:"m4 15 1.726-2.05",key:"1dsqqd"}],["path",{d:"m9 18 .722-3.25",key:"ypw2yx"}]]);/**
47
42
  * @license lucide-react v0.453.0 - ISC
48
43
  *
49
44
  * This source code is licensed under the ISC license.
@@ -53,57 +48,57 @@
53
48
  *
54
49
  * This source code is licensed under the ISC license.
55
50
  * See the LICENSE file in the root directory of this source tree.
56
- */const ut=s.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"}]]);/**
51
+ */const dt=s.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"}]]);/**
57
52
  * @license lucide-react v0.453.0 - ISC
58
53
  *
59
54
  * This source code is licensed under the ISC license.
60
55
  * See the LICENSE file in the root directory of this source tree.
61
- */const mt=s.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"}]]);/**
56
+ */const ut=s.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"}]]);/**
62
57
  * @license lucide-react v0.453.0 - ISC
63
58
  *
64
59
  * This source code is licensed under the ISC license.
65
60
  * See the LICENSE file in the root directory of this source tree.
66
- */const xt=s.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"}]]);/**
61
+ */const mt=s.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"}]]);/**
67
62
  * @license lucide-react v0.453.0 - ISC
68
63
  *
69
64
  * This source code is licensed under the ISC license.
70
65
  * See the LICENSE file in the root directory of this source tree.
71
- */const ht=s.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"}]]);/**
66
+ */const xt=s.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"}]]);/**
72
67
  * @license lucide-react v0.453.0 - ISC
73
68
  *
74
69
  * This source code is licensed under the ISC license.
75
70
  * See the LICENSE file in the root directory of this source tree.
76
- */const pt=s.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"}]]);/**
71
+ */const ht=s.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"}]]);/**
77
72
  * @license lucide-react v0.453.0 - ISC
78
73
  *
79
74
  * This source code is licensed under the ISC license.
80
75
  * See the LICENSE file in the root directory of this source tree.
81
- */const ft=s.createLucideIcon("Library",[["path",{d:"m16 6 4 14",key:"ji33uf"}],["path",{d:"M12 6v14",key:"1n7gus"}],["path",{d:"M8 8v12",key:"1gg7y9"}],["path",{d:"M4 4v16",key:"6qkkli"}]]);/**
76
+ */const pt=s.createLucideIcon("Library",[["path",{d:"m16 6 4 14",key:"ji33uf"}],["path",{d:"M12 6v14",key:"1n7gus"}],["path",{d:"M8 8v12",key:"1gg7y9"}],["path",{d:"M4 4v16",key:"6qkkli"}]]);/**
82
77
  * @license lucide-react v0.453.0 - ISC
83
78
  *
84
79
  * This source code is licensed under the ISC license.
85
80
  * See the LICENSE file in the root directory of this source tree.
86
- */const gt=s.createLucideIcon("Link2",[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]]);/**
81
+ */const ft=s.createLucideIcon("Link2",[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]]);/**
87
82
  * @license lucide-react v0.453.0 - ISC
88
83
  *
89
84
  * This source code is licensed under the ISC license.
90
85
  * See the LICENSE file in the root directory of this source tree.
91
- */const jt=s.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"}]]);/**
86
+ */const gt=s.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"}]]);/**
92
87
  * @license lucide-react v0.453.0 - ISC
93
88
  *
94
89
  * This source code is licensed under the ISC license.
95
90
  * See the LICENSE file in the root directory of this source tree.
96
- */const bt=s.createLucideIcon("ListFilter",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M7 12h10",key:"b7w52i"}],["path",{d:"M10 18h4",key:"1ulq68"}]]);/**
91
+ */const jt=s.createLucideIcon("ListFilter",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M7 12h10",key:"b7w52i"}],["path",{d:"M10 18h4",key:"1ulq68"}]]);/**
97
92
  * @license lucide-react v0.453.0 - ISC
98
93
  *
99
94
  * This source code is licensed under the ISC license.
100
95
  * See the LICENSE file in the root directory of this source tree.
101
- */const vt=s.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"}]]);/**
96
+ */const bt=s.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"}]]);/**
102
97
  * @license lucide-react v0.453.0 - ISC
103
98
  *
104
99
  * This source code is licensed under the ISC license.
105
100
  * See the LICENSE file in the root directory of this source tree.
106
- */const yt=s.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"}]]);/**
101
+ */const vt=s.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"}]]);/**
107
102
  * @license lucide-react v0.453.0 - ISC
108
103
  *
109
104
  * This source code is licensed under the ISC license.
@@ -118,17 +113,17 @@
118
113
  *
119
114
  * This source code is licensed under the ISC license.
120
115
  * See the LICENSE file in the root directory of this source tree.
121
- */const Nt=s.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"}]]);/**
116
+ */const yt=s.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"}]]);/**
122
117
  * @license lucide-react v0.453.0 - ISC
123
118
  *
124
119
  * This source code is licensed under the ISC license.
125
120
  * See the LICENSE file in the root directory of this source tree.
126
- */const Ct=s.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"}]]);/**
121
+ */const Nt=s.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"}]]);/**
127
122
  * @license lucide-react v0.453.0 - ISC
128
123
  *
129
124
  * This source code is licensed under the ISC license.
130
125
  * See the LICENSE file in the root directory of this source tree.
131
- */const St=s.createLucideIcon("PanelRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
126
+ */const Ct=s.createLucideIcon("PanelRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
132
127
  * @license lucide-react v0.453.0 - ISC
133
128
  *
134
129
  * This source code is licensed under the ISC license.
@@ -148,33 +143,33 @@
148
143
  *
149
144
  * This source code is licensed under the ISC license.
150
145
  * See the LICENSE file in the root directory of this source tree.
151
- */const wt=s.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"}]]);/**
146
+ */const St=s.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"}]]);/**
152
147
  * @license lucide-react v0.453.0 - ISC
153
148
  *
154
149
  * This source code is licensed under the ISC license.
155
150
  * See the LICENSE file in the root directory of this source tree.
156
- */const kt=s.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"}]]);/**
151
+ */const wt=s.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"}]]);/**
157
152
  * @license lucide-react v0.453.0 - ISC
158
153
  *
159
154
  * This source code is licensed under the ISC license.
160
155
  * See the LICENSE file in the root directory of this source tree.
161
- */const Tt=s.createLucideIcon("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/**
156
+ */const kt=s.createLucideIcon("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/**
162
157
  * @license lucide-react v0.453.0 - ISC
163
158
  *
164
159
  * This source code is licensed under the ISC license.
165
160
  * See the LICENSE file in the root directory of this source tree.
166
- */const Et=s.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"}]]);/**
161
+ */const Tt=s.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"}]]);/**
167
162
  * @license lucide-react v0.453.0 - ISC
168
163
  *
169
164
  * This source code is licensed under the ISC license.
170
165
  * See the LICENSE file in the root directory of this source tree.
171
- */const At=s.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 It({initialJoinPlan:t,availableDataSources:a}){const[n,r]=D.useState(t),[l,d]=D.useState(new Set),i=()=>{const w=n.joins.length>0?Math.max(...n.joins.map(y=>y.sequence))+1:1,g={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:w,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...n,joins:[...n.joins,g]}),d(new Set([...l,g.id]))},c=w=>{r({...n,joins:n.joins.filter(g=>g.id!==w)}),d(new Set([...l].filter(g=>g!==w)))},o=(w,g)=>{var b,A,F,E,L;const y=n.joins.find(S=>S.id===w);if(!y)return;const T={...y,...g};if((b=T.source)!=null&&b.name&&((A=T.target)!=null&&A.name)&&T.source.name===T.target.name){s.ue.error("Self-joins are not yet supported",{description:`Joining ${T.source.name} to itself is not currently supported. Please select a different target table.`});return}const M=n.joins.filter(S=>{var P;return S.id!==w&&S.target.name===((P=T.target)==null?void 0:P.name)});if((F=T.target)!=null&&F.name&&M.length>0){s.ue.error("Duplicate join targets are not supported",{description:`The table ${T.target.name} is already used as a target in another join. Each table can only be joined once.`});return}const N=n.joins.map(S=>S.id===w?T:S);if((E=T.source)!=null&&E.name&&((L=T.target)!=null&&L.name)&&T.joinKeyGroups[0].keys.length===0){const S=a.find(K=>{var G;return K.name===((G=T.source)==null?void 0:G.name)}),P=a.find(K=>{var G;return K.name===((G=T.target)==null?void 0:G.name)}),$={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(S==null?void 0:S.name)||"",entityName:(S==null?void 0:S.name)||"",entityType:(S==null?void 0:S.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:"="},J=[...T.joinKeyGroups];J[0]={...J[0],keys:[$]},T.joinKeyGroups=J,N[N.findIndex(K=>K.id===w)]=T}r({...n,joins:N})};return{joinPlan:n,expandedJoins:l,setJoinPlan:r,addJoin:i,removeJoin:c,updateJoin:o,moveJoinUp:w=>{const g=n.joins.findIndex(y=>y.id===w);if(g>0){const y=[...n.joins],T={...y[g]},M={...y[g-1]};y[g]=M,y[g-1]=T,y.forEach((b,A)=>{b.sequence=A+1});const N={...n,joins:y};r(N)}},moveJoinDown:w=>{const g=n.joins.findIndex(y=>y.id===w);if(g<n.joins.length-1){const y=[...n.joins],T={...y[g]},M={...y[g+1]};y[g]=M,y[g+1]=T,y.forEach((b,A)=>{b.sequence=A+1});const N={...n,joins:y};r(N)}},toggleJoinExpansion:w=>{const g=new Set(l);g.has(w)?g.delete(w):g.add(w),d(g)},getAvailableSourceEntities:w=>{if(n.joins.length===0)return a;const g=n.joins.findIndex(T=>T.id===w);if(g===0)return a.filter(T=>T.name===n.baseEntity.name);const y=new Set;return n.baseEntity.name&&y.add(n.baseEntity.name),n.joins.slice(0,g).forEach(T=>{y.add(T.source.name),y.add(T.target.name)}),a.filter(T=>y.has(T.name))},getAvailableTargetEntities:w=>a.filter(g=>g.name!==w),addJoinKeyGroup:w=>{const g=n.joins.find(T=>T.id===w);if(!g)return;const y=[...g.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];o(w,{joinKeyGroups:y})},updateGroupOperator:(w,g,y)=>{const T=n.joins.find(N=>N.id===w);if(!T)return;const M=[...T.joinKeyGroups];M[g]={...M[g],operator:y},o(w,{joinKeyGroups:M})},removeJoinKeyGroup:(w,g)=>{const y=n.joins.find(M=>M.id===w);if(!y)return;const T=[...y.joinKeyGroups];T.splice(g,1),o(w,{joinKeyGroups:T})},addJoinKey:(w,g)=>{const y=n.joins.find(A=>A.id===w);if(!y)return;const T=a.find(A=>A.name===y.source.name),M=a.find(A=>A.name===y.target.name),N=[...y.joinKeyGroups],b={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(T==null?void 0:T.name)||"",entityName:(T==null?void 0:T.name)||"",entityType:(T==null?void 0:T.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(M==null?void 0:M.name)||"",entityName:(M==null?void 0:M.name)||"",entityType:(M==null?void 0:M.type)||"table"},operator:"="};N[g]={...N[g],keys:[...N[g].keys,b]},o(w,{joinKeyGroups:N})},updateJoinKey:(w,g,y,T,M)=>{const N=n.joins.find(L=>L.id===w);if(!N)return;const b=a.find(L=>L.name===N.source.name),A=a.find(L=>L.name===N.target.name),F=[...N.joinKeyGroups],E=F[g].keys[y];T==="sourceColumnName"&&b?F[g].keys[y]={...E,source:{...E.source,name:M}}:T==="targetColumnName"&&A?F[g].keys[y]={...E,target:{...E.target,name:M}}:T==="operator"&&(F[g].keys[y]={...E,operator:M}),o(w,{joinKeyGroups:F})},removeJoinKey:(w,g,y)=>{const T=n.joins.find(N=>N.id===w);if(!T)return;const M=[...T.joinKeyGroups];M[g].keys.splice(y,1),o(w,{joinKeyGroups:M})},generateSQLPreview:()=>{const w=[...n.joins].sort((T,M)=>T.sequence-M.sequence),g=n.baseEntity;if(!g.name)return"SELECT * FROM table -- Please select a base entity";let y=`SELECT *
166
+ */const Et=s.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 At({initialJoinPlan:t,availableDataSources:a}){const[n,r]=D.useState(t),[l,d]=D.useState(new Set),i=()=>{const w=n.joins.length>0?Math.max(...n.joins.map(y=>y.sequence))+1:1,g={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:w,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...n,joins:[...n.joins,g]}),d(new Set([...l,g.id]))},c=w=>{r({...n,joins:n.joins.filter(g=>g.id!==w)}),d(new Set([...l].filter(g=>g!==w)))},o=(w,g)=>{var b,A,F,E,L;const y=n.joins.find(S=>S.id===w);if(!y)return;const T={...y,...g};if((b=T.source)!=null&&b.name&&((A=T.target)!=null&&A.name)&&T.source.name===T.target.name){s.ue.error("Self-joins are not yet supported",{description:`Joining ${T.source.name} to itself is not currently supported. Please select a different target table.`});return}const M=n.joins.filter(S=>{var P;return S.id!==w&&S.target.name===((P=T.target)==null?void 0:P.name)});if((F=T.target)!=null&&F.name&&M.length>0){s.ue.error("Duplicate join targets are not supported",{description:`The table ${T.target.name} is already used as a target in another join. Each table can only be joined once.`});return}const N=n.joins.map(S=>S.id===w?T:S);if((E=T.source)!=null&&E.name&&((L=T.target)!=null&&L.name)&&T.joinKeyGroups[0].keys.length===0){const S=a.find(K=>{var G;return K.name===((G=T.source)==null?void 0:G.name)}),P=a.find(K=>{var G;return K.name===((G=T.target)==null?void 0:G.name)}),$={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(S==null?void 0:S.name)||"",entityName:(S==null?void 0:S.name)||"",entityType:(S==null?void 0:S.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:"="},J=[...T.joinKeyGroups];J[0]={...J[0],keys:[$]},T.joinKeyGroups=J,N[N.findIndex(K=>K.id===w)]=T}r({...n,joins:N})};return{joinPlan:n,expandedJoins:l,setJoinPlan:r,addJoin:i,removeJoin:c,updateJoin:o,moveJoinUp:w=>{const g=n.joins.findIndex(y=>y.id===w);if(g>0){const y=[...n.joins],T={...y[g]},M={...y[g-1]};y[g]=M,y[g-1]=T,y.forEach((b,A)=>{b.sequence=A+1});const N={...n,joins:y};r(N)}},moveJoinDown:w=>{const g=n.joins.findIndex(y=>y.id===w);if(g<n.joins.length-1){const y=[...n.joins],T={...y[g]},M={...y[g+1]};y[g]=M,y[g+1]=T,y.forEach((b,A)=>{b.sequence=A+1});const N={...n,joins:y};r(N)}},toggleJoinExpansion:w=>{const g=new Set(l);g.has(w)?g.delete(w):g.add(w),d(g)},getAvailableSourceEntities:w=>{if(n.joins.length===0)return a;const g=n.joins.findIndex(T=>T.id===w);if(g===0)return a.filter(T=>T.name===n.baseEntity.name);const y=new Set;return n.baseEntity.name&&y.add(n.baseEntity.name),n.joins.slice(0,g).forEach(T=>{y.add(T.source.name),y.add(T.target.name)}),a.filter(T=>y.has(T.name))},getAvailableTargetEntities:w=>a.filter(g=>g.name!==w),addJoinKeyGroup:w=>{const g=n.joins.find(T=>T.id===w);if(!g)return;const y=[...g.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];o(w,{joinKeyGroups:y})},updateGroupOperator:(w,g,y)=>{const T=n.joins.find(N=>N.id===w);if(!T)return;const M=[...T.joinKeyGroups];M[g]={...M[g],operator:y},o(w,{joinKeyGroups:M})},removeJoinKeyGroup:(w,g)=>{const y=n.joins.find(M=>M.id===w);if(!y)return;const T=[...y.joinKeyGroups];T.splice(g,1),o(w,{joinKeyGroups:T})},addJoinKey:(w,g)=>{const y=n.joins.find(A=>A.id===w);if(!y)return;const T=a.find(A=>A.name===y.source.name),M=a.find(A=>A.name===y.target.name),N=[...y.joinKeyGroups],b={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(T==null?void 0:T.name)||"",entityName:(T==null?void 0:T.name)||"",entityType:(T==null?void 0:T.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(M==null?void 0:M.name)||"",entityName:(M==null?void 0:M.name)||"",entityType:(M==null?void 0:M.type)||"table"},operator:"="};N[g]={...N[g],keys:[...N[g].keys,b]},o(w,{joinKeyGroups:N})},updateJoinKey:(w,g,y,T,M)=>{const N=n.joins.find(L=>L.id===w);if(!N)return;const b=a.find(L=>L.name===N.source.name),A=a.find(L=>L.name===N.target.name),F=[...N.joinKeyGroups],E=F[g].keys[y];T==="sourceColumnName"&&b?F[g].keys[y]={...E,source:{...E.source,name:M}}:T==="targetColumnName"&&A?F[g].keys[y]={...E,target:{...E.target,name:M}}:T==="operator"&&(F[g].keys[y]={...E,operator:M}),o(w,{joinKeyGroups:F})},removeJoinKey:(w,g,y)=>{const T=n.joins.find(N=>N.id===w);if(!T)return;const M=[...T.joinKeyGroups];M[g].keys.splice(y,1),o(w,{joinKeyGroups:M})},generateSQLPreview:()=>{const w=[...n.joins].sort((T,M)=>T.sequence-M.sequence),g=n.baseEntity;if(!g.name)return"SELECT * FROM table -- Please select a base entity";let y=`SELECT *
172
167
  FROM ${g.name}`;return w.forEach(T=>{const M=a.find(A=>A.name===T.target.name);if(!M)return;const N=T.joinKeyGroups.filter(A=>A.keys&&A.keys.length>0).map(A=>{const F=A.keys.filter(E=>{var L,S,P,$;return((L=E.source)==null?void 0:L.name)&&((S=E.target)==null?void 0:S.name)&&((P=E.source)==null?void 0:P.entityName)&&(($=E.target)==null?void 0:$.entityName)}).map(E=>`${E.source.entityName}.${E.source.name} ${E.operator} ${E.target.entityName}.${E.target.name}`);return F.length>1?`(${F.join(` ${A.operator} `)})`:F[0]}).filter(Boolean),b=N.length>1?N.join(" OR "):N[0]||"condition_here";y+=`
173
168
  ${T.joinType} JOIN ${M.name}
174
- ON ${b}`}),y},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(T=>!T.source.name||!T.target.name)||n.joins.some(T=>T.joinKeyGroups.some(M=>M.keys.length===0))||n.joins.some(T=>T.joinKeyGroups.some(M=>M.keys.some(N=>!N.source.name||!N.target.name||!N.operator))))}}function Dt({joinPlan:t,availableDataSources:a,onSave:n,onRemove:r,onCancel:l}){const{setCardConfig:d}=s.useEditorActions();s.useEditorStore(N=>N.card.config);const{columnGroups:i}=s.useColumns(),{joinPlan:c,expandedJoins:o,setJoinPlan:u,addJoin:x,removeJoin:h,updateJoin:p,moveJoinUp:k,moveJoinDown:m,toggleJoinExpansion:f,getAvailableSourceEntities:j,getAvailableTargetEntities:C,addJoinKeyGroup:I,updateGroupOperator:O,removeJoinKeyGroup:R,addJoinKey:v,updateJoinKey:w,removeJoinKey:g,generateSQLPreview:y,isValidConfiguration:T}=It({initialJoinPlan:t,availableDataSources:a}),M=N=>{const b=i.find(A=>A.entityName===N);return(b==null?void 0:b.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:c.baseEntity.name,onValueChange:N=>{const b=a.find(A=>A.name===N);u({...c,baseEntity:{connectionId:(b==null?void 0:b.connectionId)||"",connectionType:(b==null?void 0:b.connectionType)||"none",type:(b==null?void 0:b.type)||"table",name:N,database:b==null?void 0:b.database,schema:b==null?void 0:b.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:a.map(N=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:N.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:N.type}),N.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},N.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:y()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{children:["Joins Configuration (",c.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:x,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),c.joins.length===0?e.jsx("div",{className:"rounded-lg border border-dashed py-8 text-center text-muted-foreground",children:e.jsx("p",{children:"No joins configured. Add a join to connect multiple data sources."})}):e.jsx("div",{className:"max-h-[300px] space-y-4 overflow-y-auto",children:c.joins.map(N=>{const b=a.find(E=>E.name===N.source.name),A=a.find(E=>E.name===N.target.name),F=o.has(N.id);return e.jsxs(s.Card,{className:"border",children:[e.jsx(s.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(s.Badge,{children:N.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",N.sequence,b&&A&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",b.name," → ",A.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>k(N.id),disabled:N.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>m(N.id),disabled:N.sequence===c.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>f(N.id),children:F?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>h(N.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),F&&e.jsxs(s.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(s.Label,{children:"Source"}),e.jsxs(s.Select,{value:N.source.name,onValueChange:E=>{const L=a.find(S=>S.name===E);p(N.id,{source:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:E,database:L==null?void 0:L.database,schema:L==null?void 0:L.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:j(N.id).map(E=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:E.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:E.type}),E.name]})},E.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:N.joinType,onValueChange:E=>p(N.id,{joinType:E}),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Target"}),e.jsxs(s.Select,{value:N.target.name,onValueChange:E=>{const L=a.find(S=>S.name===E);p(N.id,{target:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:E,database:L==null?void 0:L.database,schema:L==null?void 0:L.schema}})},disabled:!N.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:N.source.name?C(N.source.name).map(E=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:E.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:E.type}),E.name,E.name===N.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},E.name)):[]})]})]})]}),N.source.name&&N.target.name&&b&&A&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>I(N.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),N.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:N.joinKeyGroups.map((E,L)=>e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{children:["Group ",L+1]}),L>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(s.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(s.Select,{value:E.operator,onValueChange:S=>O(N.id,L,S),children:[e.jsx(s.SelectTrigger,{className:"w-[100px]",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>R(N.id,L),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[E.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:E.keys.map((S,P)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[P>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:E.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:S.source.name,onValueChange:$=>w(N.id,L,P,"sourceColumnName",$),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:M(N.source.name).map($=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:$.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:$.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:$.dataType})]})},$.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:S.operator,onValueChange:$=>w(N.id,L,P,"operator",$),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:S.target.name,onValueChange:$=>w(N.id,L,P,"targetColumnName",$),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:M(N.target.name).map($=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:$.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:$.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:$.dataType})]})},$.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>g(N.id,L,P),children:e.jsx(s.X,{className:"size-3.5"})})]},S.id||P))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>v(N.id,L),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},E.id))})]})]})]},N.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),l()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:l,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>n(c),disabled:!T(),children:"Save"})]})]})}function ws({children:t,open:a,onOpenChange:n,joinPlan:r,availableDataSources:l,onRemove:d,onSave:i,onCancel:c}){return e.jsxs(s.Dialog,{open:a,onOpenChange:n,children:[e.jsxs(s.DialogContent,{className:"max-w-4xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Join Configuration"}),e.jsx(s.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(Dt,{joinPlan:r,availableDataSources:l,onSave:i,onCancel:c,onRemove:d})]}),t]})}function Mt({joins:t,baseEntityId:a,availableDataSources:n,generateSQLPreview:r}){return e.jsxs("div",{className:"max-h-[400px] divide-y divide-border overflow-y-auto",children:[t.length>0&&e.jsxs("div",{className:"p-4",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 l=[...t].sort((i,c)=>i.sequence-c.sequence),d=n.find(i=>i.name===a);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.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}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),l.map(i=>{const c=n.find(o=>o.name===i.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(s.Badge,{variant:"outline",className:"text-xs",children:i.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(s.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})]})]},i.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",t.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...t].sort((l,d)=>l.sequence-d.sequence).map((l,d)=>{const i=n.find(u=>u.name===l.source.name),c=n.find(u=>u.name===l.target.name),o=l.joinKeyGroups.reduce((u,x)=>u+x.keys.length,0);return e.jsxs("div",{className:"rounded-md bg-muted p-2 text-left",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:d+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:l.joinType}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto shrink-0 text-xs",children:[o," condition",o>1?"s":""]})]}),e.jsxs("div",{className:"mt-1 truncate pl-1 text-xs text-muted-foreground",children:[i==null?void 0:i.name," → ",c==null?void 0:c.name]})]},l.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 ns({open:t,onOpenChange:a,variant:n="button"}={}){var I,O;const r=s.useEditorStore(R=>R.card),{autoJoinMetadata:l}=s.useDashboardCardQuery(r),d=s.useEditorStore(R=>R.actions.updateCardConfig),i=((I=r==null?void 0:r.config)==null?void 0:I.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[c,o]=D.useState(!1),u=t!==void 0,x=u?t:c,h=u?a:o,p=((O=r==null?void 0:r.dataSource)==null?void 0:O.selectedEntities)||[],k=R=>{d(r.id,{...r==null?void 0:r.config,joinPlan:R}),h(!1)},m=()=>{d(r.id,{...r==null?void 0:r.config,joinPlan:void 0})},f=()=>{h(!1)},j=()=>{const R=[...i.joins].sort((g,y)=>g.sequence-y.sequence),v=i.baseEntity;if(!v.name)return"SELECT * FROM table -- Please select a base entity";let w=`SELECT *
169
+ ON ${b}`}),y},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(T=>!T.source.name||!T.target.name)||n.joins.some(T=>T.joinKeyGroups.some(M=>M.keys.length===0))||n.joins.some(T=>T.joinKeyGroups.some(M=>M.keys.some(N=>!N.source.name||!N.target.name||!N.operator))))}}function It({joinPlan:t,availableDataSources:a,onSave:n,onRemove:r,onCancel:l}){const{setCardConfig:d}=s.useEditorActions();s.useEditorStore(N=>N.card.config);const{columnGroups:i}=s.useColumns(),{joinPlan:c,expandedJoins:o,setJoinPlan:u,addJoin:x,removeJoin:h,updateJoin:p,moveJoinUp:k,moveJoinDown:m,toggleJoinExpansion:f,getAvailableSourceEntities:j,getAvailableTargetEntities:C,addJoinKeyGroup:I,updateGroupOperator:O,removeJoinKeyGroup:R,addJoinKey:v,updateJoinKey:w,removeJoinKey:g,generateSQLPreview:y,isValidConfiguration:T}=At({initialJoinPlan:t,availableDataSources:a}),M=N=>{const b=i.find(A=>A.entityName===N);return(b==null?void 0:b.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:c.baseEntity.name,onValueChange:N=>{const b=a.find(A=>A.name===N);u({...c,baseEntity:{connectionId:(b==null?void 0:b.connectionId)||"",connectionType:(b==null?void 0:b.connectionType)||"none",type:(b==null?void 0:b.type)||"table",name:N,database:b==null?void 0:b.database,schema:b==null?void 0:b.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:a.map(N=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:N.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:N.type}),N.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},N.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:y()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{children:["Joins Configuration (",c.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:x,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),c.joins.length===0?e.jsx("div",{className:"rounded-lg border border-dashed py-8 text-center text-muted-foreground",children:e.jsx("p",{children:"No joins configured. Add a join to connect multiple data sources."})}):e.jsx("div",{className:"max-h-[300px] space-y-4 overflow-y-auto",children:c.joins.map(N=>{const b=a.find(E=>E.name===N.source.name),A=a.find(E=>E.name===N.target.name),F=o.has(N.id);return e.jsxs(s.Card,{className:"border",children:[e.jsx(s.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(s.Badge,{children:N.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",N.sequence,b&&A&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",b.name," → ",A.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>k(N.id),disabled:N.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>m(N.id),disabled:N.sequence===c.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>f(N.id),children:F?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>h(N.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),F&&e.jsxs(s.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(s.Label,{children:"Source"}),e.jsxs(s.Select,{value:N.source.name,onValueChange:E=>{const L=a.find(S=>S.name===E);p(N.id,{source:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:E,database:L==null?void 0:L.database,schema:L==null?void 0:L.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:j(N.id).map(E=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:E.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:E.type}),E.name]})},E.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:N.joinType,onValueChange:E=>p(N.id,{joinType:E}),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Target"}),e.jsxs(s.Select,{value:N.target.name,onValueChange:E=>{const L=a.find(S=>S.name===E);p(N.id,{target:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:E,database:L==null?void 0:L.database,schema:L==null?void 0:L.schema}})},disabled:!N.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:N.source.name?C(N.source.name).map(E=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:E.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:E.type}),E.name,E.name===N.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},E.name)):[]})]})]})]}),N.source.name&&N.target.name&&b&&A&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>I(N.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),N.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:N.joinKeyGroups.map((E,L)=>e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{children:["Group ",L+1]}),L>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(s.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(s.Select,{value:E.operator,onValueChange:S=>O(N.id,L,S),children:[e.jsx(s.SelectTrigger,{className:"w-[100px]",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>R(N.id,L),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[E.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:E.keys.map((S,P)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[P>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:E.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:S.source.name,onValueChange:$=>w(N.id,L,P,"sourceColumnName",$),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:M(N.source.name).map($=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:$.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:$.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:$.dataType})]})},$.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:S.operator,onValueChange:$=>w(N.id,L,P,"operator",$),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:S.target.name,onValueChange:$=>w(N.id,L,P,"targetColumnName",$),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:M(N.target.name).map($=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:$.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:$.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:$.dataType})]})},$.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>g(N.id,L,P),children:e.jsx(s.X,{className:"size-3.5"})})]},S.id||P))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>v(N.id,L),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},E.id))})]})]})]},N.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),l()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:l,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>n(c),disabled:!T(),children:"Save"})]})]})}function ws({children:t,open:a,onOpenChange:n,joinPlan:r,availableDataSources:l,onRemove:d,onSave:i,onCancel:c}){return e.jsxs(s.Dialog,{open:a,onOpenChange:n,children:[e.jsxs(s.DialogContent,{className:"max-w-4xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Join Configuration"}),e.jsx(s.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(It,{joinPlan:r,availableDataSources:l,onSave:i,onCancel:c,onRemove:d})]}),t]})}function Dt({joins:t,baseEntityId:a,availableDataSources:n,generateSQLPreview:r}){return e.jsxs("div",{className:"max-h-[400px] divide-y divide-border overflow-y-auto",children:[t.length>0&&e.jsxs("div",{className:"p-4",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 l=[...t].sort((i,c)=>i.sequence-c.sequence),d=n.find(i=>i.name===a);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.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}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),l.map(i=>{const c=n.find(o=>o.name===i.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(s.Badge,{variant:"outline",className:"text-xs",children:i.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(s.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})]})]},i.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",t.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...t].sort((l,d)=>l.sequence-d.sequence).map((l,d)=>{const i=n.find(u=>u.name===l.source.name),c=n.find(u=>u.name===l.target.name),o=l.joinKeyGroups.reduce((u,x)=>u+x.keys.length,0);return e.jsxs("div",{className:"rounded-md bg-muted p-2 text-left",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:d+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:l.joinType}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto shrink-0 text-xs",children:[o," condition",o>1?"s":""]})]}),e.jsxs("div",{className:"mt-1 truncate pl-1 text-xs text-muted-foreground",children:[i==null?void 0:i.name," → ",c==null?void 0:c.name]})]},l.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 ns({open:t,onOpenChange:a,variant:n="button"}={}){var I,O;const r=s.useEditorStore(R=>R.card),{autoJoinMetadata:l}=s.useDashboardCardQuery(r),d=s.useEditorStore(R=>R.actions.updateCardConfig),i=((I=r==null?void 0:r.config)==null?void 0:I.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[c,o]=D.useState(!1),u=t!==void 0,x=u?t:c,h=u?a:o,p=((O=r==null?void 0:r.dataSource)==null?void 0:O.selectedEntities)||[],k=R=>{d(r.id,{...r==null?void 0:r.config,joinPlan:R}),h(!1)},m=()=>{d(r.id,{...r==null?void 0:r.config,joinPlan:void 0})},f=()=>{h(!1)},j=()=>{const R=[...i.joins].sort((g,y)=>g.sequence-y.sequence),v=i.baseEntity;if(!v.name)return"SELECT * FROM table -- Please select a base entity";let w=`SELECT *
175
170
  FROM ${v.name}`;return R.forEach(g=>{const y=p.find(N=>N.name===g.target.name);if(!y)return;const T=g.joinKeyGroups.filter(N=>N.keys&&N.keys.length>0).map(N=>{const b=N.keys.filter(A=>{var F,E,L,S;return((F=A.source)==null?void 0:F.name)&&((E=A.target)==null?void 0:E.name)&&((L=A.source)==null?void 0:L.entityName)&&((S=A.target)==null?void 0:S.entityName)}).map(A=>`${A.source.entityName}.${A.source.name} ${A.operator} ${A.target.entityName}.${A.target.name}`);return b.length>1?`(${b.join(` ${N.operator} `)})`:b[0]}).filter(Boolean),M=T.length>1?T.join(" OR "):T[0]||"condition_here";w+=`
176
171
  ${g.joinType} JOIN ${y.name}
177
- ON ${M}`}),w};if(p.length<2)return null;const C=i.joins.length>0&&e.jsx(s.TooltipContent,{side:"bottom",className:"ml-4 max-w-md overflow-hidden p-0",children:e.jsx(Mt,{joins:i.joins,baseEntityId:i.baseEntity.name,availableDataSources:p,generateSQLPreview:j})});return e.jsxs(e.Fragment,{children:[e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:n==="badge"?e.jsxs(s.Badge,{variant:"secondary",className:"h-5 cursor-pointer gap-1 px-1.5 text-xs transition-colors hover:bg-secondary/80",onClick:R=>{R.stopPropagation(),h(!0)},children:[e.jsx(s.Link,{className:"h-3 w-3"}),i.joins.length]}):e.jsxs(s.Button,{onClick:()=>h(!0),variant:"outline",className:"w-full bg-muted/50",children:[e.jsx(s.Link,{className:"mr-2 h-3.5 w-3.5"}),i.joins.length===0?"Configure Joins":i.joins.length===1?"Join":"Joins",i.joins.length>0&&e.jsx("span",{className:"ml-2 flex h-5 min-w-5 items-center justify-center rounded-full bg-primary px-1.5 text-xs font-medium text-primary-foreground",children:i.joins.length}),(l==null?void 0:l.autoResolved)&&e.jsxs(s.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(s.Sparkles,{className:"h-3 w-3"}),"Auto"]})]})}),C]})}),e.jsx(ws,{open:x,onOpenChange:h,joinPlan:i,availableDataSources:p,onSave:k,onCancel:f,onRemove:m,children:e.jsx("div",{})})]})}function Lt({open:t,onOpenChange:a}){const[n,r]=D.useState([]),{updateDataSource:l}=s.useEditorActions(),d=s.useDashboardStore(m=>m.dashboard.aiContext),i=(d==null?void 0:d.selectedEntities)||[];D.useEffect(()=>{t&&r([])},[t]);const c=m=>{r(f=>f.some(C=>C.name===m.name&&C.type===m.type)?f.filter(C=>!(C.name===m.name&&C.type===m.type)):[...f,m])},o=()=>{r([...i])},u=()=>{r([])},x=()=>{if(n.length===0)return;const m=n[0],f=m.connectionId||"",j=m.connectionType||"",I=n.some(R=>R.type==="dataset")?"semanticDomain":"database";l({connectionId:f,connectionType:j,mode:I,selectedEntities:n}),a(!1)},h=m=>"label"in m&&m.label?m.label:m.name,p=m=>{if("description"in m&&m.description)return m.description;const f=[];return m.database&&f.push(m.database),m.schema&&f.push(m.schema),m.name&&f.push(m.name),f.join(".")},k=m=>n.some(f=>f.name===m.name&&f.type===m.type);return i.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"max-w-md",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"No Data Available"}),e.jsx(s.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{onClick:()=>a(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(s.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(s.Button,{variant:"outline",size:"sm",onClick:o,disabled:n.length===i.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:u,disabled:n.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[n.length," of ",i.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:i.map((m,f)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",k(m)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:k(m),onCheckedChange:()=>c(m)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:s.getEntityIcon(m.type)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:h(m)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:p(m)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:m.type})]},`${m.type}-${m.name}-${f}`))})})]}),e.jsx(s.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(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:x,disabled:n.length===0,children:["Select"," ",n.length>0?`(${n.length})`:""]})]})})})]})})}function as({entities:t,title:a}){const{isConsoleMode:n}=s.useDashboardPreferences();return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:a??`${t.length} more entities`}),e.jsx("div",{className:"space-y-1",children:t.map((r,l)=>{const d=s.getEntityDetails(r),i=d.find(o=>o.label==="Description"&&o.value),c=d.filter(o=>o.label==="Description"?!1:n?!0:!["Connection","Database","Schema"].includes(o.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(r)}),i&&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:i.value})]}),c.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:c.map((o,u)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[o.label,":"]}),e.jsx("span",{className:"font-mono",children:o.value})]},u))})]},`remaining-${r.type}-${r.name}-${l}`)})})]})})}function ks(t,a){const[n,r]=D.useState(()=>{const l=localStorage.getItem(t);return l?JSON.parse(l):a});return D.useEffect(()=>{localStorage.setItem(t,JSON.stringify(n))},[n,t]),[n,r]}function Ts({isVisible:t}){var f,j;const a=s.useEditorStore(C=>C.isDevMode);s.useSyncLegacyEditorState();const[n,r]=D.useState(!1),[l,d]=D.useState(!1),[i,c]=ks("semaphor:data-source-collapsed",!1),o=s.useEditorStore(C=>C.card.dataSource),u=s.useEditorStore(C=>{var I,O;return(O=(I=C.card)==null?void 0:I.config)==null?void 0:O.joinPlan}),{updateDataSource:x}=s.useEditorActions(),h=((f=o==null?void 0:o.selectedEntities)==null?void 0:f.length)||0,p=((j=u==null?void 0:u.joins)==null?void 0:j.length)||0,m={...{connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},...o,selectedEntities:(o==null?void 0:o.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[h===0&&p===0?e.jsx("div",{className:"p-4 px-6",children:e.jsxs(s.Button,{className:"w-full bg-muted/50",variant:"outline",onClick:()=>r(!0),children:[e.jsx(s.Database,{className:"mr-2 h-3.5 w-3.5"}),"Choose Dataset"]})}):e.jsxs("div",{children:[e.jsxs("div",{className:s.cn("flex cursor-pointer items-center justify-between px-6 pt-3",!i&&"pb-3"),onClick:()=>c(!i),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:"Data Source"}),i&&e.jsxs("div",{className:"flex items-center gap-1.5",onClick:C=>C.stopPropagation(),children:[h>0&&e.jsx(s.TooltipProvider,{delayDuration:100,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.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(s.Database,{className:"h-3 w-3"}),h]})}),e.jsx(as,{entities:m.selectedEntities,title:`${h} selected ${h===1?"entity":"entities"}`})]})}),p>0&&!a&&e.jsx(ns,{variant:"badge"})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:C=>{C.stopPropagation(),c(!i)},children:i?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronUp,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:s.cn("overflow-hidden transition-all duration-200 ease-in-out",i?"max-h-0 opacity-0":"max-h-96 opacity-100"),children:[e.jsx("div",{className:"px-6 pb-2",children:e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{className:"w-full bg-muted/50",variant:"outline",onClick:()=>r(!0),children:[e.jsx(s.Database,{className:"mr-2 h-3.5 w-3.5"}),h===1?"Dataset":"Datasets",e.jsx("span",{className:"ml-2 flex h-5 min-w-5 items-center justify-center rounded-full bg-primary px-1.5 text-xs font-medium text-primary-foreground",children:h})]})}),e.jsx(as,{entities:m.selectedEntities,title:`${h} selected ${h===1?"entity":"entities"}`})]})})}),!a&&e.jsx("div",{className:"px-6 pb-2",children:e.jsx(ns,{})})]})]}),e.jsx(s.FieldsSection,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(o==null?void 0:o.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:r,dataSource:m}),e.jsx(Lt,{open:l,onOpenChange:d})]})}function He({error:t,errorSql:a,onSendFeedback:n,onOpenInEditor:r,className:l,showFeedbackButton:d=!0,errorTitle:i="Query Error"}){const[c,o]=D.useState(!1);return e.jsx("div",{className:s.cn("rounded-lg border border-destructive/30 bg-destructive/5 p-4",l),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(s.CircleAlert,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-destructive"}),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-destructive",children:i}),e.jsxs("div",{className:"relative rounded-md bg-background/60 p-3",children:[e.jsx(s.CopyButton,{text:t,className:"absolute right-2 top-2 h-6 w-6 z-10"}),e.jsx("div",{className:"max-h-40 overflow-auto pr-10",children:e.jsx("p",{className:"font-mono text-xs text-foreground/80 break-all",children:t})})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a&&e.jsx(s.Collapsible,{open:c,onOpenChange:o,children:e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",children:c?e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronUp,{className:"mr-1.5 h-3.5 w-3.5"}),"Hide Details"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronDown,{className:"mr-1.5 h-3.5 w-3.5"}),"Show Details"]})})})}),r&&a&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:r,children:[e.jsx(Cs,{className:"mr-1.5 h-3.5 w-3.5"}),"Open in Editor"]}),d&&n&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:n,children:[e.jsx(s.MessageSquareWarning,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]})]}),a&&e.jsx(s.Collapsible,{open:c,onOpenChange:o,children:e.jsx(s.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:"Error SQL Query"}),e.jsx(s.CopyButton,{text:a,className:"h-6 w-6"})]}),e.jsx("div",{className:"rounded-md bg-background/60 p-2 max-h-80 overflow-auto",children:e.jsx(s.CodeHighlighter,{code:a,language:"sql"})})]})})})]})]})})}function Es({sql:t,error:a,errorSql:n,onDebugWithAssistant:r}){const l=s.useEditorStore(f=>f.isDevMode),{setIsDevMode:d,setCardSql:i,setRunSql:c}=s.useEditorActions(),[o,u]=D.useState(!1),x=s.useEditorStore(f=>f.card),h=s.useEditorStore(f=>f.frame),p=s.useDashboardStore(f=>f.selectedSheetId),k=s.useDashboardStore(f=>{var j;return(j=f.dashboard)==null?void 0:j.id});function m(f){d(!0),i(f||t),setTimeout(()=>{c(!0)},100)}return e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col pt-4",children:[!l&&t&&!a&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsxs(s.Button,{onClick:()=>m(),variant:"secondary",size:"sm",children:[e.jsx(Cs,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),e.jsxs(s.Button,{onClick:()=>u(!o),variant:"outline",size:"sm",children:[e.jsx(s.Info,{className:"mr-2 h-4 w-4"}),"Card Details"]})]}),o&&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(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>u(!1),children:e.jsx(ys,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Card ID"}),e.jsx("code",{className:"text-xs font-mono",children:x.id||"N/A"})]}),e.jsx(s.CopyButton,{text:x.id||"",className:"h-6 w-6"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Frame ID"}),e.jsx("code",{className:"text-xs font-mono",children:h.id||"N/A"})]}),e.jsx(s.CopyButton,{text:h.id||"",className:"h-6 w-6"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Sheet ID"}),e.jsx("code",{className:"text-xs font-mono",children:p||"N/A"})]}),e.jsx(s.CopyButton,{text:p||"",className:"h-6 w-6"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Dashboard ID"}),e.jsx("code",{className:"text-xs font-mono",children:k||"N/A"})]}),e.jsx(s.CopyButton,{text:k||"",className:"h-6 w-6"})]})]})]})}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-auto text-xs leading-relaxed text-foreground/80",children:[a&&e.jsx(He,{error:a,errorSql:n,showFeedbackButton:!1,onOpenInEditor:()=>m(n)}),!a&&t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute right-2 top-2 z-10",children:e.jsx(s.CopyButton,{text:t,className:"h-6 w-6"})}),e.jsx(s.CodeHighlighter,{code:t,language:"sql"})]})})]}),a&&r&&e.jsx("div",{className:"mt-3",children:e.jsxs(s.Button,{onClick:r,size:"sm",variant:"outline",children:[e.jsx(ht,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})})]})}function Ft({sql:t,error:a,errorSql:n,onDebugWithAssistant:r}){return e.jsxs(s.HoverCard,{openDelay:a?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:a?e.jsx(ys,{className:"h-4 w-4 text-red-500"}):e.jsx(s.Info,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(s.HoverCardContent,{align:"start",className:"flex w-[700px]",children:e.jsx(Es,{errorSql:n,sql:t,error:a,onDebugWithAssistant:r})})]})}function Ot(t){return s.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:[]}]})(t)}function As(t){const{theme:a}=s.useTheme(),n=s.useDashboardStore(f=>f.theme),r=s.useEditorStore(f=>f.frame),l=s.useEditorStore(f=>f.card),d=s.useEditorStore(f=>f.activeTabCardId),i=s.Le(),{refetch:c}=s.useDashboardCardQuery(l),{updateCardTab:o,setRunSql:u}=s.useEditorActions(),x=D.useRef(void 0),h=D.useRef({}),p=r.cards.find(f=>f.id===d),k=D.useCallback(()=>{let f="";return t==="python"&&(f=(p==null?void 0:p.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(f=(p==null?void 0:p.sql)||""),f},[t,p]);D.useEffect(()=>{if(d&&l.id&&l.id!==d){if(x.current&&i){const f=x.current.getModel();f&&(h.current[l.id]=f);let j=h.current[d];if(!j){const C=k();j=i.editor.createModel(C,t),h.current[d]=j}x.current.setModel(j)}o(d,l),u(!0)}},[d,l,o,i,u,t,k]),D.useEffect(()=>{if(!i)return;const f=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",j=n==="system"?f:n;i.editor.defineTheme("default",{base:j==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":j==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),i.editor.setTheme("default")},[a,n,i]),D.useEffect(()=>{const f=x.current;f&&i&&l&&f.addCommand(i.KeyMod.Shift|i.KeyCode.Enter,function(){return c(),!1})},[i,c,l]);function m(f,j){if(x.current=f,!h.current[l.id]){const C=f.getModel(),I=k();h.current[l.id]=C||(j==null?void 0:j.editor.createModel(I,t))||f.getModel()}f.setModel(h.current[l.id])}return{handleEditorDidMount:m}}function Rt(){const t=s.useEditorStore(i=>i.card.sql),a=s.useEditorStore(i=>i.sqlGen),{setCardSql:n,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=As("sql");function d(i){n(i),s.isObjectEmpty(a)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:d,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function Bt(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:a}=s.useEditorActions(),{handleEditorDidMount:n}=As("python");function r(l){a(l)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:n})}function Vt(){const t=s.useQueryClient(),{isConsoleMode:a}=s.useDashboardPreferences(),[n,r]=D.useState(!1);s.useEditorStore(B=>B.frame);const l=s.useEditorStore(B=>B.card);s.useEditorStore(B=>B.isShowingVisual),s.useEditorStore(B=>B.selectedConnectionId),s.useEditorStore(B=>B.tempQueryData),s.useEditorStore(B=>B.selectedDatabaseName),s.useEditorStore(B=>B.selectedDatamodelId),s.useEditorStore(B=>B.selectedSchemaName);const d=s.useEditorStore(B=>B.showAIDialog);s.useEditorStore(B=>B.selectedTableName);const i=s.useEditorStore(B=>{var U;return(U=B==null?void 0:B.card)==null?void 0:U.sql}),c=s.useEditorStore(B=>{var U;return(U=B==null?void 0:B.card)==null?void 0:U.python}),{cardFilterValues:o}=s.useCardFilterValues((l==null?void 0:l.id)??""),u=s.useDashboardStore(B=>B.inlineFilterValuesMap[(l==null?void 0:l.id)??""]),x=D.useRef(!0),{setCardCustomCfg:h,setQueryResultColumns:p,setCardSql:k,setTempQueryData:m,setPythonStdOut:f,setCardPreferences:j,setCardType:C,setCardPython:I,runAssistant:O,setShowAIDialog:R,setCard:v,updateCardInFrame:w}=s.useEditorActions();s.useEditorStore(B=>B.onSave),s.useEditorStore(B=>B.onClose),s.useEditorStore(B=>B.actions.setSqlGen);const g=s.useEditorStore(B=>B.runSql),y=s.useEditorStore(B=>B.actions.setRunSql),T=s.useEditorStore(B=>B.actions.setIsSqlRunning),{data:M,isLoading:N,isFetching:b,isSuccess:A,isError:F,error:E,errorSql:L,queryKey:S,refetch:P,errorMessage:$}=s.useDashboardCardQuery(l);D.useEffect(()=>{if(M&&(M.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),f((M==null?void 0:M.output)||""),M.records.length>0)){const{dimensionKeys:B}=s.getKeys(M.records);p(B)}},[M,p,f]),D.useEffect(()=>{(N||b)&&T(!0),(F||A)&&T(!1),F&&(p([]),f(""))},[N,b,M,f,F,A,T,p,E]),D.useEffect(()=>{g&&(t.getQueryData(S)||P(),y(!1))},[g,P,y,S,t]);const J=D.useRef(P);J.current=P,D.useEffect(()=>{if(x.current){x.current=!1;return}J.current()},[u]);async function K(){const B=`Can you help me debug this query?
172
+ ON ${M}`}),w};if(p.length<2)return null;const C=i.joins.length>0&&e.jsx(s.TooltipContent,{side:"bottom",className:"ml-4 max-w-md overflow-hidden p-0",children:e.jsx(Dt,{joins:i.joins,baseEntityId:i.baseEntity.name,availableDataSources:p,generateSQLPreview:j})});return e.jsxs(e.Fragment,{children:[e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:n==="badge"?e.jsxs(s.Badge,{variant:"secondary",className:"h-5 cursor-pointer gap-1 px-1.5 text-xs transition-colors hover:bg-secondary/80",onClick:R=>{R.stopPropagation(),h(!0)},children:[e.jsx(s.Link,{className:"h-3 w-3"}),i.joins.length]}):e.jsxs(s.Button,{onClick:()=>h(!0),variant:"outline",className:"w-full bg-muted/50",children:[e.jsx(s.Link,{className:"mr-2 h-3.5 w-3.5"}),i.joins.length===0?"Configure Joins":i.joins.length===1?"Join":"Joins",i.joins.length>0&&e.jsx("span",{className:"ml-2 flex h-5 min-w-5 items-center justify-center rounded-full bg-primary px-1.5 text-xs font-medium text-primary-foreground",children:i.joins.length}),(l==null?void 0:l.autoResolved)&&e.jsxs(s.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(s.Sparkles,{className:"h-3 w-3"}),"Auto"]})]})}),C]})}),e.jsx(ws,{open:x,onOpenChange:h,joinPlan:i,availableDataSources:p,onSave:k,onCancel:f,onRemove:m,children:e.jsx("div",{})})]})}function Mt({open:t,onOpenChange:a}){const[n,r]=D.useState([]),{updateDataSource:l}=s.useEditorActions(),d=s.useDashboardStore(m=>m.dashboard.aiContext),i=(d==null?void 0:d.selectedEntities)||[];D.useEffect(()=>{t&&r([])},[t]);const c=m=>{r(f=>f.some(C=>C.name===m.name&&C.type===m.type)?f.filter(C=>!(C.name===m.name&&C.type===m.type)):[...f,m])},o=()=>{r([...i])},u=()=>{r([])},x=()=>{if(n.length===0)return;const m=n[0],f=m.connectionId||"",j=m.connectionType||"",I=n.some(R=>R.type==="dataset")?"semanticDomain":"database";l({connectionId:f,connectionType:j,mode:I,selectedEntities:n}),a(!1)},h=m=>"label"in m&&m.label?m.label:m.name,p=m=>{if("description"in m&&m.description)return m.description;const f=[];return m.database&&f.push(m.database),m.schema&&f.push(m.schema),m.name&&f.push(m.name),f.join(".")},k=m=>n.some(f=>f.name===m.name&&f.type===m.type);return i.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"max-w-md",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"No Data Available"}),e.jsx(s.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{onClick:()=>a(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(s.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(s.Button,{variant:"outline",size:"sm",onClick:o,disabled:n.length===i.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:u,disabled:n.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[n.length," of ",i.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:i.map((m,f)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",k(m)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:k(m),onCheckedChange:()=>c(m)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:s.getEntityIcon(m.type)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:h(m)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:p(m)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:m.type})]},`${m.type}-${m.name}-${f}`))})})]}),e.jsx(s.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(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:x,disabled:n.length===0,children:["Select"," ",n.length>0?`(${n.length})`:""]})]})})})]})})}function as({entities:t,title:a}){const{isConsoleMode:n}=s.useDashboardPreferences();return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:a??`${t.length} more entities`}),e.jsx("div",{className:"space-y-1",children:t.map((r,l)=>{const d=s.getEntityDetails(r),i=d.find(o=>o.label==="Description"&&o.value),c=d.filter(o=>o.label==="Description"?!1:n?!0:!["Connection","Database","Schema"].includes(o.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(r)}),i&&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:i.value})]}),c.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:c.map((o,u)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[o.label,":"]}),e.jsx("span",{className:"font-mono",children:o.value})]},u))})]},`remaining-${r.type}-${r.name}-${l}`)})})]})})}function ks(t,a){const[n,r]=D.useState(()=>{const l=localStorage.getItem(t);return l?JSON.parse(l):a});return D.useEffect(()=>{localStorage.setItem(t,JSON.stringify(n))},[n,t]),[n,r]}function Ts({isVisible:t}){var f,j;const a=s.useEditorStore(C=>C.isDevMode);s.useSyncLegacyEditorState();const[n,r]=D.useState(!1),[l,d]=D.useState(!1),[i,c]=ks("semaphor:data-source-collapsed",!1),o=s.useEditorStore(C=>C.card.dataSource),u=s.useEditorStore(C=>{var I,O;return(O=(I=C.card)==null?void 0:I.config)==null?void 0:O.joinPlan}),{updateDataSource:x}=s.useEditorActions(),h=((f=o==null?void 0:o.selectedEntities)==null?void 0:f.length)||0,p=((j=u==null?void 0:u.joins)==null?void 0:j.length)||0,m={...{connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},...o,selectedEntities:(o==null?void 0:o.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[h===0&&p===0?e.jsx("div",{className:"p-4 px-6",children:e.jsxs(s.Button,{className:"w-full bg-muted/50",variant:"outline",onClick:()=>r(!0),children:[e.jsx(s.Database,{className:"mr-2 h-3.5 w-3.5"}),"Choose Dataset"]})}):e.jsxs("div",{children:[e.jsxs("div",{className:s.cn("flex cursor-pointer items-center justify-between px-6 pt-3",!i&&"pb-3"),onClick:()=>c(!i),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:"Data Source"}),i&&e.jsxs("div",{className:"flex items-center gap-1.5",onClick:C=>C.stopPropagation(),children:[h>0&&e.jsx(s.TooltipProvider,{delayDuration:100,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.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(s.Database,{className:"h-3 w-3"}),h]})}),e.jsx(as,{entities:m.selectedEntities,title:`${h} selected ${h===1?"entity":"entities"}`})]})}),p>0&&!a&&e.jsx(ns,{variant:"badge"})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:C=>{C.stopPropagation(),c(!i)},children:i?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronUp,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:s.cn("overflow-hidden transition-all duration-200 ease-in-out",i?"max-h-0 opacity-0":"max-h-96 opacity-100"),children:[e.jsx("div",{className:"px-6 pb-2",children:e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{className:"w-full bg-muted/50",variant:"outline",onClick:()=>r(!0),children:[e.jsx(s.Database,{className:"mr-2 h-3.5 w-3.5"}),h===1?"Dataset":"Datasets",e.jsx("span",{className:"ml-2 flex h-5 min-w-5 items-center justify-center rounded-full bg-primary px-1.5 text-xs font-medium text-primary-foreground",children:h})]})}),e.jsx(as,{entities:m.selectedEntities,title:`${h} selected ${h===1?"entity":"entities"}`})]})})}),!a&&e.jsx("div",{className:"px-6 pb-2",children:e.jsx(ns,{})})]})]}),e.jsx(s.FieldsSection,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(o==null?void 0:o.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:r,dataSource:m}),e.jsx(Mt,{open:l,onOpenChange:d})]})}function He({error:t,errorSql:a,onSendFeedback:n,onOpenInEditor:r,className:l,showFeedbackButton:d=!0,errorTitle:i="Query Error"}){const[c,o]=D.useState(!1);return e.jsx("div",{className:s.cn("rounded-lg border border-destructive/30 bg-destructive/5 p-4",l),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(s.CircleAlert,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-destructive"}),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-destructive",children:i}),e.jsxs("div",{className:"relative rounded-md bg-background/60 p-3",children:[e.jsx(s.CopyButton,{text:t,className:"absolute right-2 top-2 h-6 w-6 z-10"}),e.jsx("div",{className:"max-h-40 overflow-auto pr-10",children:e.jsx("p",{className:"font-mono text-xs text-foreground/80 break-all",children:t})})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a&&e.jsx(s.Collapsible,{open:c,onOpenChange:o,children:e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",children:c?e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronUp,{className:"mr-1.5 h-3.5 w-3.5"}),"Hide Details"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronDown,{className:"mr-1.5 h-3.5 w-3.5"}),"Show Details"]})})})}),r&&a&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:r,children:[e.jsx(Cs,{className:"mr-1.5 h-3.5 w-3.5"}),"Open in Editor"]}),d&&n&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:n,children:[e.jsx(s.MessageSquareWarning,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]})]}),a&&e.jsx(s.Collapsible,{open:c,onOpenChange:o,children:e.jsx(s.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:"Error SQL Query"}),e.jsx(s.CopyButton,{text:a,className:"h-6 w-6"})]}),e.jsx("div",{className:"rounded-md bg-background/60 p-2 max-h-80 overflow-auto",children:e.jsx(s.CodeHighlighter,{code:a,language:"sql"})})]})})})]})]})})}function Es({sql:t,error:a,errorSql:n,onDebugWithAssistant:r}){const l=s.useEditorStore(f=>f.isDevMode),{setIsDevMode:d,setCardSql:i,setRunSql:c}=s.useEditorActions(),[o,u]=D.useState(!1),x=s.useEditorStore(f=>f.card),h=s.useEditorStore(f=>f.frame),p=s.useDashboardStore(f=>f.selectedSheetId),k=s.useDashboardStore(f=>{var j;return(j=f.dashboard)==null?void 0:j.id});function m(f){d(!0),i(f||t),setTimeout(()=>{c(!0)},100)}return e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col pt-4",children:[!l&&t&&!a&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsxs(s.Button,{onClick:()=>m(),variant:"secondary",size:"sm",children:[e.jsx(Cs,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),e.jsxs(s.Button,{onClick:()=>u(!o),variant:"outline",size:"sm",children:[e.jsx(s.Info,{className:"mr-2 h-4 w-4"}),"Card Details"]})]}),o&&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(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>u(!1),children:e.jsx(ys,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Card ID"}),e.jsx("code",{className:"text-xs font-mono",children:x.id||"N/A"})]}),e.jsx(s.CopyButton,{text:x.id||"",className:"h-6 w-6"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Frame ID"}),e.jsx("code",{className:"text-xs font-mono",children:h.id||"N/A"})]}),e.jsx(s.CopyButton,{text:h.id||"",className:"h-6 w-6"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Sheet ID"}),e.jsx("code",{className:"text-xs font-mono",children:p||"N/A"})]}),e.jsx(s.CopyButton,{text:p||"",className:"h-6 w-6"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Dashboard ID"}),e.jsx("code",{className:"text-xs font-mono",children:k||"N/A"})]}),e.jsx(s.CopyButton,{text:k||"",className:"h-6 w-6"})]})]})]})}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-auto text-xs leading-relaxed text-foreground/80",children:[a&&e.jsx(He,{error:a,errorSql:n,showFeedbackButton:!1,onOpenInEditor:()=>m(n)}),!a&&t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute right-2 top-2 z-10",children:e.jsx(s.CopyButton,{text:t,className:"h-6 w-6"})}),e.jsx(s.CodeHighlighter,{code:t,language:"sql"})]})})]}),a&&r&&e.jsx("div",{className:"mt-3",children:e.jsxs(s.Button,{onClick:r,size:"sm",variant:"outline",children:[e.jsx(xt,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})})]})}function Lt({sql:t,error:a,errorSql:n,onDebugWithAssistant:r}){return e.jsxs(s.HoverCard,{openDelay:a?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:a?e.jsx(ys,{className:"h-4 w-4 text-red-500"}):e.jsx(s.Info,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(s.HoverCardContent,{align:"start",className:"flex w-[700px]",children:e.jsx(Es,{errorSql:n,sql:t,error:a,onDebugWithAssistant:r})})]})}function Ft(t){return s.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:[]}]})(t)}function As(t){const{theme:a}=s.useTheme(),n=s.useDashboardStore(f=>f.theme),r=s.useEditorStore(f=>f.frame),l=s.useEditorStore(f=>f.card),d=s.useEditorStore(f=>f.activeTabCardId),i=s.Le(),{refetch:c}=s.useDashboardCardQuery(l),{updateCardTab:o,setRunSql:u}=s.useEditorActions(),x=D.useRef(void 0),h=D.useRef({}),p=r.cards.find(f=>f.id===d),k=D.useCallback(()=>{let f="";return t==="python"&&(f=(p==null?void 0:p.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(f=(p==null?void 0:p.sql)||""),f},[t,p]);D.useEffect(()=>{if(d&&l.id&&l.id!==d){if(x.current&&i){const f=x.current.getModel();f&&(h.current[l.id]=f);let j=h.current[d];if(!j){const C=k();j=i.editor.createModel(C,t),h.current[d]=j}x.current.setModel(j)}o(d,l),u(!0)}},[d,l,o,i,u,t,k]),D.useEffect(()=>{if(!i)return;const f=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",j=n==="system"?f:n;i.editor.defineTheme("default",{base:j==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":j==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),i.editor.setTheme("default")},[a,n,i]),D.useEffect(()=>{const f=x.current;f&&i&&l&&f.addCommand(i.KeyMod.Shift|i.KeyCode.Enter,function(){return c(),!1})},[i,c,l]);function m(f,j){if(x.current=f,!h.current[l.id]){const C=f.getModel(),I=k();h.current[l.id]=C||(j==null?void 0:j.editor.createModel(I,t))||f.getModel()}f.setModel(h.current[l.id])}return{handleEditorDidMount:m}}function Ot(){const t=s.useEditorStore(i=>i.card.sql),a=s.useEditorStore(i=>i.sqlGen),{setCardSql:n,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=As("sql");function d(i){n(i),s.isObjectEmpty(a)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:d,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function Rt(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:a}=s.useEditorActions(),{handleEditorDidMount:n}=As("python");function r(l){a(l)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:n})}function Bt(){const t=s.useQueryClient(),{isConsoleMode:a}=s.useDashboardPreferences(),[n,r]=D.useState(!1);s.useEditorStore(B=>B.frame);const l=s.useEditorStore(B=>B.card);s.useEditorStore(B=>B.isShowingVisual),s.useEditorStore(B=>B.selectedConnectionId),s.useEditorStore(B=>B.tempQueryData),s.useEditorStore(B=>B.selectedDatabaseName),s.useEditorStore(B=>B.selectedDatamodelId),s.useEditorStore(B=>B.selectedSchemaName);const d=s.useEditorStore(B=>B.showAIDialog);s.useEditorStore(B=>B.selectedTableName);const i=s.useEditorStore(B=>{var U;return(U=B==null?void 0:B.card)==null?void 0:U.sql}),c=s.useEditorStore(B=>{var U;return(U=B==null?void 0:B.card)==null?void 0:U.python}),{cardFilterValues:o}=s.useCardFilterValues((l==null?void 0:l.id)??""),u=s.useDashboardStore(B=>B.inlineFilterValuesMap[(l==null?void 0:l.id)??""]),x=D.useRef(!0),{setCardCustomCfg:h,setQueryResultColumns:p,setCardSql:k,setTempQueryData:m,setPythonStdOut:f,setCardPreferences:j,setCardType:C,setCardPython:I,runAssistant:O,setShowAIDialog:R,setCard:v,updateCardInFrame:w}=s.useEditorActions();s.useEditorStore(B=>B.onSave),s.useEditorStore(B=>B.onClose),s.useEditorStore(B=>B.actions.setSqlGen);const g=s.useEditorStore(B=>B.runSql),y=s.useEditorStore(B=>B.actions.setRunSql),T=s.useEditorStore(B=>B.actions.setIsSqlRunning),{data:M,isLoading:N,isFetching:b,isSuccess:A,isError:F,error:E,errorSql:L,queryKey:S,refetch:P,errorMessage:$}=s.useDashboardCardQuery(l);D.useEffect(()=>{if(M&&(M.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),f((M==null?void 0:M.output)||""),M.records.length>0)){const{dimensionKeys:B}=s.getKeys(M.records);p(B)}},[M,p,f]),D.useEffect(()=>{(N||b)&&T(!0),(F||A)&&T(!1),F&&(p([]),f(""))},[N,b,M,f,F,A,T,p,E]),D.useEffect(()=>{g&&(t.getQueryData(S)||P(),y(!1))},[g,P,y,S,t]);const J=D.useRef(P);J.current=P,D.useEffect(()=>{if(x.current){x.current=!1;return}J.current()},[u]);async function K(){const B=`Can you help me debug this query?
178
173
 
179
174
  Error:
180
175
 
@@ -190,6 +185,6 @@ ${g.joinType} JOIN ${y.name}
190
185
 
191
186
  ${c?`Python:
192
187
  ${c}`:""}
193
- `;O(B)}function G(){return e.jsxs(s.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(s.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(Rt,{})}),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(s.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(s.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(Bt,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function H(){var B,U,V,W,X,se;return e.jsx("div",{role:"editor-controls",className:"item-center flex flex-wrap justify-between gap-2 px-6 py-4",children:e.jsxs("div",{className:"flex grow items-center gap-4",children:[e.jsxs(s.Button,{title:"Shift + Enter",disabled:N||b,onClick:()=>{P()},className:"h-8 shrink-0",size:"sm",children:[N||b?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(s.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),e.jsx(Ft,{errorSql:L,sql:M==null?void 0:M.sql,error:$,onDebugWithAssistant:K}),e.jsx(qe.EditorClearButton,{}),e.jsxs(s.Toggle,{pressed:n,onPressedChange:_=>r(_),className:"h-8",size:"sm",variant:"outline",children:[e.jsx(Ot,{className:"mr-2 size-4 text-foreground/70"}),"Python"]}),!d&&e.jsxs("button",{disabled:d,onClick:()=>{R(!0)},className:"flex h-8 w-full cursor-text items-center justify-start rounded-md bg-muted/50 px-3 text-left text-sm text-muted-foreground",children:[e.jsx(s.Sparkles,{className:"mr-3 size-4 text-foreground/70"}),"Type your question..."]}),e.jsxs("div",{className:"flex flex-1 items-center justify-end gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((U=(B=l.preferences)==null?void 0:B.tablePrefs)==null?void 0:U.enableDevModePagination)??!1,onCheckedChange:_=>{var te;j({...l.preferences,tablePrefs:{...(te=l.preferences)==null?void 0:te.tablePrefs,enableDevModePagination:_}})}}),e.jsx(s.Label,{htmlFor:"pagination",className:"cursor-pointer text-sm",children:"Paginate"}),((W=(V=l.preferences)==null?void 0:V.tablePrefs)==null?void 0:W.enableDevModePagination)&&e.jsxs(s.Select,{value:String(((se=(X=l.preferences)==null?void 0:X.tablePrefs)==null?void 0:se.pageSize)||50),onValueChange:_=>{var le,ce,z;const te=Number(_),Y={...l,preferences:{...l.preferences,tablePrefs:{...(le=l.preferences)==null?void 0:le.tablePrefs,pageSize:te}},paginationConfig:{page:1,pageSize:te}};v(Y),w(Y),l.sql&&((z=(ce=l.preferences)==null?void 0:ce.tablePrefs)!=null&&z.enableDevModePagination)&&y(!0)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"10",children:"10"}),e.jsx(s.SelectItem,{value:"25",children:"25"}),e.jsx(s.SelectItem,{value:"50",children:"50"}),e.jsx(s.SelectItem,{value:"100",children:"100"}),e.jsx(s.SelectItem,{value:"500",children:"500"}),e.jsx(s.SelectItem,{value:"1000",children:"1000"})]})]})]}),o&&o.length>0&&e.jsxs(s.HoverCard,{openDelay:200,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",className:"h-8 gap-2 px-2",children:[e.jsx(s.Filter,{className:"size-4"}),e.jsx(s.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:o.length})]})}),e.jsx(s.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(s.CodeHighlighter,{code:JSON.stringify(o,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:G()}),H()]})}const Pt=[{value:"table",label:"Table",icon:s.Table2},{value:"aggregateTable",label:"Aggregate",icon:s.Layers},{value:"pivotTable",label:"Pivot",icon:s.Grid3x3}];function zt({className:t}){const a=s.useEditorStore(o=>o.card),{setCardType:n,setCard:r,updateCardInFrame:l}=s.useEditorActions(),d=["table","aggregateTable","pivotTable"].includes(a.type),i=s.hasValidCardConfig(a.config);if(!d||!i)return null;const c=o=>{var x;const u=o;if(u==="aggregateTable"&&((x=a.config)!=null&&x.pivotByColumns)&&a.config.pivotByColumns.length>0){const h={...a,type:u,config:{...a.config,pivotByColumns:[]}};r(h),l(h)}else{n(u);const h={...a,type:u};l(h)}};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsx(s.RadioGroup,{value:a.type,onValueChange:c,className:"flex flex-row items-center justify-between gap-1 rounded-lg border p-1",children:Pt.map(o=>{const u=o.icon,x=a.type===o.value;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(s.RadioGroupItem,{value:o.value,id:`table-type-${o.value}`,className:"peer sr-only"}),e.jsxs(s.Label,{htmlFor:`table-type-${o.value}`,className:s.cn("flex cursor-pointer items-center gap-1.5 rounded-md px-3 py-1 text-sm font-medium transition-all",x?"bg-muted text-foreground shadow-sm":"text-muted-foreground hover:bg-muted/50"),children:[e.jsx(u,{className:"h-3.5 w-3.5"}),o.label]})]},o.value)})})})}function $t({type:t,isLinked:a,className:n}){const r=s.useDashboardStore(p=>p.selectedFrameId),l=s.useManagementStore(p=>p.selectedVisual),d=s.useEditorStore(p=>p.frame);let i;if(t)i=t;else if(a!==void 0)i=a?"linked":"library";else if(!!!(d!=null&&d.visualId||l!=null&&l.id)&&r)i="local";else if(l&&!r)i="library";else if(d!=null&&d.visualId&&r)i="linked";else if(l!=null&&l.id&&r)i="library";else return null;if(i==="local")return null;const c={linked:"border-purple-200/70 bg-gradient-to-r from-purple-50/50 to-purple-100/30 text-purple-900 shadow-sm hover:from-purple-100/60 hover:to-purple-100/50 hover:shadow-md dark:border-purple-800/50 dark:from-purple-950/40 dark:to-purple-900/30 dark:text-purple-100 dark:hover:from-purple-950/60 dark:hover:to-purple-900/50",library:"border-blue-200/70 bg-gradient-to-r from-blue-50/50 to-blue-100/30 text-blue-900 shadow-sm hover:from-blue-100/60 hover:to-blue-100/50 hover:shadow-md dark:border-blue-800/50 dark:from-blue-950/40 dark:to-blue-900/30 dark:text-blue-100 dark:hover:from-blue-950/60 dark:hover:to-blue-900/50"},o={linked:"Linked to library: Changes made here update the library visual and all linked instances.",library:"Library visual: Share and reuse this visual across multiple dashboards."},u={linked:"border-purple-200 bg-purple-50 text-purple-900 dark:border-purple-800 dark:bg-purple-950 dark:text-purple-100",library:"border-blue-200 bg-blue-50 text-blue-900 dark:border-blue-800 dark:bg-blue-950 dark:text-blue-100"},x={linked:"fill-purple-50 dark:fill-purple-950",library:"fill-blue-50 dark:fill-blue-950"},h={linked:e.jsx(gt,{className:"h-3.5 w-3.5"}),library:e.jsx(ft,{className:"h-3.5 w-3.5"})};return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:s.cn("cursor-help select-none transition-all",c[i],n),children:h[i]})}),e.jsxs(s.TooltipContent,{side:"bottom",className:s.cn("max-w-xs",u[i]),children:[e.jsx(s.TooltipArrow,{className:x[i]}),e.jsx("p",{children:o[i]})]})]})})}function Is({className:t,...a}){var K,G,H;const n=s.useEditorStore(B=>B.card),r=((K=n.customCardPreferences)==null?void 0:K.showCardHeader)??!0,l=((H=(G=n.preferences)==null?void 0:G.displayOptions)==null?void 0:H.showInlineFilterBar)??!0,d=s.useEditorStore(B=>B.frame),i=s.useDashboardStore(B=>B.dashboard.filters),c=s.useDashboardStore(B=>B.selectedSheetId),[o,u]=D.useState(!1),{currentUser:x}=s.useCurrentUserInfo(),{tokenProps:h}=D.useContext(s.SemaphorContext),p=s.useEditorStore(B=>B.actions.setRunSql),{updateFilter:k}=s.useDashboardActions(),m=i==null?void 0:i.find(B=>B.id===d.filterId),{data:f,isLoading:j,isFetching:C,errorMessage:I,errorSql:O,pagination:R}=s.useDashboardCardQuery(n),v=D.useMemo(()=>(f==null?void 0:f.records)||[],[f==null?void 0:f.records]),{setCard:w,updateCardInFrame:g,setIsDevMode:y,setCardSql:T}=s.useEditorActions(),{data:M}=s.useTopoJson(n),N=D.useMemo(()=>{var B;return n.type!=="pivotTable"||!((B=f==null?void 0:f.records)!=null&&B.length)?null:{records:f.records,columnSubtotalMeta:f.columnSubtotalMeta,subtotalColumns:f.subtotalColumns||[],pivotSchema:f.pivotSchema||[],groupByColumns:f.groupByColumns}},[n.type,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]),b=s.usePivotTableConfig(n,N),A=B=>{y(!0),T(B||O||n.sql||n.python||""),setTimeout(()=>{p(!0)},100)},F=()=>{u(!0)},E=D.useMemo(()=>{const B=typeof window<"u"?window.location.href:"",U=typeof navigator<"u"?navigator.userAgent:"",V=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:s.FeedbackCategory.QUERY_GENERATION,user:x,tokenContext:h,systemState:{cardConfig:n.config,dataSource:n.dataSource,dashboardFilters:i,errorMessage:I||void 0,errorSql:O||n.sql||n.python,generatedSql:O||n.sql},metadata:{url:B,userAgent:U,timestamp:new Date().toISOString(),viewport:V}}},[x,h,n,i,I,O]),L=(B,U)=>{var W,X;const V={...n,paginationConfig:{page:B+1,pageSize:U}};w(V),g(V),n.sql&&((X=(W=n.preferences)==null?void 0:W.tablePrefs)!=null&&X.enableDevModePagination)&&p(!0)},S=B=>{var W,X,se,_;const U=s.sortStateToSortByColumns(B,(W=n.config)==null?void 0:W.metricColumns,(X=n.config)==null?void 0:X.groupByColumns),V={...n,config:{...n.config||{},sortByColumns:U}};w(V),g(V),n.sql&&((_=(se=n.preferences)==null?void 0:se.tablePrefs)!=null&&_.enableDevModePagination)&&p(!0)},P=D.useMemo(()=>!n.id||!(f!=null&&f.records)?null:s.createChartConfig({card:n,data:f==null?void 0:f.records,cardType:n.type,queryConfig:n.queryConfig,customCfg:n.customCfg,preferences:n.preferences,topoJson:M}),[n.id,f==null?void 0:f.records,n.type,n.customCfg,n.preferences,M]);function $(B){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(s.EditorCustomVisual,{card:B})})}function J(){if(f!=null&&f.records&&(f==null?void 0:f.records.length)===0&&!j&&!C)return I?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(He,{error:I,errorSql:O||n.sql||n.python,onOpenInEditor:A,onSendFeedback:F,showFeedbackButton:!0,errorTitle:"Unable to Create Visual"})}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((j||C)&&(!(f!=null&&f.records)||f.records.length===0))return n.type==="table"?e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableSkeleton,{})}):e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!n.id)return null;if(n.type==="custom")return $(n);if(!["table","pivotTable","aggregateTable","custom"].includes(n.type)&&P)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:j||C?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:P})});if(n.type==="table")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:n,data:v,paginationMetadata:R,onPaginationChange:L,onSortChange:S,isLoading:j||C})});if(n.type==="pivotTable"&&b)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.PivotTableTanstack,{card:n,data:b.data,options:b.options,onAggregationChange:B=>{const U=s.handleAggregationChange(B,n.config),V={...n,config:U};w(V),g(V)},onAggregationLabelChange:B=>{const U=s.handleAggregationLabelChange(B,n.config),V={...n,config:U};w(V),g(V)}})});if(n.type==="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(s.AggregateTable,{card:n,data:(f==null?void 0:f.records)||[],groupByColumns:f==null?void 0:f.groupByColumns,pivotSchema:f==null?void 0:f.pivotSchema,paginationMetadata:R,onPaginationChange:L,onAggregationChange:B=>{const U=s.handleAggregationChange(B,n.config),V={...n,config:U};w(V),g(V)},isLoading:j||C})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...a,children:[(j||C)&&(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(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),r&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.CardTitle,{className:"text-base",children:e.jsx(s.EditableText,{value:n.title,onSave:B=>w({...n,title:B}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx($t,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(zt,{})})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:n.description||"",onSave:B=>w({...n,description:B}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),m&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:m.title||m.column,onSave:B=>k({...m,title:B}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:m})]})]}),l&&n.inlineFilters&&n.inlineFilters.length>0&&e.jsx("div",{className:"px-6 pb-3",children:e.jsx(s.InlineFilterBar,{card:n,sheetId:c||""})}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:J()}),e.jsx(s.FeedbackDialog,{open:o,onOpenChange:u,feedbackData:E,showDebugInfo:!0})]})}const ze=({language:t,value:a,onChange:n,readonly:r})=>e.jsx(s.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:t,value:a,onChange:n}),Kt=()=>e.jsxs(s.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(s.DialogTitle,{children:"Customize Card"})}),e.jsxs(s.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."})]})]}),Gt=({customCode:t,cardCustomCfgString:a,mergedConfig:n,onConfigChange:r,onCodeChange:l})=>e.jsxs(s.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(s.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(s.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(s.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(s.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(s.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ze,{language:"json",value:n,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ze,{readonly:!0,language:"json",value:a,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ze,{language:"javascript",value:t,onChange:l})})]}),qt=({error:t,hasCardCustomConfig:a,onReset:n,onApply:r,onClose:l})=>e.jsxs(s.DialogFooter,{className:"flex items-center",children:[e.jsx(s.Label,{className:"mr-2 text-red-500",children:t}),e.jsx(s.Button,{disabled:!a,onClick:n,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:l,variant:"outline",children:"Close"})]});function Ut(){const[t,a]=D.useState(!1),[n,r]=D.useState(""),[l,d]=D.useState(""),[i,c]=D.useState(""),[o,u]=D.useState(""),x=s.useEditorStore(v=>v.card),h=s.useEditorStore(v=>v.card.customCfg),p=h?JSON.stringify(h,null,2):"",{data:k}=s.useDashboardCardQuery(x),{data:m}=s.useTopoJson(x),{setCardCustomCfg:f,setCustomVisualCode:j}=s.useEditorActions(),C=v=>{var w,g;return JSON.stringify({...v,data:{...v.data,datasets:(g=(w=v.data)==null?void 0:w.datasets)==null?void 0:g.map(y=>({...y,data:[]}))}},null,2)},I=()=>{var w,g;if(!((w=k==null?void 0:k.records)!=null&&w.length))return;const v=s.createChartConfig({card:x,data:k.records,cardType:x.type,queryConfig:x.queryConfig,preferences:x.preferences,topoJson:m});if(v){r(C(v)),c(((g=x.preferences)==null?void 0:g.customVisualCode)||"");const y=s.merge(v,h);d(C(y))}},O=()=>{try{if(i&&j(i),l){const v=JSON.parse(l),w=s.getObjectDiff(JSON.parse(n),v);f(w),u("")}}catch{u("Invalid JSON configuration")}},R=Object.keys(h||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:a,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:I,className:R?"":"text-green-600 hover:text-green-700",children:e.jsx(s.Settings,{className:"h-4 w-4"})})}),e.jsxs(s.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(Kt,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Is,{className:"w-1/2 rounded shadow-none"})}),e.jsx(Gt,{customCode:i,cardCustomCfgString:p,mergedConfig:l,onConfigChange:v=>d(v??""),onCodeChange:v=>c(v??"")})]}),e.jsx(qt,{error:o,hasCardCustomConfig:!!h,onReset:()=>{d(n),f(null)},onApply:O,onClose:()=>a(!1)})]})]})}function Ht({isStarred:t,onClick:a,className:n}){const r=l=>{l.stopPropagation(),l.preventDefault(),a(l)};return e.jsx("button",{type:"button",onClick:r,className:s.cn("flex items-center justify-center rounded-sm p-0.5 transition-all","hover:bg-muted/80",n),"aria-label":t?"Remove from favorites":"Add to favorites",children:e.jsx(s.Star,{className:s.cn("h-3.5 w-3.5 transition-colors",t?"fill-yellow-400 text-yellow-400":"text-muted-foreground hover:text-foreground")})})}function rs({chartType:t,chartName:a,isCustom:n=!1,pluginName:r,isStarred:l,showStar:d=!0,onSelect:i,onToggleStar:c}){return e.jsxs("button",{onClick:i,className:s.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:[d&&e.jsx("div",{className:s.cn("absolute left-1 top-1 transition-opacity",l?"opacity-100":"opacity-0 group-hover:opacity-100"),children:e.jsx(Ht,{isStarred:l,onClick:()=>c()})}),n&&r&&e.jsx("div",{className:"absolute right-1 top-1",children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center justify-center",children:e.jsx(s.Info,{className:"h-3 w-3 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"top",className:"text-xs",children:r})]})}),e.jsx(s.ChartIcon,{chartType:t,chartName:a,isCustom:n,className:"h-6 w-6"}),e.jsx("span",{title:a,className:"line-clamp-2 text-center text-xs font-medium text-foreground",children:a})]})}const ls=[{id:"table",name:"Table"},{id:"bar",name:"Bar Chart"},{id:"line",name:"Line Chart"},{id:"stackedBar",name:"Stacked Bar"},{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:"kpi",name:"KPI"},{id:"text",name:"Text"},{id:"map",name:"Map"}];function Ds({onChartSelect:t,onClose:a}){const[n,r]=D.useState(""),{starredCharts:l,isStarred:d,toggleStar:i}=s.useStarredChartsStore(),{data:c=[],isLoading:o}=s.useCustomVisualsQuery(),{setCardType:u,setCardPreferences:x,setIsDevMode:h}=s.useEditorStore(v=>v.actions),{setCardCustomCfg:p,setCustomCardPreferences:k,setQueryConfig:m}=s.useEditorActions(),f=D.useMemo(()=>{if(!n)return ls;const v=n.toLowerCase();return ls.filter(w=>w.name.toLowerCase().includes(v))},[n]),j=D.useMemo(()=>{const v=c.filter(g=>g.componentType==="chart");if(!n)return v;const w=n.toLowerCase();return v.filter(g=>g.name.toLowerCase().includes(w))},[c,n]),C=v=>{p(null),x({}),u(v),["custom","text","map"].includes(v)&&(h(!0),m(void 0)),t==null||t(v),a==null||a()},I=v=>{p(null),x({}),u("custom"),k({type:"component",visualType:"single",url:v.url,componentName:v.name,icon:v.icon,pluginChartType:v.chartType}),m(void 0),t==null||t("custom",v),a==null||a()},O=v=>{const w={type:"default",id:v.id,name:v.name};i(w)},R=v=>{const w={type:"custom",id:v.name,url:v.url,icon:v.icon,name:v.name};i(w)};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(s.Search,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search charts...",value:n,onChange:v=>r(v.target.value),className:"h-auto border-0 p-0 text-sm focus-visible:ring-0 focus-visible:ring-offset-0"})]}),e.jsxs("div",{className:"max-h-[400px] overflow-y-auto",children:[f.length>0&&e.jsxs("div",{className:"mb-3",children:[e.jsx("span",{className:"mb-2 block text-xs font-medium text-muted-foreground",children:"Default Charts"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:f.map(v=>e.jsx(rs,{chartType:v.id,chartName:v.name,isCustom:!1,isStarred:d("default",v.id),onSelect:()=>C(v.id),onToggleStar:()=>O(v)},v.id))})]}),j.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-3"}),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:j.map((v,w)=>e.jsx(rs,{chartName:v.name,isCustom:!0,pluginName:v.pluginName,isStarred:d("custom",v.name),onSelect:()=>I(v),onToggleStar:()=>R(v)},`${v.url}-${v.name}-${w}`))})]})]}),o&&e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-3"}),e.jsx("div",{className:"py-4 text-center text-sm text-muted-foreground",children:"Loading custom charts..."})]}),f.length===0&&j.length===0&&!o&&e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No charts found"})]})]})}function Ms({variant:t="ghost"}){var d,i;const[a,n]=D.useState(!1),r=s.useEditorStore(c=>c.card),l=r.type;return e.jsxs(s.Popover,{open:a,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(s.SelectedChartIcon,{className:"size-4",chartType:l,customIcon:(d=r.customCardPreferences)==null?void 0:d.icon,componentName:(i=r.customCardPreferences)==null?void 0:i.componentName})})}),e.jsx(s.PopoverContent,{onOpenAutoFocus:c=>c.preventDefault(),className:"z-[70] w-[360px] p-3",children:e.jsx(Ds,{onClose:()=>n(!1)})})]})}function Jt({error:t,className:a="",textClassName:n="",copyButtonClassName:r=""}){const[l,d]=D.useState(!1),i=D.useRef(null),c=D.useRef(!1);function o(){t&&!c.current&&navigator.clipboard.writeText(t)}function u(p){(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),o())}function x(){const p=window.getSelection();if(p&&p.toString().trim()!==""){const k=p.toString();navigator.clipboard.writeText(k),d(!0),c.current=!0,setTimeout(()=>{d(!1),c.current=!1},1e3)}else c.current=!1}function h(){d(!1),c.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${a}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:i,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${n}`,onClick:o,onKeyDown:u,onMouseUp:x,onMouseDown:h,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),l&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function _t(){const t=s.useEditorStore(o=>{var u,x;return(x=(u=o.card.preferences)==null?void 0:u.chartOptions)==null?void 0:x.indexAxis}),a=s.useEditorStore(o=>o.card.type),{setChartOrientation:n,setCardPreferences:r}=s.useEditorStore(o=>o.actions),l=o=>{if(n(o),a!=="bullet")return;const u=o==="y"?"horizontal":"vertical",x=s.useEditorStore.getState().card.preferences,h={...x||{},bulletConfig:{...(x==null?void 0:x.bulletConfig)||{},orientation:u}};r(h)};function d(){const o=t??"x",u=()=>{l(o==="x"?"y":"x")};return e.jsx(s.IconButton,{onClick:u,tooltip:"Chart Orientation",children:o==="x"?e.jsx(Pe,{className:"size-4"}):e.jsx(Ve,{className:"size-4"})})}function i(){const o=()=>{l(t==="y"||t===void 0?"x":"y")};return e.jsx(s.IconButton,{onClick:o,tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(Pe,{className:"size-4"}):e.jsx(Ve,{className:"size-4"})})}function c(){const o=t??"y",u=()=>{l(o==="y"?"x":"y")};return e.jsx(s.IconButton,{onClick:u,tooltip:"Chart Orientation",children:o==="y"?e.jsx(Ve,{className:"size-4"}):e.jsx(Pe,{className:"size-4"})})}return e.jsx(e.Fragment,{children:a==="funnel"?i():a==="bullet"?c():d()})}function Qt({className:t}){var k,m,f,j,C,I,O,R,v,w;const a=s.useEditorStore(g=>g.card),{setCardPreferences:n,updateCardInFrame:r,setCard:l}=s.useEditorActions(),[d,i]=D.useState(!1),c=((m=(k=a.preferences)==null?void 0:k.displayOptions)==null?void 0:m.showFilterInfo)??!0,o=((j=(f=a.preferences)==null?void 0:f.displayOptions)==null?void 0:j.showCardToolbar)??!0,u=((I=(C=a.preferences)==null?void 0:C.displayOptions)==null?void 0:I.showChrome)??!0,x=((R=(O=a.preferences)==null?void 0:O.displayOptions)==null?void 0:R.allowScroll)??!0,h=((w=(v=a.preferences)==null?void 0:v.displayOptions)==null?void 0:w.showInlineFilterBar)??!0,p=(g,y)=>{var N;const T={...a.preferences,displayOptions:{...(N=a.preferences)==null?void 0:N.displayOptions,[g]:y}};n(T);const M={...a,preferences:T};l(M),r(M)};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsxs(s.DropdownMenu,{modal:!1,open:d,onOpenChange:i,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{className:"h-8 w-8 p-0",tooltip:"Display Options",children:e.jsx(Ss,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(s.DropdownMenuLabel,{children:"Display Options"}),e.jsx(s.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(s.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:g=>{p("showFilterInfo",g)},onSelect:g=>g.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(s.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:g=>{p("showCardToolbar",g)},onSelect:g=>g.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(s.DropdownMenuCheckboxItem,{checked:u,onCheckedChange:g=>{p("showChrome",g)},onSelect:g=>g.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(s.DropdownMenuCheckboxItem,{checked:x,onCheckedChange:g=>{p("allowScroll",g)},onSelect:g=>g.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(s.DropdownMenuCheckboxItem,{checked:h,onCheckedChange:g=>{p("showInlineFilterBar",g)},onSelect:g=>g.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 Yt(){const[t,a]=D.useState(!1),n=s.useEditorStore(h=>h.card),r=s.useEditorStore(h=>h.selectedConnectionId),{setCard:l}=s.useEditorActions(),d=s.useDashboardStore(h=>h.actions.removeCardInlineFilterValue),i=(n==null?void 0:n.inlineFilters)||[];function c(h){const p=h.qualifiedFieldName||h.name;if(i.find(I=>I.column===p))return;const m=h.qualifiedFieldName?h.qualifiedFieldName.split(".").slice(0,-1).join("."):h.qualifiedEntityName||h.entityName,f=s.fmt(h.name),j=h.qualifiedFieldName||f,C={id:s.v4(),column:p,title:h.label||h.name,dataType:h.dataType,table:h.entityName||"",database:"",connectionId:r||"",operation:"in",sql:s.getDefaultFilterSql(h.dataType,m,j),width:250};l({...n,inlineFilters:[...i,C]})}function o(h){const p=i.filter(k=>k.id!==h);l({...n,inlineFilters:p}),d(n.id,h)}function u(h,p){const k=i.map(m=>m.id===h?{...m,...p}:m);l({...n,inlineFilters:k})}return["bar","line","pie","doughnut","table","stackedBar","stackedLine","horizontalBar","radar","polarArea","scatter","bubble","funnel","aggregateTable","custom"].includes(n==null?void 0:n.type)?e.jsx("div",{className:"flex items-center gap-1",children:e.jsxs(s.Popover,{open:t,onOpenChange:a,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.IconButton,{tooltip:"Add Inline Filter",className:s.cn("relative",{"text-primary":i.length>0}),children:[e.jsx(bt,{className:"h-4 w-4"}),i.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:i.length})]})}),e.jsx(s.PopoverContent,{align:"end",className:"w-80 p-0",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 max-h-[300px] flex-col overflow-hidden",children:e.jsx(s.DndContext,{collisionDetection:s.closestCenter,children:e.jsx(s.SortableContext,{items:[],strategy:s.verticalListSortingStrategy,children:e.jsx(s.FieldsList,{context:"inline-filter",onFieldSelect:c,inlineFilters:i})})})}),i.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:i.map(h=>e.jsx(Wt,{filter:h,onUpdate:p=>u(h.id,p),onRemove:()=>o(h.id)},h.id))})]})]})})]})}):null}function Wt({filter:t,onUpdate:a,onRemove:n}){return e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-muted px-2 py-1.5 text-sm",children:[e.jsx("span",{className:"truncate",title:t.column,children:t.title}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(s.CustomFilterPopover,{filter:t,variant:"inline",onAccept:r=>a(r),trigger:e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0",title:"Configure filter",children:e.jsx(s.Settings2,{className:"h-3 w-3"})})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0 hover:bg-destructive/10 hover:text-destructive",onClick:n,children:e.jsx(s.X,{className:"h-3 w-3"})})]})]})}function Ls(){const t=s.useEditorStore(d=>d.card),a=s.useEditorStore(d=>{var i,c;return(c=(i=d.card)==null?void 0:i.preferences)==null?void 0:c.chartOptions}),n=s.getChartGridStyle(a),{setChartGrid:r}=s.useEditorActions();function l(){const d=["xy","none","x","y"],c=(d.indexOf(n)+1)%d.length;r(d[c])}return e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel","bullet"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(_t,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsx(e.Fragment,{}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(t.type)&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:l,children:[(n==="xy"||!n)&&e.jsx(s.Grid3x3,{className:"size-4"}),n==="x"&&e.jsx(Ns,{className:"size-4"}),n==="y"&&e.jsx(Ue,{className:"size-4"}),n==="none"&&e.jsx(Tt,{className:"size-4"})]}),e.jsx(Yt,{}),e.jsx(Qt,{})]})}function Xt(){const t=s.useEditorStore(m=>m.frame),a=s.useEditorStore(m=>m.card),{setFrame:n,setActiveTabCardId:r,setCard:l,updateCardInFrame:d}=s.useEditorActions(),i=(m,f)=>{m.dataTransfer.setData("tabIndex",f.toString())},c=m=>{m.preventDefault()},o=(m,f)=>{const j=m.dataTransfer.getData("tabIndex");if(j===f.toString())return;const C=Array.from(t.cards),[I]=C.splice(parseInt(j),1);C.splice(f,0,I),n({...t,cards:C})};function u(m){const f=t.cards.filter(I=>I.id!==m),j=f[0],C={...t,cards:f,activeCardId:j.id};n(C),r(j.id),l(j)}function x(m,f){const j={...t,cards:[...t.cards,f],activeCardId:m.id};n(j),r(f.id)}function h(){const m={...a,id:s.v4(),title:`${a.title} Copy`,tabTitle:`${a.tabTitle||a.title} Copy`};x(a,m)}function p(m){const f={dataSource:m.dataSource,connectionId:m.connectionId,lastSelectedDatabase:m.lastSelectedDatabase,lastSelectedSchema:m.lastSelectedSchema,lastSelectedTable:m.lastSelectedTable,lastSelectedDatamodelId:m.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};x(m,f)}function k(m,f){return m.cards.length===1&&(f.displayTab===!0||f.displayTab===void 0)||m.activeCardId!==f.id&&(f.displayTab===!0||f.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const j=f.displayTab===void 0?!1:!f.displayTab;l({...f,displayTab:j}),d({...f,displayTab:j})},children:f.displayTab===!0||f.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(dt,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(s.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[t.cards.map((m,f)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:j=>i(j,f),onDragOver:c,onDrop:j=>o(j,f),className:"",value:m.id,children:[k(t,m),e.jsx(s.Editable,{enabled:t.activeCardId===m.id,text:m.tabTitle||m.title,onSave:j=>{l({...a,tabTitle:j}),d({...a,tabTitle:j})},children:m.tabTitle||m.title},m.id),t.activeCardId===m.id&&e.jsx(s.CopyPlus,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:j=>{j.stopPropagation(),h()}}),t.activeCardId===m.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>u(m.id)})]},m.id)),e.jsx(s.IconButton,{tooltip:"Add Card",className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",onClick:()=>p(a),children:e.jsx(s.Plus,{className:"h-4 w-4"})})]})})}function Ge(){const t=s.useEditorStore(j=>j.frame),a=s.useEditorStore(j=>j.card),n=s.useEditorStore(j=>j.isSqlRunning),r=s.useEditorStore(j=>j.isDevMode),{setFrame:l,setActiveTabCardId:d,setCard:i,setIsDevMode:c,setRunSql:o}=s.useEditorActions(),{data:u,isLoading:x,isFetching:h,isError:p}=s.useDashboardCardQuery(a);function k(j){const C=t.cards.find(I=>I.id===j);if(C!=null&&C.sql){r||c(!0),d(j);return}if(C!=null&&C.queryConfig){r&&c(!1),m(j),d(j);return}r||m(j),d(j)}function m(j){const C={...t,cards:t.cards.map(O=>O.id===a.id?a:O),activeCardId:j};l(C);const I=C.cards.find(O=>O.id===j);I.sql&&o(!0),i(I)}function f(){return a.type==="kpi"?x||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.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 border-border",children:e.jsx(s.KPICard,{card:a,data:u==null?void 0:u.records,isPending:x||h,isError:p})})}):a.type==="text"?x||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.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(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:n,card:a,data:u==null?void 0:u.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Is,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:k,value:t.activeCardId,className:"flex grow flex-col",children:[t.cards.map(j=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:j.id,children:f()},j.id)),e.jsx(Xt,{})]})}function os({children:t}){const a=s.useEditorStore(b=>b.frame),n=s.useEditorStore(b=>b.card),r=s.useEditorStore(b=>b.isDevMode),l=s.useEditorStore(b=>b.isShowingVisual),d=s.useDashboardStore(b=>b.isVisualEditing),i=s.useEditorStore(b=>b.pythonStdOut),c=s.useEditorStore(b=>b.actions.setRunSql),{setFrame:o,setCard:u,setActiveTabCardId:x,runAssistant:h,setIsDevMode:p,setCardPreferences:k}=s.useEditorActions(),{data:m,isLoading:f,isFetching:j,errorMessage:C,refetch:I,pagination:O}=s.useDashboardCardQuery(n),R=D.useMemo(()=>(m==null?void 0:m.records)||[],[m==null?void 0:m.records]),[v,w]=D.useState(!1);D.useEffect(()=>{j||w(!1)},[j]);function g(b,A){var L,S;const F={...n,paginationConfig:{page:b+1,pageSize:A}};u(F);const E={...a,cards:a.cards.map(P=>P.id===n.id?F:P)};o(E),n.sql&&((S=(L=n.preferences)==null?void 0:L.tablePrefs)!=null&&S.enableDevModePagination)&&c(!0)}function y(b){var L,S,P,$;const A=s.sortStateToSortByColumns(b,(L=n.config)==null?void 0:L.metricColumns,(S=n.config)==null?void 0:S.groupByColumns),F={...n,config:{...n.config||{},sortByColumns:A}};u(F);const E={...a,cards:a.cards.map(J=>J.id===n.id?F:J)};o(E),n.sql&&(($=(P=n.preferences)==null?void 0:P.tablePrefs)!=null&&$.enableDevModePagination)&&c(!0)}function T(){const b=JSON.stringify(m==null?void 0:m.records,null,2),A=new Blob([b],{type:"application/json"}),F=URL.createObjectURL(A),E=document.createElement("a");E.href=F,E.download=`${n.title}.json`,E.click()}function M(){const A=[Object.keys(m==null?void 0:m.records.reduce((S,P)=>({...S,...P}),{})).join(","),...((m==null?void 0:m.records)||[]).map(S=>Object.values(S).join(","))].join(`
194
- `),F=new Blob([A],{type:"text/csv"}),E=URL.createObjectURL(F),L=document.createElement("a");L.href=E,L.download=`${n.title}.csv`,L.click()}function N(){const b=`Can you get the documentation for ${n.type} chart?`;h(b)}return n?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 px-6",children:[l&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(Ms,{}),d&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:N,children:e.jsx(ot,{className:"size-4"})}),!["table","custom"].includes(n.type)&&d&&e.jsx(Ut,{})]}),!l&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:M,children:e.jsx(s.PiFileCsv,{className:"size-4"})}),e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:T,children:e.jsx(ut,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(m==null?void 0:m.records,null,2),className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t,e.jsx(s.IconButton,{tooltip:"Refresh",disabled:f||j,onClick:()=>{w(!0),I()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":v})})}),e.jsx(Ls,{})]}),r&&e.jsx(en,{})]}),l?e.jsx(Ge,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[i&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:i&&e.jsx(Zt,{})}),e.jsx(s.ResizableHandle,{})]}),e.jsxs(s.ResizablePanel,{id:"2",order:2,minSize:10,className:s.cn("relative flex h-full min-h-0 w-full flex-1 basis-0",{"px-6":i}),children:[(m==null?void 0:m.records)&&(m==null?void 0:m.records.length)>0&&e.jsx(s.TableVisual,{card:n,data:R,paginationMetadata:O,onPaginationChange:g,onSortChange:y,isLoading:f||j}),C&&e.jsx(Jt,{error:C})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function Zt(){const t=s.useEditorStore(n=>n.pythonStdOut);if(!t)return null;const a=t.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(s.ScrollArea,{className:"overflow-y-auto pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:a}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function en(){const t=s.useEditorStore(n=>n.isShowingVisual),a=s.useEditorStore(n=>n.actions.setIsShowingVisual);return e.jsxs(s.Toggle,{pressed:!t,onPressedChange:()=>a(!t),variant:"outline",size:"sm",className:"h-8 gap-2",children:[e.jsx(s.Table2,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:"Results"})]})}function ie({value:t,onCommit:a,type:n="text",placeholder:r,className:l}){const[d,i]=D.useState(t),c=D.useRef(!1);D.useEffect(()=>{i(t)},[t]);const o=()=>{if(c.current){c.current=!1;return}d!==t&&a(d)},u=x=>{if(x.key==="Enter"){x.currentTarget.blur();return}x.key==="Escape"&&(c.current=!0,i(t),x.currentTarget.blur())};return e.jsx(s.Input$1,{type:n,placeholder:r,value:d,onChange:x=>i(x.target.value),onBlur:o,onKeyDown:u,className:l})}function he({defaultValue:t,label:a,options:n,value:r,onValueChange:l,className:d,icon:i,showPlaceholderLabel:c=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:l,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",d),children:e.jsxs("div",{className:"flex items-center gap-2",children:[i&&e.jsx("span",{children:i}),c&&e.jsx(s.SelectValue,{placeholder:a})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:a}),n.map(o=>e.jsx(s.SelectItem,{value:o.value,children:o.label},o.value))]})})]})}const sn={table:({children:t})=>e.jsx("table",{className:"my-3 w-full border-collapse overflow-hidden rounded-md border border-border text-sm",children:t}),thead:({children:t})=>e.jsx("thead",{className:"bg-muted",children:t}),th:({children:t})=>e.jsx("th",{className:"border border-border px-3 py-2 text-left font-medium",children:t}),td:({children:t})=>e.jsx("td",{className:"border border-border px-3 py-2",children:t}),code:({children:t,className:a})=>(a==null?void 0:a.includes("language-"))?e.jsx("pre",{className:"my-3 overflow-x-auto rounded-md bg-muted p-3 text-xs",children:e.jsx("code",{children:t})}):e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-xs",children:t}),pre:({children:t})=>e.jsx(e.Fragment,{children:t})};function Fs(){var f,j;const t=s.useEditorStore(C=>C.card.customCardPreferences),{data:a}=s.usePluginQuery(),n=(a==null?void 0:a.plugins)||[],r=s.useEditorStore(C=>C.card),l=s.useEditorStore(C=>C.frame),d=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:i}=s.useEditorActions(),{components:c,manifest:o}=s.useCustomVisual((t==null?void 0:t.url)||""),u=(f=o==null?void 0:o.visuals)==null?void 0:f.find(C=>C.name===(t==null?void 0:t.componentName));function x(C,I){if(!t)return;const R={...(t==null?void 0:t.dataInputCardIds)||{},[C]:{cardId:I,hookRef:null}};i({...t,dataInputCardIds:R})}function h(C){var O,R;const I=(O=l==null?void 0:l.cards)==null?void 0:O.filter(v=>{var w;return((w=v==null?void 0:v.customCardPreferences)==null?void 0:w.visualType)!=="multiple"}).map(v=>({value:v.id,label:v.tabTitle||v.title}));return e.jsx("div",{className:"space-y-2",children:(R=C==null?void 0:C.dataInputs)==null?void 0:R.map((v,w)=>{var g,y;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:v}),e.jsx(he,{className:"col-span-6 h-8 w-full justify-between",label:"",options:I||[],value:((y=(g=t==null?void 0:t.dataInputCardIds)==null?void 0:g[w])==null?void 0:y.cardId)||"",onValueChange:T=>x(w,T)})]},w+Math.random())})})}function p(C,I,O=[],R=""){var v,w;return t?C==="input"?e.jsx(ie,{className:`h-8 w-full ${s.removeRing}`,value:String(((v=t==null?void 0:t.settings)==null?void 0:v[I])??R??""),onCommit:g=>{i({...t,settings:{...t==null?void 0:t.settings,[I]:g}})}},I):C==="select"?e.jsx(he,{className:"h-8 w-full",label:"",options:O,value:((w=t==null?void 0:t.settings)==null?void 0:w[I])||R,onValueChange:g=>{i({...t,settings:{...t==null?void 0:t.settings,[I]:g}})}}):null:null}function k(C){const I=Object.entries((C==null?void 0:C.settings)||{});return e.jsx("div",{className:"space-y-3",children:I.map(([O,R])=>{var v;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:R.title}),((v=R.docs)==null?void 0:v.description)&&e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{className:"text-xs",children:R.docs.description})})]})})]}),p(R.ui,O,R.options,R.defaultValue)]},O)})})}function m(C){t&&i({...t,visualType:C,componentName:""})}return e.jsxs(s.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"",children:[e.jsxs(s.AccordionItem,{value:"plugin-settings",children:[e.jsx(s.AccordionTrigger,{children:"Plugin"}),e.jsx(s.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:[e.jsx(he,{icon:e.jsx(vs,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(t==null?void 0:t.url)||"",onValueChange:C=>i({...t||{url:"",componentName:""},url:C})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:d,onValueChange:m,children:e.jsxs(s.TabsList,{className:"h-9 w-full",children:[e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&e.jsx(e.Fragment,{children:c&&e.jsx(he,{icon:e.jsx(ct,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(c==null?void 0:c.filter(C=>C.type===d).map(C=>({value:C.name,label:C.name})))||[],value:t.componentName,onValueChange:C=>{console.log("changing value",C),i({...t,componentName:C})}})})]})})]}),((j=r==null?void 0:r.customCardPreferences)==null?void 0:j.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:(u==null?void 0:u.name)||"Settings"}),(u==null?void 0:u.docs)&&e.jsxs(s.HoverCard,{openDelay:0,closeDelay:100,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,onClick:C=>C.stopPropagation(),children:e.jsx(s.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground transition-colors hover:text-foreground"})}),e.jsx(s.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:[u.docs.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:u.docs.description}),u.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(s.Markdown,{remarkPlugins:[s.remarkGfm],components:sn,children:u.docs.dataSchema})})]}),u.docs.useCases&&u.docs.useCases.length>0&&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:u.docs.useCases.map((C,I)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1 text-primary",children:"•"}),e.jsx("span",{children:C})]},I))})]})]})})]})]})}),e.jsxs(s.AccordionContent,{children:[u&&u.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:h(u)})]}),u&&u.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:k(u)})})]})]})]})}function Se(){const[t,a]=D.useState([]),n=s.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:l}=s.useEditorStore(u=>u.actions),d=s.useEditorStore(u=>u.queryResultColumns);s.useEditorStore(u=>{var x;return(x=u.card.preferences)==null?void 0:x.filterOnClickColumnIndex}),D.useEffect(()=>{d&&a(new Array(d.length).fill(!1))},[d]);function i(u,x){var h,p;x?n!=null&&n.onClickFilter&&((h=n==null?void 0:n.onClickFilter)==null?void 0:h.length)>0?l({...n,onClickFilter:[...n.onClickFilter,{columnIndex:u,expression:""}]}):l({...n,onClickFilter:[{columnIndex:u,expression:""}]}):(l({...n,onClickFilter:(p=n==null?void 0:n.onClickFilter)==null?void 0:p.filter(k=>k.columnIndex!==u)}),a(k=>{const m=[...k];return m[u]=!1,m}))}function c(u,x){var p;const h=(p=n==null?void 0:n.onClickFilter)==null?void 0:p.map(k=>k.columnIndex===u?{...k,expression:x.target.value}:k);l({...n,onClickFilter:h})}function o(u){var x,h,p,k;if(t!=null&&t[u]||(h=(x=n==null?void 0:n.onClickFilter)==null?void 0:x.find(m=>m.columnIndex===u))!=null&&h.expression)return e.jsx(s.Input$1,{value:(k=(p=n==null?void 0:n.onClickFilter)==null?void 0:p.find(m=>m.columnIndex===u))==null?void 0:k.expression,onChange:m=>c(u,m),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:d==null?void 0:d.map((u,x)=>{var h,p;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((h=n==null?void 0:n.onClickFilter)!=null&&h.find(k=>k.columnIndex===x)),onCheckedChange:k=>i(x,k)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:u}),e.jsx("div",{className:"flex items-center gap-2",children:((p=n==null?void 0:n.onClickFilter)==null?void 0:p.find(k=>k.columnIndex===x))&&e.jsx(s.Pencil,{onClick:()=>{a(k=>{const m=[...k];return m[x]=!k[x],m})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),o(x)]})},u)})})}function tn({idx:t}){var c;const a=s.useEditorStore(o=>{var u;return(u=o.card)==null?void 0:u.preferences}),n=s.useEditorStore(o=>{var u;return(u=o.card.preferences)==null?void 0:u.datasetOptions}),r=s.useEditorStore(o=>o.actions.setCardPreferences),l=(c=a==null?void 0:a.chartOptions)==null?void 0:c.indexAxis,d=n==null?void 0:n.find(o=>o.idx===t);function i(o,u){(o==="end"||o==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const x={display:o!=="none",align:o,anchor:o,clamp:!0};if(!d)r({...a,datasetOptions:[...n||[],{idx:u,datalabels:x}]});else{const h={...d};h.datalabels=x;const p=n==null?void 0:n.map(k=>k.idx===u?h:k);r({...a,datasetOptions:p})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(s.Tag,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(s.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>i("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>i("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(jt,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>i("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(yt,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>i("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(vt,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function nn(){const t=s.useEditorStore(d=>d.card),{data:a}=s.useDashboardCardQuery(t),{keys:n}=s.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(d=>!s.METADATA_KEYS.includes(d));let l=r;if(["stackedBar","stackedLine"].includes(t.type)){const d=s.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:i}=s.getKeys(d);l=i.slice(1)}return{transformedMetricKeys:l,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}function Je({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function Os(){const t=s.useEditorStore(o=>o.card),a=s.useEditorStore(o=>{var u,x,h;return(h=(x=(u=o==null?void 0:o.card)==null?void 0:u.preferences)==null?void 0:x.chartOptions)==null?void 0:h.indexAxis}),{data:n}=s.useDashboardCardQuery(t),r=a==="y"?"Metric":"Dimension",l=a==="y"?"Dimension":"Metric",{dimensionKeys:d,transformedMetricKeys:i,keys:c}=nn();return c.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:d.map(o=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:o,children:Rs(o)},o))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:l}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:i.map((o,u)=>e.jsx(Bs,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:o,idx:u},o))})]})]})}function Rs(t,a=30){return t.length>a?t.slice(0,a)+"...":t}function Bs({col:t,idx:a,className:n,iconClassName:r,children:l}){const d=s.useEditorStore(x=>{var h;return(h=x.card)==null?void 0:h.preferences}),i=s.useEditorStore(x=>{var h,p;return(p=(h=x.card)==null?void 0:h.preferences)==null?void 0:p.datasetOptions}),c=i==null?void 0:i.find(x=>x.idx===a),{setCardPreferences:o}=s.useEditorStore(x=>x.actions);function u(x){if(!c)o({...d,datasetOptions:[...i||[],{idx:a,type:x==="area"?"line":x,fill:x==="area"?"origin":""}]});else{const h={...c};h.type=x==="area"?"line":x,h.fill=x==="area"?"origin":"";const p=i==null?void 0:i.map(k=>k.idx===a?h:k);o({...d,datasetOptions:p})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[l||e.jsx(Je,{className:"max-w-[100px]",title:t,children:Rs(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.ChartColumnIncreasing,{onClick:()=>u("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartLine,{onClick:()=>u("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartArea,{onClick:()=>u("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(tn,{idx:a})]})]})}function De(){const t=s.useDashboardStore(c=>c.dashboard.filters),a=s.useEditorStore(c=>c.frame),{setFrame:n}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=s.useAssignFilter();function d(c){const o=l(c,"frame");n({...a,filterId:o})}const i=t==null?void 0:t.find(c=>c.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(an,{onSelect:d,columns:r}),i&&e.jsx(s.FilterHeader,{filter:i})]})}function an({columns:t,onSelect:a}){var i;const[n,r]=Ke.useState(!1),[l,d]=Ke.useState("");return e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[l?(i=t.find(c=>c.column_name===l))==null?void 0:i.column_name:"Select Column...",e.jsx(s.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No framework found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(c=>e.jsxs(s.CommandItem,{value:c.column_name,onSelect:o=>{const u=o===l?"":o;d(u),r(!1),u&&a(c)},children:[c.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",l===c.column_name?"opacity-100":"opacity-0")})]},c.column_name))})]})]})})]})}function rn({cardType:t}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, y-axis-1, y-axis-2,... FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"y-axis1 - number"}),e.jsx("li",{children:"y-axis2 - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:a=>a.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(Os,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Se,{}),e.jsx(De,{})]})]})]})})}function ln({cardType:t}){function a(n){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:n==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),n==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:d=>d.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsx(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:a(t)})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Se,{}),e.jsx(De,{})]})]})]})})}function Vs(){const t=s.useEditorStore(c=>c.card.type),a=s.useEditorStore(c=>c.isDevMode),n=s.useEditorStore(c=>c.card.preferences),{setCardPreferences:r}=s.useEditorStore(c=>c.actions);function l(c){var x;const o={datalabels:{display:c!=="none",align:c,anchor:c,clamp:!0}},u={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(x=n==null?void 0:n.chartOptions)==null?void 0:x.plugins,...o}}};r(u)}function d(){var c,o,u;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((u=(o=(c=n==null?void 0:n.chartOptions)==null?void 0:c.plugins)==null?void 0:o.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Data Labels"}),e.jsx(s.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"start",children:"Start"}),e.jsx(s.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"end",children:"End"})]})})]})]})}function i(){var c,o,u;return e.jsx("div",{children:e.jsxs(s.Select,{value:((u=(o=(c=n==null?void 0:n.chartOptions)==null?void 0:c.plugins)==null?void 0:o.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(s.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:a?d():i()})}const on={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},cn={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function dn(){const t=s.useEditorStore(a=>a.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:un(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Vs,{}),e.jsx(Se,{}),e.jsx(De,{})]})]})}function un(t){if(["line","bar"].includes(t))return e.jsxs(e.Fragment,{children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsx("p",{children:"Chart Query"})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT x-axis, y-axis-1, y-axis-2, y-axis-3,... FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"X-axis - Category (ex. city)"}),e.jsx("li",{children:"Y-axis - Number (ex. population)"})]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Mixed Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and change the `type` property in the dataset."]}),e.jsx("pre",{children:JSON.stringify(on,null,2)})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Area Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and add `fill` property to the dataset. See",e.jsx("a",{className:"mx-1 text-blue-500 hover:underline",href:"https://www.chartjs.org/docs/latest/samples/area/line-boundaries.html",target:"_blank",children:"docs"}),"for more options."]}),e.jsx("pre",{children:JSON.stringify(cn,null,2)})]})]})]});if(t==="bubble")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis, radius FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Bubble Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"}),e.jsx("li",{children:"Radius - Number (ex. population)"})]})]})]})});if(t==="scatter")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"})]})]})]})});if(["pie","doughnut","polarArea","funnel"].includes(t))return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:[e.jsx("span",{children:t==="polarArea"?"Polar":t.charAt(0).toUpperCase()+t.slice(1)})," ","chart query"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Measure - Number (ex. population)"})]})]})]})})}function mn({colorRanges:t,setColorRanges:a}){const n={start:-1/0,end:100,color:""};function r(i,c,o){const u=[...t];u[i]={...u[i],[c]:o},a(u)}function l(i){const c=[...t];c.splice(i,1),a(c)}function d(){a([...t,n])}return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:"Color Range"}),e.jsx(s.Button,{onClick:d,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((i,c)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input$1,{onChange:o=>r(c,"start",o.target.value),value:i.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input$1,{value:i.end,onChange:o=>r(c,"end",o.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input$1,{onChange:o=>r(c,"color",o.target.value),value:i.color,className:s.cn(`h-7 min-w-14 p-0 ${s.removeRing}`),type:"color",list:"presetColors"}),e.jsxs("datalist",{id:"presetColors",children:[e.jsx("option",{children:s.colors.green[600]}),e.jsx("option",{children:s.colors.red[500]}),e.jsx("option",{children:s.colors.yellow[400]}),e.jsx("option",{children:s.colors.orange[500]})]}),e.jsx(s.Button,{onClick:()=>l(c),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},c))]})}function xn(){var x,h,p,k,m;const t=s.useEditorStore(f=>f.card.preferences),a=s.useEditorStore(f=>f.actions.setCardPreferences),n=s.useEditorStore(f=>f.card),r=s.hasValidCardConfig(n.config),l=s.useEditorStore(f=>f.actions.setNumberFormat);s.useEditorStore(f=>{var j,C;return(C=(j=f.card.preferences)==null?void 0:j.formatNumber)==null?void 0:C.decimalPlaces});const d=s.useEditorStore(f=>{var j,C;return(C=(j=f.card.preferences)==null?void 0:j.formatNumber)==null?void 0:C.locale}),i=s.useEditorStore(f=>{var j,C;return(C=(j=f.card.preferences)==null?void 0:j.formatNumber)==null?void 0:C.currency});s.useEditorStore(f=>f.actions.setFilterOnClickField);const c=s.useEditorStore(f=>{var j,C;return(C=(j=f.card.preferences)==null?void 0:j.formatNumber)==null?void 0:C.colorRanges})||[],o=s.useEditorStore(f=>f.actions.setColorRanges),u=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(f=>f.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(s.Checkbox,{checked:!!((x=t==null?void 0:t.formatNumber)!=null&&x.enabled),onCheckedChange:f=>{a({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:f}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((h=t==null?void 0:t.formatNumber)==null?void 0:h.enabled)===!0||r)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Locale"}),e.jsxs(s.Select,{value:d||"none",onValueChange:f=>{var j,C,I;return l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,((C=t==null?void 0:t.formatNumber)==null?void 0:C.currency)||"",f,((I=t==null?void 0:t.formatNumber)==null?void 0:I.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Format"}),e.jsx(s.SelectItem,{value:"none",children:"Auto"},"none"),s.LOCALE_CURRENCY_PAIRS.map(f=>e.jsx(s.SelectItem,{value:f.locale,children:f.locale},f.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:i||"none",onValueChange:f=>{var j,C,I;console.log("currency",f),l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,f==="none"?"":f,((C=t==null?void 0:t.formatNumber)==null?void 0:C.locale)||"",((I=t==null?void 0:t.formatNumber)==null?void 0:I.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Currency"}),e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),u.map(f=>e.jsx(s.SelectItem,{value:f,children:f},f))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Decimals"}),e.jsxs(s.Select,{value:((k=(p=t==null?void 0:t.formatNumber)==null?void 0:p.decimalPlaces)==null?void 0:k.toString())||"0",onValueChange:f=>{var j,C,I;return l(Number(f),((j=t==null?void 0:t.formatNumber)==null?void 0:j.currency)||"",((C=t==null?void 0:t.formatNumber)==null?void 0:C.locale)||"",((I=t==null?void 0:t.formatNumber)==null?void 0:I.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-3 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["0","1","2","3","4"].map(f=>e.jsx(s.SelectItem,{value:f,children:f},f))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Suffix"}),e.jsx(s.Input$1,{value:((m=t==null?void 0:t.formatNumber)==null?void 0:m.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:f=>{var j,C,I;return l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,((C=t==null?void 0:t.formatNumber)==null?void 0:C.currency)||"",((I=t==null?void 0:t.formatNumber)==null?void 0:I.locale)||"",f.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(mn,{colorRanges:c,setColorRanges:o})]})]})}function hn(){return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{type:"single",collapsible:!0,children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"",children:"KPI Query"}),e.jsxs(s.AccordionContent,{className:"font-mono",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs",children:"SELECT current, previous FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"current - number"}),e.jsx("li",{children:"previous - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/kpi",children:"example"})," in the docs."]})]})]})}),e.jsx("section",{className:"",children:e.jsx(xn,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function $e({children:t,summary:a,open:n,className:r}){return e.jsxs("details",{open:n,className:s.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(s.Label,{children:a}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const pn=[{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"}],fn=["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"],gn=fn.map(t=>({label:t,value:t}));function jn(){var o,u,x,h,p,k,m,f,j,C,I,O,R,v,w,g,y,T;const t=s.useEditorStore(M=>M.card),a=(u=(o=t==null?void 0:t.preferences)==null?void 0:o.mapVisualOptions)==null?void 0:u.topoJsonUrl,[n,r]=D.useState(((h=(x=t==null?void 0:t.preferences)==null?void 0:x.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:d}=s.useTopoJson(t),i=Object.keys((d==null?void 0:d.objects)||{}).map(M=>({label:M,value:M}))||[],c=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"p-6",children:[e.jsx($e,{summary:"Map Chart",children:e.jsx("p",{className:"rounded-md bg-muted p-2 font-mono text-xs",children:"SELECT country, value FROM table"})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx($e,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(he,{className:"h-9",options:c,onValueChange:M=>{console.log("value",M),l({...t.preferences,mapVisualOptions:{topoJsonUrl:M}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(s.Input$1,{onChange:M=>{r(M.target.value)},onBlur:()=>{var M;console.log("onBlur",n),l({...t.preferences,mapVisualOptions:{...(M=t.preferences)==null?void 0:M.mapVisualOptions,customTopoJsonUrl:n}})},value:n,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),d&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(he,{className:"h-9",options:i,value:((k=(p=t.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:k.objectKey)||"",label:"Map Object",onValueChange:M=>{var N;l({...t.preferences,mapVisualOptions:{...(N=t.preferences)==null?void 0:N.mapVisualOptions,objectKey:M}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(he,{className:"h-9",options:pn,value:((f=(m=t.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:f.projection)||"",label:"Projection",onValueChange:M=>{var N;l({...t.preferences,mapVisualOptions:{...(N=t.preferences)==null?void 0:N.mapVisualOptions,projection:M}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(he,{className:"h-9",options:gn,value:((C=(j=t.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:C.colorScale)||"",label:"Select Color Scale",onValueChange:M=>{var N;l({...t.preferences,mapVisualOptions:{...(N=t.preferences)==null?void 0:N.mapVisualOptions,colorScale:M}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx($e,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Input$1,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:.1,value:((O=(I=t.preferences)==null?void 0:I.mapVisualOptions)==null?void 0:O.projectionScale)||1,onChange:M=>{var N;l({...t.preferences,mapVisualOptions:{...(N=t.preferences)==null?void 0:N.mapVisualOptions,projectionScale:Number(M.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input$1,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((w=(v=(R=t.preferences)==null?void 0:R.mapVisualOptions)==null?void 0:v.projectionOffset)==null?void 0:w[0])||0,onChange:M=>{var N,b,A,F;l({...t.preferences,mapVisualOptions:{...(N=t.preferences)==null?void 0:N.mapVisualOptions,projectionOffset:[Number(M.target.value),((F=(A=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:F[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input$1,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((T=(y=(g=t.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:y.projectionOffset)==null?void 0:T[1])||0,onChange:M=>{var N,b,A,F;l({...t.preferences,mapVisualOptions:{...(N=t.preferences)==null?void 0:N.mapVisualOptions,projectionOffset:[((F=(A=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:F[0])||0,Number(M.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Se,{})]})}function bn(){var r;const t=s.useEditorStore(l=>l.card.preferences),{setCardPreferences:a}=s.useEditorStore(l=>l.actions);function n(l){a({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:l==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:n,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.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(s.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function Oe({cardType:t,docContent:a,suffix:n="Chart"}){let r="pie-donut-polar";return t==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} ${n}`}),e.jsx(s.AccordionContent,{children:a||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:l=>l.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),t==="text"&&e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2 py-4",children:e.jsx(bn,{})})]}),!["range","text"].includes(t)&&e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Se,{}),e.jsx(De,{})]})]})]})})}function vn(){const t=s.useEditorStore(r=>{var l,d;return(d=(l=r==null?void 0:r.card)==null?void 0:l.preferences)==null?void 0:d.sortChart}),{setSortChart:a}=s.useEditorActions();function n(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(he,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:t||"none",onValueChange:r=>{a(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[n(),e.jsx(Os,{})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Se,{}),e.jsx(De,{})]})]})]})})}function yn({cardType:t="table"}){console.log("cardType",t);const a=s.useEditorStore(l=>{var d;return(d=l.card)==null?void 0:d.preferences}),n=s.useEditorStore(l=>l.actions.setCardPreferences),r=l=>{n({...a,allowDownload:l})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Se,{}),e.jsx(De,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{onCheckedChange:r,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 Ps({color:t,onColorChange:a,onClose:n}){const[r,l]=D.useState(0),[d,i]=D.useState(100),[c,o]=D.useState(50),[u,x]=D.useState(t);D.useEffect(()=>{const j=is(t);if(j){const C=cs(j.r,j.g,j.b);l(C.h),i(C.s),o(C.l),x(t)}},[t]);const h=j=>{l(j),k(j,d,c)},p=j=>{const C=j.currentTarget.getBoundingClientRect(),I=Math.max(0,Math.min(1,(j.clientX-C.left)/C.width)),O=Math.max(0,Math.min(1,(j.clientY-C.top)/C.height)),R=I*100,v=(1-O)*100;i(R),o(v),k(r,R,v)},k=(j,C,I)=>{const O=Cn(j,C,I),R=Nn(O.r,O.g,O.b);x(R)},m=j=>{if(x(j),/^#[0-9A-Fa-f]{6}$/.test(j)){const C=is(j);if(C){const I=cs(C.r,C.g,C.b);l(I.h),i(I.s),o(I.l)}}},f=()=>{/^#[0-9A-Fa-f]{6}$/.test(u)&&(a(u),n())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:p,onMouseMove:j=>{j.buttons===1&&p(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:`${d}%`,top:`${100-c}%`,backgroundColor:u}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:j=>h(Number(j.target.value)),className:"w-full h-4 rounded-lg appearance-none cursor-pointer",style:{background:"linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"}})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"HEX"}),e.jsx(s.Input$1,{value:u,onChange:j=>m(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:t}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:u}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(s.Button,{variant:"outline",onClick:n,children:"Cancel"}),e.jsx(s.Button,{onClick:f,children:"OK"})]})]})}function is(t){const a=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return a?{r:parseInt(a[1],16),g:parseInt(a[2],16),b:parseInt(a[3],16)}:null}function Nn(t,a,n){return"#"+((1<<24)+(t<<16)+(a<<8)+n).toString(16).slice(1)}function cs(t,a,n){t/=255,a/=255,n/=255;const r=Math.max(t,a,n),l=Math.min(t,a,n);let d=0,i=0;const c=(r+l)/2;if(r!==l){const o=r-l;switch(i=c>.5?o/(2-r-l):o/(r+l),r){case t:d=((a-n)/o+(a<n?6:0))/6;break;case a:d=((n-t)/o+2)/6;break;case n:d=((t-a)/o+4)/6;break}}return{h:Math.round(d*360),s:Math.round(i*100),l:Math.round(c*100)}}function Cn(t,a,n){t/=360,a/=100,n/=100;let r,l,d;if(a===0)r=l=d=n;else{const i=(u,x,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?u+(x-u)*6*h:h<.5?x:h<.6666666666666666?u+(x-u)*(.6666666666666666-h)*6:u),c=n<.5?n*(1+a):n+a-n*a,o=2*n-c;r=i(o,c,t+1/3),l=i(o,c,t),d=i(o,c,t-1/3)}return{r:Math.round(r*255),g:Math.round(l*255),b:Math.round(d*255)}}const Sn=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function zs(){var O,R,v,w,g,y,T,M,N,b;const t=s.useEditorStore(A=>A.card),a=s.useEditorStore(A=>{var F;return(F=A.card)==null?void 0:F.preferences}),{setCardPreferences:n,updateCardInFrame:r}=s.useEditorActions(),{data:l}=s.useDashboardCardQuery(t),[d,i]=D.useState({}),[c,o]=D.useState(null),[u,x]=D.useState(null),h=D.useMemo(()=>{var L,S,P,$,J,K,G;if(!(l!=null&&l.records)||l.records.length===0)return[];const A=(t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine",F=(t==null?void 0:t.type)==="bar"||(t==null?void 0:t.type)==="line"||(t==null?void 0:t.type)==="horizontalBar"||(t==null?void 0:t.type)==="bullet",E=((L=t==null?void 0:t.config)==null?void 0:L.pivotByColumns)&&t.config.pivotByColumns.length>0;if((A||F)&&E){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const H=new Set;return l.pivotSchema.forEach(B=>{B.alias&&H.add(B.alias)}),Array.from(H)}if(l.records.length>0){const H=l.records[0],B=Object.keys(H),U=new Set;(S=t==null?void 0:t.config)!=null&&S.groupByColumns&&t.config.groupByColumns.forEach(X=>{U.add(X.label||X.name),U.add(X.alias||X.name)});const V=new Set;return(P=t==null?void 0:t.config)!=null&&P.metricColumns&&t.config.metricColumns.forEach(X=>{const se=X.alias||X.name;V.add(se),V.add(`${se}_count`),V.add(`${se}_sum`),V.add(`${se}_avg`),V.add(`${se}_min`),V.add(`${se}_max`);const _=X.entityName||X.qualifiedEntityName;_&&(V.add(`${_}_${se}`),V.add(`${_}_${se}_count`))}),B.filter(X=>!U.has(X)&&!V.has(X))}}if((F||A)&&!E&&((J=($=t==null?void 0:t.config)==null?void 0:$.metricColumns)!=null&&J.length))return t.config.metricColumns.map(H=>H.alias||H.label||H.name);if((G=(K=t==null?void 0:t.config)==null?void 0:K.groupByColumns)!=null&&G.length){const H=t.config.groupByColumns[0],B=H.label||H.name,U=new Set;return l.records.forEach(V=>{const W=V[B];W!=null&&U.add(String(W))}),Array.from(U)}return[]},[l,(O=t==null?void 0:t.config)==null?void 0:O.groupByColumns,(R=t==null?void 0:t.config)==null?void 0:R.pivotByColumns,(v=t==null?void 0:t.config)==null?void 0:v.metricColumns,t==null?void 0:t.type]),p=D.useMemo(()=>s.getDefaultChartColors(),[]);D.useEffect(()=>{const A={};h.forEach((F,E)=>{A[F]=s.getColorForValue(F,E,a==null?void 0:a.colorConfig)}),i(A)},[h,a==null?void 0:a.colorConfig,p]);const k=(A,F)=>{const E={...d,[A]:F};i(E);const L={...a||{},colorConfig:{segments:E}};n(L);const S={...t,preferences:L};r(S)},m=(A,F)=>{var J;const E=p[F%p.length],{[A]:L,...S}=((J=a==null?void 0:a.colorConfig)==null?void 0:J.segments)||{},P={...a||{},colorConfig:{segments:S}};n(P);const $={...t,preferences:P};r($),i(K=>({...K,[A]:E}))};if(!h.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((g=(w=t==null?void 0:t.config)==null?void 0:w.groupByColumns)==null?void 0:g.length)||((T=(y=t==null?void 0:t.config)==null?void 0:y.pivotByColumns)==null?void 0:T.length):(N=(M=t==null?void 0:t.config)==null?void 0:M.groupByColumns)==null?void 0:N.length)||["table","kpi","text","custom","heatmap"].includes(t.type))return null;const C=()=>{const A={...a||{},colorConfig:{segments:{}}};n(A);const F={...t,preferences:A};r(F);const E={};h.forEach((L,S)=>{E[L]=s.getColorForValue(L,S,void 0)}),i(E)},I=Object.keys(((b=a==null?void 0:a.colorConfig)==null?void 0:b.segments)||{}).length>0;return e.jsxs(s.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(s.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(Nt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Colors"})]})}),e.jsx(s.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:I&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:C,children:[e.jsx(ts,{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((A,F)=>{const E=s.isDefaultColor(d[A],F),L=!E;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:c===A,onOpenChange:S=>o(S?A:null),children:[e.jsx(s.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[A]}})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-3",children:e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Theme Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:p.slice(0,10).map((S,P)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",d[A]===S?"border-gray-900":"border-transparent"),style:{backgroundColor:S},onClick:()=>{k(A,S),o(null)},children:[P===F%p.length&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-white/90 px-0.5 text-[8px] font-bold text-gray-900 shadow-sm",children:"D"})}),e.jsx("span",{className:"sr-only",children:S})]},`default-${P}`))})]}),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:Sn.map((S,P)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",d[A]===S?"border-2 border-gray-900":S==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:S},onClick:()=>{k(A,S),o(null)},children:e.jsx("span",{className:"sr-only",children:S})},`preset-${P}`))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsx("button",{className:"text-sm font-medium text-blue-600 hover:text-blue-700",onClick:()=>{x({value:A,color:d[A]}),o(null)},children:"Custom color"}),!E&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{m(A,F),o(null)},children:[e.jsx(ts,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:A}),L&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},A)})}),u&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>x(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Ps,{color:u.color,onColorChange:A=>{k(u.value,A),x(null)},onClose:()=>x(null)})})]})]})})]})}function pe({value:t,onSave:a,placeholder:n="",type:r="text",className:l=""}){const[d,i]=D.useState(t??""),[c,o]=D.useState(!1);D.useEffect(()=>{i(t??"")},[t]);const u=()=>{a(d),o(!1)},x=()=>{i(t??""),o(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${l}`,children:[e.jsx(s.Input,{placeholder:n,type:r,value:c?d:t??"",onChange:h=>{i(h.target.value),o(!0)},onFocus:()=>o(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&c&&d!==t?u():h.key==="Escape"&&x()},"aria-label":n||"Edit field"}),c&&d!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:u,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:x,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}const wn=["auto","number","currency","percent","scientific","date"],kn=[{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"}],Tn=[{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"}],En=t=>t.charAt(0).toUpperCase()+t.slice(1);function _e({formatOptions:t={},onFormatOptionsChange:a,showTitle:n=!0,title:r="NUMBER FORMAT"}){const l=t.type||"auto",d=(c,o)=>{a({...t,[c]:o})},i=()=>l==="currency"?2:l==="percent"?1:0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[n&&e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(s.Select,{value:l,onValueChange:c=>d("type",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:wn.map(c=>e.jsx(s.SelectItem,{value:c,className:"text-xs",children:c==="auto"?"Auto (Default)":En(c)},c))})]})]}),l!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent"].includes(l)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input$1,{type:"number",min:"0",max:"10",placeholder:"0",value:t.decimalPlaces??i(),onChange:c=>d("decimalPlaces",parseInt(c.target.value)||0),className:"h-8 text-xs"})})]}),l==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(s.Select,{value:t.currency||"USD",onValueChange:c=>d("currency",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:kn.map(c=>e.jsx(s.SelectItem,{value:c.value,className:"text-xs",children:c.label},c.value))})]})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:t.useSuffix??!1,onCheckedChange:c=>d("useSuffix",c)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(s.Select,{value:t.locale||"en-US",onValueChange:c=>d("locale",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Tn.map(c=>e.jsx(s.SelectItem,{value:c.value,className:"text-xs",children:c.label},c.value))})]})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input$1,{placeholder:"e.g., $",value:t.prefix||"",onChange:c=>d("prefix",c.target.value),className:"h-8 text-xs"})})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input$1,{placeholder:"e.g., units",value:t.suffix||"",onChange:c=>d("suffix",c.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Negative in ()"}),e.jsx(s.SmallSwitch,{checked:t.negativeInParentheses??!1,onCheckedChange:c=>d("negativeInParentheses",c)})]}),l==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input$1,{type:"number",placeholder:"100",value:t.multiplyBy??"",onChange:c=>d("multiplyBy",c.target.value?parseFloat(c.target.value):void 0),className:"h-8 text-xs"})})]}),l==="date"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Format"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input$1,{type:"text",placeholder:"MM/DD/YYYY",value:t.dateFormat||"",onChange:c=>d("dateFormat",c.target.value),className:"h-8 text-xs"})})]})]})]})}function ds({axis:t,label:a,type:n,config:r,onChange:l}){var h,p,k,m,f,j,C,I,O,R,v,w;const d=(g,y)=>{l({...r,[g]:y})},i=(g,y)=>{var T,M;l({...r,name:{enabled:g==="enabled"?y:((T=r==null?void 0:r.name)==null?void 0:T.enabled)??!1,text:g==="text"?y:(M=r==null?void 0:r.name)==null?void 0:M.text}})},c=(g,y)=>{var T,M;l({...r,labels:{enabled:g==="enabled"?y:((T=r==null?void 0:r.labels)==null?void 0:T.enabled)??!0,rotation:g==="rotation"?y:(M=r==null?void 0:r.labels)==null?void 0:M.rotation}})},o=(g,y)=>{l({...r,scale:{...r==null?void 0:r.scale,[g]:y===""?"auto":Number(y)}})},u=t==="x"?["auto","top","bottom"]:["auto","left","right"],x=["auto","0","45","90","-45","-90"];return e.jsxs(s.AccordionItem,{value:`${t}-axis`,className:"border-b-0",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx(s.AccordionTrigger,{className:"flex grow items-center justify-between gap-3 py-2 text-sm font-medium hover:no-underline",children:e.jsx("div",{className:"flex grow items-center justify-between gap-2",children:e.jsx("span",{children:a})})}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:g=>d("enabled",g),onClick:g=>g.stopPropagation()})]}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TITLE"}),e.jsx(s.SmallSwitch,{checked:((h=r==null?void 0:r.name)==null?void 0:h.enabled)??!1,onCheckedChange:g=>i("enabled",g)})]}),((p=r==null?void 0:r.name)==null?void 0:p.enabled)&&e.jsx(pe,{placeholder:`${a} title`,value:((k=r==null?void 0:r.name)==null?void 0:k.text)||"",onSave:g=>i("text",g),className:""})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(s.Select,{value:(r==null?void 0:r.position)||"auto",onValueChange:g=>d("position",g),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(g=>e.jsx(s.SelectItem,{value:g,className:"text-xs",children:g==="auto"?"Auto (Default)":s.titleCase(g)},g))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(s.SmallSwitch,{checked:((m=r==null?void 0:r.labels)==null?void 0:m.enabled)!==!1,onCheckedChange:g=>c("enabled",g)})]}),((f=r==null?void 0:r.labels)==null?void 0:f.enabled)!==!1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Rotation"}),e.jsxs(s.Select,{value:String(((j=r==null?void 0:r.labels)==null?void 0:j.rotation)||"auto"),onValueChange:g=>c("rotation",g==="auto"?"auto":Number(g)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:x.map(g=>e.jsx(s.SelectItem,{value:g,className:"text-xs",children:g==="auto"?"Auto (Default)":`${g}°`},g))})]})]})]}),n==="value"&&e.jsx(_e,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:g=>l({...r,formatOptions:g}),showTitle:!0,title:"FORMAT"}),n==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.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(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"auto",value:((C=r==null?void 0:r.scale)==null?void 0:C.min)==="auto"||((I=r==null?void 0:r.scale)==null?void 0:I.min)===void 0?"":String(r.scale.min),onSave:g=>o("min",g),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Max"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"auto",value:((O=r==null?void 0:r.scale)==null?void 0:O.max)==="auto"||((R=r==null?void 0:r.scale)==null?void 0:R.max)===void 0?"":String(r.scale.max),onSave:g=>o("max",g),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Step"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"auto",value:((v=r==null?void 0:r.scale)==null?void 0:v.stepSize)==="auto"||((w=r==null?void 0:r.scale)==null?void 0:w.stepSize)===void 0?"":String(r.scale.stepSize),onSave:g=>o("stepSize",g),className:""})})]})]})]})]})]})}function $s(){const t=s.useEditorStore(i=>i.card),a=s.useEditorStore(i=>{var c;return(c=i.card)==null?void 0:c.preferences}),{setCardPreferences:n,updateCardInFrame:r}=s.useEditorActions();if(!t||["tornado","pyramid","kpi","treemap"].includes(t.type))return null;const l=s.AxisConfigurator.getAxisInfo(t.type,a);if(!l.hasXAxis&&!l.hasYAxis)return null;const d=(i,c)=>{const u={...a||{},[i==="x"?"xAxisConfig":"yAxisConfig"]:c};n(u);const x={...t,preferences:u};r(x)};return e.jsxs(s.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(s.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(Ss,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Axes"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[l.hasXAxis&&e.jsx(ds,{axis:"x",label:"X-Axis",type:l.xAxisType,config:s.mergeAxisConfig(s.getDefaultAxisConfig(t.type,"x"),a==null?void 0:a.xAxisConfig),onChange:i=>d("x",i)}),l.hasYAxis&&e.jsx(ds,{axis:"y",label:"Y-Axis",type:l.yAxisType,config:s.mergeAxisConfig(s.getDefaultAxisConfig(t.type,"y"),a==null?void 0:a.yAxisConfig),onChange:i=>d("y",i)})]})})]})}function Ks(){const t=s.useEditorStore(x=>x.card),a=s.useEditorStore(x=>{var h,p,k,m;return(m=(k=(p=(h=x.card)==null?void 0:h.preferences)==null?void 0:p.chartOptions)==null?void 0:k.plugins)==null?void 0:m.legend}),{setLegendOptions:n}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r=s.getDefaultLegendConfig(t.type),l=(r==null?void 0:r.display)??!0,d=(r==null?void 0:r.position)??"top",i=(r==null?void 0:r.align)??"center",c=(x,h)=>{const p={...a,[x]:h};n(p)},o=["top","bottom","left","right"],u=["start","center","end"];return e.jsxs(s.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(s.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(pt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(s.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(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:(a==null?void 0:a.display)??l,onCheckedChange:x=>c("display",x)})]}),((a==null?void 0:a.display)??l)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(a==null?void 0:a.position)||d,onValueChange:x=>c("position",x),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:o.map(x=>e.jsx(s.SelectItem,{value:x,className:"text-xs",children:s.titleCase(x)},x))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(s.Select,{value:(a==null?void 0:a.align)||i,onValueChange:x=>c("align",x),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(x=>e.jsx(s.SelectItem,{value:x,className:"text-xs",children:s.titleCase(x)},x))})]})]})]})]})})]})}function Gs(){var E,L,S,P,$,J,K,G,H,B,U;const t=s.useEditorStore(V=>V.card),a=s.useEditorStore(V=>{var W,X;return(X=(W=V.card)==null?void 0:W.preferences)==null?void 0:X.dataLabelsConfig}),n=s.useEditorStore(V=>{var W;return(W=V.card)==null?void 0:W.preferences}),{setCardPreferences:r,updateCardInFrame:l}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(t.type))return null;const d=t.type==="bullet"?((E=n==null?void 0:n.bulletConfig)==null?void 0:E.orientation)??(((L=n==null?void 0:n.chartOptions)==null?void 0:L.indexAxis)==="x"?"vertical":"horizontal"):void 0,i=d!=null?d==="horizontal":((S=n==null?void 0:n.chartOptions)==null?void 0:S.indexAxis)==="y",c=t.type==="stackedBar"||t.type==="stackedLine",o=t.type==="pie"||t.type==="doughnut"||t.type==="polarArea"||t.type==="funnel",u=!o,x=t.type==="bubble"||t.type==="scatter",h=($=(P=n==null?void 0:n.chartOptions)==null?void 0:P.plugins)==null?void 0:$.datalabels,p=(h==null?void 0:h.display)!==!1&&((h==null?void 0:h.anchor)||(h==null?void 0:h.align)),k=s.getDefaultDataLabelsConfig(t.type,t.preferences),m=a??k,f=(k==null?void 0:k.enabled)??p??!1,j=(a==null?void 0:a.enabled)!==void 0?a.enabled:f,C=(V,W)=>{const _={...k??{},...a??{},[V]:W};V==="enabled"&&(_.display=W,W&&x&&!_.position&&(_.position="bottom")),V==="position"&&x&&(_.position="bottom");const te={...t.preferences||{},dataLabelsConfig:_};r(te);const Y={...t,preferences:te};l(Y)},I=(V,W)=>{const X=a??{},_={...k??{},...X,font:{...X.font||{},[V]:W}},te={...t.preferences||{},dataLabelsConfig:_};r(te);const Y={...t,preferences:te};l(Y)},O=(V,W)=>{const X=a??{},_={...k??{},...X,formatOptions:{...X.formatOptions||{},[V]:W}},te={...t.preferences||{},dataLabelsConfig:_};r(te);const Y={...t,preferences:te};l(Y)},R=()=>{const V=t.type;return V==="stackedBar"||V==="stackedLine"||V==="pie"||V==="doughnut"?"center":i?"right":"top"},v=t.type!=="treemap"&&t.type!=="heatmap",w=t.type!=="treemap",g=R();let y=[];if(v)if(x)y=["bottom"];else if(c||o)y=["center"];else{const V=i?["center","left","right"]:["center","top","bottom"];y=["auto",...t.type==="bullet"?V:V.filter(X=>X!==g),"custom"]}const T=()=>s.titleCase(g),M=["center","start","end"],N=["center","start","end","top","bottom"],b=u?["auto","number","currency","percent","none"]:["number","currency","percent","none"],A=[{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"}],F=[{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)"}];return e.jsxs(s.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(s.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(Et,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(s.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(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:j,onCheckedChange:V=>C("enabled",V)})]}),j&&e.jsxs(e.Fragment,{children:[v&&!c&&!o&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:x?(m==null?void 0:m.position)||"bottom":(m==null?void 0:m.position)||"auto",onValueChange:V=>C("position",V),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:y.map(V=>e.jsx(s.SelectItem,{value:V,className:"text-xs",children:V==="auto"?T():V==="custom"?"Custom (Advanced)":s.titleCase(V)},V))})]})]}),c&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Show Total"}),e.jsx(s.SmallSwitch,{checked:(a==null?void 0:a.showTotal)??!1,onCheckedChange:V=>C("showTotal",V)})]}),(m==null?void 0:m.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(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Anchor"}),e.jsxs(s.Select,{value:(m==null?void 0:m.anchor)||"center",onValueChange:V=>C("anchor",V),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:M.map(V=>e.jsx(s.SelectItem,{value:V,className:"text-xs",children:s.titleCase(V)},V))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Align"}),e.jsxs(s.Select,{value:String((m==null?void 0:m.align)||"center"),onValueChange:V=>C("align",V),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:N.map(V=>e.jsx(s.SelectItem,{value:V,className:"text-xs",children:s.titleCase(V)},V))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(m==null?void 0:m.format)||(u?"auto":"none"),onValueChange:V=>C("format",V),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:b.map(V=>e.jsx(s.SelectItem,{value:V,className:"text-xs",children:V==="auto"&&u?"Auto (Use Axis)":V==="none"?"None (Raw Value)":s.titleCase(V)},V))})]})]}),(m==null?void 0:m.format)&&!["auto","none"].includes(m.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(m.format)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"0",value:String(((J=m==null?void 0:m.formatOptions)==null?void 0:J.decimalPlaces)??(m.format==="currency"?2:m.format==="percent"?1:0)),onSave:V=>O("decimalPlaces",Number(V)),className:""})})]}),m.format==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Currency"}),e.jsxs(s.Select,{value:((K=m==null?void 0:m.formatOptions)==null?void 0:K.currency)||"USD",onValueChange:V=>O("currency",V),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:A.map(V=>e.jsx(s.SelectItem,{value:V.value,className:"text-xs",children:V.label},V.value))})]})]}),["number","currency"].includes(m.format)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((G=m==null?void 0:m.formatOptions)==null?void 0:G.useSuffix)??!1,onCheckedChange:V=>O("useSuffix",V)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Locale"}),e.jsxs(s.Select,{value:((H=m==null?void 0:m.formatOptions)==null?void 0:H.locale)||"en-US",onValueChange:V=>O("locale",V),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:F.map(V=>e.jsx(s.SelectItem,{value:V.value,className:"text-xs",children:V.label},V.value))})]})]})]}),w&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Appearance"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Size"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"12",value:String(((B=m==null?void 0:m.font)==null?void 0:B.size)||12),onSave:V=>I("size",Number(V)),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Weight"}),e.jsxs(s.Select,{value:((U=m==null?void 0:m.font)==null?void 0:U.weight)||"normal",onValueChange:V=>I("weight",V),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(s.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Color"}),e.jsxs(s.Select,{value:(m==null?void 0:m.color)==="auto"||!(m!=null&&m.color)?"auto":"custom",onValueChange:V=>{V==="auto"&&C("color","auto")},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Smart Contrast)"}),e.jsx(s.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom (Coming Soon)"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Rotation"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"0",value:String((m==null?void 0:m.rotation)||0),onSave:V=>C("rotation",Number(V)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}const us=["poor","satisfactory","good"];function ms(t){if(!t)return;const a={...t};return a.targetMetricKey||delete a.targetMetricKey,a.comparativeMetricKey||delete a.comparativeMetricKey,!a.targetValue&&a.targetValue!==0&&delete a.targetValue,(!a.rangeKeys||Object.keys(a.rangeKeys).length===0)&&delete a.rangeKeys,(!a.ranges||Object.keys(a.ranges).length===0)&&delete a.ranges,(!a.rangeLabels||Object.keys(a.rangeLabels).length===0)&&delete a.rangeLabels,a}function qs(){var A,F;const t=s.useEditorStore(E=>E.card.preferences),a=s.useEditorStore(E=>E.card),n=s.useEditorStore(E=>E.isDevMode),{setCardPreferences:r,setChartOrientation:l}=s.useEditorActions(),d=D.useMemo(()=>(t==null?void 0:t.bulletConfig)||{},[t==null?void 0:t.bulletConfig]),c=s.hasValidCardConfig(a==null?void 0:a.config)&&!n,[o,u]=D.useState(d.showRanges??!1),[x,h]=D.useState(d.rangesArePercentages??!1),p=d.disableAutoComparative?!1:d.comparativeMetricKey!==void 0||!c,[k,m]=D.useState(p);D.useEffect(()=>{u(d.showRanges??!1)},[d.showRanges]),D.useEffect(()=>{h(d.rangesArePercentages??!1)},[d.rangesArePercentages]);const f=d.targetValue===void 0?"":String(d.targetValue);D.useEffect(()=>{const E=d.disableAutoComparative?!1:d.comparativeMetricKey!==void 0||!c;m(E)},[d.disableAutoComparative,d.comparativeMetricKey,c]);const j=D.useMemo(()=>{var E,L;return((L=(E=a==null?void 0:a.config)==null?void 0:E.metricColumns)==null?void 0:L.map(S=>{const P=S.label||S.name||S.alias||"";return{value:P,label:P}}))||[]},[(A=a==null?void 0:a.config)==null?void 0:A.metricColumns]);D.useEffect(()=>{var G,H;if(!t||j.length===0)return;const E={};let L=!1;const S=(G=j[1])==null?void 0:G.value;!d.targetMetricKey&&S&&(E.targetMetricKey=S,L=!0);const P=(H=j[2])==null?void 0:H.value;!d.comparativeMetricKey&&!d.disableAutoComparative&&P&&(E.comparativeMetricKey=P,L=!0);const $=j.slice(3),J={...d.rangeKeys||{}};let K=!1;if(us.forEach((B,U)=>{!J[B]&&$[U]&&(J[B]=$[U].value,K=!0)}),K&&(E.rangeKeys=J,L=!0,d.showRanges===void 0&&(E.showRanges=!0)),L){const B=ms({...d,...E});r({...t,bulletConfig:B})}},[j,d,t,r]);const C=E=>{const L=ms({...d,...E});r({...t,bulletConfig:L})},I=(E,L)=>{const S={...d.rangeKeys||{},[E]:L.trim()};L.trim()||delete S[E],C({rangeKeys:Object.keys(S).length>0?S:void 0})},O=(E,L)=>{const S=L===""?void 0:Number(L),P={...d.ranges||{}};S===void 0||Number.isNaN(S)?delete P[E]:P[E]=S,C({ranges:Object.keys(P).length?P:void 0})},R=E=>{if(E===""){C({targetValue:void 0});return}const L=Number(E);C({targetValue:Number.isNaN(L)?void 0:L})},v=(E,L)=>{const S=L.trim(),P={...d.rangeLabels||{}};S?P[E]=S:delete P[E],C({rangeLabels:Object.keys(P).length>0?P:void 0})},w=E=>{u(E),C({showRanges:E})},g=E=>{h(E),C({rangesArePercentages:E})},y=d.orientation||(((F=t==null?void 0:t.chartOptions)==null?void 0:F.indexAxis)==="y"?"horizontal":"vertical"),T=E=>{C({orientation:E}),l(E==="horizontal"?"y":"x")},M=[{value:"__none",label:"None"},...j.map(E=>({value:E.value,label:E.label}))],N=M,b=E=>{if(m(E),!E){C({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!c){C({disableAutoComparative:!1});return}if(d.comparativeMetricKey)C({disableAutoComparative:!1});else{const L=j.find(S=>S.value!==d.targetMetricKey);C({comparativeMetricKey:L==null?void 0:L.value,disableAutoComparative:!1})}};return e.jsxs(s.AccordionItem,{value:"bullet-config",className:"border-b-0",children:[e.jsx(s.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(s.BulletChartIcon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bullet Chart"})]})}),e.jsxs(s.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(s.Label,{className:"text-xs font-medium",children:"ORIENTATION"}),e.jsxs(s.Select,{value:y,onValueChange:E=>T(E),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"horizontal",className:"text-xs",children:"Horizontal"}),e.jsx(s.SelectItem,{value:"vertical",className:"text-xs",children:"Vertical"})]})]})]}),c&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TARGET METRIC"}),e.jsxs(s.Select,{value:d.targetMetricKey||"__none",onValueChange:E=>C({targetMetricKey:E==="__none"?void 0:E}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select metric"})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"__none",className:"text-xs",children:"None"}),j.map(E=>e.jsx(s.SelectItem,{value:E.value,className:"text-xs",children:E.label},E.value))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"COMPARATIVE METRIC"}),c?e.jsxs(s.Select,{value:d.comparativeMetricKey||"__none",onValueChange:E=>C({comparativeMetricKey:E==="__none"?void 0:E,disableAutoComparative:E==="__none"}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select metric"})}),e.jsx(s.SelectContent,{children:M.map(E=>e.jsx(s.SelectItem,{value:E.value,className:"text-xs",children:E.label},E.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(s.SmallSwitch,{checked:k,onCheckedChange:E=>b(E)})]}),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(s.Label,{className:"text-xs font-medium",children:"TARGET VALUE (FALLBACK)"}),e.jsx(ie,{type:"number",className:"h-8 text-xs",value:f,onCommit:R,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(s.Label,{className:"text-xs font-medium",children:"QUALITATIVE RANGES"}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:200,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"text-muted-foreground transition-colors hover:text-foreground",children:e.jsx(s.Info,{className:"h-3.5 w-3.5"})})}),e.jsx(s.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(s.SmallSwitch,{checked:o,onCheckedChange:w})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:x,disabled:!o,onChange:E=>g(E.target.checked),className:"h-3.5 w-3.5 accent-primary disabled:opacity-50"}),e.jsx("span",{children:"Use % of value"})]})]}),o&&e.jsx("div",{className:"space-y-3",children:us.map(E=>{var L,S,P,$,J;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(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[E," LABEL"]}),e.jsx(ie,{placeholder:`Display label (${E})`,value:((L=d.rangeLabels)==null?void 0:L[E])||"",onCommit:K=>v(E,K),className:"h-8 text-xs"})]}),c?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[E," COLUMN"]}),e.jsxs(s.Select,{value:((S=d.rangeKeys)==null?void 0:S[E])||"__none",onValueChange:K=>{K==="__none"?I(E,""):I(E,K)},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select column"})}),e.jsx(s.SelectContent,{children:N.map(K=>e.jsx(s.SelectItem,{value:K.value,className:"text-xs",children:K.label},K.value))})]})]}):e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[E," COLUMN KEY"]}),e.jsx(ie,{placeholder:"Column key",value:((P=d.rangeKeys)==null?void 0:P[E])||"",onCommit:K=>I(E,K),className:"h-8 text-xs"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[E," VALUE"]}),e.jsx(ie,{type:"number",placeholder:x?"0.80":"Static value",value:(($=d.ranges)==null?void 0:$[E])===void 0?"":String((J=d.ranges)==null?void 0:J[E]),onCommit:K=>O(E,K),className:"h-8 text-xs"})]})]},E)})})]})]})]})}const xs=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],An=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function Le({value:t,onChange:a,label:n}){const[r,l]=D.useState(!1),[d,i]=D.useState(!1),c=()=>{const o=xs.find(u=>u.value===t);return o?o.color:t.startsWith("#")?t:xs[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:r,onOpenChange:l,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"size-5 rounded border-2 border-input shadow-sm transition-all hover:scale-110 hover:border-gray-400",style:{backgroundColor:c()},"aria-label":`Change color for ${n}`})}),e.jsx(s.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:An.map(o=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",c()===o?"border-gray-900":"border-transparent"),style:{backgroundColor:o},onClick:()=>{a(o),l(!1)},children:e.jsx("span",{className:"sr-only",children:o})},o))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{i(!0),l(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:n})]}),d&&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:()=>i(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Ps,{color:c(),onColorChange:o=>{a(o),i(!1)},onClose:()=>i(!1)})})]})]})}const In=Object.keys(s.HEATMAP_PRESET_PALETTES);function Us(){const t=s.useEditorStore(p=>p.card),a=s.useEditorStore(p=>{var k;return(k=p.card)==null?void 0:k.preferences}),{setCardPreferences:n}=s.useEditorActions(),r=(t==null?void 0:t.type)==="heatmap",l=(a==null?void 0:a.heatmapConfig)||{},d=l.colorPalette??"green",i=l.legendPosition??"bottom",c=D.useMemo(()=>l.colorRange&&l.colorRange[0]&&l.colorRange[1]?[l.colorRange[0],l.colorRange[1]]:[...s.DEFAULT_HEATMAP_CUSTOM_RANGE],[l.colorRange]),o=p=>{const k={...l,...p};k.colorPalette!=="custom"?delete k.colorRange:(!k.colorRange||!k.colorRange[0]||!k.colorRange[1])&&(k.colorRange=[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]),n({...a||{},heatmapConfig:k})},u=p=>{o({colorPalette:p,colorRange:p==="custom"?l.colorRange??[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},x=(p,k)=>{const m=[...c];m[p]=k,o({colorPalette:"custom",colorRange:m})},h=p=>{o({legendPosition:p})};return r?e.jsxs(s.AccordionItem,{value:"heatmap-color-config",className:"border-none",children:[e.jsx(s.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(s.Grid3x3,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Heatmap Settings"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs(s.RadioGroup,{value:d,onValueChange:p=>u(p??"blue"),className:"space-y-3",children:[In.map(p=>{const k=s.HEATMAP_PRESET_PALETTES[p];return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:`heatmap-${p}`,value:p}),e.jsxs(s.Label,{htmlFor:`heatmap-${p}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:k.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${k.start}, ${k.end})`}})]})]},p)}),e.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.RadioGroupItem,{id:"heatmap-custom",value:"custom"}),e.jsx(s.Label,{htmlFor:"heatmap-custom",className:"text-sm font-medium",children:"Custom colors"})]}),d==="custom"&&e.jsxs("div",{className:"flex flex-col gap-3 pl-6",children:[e.jsx(Le,{value:c[0],onChange:p=>x(0,p),label:"Start color"}),e.jsx(Le,{value:c[1],onChange:p=>x(1,p),label:"End color"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Color scale position"}),e.jsxs(s.Select,{value:i,onValueChange:p=>h(p??"bottom"),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["top","bottom","left","right"].map(p=>e.jsx(s.SelectItem,{value:p,className:"text-xs",children:p[0].toUpperCase()+p.slice(1)},p))})]})]})]})]}):null}function hs(t){if(!t)return;const a={...t};if(a.xMetricKey||delete a.xMetricKey,a.yMetricKey||delete a.yMetricKey,a.radiusMetricKey||delete a.radiusMetricKey,a.labelKey||delete a.labelKey,a.groupKey||delete a.groupKey,a.enableGrouping===void 0&&delete a.enableGrouping,a.radiusScale||delete a.radiusScale,a.fixedRadius===void 0&&delete a.fixedRadius,a.minRadius===void 0&&delete a.minRadius,a.maxRadius===void 0&&delete a.maxRadius,Object.keys(a).length!==0)return a}function Hs(){var v,w,g,y,T,M,N,b,A,F,E,L;const t=s.useEditorStore(S=>S.card.preferences),a=s.useEditorStore(S=>S.card),n=s.useEditorStore(S=>S.card.type),r=s.useEditorStore(S=>S.isDevMode),{setCardPreferences:l,updateCardInFrame:d}=s.useEditorActions(),i=n==="bubble",c=n==="scatter",o=D.useMemo(()=>(t==null?void 0:t.bubbleScatterConfig)||{},[t==null?void 0:t.bubbleScatterConfig]),x=s.hasValidCardConfig(a==null?void 0:a.config)&&!r,h=D.useMemo(()=>{var S,P;return((P=(S=a==null?void 0:a.config)==null?void 0:S.metricColumns)==null?void 0:P.map($=>{const J=$.label||$.name||$.alias||"";return{value:J,label:J}}))||[]},[(v=a==null?void 0:a.config)==null?void 0:v.metricColumns]),p=D.useMemo(()=>{var S,P;return((P=(S=a==null?void 0:a.config)==null?void 0:S.groupByColumns)==null?void 0:P.map($=>{const J=$.label||$.name||$.alias||"";return{value:J,label:J}}))||[]},[(w=a==null?void 0:a.config)==null?void 0:w.groupByColumns]),k=D.useMemo(()=>o.enableGrouping!==void 0?o.enableGrouping:!r&&p.length>=2,[o.enableGrouping,r,p.length]),[m,f]=D.useState(k);D.useEffect(()=>{f(k)},[k]);const j=S=>{const P={...t||{},bubbleScatterConfig:S};l(P),a&&d({...a,preferences:P})},C=S=>{l(S),a&&d({...a,preferences:S})};D.useEffect(()=>{if(!t||h.length===0)return;const S={};let P=!1;if(!o.xMetricKey&&h[0]&&(S.xMetricKey=h[0].value,P=!0),!o.yMetricKey&&h[1]&&(S.yMetricKey=h[1].value,P=!0),i&&!o.radiusMetricKey&&h[2]&&(S.radiusMetricKey=h[2].value,P=!0),!o.labelKey&&p[0]&&(S.labelKey=p[0].value,P=!0),k&&!o.groupKey&&p[1]&&(S.groupKey=p[1].value,S.enableGrouping=!0,P=!0),P){const $=hs({...o,...S});j($)}},[h,p,o,t,l,i,k]);const I=S=>{const P=hs({...o,...S});j(P)},O=S=>{f(S),I({enableGrouping:S,groupKey:S?o.groupKey:void 0})};if(!i&&!c)return null;const R=i?s.Circle:s.ChartScatter;return e.jsxs(s.AccordionItem,{value:"bubble-scatter-config",children:[e.jsx(s.AccordionTrigger,{className:"py-2 text-sm",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(R,{className:"h-4 w-4"}),e.jsxs("span",{children:[i?"Bubble":"Scatter"," Configuration"]})]})}),e.jsxs(s.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(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{children:e.jsx(s.Info,{className:"h-3 w-3"})}),e.jsx(s.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(s.Label,{className:"text-xs",children:"Label Column"}),x?e.jsxs(s.Select,{value:o.labelKey||"",onValueChange:S=>I({labelKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select label column"})}),e.jsx(s.SelectContent,{children:p.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(ie,{className:"h-8 text-xs",placeholder:"Column name for labels",value:o.labelKey||"",onCommit:S=>I({labelKey:S})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Group points into series"}),e.jsx(s.SmallSwitch,{checked:m,onCheckedChange:O})]}),m&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Group By"}),x?e.jsxs(s.Select,{value:o.groupKey||"",onValueChange:S=>I({groupKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select group column"})}),e.jsx(s.SelectContent,{children:p.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(ie,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:o.groupKey||"",onCommit:S=>I({groupKey:S})})]})]}),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(s.Label,{className:"text-xs",children:"X Axis"}),x?e.jsxs(s.Select,{value:o.xMetricKey||"",onValueChange:S=>I({xMetricKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select X metric"})}),e.jsx(s.SelectContent,{children:h.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(ie,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:o.xMetricKey||"",onCommit:S=>I({xMetricKey:S})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Y Axis"}),x?e.jsxs(s.Select,{value:o.yMetricKey||"",onValueChange:S=>I({yMetricKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select Y metric"})}),e.jsx(s.SelectContent,{children:h.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(ie,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:o.yMetricKey||"",onCommit:S=>I({yMetricKey:S})})]}),i&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Radius"}),x?e.jsxs(s.Select,{value:o.radiusMetricKey||"",onValueChange:S=>I({radiusMetricKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select radius metric"})}),e.jsx(s.SelectContent,{children:h.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(ie,{className:"h-8 text-xs",placeholder:"Column name for radius",value:o.radiusMetricKey||"",onCommit:S=>I({radiusMetricKey:S})})]})]}),i&&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(s.Label,{className:"text-xs",children:"Scale Mode"}),e.jsxs(s.Select,{value:o.radiusScale||"sqrt",onValueChange:S=>I({radiusScale:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"sqrt",children:"Square Root (area-proportional)"}),e.jsx(s.SelectItem,{value:"linear",children:"Linear"}),e.jsx(s.SelectItem,{value:"fixed",children:"Fixed Size"})]})]})]}),o.radiusScale!=="fixed"&&e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Min Radius"}),e.jsx(ie,{className:"h-8 text-xs",type:"number",placeholder:"5",value:((g=o.minRadius)==null?void 0:g.toString())||"",onCommit:S=>I({minRadius:S?Number(S):void 0})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Max Radius"}),e.jsx(ie,{className:"h-8 text-xs",type:"number",placeholder:"30",value:((y=o.maxRadius)==null?void 0:y.toString())||"",onCommit:S=>I({maxRadius:S?Number(S):void 0})})]})]}),o.radiusScale==="fixed"&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs(s.Label,{className:"text-xs",children:["Fixed Radius: ",o.fixedRadius||10]}),e.jsx(s.Slider,{value:[o.fixedRadius||10],onValueChange:([S])=>I({fixedRadius:S}),min:3,max:30,step:1,className:"py-2"})]})]}),c&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Point Settings"}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(s.Label,{className:"text-xs",children:["Point Size: ",o.fixedRadius||5]}),e.jsx(s.Slider,{value:[o.fixedRadius||5],onValueChange:([S])=>I({fixedRadius:S}),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(s.SmallSwitch,{checked:((M=(T=t==null?void 0:t.xAxisConfig)==null?void 0:T.name)==null?void 0:M.enabled)??!1,onCheckedChange:S=>{var J,K,G,H;const P=o.xMetricKey||"X Axis",$=o.yMetricKey||"Y Axis";C({...t??{},xAxisConfig:{...t==null?void 0:t.xAxisConfig,name:{enabled:S,text:((K=(J=t==null?void 0:t.xAxisConfig)==null?void 0:J.name)==null?void 0:K.text)||P}},yAxisConfig:{...t==null?void 0:t.yAxisConfig,name:{enabled:S,text:((H=(G=t==null?void 0:t.yAxisConfig)==null?void 0:G.name)==null?void 0:H.text)||$}}})}})]}),((b=(N=t==null?void 0:t.xAxisConfig)==null?void 0:N.name)==null?void 0:b.enabled)&&e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"X Title"}),e.jsx(ie,{className:"h-8 text-xs",placeholder:o.xMetricKey||"X Axis",value:((F=(A=t==null?void 0:t.xAxisConfig)==null?void 0:A.name)==null?void 0:F.text)||"",onCommit:S=>{var P;C({...t??{},xAxisConfig:{...t==null?void 0:t.xAxisConfig,name:{...(P=t==null?void 0:t.xAxisConfig)==null?void 0:P.name,enabled:!0,text:S||o.xMetricKey||"X Axis"}}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Y Title"}),e.jsx(ie,{className:"h-8 text-xs",placeholder:o.yMetricKey||"Y Axis",value:((L=(E=t==null?void 0:t.yAxisConfig)==null?void 0:E.name)==null?void 0:L.text)||"",onCommit:S=>{var P;C({...t??{},yAxisConfig:{...t==null?void 0:t.yAxisConfig,name:{...(P=t==null?void 0:t.yAxisConfig)==null?void 0:P.name,enabled:!0,text:S||o.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const Dn=[{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 Js(){const t=s.useEditorStore(p=>p.card),a=s.useEditorStore(p=>{var k;return(k=p.card)==null?void 0:k.preferences}),{setCardPreferences:n}=s.useEditorActions(),r=(t==null?void 0:t.type)==="funnel",l=(a==null?void 0:a.funnelConfig)||{},d=l.percentMode??"percentOfTotal",i=l.shrinkFraction??1,c=l.labelThreshold??0,o=p=>{const k={...l,...p};n({...a||{},funnelConfig:k})},u=p=>{o({percentMode:p})},x=p=>{o({shrinkFraction:p[0]})},h=p=>{o({labelThreshold:p[0]})};return r?e.jsxs(s.AccordionItem,{value:"funnel-config",className:"border-none",children:[e.jsx(s.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(s.Filter,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Funnel Settings"})]})}),e.jsxs(s.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(s.Label,{className:"text-xs font-medium",children:"PERCENTAGE MODE"}),e.jsx(s.RadioGroup,{value:d,onValueChange:p=>u(p),className:"space-y-2",children:Dn.map(p=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:`funnel-${p.value}`,value:p.value,className:"mt-0.5"}),e.jsxs(s.Label,{htmlFor:`funnel-${p.value}`,className:"flex flex-col gap-0.5 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:p.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:p.description})]})]},p.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.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(s.Slider,{value:[i],onValueChange:x,min:0,max:1,step:.1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Full Shrink"})]}),e.jsxs("p",{className:"text-center text-xs text-muted-foreground",children:["Current: ",Math.round(i*100),"%"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.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(s.Slider,{value:[c],onValueChange:h,min:0,max:25,step:1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Hide Small"})]}),e.jsx("p",{className:"text-center text-xs text-muted-foreground",children:c===0?"Showing all labels":`Hide labels below ${c}%`})]})]})]}):null}function Mn(){const t=s.useEditorStore(a=>a.card);return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Chart Configuration"}),e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:[(t==null?void 0:t.type)==="funnel"&&e.jsx(Js,{}),(t==null?void 0:t.type)==="heatmap"&&e.jsx(Us,{}),(t==null?void 0:t.type)==="bullet"&&e.jsx(qs,{}),((t==null?void 0:t.type)==="bubble"||(t==null?void 0:t.type)==="scatter")&&e.jsx(Hs,{}),e.jsx(zs,{}),e.jsx($s,{}),e.jsx(Ks,{}),e.jsx(Gs,{})]})]})}const Ln=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT dimension, cohort, metric FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/tornado",children:"example"})," in the docs."]})]}),Fn=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT y-axis, label, range-from, range-to, range-value FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/range",children:"example"})," in the docs."]})]}),On=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT text FROM table limit 1"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/text",children:"example"})," in the docs."]})]});function Rn(){const t=s.useEditorStore(n=>n.card.type);function a(n){const r=["kpi","table","text","map","custom"],l=d=>r.includes(n)?d:e.jsxs(e.Fragment,{children:[d,e.jsx(Mn,{})]});switch(n){case"stackedBar":case"stackedLine":return l(e.jsx(vn,{}));case"tornado":case"pyramid":return l(e.jsx(Oe,{docContent:Ln,cardType:n}));case"kpi":return e.jsx(hn,{});case"line":case"bar":return l(e.jsx(rn,{cardType:n}));case"range":return l(e.jsx(Oe,{docContent:Fn,cardType:n}));case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return l(e.jsx(Oe,{cardType:n}));case"bubble":case"scatter":return l(e.jsx(ln,{cardType:n}));case"table":return e.jsx(yn,{cardType:n});case"text":return e.jsx(Oe,{docContent:On,cardType:n,suffix:"Visual"});case"map":return e.jsx(jn,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(Fs,{})});default:return l(e.jsx(dn,{}))}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[a(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Bn(){const t=D.useRef(null),a=D.useRef(null),n=s.useEditorStore(l=>l.isShowingVisual),r=s.useEditorStore(l=>l.showAIDialog);return D.useEffect(()=>{var l,d,i,c;r?((l=t.current)==null||l.resize(0),(d=a.current)==null||d.resize(0)):((i=t.current)==null||i.resize(25),(c=a.current)==null||c.resize(25))},[r]),e.jsxs(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(Vt,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:n&&!r?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:t,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(Rn,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(os,{})})]}):e.jsx(os,{})})]})}function Vn(t){var ce;s.useAIInteractionStore(z=>z.currentAIContext);const[a,n]=D.useState(""),[r,l]=D.useState(null),{authToken:d,tokenProps:i}=s.useSemaphorContext(),c=s.useEditorStore(z=>{var ee;return(ee=z==null?void 0:z.card)==null?void 0:ee.sql}),o=s.useEditorStore(z=>z.isDevMode),u=s.useEditorStore(z=>{var ee;return(ee=z==null?void 0:z.card)==null?void 0:ee.python}),{setCardPython:x,setCardSql:h,setRunSql:p,switchCardType:k,setQueryConfig:m}=s.useEditorActions(),f=s.useEditorStore(z=>z.currentAssitantScope)||[],j=s.useEditorStore(z=>z.userInputForAI),C=s.useEditorStore(z=>z.triggerAIRun),I=s.useEditorStore(z=>z.card),O=s.useEditorStore(z=>z.selectedDatabaseName),R=s.useEditorStore(z=>z.selectedTableName),v=s.useEditorStore(z=>z.selectedConnectionId),w=s.useEditorStore(z=>z.selectedSchemaName),g=s.useDashboardStore(z=>z.dashboard.aiScopeTables),{errorMessage:y,refetch:T,data:M}=s.useDashboardCardQuery(I),{setTriggerAIRun:N,setCurrentAssitantScope:b,setCardConfig:A}=s.useEditorActions(),{selectedDatamodelName:F,connectionType:E,selectedDatamodelId:L}=s.useEditorAside(),S=(ce=s.useDashboardQuery().data)==null?void 0:ce.assistantProfileId,{messages:P,setMessages:$,regenerate:J,error:K,sendMessage:G,status:H,addToolResult:B,stop:U,clearError:V}=s.useChat({transport:new s.DefaultChatTransport({api:`${i.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${d==null?void 0:d.accessToken}`}),body:()=>{const z=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:S,isDevMode:o,aiContext:z.currentAIContext,reasoningEffort:z.reasoningEffort,showReasoning:z.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:z,body:ee})=>({body:{...ee,messages:s.cleanupIncompleteMessages(z)}})}),onError:z=>{var ee;if(z.name==="AbortError"||(ee=z.message)!=null&&ee.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)");return}console.error("[Editor Assistant] Stream error:",z)},onToolCall:W,onFinish({isAbort:z,isDisconnect:ee,isError:de}){n(""),console.log(z?"[Editor Assistant] Stream aborted by user":ee?"[Editor Assistant] Stream disconnected (network error)":de?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully")}});D.useEffect(()=>{C&&j&&(G({role:"user",parts:[{type:"text",text:j}]}),N(!1))},[C,j,G,N]);async function W({toolCall:z}){var ee,de,ue,we,me,je,xe,be,ke,fe,Te,Ee,Ae,Ie,ve,ye;if(["createChartFromSql","createForecast"].includes(z.toolName)){const Q=((ee=z.input)==null?void 0:ee.sql)??((de=z.args)==null?void 0:de.sql),ae=((ue=z.input)==null?void 0:ue.python)??((we=z.args)==null?void 0:we.python),re=((me=z.input)==null?void 0:me.chartType)??((je=z.args)==null?void 0:je.chartType);k(re),h(Q),x(ae),p(!0),B({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(z.toolName==="getUserSql"){if(!c){B({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"error",message:"No SQL found"}});return}B({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",sql:c,python:u||""}})}else if(z.toolName==="generateQueryConfig"){n("Generating query config...");const Q=((xe=z.input)==null?void 0:xe.chartType)??((be=z.args)==null?void 0:be.chartType),ae=((ke=z.input)==null?void 0:ke.queryConfig)??((fe=z.args)==null?void 0:fe.queryConfig);((Te=z.input)==null?void 0:Te.cardConfig)??((Ee=z.args)==null||Ee.cardConfig),k(Q),A(ae),h(void 0),x(void 0);const re=await T();if((Ae=re==null?void 0:re.data)!=null&&Ae.error){B({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"error",queryConfig:ae,message:(Ie=re==null?void 0:re.data)==null?void 0:Ie.error.message}});return}if((ve=re==null?void 0:re.data)!=null&&ve.records){B({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",queryConfig:ae,message:"The data has been visualized"}});return}B({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",queryConfig:ae,message:"The data has been visualized",records:(ye=re==null?void 0:re.data)==null?void 0:ye.records}})}else n("Analyzing...")}function X(z){const ee=s.removeFromScopeArray(f,z);se(ee)}function se(z){const ee=s.sanitizeAIScope(z);b(ee),$(de=>[...de,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(ee)}`}]}])}function _(){const z={databaseName:O||"",schemaName:w||"",tableName:R||"",datamodelId:L||"",datamodelName:s.resolveDatamodelName(F),connectionId:v||"",connectionType:E||""},ee=s.dedup([...f,z]);se(ee)}function te(){const z={databaseName:O||"",schemaName:w||"",tableName:R||"",datamodelName:s.resolveDatamodelName(F),connectionId:v||"",connectionType:E||"",datamodelId:L||""};if(!s.isInAiScopeArray([...g||[],...f],z)||f.length===0){const de=s.dedup([...g||[],...f,z]).filter(ue=>ue.connectionId===z.connectionId);se(de)}}const Y=!["ready","error"].includes(H),le=s.getErrorMessage(K);return{messages:P,setMessages:$,sendMessage:G,regenerate:J,isLoading:Y,handleSetAIScope:te,handleAddCurrentTableToScope:_,removeFromCurrentSelections:X,currentAssitantScope:f,setCurrentAssitantScope:b,stop:U,status:H,toolStatus:a,llmUsage:r,onFinish:t,errorMessage:le,clearError:V}}const Pn=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function ps({isFullscreen:t,onFullscreenChange:a,fullscreenContainer:n}){const r=D.useRef(null),[l,d]=D.useState(!1),[i,c]=D.useState(s.isDevEnv),[o,u]=D.useState(!1),[x,h]=D.useState(!1),[p,k]=D.useState(!1),m=t??p,f=s.useCurrentAIContext(),{setCurrentAIContext:j}=s.useAIActions(),{clearQueue:C}=s.useQueueActions(),{clearFileAttachments:I}=s.useFileActions(),O=s.useFileAttachments("editor"),R=s.useDashboardStore(Q=>Q.dashboard.aiContext),v=s.useEditorStore(Q=>Q.card.dataSource),w=s.useEditorStore(Q=>Q.actions.setCardSql),g=s.useEditorStore(Q=>Q.actions.setRunSql),y=s.useEditorStore(Q=>Q.showAIDialog),T=s.useDashboardStore(Q=>Q.handleOpenAssistantProfile),{setShowAIDialog:M,setCardPython:N}=s.useEditorActions(),{setDataSource:b}=s.useEditorActions(),{assistantProfile:A}=s.useAssistantProfile(),{messages:F,setMessages:E,sendMessage:L,isLoading:S,stop:P,status:$,llmUsage:J,errorMessage:K,clearError:G}=Vn(),[H,B]=D.useState(""),U=Q=>{B(Q.target.value)},V=Q=>{Q.preventDefault();const ae=H.trim();if(!ae&&O.length===0)return;const re=[];ae&&re.push({type:"text",text:ae}),O.forEach(Ne=>{Ne.data&&re.push({type:"file",mediaType:Ne.type,filename:Ne.name,url:`data:${Ne.type};base64,${Ne.data}`})}),L({role:"user",parts:re}),B(""),I("editor"),ee({force:!0})},{visibleMessages:W,hasMoreMessages:X,totalMessageCount:se,loadMoreMessages:_,resetMessageWindow:te}=s.useMessageWindow(F,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:Y,isAtBottom:le,hasNewMessages:ce,newMessageCount:z,scrollToBottom:ee,handleScroll:de,resetNewMessageCount:ue}=s.useAutoScroll(W,{threshold:50,behavior:"smooth",isStreaming:S});D.useEffect(()=>{var Q;y&&((Q=r.current)==null||Q.focus(),j({selectedEntities:(v==null?void 0:v.selectedEntities)||[]}))},[y,v,j]),s.useAutoSubmitQueue({assistantType:"editor",status:$,isLoading:S,sendMessage:L});const{hasActiveTools:we}=s.useActiveToolStatus(F),me=D.useCallback(Q=>{a==null||a(Q),t===void 0&&k(Q)},[t,a]);D.useEffect(()=>{if(!m)return;function Q(ae){ae.key==="Escape"&&me(!1)}return window.addEventListener("keydown",Q),()=>{window.removeEventListener("keydown",Q)}},[m,me]);const je=D.useCallback(Q=>{L({role:"user",parts:[{type:"text",text:Q}]}),ee({force:!0})},[L,ee]),xe=D.useCallback(async()=>{const Q=JSON.stringify(F??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(Q),s.ue.success("Conversation copied")}catch(ae){console.error("Failed to copy conversation",ae),s.ue.error("Unable to copy conversation")}},[F]),be=D.useCallback(()=>{me(!m)},[m,me]);function ke(Q,ae){ae==="sql"?(w(Q),g(!0)):ae==="python"&&(N(Q),g(!0))}function fe(){f.selectedEntities.length===0&&j({selectedEntities:(R==null?void 0:R.selectedEntities)||[]})}function Te(Q){fe();const ae={role:"user",parts:[{type:"text",text:Q.title+" "+Q.subtitle}]};L(ae)}function Ee(Q){fe(),L({role:"user",parts:[{type:"text",text:Q}]})}function Ae(){return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuLabel,{children:"Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx(s.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:d,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:i,onCheckedChange:c,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:u,children:"System Message"})]})]})}function Ie(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const ve=(H==null?void 0:H.length)===0&&(F==null?void 0:F.filter(Q=>Q.role==="user").length)===0,ye=e.jsxs("div",{"data-role":"editor-assistant",className:s.cn("flex h-full w-full flex-col justify-between px-6 py-4",m&&"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:[Ie(),T&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:T,children:(A==null?void 0:A.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[Ae(),i&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:xe,children:"Copy Conversation"}),e.jsx(s.IconButton,{tooltip:m?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:be,children:m?e.jsx(s.Minimize2,{className:"size-4"}):e.jsx(s.Maximize2,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{E([]),C("editor"),G(),te()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{M(!1)},children:e.jsx(s.X,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:Y,className:"mt-2 flex w-full grow basis-0",onScroll:de,children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[X&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:_,className:"text-xs",children:["Load ",Math.min(5,se-W.length)," ","more messages (",se-W.length," ","hidden)"]})}),e.jsx(s.PrintMessages,{messages:W,showTools:i,handleRun:ke,showSystemMessage:o,onQuickReply:je,disableQuickReplies:S}),!we&&e.jsx(s.AssistantStatus,{status:$,errorMessage:K})]})}),y&&!le&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{ee({force:!0}),ue()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),ce&&z>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:z>9?"9+":z})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[ve&&!A&&e.jsx(s.Placeholders,{onClick:Te,placeholders:Pn}),e.jsx("div",{children:ve&&A&&e.jsx(s.SeedQuestions,{seedQuestions:A.seedQuestions||[],handleSeedQuestionClick:Ee})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:r,setInput:B,stop:P,input:H,handleInputChange:U,handleSubmit:Q=>{fe(),V(Q),ee({force:!0})},isLoading:S,status:$,assistantType:"editor",onFocus:()=>{}})]}),J&&l&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",J.inputTokens," prompt tokens, ",J.outputTokens," ","completion tokens, ",J.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(v==null?void 0:v.selectedEntities)||[],open:x,onOpenChange:h,dataSource:v||s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]});return m&&n?nt.createPortal(e.jsx("div",{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:e.jsx("div",{className:"flex h-full w-full",children:ye})}),n):ye}function zn({selectedChart:t,onChartChange:a}){const[n,r]=D.useState(!1),l=s.useEditorStore(c=>c.card),d=()=>{var o;if(t==="custom")return((o=l==null?void 0:l.customCardPreferences)==null?void 0:o.componentName)||"Custom Visual";const c=s.chartTypes.find(u=>u.id===t);return(c==null?void 0:c.label)||"Select chart type"},i=()=>{var o;if(t==="custom"){const u=(o=l==null?void 0:l.customCardPreferences)==null?void 0:o.componentName;if(u){const x=s.getAutoDetectedChartIcon(u);return x||e.jsx(s.ChartIcon,{chartName:u,isCustom:!0,className:"h-4 w-4"})}return e.jsx(s.Shapes,{className:"h-4 w-4"})}const c=s.chartTypes.find(u=>u.id===t);if(c){const u=c.icon;return e.jsx(u,{className:"h-4 w-4"})}return e.jsx(s.Shapes,{className:"h-4 w-4"})};return e.jsx("div",{children:e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[i(),e.jsx("span",{children:d()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[360px] p-3",align:"start",onOpenAutoFocus:c=>c.preventDefault(),children:e.jsx(Ds,{onChartSelect:c=>a(c),onClose:()=>r(!1)})})]})})}let $n=(t=21)=>crypto.getRandomValues(new Uint8Array(t)).reduce((a,n)=>(n&=63,n<36?a+=n.toString(36):n<62?a+=(n-26).toString(36).toUpperCase():n>62?a+="-":a+="_",a),"");const Be=[{id:"sum",label:"Sum",symbol:"+",description:"Add two metrics together",template:()=>"({field_0} + {field_1})",requiresTwoInputs:!0},{id:"difference",label:"Difference",symbol:"−",description:"Subtract one metric from another",template:()=>"({field_0} - {field_1})",requiresTwoInputs:!0},{id:"product",label:"Product (Multiplication)",symbol:"×",description:"Multiply two metrics",template:()=>"({field_0} * {field_1})",requiresTwoInputs:!0},{id:"ratio",label:"Ratio",symbol:"÷",description:"Divide one metric by another",template:()=>"({field_0} / NULLIF({field_1}, 0))",requiresTwoInputs:!0},{id:"change",label:"Change",symbol:"Δ",description:"Calculate percentage change from A to B",template:()=>"(({field_1} - {field_0}) / NULLIF({field_0}, 0))",requiresTwoInputs:!0},{id:"percentage",label:"Percentage",symbol:"%",description:"Calculate (A / B) × 100",template:()=>"(({field_0} / NULLIF({field_1}, 0)) * 100)",requiresTwoInputs:!0},{id:"scale",label:"Scale (Multiply by Factor)",symbol:"×n",description:"Multiply a metric by a constant factor",template:()=>"({field_0} * {constant})",requiresTwoInputs:!1},{id:"custom",label:"Custom Expression",symbol:"{}",description:"Drag fields to create custom expression with tokens",requiresTwoInputs:!1,allowsCustomExpression:!0}];function Kn(t,a,n,r,l,d,i,c,o){const u=Be.find(f=>f.id===a);if(!u)throw new Error(`Unknown operation: ${a}`);let x,h=[],p;if(a==="custom"){if(!(c!=null&&c.trim()))throw new Error("Custom expression is required");x=c.trim()}else if(a==="scale"){if(!n)throw new Error("Metric A is required for scale operation");if(o===void 0||o===0)throw new Error("Constant factor is required for scale operation");x=u.template().replace("{constant}",String(o)),h=[n],p=o}else{if(!n||!r)throw new Error("Metrics A and B are required for standard operations");x=u.template(),h=[n,r]}const k={operation:a,inputFields:h,...p!==void 0&&{constant:p}};return{id:i||`calc_${$n(10)}`,name:t.toLowerCase().replace(/\s+/g,"_"),label:t,alias:t.toLowerCase().replace(/\s+/g,"_"),qualifiedFieldName:t.toLowerCase().replace(/\s+/g,"_"),dataType:"number",role:"metric",aggregate:"SUM",expression:x,calculatedFormula:k,entityId:d,entityName:s.CALCULATED_FIELD_ENTITY_MARKER,entityType:"table",description:`Calculated field: ${t}`}}function fs(t){var r,l;const a=Be.find(d=>d.id===t.operation);if(!a)return"Unknown operation";if(t.operation==="custom")return"Custom expression";if(t.operation==="scale"){const d=((r=t.inputFields[0])==null?void 0:r.label)||((l=t.inputFields[0])==null?void 0:l.name)||"A",i=t.constant??1;return`${d} × ${i}`}return t.inputFields.map(d=>d.label||d.name).join(` ${a.symbol} `)}const Qe=({dataType:t})=>s.getFieldIconComponent(t);function Gn({aliasTemplate:t,onAliasTemplateChange:a}){var o;const[n,r]=D.useState(t),[l,d]=D.useState(!1),i=(o=s.useEditorStore(u=>{var x;return(x=u.card.config)==null?void 0:x.pivotByColumns}))==null?void 0:o[0],c=i?`e.g. Min Sales in {{${i.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.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(s.Input,{placeholder:c,value:l?n:t,onChange:u=>{r(u.target.value),d(!0)},onFocus:()=>d(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&l&&n!==t?(a(n),d(!1)):u.key==="Escape"&&(r(t),d(!1))},"aria-label":"Edit alias template"}),l&&n!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{a(n),d(!1)},children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(t),d(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function qn({valueAliases:t,onValueAliasesChange:a}){const[n,r]=D.useState(null),[l,d]=D.useState(""),[i,c]=D.useState(""),o=()=>{a({...t,"":""})},u=h=>{const p={...t};delete p[h],a(p)},x=h=>{const p={...t};delete p[h],p[l]=i,a(p),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(t).map(([h,p],k)=>e.jsx("div",{className:"flex items-center gap-2",children:n===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input,{placeholder:"Value key",value:l,onChange:m=>d(m.target.value),className:"h-8 w-24 text-xs",onPointerDown:m=>m.stopPropagation(),onKeyDown:m=>{m.key==="Enter"?x(h):m.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input,{placeholder:"Alias label",value:i,onChange:m=>c(m.target.value),className:"h-8 w-24 text-xs",onPointerDown:m=>m.stopPropagation(),onKeyDown:m=>{m.key==="Enter"?x(h):m.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>x(h),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),d(h),c(p)},"aria-label":"Edit value alias key"}),e.jsx(s.Input,{placeholder:"Alias label",value:p,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),d(h),c(p)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+k)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:o,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function Un({column:t}){const a=s.useEditorStore(o=>o.card.type),n=s.useEditorStore(o=>{var u,x;return(x=(u=o.card)==null?void 0:u.config)==null?void 0:x.metricColumns}),r=(n==null?void 0:n.map(o=>o.label))||[],l=r==null?void 0:r.find(o=>o===t.label||o===t.name),d=l?r.indexOf(l):-1;function i(){return e.jsx("div",{className:"pr-1",children:l&&e.jsx(Bs,{idx:d,col:l,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function c(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(Vs,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&i(),["pie","doughnut"].includes(a)&&c()]})}function Hn({field:t,searchQuery:a="",limit:n=500}){const{authToken:r,tokenProps:l}=s.useSemaphorContext(),d=s.useEditorStore(u=>u.card),i=d==null?void 0:d.dataSource,c=["attribute-values",t.entityName,t.name,a,n],o=s.useQuery({queryKey:c,queryFn:async()=>{if(!(i!=null&&i.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const u={groupByColumns:[{...t,role:"groupby"}],metricColumns:[],filters:a?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:a}],groups:[]}:void 0,rowLimit:n},x={connection_id:i.connectionId,cardConfig:u,cardDataSource:i,cache_config:s.getCacheConfig({card:d})};console.log("requestBody",x);const h=await s.postRequestRegular(`${l.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",x);if(h!=null&&h.error)return console.error("Error fetching attribute values:",h.error),[];const p=t.name;return((h==null?void 0:h.records)||[]).map(m=>{const f=m[p]||m[t.alias||p]||m[t.label];return{id:f||"",value:f||"",label:String(f||"(empty)")}})}catch(u){return console.error("Error fetching attribute values:",u),[]}},enabled:!!t&&!!(i!=null&&i.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:o.data||[],isLoading:o.isLoading,isFetching:o.isFetching,isError:o.isError,error:o.error,refetch:o.refetch}}function _s({open:t,onOpenChange:a,availableFields:n,existingFilters:r,editingCondition:l,onSave:d}){var O,R;const i=!!l,[c,o]=D.useState(i?"values":"fields"),[u,x]=D.useState(""),[h,p]=D.useState({id:(l==null?void 0:l.id)||s.v4(),field:(l==null?void 0:l.field)||null,selectedValues:l?Array.isArray(l.value)?l.value:[l.value]:[]}),k=n.filter(v=>{var g;return i?!1:!((g=r==null?void 0:r.conditions)==null?void 0:g.some(y=>y.field.id===v.id))&&v.label.toLowerCase().includes(u.toLowerCase())}),m=v=>{p({...h,field:v}),o("values")},f=()=>{if(h.field&&h.selectedValues.length>0){const v={id:h.id,field:h.field,operator:"in",value:h.selectedValues};let w;if(i){const g=((r==null?void 0:r.conditions)||[]).map(y=>y.id===l.id?v:y);w={...r,conditions:g}}else{const g=(r==null?void 0:r.conditions)||[];w={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...g,v],groups:[]}}d(w),a(!1)}},j=()=>{if(!i||!l)return;const v=((r==null?void 0:r.conditions)||[]).filter(w=>w.id!==l.id);if(v.length>0){const w={...r,conditions:v};d(w)}else d(void 0);a(!1)},C=v=>{p({...h,selectedValues:v})},I=()=>{i&&l?(p({id:l.id,field:l.field,selectedValues:Array.isArray(l.value)?l.value:[l.value]}),o("values")):(p({id:s.v4(),field:null,selectedValues:[]}),o("fields")),x("")};return D.useEffect(()=>{t&&I()},[t,i,l]),e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsx(s.DialogHeader,{children:e.jsx(s.DialogTitle,{children:i?`Edit Filter: ${(O=h.field)==null?void 0:O.label}`:c==="fields"?"Select Field to Filter":`Select Values for ${(R=h.field)==null?void 0:R.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!i&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&c==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.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(v=>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:[v.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(v.value)?`${v.value.length} values`:String(v.value)})]},v.id))})]}),c==="fields"&&!i?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search fields...",value:u,onChange:v=>x(v.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:k.map(v=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>m(v),children:[e.jsx(Qe,{dataType:s.getDataType(v.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:v.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[v.entityName,".",v.name]})]})]},v.id))}),k.length===0&&u&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',u,'"']}),k.length===0&&!u&&n.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(Jn,{field:h.field,selectedValues:h.selectedValues,onValuesChange:C,onBack:i?void 0:()=>o("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:i?e.jsx(s.Button,{variant:"destructive",onClick:j,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:I,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:f,disabled:!h.field||h.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function Jn({field:t,selectedValues:a,onValuesChange:n,onBack:r}){const[l,d]=D.useState(""),{values:i,isLoading:c,isFetching:o}=Hn({field:t,searchQuery:l,limit:500}),u=l?i.filter(p=>String(p.value).toLowerCase().includes(l.toLowerCase())):i,x=p=>{const k=a.includes(p);n(k?a.filter(m=>m!==p):[...a,p])},h=()=>{a.length===u.length&&u.length>0?n([]):n(u.map(p=>p.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:r,children:"← Back"}),e.jsxs(s.Label,{className:"text-sm font-medium",children:["Select values for ",t.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search values...",value:l,onChange:p=>d(p.target.value),className:"pl-10"})]}),c||o?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(s.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(s.Checkbox,{checked:a.length===u.length&&u.length>0,onCheckedChange:h}),e.jsxs(s.Label,{className:"text-sm",children:["Select All (",u.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:u.map(p=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>x(p.value),children:[e.jsx(s.Checkbox,{checked:a.includes(p.value),onCheckedChange:()=>x(p.value)}),e.jsx(Je,{className:"text-sm",children:p.label})]},p.id))})]})]})}function Qs({open:t,onOpenChange:a,availableMetrics:n,existingField:r,onSave:l,cardId:d}){const[i,c]=D.useState(""),[o,u]=D.useState("ratio"),[x,h]=D.useState(null),[p,k]=D.useState(null),[m,f]=D.useState(1),[j,C]=D.useState(""),[I,O]=D.useState({format:"number",decimalPlaces:2}),[R,v]=D.useState({}),w=Be.find(b=>b.id===o),g=n.find(b=>b.id===x),y=n.find(b=>b.id===p);D.useEffect(()=>{if(r&&t)if(c(r.label),r.calculatedFormula)if(u(r.calculatedFormula.operation),r.calculatedFormula.operation==="custom")C(r.expression||"");else if(r.calculatedFormula.operation==="scale"){const b=r.calculatedFormula.inputFields;if(b.length>=1){const A=n.find(F=>F.qualifiedFieldName===b[0].qualifiedFieldName);h((A==null?void 0:A.id)||null)}r.calculatedFormula.constant!==void 0&&f(r.calculatedFormula.constant)}else{const b=r.calculatedFormula.inputFields;if(b.length>=2){const A=n.find(E=>E.qualifiedFieldName===b[0].qualifiedFieldName),F=n.find(E=>E.qualifiedFieldName===b[1].qualifiedFieldName);h((A==null?void 0:A.id)||null),k((F==null?void 0:F.id)||null)}}else u("custom"),C(r.expression||"")},[r,t,n]);const T=()=>{const b={};return i.trim()||(b.name="Name is required"),o==="custom"?j.trim()||(b.customExpression="Custom expression is required"):o==="scale"?(x||(b.inputA="Please select a metric for input A"),(isNaN(m)||m===0)&&(b.constantFactor="Please enter a valid non-zero number"),r&&x===r.id&&(b.circular="Cannot reference the field being edited")):(x||(b.inputA="Please select a metric for input A"),p||(b.inputB="Please select a metric for input B"),x===p&&(b.inputs="Inputs A and B must be different metrics"),r&&(x===r.id||p===r.id)&&(b.circular="Cannot reference the field being edited")),v(b),Object.keys(b).length===0},M=()=>{if(!T())return;const b=Kn(i,o,g||null,y||null,I,d,r==null?void 0:r.id,o==="custom"?j:void 0,o==="scale"?m:void 0);l(b),N()},N=()=>{c(""),u("ratio"),h(null),k(null),f(1),C(""),v({}),a(!1)};return e.jsxs(s.Dialog,{modal:!1,open:t,onOpenChange:a,children:[t&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-w-md max-h-[90vh] overflow-y-auto",onInteractOutside:b=>{b.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsxs(s.DialogTitle,{children:[r?"Edit":"Create"," Calculated Metric"]}),e.jsx(s.DialogDescription,{children:"Combine existing metrics to create a new calculated field"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"name",children:"Name"}),e.jsx(s.Input$1,{id:"name",value:i,onChange:b=>c(b.target.value),placeholder:"e.g., Profit Margin",className:R.name?"border-red-500":""}),R.name&&e.jsx("p",{className:"text-xs text-red-500",children:R.name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"operation",children:"Outcome is"}),e.jsxs(s.Select,{value:o,onValueChange:b=>{u(b),b==="custom"?(h(null),k(null)):o==="custom"&&C("")},children:[e.jsx(s.SelectTrigger,{id:"operation",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"CALCULATED"}),Be.map(b=>e.jsx(s.SelectItem,{value:b.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-sm",children:b.symbol}),e.jsx("span",{children:b.label})]})},b.id))]})})]}),w&&e.jsx("p",{className:"text-xs text-muted-foreground",children:w.description})]}),o==="custom"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"customExpression",children:"SQL Expression"}),e.jsx(s.Textarea,{id:"customExpression",value:j,onChange:b=>C(b.target.value),placeholder:"e.g., CASE WHEN revenue > 1000 THEN revenue - cost ELSE 0 END",className:s.cn("font-mono text-sm",R.customExpression&&"border-red-500"),rows:4}),R.customExpression&&e.jsx("p",{className:"text-xs text-red-500",children:R.customExpression}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Write a SQL expression using column names from your data source"})]}):e.jsxs("div",{className:"rounded-md bg-muted p-3 font-mono text-sm",children:["= ",x&&g?g.label:"A"," ",w==null?void 0:w.symbol," ",p&&y?y.label:"B"]}),o!=="custom"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"inputA",children:"Where"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded bg-muted font-mono text-sm font-medium",children:"A"}),e.jsxs(s.Select,{value:x||"",onValueChange:h,children:[e.jsx(s.SelectTrigger,{id:"inputA",className:R.inputA?"border-red-500":"",children:e.jsx(s.SelectValue,{placeholder:"+ Choose metric"})}),e.jsx(s.SelectContent,{children:n.filter(b=>!s.isCalculatedMetric(b)||b.id!==(r==null?void 0:r.id)).map(b=>e.jsxs(s.SelectItem,{value:b.id,children:[b.label||b.name,b.aggregate&&` (${b.aggregate})`]},b.id))})]})]}),R.inputA&&e.jsx("p",{className:"text-xs text-red-500",children:R.inputA})]}),o!=="custom"&&o!=="scale"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded bg-muted font-mono text-sm font-medium",children:"B"}),e.jsxs(s.Select,{value:p||"",onValueChange:k,children:[e.jsx(s.SelectTrigger,{id:"inputB",className:R.inputB?"border-red-500":"",children:e.jsx(s.SelectValue,{placeholder:"+ Choose metric"})}),e.jsx(s.SelectContent,{children:n.filter(b=>!s.isCalculatedMetric(b)||b.id!==(r==null?void 0:r.id)).map(b=>e.jsxs(s.SelectItem,{value:b.id,children:[b.label||b.name,b.aggregate&&` (${b.aggregate})`]},b.id))})]})]}),R.inputB&&e.jsx("p",{className:"text-xs text-red-500",children:R.inputB})]}),o==="scale"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"constantFactor",children:"Multiplication Factor"}),e.jsx(s.Input$1,{id:"constantFactor",type:"number",step:"any",value:m,onChange:b=>f(parseFloat(b.target.value)||0),placeholder:"e.g., 0.15",className:R.constantFactor?"border-red-500":""}),R.constantFactor&&e.jsx("p",{className:"text-xs text-red-500",children:R.constantFactor}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Enter the constant value to multiply the metric by (e.g., 0.15 for 15%)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"format",children:"Format"}),e.jsxs(s.Select,{value:I.format,onValueChange:b=>O({...I,format:b}),children:[e.jsx(s.SelectTrigger,{id:"format",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsxs(s.SelectItem,{value:"number",children:["Decimal (",I.decimalPlaces,")"]}),e.jsx(s.SelectItem,{value:"currency",children:"Currency"}),e.jsx(s.SelectItem,{value:"percent",children:"Percentage"})]})]})]}),(R.inputs||R.circular)&&e.jsxs(s.Alert,{variant:"destructive",children:[e.jsx(s.CircleAlert,{className:"h-4 w-4"}),e.jsx(s.AlertDescription,{children:R.inputs||R.circular})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:N,children:"Cancel"}),e.jsxs(s.Button,{onClick:M,children:[r?"Update":"Create"," Metric"]})]})]})]})}function _n({field:t,zone:a,index:n,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:d=!1,cardType:i}){var We,Xe,Ze,es,ss;const{attributes:c,listeners:o,setNodeRef:u,transform:x,transition:h,isDragging:p}=s.useSortable({id:t.id}),k=s.useEditorStore(q=>q.card),{updateLabel:m,handleAggregationChange:f,handleDateFormatChange:j,handleGranularityChange:C,handleAliasTemplateChange:I,handleValueAliasesChange:O,removeField:R,handleKpiComparisonTypeChange:v,handleKpiShowTrendlineChange:w,handleKpiTrendlineWindowChange:g,handleKpiTrendlineGranularityChange:y,handleKpiTargetValueChange:T}=s.useFieldManagement(k),[M,N]=D.useState(!1),[b,A]=D.useState(!1),[F,E]=D.useState(!1),[L,S]=D.useState(null),[P,$]=D.useState(t.dateFormat||"YYYY-MM-DD"),[J,K]=D.useState(t.customFormat||""),[G,H]=D.useState(!!t.customFormat),[B,U]=D.useState(t.granularity||"day"),[V,W]=D.useState(t.aliasTemplate||""),[X,se]=D.useState(t.valueAliases||{}),[_,te]=D.useState((We=t.parameters)==null?void 0:We.filters),Y=q=>{q==="custom"?H(!0):(H(!1),$(q),a==="groupBy"&&j(n,q,""))},le=q=>{K(q),a==="groupBy"&&j(n,"custom",q)},ce=q=>{var oe;U(q);const Z=(oe=s.getDateFormatOptionsForGranularity(q)[0])==null?void 0:oe.value;Z&&!G&&($(Z),a==="groupBy"&&j(n,Z,"")),a==="groupBy"&&C(n,q)},z=q=>{W(q),a==="metrics"&&I(n,q)},ee=q=>{se(q),a==="metrics"&&O(n,q)},de=q=>{m(a,n,q)},ue=q=>{var ne;if(te(q),a==="metrics"){const Z={...t,parameters:{...t.parameters,filters:q}},oe=[...((ne=k.config)==null?void 0:ne.metricColumns)||[]];oe[n]=Z,s.useEditorStore.getState().actions.updateCardConfig(k.id,{metricColumns:oe})}A(!1)},we=()=>{R(a,n)},me={transform:s.CSS.Transform.toString(x),transition:h},je=s.getDataType(t.dataType),xe=je==="date",be=i==="kpi",ke=s.getDateFormatOptionsForGranularity(B),fe=a!=="pivotBy",Te=xe&&a==="groupBy"&&(!be||((Xe=k.config)==null?void 0:Xe.comparisonType)==="start_vs_end"),Ee=!be&&xe&&a==="groupBy",Ae=i&&s.COMPARISON_SUPPORTED_CHART_TYPES.includes(i)&&xe&&a==="groupBy",Ie=i==="kpi"&&xe&&a==="groupBy",ve=i&&i!=="pivotTable"&&a==="metrics"&&((Ze=k.config)==null?void 0:Ze.comparisonType)==="target",ye=a==="metrics",Q=()=>{const q=t,ne=a==="metrics"&&s.isCalculatedMetric(q);return e.jsxs("div",{className:"space-y-1",children:[!ne&&e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:Z=>{Z.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),ne&&q.calculatedFormula&&e.jsxs("div",{title:fs(q.calculatedFormula),onPointerDown:Z=>{Z.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:["= ",fs(q.calculatedFormula)]})]})},ae=()=>fe?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(pe,{value:t.label??"",onSave:de,placeholder:"Display label...",type:"text"})]}):null,re=()=>Te?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(s.Select,{value:B,onValueChange:ce,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsx(s.SelectContent,{children:["day","week","month","quarter","year"].map(q=>e.jsx(s.SelectItem,{className:"text-xs",value:q,children:s.toTitleCase(q)},q))})]})]}):null,Ne=()=>Ee?e.jsxs(e.Fragment,{children:[re(),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Date Format"}),e.jsxs(s.Select,{value:G?"custom":P,onValueChange:Y,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select date format..."})}),e.jsx(s.SelectContent,{children:ke.map(q=>e.jsx(s.SelectItem,{className:"text-xs",value:q.value,children:q.label},q.value))})]}),G&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(s.Input,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:J,onChange:q=>{q.stopPropagation(),le(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,Ws=()=>{var Z,oe,Ce,Me,ge;const q=Ae,ne=Ie;return!q&&!ne?null:e.jsxs(e.Fragment,{children:[q&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(s.Select,{value:((Z=k.config)==null?void 0:Z.comparisonType)||"none",onValueChange:v,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"none",children:"No Comparison"}),e.jsx(s.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(s.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(s.SelectItem,{value:"start_vs_end",children:"Start vs End"})]})]})]}),ne&&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(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(s.SmallSwitch,{checked:((oe=k.config)==null?void 0:oe.showTrendline)||!1,onCheckedChange:w})]})}),((Ce=k.config)==null?void 0:Ce.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(s.Input,{type:"number",min:"1",max:"365",value:((Me=k.config)==null?void 0:Me.trendlineWindow)||30,onChange:Fe=>{const tt=parseInt(Fe.target.value)||30;g(tt)},className:"h-8 text-xs",placeholder:"30"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Granularity"}),e.jsxs(s.Select,{value:((ge=k.config)==null?void 0:ge.trendlineGranularity)||"day",onValueChange:y,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"day",children:"Day"}),e.jsx(s.SelectItem,{value:"week",children:"Week"}),e.jsx(s.SelectItem,{value:"month",children:"Month"})]})]})]})]})]})]})},Xs=()=>{var q,ne;return ve?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(pe,{value:((q=k.config)==null?void 0:q.targetValue)!==void 0&&((ne=k.config)==null?void 0:ne.targetValue)!==null?String(k.config.targetValue):"",onSave:Z=>{!isNaN(Number(Z))&&Z!==null?T(Number(Z)):T(0)},placeholder:"Enter target value...",type:"text"})]}):null},Zs=()=>{if(!ye)return null;const q=t,ne=s.isCalculatedMetric(q);return e.jsxs(e.Fragment,{children:[ne&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Formula"}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>E(!0),children:[e.jsx(s.Pencil,{className:"mr-2 h-3 w-3"}),"Edit Formula"]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(s.Select,{value:t.aggregate,onValueChange:Z=>{f(n,Z)},disabled:ne,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(_==null?void 0:_.conditions)&&_.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:_.conditions.map(Z=>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:()=>{S(Z),A(!0)},children:[e.jsxs("span",{className:"font-medium",children:[Z.field.label,":"]}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"cursor-help text-muted-foreground",children:Array.isArray(Z.value)?Z.value.length===1?String(Z.value[0]):Z.value.length<=2?Z.value.join(", "):`${Z.value.slice(0,2).join(", ")} +${Z.value.length-2}`:String(Z.value)})}),Array.isArray(Z.value)&&Z.value.length>1&&e.jsx(s.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 (",Z.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:Z.value.map((oe,Ce)=>e.jsx("div",{children:String(oe)},Ce))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:oe=>{var Me;oe.stopPropagation();const Ce=_.conditions.filter(ge=>ge.id!==Z.id);if(Ce.length>0){const ge={..._,conditions:Ce};ue(ge)}else if(te(void 0),a==="metrics"){const ge={...t,parameters:{...t.parameters,filters:void 0}},Fe=[...((Me=k.config)==null?void 0:Me.metricColumns)||[]];Fe[n]=ge,s.useEditorStore.getState().actions.updateCardConfig(k.id,{metricColumns:Fe})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},Z.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{S(null),A(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(Un,{column:t}),d&&e.jsxs(e.Fragment,{children:[e.jsx(Gn,{aliasTemplate:V,onAliasTemplateChange:z}),e.jsx(qn,{valueAliases:X,onValueAliasesChange:ee})]})]})},{columns:et=[]}=s.useColumns(),st=(_==null?void 0:_.conditions)&&_.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:u,style:me,...c,...o,className:`group mx-auto flex w-full flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${p?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(Qe,{dataType:je}),e.jsx(Je,{className:s.cn("w-[140px] flex-1 text-sm",st&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),a==="metrics"&&((es=_==null?void 0:_.conditions)==null?void 0:es.length)&&!M&&e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.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",children:[e.jsx(s.Filter,{className:"h-3 w-3"}),e.jsx("span",{children:_.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:_.conditions.map(q=>e.jsxs("div",{children:[q.field.label,":"," ",Array.isArray(q.value)?`${q.value.length} values`:String(q.value)]},q.id))})})]})}),a!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:q=>{q.stopPropagation(),N(!M)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${M?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:q=>{q.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const ne=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",ne),l(ne)},children:r==="asc"?e.jsx(s.ArrowUp,{className:"h-3 w-3"}):e.jsx(s.ArrowDown,{className:"h-3 w-3"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:q=>{q.stopPropagation(),we()},children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]}),M&&e.jsxs("div",{className:"space-y-3",children:[Q(),ae(),i==="kpi"&&re(),Ne(),Ws(),Xs(),Zs()]})]}),b&&e.jsx(_s,{open:b,onOpenChange:q=>{A(q),q||S(null)},availableFields:et,existingFilters:_,editingCondition:L,onSave:q=>{var ne;if(q)ue(q);else if(te(void 0),a==="metrics"){const Z={...t,parameters:{...t.parameters,filters:void 0}},oe=[...((ne=k.config)==null?void 0:ne.metricColumns)||[]];oe[n]=Z,s.useEditorStore.getState().actions.updateCardConfig(k.id,{metricColumns:oe})}S(null)}}),F&&a==="metrics"&&e.jsx(Qs,{open:F,onOpenChange:E,availableMetrics:((ss=k.config)==null?void 0:ss.metricColumns)||[],existingField:t,onSave:q=>{var Z;const ne=[...((Z=k.config)==null?void 0:Z.metricColumns)||[]];ne[n]=q,s.useEditorStore.getState().actions.updateCardConfig(k.id,{metricColumns:ne})},cardId:k.id})]})}function Qn({concept:t}){const a=()=>{switch(t){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"})]})]})]});default:return null}};return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(s.TooltipContent,{side:"right",align:"start",className:"p-3",children:a()})]})})}function Re({zone:t,fields:a,label:n,placeholder:r,shouldShow:l,hasPivotColumns:d=!1,activeField:i=null}){const{isOver:c,setNodeRef:o}=s.useDroppable({id:t}),{updateSortByColumn:u}=s.useEditorActions(),x=s.useEditorStore(j=>j.card),h=s.useEditorStore(j=>j.card.type),p=a.length>0,k=D.useMemo(()=>!i||!c?!0:s.validateFieldForChartType(i,t,h).isValid,[i,c,t,h]),m=(j,C)=>{var O;!((O=x.config)!=null&&O.sortByColumns)||x.config.sortByColumns.findIndex(R=>R.id===j)===-1||u(x.id,j,{direction:C})};if(t==="sortBy"&&l===!1)return null;const f=t!=="sortBy"&&h!=="kpi";return e.jsxs("div",{className:"mb-4 w-full",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:n}),f&&e.jsx(Qn,{concept:t})]}),e.jsx("div",{ref:o,className:s.cn("rounded-lg border-2 border-dotted p-0.5 transition-all",{"border-green-500 bg-green-50 dark:bg-green-950":c&&k,"border-red-500 bg-red-50 dark:bg-red-950":c&&!k,"border-muted-foreground/30 bg-muted/40":!c&&p,"min-h-[60px] border-muted-foreground/20 bg-background":!c&&!p}),children:a.length===0?e.jsx("div",{className:"flex min-h-[60px] items-center justify-center text-sm text-muted-foreground/60",children:r}):e.jsx(s.SortableContext,{items:a.map(j=>j.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:a.map((j,C)=>{const O=j.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(_n,{field:j,zone:t,index:C,sortDirection:O,onSortDirectionChange:R=>m(j.id,R),hasPivotColumns:d,cardType:h})})},j.id)})})})})]})}const gs={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%
195
- 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 Yn(){var p,k,m,f,j,C,I,O,R,v,w;const t=s.useEditorStore(g=>g.card),{setCardPreferences:a}=s.useEditorActions(),n=((p=t.config)==null?void 0:p.metricColumns)||[],r=((k=t.config)==null?void 0:k.groupByColumns)||[],l=n.length===2&&r.length===0,d=n.length>=1&&r.length>0;if(!(t.type==="kpi"&&(l||d)))return null;const c=((f=(m=t.preferences)==null?void 0:m.kpiVisualOptions)==null?void 0:f.metricComparison)||{},o=g=>{var T;const y={...t.preferences,kpiVisualOptions:{...(T=t.preferences)==null?void 0:T.kpiVisualOptions,metricComparison:{...c,...g}}};a(y)},u=d||c.enabled,x=((j=t.config)==null?void 0:j.comparisonType)||"none",h=x==="previous_period"||x==="same_period_last_year"||x==="start_vs_end";return e.jsxs(s.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(s.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(xt,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[l&&n.length===2&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(s.SmallSwitch,{id:"enable-comparison",checked:c.enabled||!1,onCheckedChange:g=>o({enabled:g,...g&&!c.calculationType?{calculationType:"difference"}:{}})})]}),u&&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(s.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Info,{className:"h-3 w-3 cursor-help text-muted-foreground"})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-xs",children:(()=>{const g=c.calculationType||"difference",y=gs[g];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:y==null?void 0:y.label}),e.jsx("p",{children:y==null?void 0:y.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:y==null?void 0:y.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",y==null?void 0:y.example]})]})})()})]})]}),e.jsxs(s.Select,{value:c.calculationType||"difference",onValueChange:g=>o({calculationType:g}),children:[e.jsx(s.SelectTrigger,{id:"calculation-type",className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Object.entries(gs).map(([g,y])=>e.jsx(s.SelectItem,{value:g,className:"text-xs",children:y.label},g))})]})]}),e.jsx(_e,{formatOptions:c.formatOptions||{},onFormatOptionsChange:g=>o({formatOptions:g}),showTitle:!0,title:"COMPARISON FORMAT"}),(h||l)&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator"}),l&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:c.position||"right",onValueChange:g=>o({position:g}),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"right",className:"text-xs",children:"Right"}),e.jsx(s.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(s.SelectItem,{value:"top",className:"text-xs",children:"Top"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-arrow",checked:c.showArrow!==!1,onCheckedChange:g=>o({showArrow:g})}),e.jsx(s.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(s.Checkbox,{id:"show-color",checked:c.showColor!==!1,onCheckedChange:g=>o({showColor:g})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),c.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(Le,{value:((C=c.colorConfig)==null?void 0:C.increase)||"green",onChange:g=>o({colorConfig:{...c.colorConfig,increase:g}}),label:"Primary > Secondary"}),e.jsx(Le,{value:((I=c.colorConfig)==null?void 0:I.decrease)||"red",onChange:g=>o({colorConfig:{...c.colorConfig,decrease:g}}),label:"Primary < Secondary"}),e.jsx(Le,{value:((O=c.colorConfig)==null?void 0:O.noChange)||"neutral",onChange:g=>o({colorConfig:{...c.colorConfig,noChange:g}}),label:"Primary = Secondary"})]})]}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"conditional-label",checked:c.conditionalLabel||!1,onCheckedChange:g=>o({conditionalLabel:g})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),c.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(s.Input$1,{id:"label-increase",type:"text",value:((R=c.conditionalLabels)==null?void 0:R.increase)??"Increase",onChange:g=>o({conditionalLabels:{...c.conditionalLabels,increase:g.target.value}}),placeholder:"Increase",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-decrease",className:"text-xs text-muted-foreground",children:["Primary ","<"," Secondary"]}),e.jsx(s.Input$1,{id:"label-decrease",type:"text",value:((v=c.conditionalLabels)==null?void 0:v.decrease)??"Decrease",onChange:g=>o({conditionalLabels:{...c.conditionalLabels,decrease:g.target.value}}),placeholder:"Decrease",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-no-change",className:"text-xs text-muted-foreground",children:"Primary = Secondary"}),e.jsx(s.Input$1,{id:"label-no-change",type:"text",value:((w=c.conditionalLabels)==null?void 0:w.noChange)??"No change",onChange:g=>o({conditionalLabels:{...c.conditionalLabels,noChange:g.target.value}}),placeholder:"No change",className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-name",className:"text-xs text-muted-foreground",children:"Previous Label"}),e.jsx(s.Input$1,{id:"label-name",type:"text",value:c.labelName??"",onChange:g=>o({labelName:g.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function Wn(){var l,d;const t=s.useEditorStore(i=>i.card),{setCardPreferences:a}=s.useEditorActions();if(t.type!=="kpi")return null;const n=((d=(l=t.preferences)==null?void 0:l.kpiVisualOptions)==null?void 0:d.formatOptions)||{},r=i=>{var o;const c={...t.preferences,kpiVisualOptions:{...(o=t.preferences)==null?void 0:o.kpiVisualOptions,formatOptions:i}};a(c)};return e.jsxs(s.AccordionItem,{value:"kpi-format",className:"border-none",children:[e.jsx(s.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(s.Hash,{className:"h-4 w-4"}),e.jsx("span",{children:"Number Format"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:e.jsx(_e,{formatOptions:n,onFormatOptionsChange:r,showTitle:!1})})]})}function Xn(){var d;const t=s.useEditorStore(i=>{var c;return(c=i.card)==null?void 0:c.type}),a=s.useEditorStore(i=>{var c;return(c=i.card)==null?void 0:c.preferences}),{setCardPreferences:n}=s.useEditorActions();if(t!=="treemap")return null;const r=((d=a==null?void 0:a.chartOptions)==null?void 0:d.treemapColorMode)??"branch",l=i=>{const c={...a||{},chartOptions:{...a==null?void 0:a.chartOptions,treemapColorMode:i}};n(c)};return e.jsxs(s.AccordionItem,{value:"treemap-color-mode",className:"border-none",children:[e.jsx(s.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(s.TbChartTreemap,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Treemap Colors"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:e.jsxs(s.RadioGroup,{value:r,onValueChange:i=>l(i??"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(s.RadioGroupItem,{id:"treemap-color-branch",value:"branch"}),e.jsxs(s.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(s.RadioGroupItem,{id:"treemap-color-category",value:"category"}),e.jsxs(s.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."})]})]})]})})]})}function Zn({groupByFields:t,pivotByFields:a,metricsFields:n,sortByFields:r,activeField:l}){const[d,i]=D.useState(!1),c=s.useEditorStore(O=>{var R;return((R=O.card.customCardPreferences)==null?void 0:R.url)&&O.card.type==="custom"}),o=s.useEditorStore(O=>O.card),u=s.useEditorStore(O=>O.actions.updateCardConfig),x=o==null?void 0:o.type,h=t.length>0||n.length>0,p=x!=="kpi"||n.length<=2,k=x!=="kpi",m=x!=="kpi"&&h,f=["pie","doughnut","polar","funnel","aggregateTable","bubble","scatter"].includes(x),j=k&&!f,C=()=>x==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},I=()=>x==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Columns",placeholder:"Drop fields to measure"};return e.jsxs(e.Fragment,{children:[e.jsxs(s.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full",children:[e.jsxs(s.AccordionItem,{value:"fields",className:"border-b-0",children:[e.jsx(s.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(s.List,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[p&&e.jsx(Re,{zone:"groupBy",fields:t,label:C().label,placeholder:C().placeholder,activeField:l}),j&&e.jsx(Re,{zone:"pivotBy",fields:a,label:"Pivot Columns",placeholder:"Drop fields to pivot data",activeField:l}),e.jsx(Re,{zone:"metrics",fields:n,label:I().label,placeholder:I().placeholder,hasPivotColumns:a.length>0,activeField:l}),n.length>=1&&e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:()=>i(!0),className:"mt-2 w-full justify-start text-xs text-muted-foreground hover:text-foreground",children:[e.jsx(s.Calculator,{className:"mr-2 h-4 w-4"}),"Create Metric"]}),m&&e.jsx(Re,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics",activeField:l})]})]}),!c&&e.jsxs(s.AccordionItem,{value:"configuration",className:"border-b-0",children:[e.jsx(s.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(s.Settings2,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"CONFIGURATION"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[e.jsx(Wn,{}),e.jsx(Yn,{}),e.jsx(zs,{}),e.jsx(Xn,{}),e.jsx(Us,{}),x==="bullet"&&e.jsx(qs,{}),x==="funnel"&&e.jsx(Js,{}),(x==="bubble"||x==="scatter")&&e.jsx(Hs,{}),e.jsx($s,{}),e.jsx(Ks,{}),e.jsx(Gs,{})]})})]}),c&&e.jsxs(s.AccordionItem,{value:"plugin",className:"border-b-0",children:[e.jsx(s.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(vs,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"CONFIGURATION"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsx(Fs,{})})]})]}),e.jsx(Qs,{open:d,onOpenChange:i,availableMetrics:n,onSave:O=>{u(o.id,{metricColumns:[...n,O]})},cardId:o.id})]})}function ea({onEditJoins:t}){const a=s.useEditorStore(c=>c.card),{autoJoinMetadata:n}=s.useDashboardCardQuery(a);if(!(n!=null&&n.autoResolved))return null;const{resolvedJoinPlan:r}=n,l=(r==null?void 0:r.joins)||[];if(l.length===0)return null;const d=c=>!c||c.length===0?"No conditions":c.map(o=>{var p,k,m,f;const u=`${(p=o.source)==null?void 0:p.entityName}.${(k=o.source)==null?void 0:k.name}`,x=`${(m=o.target)==null?void 0:m.entityName}.${(f=o.target)==null?void 0:f.name}`,h=o.operator||"=";return`${u} ${h} ${x}`}).join(" AND "),i=c=>!c.joinKeyGroups||c.joinKeyGroups.length===0?"No conditions defined":c.joinKeyGroups.length===1?d(c.joinKeyGroups[0].keys):c.joinKeyGroups.map((o,u)=>({id:u,operator:o.operator,condition:d(o.keys)}));return e.jsx(s.Card,{className:"border-blue-500/30 bg-blue-50/30 dark:bg-blue-950/20",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(At,{className:"size-4 text-blue-600 dark:text-blue-400"}),e.jsx("h3",{className:"text-sm font-medium text-blue-900 dark:text-blue-100",children:"Auto-Resolved Joins"}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"secondary",className:"cursor-help bg-blue-100 text-xs text-blue-700 dark:bg-blue-900 dark:text-blue-300",children:l.length})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"max-w-md p-3",children:e.jsx("div",{className:"space-y-2",children:l.map((c,o)=>{const u=i(c),x=Array.isArray(u);return e.jsxs("div",{className:"rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"font-medium text-foreground",children:c.source.name}),e.jsx(s.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:c.target.name})]}),e.jsx(s.Badge,{variant:"outline",className:"border-green-500/40 bg-green-50/30 text-xs text-green-700 dark:bg-green-950/30 dark:text-green-300",children:c.joinType})]}),e.jsx("div",{className:"mt-1 space-y-1",children:x?u.map(h=>e.jsxs("div",{className:"rounded bg-muted/30 px-2 py-1",children:[e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:h.condition}),h.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",h.operator,")"]})]},h.id)):e.jsx("div",{className:"rounded bg-muted/30 px-2 py-1",children:e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:u})})})]},c.id||o)})})})]})})]}),t&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:t,className:"h-7 gap-1 p-2 text-xs text-blue-700 hover:text-blue-900 dark:text-blue-300 dark:hover:text-blue-100",children:e.jsx(s.SquarePen,{className:"size-3.5"})})]})})}const js={getItem(t){if(typeof window>"u")return null;try{return localStorage.getItem(t)}catch(a){return console.warn(`Failed to read from localStorage (${t}):`,a),null}},setItem(t,a){if(!(typeof window>"u"))try{localStorage.setItem(t,a)}catch(n){console.warn(`Failed to write to localStorage (${t}):`,n)}}};function sa({selectedChart:t,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:d,activeField:i}){var g,y;const[c,o]=D.useState(()=>js.getItem("chart-selector-expanded")==="true"),[u,x]=D.useState(!1),h=s.useEditorStore(T=>T.card),p=s.useEditorStore(T=>T.actions.updateCardConfig),k=n.length>0||r.length>0||l.length>0,{data:m,autoJoinMetadata:f}=s.useDashboardCardQuery(h),j=((g=h==null?void 0:h.config)==null?void 0:g.joinPlan)||(f!=null&&f.autoResolved?f.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),C=((y=h==null?void 0:h.dataSource)==null?void 0:y.selectedEntities)||[],I=T=>{p(h.id,{...h==null?void 0:h.config,joinPlan:T}),x(!1)},O=()=>{p(h.id,{...h==null?void 0:h.config,joinPlan:void 0}),x(!1)},R=()=>{x(!1)},v=()=>{x(!0)};D.useEffect(()=>{js.setItem("chart-selector-expanded",String(c))},[c]);const w=()=>{o(T=>!T)};return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col border-x border-border",children:[e.jsxs("div",{className:s.cn("px-6 pt-4",{"space-y-4":c}),children:[e.jsx("div",{className:s.cn("overflow-hidden transition-all duration-300 ease-in-out",c?"max-h-[200px] opacity-100":"max-h-0 opacity-0"),children:c&&e.jsx(zn,{selectedChart:t,onChartChange:a})}),e.jsx("div",{"data-content":"Chart Quick Selector",className:"flex items-center justify-center",children:e.jsx(s.ChartQuickSelector,{selectedChart:t,onChartChange:a,isDropdownExpanded:c,onToggleDropdown:w})})]}),e.jsx("div",{className:s.cn("flex justify-end gap-2 px-6 py-6"),children:e.jsx("div",{className:s.cn("invisible flex gap-2",{visible:k||m}),children:e.jsx(qe.EditorClearButton,{})})}),e.jsxs(s.ScrollArea,{className:"w-full flex-1 basis-0 px-6 pb-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx(ea,{onEditJoins:v}),e.jsx(Zn,{groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:d,activeField:i})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]}),e.jsx(ws,{open:u,onOpenChange:x,joinPlan:j,availableDataSources:C,onSave:I,onCancel:R,onRemove:O,children:e.jsx("div",{})})]})}function ta({initialFilters:t,availableFields:a}={}){const[n,r]=D.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(v=>v.card.dataSource);const{columns:l,isLoading:d}=s.useColumns(),c=a||l||[],o={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=v=>{const w=g=>{if(g.id===v){const y=c[0]||o,T=s.getDataType(y.dataType)==="date";return{...g,conditions:[...g.conditions,{id:`condition-${Date.now()}`,field:y,operator:T?"between":"=",value:T?[]:""}]}}return{...g,groups:g.groups.map(w)}};r(w(n))},x=v=>{const w=g=>{if(g.id===v){const y=c[0]||o,T=s.getDataType(y.dataType)==="date";return{...g,groups:[...g.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:y,operator:T?"between":"=",value:T?[]:""}],groups:[]}]}}return{...g,groups:g.groups.map(w)}};r(w(n))},h=(v,w)=>{const g=y=>y.id===v?{...y,conditions:y.conditions.filter(T=>T.id!==w)}:{...y,groups:y.groups.map(g)};r(g(n))},p=(v,w)=>{const g=y=>y.id===v?{...y,groups:y.groups.filter(T=>T.id!==w)}:{...y,groups:y.groups.map(g)};r(g(n))},k=(v,w,g,y)=>{if(g==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const T=M=>M.id===v?{...M,conditions:M.conditions.map(N=>N.id===w?{...N,[g]:y}:N)}:{...M,groups:M.groups.map(T)};r(T(n))},m=(v,w,g)=>{const y=T=>T.id===v?{...T,conditions:T.conditions.map(M=>M.id===w?{...M,...g}:M)}:{...T,groups:T.groups.map(y)};r(y(n))},f=(v,w)=>{const g=y=>y.id===v?{...y,logicalOperator:w}:{...y,groups:y.groups.map(g)};r(g(n))},j=(v,w)=>{const g=y=>y.id===v?{...y,negate:w}:{...y,groups:y.groups.map(g)};r(g(n))},C=(v,w,g)=>{const y=T=>T.id===v?{...T,conditions:s.arrayMove(T.conditions,w,g)}:{...T,groups:T.groups.map(y)};r(y(n))},I=(v,w,g)=>{const y=T=>T.id===v?{...T,groups:s.arrayMove(T.groups,w,g)}:{...T,groups:T.groups.map(y)};r(y(n))},O=v=>{if(!v||v.conditions.length===0&&v.groups.length===0)return"-- No filters defined";const w=y=>{let T="";typeof y.field=="object"?T=y.field.entityName?`${y.field.entityName}.${y.field.name}`:y.field.name:T=String(y.field);const M=y.operator;let N=y.value;if(y.field.dataType==="string"&&!["in","not in"].includes(y.operator))typeof N=="string"?N=`'${N}'`:Array.isArray(N)&&(N=`'${N.join(", ")}'`);else if(y.field.dataType==="date"||y.field.dataType==="datetime"||y.field.dataType==="timestamp")if(y.operator==="between"&&Array.isArray(N)&&N.length===2){const b=N[0]?`'${N[0]}'`:"NULL",A=N[1]?`'${N[1]}'`:"NULL";return`${T} BETWEEN ${b} AND ${A}`}else if((y.operator==="in"||y.operator==="not in")&&Array.isArray(N)){const b=N.map(A=>A?`'${A}'`:"NULL").join(", ");return`${T} ${M} (${b})`}else typeof N=="string"||N instanceof Date?N=`'${N}'`:Array.isArray(N)&&N.length>0&&(N=`'${N[0]}'`);else if(["in","not in"].includes(y.operator)){let b=[];Array.isArray(N)?b=N.map(A=>typeof A=="string"?`'${A}'`:String(A)):typeof N=="string"?b=N.split(",").map(A=>{const F=A.trim();return y.field.dataType==="string"?`'${F}'`:F}):typeof N=="number"&&(b=[String(N)]),N=`(${b.join(", ")})`}switch(M){case"contains":return typeof N=="string"?`${T} LIKE '%${N.replace(/'/g,"")}'`:`${T} LIKE '%${String(N)}'`;case"startsWith":return typeof N=="string"?`${T} LIKE '${N.replace(/'/g,"")}%'`:`${T} LIKE '${String(N)}%'`;case"endsWith":return typeof N=="string"?`${T} LIKE '%${N.replace(/'/g,"")}'`:`${T} LIKE '%${String(N)}'`;case"isNull":return`${T} IS NULL`;case"isNotNull":return`${T} IS NOT NULL`;default:return`${T} ${M} ${N}`}},g=y=>{const T=y.conditions.map(w),M=y.groups.map(F=>g(F)),N=[...T,...M].filter(Boolean);if(N.length===0)return"";const b=N.join(` ${y.logicalOperator} `),A=N.length>1?`(${b})`:b;return y.negate?`NOT ${A}`:A};return g(v)},R=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:c,isLoading:d,addCondition:u,addGroup:x,removeCondition:h,removeGroup:p,updateCondition:k,updateConditionFields:m,updateGroupOperator:f,updateGroupNegate:j,reorderConditions:C,reorderGroups:I,generateSQLPreview:O,hasAnyFilters:R}}function na({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const aa=t=>{if(t.qualifiedEntityName){const a=t.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function ra({value:t,onValueChange:a,availableFields:n,placeholder:r="Select field",className:l="w-64"}){const[d,i]=D.useState(!1),c=D.useMemo(()=>{const o={};return n.forEach(u=>{const x=aa(u);o[x]||(o[x]={}),o[x][u.entityId]||(o[x][u.entityId]=[]),o[x][u.entityId].push(u)}),o},[n]);return e.jsxs(s.Popover,{modal:!0,open:d,onOpenChange:i,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":d,className:s.cn("justify-between",!t&&"text-muted-foreground",l),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(na,{children:[t.entityName,".",t.name]})}):r,e.jsx(it,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(s.CommandEmpty,{children:"No fields found."}),e.jsx(s.CommandList,{className:"max-h-80",children:Object.entries(c).map(([o,u])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),o]}),children:Object.entries(u).map(([x,h])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[s.getEntityIcon(h[0].entityType,{size:"h-3 w-3"}),e.jsx("span",{children:h[0].entityName})]}),h.map((p,k)=>e.jsxs(s.CommandItem,{value:p.id,onSelect:()=>{a(p),i(!1)},className:"overflow-x-auto",children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",(t==null?void 0:t.id)===p.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:p.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:p.description&&e.jsx("span",{children:p.description})})]})]},p.id+k))]},`${o}-${x}`))},o))})]})})]})}function Ye(t){var f;const a=s.useEditorStore(j=>j.card),{authToken:n,tokenProps:r}=s.useSemaphorContext(),l=s.useEditorStore(j=>j.card.config),d=l==null?void 0:l.joinPlan,i={...t,alias:t.name,label:"value",role:"groupby"},c={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},o={...i,role:"sortby",direction:"asc"},u={joinPlan:d,groupByColumns:[i],metricColumns:[c],sortByColumns:[o]},x=((f=a.dataSource)==null?void 0:f.connectionId)||a.connectionId,{data:h,isPending:p,error:k}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular(`${r.apiServiceUrl}/v1/query`,(n==null?void 0:n.accessToken)||"",{connection_id:x,cardConfig:u,cardDataSource:a.dataSource})}catch(j){console.log(t),console.error("error",j)}},enabled:!!x,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((h==null?void 0:h.records)||[]).map(j=>({label:j.value||"BLANK",value:j.value||"BLANK",count:(j==null?void 0:j.count)||0})),isPending:p,error:k}}function la({field:t,selected:a,onChange:n,placeholder:r="Select items...",className:l}){const[d,i]=Ke.useState(!1),{filterValues:c}=Ye(t),o=x=>{n(a.filter(h=>h!==x))},u=x=>{a.includes(x)?n(a.filter(h=>h!==x)):n([...a,x])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open:d,onOpenChange:i,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":d,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(x=>{const h=c.find(p=>p.value===x);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[h==null?void 0:h.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:p=>{p.key==="Enter"&&o(x)},onMouseDown:p=>{p.preventDefault(),p.stopPropagation()},onClick:p=>{p.stopPropagation(),o(x)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},x)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No results found."}),e.jsx(s.CommandGroup,{children:c.map((x,h)=>e.jsxs(s.CommandItem,{onSelect:()=>u(x.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",a.includes(x.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:x.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:x.count})]})]},x.value+h))})]})]})})]})})}function oa({field:t,value:a,onChange:n,placeholder:r="Select value...",className:l}){const{filterValues:d,isPending:i,error:c}=Ye(t);return i?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):c?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:a,onValueChange:n,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:a})}),e.jsx(s.SelectContent,{children:d.map((o,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:o.value,children:o.label},o.value+u))})]})}function ia({value:t,operator:a,onChange:n,className:r}){var o;const{tokenProps:l}=s.useSemaphorContext(),d=(o=l==null?void 0:l.params)==null?void 0:o.timezone,i=D.useMemo(()=>{if(t){if(a==="between"||a==="not between"){if(Array.isArray(t)&&t.length===2){const u=t[0]?new Date(t[0]):void 0,x=t[1]?new Date(t[1]):void 0;if(u&&x)return{from:u,to:x}}}else if(a==="="||a==="!="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:u}}}else if(a===">"||a===">="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:void 0}}}else if(a==="<"||a==="<="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:void 0,to:u}}}else if((a==="in"||a==="not in")&&Array.isArray(t)&&t.length>0){const u=new Date(t[0]),x=t.length>1?new Date(t[t.length-1]):u;if(!isNaN(u.getTime()))return{from:u,to:x}}}},[t,a]),c=u=>{if(!u){n(void 0);return}if(u.from&&u.to)n([u.from.toISOString(),u.to.toISOString()]);else if(u.from){const x=new Date(u.from);x.setHours(23,59,59,999),n([u.from.toISOString(),x.toISOString()])}else if(u.to){const x=new Date(u.to);x.setHours(0,0,0,0),n([x.toISOString(),u.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:i,onChange:c,timezone:d,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const ca=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],da=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],ua=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],ma=["=","!=","isNull","isNotNull"],xa=["between","isNull","isNotNull"],ha={"=":"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 bs(t){return ha[t]||s.titleCase(t)}function pa(t){switch(t){case"string":return da;case"number":return ua;case"boolean":return ma;case"date":return xa;default:return ca}}function Ys({condition:t,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:d,onUpdateGroupOperator:i,availableFields:c,updateConditionFields:o}){const{attributes:u,listeners:x,setNodeRef:h,transform:p,transition:k,isDragging:m}=s.useSortable({id:t.id}),{isPending:f,error:j}=Ye(t.field),C={transform:s.CSS.Transform.toString(p),transition:k};return e.jsxs("div",{ref:h,style:C,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${m?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...x,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(s.Select,{value:r,onValueChange:I=>i(n,I),children:[e.jsx(s.SelectTrigger,{className:"w-24",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(ra,{value:t.field,onValueChange:I=>{const O=I,R=s.getDataType(O.dataType)==="date";o(n,t.id,{field:O,value:"",operator:R?"between":"="})},availableFields:c,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:I=>{I==="in"||I==="not in"?o(n,t.id,{operator:I,value:[]}):I==="isNull"||I==="isNotNull"?o(n,t.id,{operator:I,value:null}):o(n,t.id,{operator:I,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?bs(t.operator):""})}),e.jsx(s.SelectContent,{children:pa(s.getDataType(t.field.dataType)).map(I=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:I,children:bs(I)},I))})]}),t.operator==="isNull"||t.operator==="isNotNull"?e.jsx("div",{className:"flex-1"}):s.getDataType(t.field.dataType)==="string"?t.operator==="in"||t.operator==="not in"?f?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.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(la,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(I=>typeof I=="string")?t.value:[],onChange:I=>o(n,t.id,{value:I}),placeholder:`Select values for ${t.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(t.operator)?e.jsx(s.Input,{value:typeof t.value=="string"?t.value:"",onChange:I=>o(n,t.id,{value:I.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(oa,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:I=>o(n,t.id,{value:I}),placeholder:"Select value...",className:"flex-1"}):s.getDataType(t.field.dataType)==="boolean"?e.jsxs(s.Select,{value:typeof t.value=="boolean"?String(t.value):"",onValueChange:I=>o(n,t.id,{value:I==="true"}),children:[e.jsx(s.SelectTrigger,{className:"flex-1",children:e.jsx(s.SelectValue,{placeholder:"Select value..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"true",children:"True"}),e.jsx(s.SelectItem,{value:"false",children:"False"})]})]}):s.getDataType(t.field.dataType)==="date"?e.jsx(ia,{value:t.value,operator:t.operator,onChange:I=>o(n,t.id,{value:I}),className:"flex-1"}):e.jsx(s.Input,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:I=>l(n,t.id,"value",I.target.value),className:"flex-1",placeholder:t.operator==="in"||t.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>d(n,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function fa({group:t,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:d,onUpdateCondition:i,onUpdateField:c,onRemoveCondition:o,onReorderConditions:u,onReorderGroups:x,onAddCondition:h,onAddGroup:p,availableFields:k,renderFilterGroup:m,updateConditionFields:f}){const{attributes:j,listeners:C,setNodeRef:I,transform:O,transition:R,isDragging:v}=s.useSortable({id:t.id}),w={transform:s.CSS.Transform.toString(O),transition:R},g=T=>{const{active:M,over:N}=T;if(N&&M.id!==N.id){const b=t.conditions.findIndex(F=>F.id===M.id),A=t.conditions.findIndex(F=>F.id===N.id);b!==-1&&A!==-1&&u(t.id,b,A)}},y=T=>{const{active:M,over:N}=T;if(N&&M.id!==N.id&&n){const b=t.groups.findIndex(F=>F.id===M.id),A=t.groups.findIndex(F=>F.id===N.id);b!==-1&&A!==-1&&x(n,b,A)}};return e.jsxs("div",{ref:I,style:w,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${v?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...j,...C,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(s.Button,{variant:t.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>l(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:T=>r(t.id,T),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>n&&d(n,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:g,children:e.jsx(s.SortableContext,{items:t.conditions.map(T=>T.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((T,M)=>e.jsx(Ys,{condition:T,index:M,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:i,onUpdateField:c,onRemoveCondition:o,onUpdateGroupOperator:r,availableFields:k,updateConditionFields:f},T.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:y,children:e.jsx(s.SortableContext,{items:t.groups.map(T=>T.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(T=>m(T,a+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>p(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function ga({filters:t,availableFields:a,onSave:n,onClearAll:r,onCancel:l}){const{currentFilters:d,availableFields:i,isLoading:c,addCondition:o,addGroup:u,removeCondition:x,removeGroup:h,updateCondition:p,updateConditionFields:k,updateGroupOperator:m,updateGroupNegate:f,reorderConditions:j,reorderGroups:C,generateSQLPreview:I,hasAnyFilters:O,setCurrentFilters:R}=ta({initialFilters:t,availableFields:a}),v=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[w,g]=D.useState(!1),y=(N,b,A)=>{const F=E=>E.id===N?{...E,conditions:E.conditions.map(L=>L.id===b?{...L,field:A,dataType:A.dataType}:L)}:{...E,groups:E.groups.map(F)};R(F(d))},T=(N,b=0,A)=>b===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:v,collisionDetection:s.closestCenter,onDragEnd:F=>{const{active:E,over:L}=F;if(L&&E.id!==L.id){const S=N.conditions.findIndex($=>$.id===E.id),P=N.conditions.findIndex($=>$.id===L.id);S!==-1&&P!==-1&&j(N.id,S,P)}},children:e.jsx(s.SortableContext,{items:N.conditions.map(F=>F.id),strategy:s.verticalListSortingStrategy,children:N.conditions.map((F,E)=>e.jsx(Ys,{condition:F,index:E,groupId:N.id,groupLogicalOperator:N.logicalOperator,onUpdateCondition:p,onUpdateField:y,onRemoveCondition:x,onUpdateGroupOperator:m,availableFields:i,updateConditionFields:k},F.id))})}),e.jsx(s.DndContext,{sensors:v,collisionDetection:s.closestCenter,onDragEnd:F=>{const{active:E,over:L}=F;if(L&&E.id!==L.id){const S=N.groups.findIndex($=>$.id===E.id),P=N.groups.findIndex($=>$.id===L.id);S!==-1&&P!==-1&&C(N.id,S,P)}},children:e.jsx(s.SortableContext,{items:N.groups.map(F=>F.id),strategy:s.verticalListSortingStrategy,children:N.groups.map(F=>T(F,b+1,N.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>o(N.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),w&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(N.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},N.id):e.jsx(fa,{group:N,depth:b,parentGroupId:A,onUpdateGroupOperator:m,onUpdateGroupNegate:f,onRemoveGroup:h,onUpdateCondition:p,onUpdateField:y,onRemoveCondition:x,onReorderConditions:j,onReorderGroups:C,onAddCondition:o,onAddGroup:u,availableFields:i,renderFilterGroup:T,updateConditionFields:k},N.id),M=s.getFilterCount(t);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Card,{children:e.jsx(s.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[c?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):T(d),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(s.SmallSwitch,{id:"advanced-mode",checked:w,onCheckedChange:N=>g(N)}),e.jsx(s.Label,{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),O&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:I(d)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:l,children:"Cancel"}),M>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>n(O?d:null),children:"Apply Filters"})]})]})}function ja({cardId:t,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:l,isOpen:d,onOpenChange:i}){const c=u=>{n(t,u),i(!1)},o=()=>{r(t),i(!1)};return e.jsxs(s.Dialog,{modal:!1,open:d,onOpenChange:i,children:[d&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:u=>{u.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Card Filters"}),e.jsx(s.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(ga,{filters:a,availableFields:l,onSave:c,onCancel:()=>i(!1),onClearAll:o})]})]})}function ba({activeCardId:t,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var j,C;const[l,d]=D.useState(null),i=s.useEditorStore(I=>I.card),c=s.useEditorStore(I=>I.actions.updateCardConfig),o=(j=i==null?void 0:i.config)==null?void 0:j.joinPlan,u=(C=i==null?void 0:i.dataSource)==null?void 0:C.semanticDomainId,{data:x}=s.useJoinabilityMap(u),h=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],p=D.useCallback(I=>I.startsWith("card-")?null:I.startsWith("source-")||a.find(O=>O.id===I)?"source":n("groupBy").find(O=>O.id===I)?"groupBy":n("metrics").find(O=>O.id===I)?"metrics":n("pivotBy").find(O=>O.id===I)?"pivotBy":n("sortBy").find(O=>O.id===I)?"sortBy":null,[a,n]),k=D.useCallback(I=>{d(I.active.id)},[]),m=D.useCallback(I=>{var T;const{active:O,over:R}=I;if(!R||!t){d(null);return}const v=O.id,w=R.id,g=p(v),y=p(w)||w;if(y==="sortBy"){if(g==="source"){const M=a.find(b=>b.id===v);if(!M){d(null);return}if(!(n("groupBy").some(b=>b.name===M.name&&b.qualifiedEntityName===M.qualifiedEntityName)||n("metrics").some(b=>b.name===M.name&&b.qualifiedEntityName===M.qualifiedEntityName))){d(null);return}}else if(g==="pivotBy"){d(null);return}else if(g!=="groupBy"&&g!=="metrics"&&g!=="sortBy"){d(null);return}}if(g==="source"&&y==="sortBy"){const M=[...a].find(F=>F.id===v);if(!M){d(null);return}const N=n("sortBy");if(s.fieldAlreadyExists(M,N)){d(null);return}const b=s.validateFieldForChartType(M,"sortBy",i.type);if(!b.isValid){s.ue.error("Invalid Field Type",{description:b.reason,position:"top-center",duration:3e3}),d(null);return}const A=s.getNewField(M,"sortBy",N);d(null),r("sortBy",[...N,A]);return}if(g==="source"&&y!=="source"&&y!=="sortBy"){const M=[...a].find(L=>L.id===v);if(!M){d(null);return}const N=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(N.length>0){const L=N[0].qualifiedEntityName;if(!L){d(null);return}if(L!==M.qualifiedEntityName&&M.qualifiedEntityName)if(u&&(x!=null&&x.joinabilityMap)){if(s.calculateFieldState(M,{joinabilityMap:x.joinabilityMap,selectedFields:N,baseEntityName:(T=o==null?void 0:o.baseEntity)==null?void 0:T.name}).state==="unreachable"){s.showJoinRequiredNotification(),d(null);return}}else{if(!o){s.showJoinRequiredNotification(),d(null);return}if(!s.areEntitiesJoined(L,M.qualifiedEntityName,o)){s.showJoinRequiredNotification(),d(null);return}}}const b=n(y);if(s.fieldAlreadyExists(M,b)){d(null);return}const A=s.validateFieldForChartType(M,y,i.type);if(!A.isValid){s.ue.error("Invalid Field Type",{description:A.reason,position:"top-center",duration:3e3}),d(null);return}const F=s.getNewField(M,y,b),E=[...b,F];d(null),r(y,E),y==="metrics"&&t&&s.cleanupKpiMetricComparisonMode(i.type,i.config,c,t,E);return}if(g&&y&&g!=="source"&&y!=="source"&&g!==y){const M=n(g),N=n(y),b=M.find(S=>S.id===v);if(!b){d(null);return}const A=s.validateFieldForChartType(b,y,i.type);if(!A.isValid){s.ue.error("Invalid Field Type",{description:A.reason,position:"top-center",duration:3e3}),d(null);return}const F=s.getNewField(b,y,N);if(d(null),y==="sortBy"){s.fieldAlreadyExists(b,N)||r(y,[...N,F]);return}const E=M.filter(S=>S.id!==v),L=[...N,F];r(g,E),r(y,L),y==="metrics"&&t&&s.cleanupKpiMetricComparisonMode(i.type,i.config,c,t,L);return}if(g&&y&&g===y&&g!=="source"){const M=n(g),N=M.findIndex(A=>A.id===v),b=M.findIndex(A=>A.id===w);if(N!==b){const A=s.arrayMove(M,N,b);r(g,A)}}d(null)},[t,a,n,r,p,o,u,x,i.type,c,i.config]),f=l?h.find(I=>I.id===l):null;return{activeId:l,activeField:f,handleDragStart:k,handleDragEnd:m}}function va({activeView:t,onViewChange:a,splitViewEnabled:n}){const r=s.useEditorStore(o=>o.card),{config:l}=D.useContext(s.SemaphorContext).tokenProps,d=(l==null?void 0:l.showInfoTab)!==!1,{errorMessage:i}=s.useDashboardCardQuery(r),c=()=>n?!1:!["table","pivotTable","aggregateTable"].includes(r.type);return e.jsx(s.Tabs,{value:t,onValueChange:o=>a(o),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-1 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),c()&&e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),r.type!=="kpi"&&d&&e.jsx(s.TabsTrigger,{value:"info",className:s.cn("rounded-md transition data-[state=active]:bg-muted",i&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:i?"Error":"Info"})]})})}const ya=[{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 Na(){var o,u;const t=s.useEditorStore(x=>x.card),{updateRowLimit:a}=s.useEditorActions(),[n,r]=D.useState(!1),[l,d]=D.useState(""),i=x=>{if(x==="custom"){r(!0);return}r(!1),a(t.id,parseInt(x))},c=x=>{const h=x.target.value;d(h),h&&!isNaN(parseInt(h))&&a(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(s.Input$1,{type:"number",value:l,onChange:c,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(o=t.config)==null?void 0:o.rowLimit)==null?void 0:u.toString())||"100",onValueChange:i,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(s.SelectValue,{placeholder:"Select limit"})}),e.jsx(s.SelectContent,{children:ya.map(x=>e.jsx(s.SelectItem,{value:x.value,children:x.label},x.value))})]})})}function Ca({card:t,queryData:a,isLoading:n,isFetching:r,pagination:l,onPaginationChange:d,onSortChange:i,sortState:c,splitViewEnabled:o}){const u=D.useMemo(()=>(a==null?void 0:a.records)||[],[a==null?void 0:a.records]);return!o||["table","pivotTable","aggregateTable"].includes(t.type)?e.jsx(Ge,{}):e.jsxs(s.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(s.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:e.jsx(Ge,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{defaultSize:40,minSize:20,role:"results-section",className:"flex flex-col",children:e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:(a==null?void 0:a.records)&&e.jsx(s.TableVisual,{card:t,data:u,paginationMetadata:l,onPaginationChange:d,isLoading:n||r,onSortChange:i,sortState:c})})})]})}const Sa="semaphor-split-view-enabled";function wa(){return ks(Sa,!0)}function ka({activeView:t,onViewChange:a,showDebug:n,onDebugToggle:r,onFiltersClick:l,activeCard:d,columns:i,columnsLoading:c,columnsError:o}){var se,_,te;const u=s.useEditorStore(Y=>Y.card),x=s.useDashboardStore(Y=>Y.filterValues),h=s.useDashboardStore(Y=>Y.selectedSheetId),p=s.useDashboardStore(Y=>Y.inlineFilterValuesMap[(d==null?void 0:d.id)||""]),{updateCardConfig:k,setCard:m,updateCardInFrame:f,setShowAIDialog:j}=s.useEditorActions(),C=s.useEditorStore(Y=>Y.showAIDialog),I=s.useDashboardStore(Y=>Y.isVisualEditing),[O,R]=D.useState(!1),[v,w]=D.useState(!1),[g,y]=D.useState(null),{config:T}=D.useContext(s.SemaphorContext).tokenProps,M=(T==null?void 0:T.showInfoTab)!==!1,[N,b]=wa();s.useEditorStore(Y=>{var le;return((le=Y.card.customCardPreferences)==null?void 0:le.url)&&Y.card.type==="custom"});const{data:A,errorMessage:F,isLoading:E,isFetching:L,errorSql:S,pagination:P,refetch:$,comparisonMetadata:J}=s.useDashboardCardQuery(d),K=D.useMemo(()=>(A==null?void 0:A.records)||[],[A==null?void 0:A.records]),[G,H]=D.useState(!1);D.useEffect(()=>{L||H(!1)},[L]);const B=()=>{const Y=!N;Y&&t==="table"&&a("chart"),b(Y)},U=(Y,le)=>{const ce={...d,paginationConfig:{page:Y+1,pageSize:le}};m(ce),f(ce)};function V(){return e.jsxs("div",{className:"relative border-b border-border bg-background p-4",children:[e.jsx("button",{onClick:r,className:"absolute right-4 top-4 rounded-md p-1 hover:bg-muted","aria-label":"Close Debug Panel",children:e.jsx(s.X,{className:"h-4 w-4"})}),e.jsxs("div",{className:"space-y-4 pr-8",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(u.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Dashboard Filters"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(x||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(d.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",i.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:c?"Loading...":o?"Error loading columns":JSON.stringify(i.slice(0,5),null,2)})]})]})]})}const W=Y=>{if(!u.config)return;const le=s.sortStateToSortByColumns(Y,u.config.metricColumns,u.config.groupByColumns);k(u.id,{...u.config,sortByColumns:le})},X=D.useMemo(()=>{var Y;return s.sortByColumnsToSortState((Y=u.config)==null?void 0:Y.sortByColumns)},[(se=u.config)==null?void 0:se.sortByColumns]);return e.jsxs("div",{className:s.cn("relative flex w-0 grow flex-col",{"border-l":C&&I}),children:[n&&V(),e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t==="chart"&&C&&e.jsx(Ms,{variant:"outline"}),e.jsx(va,{activeView:t,onViewChange:a,splitViewEnabled:N}),e.jsx(s.FilterInfo,{cardId:d.id,cardFilters:(_=d.config)==null?void 0:_.filters,cardFilterCount:s.getFilterCount(((te=d.config)==null?void 0:te.filters)||null),onFiltersClick:l,inlineFilters:d.inlineFilters,inlineFilterValues:p,sheetId:h||""}),J&&e.jsx(s.ComparisonMetadataBadge,{metadata:J,variant:"compact"}),e.jsx("div",{className:"ml-2",children:e.jsx(Na,{})}),C&&e.jsx(qe.EditorClearButton,{})]}),e.jsxs("div",{className:s.cn("flex grow items-center justify-end gap-2"),children:[e.jsx(s.IconButton,{tooltip:"Refresh",disabled:E||L,onClick:()=>{H(!0),$()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":G})})}),t==="chart"&&e.jsx(s.IconButton,{tooltip:N?"Hide Results Table":"Show Results Table",onClick:B,children:N?e.jsx(mt,{className:"size-4"}):e.jsx(kt,{className:"size-4"})}),t==="chart"&&e.jsx(e.Fragment,{children:e.jsx(Ls,{})}),!C&&e.jsx(s.IconButton,{onClick:()=>j(!C),tooltip:"AI",className:"h-8","aria-label":"AI",children:e.jsx(s.Sparkles,{className:"size-4"})}),r&&s.isDevEnv]})]}),e.jsxs("div",{className:"mt-3 flex min-h-0 grow flex-col",children:[t==="chart"&&e.jsx("div",{className:s.cn("flex grow flex-col pb-6",{"pb-0":N&&!["table","pivotTable","aggregateTable"].includes(d.type)}),children:e.jsx(Ca,{card:d,queryData:A,isLoading:E,isFetching:L,pagination:P,onPaginationChange:U,onSortChange:W,sortState:X,splitViewEnabled:N})}),t==="table"&&(A==null?void 0:A.records)&&e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:e.jsx(s.TableVisual,{card:d,data:K,paginationMetadata:P,onPaginationChange:U,isLoading:E||L,onSortChange:W,sortState:X})}),t==="info"&&M&&e.jsx("div",{className:"flex min-h-0 flex-1 flex-col pb-6",children:e.jsx("div",{className:"flex min-h-0 flex-1 flex-col rounded-md bg-background px-6",children:F?e.jsx(He,{error:F,errorSql:S,onSendFeedback:()=>{const Y=s.prepareFeedbackData(s.FeedbackCategory.QUERY_GENERATION,{cardConfig:u.config,dataSource:d.dataSource,dashboardFilters:x,errorMessage:F,errorSql:S,generatedSql:A==null?void 0:A.sql});y(Y),w(!0)},onOpenInEditor:()=>{j(!0),setTimeout(()=>{const Y=s.useEditorStore.getState().actions;Y.setIsDevMode(!0),Y.setCardSql(S||""),setTimeout(()=>{Y.setRunSql(!0)},100)},100)}}):e.jsx(Es,{sql:A==null?void 0:A.sql,error:F,errorSql:S})})})]}),g&&e.jsx(s.FeedbackDialog,{open:v,onOpenChange:w,feedbackData:g})]})]})}function Ta({activeField:t}){const[a,n]=D.useState(!0);return D.useEffect(()=>{t&&n(!0)},[t]),t?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${a?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(s.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(Qe,{dataType:t.dataType}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-sm dark:text-muted-foreground",children:t.label||t.name})]}):null}const Ea=()=>{const t=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||t.apply(console,r)};const a=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},n=r=>{var l;if((l=r.reason)!=null&&l.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=t,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function Aa({column:t,isSelected:a,onSelect:n,availableFields:r,width:l,onWidthChange:d}){var $,J,K;const i=s.useEditorStore(G=>G.card),{updateCardConfig:c,removeGroupByColumn:o,removeMetricColumn:u,updateFilters:x}=s.useEditorActions(),[h,p]=D.useState(!1),[k,m]=D.useState(!1),f=D.useRef(null),j=D.useCallback(G=>{G.preventDefault(),G.stopPropagation(),m(!0),f.current={startX:G.clientX,startWidth:l||150};const H=U=>{if(!f.current)return;const V=U.clientX-f.current.startX,W=Math.max(80,f.current.startWidth+V);d==null||d(t.id,W)},B=()=>{m(!1),f.current=null,document.removeEventListener("mousemove",H),document.removeEventListener("mouseup",B)};document.addEventListener("mousemove",H),document.addEventListener("mouseup",B)},[l,t.id,d]),C=($=i==null?void 0:i.config)==null?void 0:$.filters,I=(J=C==null?void 0:C.conditions)==null?void 0:J.some(G=>G.field.name===t.name&&G.field.qualifiedEntityName===t.qualifiedEntityName),O=G=>{G?x(i.id,G):c(i.id,{filters:void 0})},{attributes:R,listeners:v,setNodeRef:w,transform:g,transition:y,isDragging:T}=s.useSortable({id:t.id}),M={transform:s.CSS.Transform.toString(g),transition:y},N=s.getDataType(t.dataType),b=Ia(N),A=()=>{var B;const G=((B=i==null?void 0:i.config)==null?void 0:B.sortByColumns)||[],H=G.findIndex(U=>U.name===t.name);if(H!==-1){const U=[...G];U[H]={...U[H],direction:"asc"},c(i.id,{sortByColumns:U})}else c(i.id,{sortByColumns:[...G,{...t,id:`sort-${t.id}`,role:"sortby",direction:"asc"}]})},F=()=>{var B;const G=((B=i==null?void 0:i.config)==null?void 0:B.sortByColumns)||[],H=G.findIndex(U=>U.name===t.name);if(H!==-1){const U=[...G];U[H]={...U[H],direction:"desc"},c(i.id,{sortByColumns:U})}else c(i.id,{sortByColumns:[...G,{...t,id:`sort-${t.id}`,role:"sortby",direction:"desc"}]})},E=()=>{var B;const G=((B=i==null?void 0:i.config)==null?void 0:B.groupByColumns)||[];if(!G.some(U=>U.name===t.name)){const U={...t,id:`groupby-${t.id}-${Date.now()}`,role:"groupby"};c(i.id,{groupByColumns:[...G,U]})}},L=G=>{var U;const H=((U=i==null?void 0:i.config)==null?void 0:U.metricColumns)||[];if(!H.some(V=>V.name===t.name&&V.aggregate===G)){const V={...t,id:`metric-${t.id}-${G}-${Date.now()}`,label:`${G} of ${t.label||t.name}`,role:"metric",aggregate:G};c(i.id,{metricColumns:[...H,V]})}},S=()=>{t.role==="groupby"?o(i.id,t.id):t.role==="metric"&&u(i.id,t.id)},P={...M,width:l?`${l}px`:void 0,minWidth:l?`${l}px`:"120px"};return e.jsxs("th",{ref:w,style:P,className:s.cn("group relative border-r border-border bg-background px-1 py-0",T&&"opacity-50",a&&"bg-primary/10",k&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...R,...v,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(s.GripVertical,{className:"h-3 w-3"})}),e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsxs("button",{onClick:n,className:s.cn("flex flex-1 items-center justify-between gap-1 rounded px-2 py-2 text-left text-sm font-medium transition-colors hover:bg-muted/50",a&&"bg-primary/10"),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(b,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:t.label||t.name}),t.role==="metric"&&t.aggregate&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",t.aggregate,")"]}),I&&e.jsx(s.Filter,{className:"h-3 w-3 text-primary"})]}),e.jsx(s.ChevronDown,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsxs(s.DropdownMenuContent,{align:"start",className:"w-48",children:[e.jsxs(s.DropdownMenuItem,{onClick:()=>p(!0),children:[e.jsx(s.Filter,{className:s.cn("mr-2 h-4 w-4",I&&"text-primary")}),I?"Edit Filter":"Filter"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:A,children:[e.jsx(lt,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(s.DropdownMenuItem,{onClick:F,children:[e.jsx(rt,{className:"mr-2 h-4 w-4"}),"Sort Z → A"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuSub,{children:[e.jsxs(s.DropdownMenuSubTrigger,{children:[e.jsx(s.Calculator,{className:"mr-2 h-4 w-4"}),"Summarize"]}),e.jsxs(s.DropdownMenuSubContent,{children:[e.jsx(s.DropdownMenuItem,{onClick:()=>L("SUM"),children:"Sum"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("AVG"),children:"Average"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("COUNT"),children:"Count"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("DISTINCT"),children:"Count Distinct"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("MIN"),children:"Min"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("MAX"),children:"Max"})]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:E,children:[e.jsx(Ue,{className:"mr-2 h-4 w-4"}),"Group by this column"]}),e.jsxs(s.DropdownMenuItem,{disabled:!0,children:[e.jsx(Ns,{className:"mr-2 h-4 w-4"}),"Pivot by this column"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{disabled:!0,children:[e.jsx(s.EyeOff,{className:"mr-2 h-4 w-4"}),"Hide column"]}),e.jsxs(s.DropdownMenuItem,{onClick:S,className:"text-destructive focus:text-destructive",children:[e.jsx(s.Trash2,{className:"mr-2 h-4 w-4"}),"Remove column"]})]})]})]}),e.jsx("div",{onMouseDown:j,className:s.cn("absolute right-0 top-0 h-full w-1 cursor-col-resize bg-transparent hover:bg-primary/50",k&&"bg-primary")}),e.jsx(_s,{open:h,onOpenChange:p,availableFields:r.length>0?r:[t],existingFilters:C,editingCondition:I?(K=C==null?void 0:C.conditions)==null?void 0:K.find(G=>G.field.name===t.name&&G.field.qualifiedEntityName===t.qualifiedEntityName):void 0,onSave:O})]})}function Ia(t){switch(t){case"number":return s.Hash;case"date":return s.Calendar;case"string":default:return s.Type}}function Da({selectedColumn:t,onColumnSelect:a,isLoading:n=!1,sourceFields:r=[]}){var y,T,M,N;const l=s.useEditorStore(b=>b.card),{updateCardConfig:d}=s.useEditorActions(),[i,c]=D.useState(null),[o,u]=D.useState({}),[x,h]=D.useState(!1),p=D.useMemo(()=>{var F,E;const b=((F=l==null?void 0:l.config)==null?void 0:F.groupByColumns)||[],A=((E=l==null?void 0:l.config)==null?void 0:E.metricColumns)||[];return[...b,...A]},[(y=l==null?void 0:l.config)==null?void 0:y.groupByColumns,(T=l==null?void 0:l.config)==null?void 0:T.metricColumns]),k=D.useMemo(()=>{const b=new Set(p.map(A=>`${A.qualifiedEntityName}.${A.name}`));return r.filter(A=>!b.has(`${A.qualifiedEntityName}.${A.name}`))},[r,p]),{data:m,isLoading:f}=s.useDashboardCardQuery(l),j=(m==null?void 0:m.records)||[],C=D.useCallback((b,A)=>{u(F=>({...F,[b]:A}))},[]),I=D.useCallback(b=>{var L,S;const A=s.getDataType(b.dataType),F=((L=l==null?void 0:l.config)==null?void 0:L.groupByColumns)||[],E=((S=l==null?void 0:l.config)==null?void 0:S.metricColumns)||[];if(A==="number"){const P={...b,id:`metric-${b.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};d(l.id,{metricColumns:[...E,P]})}else{const P={...b,id:`groupby-${b.id}-${Date.now()}`,role:"groupby"};d(l.id,{groupByColumns:[...F,P]})}h(!1)},[(M=l==null?void 0:l.config)==null?void 0:M.groupByColumns,(N=l==null?void 0:l.config)==null?void 0:N.metricColumns,l.id,d]),O=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),R=b=>{c(b.active.id)},v=b=>{const{active:A,over:F}=b;if(c(null),!F||A.id===F.id)return;const E=p.findIndex(S=>S.id===A.id),L=p.findIndex(S=>S.id===F.id);if(E!==-1&&L!==-1){const S=s.arrayMove(p,E,L),P=S.filter(J=>J.role==="groupby"),$=S.filter(J=>J.role==="metric");d(l.id,{groupByColumns:P,metricColumns:$})}},w=i?p.find(b=>b.id===i):null,g=b=>{let A="";for(;b>=0;)A=String.fromCharCode(b%26+65)+A,b=Math.floor(b/26)-1;return A};return n?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):p.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(s.DndContext,{sensors:O,collisionDetection:s.closestCenter,onDragStart:R,onDragEnd:v,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(s.SortableContext,{items:p.map(b=>b.id),strategy:s.horizontalListSortingStrategy,children:p.map((b,A)=>e.jsx("th",{style:{width:o[b.id]?`${o[b.id]}px`:void 0,minWidth:o[b.id]?`${o[b.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:g(A)},`letter-${b.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(s.SortableContext,{items:p.map(b=>b.id),strategy:s.horizontalListSortingStrategy,children:p.map(b=>e.jsx(Aa,{column:b,isSelected:(t==null?void 0:t.id)===b.id,onSelect:()=>a(b),availableFields:r,width:o[b.id],onWidthChange:C},b.id))}),e.jsx("th",{className:"w-10 border-r border-border bg-background px-1 py-2",children:e.jsxs(s.Popover,{open:x,onOpenChange:h,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Add column",children:e.jsx(s.Plus,{className:"h-4 w-4"})})}),e.jsx(s.PopoverContent,{className:"w-[280px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search columns..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No columns available."}),e.jsx(s.CommandGroup,{heading:"Available Columns",children:k.map(b=>{const A=s.getDataType(b.dataType),F=A==="number"?s.Hash:A==="date"?s.Calendar:s.Type;return e.jsxs(s.CommandItem,{value:b.label||b.name,onSelect:()=>I(b),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:b.label||b.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:b.entityName})]})]},b.id)})})]})]})})]})})]})]}),e.jsx("tbody",{children:f?e.jsx("tr",{children:e.jsx("td",{colSpan:p.length+2,className:"h-32 text-center",children:e.jsx(s.LoaderCircle,{className:"mx-auto h-6 w-6 animate-spin text-muted-foreground"})})}):j.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:p.length+2,className:"h-32 text-center text-muted-foreground",children:"No data available"})}):j.slice(0,100).map((b,A)=>e.jsxs("tr",{className:s.cn("border-b border-border transition-colors hover:bg-muted/50",A%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:A+1}),p.map(F=>{const E=b[F.name]??b[F.label??""];return e.jsx("td",{style:{width:o[F.id]?`${o[F.id]}px`:void 0,minWidth:o[F.id]?`${o[F.id]}px`:"120px"},className:s.cn("border-r border-border px-3 py-2 text-sm",(t==null?void 0:t.id)===F.id&&"bg-primary/5"),children:e.jsx("span",{className:"block truncate",children:Ma(E,F)})},`${A}-${F.id}`)}),e.jsx("td",{className:"w-10 border-r border-border"})]},A))})]}),e.jsx(s.DragOverlay,{children:w&&e.jsx("div",{className:"rounded border border-primary bg-background px-3 py-2 text-sm font-medium shadow-lg",children:w.label||w.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:[p.length," columns"]})]})]})}function Ma(t,a){if(t==null)return"—";if(typeof t=="number")return a.role==="metric"?new Intl.NumberFormat("en-US",{minimumFractionDigits:0,maximumFractionDigits:2}).format(t):t.toString();if(t instanceof Date||typeof t=="string"&&!isNaN(Date.parse(t))){const n=new Date(t);if(!isNaN(n.getTime()))return n.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}return String(t)}function La({entityGroups:t,isLoading:a=!1}){var O,R;const n=s.useEditorStore(v=>v.card),{updateCardConfig:r,removeGroupByColumn:l,removeMetricColumn:d}=s.useEditorActions(),[i,c]=D.useState(!0),[o,u]=D.useState(""),[x,h]=D.useState(new Set),p=((O=n==null?void 0:n.config)==null?void 0:O.groupByColumns)||[],k=((R=n==null?void 0:n.config)==null?void 0:R.metricColumns)||[],m=v=>{const w=new Set(x);w.has(v)?w.delete(v):w.add(v),h(w)},f=v=>p.some(w=>w.name===v.name&&w.qualifiedEntityName===v.qualifiedEntityName)||k.some(w=>w.name===v.name&&w.qualifiedEntityName===v.qualifiedEntityName),j=(v,w)=>{if(w)if(s.getDataType(v.dataType)==="number"){const y={...v,id:`metric-${v.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};r(n.id,{metricColumns:[...k,y]})}else{const y={...v,id:`groupby-${v.id}-${Date.now()}`,role:"groupby"};r(n.id,{groupByColumns:[...p,y]})}else{const g=p.findIndex(T=>T.name===v.name&&T.qualifiedEntityName===v.qualifiedEntityName),y=k.findIndex(T=>T.name===v.name&&T.qualifiedEntityName===v.qualifiedEntityName);g!==-1&&l(n.id,p[g].id),y!==-1&&d(n.id,k[y].id)}},C=v=>{if(!o)return v;const w=o.toLowerCase();return v.filter(g=>g.name.toLowerCase().includes(w)||g.label&&g.label.toLowerCase().includes(w))},I=v=>{switch(s.getDataType(v)){case"number":return s.Hash;case"date":return s.Calendar;default:return s.Type}};return i?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(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:()=>c(!1),title:"Close panel",children:e.jsx(Ct,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"border-b border-border p-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search columns...",value:o,onChange:v=>u(v.target.value),className:"h-8 pl-8 text-sm"})]})}),(p.length>0||k.length>0)&&e.jsxs("div",{className:"border-b border-border",children:[p.length>0&&e.jsxs(s.Collapsible,{defaultOpen:!0,children:[e.jsxs(s.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(s.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(Ue,{className:"h-3.5 w-3.5 text-blue-500"}),e.jsx("span",{children:"Groupings"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:p.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:p.map(v=>{const w=I(v.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(s.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(w,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:v.label||v.name}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>l(n.id,v.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},v.id)})})})]}),k.length>0&&e.jsxs(s.Collapsible,{defaultOpen:!0,children:[e.jsxs(s.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(s.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(s.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:k.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:k.map(v=>{const w=I(v.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(s.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(w,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:v.label||v.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:v.aggregate}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>d(n.id,v.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},v.id)})})})]})]}),e.jsx(s.ScrollArea,{className:"flex-1",children:e.jsx("div",{className:"p-2",children:a?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent"})}):t.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No columns available"}):t.map(v=>{const w=C(v.columns);if(w.length===0)return null;const g=x.has(v.entityId)||o.length>0;return e.jsxs(s.Collapsible,{open:g,onOpenChange:()=>m(v.entityId),children:[e.jsxs(s.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(s.ChevronRight,{className:s.cn("h-3.5 w-3.5 transition-transform duration-200",g&&"rotate-90")}),e.jsx(s.Table2,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate text-left",children:v.label||v.entityName}),e.jsx("span",{className:"text-xs text-muted-foreground",children:w.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:w.map(y=>{const T=I(y.dataType),M=f(y);return e.jsxs("label",{className:s.cn("flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-sm transition-colors hover:bg-muted/50",M&&"bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:M,onCheckedChange:N=>j(y,N),className:"h-3.5 w-3.5"}),e.jsx(T,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:y.label||y.name})]},y.id)})})})]},v.entityId)})})})]}):e.jsx("div",{className:"flex h-full items-start border-l border-border bg-muted/30 p-2",children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>c(!0),title:"Open panel",children:e.jsx(St,{className:"h-4 w-4"})})})}const Fa=[{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 Oa({value:t,onChange:a,onSubmit:n,onCancel:r,selectedColumn:l,availableColumns:d}){const[i,c]=D.useState(!1),[o,u]=D.useState("column"),x=D.useRef(null);D.useEffect(()=>{const m=f=>{f.key==="Escape"&&t?r():f.key==="Enter"&&t&&!i&&n(t)};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[t,r,n,i]);const h=m=>{const f=`[${m.label||m.name}]`,j=x.current;if(j){const C=j.selectionStart||0,I=j.selectionEnd||0,O=t.slice(0,C)+f+t.slice(I);a(O),setTimeout(()=>{j.setSelectionRange(C+f.length,C+f.length),j.focus()},0)}else a(t+f);c(!1)},p=m=>{const f=x.current;if(f){const j=f.selectionStart||0,C=f.selectionEnd||0,I=t.slice(0,j)+m.syntax+t.slice(C);a(I),setTimeout(()=>{f.setSelectionRange(j+m.name.length+1,j+m.syntax.length-1),f.focus()},0)}else a(t+m.syntax);c(!1)},k=m=>{switch(s.getDataType(m)){case"number":return s.Hash;case"date":return s.Calendar;default:return s.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:l?e.jsx("span",{className:"truncate",children:l.label||l.name}):e.jsx("span",{children:"—"})}),e.jsxs(s.Popover,{open:i&&o==="function",onOpenChange:m=>{c(m),m&&u("function")},children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Insert function",children:e.jsx(wt,{className:"h-4 w-4"})})}),e.jsx(s.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search functions..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No functions found."}),e.jsx(s.CommandGroup,{heading:"Functions",children:Fa.map(m=>e.jsx(s.CommandItem,{value:m.name,onSelect:()=>p(m),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:m.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.description})]}),e.jsx("span",{className:"font-mono text-xs text-muted-foreground/75",children:m.syntax})]})},m.name))})]})]})})]}),e.jsxs(s.Popover,{open:i&&o==="column",onOpenChange:m=>{c(m),m&&u("column")},children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.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(s.ChevronDown,{className:"h-3 w-3"})]})}),e.jsx(s.PopoverContent,{className:"w-[250px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search columns..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No columns found."}),e.jsx(s.CommandGroup,{heading:"Available Columns",children:d.map(m=>{const f=k(m.dataType);return e.jsxs(s.CommandItem,{value:m.label||m.name,onSelect:()=>h(m),children:[e.jsx(f,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:m.label||m.name})]},m.id)})})]})]})})]}),e.jsx("div",{className:"relative flex-1",children:e.jsx(s.Input$1,{ref:x,value:t,onChange:m=>a(m.target.value),placeholder:"Enter a formula or select a column...",className:"h-7 border-border bg-background font-mono text-sm"})}),t&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.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(s.X,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-green-600 hover:bg-green-600/10 hover:text-green-600",onClick:()=>n(t),title:"Apply (Enter)",children:e.jsx(s.Check,{className:"h-4 w-4"})})]})]})}function Ra({className:t}){var p,k,m,f;const a=s.useEditorStore(j=>j.card),[n,r]=D.useState(null),[l,d]=D.useState(""),{columns:i=[],columnGroups:c=[],isLoading:o}=s.useColumns();(p=a==null?void 0:a.config)!=null&&p.groupByColumns,(k=a==null?void 0:a.config)!=null&&k.metricColumns,(m=a==null?void 0:a.config)!=null&&m.groupByColumns,(f=a==null?void 0:a.config)!=null&&f.pivotByColumns;const u=j=>{r(j),d(j?`[${j.label||j.name}]`:"")},x=j=>{console.log("Formula submitted:",j),d(""),r(null)},h=()=>{d(""),r(null)};return e.jsxs("div",{className:s.cn("flex h-full w-full flex-col",t),children:[e.jsx(Oa,{value:l,onChange:d,onSubmit:x,onCancel:h,selectedColumn:n,availableColumns:i}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(Da,{selectedColumn:n,onColumnSelect:u,isLoading:o,sourceFields:i})}),e.jsx(La,{entityGroups:c,isLoading:o})]})]})}function Ba(){var $,J;const[t,a]=D.useState("chart"),[n,r]=D.useState(!1),[l,d]=D.useState(!1),[i,c]=D.useState(!0),o=s.useEditorStore(K=>K.showAIDialog),u=s.useDashboardStore(K=>K.isVisualEditing),{setCardType:x}=s.useEditorActions(),h=s.useEditorStore(K=>K.card.type);D.useEffect(()=>Ea(),[]);const p=K=>{x(K)},k=s.useEditorStore(K=>K.frame),m=s.useEditorStore(K=>K.card);s.useEditorStore(K=>K.activeTabCardId),s.useEditorStore(K=>K.actions.getAvailableFields);const{addCard:f,removeCard:j,updateCard:C,setActiveCard:I,updateFilters:O}=s.useEditorActions(),{columns:R=[],isLoading:v,error:w}=s.useColumns(),g=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),y=m,{getFieldsForContainer:T,setFieldsForContainer:M}=s.useFieldManagement(y),{activeField:N,handleDragStart:b,handleDragEnd:A}=ba({activeCardId:k.activeCardId,sourceFields:R,getFieldsForContainer:T,setFieldsForContainer:M}),F=(K,G)=>{G&&O(K,G)},E=K=>{var G;C(K,{config:{...(G=k.cards.find(H=>H.id===K))==null?void 0:G.config,filters:void 0}})},L=R,S=K=>{if(!K)return 0;let G=K.conditions.length;return K.groups.forEach(H=>{G+=S(H)}),G},P=S((($=y==null?void 0:y.config)==null?void 0:$.filters)||null);return e.jsxs(s.DndContext,{sensors:g,collisionDetection:s.closestCenter,onDragStart:b,onDragEnd:A,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Ts,{isVisible:i,onToggleVisibility:()=>c(!i)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:h==="tableBuilder"?e.jsx(Ra,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!o&&e.jsx(sa,{selectedChart:h,onChartChange:p,groupByFields:T("groupBy"),pivotByFields:T("pivotBy"),metricsFields:T("metrics"),sortByFields:T("sortBy"),activeField:N}),e.jsx(ka,{selectedChart:h,activeView:t,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onFiltersClick:()=>d(!0),filterCount:P,activeCard:y,dataSourceState:m.dataSource||s.EMPTY_DATA_SOURCE,columns:R,columnsLoading:v,columnsError:w,getFieldsForContainer:T,cards:k.cards,activeCardId:k.activeCardId,addCard:f,setActiveCard:I})]})}),!i&&u&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.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(s.Database,{className:"h-4 w-4"})})})]}),y&&e.jsx(ja,{cardId:y.id,filters:((J=y.config)==null?void 0:J.filters)||null,onFiltersChange:F,onClearFilters:E,availableFields:L,isOpen:l,onOpenChange:d}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Ta,{activeField:N||null})})]})}function Va({authToken:t,onSave:a,onClose:n}){const r=D.useRef(null),l=s.useEditorStore(w=>w.showAIDialog),d=s.useEditorStore(w=>w.isDevMode),i=s.useAssistantLayoutStore(w=>w.setFullscreen),c=s.useAssistantLayoutStore(w=>w.setPanelOpen),o=s.useAssistantLayoutStore(w=>w.setContainer),u=s.useAssistantPanel("editor"),x=s.useFullscreenAssistant(),h=s.useAssistantContainer("editor"),p=x==="editor",k=D.useCallback(w=>{o("editor",w)},[o]),{setAuthToken:m}=s.useDashboardActions(),{setShowAIDialog:f,setOnSave:j,setOnClose:C}=s.useEditorActions(),{setActiveAssistantType:I}=s.useAIActions();D.useEffect(()=>{a&&j(a),n&&C(n)},[a,j,n,C]),D.useEffect(()=>{t&&t.accessToken&&m(t)},[t,m]),D.useEffect(()=>{var w,g;l?((w=r.current)==null||w.resize(40),c("editor",!0),I("editor")):((g=r.current)==null||g.resize(0),c("editor",!1),x==="editor"&&i(null),I(null))},[l,c,I,i,x]);function O(w){w<1?(f(!1),c("editor",!1),x==="editor"&&i(null),I(null)):(l||(f(!0),I("editor")),u.isOpen||c("editor",!0))}function R(){return e.jsxs(e.Fragment,{children:[e.jsx(Ts,{isVisible:!0,onToggleVisibility:()=>{}}),e.jsxs("div",{className:"relative flex grow border-l",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:s.cn("grow transition-opacity",p&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Bn,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:O,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(ps,{isFullscreen:p,onFullscreenChange:w=>i(w?"editor":null),fullscreenContainer:h})})})]}),e.jsx("div",{ref:k,className:s.cn("absolute inset-0",!p&&"pointer-events-none")})]})]})}function v(){return e.jsxs("div",{className:"relative flex h-full grow",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:s.cn("flex grow transition-opacity",p&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Ba,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:O,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(ps,{isFullscreen:p,onFullscreenChange:w=>i(w?"editor":null),fullscreenContainer:h})})})]}),e.jsx("div",{ref:k,className:s.cn("absolute inset-0",!p&&"pointer-events-none")})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:d?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:R()}):v()})}function Pa(){s.useDashboardStore(i=>i.selectedCardId);const t=s.useDashboardStore(i=>i.selectedSheetId),{setIsVisualEditing:a}=s.useDashboardStore(i=>i.actions),n=s.useDashboardStore(i=>i.isVisualEditing),r=s.useDashboardStore(i=>i.actions.updateFrame);function l(i){t&&(r(t,i),a(!1))}function d(){a(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!n}),children:e.jsx(Va,{onSave:l,onClose:d})})}exports.default=Pa;
188
+ `;O(B)}function G(){return e.jsxs(s.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(s.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(Ot,{})}),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(s.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(s.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(Rt,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function H(){var B,U,V,W,X,se;return e.jsx("div",{role:"editor-controls",className:"item-center flex flex-wrap justify-between gap-2 px-6 py-4",children:e.jsxs("div",{className:"flex grow items-center gap-4",children:[e.jsxs(s.Button,{title:"Shift + Enter",disabled:N||b,onClick:()=>{P()},className:"h-8 shrink-0",size:"sm",children:[N||b?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(s.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),e.jsx(Lt,{errorSql:L,sql:M==null?void 0:M.sql,error:$,onDebugWithAssistant:K}),e.jsx(qe.EditorClearButton,{}),e.jsxs(s.Toggle,{pressed:n,onPressedChange:_=>r(_),className:"h-8",size:"sm",variant:"outline",children:[e.jsx(Ft,{className:"mr-2 size-4 text-foreground/70"}),"Python"]}),!d&&e.jsxs("button",{disabled:d,onClick:()=>{R(!0)},className:"flex h-8 w-full cursor-text items-center justify-start rounded-md bg-muted/50 px-3 text-left text-sm text-muted-foreground",children:[e.jsx(s.Sparkles,{className:"mr-3 size-4 text-foreground/70"}),"Type your question..."]}),e.jsxs("div",{className:"flex flex-1 items-center justify-end gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((U=(B=l.preferences)==null?void 0:B.tablePrefs)==null?void 0:U.enableDevModePagination)??!1,onCheckedChange:_=>{var te;j({...l.preferences,tablePrefs:{...(te=l.preferences)==null?void 0:te.tablePrefs,enableDevModePagination:_}})}}),e.jsx(s.Label,{htmlFor:"pagination",className:"cursor-pointer text-sm",children:"Paginate"}),((W=(V=l.preferences)==null?void 0:V.tablePrefs)==null?void 0:W.enableDevModePagination)&&e.jsxs(s.Select,{value:String(((se=(X=l.preferences)==null?void 0:X.tablePrefs)==null?void 0:se.pageSize)||50),onValueChange:_=>{var le,ce,z;const te=Number(_),Y={...l,preferences:{...l.preferences,tablePrefs:{...(le=l.preferences)==null?void 0:le.tablePrefs,pageSize:te}},paginationConfig:{page:1,pageSize:te}};v(Y),w(Y),l.sql&&((z=(ce=l.preferences)==null?void 0:ce.tablePrefs)!=null&&z.enableDevModePagination)&&y(!0)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"10",children:"10"}),e.jsx(s.SelectItem,{value:"25",children:"25"}),e.jsx(s.SelectItem,{value:"50",children:"50"}),e.jsx(s.SelectItem,{value:"100",children:"100"}),e.jsx(s.SelectItem,{value:"500",children:"500"}),e.jsx(s.SelectItem,{value:"1000",children:"1000"})]})]})]}),o&&o.length>0&&e.jsxs(s.HoverCard,{openDelay:200,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",className:"h-8 gap-2 px-2",children:[e.jsx(s.Filter,{className:"size-4"}),e.jsx(s.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:o.length})]})}),e.jsx(s.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(s.CodeHighlighter,{code:JSON.stringify(o,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:G()}),H()]})}const Vt=[{value:"table",label:"Table",icon:s.Table2},{value:"aggregateTable",label:"Aggregate",icon:s.Layers},{value:"pivotTable",label:"Pivot",icon:s.Grid3x3}];function Pt({className:t}){const a=s.useEditorStore(o=>o.card),{setCardType:n,setCard:r,updateCardInFrame:l}=s.useEditorActions(),d=["table","aggregateTable","pivotTable"].includes(a.type),i=s.hasValidCardConfig(a.config);if(!d||!i)return null;const c=o=>{var x;const u=o;if(u==="aggregateTable"&&((x=a.config)!=null&&x.pivotByColumns)&&a.config.pivotByColumns.length>0){const h={...a,type:u,config:{...a.config,pivotByColumns:[]}};r(h),l(h)}else{n(u);const h={...a,type:u};l(h)}};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsx(s.RadioGroup,{value:a.type,onValueChange:c,className:"flex flex-row items-center justify-between gap-1 rounded-lg border p-1",children:Vt.map(o=>{const u=o.icon,x=a.type===o.value;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(s.RadioGroupItem,{value:o.value,id:`table-type-${o.value}`,className:"peer sr-only"}),e.jsxs(s.Label,{htmlFor:`table-type-${o.value}`,className:s.cn("flex cursor-pointer items-center gap-1.5 rounded-md px-3 py-1 text-sm font-medium transition-all",x?"bg-muted text-foreground shadow-sm":"text-muted-foreground hover:bg-muted/50"),children:[e.jsx(u,{className:"h-3.5 w-3.5"}),o.label]})]},o.value)})})})}function zt({type:t,isLinked:a,className:n}){const r=s.useDashboardStore(p=>p.selectedFrameId),l=s.useManagementStore(p=>p.selectedVisual),d=s.useEditorStore(p=>p.frame);let i;if(t)i=t;else if(a!==void 0)i=a?"linked":"library";else if(!!!(d!=null&&d.visualId||l!=null&&l.id)&&r)i="local";else if(l&&!r)i="library";else if(d!=null&&d.visualId&&r)i="linked";else if(l!=null&&l.id&&r)i="library";else return null;if(i==="local")return null;const c={linked:"border-purple-200/70 bg-gradient-to-r from-purple-50/50 to-purple-100/30 text-purple-900 shadow-sm hover:from-purple-100/60 hover:to-purple-100/50 hover:shadow-md dark:border-purple-800/50 dark:from-purple-950/40 dark:to-purple-900/30 dark:text-purple-100 dark:hover:from-purple-950/60 dark:hover:to-purple-900/50",library:"border-blue-200/70 bg-gradient-to-r from-blue-50/50 to-blue-100/30 text-blue-900 shadow-sm hover:from-blue-100/60 hover:to-blue-100/50 hover:shadow-md dark:border-blue-800/50 dark:from-blue-950/40 dark:to-blue-900/30 dark:text-blue-100 dark:hover:from-blue-950/60 dark:hover:to-blue-900/50"},o={linked:"Linked to library: Changes made here update the library visual and all linked instances.",library:"Library visual: Share and reuse this visual across multiple dashboards."},u={linked:"border-purple-200 bg-purple-50 text-purple-900 dark:border-purple-800 dark:bg-purple-950 dark:text-purple-100",library:"border-blue-200 bg-blue-50 text-blue-900 dark:border-blue-800 dark:bg-blue-950 dark:text-blue-100"},x={linked:"fill-purple-50 dark:fill-purple-950",library:"fill-blue-50 dark:fill-blue-950"},h={linked:e.jsx(ft,{className:"h-3.5 w-3.5"}),library:e.jsx(pt,{className:"h-3.5 w-3.5"})};return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:s.cn("cursor-help select-none transition-all",c[i],n),children:h[i]})}),e.jsxs(s.TooltipContent,{side:"bottom",className:s.cn("max-w-xs",u[i]),children:[e.jsx(s.TooltipArrow,{className:x[i]}),e.jsx("p",{children:o[i]})]})]})})}function Is({className:t,...a}){var K,G,H;const n=s.useEditorStore(B=>B.card),r=((K=n.customCardPreferences)==null?void 0:K.showCardHeader)??!0,l=((H=(G=n.preferences)==null?void 0:G.displayOptions)==null?void 0:H.showInlineFilterBar)??!0,d=s.useEditorStore(B=>B.frame),i=s.useDashboardStore(B=>B.dashboard.filters),c=s.useDashboardStore(B=>B.selectedSheetId),[o,u]=D.useState(!1),{currentUser:x}=s.useCurrentUserInfo(),{tokenProps:h}=D.useContext(s.SemaphorContext),p=s.useEditorStore(B=>B.actions.setRunSql),{updateFilter:k}=s.useDashboardActions(),m=i==null?void 0:i.find(B=>B.id===d.filterId),{data:f,isLoading:j,isFetching:C,errorMessage:I,errorSql:O,pagination:R}=s.useDashboardCardQuery(n),v=D.useMemo(()=>(f==null?void 0:f.records)||[],[f==null?void 0:f.records]),{setCard:w,updateCardInFrame:g,setIsDevMode:y,setCardSql:T}=s.useEditorActions(),{data:M}=s.useTopoJson(n),N=D.useMemo(()=>{var B;return n.type!=="pivotTable"||!((B=f==null?void 0:f.records)!=null&&B.length)?null:{records:f.records,columnSubtotalMeta:f.columnSubtotalMeta,subtotalColumns:f.subtotalColumns||[],pivotSchema:f.pivotSchema||[],groupByColumns:f.groupByColumns}},[n.type,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]),b=s.usePivotTableConfig(n,N),A=B=>{y(!0),T(B||O||n.sql||n.python||""),setTimeout(()=>{p(!0)},100)},F=()=>{u(!0)},E=D.useMemo(()=>{const B=typeof window<"u"?window.location.href:"",U=typeof navigator<"u"?navigator.userAgent:"",V=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:s.FeedbackCategory.QUERY_GENERATION,user:x,tokenContext:h,systemState:{cardConfig:n.config,dataSource:n.dataSource,dashboardFilters:i,errorMessage:I||void 0,errorSql:O||n.sql||n.python,generatedSql:O||n.sql},metadata:{url:B,userAgent:U,timestamp:new Date().toISOString(),viewport:V}}},[x,h,n,i,I,O]),L=(B,U)=>{var W,X;const V={...n,paginationConfig:{page:B+1,pageSize:U}};w(V),g(V),n.sql&&((X=(W=n.preferences)==null?void 0:W.tablePrefs)!=null&&X.enableDevModePagination)&&p(!0)},S=B=>{var W,X,se,_;const U=s.sortStateToSortByColumns(B,(W=n.config)==null?void 0:W.metricColumns,(X=n.config)==null?void 0:X.groupByColumns),V={...n,config:{...n.config||{},sortByColumns:U}};w(V),g(V),n.sql&&((_=(se=n.preferences)==null?void 0:se.tablePrefs)!=null&&_.enableDevModePagination)&&p(!0)},P=D.useMemo(()=>!n.id||!(f!=null&&f.records)?null:s.createChartConfig({card:n,data:f==null?void 0:f.records,cardType:n.type,queryConfig:n.queryConfig,customCfg:n.customCfg,preferences:n.preferences,topoJson:M}),[n.id,f==null?void 0:f.records,n.type,n.customCfg,n.preferences,M]);function $(B){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(s.EditorCustomVisual,{card:B})})}function J(){if(f!=null&&f.records&&(f==null?void 0:f.records.length)===0&&!j&&!C)return I?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(He,{error:I,errorSql:O||n.sql||n.python,onOpenInEditor:A,onSendFeedback:F,showFeedbackButton:!0,errorTitle:"Unable to Create Visual"})}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((j||C)&&(!(f!=null&&f.records)||f.records.length===0))return n.type==="table"?e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableSkeleton,{})}):e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!n.id)return null;if(n.type==="custom")return $(n);if(!["table","pivotTable","aggregateTable","custom"].includes(n.type)&&P)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:j||C?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:P})});if(n.type==="table")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:n,data:v,paginationMetadata:R,onPaginationChange:L,onSortChange:S,isLoading:j||C})});if(n.type==="pivotTable"&&b)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.PivotTableTanstack,{card:n,data:b.data,options:b.options,onAggregationChange:B=>{const U=s.handleAggregationChange(B,n.config),V={...n,config:U};w(V),g(V)},onAggregationLabelChange:B=>{const U=s.handleAggregationLabelChange(B,n.config),V={...n,config:U};w(V),g(V)}})});if(n.type==="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(s.AggregateTable,{card:n,data:(f==null?void 0:f.records)||[],groupByColumns:f==null?void 0:f.groupByColumns,pivotSchema:f==null?void 0:f.pivotSchema,paginationMetadata:R,onPaginationChange:L,onAggregationChange:B=>{const U=s.handleAggregationChange(B,n.config),V={...n,config:U};w(V),g(V)},isLoading:j||C})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...a,children:[(j||C)&&(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(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),r&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.CardTitle,{className:"text-base",children:e.jsx(s.EditableText,{value:n.title,onSave:B=>w({...n,title:B}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(zt,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(Pt,{})})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:n.description||"",onSave:B=>w({...n,description:B}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),m&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:m.title||m.column,onSave:B=>k({...m,title:B}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:m})]})]}),l&&n.inlineFilters&&n.inlineFilters.length>0&&e.jsx("div",{className:"px-6 pb-3",children:e.jsx(s.InlineFilterBar,{card:n,sheetId:c||""})}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:J()}),e.jsx(s.FeedbackDialog,{open:o,onOpenChange:u,feedbackData:E,showDebugInfo:!0})]})}const ze=({language:t,value:a,onChange:n,readonly:r})=>e.jsx(s.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:t,value:a,onChange:n}),$t=()=>e.jsxs(s.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(s.DialogTitle,{children:"Customize Card"})}),e.jsxs(s.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."})]})]}),Kt=({customCode:t,cardCustomCfgString:a,mergedConfig:n,onConfigChange:r,onCodeChange:l})=>e.jsxs(s.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(s.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(s.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(s.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(s.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(s.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ze,{language:"json",value:n,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ze,{readonly:!0,language:"json",value:a,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ze,{language:"javascript",value:t,onChange:l})})]}),Gt=({error:t,hasCardCustomConfig:a,onReset:n,onApply:r,onClose:l})=>e.jsxs(s.DialogFooter,{className:"flex items-center",children:[e.jsx(s.Label,{className:"mr-2 text-red-500",children:t}),e.jsx(s.Button,{disabled:!a,onClick:n,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:l,variant:"outline",children:"Close"})]});function qt(){const[t,a]=D.useState(!1),[n,r]=D.useState(""),[l,d]=D.useState(""),[i,c]=D.useState(""),[o,u]=D.useState(""),x=s.useEditorStore(v=>v.card),h=s.useEditorStore(v=>v.card.customCfg),p=h?JSON.stringify(h,null,2):"",{data:k}=s.useDashboardCardQuery(x),{data:m}=s.useTopoJson(x),{setCardCustomCfg:f,setCustomVisualCode:j}=s.useEditorActions(),C=v=>{var w,g;return JSON.stringify({...v,data:{...v.data,datasets:(g=(w=v.data)==null?void 0:w.datasets)==null?void 0:g.map(y=>({...y,data:[]}))}},null,2)},I=()=>{var w,g;if(!((w=k==null?void 0:k.records)!=null&&w.length))return;const v=s.createChartConfig({card:x,data:k.records,cardType:x.type,queryConfig:x.queryConfig,preferences:x.preferences,topoJson:m});if(v){r(C(v)),c(((g=x.preferences)==null?void 0:g.customVisualCode)||"");const y=s.merge(v,h);d(C(y))}},O=()=>{try{if(i&&j(i),l){const v=JSON.parse(l),w=s.getObjectDiff(JSON.parse(n),v);f(w),u("")}}catch{u("Invalid JSON configuration")}},R=Object.keys(h||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:a,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:I,className:R?"":"text-green-600 hover:text-green-700",children:e.jsx(s.Settings,{className:"h-4 w-4"})})}),e.jsxs(s.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx($t,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Is,{className:"w-1/2 rounded shadow-none"})}),e.jsx(Kt,{customCode:i,cardCustomCfgString:p,mergedConfig:l,onConfigChange:v=>d(v??""),onCodeChange:v=>c(v??"")})]}),e.jsx(Gt,{error:o,hasCardCustomConfig:!!h,onReset:()=>{d(n),f(null)},onApply:O,onClose:()=>a(!1)})]})]})}function Ut({isStarred:t,onClick:a,className:n}){const r=l=>{l.stopPropagation(),l.preventDefault(),a(l)};return e.jsx("button",{type:"button",onClick:r,className:s.cn("flex items-center justify-center rounded-sm p-0.5 transition-all","hover:bg-muted/80",n),"aria-label":t?"Remove from favorites":"Add to favorites",children:e.jsx(s.Star,{className:s.cn("h-3.5 w-3.5 transition-colors",t?"fill-yellow-400 text-yellow-400":"text-muted-foreground hover:text-foreground")})})}function rs({chartType:t,chartName:a,isCustom:n=!1,pluginName:r,isStarred:l,showStar:d=!0,onSelect:i,onToggleStar:c}){return e.jsxs("button",{onClick:i,className:s.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:[d&&e.jsx("div",{className:s.cn("absolute left-1 top-1 transition-opacity",l?"opacity-100":"opacity-0 group-hover:opacity-100"),children:e.jsx(Ut,{isStarred:l,onClick:()=>c()})}),n&&r&&e.jsx("div",{className:"absolute right-1 top-1",children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center justify-center",children:e.jsx(s.Info,{className:"h-3 w-3 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"top",className:"text-xs",children:r})]})}),e.jsx(s.ChartIcon,{chartType:t,chartName:a,isCustom:n,className:"h-6 w-6"}),e.jsx("span",{title:a,className:"line-clamp-2 text-center text-xs font-medium text-foreground",children:a})]})}const ls=[{id:"table",name:"Table"},{id:"bar",name:"Bar Chart"},{id:"line",name:"Line Chart"},{id:"stackedBar",name:"Stacked Bar"},{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:"kpi",name:"KPI"},{id:"text",name:"Text"},{id:"map",name:"Map"}];function Ds({onChartSelect:t,onClose:a}){const[n,r]=D.useState(""),{starredCharts:l,isStarred:d,toggleStar:i}=s.useStarredChartsStore(),{data:c=[],isLoading:o}=s.useCustomVisualsQuery(),{setCardType:u,setCardPreferences:x,setIsDevMode:h}=s.useEditorStore(v=>v.actions),{setCardCustomCfg:p,setCustomCardPreferences:k,setQueryConfig:m}=s.useEditorActions(),f=D.useMemo(()=>{if(!n)return ls;const v=n.toLowerCase();return ls.filter(w=>w.name.toLowerCase().includes(v))},[n]),j=D.useMemo(()=>{const v=c.filter(g=>g.componentType==="chart");if(!n)return v;const w=n.toLowerCase();return v.filter(g=>g.name.toLowerCase().includes(w))},[c,n]),C=v=>{p(null),x({}),u(v),["custom","text","map"].includes(v)&&(h(!0),m(void 0)),t==null||t(v),a==null||a()},I=v=>{p(null),x({}),u("custom"),k({type:"component",visualType:"single",url:v.url,componentName:v.name,icon:v.icon,pluginChartType:v.chartType}),m(void 0),t==null||t("custom",v),a==null||a()},O=v=>{const w={type:"default",id:v.id,name:v.name};i(w)},R=v=>{const w={type:"custom",id:v.name,url:v.url,icon:v.icon,name:v.name};i(w)};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(s.Search,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search charts...",value:n,onChange:v=>r(v.target.value),className:"h-auto border-0 p-0 text-sm focus-visible:ring-0 focus-visible:ring-offset-0"})]}),e.jsxs("div",{className:"max-h-[400px] overflow-y-auto",children:[f.length>0&&e.jsxs("div",{className:"mb-3",children:[e.jsx("span",{className:"mb-2 block text-xs font-medium text-muted-foreground",children:"Default Charts"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:f.map(v=>e.jsx(rs,{chartType:v.id,chartName:v.name,isCustom:!1,isStarred:d("default",v.id),onSelect:()=>C(v.id),onToggleStar:()=>O(v)},v.id))})]}),j.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-3"}),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:j.map((v,w)=>e.jsx(rs,{chartName:v.name,isCustom:!0,pluginName:v.pluginName,isStarred:d("custom",v.name),onSelect:()=>I(v),onToggleStar:()=>R(v)},`${v.url}-${v.name}-${w}`))})]})]}),o&&e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-3"}),e.jsx("div",{className:"py-4 text-center text-sm text-muted-foreground",children:"Loading custom charts..."})]}),f.length===0&&j.length===0&&!o&&e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No charts found"})]})]})}function Ms({variant:t="ghost"}){var d,i;const[a,n]=D.useState(!1),r=s.useEditorStore(c=>c.card),l=r.type;return e.jsxs(s.Popover,{open:a,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(s.SelectedChartIcon,{className:"size-4",chartType:l,customIcon:(d=r.customCardPreferences)==null?void 0:d.icon,componentName:(i=r.customCardPreferences)==null?void 0:i.componentName})})}),e.jsx(s.PopoverContent,{onOpenAutoFocus:c=>c.preventDefault(),className:"z-[70] w-[360px] p-3",children:e.jsx(Ds,{onClose:()=>n(!1)})})]})}function Ht({error:t,className:a="",textClassName:n="",copyButtonClassName:r=""}){const[l,d]=D.useState(!1),i=D.useRef(null),c=D.useRef(!1);function o(){t&&!c.current&&navigator.clipboard.writeText(t)}function u(p){(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),o())}function x(){const p=window.getSelection();if(p&&p.toString().trim()!==""){const k=p.toString();navigator.clipboard.writeText(k),d(!0),c.current=!0,setTimeout(()=>{d(!1),c.current=!1},1e3)}else c.current=!1}function h(){d(!1),c.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${a}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:i,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${n}`,onClick:o,onKeyDown:u,onMouseUp:x,onMouseDown:h,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),l&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function Jt(){const t=s.useEditorStore(o=>{var u,x;return(x=(u=o.card.preferences)==null?void 0:u.chartOptions)==null?void 0:x.indexAxis}),a=s.useEditorStore(o=>o.card.type),{setChartOrientation:n,setCardPreferences:r}=s.useEditorStore(o=>o.actions),l=o=>{if(n(o),a!=="bullet")return;const u=o==="y"?"horizontal":"vertical",x=s.useEditorStore.getState().card.preferences,h={...x||{},bulletConfig:{...(x==null?void 0:x.bulletConfig)||{},orientation:u}};r(h)};function d(){const o=t??"x",u=()=>{l(o==="x"?"y":"x")};return e.jsx(s.IconButton,{onClick:u,tooltip:"Chart Orientation",children:o==="x"?e.jsx(Pe,{className:"size-4"}):e.jsx(Ve,{className:"size-4"})})}function i(){const o=()=>{l(t==="y"||t===void 0?"x":"y")};return e.jsx(s.IconButton,{onClick:o,tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(Pe,{className:"size-4"}):e.jsx(Ve,{className:"size-4"})})}function c(){const o=t??"y",u=()=>{l(o==="y"?"x":"y")};return e.jsx(s.IconButton,{onClick:u,tooltip:"Chart Orientation",children:o==="y"?e.jsx(Ve,{className:"size-4"}):e.jsx(Pe,{className:"size-4"})})}return e.jsx(e.Fragment,{children:a==="funnel"?i():a==="bullet"?c():d()})}function _t({className:t}){var k,m,f,j,C,I,O,R,v,w;const a=s.useEditorStore(g=>g.card),{setCardPreferences:n,updateCardInFrame:r,setCard:l}=s.useEditorActions(),[d,i]=D.useState(!1),c=((m=(k=a.preferences)==null?void 0:k.displayOptions)==null?void 0:m.showFilterInfo)??!0,o=((j=(f=a.preferences)==null?void 0:f.displayOptions)==null?void 0:j.showCardToolbar)??!0,u=((I=(C=a.preferences)==null?void 0:C.displayOptions)==null?void 0:I.showChrome)??!0,x=((R=(O=a.preferences)==null?void 0:O.displayOptions)==null?void 0:R.allowScroll)??!0,h=((w=(v=a.preferences)==null?void 0:v.displayOptions)==null?void 0:w.showInlineFilterBar)??!0,p=(g,y)=>{var N;const T={...a.preferences,displayOptions:{...(N=a.preferences)==null?void 0:N.displayOptions,[g]:y}};n(T);const M={...a,preferences:T};l(M),r(M)};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsxs(s.DropdownMenu,{modal:!1,open:d,onOpenChange:i,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{className:"h-8 w-8 p-0",tooltip:"Display Options",children:e.jsx(Ss,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(s.DropdownMenuLabel,{children:"Display Options"}),e.jsx(s.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(s.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:g=>{p("showFilterInfo",g)},onSelect:g=>g.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(s.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:g=>{p("showCardToolbar",g)},onSelect:g=>g.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(s.DropdownMenuCheckboxItem,{checked:u,onCheckedChange:g=>{p("showChrome",g)},onSelect:g=>g.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(s.DropdownMenuCheckboxItem,{checked:x,onCheckedChange:g=>{p("allowScroll",g)},onSelect:g=>g.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(s.DropdownMenuCheckboxItem,{checked:h,onCheckedChange:g=>{p("showInlineFilterBar",g)},onSelect:g=>g.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 Qt(){const[t,a]=D.useState(!1),n=s.useEditorStore(h=>h.card),r=s.useEditorStore(h=>h.selectedConnectionId),{setCard:l}=s.useEditorActions(),d=s.useDashboardStore(h=>h.actions.removeCardInlineFilterValue),i=(n==null?void 0:n.inlineFilters)||[];function c(h){const p=h.qualifiedFieldName||h.name;if(i.find(I=>I.column===p))return;const m=h.qualifiedFieldName?h.qualifiedFieldName.split(".").slice(0,-1).join("."):h.qualifiedEntityName||h.entityName,f=s.fmt(h.name),j=h.qualifiedFieldName||f,C={id:s.v4(),column:p,title:h.label||h.name,dataType:h.dataType,table:h.entityName||"",database:"",connectionId:r||"",operation:"in",sql:s.getDefaultFilterSql(h.dataType,m,j),width:250};l({...n,inlineFilters:[...i,C]})}function o(h){const p=i.filter(k=>k.id!==h);l({...n,inlineFilters:p}),d(n.id,h)}function u(h,p){const k=i.map(m=>m.id===h?{...m,...p}:m);l({...n,inlineFilters:k})}return["bar","line","pie","doughnut","table","stackedBar","stackedLine","horizontalBar","radar","polarArea","scatter","bubble","funnel","aggregateTable","custom"].includes(n==null?void 0:n.type)?e.jsx("div",{className:"flex items-center gap-1",children:e.jsxs(s.Popover,{open:t,onOpenChange:a,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.IconButton,{tooltip:"Add Inline Filter",className:s.cn("relative",{"text-primary":i.length>0}),children:[e.jsx(jt,{className:"h-4 w-4"}),i.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:i.length})]})}),e.jsx(s.PopoverContent,{align:"end",className:"w-80 p-0",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 max-h-[300px] flex-col overflow-hidden",children:e.jsx(s.DndContext,{collisionDetection:s.closestCenter,children:e.jsx(s.SortableContext,{items:[],strategy:s.verticalListSortingStrategy,children:e.jsx(s.FieldsList,{context:"inline-filter",onFieldSelect:c,inlineFilters:i})})})}),i.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:i.map(h=>e.jsx(Yt,{filter:h,onUpdate:p=>u(h.id,p),onRemove:()=>o(h.id)},h.id))})]})]})})]})}):null}function Yt({filter:t,onUpdate:a,onRemove:n}){return e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-muted px-2 py-1.5 text-sm",children:[e.jsx("span",{className:"truncate",title:t.column,children:t.title}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(s.CustomFilterPopover,{filter:t,variant:"inline",onAccept:r=>a(r),trigger:e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0",title:"Configure filter",children:e.jsx(s.Settings2,{className:"h-3 w-3"})})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0 hover:bg-destructive/10 hover:text-destructive",onClick:n,children:e.jsx(s.X,{className:"h-3 w-3"})})]})]})}function Ls(){const t=s.useEditorStore(d=>d.card),a=s.useEditorStore(d=>{var i,c;return(c=(i=d.card)==null?void 0:i.preferences)==null?void 0:c.chartOptions}),n=s.getChartGridStyle(a),{setChartGrid:r}=s.useEditorActions();function l(){const d=["xy","none","x","y"],c=(d.indexOf(n)+1)%d.length;r(d[c])}return e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel","bullet"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(Jt,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsx(e.Fragment,{}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(t.type)&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:l,children:[(n==="xy"||!n)&&e.jsx(s.Grid3x3,{className:"size-4"}),n==="x"&&e.jsx(Ns,{className:"size-4"}),n==="y"&&e.jsx(Ue,{className:"size-4"}),n==="none"&&e.jsx(kt,{className:"size-4"})]}),e.jsx(Qt,{}),e.jsx(_t,{})]})}function Wt(){const t=s.useEditorStore(m=>m.frame),a=s.useEditorStore(m=>m.card),{setFrame:n,setActiveTabCardId:r,setCard:l,updateCardInFrame:d}=s.useEditorActions(),i=(m,f)=>{m.dataTransfer.setData("tabIndex",f.toString())},c=m=>{m.preventDefault()},o=(m,f)=>{const j=m.dataTransfer.getData("tabIndex");if(j===f.toString())return;const C=Array.from(t.cards),[I]=C.splice(parseInt(j),1);C.splice(f,0,I),n({...t,cards:C})};function u(m){const f=t.cards.filter(I=>I.id!==m),j=f[0],C={...t,cards:f,activeCardId:j.id};n(C),r(j.id),l(j)}function x(m,f){const j={...t,cards:[...t.cards,f],activeCardId:m.id};n(j),r(f.id)}function h(){const m={...a,id:s.v4(),title:`${a.title} Copy`,tabTitle:`${a.tabTitle||a.title} Copy`};x(a,m)}function p(m){const f={dataSource:m.dataSource,connectionId:m.connectionId,lastSelectedDatabase:m.lastSelectedDatabase,lastSelectedSchema:m.lastSelectedSchema,lastSelectedTable:m.lastSelectedTable,lastSelectedDatamodelId:m.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};x(m,f)}function k(m,f){return m.cards.length===1&&(f.displayTab===!0||f.displayTab===void 0)||m.activeCardId!==f.id&&(f.displayTab===!0||f.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const j=f.displayTab===void 0?!1:!f.displayTab;l({...f,displayTab:j}),d({...f,displayTab:j})},children:f.displayTab===!0||f.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(ct,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(s.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[t.cards.map((m,f)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:j=>i(j,f),onDragOver:c,onDrop:j=>o(j,f),className:"",value:m.id,children:[k(t,m),e.jsx(s.Editable,{enabled:t.activeCardId===m.id,text:m.tabTitle||m.title,onSave:j=>{l({...a,tabTitle:j}),d({...a,tabTitle:j})},children:m.tabTitle||m.title},m.id),t.activeCardId===m.id&&e.jsx(s.CopyPlus,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:j=>{j.stopPropagation(),h()}}),t.activeCardId===m.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>u(m.id)})]},m.id)),e.jsx(s.IconButton,{tooltip:"Add Card",className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",onClick:()=>p(a),children:e.jsx(s.Plus,{className:"h-4 w-4"})})]})})}function Ge(){const t=s.useEditorStore(j=>j.frame),a=s.useEditorStore(j=>j.card),n=s.useEditorStore(j=>j.isSqlRunning),r=s.useEditorStore(j=>j.isDevMode),{setFrame:l,setActiveTabCardId:d,setCard:i,setIsDevMode:c,setRunSql:o}=s.useEditorActions(),{data:u,isLoading:x,isFetching:h,isError:p}=s.useDashboardCardQuery(a);function k(j){const C=t.cards.find(I=>I.id===j);if(C!=null&&C.sql){r||c(!0),d(j);return}if(C!=null&&C.queryConfig){r&&c(!1),m(j),d(j);return}r||m(j),d(j)}function m(j){const C={...t,cards:t.cards.map(O=>O.id===a.id?a:O),activeCardId:j};l(C);const I=C.cards.find(O=>O.id===j);I.sql&&o(!0),i(I)}function f(){return a.type==="kpi"?x||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.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 border-border",children:e.jsx(s.KPICard,{card:a,data:u==null?void 0:u.records,isPending:x||h,isError:p})})}):a.type==="text"?x||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.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(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:n,card:a,data:u==null?void 0:u.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Is,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:k,value:t.activeCardId,className:"flex grow flex-col",children:[t.cards.map(j=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:j.id,children:f()},j.id)),e.jsx(Wt,{})]})}function os({children:t}){const a=s.useEditorStore(b=>b.frame),n=s.useEditorStore(b=>b.card),r=s.useEditorStore(b=>b.isDevMode),l=s.useEditorStore(b=>b.isShowingVisual),d=s.useDashboardStore(b=>b.isVisualEditing),i=s.useEditorStore(b=>b.pythonStdOut),c=s.useEditorStore(b=>b.actions.setRunSql),{setFrame:o,setCard:u,setActiveTabCardId:x,runAssistant:h,setIsDevMode:p,setCardPreferences:k}=s.useEditorActions(),{data:m,isLoading:f,isFetching:j,errorMessage:C,refetch:I,pagination:O}=s.useDashboardCardQuery(n),R=D.useMemo(()=>(m==null?void 0:m.records)||[],[m==null?void 0:m.records]),[v,w]=D.useState(!1);D.useEffect(()=>{j||w(!1)},[j]);function g(b,A){var L,S;const F={...n,paginationConfig:{page:b+1,pageSize:A}};u(F);const E={...a,cards:a.cards.map(P=>P.id===n.id?F:P)};o(E),n.sql&&((S=(L=n.preferences)==null?void 0:L.tablePrefs)!=null&&S.enableDevModePagination)&&c(!0)}function y(b){var L,S,P,$;const A=s.sortStateToSortByColumns(b,(L=n.config)==null?void 0:L.metricColumns,(S=n.config)==null?void 0:S.groupByColumns),F={...n,config:{...n.config||{},sortByColumns:A}};u(F);const E={...a,cards:a.cards.map(J=>J.id===n.id?F:J)};o(E),n.sql&&(($=(P=n.preferences)==null?void 0:P.tablePrefs)!=null&&$.enableDevModePagination)&&c(!0)}function T(){const b=JSON.stringify(m==null?void 0:m.records,null,2),A=new Blob([b],{type:"application/json"}),F=URL.createObjectURL(A),E=document.createElement("a");E.href=F,E.download=`${n.title}.json`,E.click()}function M(){const A=[Object.keys(m==null?void 0:m.records.reduce((S,P)=>({...S,...P}),{})).join(","),...((m==null?void 0:m.records)||[]).map(S=>Object.values(S).join(","))].join(`
189
+ `),F=new Blob([A],{type:"text/csv"}),E=URL.createObjectURL(F),L=document.createElement("a");L.href=E,L.download=`${n.title}.csv`,L.click()}function N(){const b=`Can you get the documentation for ${n.type} chart?`;h(b)}return n?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 px-6",children:[l&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(Ms,{}),d&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:N,children:e.jsx(ot,{className:"size-4"})}),!["table","custom"].includes(n.type)&&d&&e.jsx(qt,{})]}),!l&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:M,children:e.jsx(s.PiFileCsv,{className:"size-4"})}),e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:T,children:e.jsx(dt,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(m==null?void 0:m.records,null,2),className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t,e.jsx(s.IconButton,{tooltip:"Refresh",disabled:f||j,onClick:()=>{w(!0),I()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":v})})}),e.jsx(Ls,{})]}),r&&e.jsx(Zt,{})]}),l?e.jsx(Ge,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[i&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:i&&e.jsx(Xt,{})}),e.jsx(s.ResizableHandle,{})]}),e.jsxs(s.ResizablePanel,{id:"2",order:2,minSize:10,className:s.cn("relative flex h-full min-h-0 w-full flex-1 basis-0",{"px-6":i}),children:[(m==null?void 0:m.records)&&(m==null?void 0:m.records.length)>0&&e.jsx(s.TableVisual,{card:n,data:R,paginationMetadata:O,onPaginationChange:g,onSortChange:y,isLoading:f||j}),C&&e.jsx(Ht,{error:C})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function Xt(){const t=s.useEditorStore(n=>n.pythonStdOut);if(!t)return null;const a=t.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(s.ScrollArea,{className:"overflow-y-auto pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:a}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Zt(){const t=s.useEditorStore(n=>n.isShowingVisual),a=s.useEditorStore(n=>n.actions.setIsShowingVisual);return e.jsxs(s.Toggle,{pressed:!t,onPressedChange:()=>a(!t),variant:"outline",size:"sm",className:"h-8 gap-2",children:[e.jsx(s.Table2,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:"Results"})]})}function ie({value:t,onCommit:a,type:n="text",placeholder:r,className:l}){const[d,i]=D.useState(t),c=D.useRef(!1);D.useEffect(()=>{i(t)},[t]);const o=()=>{if(c.current){c.current=!1;return}d!==t&&a(d)},u=x=>{if(x.key==="Enter"){x.currentTarget.blur();return}x.key==="Escape"&&(c.current=!0,i(t),x.currentTarget.blur())};return e.jsx(s.Input$1,{type:n,placeholder:r,value:d,onChange:x=>i(x.target.value),onBlur:o,onKeyDown:u,className:l})}function he({defaultValue:t,label:a,options:n,value:r,onValueChange:l,className:d,icon:i,showPlaceholderLabel:c=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:l,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",d),children:e.jsxs("div",{className:"flex items-center gap-2",children:[i&&e.jsx("span",{children:i}),c&&e.jsx(s.SelectValue,{placeholder:a})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:a}),n.map(o=>e.jsx(s.SelectItem,{value:o.value,children:o.label},o.value))]})})]})}const en={table:({children:t})=>e.jsx("table",{className:"my-3 w-full border-collapse overflow-hidden rounded-md border border-border text-sm",children:t}),thead:({children:t})=>e.jsx("thead",{className:"bg-muted",children:t}),th:({children:t})=>e.jsx("th",{className:"border border-border px-3 py-2 text-left font-medium",children:t}),td:({children:t})=>e.jsx("td",{className:"border border-border px-3 py-2",children:t}),code:({children:t,className:a})=>(a==null?void 0:a.includes("language-"))?e.jsx("pre",{className:"my-3 overflow-x-auto rounded-md bg-muted p-3 text-xs",children:e.jsx("code",{children:t})}):e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-xs",children:t}),pre:({children:t})=>e.jsx(e.Fragment,{children:t})};function Fs(){var f,j;const t=s.useEditorStore(C=>C.card.customCardPreferences),{data:a}=s.usePluginQuery(),n=(a==null?void 0:a.plugins)||[],r=s.useEditorStore(C=>C.card),l=s.useEditorStore(C=>C.frame),d=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:i}=s.useEditorActions(),{components:c,manifest:o}=s.useCustomVisual((t==null?void 0:t.url)||""),u=(f=o==null?void 0:o.visuals)==null?void 0:f.find(C=>C.name===(t==null?void 0:t.componentName));function x(C,I){if(!t)return;const R={...(t==null?void 0:t.dataInputCardIds)||{},[C]:{cardId:I,hookRef:null}};i({...t,dataInputCardIds:R})}function h(C){var O,R;const I=(O=l==null?void 0:l.cards)==null?void 0:O.filter(v=>{var w;return((w=v==null?void 0:v.customCardPreferences)==null?void 0:w.visualType)!=="multiple"}).map(v=>({value:v.id,label:v.tabTitle||v.title}));return e.jsx("div",{className:"space-y-2",children:(R=C==null?void 0:C.dataInputs)==null?void 0:R.map((v,w)=>{var g,y;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:v}),e.jsx(he,{className:"col-span-6 h-8 w-full justify-between",label:"",options:I||[],value:((y=(g=t==null?void 0:t.dataInputCardIds)==null?void 0:g[w])==null?void 0:y.cardId)||"",onValueChange:T=>x(w,T)})]},w+Math.random())})})}function p(C,I,O=[],R=""){var v,w;return t?C==="input"?e.jsx(ie,{className:`h-8 w-full ${s.removeRing}`,value:String(((v=t==null?void 0:t.settings)==null?void 0:v[I])??R??""),onCommit:g=>{i({...t,settings:{...t==null?void 0:t.settings,[I]:g}})}},I):C==="select"?e.jsx(he,{className:"h-8 w-full",label:"",options:O,value:((w=t==null?void 0:t.settings)==null?void 0:w[I])||R,onValueChange:g=>{i({...t,settings:{...t==null?void 0:t.settings,[I]:g}})}}):null:null}function k(C){const I=Object.entries((C==null?void 0:C.settings)||{});return e.jsx("div",{className:"space-y-3",children:I.map(([O,R])=>{var v;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:R.title}),((v=R.docs)==null?void 0:v.description)&&e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{className:"text-xs",children:R.docs.description})})]})})]}),p(R.ui,O,R.options,R.defaultValue)]},O)})})}function m(C){t&&i({...t,visualType:C,componentName:""})}return e.jsxs(s.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"",children:[e.jsxs(s.AccordionItem,{value:"plugin-settings",children:[e.jsx(s.AccordionTrigger,{children:"Plugin"}),e.jsx(s.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:[e.jsx(he,{icon:e.jsx(vs,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(t==null?void 0:t.url)||"",onValueChange:C=>i({...t||{url:"",componentName:""},url:C})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:d,onValueChange:m,children:e.jsxs(s.TabsList,{className:"h-9 w-full",children:[e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&e.jsx(e.Fragment,{children:c&&e.jsx(he,{icon:e.jsx(it,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(c==null?void 0:c.filter(C=>C.type===d).map(C=>({value:C.name,label:C.name})))||[],value:t.componentName,onValueChange:C=>{console.log("changing value",C),i({...t,componentName:C})}})})]})})]}),((j=r==null?void 0:r.customCardPreferences)==null?void 0:j.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:(u==null?void 0:u.name)||"Settings"}),(u==null?void 0:u.docs)&&e.jsxs(s.HoverCard,{openDelay:0,closeDelay:100,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,onClick:C=>C.stopPropagation(),children:e.jsx(s.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground transition-colors hover:text-foreground"})}),e.jsx(s.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:[u.docs.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:u.docs.description}),u.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(s.Markdown,{remarkPlugins:[s.remarkGfm],components:en,children:u.docs.dataSchema})})]}),u.docs.useCases&&u.docs.useCases.length>0&&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:u.docs.useCases.map((C,I)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1 text-primary",children:"•"}),e.jsx("span",{children:C})]},I))})]})]})})]})]})}),e.jsxs(s.AccordionContent,{children:[u&&u.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:h(u)})]}),u&&u.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:k(u)})})]})]})]})}function Se(){const[t,a]=D.useState([]),n=s.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:l}=s.useEditorStore(u=>u.actions),d=s.useEditorStore(u=>u.queryResultColumns);s.useEditorStore(u=>{var x;return(x=u.card.preferences)==null?void 0:x.filterOnClickColumnIndex}),D.useEffect(()=>{d&&a(new Array(d.length).fill(!1))},[d]);function i(u,x){var h,p;x?n!=null&&n.onClickFilter&&((h=n==null?void 0:n.onClickFilter)==null?void 0:h.length)>0?l({...n,onClickFilter:[...n.onClickFilter,{columnIndex:u,expression:""}]}):l({...n,onClickFilter:[{columnIndex:u,expression:""}]}):(l({...n,onClickFilter:(p=n==null?void 0:n.onClickFilter)==null?void 0:p.filter(k=>k.columnIndex!==u)}),a(k=>{const m=[...k];return m[u]=!1,m}))}function c(u,x){var p;const h=(p=n==null?void 0:n.onClickFilter)==null?void 0:p.map(k=>k.columnIndex===u?{...k,expression:x.target.value}:k);l({...n,onClickFilter:h})}function o(u){var x,h,p,k;if(t!=null&&t[u]||(h=(x=n==null?void 0:n.onClickFilter)==null?void 0:x.find(m=>m.columnIndex===u))!=null&&h.expression)return e.jsx(s.Input$1,{value:(k=(p=n==null?void 0:n.onClickFilter)==null?void 0:p.find(m=>m.columnIndex===u))==null?void 0:k.expression,onChange:m=>c(u,m),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:d==null?void 0:d.map((u,x)=>{var h,p;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((h=n==null?void 0:n.onClickFilter)!=null&&h.find(k=>k.columnIndex===x)),onCheckedChange:k=>i(x,k)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:u}),e.jsx("div",{className:"flex items-center gap-2",children:((p=n==null?void 0:n.onClickFilter)==null?void 0:p.find(k=>k.columnIndex===x))&&e.jsx(s.Pencil,{onClick:()=>{a(k=>{const m=[...k];return m[x]=!k[x],m})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),o(x)]})},u)})})}function sn({idx:t}){var c;const a=s.useEditorStore(o=>{var u;return(u=o.card)==null?void 0:u.preferences}),n=s.useEditorStore(o=>{var u;return(u=o.card.preferences)==null?void 0:u.datasetOptions}),r=s.useEditorStore(o=>o.actions.setCardPreferences),l=(c=a==null?void 0:a.chartOptions)==null?void 0:c.indexAxis,d=n==null?void 0:n.find(o=>o.idx===t);function i(o,u){(o==="end"||o==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const x={display:o!=="none",align:o,anchor:o,clamp:!0};if(!d)r({...a,datasetOptions:[...n||[],{idx:u,datalabels:x}]});else{const h={...d};h.datalabels=x;const p=n==null?void 0:n.map(k=>k.idx===u?h:k);r({...a,datasetOptions:p})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(s.Tag,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(s.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>i("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>i("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(gt,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>i("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(vt,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>i("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(bt,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function tn(){const t=s.useEditorStore(d=>d.card),{data:a}=s.useDashboardCardQuery(t),{keys:n}=s.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(d=>!s.METADATA_KEYS.includes(d));let l=r;if(["stackedBar","stackedLine"].includes(t.type)){const d=s.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:i}=s.getKeys(d);l=i.slice(1)}return{transformedMetricKeys:l,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}function Je({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function Os(){const t=s.useEditorStore(o=>o.card),a=s.useEditorStore(o=>{var u,x,h;return(h=(x=(u=o==null?void 0:o.card)==null?void 0:u.preferences)==null?void 0:x.chartOptions)==null?void 0:h.indexAxis}),{data:n}=s.useDashboardCardQuery(t),r=a==="y"?"Metric":"Dimension",l=a==="y"?"Dimension":"Metric",{dimensionKeys:d,transformedMetricKeys:i,keys:c}=tn();return c.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:d.map(o=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:o,children:Rs(o)},o))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:l}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:i.map((o,u)=>e.jsx(Bs,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:o,idx:u},o))})]})]})}function Rs(t,a=30){return t.length>a?t.slice(0,a)+"...":t}function Bs({col:t,idx:a,className:n,iconClassName:r,children:l}){const d=s.useEditorStore(x=>{var h;return(h=x.card)==null?void 0:h.preferences}),i=s.useEditorStore(x=>{var h,p;return(p=(h=x.card)==null?void 0:h.preferences)==null?void 0:p.datasetOptions}),c=i==null?void 0:i.find(x=>x.idx===a),{setCardPreferences:o}=s.useEditorStore(x=>x.actions);function u(x){if(!c)o({...d,datasetOptions:[...i||[],{idx:a,type:x==="area"?"line":x,fill:x==="area"?"origin":""}]});else{const h={...c};h.type=x==="area"?"line":x,h.fill=x==="area"?"origin":"";const p=i==null?void 0:i.map(k=>k.idx===a?h:k);o({...d,datasetOptions:p})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[l||e.jsx(Je,{className:"max-w-[100px]",title:t,children:Rs(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.ChartColumnIncreasing,{onClick:()=>u("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartLine,{onClick:()=>u("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartArea,{onClick:()=>u("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(sn,{idx:a})]})]})}function De(){const t=s.useDashboardStore(c=>c.dashboard.filters),a=s.useEditorStore(c=>c.frame),{setFrame:n}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=s.useAssignFilter();function d(c){const o=l(c,"frame");n({...a,filterId:o})}const i=t==null?void 0:t.find(c=>c.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(nn,{onSelect:d,columns:r}),i&&e.jsx(s.FilterHeader,{filter:i})]})}function nn({columns:t,onSelect:a}){var i;const[n,r]=Ke.useState(!1),[l,d]=Ke.useState("");return e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[l?(i=t.find(c=>c.column_name===l))==null?void 0:i.column_name:"Select Column...",e.jsx(s.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No framework found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(c=>e.jsxs(s.CommandItem,{value:c.column_name,onSelect:o=>{const u=o===l?"":o;d(u),r(!1),u&&a(c)},children:[c.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",l===c.column_name?"opacity-100":"opacity-0")})]},c.column_name))})]})]})})]})}function an({cardType:t}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, y-axis-1, y-axis-2,... FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"y-axis1 - number"}),e.jsx("li",{children:"y-axis2 - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:a=>a.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(Os,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Se,{}),e.jsx(De,{})]})]})]})})}function rn({cardType:t}){function a(n){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:n==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),n==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:d=>d.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsx(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:a(t)})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Se,{}),e.jsx(De,{})]})]})]})})}function Vs(){const t=s.useEditorStore(c=>c.card.type),a=s.useEditorStore(c=>c.isDevMode),n=s.useEditorStore(c=>c.card.preferences),{setCardPreferences:r}=s.useEditorStore(c=>c.actions);function l(c){var x;const o={datalabels:{display:c!=="none",align:c,anchor:c,clamp:!0}},u={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(x=n==null?void 0:n.chartOptions)==null?void 0:x.plugins,...o}}};r(u)}function d(){var c,o,u;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((u=(o=(c=n==null?void 0:n.chartOptions)==null?void 0:c.plugins)==null?void 0:o.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Data Labels"}),e.jsx(s.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"start",children:"Start"}),e.jsx(s.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"end",children:"End"})]})})]})]})}function i(){var c,o,u;return e.jsx("div",{children:e.jsxs(s.Select,{value:((u=(o=(c=n==null?void 0:n.chartOptions)==null?void 0:c.plugins)==null?void 0:o.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(s.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:a?d():i()})}const ln={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},on={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function cn(){const t=s.useEditorStore(a=>a.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:dn(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Vs,{}),e.jsx(Se,{}),e.jsx(De,{})]})]})}function dn(t){if(["line","bar"].includes(t))return e.jsxs(e.Fragment,{children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsx("p",{children:"Chart Query"})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT x-axis, y-axis-1, y-axis-2, y-axis-3,... FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"X-axis - Category (ex. city)"}),e.jsx("li",{children:"Y-axis - Number (ex. population)"})]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Mixed Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and change the `type` property in the dataset."]}),e.jsx("pre",{children:JSON.stringify(ln,null,2)})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Area Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and add `fill` property to the dataset. See",e.jsx("a",{className:"mx-1 text-blue-500 hover:underline",href:"https://www.chartjs.org/docs/latest/samples/area/line-boundaries.html",target:"_blank",children:"docs"}),"for more options."]}),e.jsx("pre",{children:JSON.stringify(on,null,2)})]})]})]});if(t==="bubble")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis, radius FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Bubble Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"}),e.jsx("li",{children:"Radius - Number (ex. population)"})]})]})]})});if(t==="scatter")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"})]})]})]})});if(["pie","doughnut","polarArea","funnel"].includes(t))return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:[e.jsx("span",{children:t==="polarArea"?"Polar":t.charAt(0).toUpperCase()+t.slice(1)})," ","chart query"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Measure - Number (ex. population)"})]})]})]})})}function un({colorRanges:t,setColorRanges:a}){const n={start:-1/0,end:100,color:""};function r(i,c,o){const u=[...t];u[i]={...u[i],[c]:o},a(u)}function l(i){const c=[...t];c.splice(i,1),a(c)}function d(){a([...t,n])}return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:"Color Range"}),e.jsx(s.Button,{onClick:d,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((i,c)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input$1,{onChange:o=>r(c,"start",o.target.value),value:i.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input$1,{value:i.end,onChange:o=>r(c,"end",o.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input$1,{onChange:o=>r(c,"color",o.target.value),value:i.color,className:s.cn(`h-7 min-w-14 p-0 ${s.removeRing}`),type:"color",list:"presetColors"}),e.jsxs("datalist",{id:"presetColors",children:[e.jsx("option",{children:s.colors.green[600]}),e.jsx("option",{children:s.colors.red[500]}),e.jsx("option",{children:s.colors.yellow[400]}),e.jsx("option",{children:s.colors.orange[500]})]}),e.jsx(s.Button,{onClick:()=>l(c),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},c))]})}function mn(){var x,h,p,k,m;const t=s.useEditorStore(f=>f.card.preferences),a=s.useEditorStore(f=>f.actions.setCardPreferences),n=s.useEditorStore(f=>f.card),r=s.hasValidCardConfig(n.config),l=s.useEditorStore(f=>f.actions.setNumberFormat);s.useEditorStore(f=>{var j,C;return(C=(j=f.card.preferences)==null?void 0:j.formatNumber)==null?void 0:C.decimalPlaces});const d=s.useEditorStore(f=>{var j,C;return(C=(j=f.card.preferences)==null?void 0:j.formatNumber)==null?void 0:C.locale}),i=s.useEditorStore(f=>{var j,C;return(C=(j=f.card.preferences)==null?void 0:j.formatNumber)==null?void 0:C.currency});s.useEditorStore(f=>f.actions.setFilterOnClickField);const c=s.useEditorStore(f=>{var j,C;return(C=(j=f.card.preferences)==null?void 0:j.formatNumber)==null?void 0:C.colorRanges})||[],o=s.useEditorStore(f=>f.actions.setColorRanges),u=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(f=>f.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(s.Checkbox,{checked:!!((x=t==null?void 0:t.formatNumber)!=null&&x.enabled),onCheckedChange:f=>{a({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:f}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((h=t==null?void 0:t.formatNumber)==null?void 0:h.enabled)===!0||r)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Locale"}),e.jsxs(s.Select,{value:d||"none",onValueChange:f=>{var j,C,I;return l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,((C=t==null?void 0:t.formatNumber)==null?void 0:C.currency)||"",f,((I=t==null?void 0:t.formatNumber)==null?void 0:I.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Format"}),e.jsx(s.SelectItem,{value:"none",children:"Auto"},"none"),s.LOCALE_CURRENCY_PAIRS.map(f=>e.jsx(s.SelectItem,{value:f.locale,children:f.locale},f.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:i||"none",onValueChange:f=>{var j,C,I;console.log("currency",f),l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,f==="none"?"":f,((C=t==null?void 0:t.formatNumber)==null?void 0:C.locale)||"",((I=t==null?void 0:t.formatNumber)==null?void 0:I.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Currency"}),e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),u.map(f=>e.jsx(s.SelectItem,{value:f,children:f},f))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Decimals"}),e.jsxs(s.Select,{value:((k=(p=t==null?void 0:t.formatNumber)==null?void 0:p.decimalPlaces)==null?void 0:k.toString())||"0",onValueChange:f=>{var j,C,I;return l(Number(f),((j=t==null?void 0:t.formatNumber)==null?void 0:j.currency)||"",((C=t==null?void 0:t.formatNumber)==null?void 0:C.locale)||"",((I=t==null?void 0:t.formatNumber)==null?void 0:I.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-3 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["0","1","2","3","4"].map(f=>e.jsx(s.SelectItem,{value:f,children:f},f))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Suffix"}),e.jsx(s.Input$1,{value:((m=t==null?void 0:t.formatNumber)==null?void 0:m.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:f=>{var j,C,I;return l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,((C=t==null?void 0:t.formatNumber)==null?void 0:C.currency)||"",((I=t==null?void 0:t.formatNumber)==null?void 0:I.locale)||"",f.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(un,{colorRanges:c,setColorRanges:o})]})]})}function xn(){return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{type:"single",collapsible:!0,children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"",children:"KPI Query"}),e.jsxs(s.AccordionContent,{className:"font-mono",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs",children:"SELECT current, previous FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"current - number"}),e.jsx("li",{children:"previous - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/kpi",children:"example"})," in the docs."]})]})]})}),e.jsx("section",{className:"",children:e.jsx(mn,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function $e({children:t,summary:a,open:n,className:r}){return e.jsxs("details",{open:n,className:s.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(s.Label,{children:a}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const hn=[{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"}],pn=["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"],fn=pn.map(t=>({label:t,value:t}));function gn(){var o,u,x,h,p,k,m,f,j,C,I,O,R,v,w,g,y,T;const t=s.useEditorStore(M=>M.card),a=(u=(o=t==null?void 0:t.preferences)==null?void 0:o.mapVisualOptions)==null?void 0:u.topoJsonUrl,[n,r]=D.useState(((h=(x=t==null?void 0:t.preferences)==null?void 0:x.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:d}=s.useTopoJson(t),i=Object.keys((d==null?void 0:d.objects)||{}).map(M=>({label:M,value:M}))||[],c=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"p-6",children:[e.jsx($e,{summary:"Map Chart",children:e.jsx("p",{className:"rounded-md bg-muted p-2 font-mono text-xs",children:"SELECT country, value FROM table"})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx($e,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(he,{className:"h-9",options:c,onValueChange:M=>{console.log("value",M),l({...t.preferences,mapVisualOptions:{topoJsonUrl:M}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(s.Input$1,{onChange:M=>{r(M.target.value)},onBlur:()=>{var M;console.log("onBlur",n),l({...t.preferences,mapVisualOptions:{...(M=t.preferences)==null?void 0:M.mapVisualOptions,customTopoJsonUrl:n}})},value:n,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),d&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(he,{className:"h-9",options:i,value:((k=(p=t.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:k.objectKey)||"",label:"Map Object",onValueChange:M=>{var N;l({...t.preferences,mapVisualOptions:{...(N=t.preferences)==null?void 0:N.mapVisualOptions,objectKey:M}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(he,{className:"h-9",options:hn,value:((f=(m=t.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:f.projection)||"",label:"Projection",onValueChange:M=>{var N;l({...t.preferences,mapVisualOptions:{...(N=t.preferences)==null?void 0:N.mapVisualOptions,projection:M}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(he,{className:"h-9",options:fn,value:((C=(j=t.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:C.colorScale)||"",label:"Select Color Scale",onValueChange:M=>{var N;l({...t.preferences,mapVisualOptions:{...(N=t.preferences)==null?void 0:N.mapVisualOptions,colorScale:M}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx($e,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Input$1,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:.1,value:((O=(I=t.preferences)==null?void 0:I.mapVisualOptions)==null?void 0:O.projectionScale)||1,onChange:M=>{var N;l({...t.preferences,mapVisualOptions:{...(N=t.preferences)==null?void 0:N.mapVisualOptions,projectionScale:Number(M.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input$1,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((w=(v=(R=t.preferences)==null?void 0:R.mapVisualOptions)==null?void 0:v.projectionOffset)==null?void 0:w[0])||0,onChange:M=>{var N,b,A,F;l({...t.preferences,mapVisualOptions:{...(N=t.preferences)==null?void 0:N.mapVisualOptions,projectionOffset:[Number(M.target.value),((F=(A=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:F[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input$1,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((T=(y=(g=t.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:y.projectionOffset)==null?void 0:T[1])||0,onChange:M=>{var N,b,A,F;l({...t.preferences,mapVisualOptions:{...(N=t.preferences)==null?void 0:N.mapVisualOptions,projectionOffset:[((F=(A=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:F[0])||0,Number(M.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Se,{})]})}function jn(){var r;const t=s.useEditorStore(l=>l.card.preferences),{setCardPreferences:a}=s.useEditorStore(l=>l.actions);function n(l){a({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:l==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:n,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.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(s.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function Oe({cardType:t,docContent:a,suffix:n="Chart"}){let r="pie-donut-polar";return t==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} ${n}`}),e.jsx(s.AccordionContent,{children:a||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:l=>l.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),t==="text"&&e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2 py-4",children:e.jsx(jn,{})})]}),!["range","text"].includes(t)&&e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Se,{}),e.jsx(De,{})]})]})]})})}function bn(){const t=s.useEditorStore(r=>{var l,d;return(d=(l=r==null?void 0:r.card)==null?void 0:l.preferences)==null?void 0:d.sortChart}),{setSortChart:a}=s.useEditorActions();function n(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(he,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:t||"none",onValueChange:r=>{a(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[n(),e.jsx(Os,{})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Se,{}),e.jsx(De,{})]})]})]})})}function vn({cardType:t="table"}){console.log("cardType",t);const a=s.useEditorStore(l=>{var d;return(d=l.card)==null?void 0:d.preferences}),n=s.useEditorStore(l=>l.actions.setCardPreferences),r=l=>{n({...a,allowDownload:l})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Se,{}),e.jsx(De,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{onCheckedChange:r,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 Ps({color:t,onColorChange:a,onClose:n}){const[r,l]=D.useState(0),[d,i]=D.useState(100),[c,o]=D.useState(50),[u,x]=D.useState(t);D.useEffect(()=>{const j=is(t);if(j){const C=cs(j.r,j.g,j.b);l(C.h),i(C.s),o(C.l),x(t)}},[t]);const h=j=>{l(j),k(j,d,c)},p=j=>{const C=j.currentTarget.getBoundingClientRect(),I=Math.max(0,Math.min(1,(j.clientX-C.left)/C.width)),O=Math.max(0,Math.min(1,(j.clientY-C.top)/C.height)),R=I*100,v=(1-O)*100;i(R),o(v),k(r,R,v)},k=(j,C,I)=>{const O=Nn(j,C,I),R=yn(O.r,O.g,O.b);x(R)},m=j=>{if(x(j),/^#[0-9A-Fa-f]{6}$/.test(j)){const C=is(j);if(C){const I=cs(C.r,C.g,C.b);l(I.h),i(I.s),o(I.l)}}},f=()=>{/^#[0-9A-Fa-f]{6}$/.test(u)&&(a(u),n())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:p,onMouseMove:j=>{j.buttons===1&&p(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:`${d}%`,top:`${100-c}%`,backgroundColor:u}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:j=>h(Number(j.target.value)),className:"w-full h-4 rounded-lg appearance-none cursor-pointer",style:{background:"linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"}})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"HEX"}),e.jsx(s.Input$1,{value:u,onChange:j=>m(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:t}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:u}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(s.Button,{variant:"outline",onClick:n,children:"Cancel"}),e.jsx(s.Button,{onClick:f,children:"OK"})]})]})}function is(t){const a=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return a?{r:parseInt(a[1],16),g:parseInt(a[2],16),b:parseInt(a[3],16)}:null}function yn(t,a,n){return"#"+((1<<24)+(t<<16)+(a<<8)+n).toString(16).slice(1)}function cs(t,a,n){t/=255,a/=255,n/=255;const r=Math.max(t,a,n),l=Math.min(t,a,n);let d=0,i=0;const c=(r+l)/2;if(r!==l){const o=r-l;switch(i=c>.5?o/(2-r-l):o/(r+l),r){case t:d=((a-n)/o+(a<n?6:0))/6;break;case a:d=((n-t)/o+2)/6;break;case n:d=((t-a)/o+4)/6;break}}return{h:Math.round(d*360),s:Math.round(i*100),l:Math.round(c*100)}}function Nn(t,a,n){t/=360,a/=100,n/=100;let r,l,d;if(a===0)r=l=d=n;else{const i=(u,x,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?u+(x-u)*6*h:h<.5?x:h<.6666666666666666?u+(x-u)*(.6666666666666666-h)*6:u),c=n<.5?n*(1+a):n+a-n*a,o=2*n-c;r=i(o,c,t+1/3),l=i(o,c,t),d=i(o,c,t-1/3)}return{r:Math.round(r*255),g:Math.round(l*255),b:Math.round(d*255)}}const Cn=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function zs(){var O,R,v,w,g,y,T,M,N,b;const t=s.useEditorStore(A=>A.card),a=s.useEditorStore(A=>{var F;return(F=A.card)==null?void 0:F.preferences}),{setCardPreferences:n,updateCardInFrame:r}=s.useEditorActions(),{data:l}=s.useDashboardCardQuery(t),[d,i]=D.useState({}),[c,o]=D.useState(null),[u,x]=D.useState(null),h=D.useMemo(()=>{var L,S,P,$,J,K,G;if(!(l!=null&&l.records)||l.records.length===0)return[];const A=(t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine",F=(t==null?void 0:t.type)==="bar"||(t==null?void 0:t.type)==="line"||(t==null?void 0:t.type)==="horizontalBar"||(t==null?void 0:t.type)==="bullet",E=((L=t==null?void 0:t.config)==null?void 0:L.pivotByColumns)&&t.config.pivotByColumns.length>0;if((A||F)&&E){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const H=new Set;return l.pivotSchema.forEach(B=>{B.alias&&H.add(B.alias)}),Array.from(H)}if(l.records.length>0){const H=l.records[0],B=Object.keys(H),U=new Set;(S=t==null?void 0:t.config)!=null&&S.groupByColumns&&t.config.groupByColumns.forEach(X=>{U.add(X.label||X.name),U.add(X.alias||X.name)});const V=new Set;return(P=t==null?void 0:t.config)!=null&&P.metricColumns&&t.config.metricColumns.forEach(X=>{const se=X.alias||X.name;V.add(se),V.add(`${se}_count`),V.add(`${se}_sum`),V.add(`${se}_avg`),V.add(`${se}_min`),V.add(`${se}_max`);const _=X.entityName||X.qualifiedEntityName;_&&(V.add(`${_}_${se}`),V.add(`${_}_${se}_count`))}),B.filter(X=>!U.has(X)&&!V.has(X))}}if((F||A)&&!E&&((J=($=t==null?void 0:t.config)==null?void 0:$.metricColumns)!=null&&J.length))return t.config.metricColumns.map(H=>H.alias||H.label||H.name);if((G=(K=t==null?void 0:t.config)==null?void 0:K.groupByColumns)!=null&&G.length){const H=t.config.groupByColumns[0],B=H.label||H.name,U=new Set;return l.records.forEach(V=>{const W=V[B];W!=null&&U.add(String(W))}),Array.from(U)}return[]},[l,(O=t==null?void 0:t.config)==null?void 0:O.groupByColumns,(R=t==null?void 0:t.config)==null?void 0:R.pivotByColumns,(v=t==null?void 0:t.config)==null?void 0:v.metricColumns,t==null?void 0:t.type]),p=D.useMemo(()=>s.getDefaultChartColors(),[]);D.useEffect(()=>{const A={};h.forEach((F,E)=>{A[F]=s.getColorForValue(F,E,a==null?void 0:a.colorConfig)}),i(A)},[h,a==null?void 0:a.colorConfig,p]);const k=(A,F)=>{const E={...d,[A]:F};i(E);const L={...a||{},colorConfig:{segments:E}};n(L);const S={...t,preferences:L};r(S)},m=(A,F)=>{var J;const E=p[F%p.length],{[A]:L,...S}=((J=a==null?void 0:a.colorConfig)==null?void 0:J.segments)||{},P={...a||{},colorConfig:{segments:S}};n(P);const $={...t,preferences:P};r($),i(K=>({...K,[A]:E}))};if(!h.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((g=(w=t==null?void 0:t.config)==null?void 0:w.groupByColumns)==null?void 0:g.length)||((T=(y=t==null?void 0:t.config)==null?void 0:y.pivotByColumns)==null?void 0:T.length):(N=(M=t==null?void 0:t.config)==null?void 0:M.groupByColumns)==null?void 0:N.length)||["table","kpi","text","custom","heatmap"].includes(t.type))return null;const C=()=>{const A={...a||{},colorConfig:{segments:{}}};n(A);const F={...t,preferences:A};r(F);const E={};h.forEach((L,S)=>{E[L]=s.getColorForValue(L,S,void 0)}),i(E)},I=Object.keys(((b=a==null?void 0:a.colorConfig)==null?void 0:b.segments)||{}).length>0;return e.jsxs(s.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(s.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(yt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Colors"})]})}),e.jsx(s.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:I&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:C,children:[e.jsx(ts,{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((A,F)=>{const E=s.isDefaultColor(d[A],F),L=!E;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:c===A,onOpenChange:S=>o(S?A:null),children:[e.jsx(s.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[A]}})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-3",children:e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Theme Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:p.slice(0,10).map((S,P)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",d[A]===S?"border-gray-900":"border-transparent"),style:{backgroundColor:S},onClick:()=>{k(A,S),o(null)},children:[P===F%p.length&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-white/90 px-0.5 text-[8px] font-bold text-gray-900 shadow-sm",children:"D"})}),e.jsx("span",{className:"sr-only",children:S})]},`default-${P}`))})]}),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:Cn.map((S,P)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",d[A]===S?"border-2 border-gray-900":S==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:S},onClick:()=>{k(A,S),o(null)},children:e.jsx("span",{className:"sr-only",children:S})},`preset-${P}`))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsx("button",{className:"text-sm font-medium text-blue-600 hover:text-blue-700",onClick:()=>{x({value:A,color:d[A]}),o(null)},children:"Custom color"}),!E&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{m(A,F),o(null)},children:[e.jsx(ts,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:A}),L&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},A)})}),u&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>x(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Ps,{color:u.color,onColorChange:A=>{k(u.value,A),x(null)},onClose:()=>x(null)})})]})]})})]})}function pe({value:t,onSave:a,placeholder:n="",type:r="text",className:l=""}){const[d,i]=D.useState(t??""),[c,o]=D.useState(!1);D.useEffect(()=>{i(t??"")},[t]);const u=()=>{a(d),o(!1)},x=()=>{i(t??""),o(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${l}`,children:[e.jsx(s.Input,{placeholder:n,type:r,value:c?d:t??"",onChange:h=>{i(h.target.value),o(!0)},onFocus:()=>o(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&c&&d!==t?u():h.key==="Escape"&&x()},"aria-label":n||"Edit field"}),c&&d!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:u,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:x,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}const Sn=["auto","number","currency","percent","scientific","date"],wn=[{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"}],kn=[{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"}],Tn=t=>t.charAt(0).toUpperCase()+t.slice(1);function _e({formatOptions:t={},onFormatOptionsChange:a,showTitle:n=!0,title:r="NUMBER FORMAT"}){const l=t.type||"auto",d=(c,o)=>{a({...t,[c]:o})},i=()=>l==="currency"?2:l==="percent"?1:0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[n&&e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(s.Select,{value:l,onValueChange:c=>d("type",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Sn.map(c=>e.jsx(s.SelectItem,{value:c,className:"text-xs",children:c==="auto"?"Auto (Default)":Tn(c)},c))})]})]}),l!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent"].includes(l)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input$1,{type:"number",min:"0",max:"10",placeholder:"0",value:t.decimalPlaces??i(),onChange:c=>d("decimalPlaces",parseInt(c.target.value)||0),className:"h-8 text-xs"})})]}),l==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(s.Select,{value:t.currency||"USD",onValueChange:c=>d("currency",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:wn.map(c=>e.jsx(s.SelectItem,{value:c.value,className:"text-xs",children:c.label},c.value))})]})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:t.useSuffix??!1,onCheckedChange:c=>d("useSuffix",c)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(s.Select,{value:t.locale||"en-US",onValueChange:c=>d("locale",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:kn.map(c=>e.jsx(s.SelectItem,{value:c.value,className:"text-xs",children:c.label},c.value))})]})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input$1,{placeholder:"e.g., $",value:t.prefix||"",onChange:c=>d("prefix",c.target.value),className:"h-8 text-xs"})})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input$1,{placeholder:"e.g., units",value:t.suffix||"",onChange:c=>d("suffix",c.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Negative in ()"}),e.jsx(s.SmallSwitch,{checked:t.negativeInParentheses??!1,onCheckedChange:c=>d("negativeInParentheses",c)})]}),l==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input$1,{type:"number",placeholder:"100",value:t.multiplyBy??"",onChange:c=>d("multiplyBy",c.target.value?parseFloat(c.target.value):void 0),className:"h-8 text-xs"})})]}),l==="date"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Format"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input$1,{type:"text",placeholder:"MM/DD/YYYY",value:t.dateFormat||"",onChange:c=>d("dateFormat",c.target.value),className:"h-8 text-xs"})})]})]})]})}function ds({axis:t,label:a,type:n,config:r,onChange:l}){var h,p,k,m,f,j,C,I,O,R,v,w;const d=(g,y)=>{l({...r,[g]:y})},i=(g,y)=>{var T,M;l({...r,name:{enabled:g==="enabled"?y:((T=r==null?void 0:r.name)==null?void 0:T.enabled)??!1,text:g==="text"?y:(M=r==null?void 0:r.name)==null?void 0:M.text}})},c=(g,y)=>{var T,M;l({...r,labels:{enabled:g==="enabled"?y:((T=r==null?void 0:r.labels)==null?void 0:T.enabled)??!0,rotation:g==="rotation"?y:(M=r==null?void 0:r.labels)==null?void 0:M.rotation}})},o=(g,y)=>{l({...r,scale:{...r==null?void 0:r.scale,[g]:y===""?"auto":Number(y)}})},u=t==="x"?["auto","top","bottom"]:["auto","left","right"],x=["auto","0","45","90","-45","-90"];return e.jsxs(s.AccordionItem,{value:`${t}-axis`,className:"border-b-0",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx(s.AccordionTrigger,{className:"flex grow items-center justify-between gap-3 py-2 text-sm font-medium hover:no-underline",children:e.jsx("div",{className:"flex grow items-center justify-between gap-2",children:e.jsx("span",{children:a})})}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:g=>d("enabled",g),onClick:g=>g.stopPropagation()})]}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TITLE"}),e.jsx(s.SmallSwitch,{checked:((h=r==null?void 0:r.name)==null?void 0:h.enabled)??!1,onCheckedChange:g=>i("enabled",g)})]}),((p=r==null?void 0:r.name)==null?void 0:p.enabled)&&e.jsx(pe,{placeholder:`${a} title`,value:((k=r==null?void 0:r.name)==null?void 0:k.text)||"",onSave:g=>i("text",g),className:""})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(s.Select,{value:(r==null?void 0:r.position)||"auto",onValueChange:g=>d("position",g),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(g=>e.jsx(s.SelectItem,{value:g,className:"text-xs",children:g==="auto"?"Auto (Default)":s.titleCase(g)},g))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(s.SmallSwitch,{checked:((m=r==null?void 0:r.labels)==null?void 0:m.enabled)!==!1,onCheckedChange:g=>c("enabled",g)})]}),((f=r==null?void 0:r.labels)==null?void 0:f.enabled)!==!1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Rotation"}),e.jsxs(s.Select,{value:String(((j=r==null?void 0:r.labels)==null?void 0:j.rotation)||"auto"),onValueChange:g=>c("rotation",g==="auto"?"auto":Number(g)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:x.map(g=>e.jsx(s.SelectItem,{value:g,className:"text-xs",children:g==="auto"?"Auto (Default)":`${g}°`},g))})]})]})]}),n==="value"&&e.jsx(_e,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:g=>l({...r,formatOptions:g}),showTitle:!0,title:"FORMAT"}),n==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.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(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"auto",value:((C=r==null?void 0:r.scale)==null?void 0:C.min)==="auto"||((I=r==null?void 0:r.scale)==null?void 0:I.min)===void 0?"":String(r.scale.min),onSave:g=>o("min",g),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Max"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"auto",value:((O=r==null?void 0:r.scale)==null?void 0:O.max)==="auto"||((R=r==null?void 0:r.scale)==null?void 0:R.max)===void 0?"":String(r.scale.max),onSave:g=>o("max",g),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Step"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"auto",value:((v=r==null?void 0:r.scale)==null?void 0:v.stepSize)==="auto"||((w=r==null?void 0:r.scale)==null?void 0:w.stepSize)===void 0?"":String(r.scale.stepSize),onSave:g=>o("stepSize",g),className:""})})]})]})]})]})]})}function $s(){const t=s.useEditorStore(i=>i.card),a=s.useEditorStore(i=>{var c;return(c=i.card)==null?void 0:c.preferences}),{setCardPreferences:n,updateCardInFrame:r}=s.useEditorActions();if(!t||["tornado","pyramid","kpi","treemap"].includes(t.type))return null;const l=s.AxisConfigurator.getAxisInfo(t.type,a);if(!l.hasXAxis&&!l.hasYAxis)return null;const d=(i,c)=>{const u={...a||{},[i==="x"?"xAxisConfig":"yAxisConfig"]:c};n(u);const x={...t,preferences:u};r(x)};return e.jsxs(s.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(s.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(Ss,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Axes"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[l.hasXAxis&&e.jsx(ds,{axis:"x",label:"X-Axis",type:l.xAxisType,config:s.mergeAxisConfig(s.getDefaultAxisConfig(t.type,"x"),a==null?void 0:a.xAxisConfig),onChange:i=>d("x",i)}),l.hasYAxis&&e.jsx(ds,{axis:"y",label:"Y-Axis",type:l.yAxisType,config:s.mergeAxisConfig(s.getDefaultAxisConfig(t.type,"y"),a==null?void 0:a.yAxisConfig),onChange:i=>d("y",i)})]})})]})}function Ks(){const t=s.useEditorStore(x=>x.card),a=s.useEditorStore(x=>{var h,p,k,m;return(m=(k=(p=(h=x.card)==null?void 0:h.preferences)==null?void 0:p.chartOptions)==null?void 0:k.plugins)==null?void 0:m.legend}),{setLegendOptions:n}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r=s.getDefaultLegendConfig(t.type),l=(r==null?void 0:r.display)??!0,d=(r==null?void 0:r.position)??"top",i=(r==null?void 0:r.align)??"center",c=(x,h)=>{const p={...a,[x]:h};n(p)},o=["top","bottom","left","right"],u=["start","center","end"];return e.jsxs(s.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(s.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(ht,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(s.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(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:(a==null?void 0:a.display)??l,onCheckedChange:x=>c("display",x)})]}),((a==null?void 0:a.display)??l)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(a==null?void 0:a.position)||d,onValueChange:x=>c("position",x),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:o.map(x=>e.jsx(s.SelectItem,{value:x,className:"text-xs",children:s.titleCase(x)},x))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(s.Select,{value:(a==null?void 0:a.align)||i,onValueChange:x=>c("align",x),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(x=>e.jsx(s.SelectItem,{value:x,className:"text-xs",children:s.titleCase(x)},x))})]})]})]})]})})]})}function Gs(){var E,L,S,P,$,J,K,G,H,B,U;const t=s.useEditorStore(V=>V.card),a=s.useEditorStore(V=>{var W,X;return(X=(W=V.card)==null?void 0:W.preferences)==null?void 0:X.dataLabelsConfig}),n=s.useEditorStore(V=>{var W;return(W=V.card)==null?void 0:W.preferences}),{setCardPreferences:r,updateCardInFrame:l}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(t.type))return null;const d=t.type==="bullet"?((E=n==null?void 0:n.bulletConfig)==null?void 0:E.orientation)??(((L=n==null?void 0:n.chartOptions)==null?void 0:L.indexAxis)==="x"?"vertical":"horizontal"):void 0,i=d!=null?d==="horizontal":((S=n==null?void 0:n.chartOptions)==null?void 0:S.indexAxis)==="y",c=t.type==="stackedBar"||t.type==="stackedLine",o=t.type==="pie"||t.type==="doughnut"||t.type==="polarArea"||t.type==="funnel",u=!o,x=t.type==="bubble"||t.type==="scatter",h=($=(P=n==null?void 0:n.chartOptions)==null?void 0:P.plugins)==null?void 0:$.datalabels,p=(h==null?void 0:h.display)!==!1&&((h==null?void 0:h.anchor)||(h==null?void 0:h.align)),k=s.getDefaultDataLabelsConfig(t.type,t.preferences),m=a??k,f=(k==null?void 0:k.enabled)??p??!1,j=(a==null?void 0:a.enabled)!==void 0?a.enabled:f,C=(V,W)=>{const _={...k??{},...a??{},[V]:W};V==="enabled"&&(_.display=W,W&&x&&!_.position&&(_.position="bottom")),V==="position"&&x&&(_.position="bottom");const te={...t.preferences||{},dataLabelsConfig:_};r(te);const Y={...t,preferences:te};l(Y)},I=(V,W)=>{const X=a??{},_={...k??{},...X,font:{...X.font||{},[V]:W}},te={...t.preferences||{},dataLabelsConfig:_};r(te);const Y={...t,preferences:te};l(Y)},O=(V,W)=>{const X=a??{},_={...k??{},...X,formatOptions:{...X.formatOptions||{},[V]:W}},te={...t.preferences||{},dataLabelsConfig:_};r(te);const Y={...t,preferences:te};l(Y)},R=()=>{const V=t.type;return V==="stackedBar"||V==="stackedLine"||V==="pie"||V==="doughnut"?"center":i?"right":"top"},v=t.type!=="treemap"&&t.type!=="heatmap",w=t.type!=="treemap",g=R();let y=[];if(v)if(x)y=["bottom"];else if(c||o)y=["center"];else{const V=i?["center","left","right"]:["center","top","bottom"];y=["auto",...t.type==="bullet"?V:V.filter(X=>X!==g),"custom"]}const T=()=>s.titleCase(g),M=["center","start","end"],N=["center","start","end","top","bottom"],b=u?["auto","number","currency","percent","none"]:["number","currency","percent","none"],A=[{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"}],F=[{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)"}];return e.jsxs(s.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(s.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(Tt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(s.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(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:j,onCheckedChange:V=>C("enabled",V)})]}),j&&e.jsxs(e.Fragment,{children:[v&&!c&&!o&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:x?(m==null?void 0:m.position)||"bottom":(m==null?void 0:m.position)||"auto",onValueChange:V=>C("position",V),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:y.map(V=>e.jsx(s.SelectItem,{value:V,className:"text-xs",children:V==="auto"?T():V==="custom"?"Custom (Advanced)":s.titleCase(V)},V))})]})]}),c&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Show Total"}),e.jsx(s.SmallSwitch,{checked:(a==null?void 0:a.showTotal)??!1,onCheckedChange:V=>C("showTotal",V)})]}),(m==null?void 0:m.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(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Anchor"}),e.jsxs(s.Select,{value:(m==null?void 0:m.anchor)||"center",onValueChange:V=>C("anchor",V),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:M.map(V=>e.jsx(s.SelectItem,{value:V,className:"text-xs",children:s.titleCase(V)},V))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Align"}),e.jsxs(s.Select,{value:String((m==null?void 0:m.align)||"center"),onValueChange:V=>C("align",V),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:N.map(V=>e.jsx(s.SelectItem,{value:V,className:"text-xs",children:s.titleCase(V)},V))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(m==null?void 0:m.format)||(u?"auto":"none"),onValueChange:V=>C("format",V),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:b.map(V=>e.jsx(s.SelectItem,{value:V,className:"text-xs",children:V==="auto"&&u?"Auto (Use Axis)":V==="none"?"None (Raw Value)":s.titleCase(V)},V))})]})]}),(m==null?void 0:m.format)&&!["auto","none"].includes(m.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(m.format)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"0",value:String(((J=m==null?void 0:m.formatOptions)==null?void 0:J.decimalPlaces)??(m.format==="currency"?2:m.format==="percent"?1:0)),onSave:V=>O("decimalPlaces",Number(V)),className:""})})]}),m.format==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Currency"}),e.jsxs(s.Select,{value:((K=m==null?void 0:m.formatOptions)==null?void 0:K.currency)||"USD",onValueChange:V=>O("currency",V),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:A.map(V=>e.jsx(s.SelectItem,{value:V.value,className:"text-xs",children:V.label},V.value))})]})]}),["number","currency"].includes(m.format)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((G=m==null?void 0:m.formatOptions)==null?void 0:G.useSuffix)??!1,onCheckedChange:V=>O("useSuffix",V)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Locale"}),e.jsxs(s.Select,{value:((H=m==null?void 0:m.formatOptions)==null?void 0:H.locale)||"en-US",onValueChange:V=>O("locale",V),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:F.map(V=>e.jsx(s.SelectItem,{value:V.value,className:"text-xs",children:V.label},V.value))})]})]})]}),w&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Appearance"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Size"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"12",value:String(((B=m==null?void 0:m.font)==null?void 0:B.size)||12),onSave:V=>I("size",Number(V)),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Weight"}),e.jsxs(s.Select,{value:((U=m==null?void 0:m.font)==null?void 0:U.weight)||"normal",onValueChange:V=>I("weight",V),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(s.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Color"}),e.jsxs(s.Select,{value:(m==null?void 0:m.color)==="auto"||!(m!=null&&m.color)?"auto":"custom",onValueChange:V=>{V==="auto"&&C("color","auto")},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Smart Contrast)"}),e.jsx(s.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom (Coming Soon)"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Rotation"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"0",value:String((m==null?void 0:m.rotation)||0),onSave:V=>C("rotation",Number(V)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}const us=["poor","satisfactory","good"];function ms(t){if(!t)return;const a={...t};return a.targetMetricKey||delete a.targetMetricKey,a.comparativeMetricKey||delete a.comparativeMetricKey,!a.targetValue&&a.targetValue!==0&&delete a.targetValue,(!a.rangeKeys||Object.keys(a.rangeKeys).length===0)&&delete a.rangeKeys,(!a.ranges||Object.keys(a.ranges).length===0)&&delete a.ranges,(!a.rangeLabels||Object.keys(a.rangeLabels).length===0)&&delete a.rangeLabels,a}function qs(){var A,F;const t=s.useEditorStore(E=>E.card.preferences),a=s.useEditorStore(E=>E.card),n=s.useEditorStore(E=>E.isDevMode),{setCardPreferences:r,setChartOrientation:l}=s.useEditorActions(),d=D.useMemo(()=>(t==null?void 0:t.bulletConfig)||{},[t==null?void 0:t.bulletConfig]),c=s.hasValidCardConfig(a==null?void 0:a.config)&&!n,[o,u]=D.useState(d.showRanges??!1),[x,h]=D.useState(d.rangesArePercentages??!1),p=d.disableAutoComparative?!1:d.comparativeMetricKey!==void 0||!c,[k,m]=D.useState(p);D.useEffect(()=>{u(d.showRanges??!1)},[d.showRanges]),D.useEffect(()=>{h(d.rangesArePercentages??!1)},[d.rangesArePercentages]);const f=d.targetValue===void 0?"":String(d.targetValue);D.useEffect(()=>{const E=d.disableAutoComparative?!1:d.comparativeMetricKey!==void 0||!c;m(E)},[d.disableAutoComparative,d.comparativeMetricKey,c]);const j=D.useMemo(()=>{var E,L;return((L=(E=a==null?void 0:a.config)==null?void 0:E.metricColumns)==null?void 0:L.map(S=>{const P=S.label||S.name||S.alias||"";return{value:P,label:P}}))||[]},[(A=a==null?void 0:a.config)==null?void 0:A.metricColumns]);D.useEffect(()=>{var G,H;if(!t||j.length===0)return;const E={};let L=!1;const S=(G=j[1])==null?void 0:G.value;!d.targetMetricKey&&S&&(E.targetMetricKey=S,L=!0);const P=(H=j[2])==null?void 0:H.value;!d.comparativeMetricKey&&!d.disableAutoComparative&&P&&(E.comparativeMetricKey=P,L=!0);const $=j.slice(3),J={...d.rangeKeys||{}};let K=!1;if(us.forEach((B,U)=>{!J[B]&&$[U]&&(J[B]=$[U].value,K=!0)}),K&&(E.rangeKeys=J,L=!0,d.showRanges===void 0&&(E.showRanges=!0)),L){const B=ms({...d,...E});r({...t,bulletConfig:B})}},[j,d,t,r]);const C=E=>{const L=ms({...d,...E});r({...t,bulletConfig:L})},I=(E,L)=>{const S={...d.rangeKeys||{},[E]:L.trim()};L.trim()||delete S[E],C({rangeKeys:Object.keys(S).length>0?S:void 0})},O=(E,L)=>{const S=L===""?void 0:Number(L),P={...d.ranges||{}};S===void 0||Number.isNaN(S)?delete P[E]:P[E]=S,C({ranges:Object.keys(P).length?P:void 0})},R=E=>{if(E===""){C({targetValue:void 0});return}const L=Number(E);C({targetValue:Number.isNaN(L)?void 0:L})},v=(E,L)=>{const S=L.trim(),P={...d.rangeLabels||{}};S?P[E]=S:delete P[E],C({rangeLabels:Object.keys(P).length>0?P:void 0})},w=E=>{u(E),C({showRanges:E})},g=E=>{h(E),C({rangesArePercentages:E})},y=d.orientation||(((F=t==null?void 0:t.chartOptions)==null?void 0:F.indexAxis)==="y"?"horizontal":"vertical"),T=E=>{C({orientation:E}),l(E==="horizontal"?"y":"x")},M=[{value:"__none",label:"None"},...j.map(E=>({value:E.value,label:E.label}))],N=M,b=E=>{if(m(E),!E){C({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!c){C({disableAutoComparative:!1});return}if(d.comparativeMetricKey)C({disableAutoComparative:!1});else{const L=j.find(S=>S.value!==d.targetMetricKey);C({comparativeMetricKey:L==null?void 0:L.value,disableAutoComparative:!1})}};return e.jsxs(s.AccordionItem,{value:"bullet-config",className:"border-b-0",children:[e.jsx(s.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(s.BulletChartIcon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bullet Chart"})]})}),e.jsxs(s.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(s.Label,{className:"text-xs font-medium",children:"ORIENTATION"}),e.jsxs(s.Select,{value:y,onValueChange:E=>T(E),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"horizontal",className:"text-xs",children:"Horizontal"}),e.jsx(s.SelectItem,{value:"vertical",className:"text-xs",children:"Vertical"})]})]})]}),c&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TARGET METRIC"}),e.jsxs(s.Select,{value:d.targetMetricKey||"__none",onValueChange:E=>C({targetMetricKey:E==="__none"?void 0:E}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select metric"})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"__none",className:"text-xs",children:"None"}),j.map(E=>e.jsx(s.SelectItem,{value:E.value,className:"text-xs",children:E.label},E.value))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"COMPARATIVE METRIC"}),c?e.jsxs(s.Select,{value:d.comparativeMetricKey||"__none",onValueChange:E=>C({comparativeMetricKey:E==="__none"?void 0:E,disableAutoComparative:E==="__none"}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select metric"})}),e.jsx(s.SelectContent,{children:M.map(E=>e.jsx(s.SelectItem,{value:E.value,className:"text-xs",children:E.label},E.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(s.SmallSwitch,{checked:k,onCheckedChange:E=>b(E)})]}),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(s.Label,{className:"text-xs font-medium",children:"TARGET VALUE (FALLBACK)"}),e.jsx(ie,{type:"number",className:"h-8 text-xs",value:f,onCommit:R,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(s.Label,{className:"text-xs font-medium",children:"QUALITATIVE RANGES"}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:200,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"text-muted-foreground transition-colors hover:text-foreground",children:e.jsx(s.Info,{className:"h-3.5 w-3.5"})})}),e.jsx(s.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(s.SmallSwitch,{checked:o,onCheckedChange:w})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:x,disabled:!o,onChange:E=>g(E.target.checked),className:"h-3.5 w-3.5 accent-primary disabled:opacity-50"}),e.jsx("span",{children:"Use % of value"})]})]}),o&&e.jsx("div",{className:"space-y-3",children:us.map(E=>{var L,S,P,$,J;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(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[E," LABEL"]}),e.jsx(ie,{placeholder:`Display label (${E})`,value:((L=d.rangeLabels)==null?void 0:L[E])||"",onCommit:K=>v(E,K),className:"h-8 text-xs"})]}),c?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[E," COLUMN"]}),e.jsxs(s.Select,{value:((S=d.rangeKeys)==null?void 0:S[E])||"__none",onValueChange:K=>{K==="__none"?I(E,""):I(E,K)},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select column"})}),e.jsx(s.SelectContent,{children:N.map(K=>e.jsx(s.SelectItem,{value:K.value,className:"text-xs",children:K.label},K.value))})]})]}):e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[E," COLUMN KEY"]}),e.jsx(ie,{placeholder:"Column key",value:((P=d.rangeKeys)==null?void 0:P[E])||"",onCommit:K=>I(E,K),className:"h-8 text-xs"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[E," VALUE"]}),e.jsx(ie,{type:"number",placeholder:x?"0.80":"Static value",value:(($=d.ranges)==null?void 0:$[E])===void 0?"":String((J=d.ranges)==null?void 0:J[E]),onCommit:K=>O(E,K),className:"h-8 text-xs"})]})]},E)})})]})]})]})}const xs=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],En=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function Le({value:t,onChange:a,label:n}){const[r,l]=D.useState(!1),[d,i]=D.useState(!1),c=()=>{const o=xs.find(u=>u.value===t);return o?o.color:t.startsWith("#")?t:xs[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:r,onOpenChange:l,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"size-5 rounded border-2 border-input shadow-sm transition-all hover:scale-110 hover:border-gray-400",style:{backgroundColor:c()},"aria-label":`Change color for ${n}`})}),e.jsx(s.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:En.map(o=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",c()===o?"border-gray-900":"border-transparent"),style:{backgroundColor:o},onClick:()=>{a(o),l(!1)},children:e.jsx("span",{className:"sr-only",children:o})},o))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{i(!0),l(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:n})]}),d&&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:()=>i(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Ps,{color:c(),onColorChange:o=>{a(o),i(!1)},onClose:()=>i(!1)})})]})]})}const An=Object.keys(s.HEATMAP_PRESET_PALETTES);function Us(){const t=s.useEditorStore(p=>p.card),a=s.useEditorStore(p=>{var k;return(k=p.card)==null?void 0:k.preferences}),{setCardPreferences:n}=s.useEditorActions(),r=(t==null?void 0:t.type)==="heatmap",l=(a==null?void 0:a.heatmapConfig)||{},d=l.colorPalette??"green",i=l.legendPosition??"bottom",c=D.useMemo(()=>l.colorRange&&l.colorRange[0]&&l.colorRange[1]?[l.colorRange[0],l.colorRange[1]]:[...s.DEFAULT_HEATMAP_CUSTOM_RANGE],[l.colorRange]),o=p=>{const k={...l,...p};k.colorPalette!=="custom"?delete k.colorRange:(!k.colorRange||!k.colorRange[0]||!k.colorRange[1])&&(k.colorRange=[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]),n({...a||{},heatmapConfig:k})},u=p=>{o({colorPalette:p,colorRange:p==="custom"?l.colorRange??[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},x=(p,k)=>{const m=[...c];m[p]=k,o({colorPalette:"custom",colorRange:m})},h=p=>{o({legendPosition:p})};return r?e.jsxs(s.AccordionItem,{value:"heatmap-color-config",className:"border-none",children:[e.jsx(s.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(s.Grid3x3,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Heatmap Settings"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs(s.RadioGroup,{value:d,onValueChange:p=>u(p??"blue"),className:"space-y-3",children:[An.map(p=>{const k=s.HEATMAP_PRESET_PALETTES[p];return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:`heatmap-${p}`,value:p}),e.jsxs(s.Label,{htmlFor:`heatmap-${p}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:k.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${k.start}, ${k.end})`}})]})]},p)}),e.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.RadioGroupItem,{id:"heatmap-custom",value:"custom"}),e.jsx(s.Label,{htmlFor:"heatmap-custom",className:"text-sm font-medium",children:"Custom colors"})]}),d==="custom"&&e.jsxs("div",{className:"flex flex-col gap-3 pl-6",children:[e.jsx(Le,{value:c[0],onChange:p=>x(0,p),label:"Start color"}),e.jsx(Le,{value:c[1],onChange:p=>x(1,p),label:"End color"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Color scale position"}),e.jsxs(s.Select,{value:i,onValueChange:p=>h(p??"bottom"),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["top","bottom","left","right"].map(p=>e.jsx(s.SelectItem,{value:p,className:"text-xs",children:p[0].toUpperCase()+p.slice(1)},p))})]})]})]})]}):null}function hs(t){if(!t)return;const a={...t};if(a.xMetricKey||delete a.xMetricKey,a.yMetricKey||delete a.yMetricKey,a.radiusMetricKey||delete a.radiusMetricKey,a.labelKey||delete a.labelKey,a.groupKey||delete a.groupKey,a.enableGrouping===void 0&&delete a.enableGrouping,a.radiusScale||delete a.radiusScale,a.fixedRadius===void 0&&delete a.fixedRadius,a.minRadius===void 0&&delete a.minRadius,a.maxRadius===void 0&&delete a.maxRadius,Object.keys(a).length!==0)return a}function Hs(){var v,w,g,y,T,M,N,b,A,F,E,L;const t=s.useEditorStore(S=>S.card.preferences),a=s.useEditorStore(S=>S.card),n=s.useEditorStore(S=>S.card.type),r=s.useEditorStore(S=>S.isDevMode),{setCardPreferences:l,updateCardInFrame:d}=s.useEditorActions(),i=n==="bubble",c=n==="scatter",o=D.useMemo(()=>(t==null?void 0:t.bubbleScatterConfig)||{},[t==null?void 0:t.bubbleScatterConfig]),x=s.hasValidCardConfig(a==null?void 0:a.config)&&!r,h=D.useMemo(()=>{var S,P;return((P=(S=a==null?void 0:a.config)==null?void 0:S.metricColumns)==null?void 0:P.map($=>{const J=$.label||$.name||$.alias||"";return{value:J,label:J}}))||[]},[(v=a==null?void 0:a.config)==null?void 0:v.metricColumns]),p=D.useMemo(()=>{var S,P;return((P=(S=a==null?void 0:a.config)==null?void 0:S.groupByColumns)==null?void 0:P.map($=>{const J=$.label||$.name||$.alias||"";return{value:J,label:J}}))||[]},[(w=a==null?void 0:a.config)==null?void 0:w.groupByColumns]),k=D.useMemo(()=>o.enableGrouping!==void 0?o.enableGrouping:!r&&p.length>=2,[o.enableGrouping,r,p.length]),[m,f]=D.useState(k);D.useEffect(()=>{f(k)},[k]);const j=S=>{const P={...t||{},bubbleScatterConfig:S};l(P),a&&d({...a,preferences:P})},C=S=>{l(S),a&&d({...a,preferences:S})};D.useEffect(()=>{if(!t||h.length===0)return;const S={};let P=!1;if(!o.xMetricKey&&h[0]&&(S.xMetricKey=h[0].value,P=!0),!o.yMetricKey&&h[1]&&(S.yMetricKey=h[1].value,P=!0),i&&!o.radiusMetricKey&&h[2]&&(S.radiusMetricKey=h[2].value,P=!0),!o.labelKey&&p[0]&&(S.labelKey=p[0].value,P=!0),k&&!o.groupKey&&p[1]&&(S.groupKey=p[1].value,S.enableGrouping=!0,P=!0),P){const $=hs({...o,...S});j($)}},[h,p,o,t,l,i,k]);const I=S=>{const P=hs({...o,...S});j(P)},O=S=>{f(S),I({enableGrouping:S,groupKey:S?o.groupKey:void 0})};if(!i&&!c)return null;const R=i?s.Circle:s.ChartScatter;return e.jsxs(s.AccordionItem,{value:"bubble-scatter-config",children:[e.jsx(s.AccordionTrigger,{className:"py-2 text-sm",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(R,{className:"h-4 w-4"}),e.jsxs("span",{children:[i?"Bubble":"Scatter"," Configuration"]})]})}),e.jsxs(s.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(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{children:e.jsx(s.Info,{className:"h-3 w-3"})}),e.jsx(s.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(s.Label,{className:"text-xs",children:"Label Column"}),x?e.jsxs(s.Select,{value:o.labelKey||"",onValueChange:S=>I({labelKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select label column"})}),e.jsx(s.SelectContent,{children:p.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(ie,{className:"h-8 text-xs",placeholder:"Column name for labels",value:o.labelKey||"",onCommit:S=>I({labelKey:S})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Group points into series"}),e.jsx(s.SmallSwitch,{checked:m,onCheckedChange:O})]}),m&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Group By"}),x?e.jsxs(s.Select,{value:o.groupKey||"",onValueChange:S=>I({groupKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select group column"})}),e.jsx(s.SelectContent,{children:p.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(ie,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:o.groupKey||"",onCommit:S=>I({groupKey:S})})]})]}),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(s.Label,{className:"text-xs",children:"X Axis"}),x?e.jsxs(s.Select,{value:o.xMetricKey||"",onValueChange:S=>I({xMetricKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select X metric"})}),e.jsx(s.SelectContent,{children:h.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(ie,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:o.xMetricKey||"",onCommit:S=>I({xMetricKey:S})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Y Axis"}),x?e.jsxs(s.Select,{value:o.yMetricKey||"",onValueChange:S=>I({yMetricKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select Y metric"})}),e.jsx(s.SelectContent,{children:h.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(ie,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:o.yMetricKey||"",onCommit:S=>I({yMetricKey:S})})]}),i&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Radius"}),x?e.jsxs(s.Select,{value:o.radiusMetricKey||"",onValueChange:S=>I({radiusMetricKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select radius metric"})}),e.jsx(s.SelectContent,{children:h.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(ie,{className:"h-8 text-xs",placeholder:"Column name for radius",value:o.radiusMetricKey||"",onCommit:S=>I({radiusMetricKey:S})})]})]}),i&&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(s.Label,{className:"text-xs",children:"Scale Mode"}),e.jsxs(s.Select,{value:o.radiusScale||"sqrt",onValueChange:S=>I({radiusScale:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"sqrt",children:"Square Root (area-proportional)"}),e.jsx(s.SelectItem,{value:"linear",children:"Linear"}),e.jsx(s.SelectItem,{value:"fixed",children:"Fixed Size"})]})]})]}),o.radiusScale!=="fixed"&&e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Min Radius"}),e.jsx(ie,{className:"h-8 text-xs",type:"number",placeholder:"5",value:((g=o.minRadius)==null?void 0:g.toString())||"",onCommit:S=>I({minRadius:S?Number(S):void 0})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Max Radius"}),e.jsx(ie,{className:"h-8 text-xs",type:"number",placeholder:"30",value:((y=o.maxRadius)==null?void 0:y.toString())||"",onCommit:S=>I({maxRadius:S?Number(S):void 0})})]})]}),o.radiusScale==="fixed"&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs(s.Label,{className:"text-xs",children:["Fixed Radius: ",o.fixedRadius||10]}),e.jsx(s.Slider,{value:[o.fixedRadius||10],onValueChange:([S])=>I({fixedRadius:S}),min:3,max:30,step:1,className:"py-2"})]})]}),c&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Point Settings"}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(s.Label,{className:"text-xs",children:["Point Size: ",o.fixedRadius||5]}),e.jsx(s.Slider,{value:[o.fixedRadius||5],onValueChange:([S])=>I({fixedRadius:S}),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(s.SmallSwitch,{checked:((M=(T=t==null?void 0:t.xAxisConfig)==null?void 0:T.name)==null?void 0:M.enabled)??!1,onCheckedChange:S=>{var J,K,G,H;const P=o.xMetricKey||"X Axis",$=o.yMetricKey||"Y Axis";C({...t??{},xAxisConfig:{...t==null?void 0:t.xAxisConfig,name:{enabled:S,text:((K=(J=t==null?void 0:t.xAxisConfig)==null?void 0:J.name)==null?void 0:K.text)||P}},yAxisConfig:{...t==null?void 0:t.yAxisConfig,name:{enabled:S,text:((H=(G=t==null?void 0:t.yAxisConfig)==null?void 0:G.name)==null?void 0:H.text)||$}}})}})]}),((b=(N=t==null?void 0:t.xAxisConfig)==null?void 0:N.name)==null?void 0:b.enabled)&&e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"X Title"}),e.jsx(ie,{className:"h-8 text-xs",placeholder:o.xMetricKey||"X Axis",value:((F=(A=t==null?void 0:t.xAxisConfig)==null?void 0:A.name)==null?void 0:F.text)||"",onCommit:S=>{var P;C({...t??{},xAxisConfig:{...t==null?void 0:t.xAxisConfig,name:{...(P=t==null?void 0:t.xAxisConfig)==null?void 0:P.name,enabled:!0,text:S||o.xMetricKey||"X Axis"}}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Y Title"}),e.jsx(ie,{className:"h-8 text-xs",placeholder:o.yMetricKey||"Y Axis",value:((L=(E=t==null?void 0:t.yAxisConfig)==null?void 0:E.name)==null?void 0:L.text)||"",onCommit:S=>{var P;C({...t??{},yAxisConfig:{...t==null?void 0:t.yAxisConfig,name:{...(P=t==null?void 0:t.yAxisConfig)==null?void 0:P.name,enabled:!0,text:S||o.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const In=[{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 Js(){const t=s.useEditorStore(p=>p.card),a=s.useEditorStore(p=>{var k;return(k=p.card)==null?void 0:k.preferences}),{setCardPreferences:n}=s.useEditorActions(),r=(t==null?void 0:t.type)==="funnel",l=(a==null?void 0:a.funnelConfig)||{},d=l.percentMode??"percentOfTotal",i=l.shrinkFraction??1,c=l.labelThreshold??0,o=p=>{const k={...l,...p};n({...a||{},funnelConfig:k})},u=p=>{o({percentMode:p})},x=p=>{o({shrinkFraction:p[0]})},h=p=>{o({labelThreshold:p[0]})};return r?e.jsxs(s.AccordionItem,{value:"funnel-config",className:"border-none",children:[e.jsx(s.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(s.Filter,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Funnel Settings"})]})}),e.jsxs(s.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(s.Label,{className:"text-xs font-medium",children:"PERCENTAGE MODE"}),e.jsx(s.RadioGroup,{value:d,onValueChange:p=>u(p),className:"space-y-2",children:In.map(p=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:`funnel-${p.value}`,value:p.value,className:"mt-0.5"}),e.jsxs(s.Label,{htmlFor:`funnel-${p.value}`,className:"flex flex-col gap-0.5 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:p.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:p.description})]})]},p.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.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(s.Slider,{value:[i],onValueChange:x,min:0,max:1,step:.1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Full Shrink"})]}),e.jsxs("p",{className:"text-center text-xs text-muted-foreground",children:["Current: ",Math.round(i*100),"%"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.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(s.Slider,{value:[c],onValueChange:h,min:0,max:25,step:1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Hide Small"})]}),e.jsx("p",{className:"text-center text-xs text-muted-foreground",children:c===0?"Showing all labels":`Hide labels below ${c}%`})]})]})]}):null}function Dn(){const t=s.useEditorStore(a=>a.card);return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Chart Configuration"}),e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:[(t==null?void 0:t.type)==="funnel"&&e.jsx(Js,{}),(t==null?void 0:t.type)==="heatmap"&&e.jsx(Us,{}),(t==null?void 0:t.type)==="bullet"&&e.jsx(qs,{}),((t==null?void 0:t.type)==="bubble"||(t==null?void 0:t.type)==="scatter")&&e.jsx(Hs,{}),e.jsx(zs,{}),e.jsx($s,{}),e.jsx(Ks,{}),e.jsx(Gs,{})]})]})}const Mn=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT dimension, cohort, metric FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/tornado",children:"example"})," in the docs."]})]}),Ln=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT y-axis, label, range-from, range-to, range-value FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/range",children:"example"})," in the docs."]})]}),Fn=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT text FROM table limit 1"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/text",children:"example"})," in the docs."]})]});function On(){const t=s.useEditorStore(n=>n.card.type);function a(n){const r=["kpi","table","text","map","custom"],l=d=>r.includes(n)?d:e.jsxs(e.Fragment,{children:[d,e.jsx(Dn,{})]});switch(n){case"stackedBar":case"stackedLine":return l(e.jsx(bn,{}));case"tornado":case"pyramid":return l(e.jsx(Oe,{docContent:Mn,cardType:n}));case"kpi":return e.jsx(xn,{});case"line":case"bar":return l(e.jsx(an,{cardType:n}));case"range":return l(e.jsx(Oe,{docContent:Ln,cardType:n}));case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return l(e.jsx(Oe,{cardType:n}));case"bubble":case"scatter":return l(e.jsx(rn,{cardType:n}));case"table":return e.jsx(vn,{cardType:n});case"text":return e.jsx(Oe,{docContent:Fn,cardType:n,suffix:"Visual"});case"map":return e.jsx(gn,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(Fs,{})});default:return l(e.jsx(cn,{}))}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[a(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Rn(){const t=D.useRef(null),a=D.useRef(null),n=s.useEditorStore(l=>l.isShowingVisual),r=s.useEditorStore(l=>l.showAIDialog);return D.useEffect(()=>{var l,d,i,c;r?((l=t.current)==null||l.resize(0),(d=a.current)==null||d.resize(0)):((i=t.current)==null||i.resize(25),(c=a.current)==null||c.resize(25))},[r]),e.jsxs(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(Bt,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:n&&!r?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:t,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(On,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(os,{})})]}):e.jsx(os,{})})]})}function Bn(t){var ce;s.useAIInteractionStore(z=>z.currentAIContext);const[a,n]=D.useState(""),[r,l]=D.useState(null),{authToken:d,tokenProps:i}=s.useSemaphorContext(),c=s.useEditorStore(z=>{var ee;return(ee=z==null?void 0:z.card)==null?void 0:ee.sql}),o=s.useEditorStore(z=>z.isDevMode),u=s.useEditorStore(z=>{var ee;return(ee=z==null?void 0:z.card)==null?void 0:ee.python}),{setCardPython:x,setCardSql:h,setRunSql:p,switchCardType:k,setQueryConfig:m}=s.useEditorActions(),f=s.useEditorStore(z=>z.currentAssitantScope)||[],j=s.useEditorStore(z=>z.userInputForAI),C=s.useEditorStore(z=>z.triggerAIRun),I=s.useEditorStore(z=>z.card),O=s.useEditorStore(z=>z.selectedDatabaseName),R=s.useEditorStore(z=>z.selectedTableName),v=s.useEditorStore(z=>z.selectedConnectionId),w=s.useEditorStore(z=>z.selectedSchemaName),g=s.useDashboardStore(z=>z.dashboard.aiScopeTables),{errorMessage:y,refetch:T,data:M}=s.useDashboardCardQuery(I),{setTriggerAIRun:N,setCurrentAssitantScope:b,setCardConfig:A}=s.useEditorActions(),{selectedDatamodelName:F,connectionType:E,selectedDatamodelId:L}=s.useEditorAside(),S=(ce=s.useDashboardQuery().data)==null?void 0:ce.assistantProfileId,{messages:P,setMessages:$,regenerate:J,error:K,sendMessage:G,status:H,addToolResult:B,stop:U,clearError:V}=s.useChat({transport:new s.DefaultChatTransport({api:`${i.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${d==null?void 0:d.accessToken}`}),body:()=>{const z=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:S,isDevMode:o,aiContext:z.currentAIContext,reasoningEffort:z.reasoningEffort,showReasoning:z.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:z,body:ee})=>({body:{...ee,messages:s.cleanupIncompleteMessages(z)}})}),onError:z=>{var ee;if(z.name==="AbortError"||(ee=z.message)!=null&&ee.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)");return}console.error("[Editor Assistant] Stream error:",z)},onToolCall:W,onFinish({isAbort:z,isDisconnect:ee,isError:de}){n(""),console.log(z?"[Editor Assistant] Stream aborted by user":ee?"[Editor Assistant] Stream disconnected (network error)":de?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully")}});D.useEffect(()=>{C&&j&&(G({role:"user",parts:[{type:"text",text:j}]}),N(!1))},[C,j,G,N]);async function W({toolCall:z}){var ee,de,ue,we,me,je,xe,be,ke,fe,Te,Ee,Ae,Ie,ve,ye;if(["createChartFromSql","createForecast"].includes(z.toolName)){const Q=((ee=z.input)==null?void 0:ee.sql)??((de=z.args)==null?void 0:de.sql),ae=((ue=z.input)==null?void 0:ue.python)??((we=z.args)==null?void 0:we.python),re=((me=z.input)==null?void 0:me.chartType)??((je=z.args)==null?void 0:je.chartType);k(re),h(Q),x(ae),p(!0),B({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(z.toolName==="getUserSql"){if(!c){B({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"error",message:"No SQL found"}});return}B({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",sql:c,python:u||""}})}else if(z.toolName==="generateQueryConfig"){n("Generating query config...");const Q=((xe=z.input)==null?void 0:xe.chartType)??((be=z.args)==null?void 0:be.chartType),ae=((ke=z.input)==null?void 0:ke.queryConfig)??((fe=z.args)==null?void 0:fe.queryConfig);((Te=z.input)==null?void 0:Te.cardConfig)??((Ee=z.args)==null||Ee.cardConfig),k(Q),A(ae),h(void 0),x(void 0);const re=await T();if((Ae=re==null?void 0:re.data)!=null&&Ae.error){B({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"error",queryConfig:ae,message:(Ie=re==null?void 0:re.data)==null?void 0:Ie.error.message}});return}if((ve=re==null?void 0:re.data)!=null&&ve.records){B({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",queryConfig:ae,message:"The data has been visualized"}});return}B({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",queryConfig:ae,message:"The data has been visualized",records:(ye=re==null?void 0:re.data)==null?void 0:ye.records}})}else n("Analyzing...")}function X(z){const ee=s.removeFromScopeArray(f,z);se(ee)}function se(z){const ee=s.sanitizeAIScope(z);b(ee),$(de=>[...de,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(ee)}`}]}])}function _(){const z={databaseName:O||"",schemaName:w||"",tableName:R||"",datamodelId:L||"",datamodelName:s.resolveDatamodelName(F),connectionId:v||"",connectionType:E||""},ee=s.dedup([...f,z]);se(ee)}function te(){const z={databaseName:O||"",schemaName:w||"",tableName:R||"",datamodelName:s.resolveDatamodelName(F),connectionId:v||"",connectionType:E||"",datamodelId:L||""};if(!s.isInAiScopeArray([...g||[],...f],z)||f.length===0){const de=s.dedup([...g||[],...f,z]).filter(ue=>ue.connectionId===z.connectionId);se(de)}}const Y=!["ready","error"].includes(H),le=s.getErrorMessage(K);return{messages:P,setMessages:$,sendMessage:G,regenerate:J,isLoading:Y,handleSetAIScope:te,handleAddCurrentTableToScope:_,removeFromCurrentSelections:X,currentAssitantScope:f,setCurrentAssitantScope:b,stop:U,status:H,toolStatus:a,llmUsage:r,onFinish:t,errorMessage:le,clearError:V}}const Vn=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function ps({isFullscreen:t,onFullscreenChange:a,fullscreenContainer:n}){const r=D.useRef(null),[l,d]=D.useState(!1),[i,c]=D.useState(s.isDevEnv),[o,u]=D.useState(!1),[x,h]=D.useState(!1),[p,k]=D.useState(!1),m=t??p,f=s.useCurrentAIContext(),{setCurrentAIContext:j}=s.useAIActions(),{clearQueue:C}=s.useQueueActions(),{clearFileAttachments:I}=s.useFileActions(),O=s.useFileAttachments("editor"),R=s.useDashboardStore(Q=>Q.dashboard.aiContext),v=s.useEditorStore(Q=>Q.card.dataSource),w=s.useEditorStore(Q=>Q.actions.setCardSql),g=s.useEditorStore(Q=>Q.actions.setRunSql),y=s.useEditorStore(Q=>Q.showAIDialog),T=s.useDashboardStore(Q=>Q.handleOpenAssistantProfile),{setShowAIDialog:M,setCardPython:N}=s.useEditorActions(),{setDataSource:b}=s.useEditorActions(),{assistantProfile:A}=s.useAssistantProfile(),{messages:F,setMessages:E,sendMessage:L,isLoading:S,stop:P,status:$,llmUsage:J,errorMessage:K,clearError:G}=Bn(),[H,B]=D.useState(""),U=Q=>{B(Q.target.value)},V=Q=>{Q.preventDefault();const ae=H.trim();if(!ae&&O.length===0)return;const re=[];ae&&re.push({type:"text",text:ae}),O.forEach(Ne=>{Ne.data&&re.push({type:"file",mediaType:Ne.type,filename:Ne.name,url:`data:${Ne.type};base64,${Ne.data}`})}),L({role:"user",parts:re}),B(""),I("editor"),ee({force:!0})},{visibleMessages:W,hasMoreMessages:X,totalMessageCount:se,loadMoreMessages:_,resetMessageWindow:te}=s.useMessageWindow(F,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:Y,isAtBottom:le,hasNewMessages:ce,newMessageCount:z,scrollToBottom:ee,handleScroll:de,resetNewMessageCount:ue}=s.useAutoScroll(W,{threshold:50,behavior:"smooth",isStreaming:S});D.useEffect(()=>{var Q;y&&((Q=r.current)==null||Q.focus(),j({selectedEntities:(v==null?void 0:v.selectedEntities)||[]}))},[y,v,j]),s.useAutoSubmitQueue({assistantType:"editor",status:$,isLoading:S,sendMessage:L});const{hasActiveTools:we}=s.useActiveToolStatus(F),me=D.useCallback(Q=>{a==null||a(Q),t===void 0&&k(Q)},[t,a]);D.useEffect(()=>{if(!m)return;function Q(ae){ae.key==="Escape"&&me(!1)}return window.addEventListener("keydown",Q),()=>{window.removeEventListener("keydown",Q)}},[m,me]);const je=D.useCallback(Q=>{L({role:"user",parts:[{type:"text",text:Q}]}),ee({force:!0})},[L,ee]),xe=D.useCallback(async()=>{const Q=JSON.stringify(F??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(Q),s.ue.success("Conversation copied")}catch(ae){console.error("Failed to copy conversation",ae),s.ue.error("Unable to copy conversation")}},[F]),be=D.useCallback(()=>{me(!m)},[m,me]);function ke(Q,ae){ae==="sql"?(w(Q),g(!0)):ae==="python"&&(N(Q),g(!0))}function fe(){f.selectedEntities.length===0&&j({selectedEntities:(R==null?void 0:R.selectedEntities)||[]})}function Te(Q){fe();const ae={role:"user",parts:[{type:"text",text:Q.title+" "+Q.subtitle}]};L(ae)}function Ee(Q){fe(),L({role:"user",parts:[{type:"text",text:Q}]})}function Ae(){return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuLabel,{children:"Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx(s.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:d,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:i,onCheckedChange:c,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:u,children:"System Message"})]})]})}function Ie(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const ve=(H==null?void 0:H.length)===0&&(F==null?void 0:F.filter(Q=>Q.role==="user").length)===0,ye=e.jsxs("div",{"data-role":"editor-assistant",className:s.cn("flex h-full w-full flex-col justify-between px-6 py-4",m&&"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:[Ie(),T&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:T,children:(A==null?void 0:A.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[Ae(),i&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:xe,children:"Copy Conversation"}),e.jsx(s.IconButton,{tooltip:m?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:be,children:m?e.jsx(s.Minimize2,{className:"size-4"}):e.jsx(s.Maximize2,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{E([]),C("editor"),G(),te()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{M(!1)},children:e.jsx(s.X,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:Y,className:"mt-2 flex w-full grow basis-0",onScroll:de,children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[X&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:_,className:"text-xs",children:["Load ",Math.min(5,se-W.length)," ","more messages (",se-W.length," ","hidden)"]})}),e.jsx(s.PrintMessages,{messages:W,showTools:i,handleRun:ke,showSystemMessage:o,onQuickReply:je,disableQuickReplies:S}),!we&&e.jsx(s.AssistantStatus,{status:$,errorMessage:K})]})}),y&&!le&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{ee({force:!0}),ue()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),ce&&z>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:z>9?"9+":z})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[ve&&!A&&e.jsx(s.Placeholders,{onClick:Te,placeholders:Vn}),e.jsx("div",{children:ve&&A&&e.jsx(s.SeedQuestions,{seedQuestions:A.seedQuestions||[],handleSeedQuestionClick:Ee})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:r,setInput:B,stop:P,input:H,handleInputChange:U,handleSubmit:Q=>{fe(),V(Q),ee({force:!0})},isLoading:S,status:$,assistantType:"editor",onFocus:()=>{}})]}),J&&l&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",J.inputTokens," prompt tokens, ",J.outputTokens," ","completion tokens, ",J.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(v==null?void 0:v.selectedEntities)||[],open:x,onOpenChange:h,dataSource:v||s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]});return m&&n?nt.createPortal(e.jsx("div",{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:e.jsx("div",{className:"flex h-full w-full",children:ye})}),n):ye}function Pn({selectedChart:t,onChartChange:a}){const[n,r]=D.useState(!1),l=s.useEditorStore(c=>c.card),d=()=>{var o;if(t==="custom")return((o=l==null?void 0:l.customCardPreferences)==null?void 0:o.componentName)||"Custom Visual";const c=s.chartTypes.find(u=>u.id===t);return(c==null?void 0:c.label)||"Select chart type"},i=()=>{var o;if(t==="custom"){const u=(o=l==null?void 0:l.customCardPreferences)==null?void 0:o.componentName;if(u){const x=s.getAutoDetectedChartIcon(u);return x||e.jsx(s.ChartIcon,{chartName:u,isCustom:!0,className:"h-4 w-4"})}return e.jsx(s.Shapes,{className:"h-4 w-4"})}const c=s.chartTypes.find(u=>u.id===t);if(c){const u=c.icon;return e.jsx(u,{className:"h-4 w-4"})}return e.jsx(s.Shapes,{className:"h-4 w-4"})};return e.jsx("div",{children:e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[i(),e.jsx("span",{children:d()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[360px] p-3",align:"start",onOpenAutoFocus:c=>c.preventDefault(),children:e.jsx(Ds,{onChartSelect:c=>a(c),onClose:()=>r(!1)})})]})})}let zn=(t=21)=>crypto.getRandomValues(new Uint8Array(t)).reduce((a,n)=>(n&=63,n<36?a+=n.toString(36):n<62?a+=(n-26).toString(36).toUpperCase():n>62?a+="-":a+="_",a),"");const Be=[{id:"sum",label:"Sum",symbol:"+",description:"Add two metrics together",template:()=>"({field_0} + {field_1})",requiresTwoInputs:!0},{id:"difference",label:"Difference",symbol:"−",description:"Subtract one metric from another",template:()=>"({field_0} - {field_1})",requiresTwoInputs:!0},{id:"product",label:"Product (Multiplication)",symbol:"×",description:"Multiply two metrics",template:()=>"({field_0} * {field_1})",requiresTwoInputs:!0},{id:"ratio",label:"Ratio",symbol:"÷",description:"Divide one metric by another",template:()=>"({field_0} / NULLIF({field_1}, 0))",requiresTwoInputs:!0},{id:"change",label:"Change",symbol:"Δ",description:"Calculate percentage change from A to B",template:()=>"(({field_1} - {field_0}) / NULLIF({field_0}, 0))",requiresTwoInputs:!0},{id:"percentage",label:"Percentage",symbol:"%",description:"Calculate (A / B) × 100",template:()=>"(({field_0} / NULLIF({field_1}, 0)) * 100)",requiresTwoInputs:!0},{id:"scale",label:"Scale (Multiply by Factor)",symbol:"×n",description:"Multiply a metric by a constant factor",template:()=>"({field_0} * {constant})",requiresTwoInputs:!1},{id:"custom",label:"Custom Expression",symbol:"{}",description:"Drag fields to create custom expression with tokens",requiresTwoInputs:!1,allowsCustomExpression:!0}];function $n(t,a,n,r,l,d,i,c,o){const u=Be.find(f=>f.id===a);if(!u)throw new Error(`Unknown operation: ${a}`);let x,h=[],p;if(a==="custom"){if(!(c!=null&&c.trim()))throw new Error("Custom expression is required");x=c.trim()}else if(a==="scale"){if(!n)throw new Error("Metric A is required for scale operation");if(o===void 0||o===0)throw new Error("Constant factor is required for scale operation");x=u.template().replace("{constant}",String(o)),h=[n],p=o}else{if(!n||!r)throw new Error("Metrics A and B are required for standard operations");x=u.template(),h=[n,r]}const k={operation:a,inputFields:h,...p!==void 0&&{constant:p}};return{id:i||`calc_${zn(10)}`,name:t.toLowerCase().replace(/\s+/g,"_"),label:t,alias:t.toLowerCase().replace(/\s+/g,"_"),qualifiedFieldName:t.toLowerCase().replace(/\s+/g,"_"),dataType:"number",role:"metric",aggregate:"SUM",expression:x,calculatedFormula:k,entityId:d,entityName:s.CALCULATED_FIELD_ENTITY_MARKER,entityType:"table",description:`Calculated field: ${t}`}}function fs(t){var r,l;const a=Be.find(d=>d.id===t.operation);if(!a)return"Unknown operation";if(t.operation==="custom")return"Custom expression";if(t.operation==="scale"){const d=((r=t.inputFields[0])==null?void 0:r.label)||((l=t.inputFields[0])==null?void 0:l.name)||"A",i=t.constant??1;return`${d} × ${i}`}return t.inputFields.map(d=>d.label||d.name).join(` ${a.symbol} `)}const Qe=({dataType:t})=>s.getFieldIconComponent(t);function Kn({aliasTemplate:t,onAliasTemplateChange:a}){var o;const[n,r]=D.useState(t),[l,d]=D.useState(!1),i=(o=s.useEditorStore(u=>{var x;return(x=u.card.config)==null?void 0:x.pivotByColumns}))==null?void 0:o[0],c=i?`e.g. Min Sales in {{${i.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.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(s.Input,{placeholder:c,value:l?n:t,onChange:u=>{r(u.target.value),d(!0)},onFocus:()=>d(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&l&&n!==t?(a(n),d(!1)):u.key==="Escape"&&(r(t),d(!1))},"aria-label":"Edit alias template"}),l&&n!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{a(n),d(!1)},children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(t),d(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function Gn({valueAliases:t,onValueAliasesChange:a}){const[n,r]=D.useState(null),[l,d]=D.useState(""),[i,c]=D.useState(""),o=()=>{a({...t,"":""})},u=h=>{const p={...t};delete p[h],a(p)},x=h=>{const p={...t};delete p[h],p[l]=i,a(p),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(t).map(([h,p],k)=>e.jsx("div",{className:"flex items-center gap-2",children:n===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input,{placeholder:"Value key",value:l,onChange:m=>d(m.target.value),className:"h-8 w-24 text-xs",onPointerDown:m=>m.stopPropagation(),onKeyDown:m=>{m.key==="Enter"?x(h):m.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input,{placeholder:"Alias label",value:i,onChange:m=>c(m.target.value),className:"h-8 w-24 text-xs",onPointerDown:m=>m.stopPropagation(),onKeyDown:m=>{m.key==="Enter"?x(h):m.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>x(h),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),d(h),c(p)},"aria-label":"Edit value alias key"}),e.jsx(s.Input,{placeholder:"Alias label",value:p,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),d(h),c(p)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+k)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:o,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function qn({column:t}){const a=s.useEditorStore(o=>o.card.type),n=s.useEditorStore(o=>{var u,x;return(x=(u=o.card)==null?void 0:u.config)==null?void 0:x.metricColumns}),r=(n==null?void 0:n.map(o=>o.label))||[],l=r==null?void 0:r.find(o=>o===t.label||o===t.name),d=l?r.indexOf(l):-1;function i(){return e.jsx("div",{className:"pr-1",children:l&&e.jsx(Bs,{idx:d,col:l,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function c(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(Vs,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&i(),["pie","doughnut"].includes(a)&&c()]})}function Un({field:t,searchQuery:a="",limit:n=500}){const{authToken:r,tokenProps:l}=s.useSemaphorContext(),d=s.useEditorStore(u=>u.card),i=d==null?void 0:d.dataSource,c=["attribute-values",t.entityName,t.name,a,n],o=s.useQuery({queryKey:c,queryFn:async()=>{if(!(i!=null&&i.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const u={groupByColumns:[{...t,role:"groupby"}],metricColumns:[],filters:a?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:a}],groups:[]}:void 0,rowLimit:n},x={connection_id:i.connectionId,cardConfig:u,cardDataSource:i,cache_config:s.getCacheConfig({card:d})};console.log("requestBody",x);const h=await s.postRequestRegular(`${l.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",x);if(h!=null&&h.error)return console.error("Error fetching attribute values:",h.error),[];const p=t.name;return((h==null?void 0:h.records)||[]).map(m=>{const f=m[p]||m[t.alias||p]||m[t.label];return{id:f||"",value:f||"",label:String(f||"(empty)")}})}catch(u){return console.error("Error fetching attribute values:",u),[]}},enabled:!!t&&!!(i!=null&&i.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:o.data||[],isLoading:o.isLoading,isFetching:o.isFetching,isError:o.isError,error:o.error,refetch:o.refetch}}function _s({open:t,onOpenChange:a,availableFields:n,existingFilters:r,editingCondition:l,onSave:d}){var O,R;const i=!!l,[c,o]=D.useState(i?"values":"fields"),[u,x]=D.useState(""),[h,p]=D.useState({id:(l==null?void 0:l.id)||s.v4(),field:(l==null?void 0:l.field)||null,selectedValues:l?Array.isArray(l.value)?l.value:[l.value]:[]}),k=n.filter(v=>{var g;return i?!1:!((g=r==null?void 0:r.conditions)==null?void 0:g.some(y=>y.field.id===v.id))&&v.label.toLowerCase().includes(u.toLowerCase())}),m=v=>{p({...h,field:v}),o("values")},f=()=>{if(h.field&&h.selectedValues.length>0){const v={id:h.id,field:h.field,operator:"in",value:h.selectedValues};let w;if(i){const g=((r==null?void 0:r.conditions)||[]).map(y=>y.id===l.id?v:y);w={...r,conditions:g}}else{const g=(r==null?void 0:r.conditions)||[];w={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...g,v],groups:[]}}d(w),a(!1)}},j=()=>{if(!i||!l)return;const v=((r==null?void 0:r.conditions)||[]).filter(w=>w.id!==l.id);if(v.length>0){const w={...r,conditions:v};d(w)}else d(void 0);a(!1)},C=v=>{p({...h,selectedValues:v})},I=()=>{i&&l?(p({id:l.id,field:l.field,selectedValues:Array.isArray(l.value)?l.value:[l.value]}),o("values")):(p({id:s.v4(),field:null,selectedValues:[]}),o("fields")),x("")};return D.useEffect(()=>{t&&I()},[t,i,l]),e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsx(s.DialogHeader,{children:e.jsx(s.DialogTitle,{children:i?`Edit Filter: ${(O=h.field)==null?void 0:O.label}`:c==="fields"?"Select Field to Filter":`Select Values for ${(R=h.field)==null?void 0:R.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!i&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&c==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.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(v=>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:[v.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(v.value)?`${v.value.length} values`:String(v.value)})]},v.id))})]}),c==="fields"&&!i?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search fields...",value:u,onChange:v=>x(v.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:k.map(v=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>m(v),children:[e.jsx(Qe,{dataType:s.getDataType(v.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:v.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[v.entityName,".",v.name]})]})]},v.id))}),k.length===0&&u&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',u,'"']}),k.length===0&&!u&&n.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(Hn,{field:h.field,selectedValues:h.selectedValues,onValuesChange:C,onBack:i?void 0:()=>o("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:i?e.jsx(s.Button,{variant:"destructive",onClick:j,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:I,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:f,disabled:!h.field||h.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function Hn({field:t,selectedValues:a,onValuesChange:n,onBack:r}){const[l,d]=D.useState(""),{values:i,isLoading:c,isFetching:o}=Un({field:t,searchQuery:l,limit:500}),u=l?i.filter(p=>String(p.value).toLowerCase().includes(l.toLowerCase())):i,x=p=>{const k=a.includes(p);n(k?a.filter(m=>m!==p):[...a,p])},h=()=>{a.length===u.length&&u.length>0?n([]):n(u.map(p=>p.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:r,children:"← Back"}),e.jsxs(s.Label,{className:"text-sm font-medium",children:["Select values for ",t.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search values...",value:l,onChange:p=>d(p.target.value),className:"pl-10"})]}),c||o?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(s.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(s.Checkbox,{checked:a.length===u.length&&u.length>0,onCheckedChange:h}),e.jsxs(s.Label,{className:"text-sm",children:["Select All (",u.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:u.map(p=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>x(p.value),children:[e.jsx(s.Checkbox,{checked:a.includes(p.value),onCheckedChange:()=>x(p.value)}),e.jsx(Je,{className:"text-sm",children:p.label})]},p.id))})]})]})}function Qs({open:t,onOpenChange:a,availableMetrics:n,existingField:r,onSave:l,cardId:d}){const[i,c]=D.useState(""),[o,u]=D.useState("ratio"),[x,h]=D.useState(null),[p,k]=D.useState(null),[m,f]=D.useState(1),[j,C]=D.useState(""),[I,O]=D.useState({format:"number",decimalPlaces:2}),[R,v]=D.useState({}),w=Be.find(b=>b.id===o),g=n.find(b=>b.id===x),y=n.find(b=>b.id===p);D.useEffect(()=>{if(r&&t)if(c(r.label),r.calculatedFormula)if(u(r.calculatedFormula.operation),r.calculatedFormula.operation==="custom")C(r.expression||"");else if(r.calculatedFormula.operation==="scale"){const b=r.calculatedFormula.inputFields;if(b.length>=1){const A=n.find(F=>F.qualifiedFieldName===b[0].qualifiedFieldName);h((A==null?void 0:A.id)||null)}r.calculatedFormula.constant!==void 0&&f(r.calculatedFormula.constant)}else{const b=r.calculatedFormula.inputFields;if(b.length>=2){const A=n.find(E=>E.qualifiedFieldName===b[0].qualifiedFieldName),F=n.find(E=>E.qualifiedFieldName===b[1].qualifiedFieldName);h((A==null?void 0:A.id)||null),k((F==null?void 0:F.id)||null)}}else u("custom"),C(r.expression||"")},[r,t,n]);const T=()=>{const b={};return i.trim()||(b.name="Name is required"),o==="custom"?j.trim()||(b.customExpression="Custom expression is required"):o==="scale"?(x||(b.inputA="Please select a metric for input A"),(isNaN(m)||m===0)&&(b.constantFactor="Please enter a valid non-zero number"),r&&x===r.id&&(b.circular="Cannot reference the field being edited")):(x||(b.inputA="Please select a metric for input A"),p||(b.inputB="Please select a metric for input B"),x===p&&(b.inputs="Inputs A and B must be different metrics"),r&&(x===r.id||p===r.id)&&(b.circular="Cannot reference the field being edited")),v(b),Object.keys(b).length===0},M=()=>{if(!T())return;const b=$n(i,o,g||null,y||null,I,d,r==null?void 0:r.id,o==="custom"?j:void 0,o==="scale"?m:void 0);l(b),N()},N=()=>{c(""),u("ratio"),h(null),k(null),f(1),C(""),v({}),a(!1)};return e.jsxs(s.Dialog,{modal:!1,open:t,onOpenChange:a,children:[t&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-w-md max-h-[90vh] overflow-y-auto",onInteractOutside:b=>{b.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsxs(s.DialogTitle,{children:[r?"Edit":"Create"," Calculated Metric"]}),e.jsx(s.DialogDescription,{children:"Combine existing metrics to create a new calculated field"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"name",children:"Name"}),e.jsx(s.Input$1,{id:"name",value:i,onChange:b=>c(b.target.value),placeholder:"e.g., Profit Margin",className:R.name?"border-red-500":""}),R.name&&e.jsx("p",{className:"text-xs text-red-500",children:R.name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"operation",children:"Outcome is"}),e.jsxs(s.Select,{value:o,onValueChange:b=>{u(b),b==="custom"?(h(null),k(null)):o==="custom"&&C("")},children:[e.jsx(s.SelectTrigger,{id:"operation",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"CALCULATED"}),Be.map(b=>e.jsx(s.SelectItem,{value:b.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-sm",children:b.symbol}),e.jsx("span",{children:b.label})]})},b.id))]})})]}),w&&e.jsx("p",{className:"text-xs text-muted-foreground",children:w.description})]}),o==="custom"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"customExpression",children:"SQL Expression"}),e.jsx(s.Textarea,{id:"customExpression",value:j,onChange:b=>C(b.target.value),placeholder:"e.g., CASE WHEN revenue > 1000 THEN revenue - cost ELSE 0 END",className:s.cn("font-mono text-sm",R.customExpression&&"border-red-500"),rows:4}),R.customExpression&&e.jsx("p",{className:"text-xs text-red-500",children:R.customExpression}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Write a SQL expression using column names from your data source"})]}):e.jsxs("div",{className:"rounded-md bg-muted p-3 font-mono text-sm",children:["= ",x&&g?g.label:"A"," ",w==null?void 0:w.symbol," ",p&&y?y.label:"B"]}),o!=="custom"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"inputA",children:"Where"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded bg-muted font-mono text-sm font-medium",children:"A"}),e.jsxs(s.Select,{value:x||"",onValueChange:h,children:[e.jsx(s.SelectTrigger,{id:"inputA",className:R.inputA?"border-red-500":"",children:e.jsx(s.SelectValue,{placeholder:"+ Choose metric"})}),e.jsx(s.SelectContent,{children:n.filter(b=>!s.isCalculatedMetric(b)||b.id!==(r==null?void 0:r.id)).map(b=>e.jsxs(s.SelectItem,{value:b.id,children:[b.label||b.name,b.aggregate&&` (${b.aggregate})`]},b.id))})]})]}),R.inputA&&e.jsx("p",{className:"text-xs text-red-500",children:R.inputA})]}),o!=="custom"&&o!=="scale"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded bg-muted font-mono text-sm font-medium",children:"B"}),e.jsxs(s.Select,{value:p||"",onValueChange:k,children:[e.jsx(s.SelectTrigger,{id:"inputB",className:R.inputB?"border-red-500":"",children:e.jsx(s.SelectValue,{placeholder:"+ Choose metric"})}),e.jsx(s.SelectContent,{children:n.filter(b=>!s.isCalculatedMetric(b)||b.id!==(r==null?void 0:r.id)).map(b=>e.jsxs(s.SelectItem,{value:b.id,children:[b.label||b.name,b.aggregate&&` (${b.aggregate})`]},b.id))})]})]}),R.inputB&&e.jsx("p",{className:"text-xs text-red-500",children:R.inputB})]}),o==="scale"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"constantFactor",children:"Multiplication Factor"}),e.jsx(s.Input$1,{id:"constantFactor",type:"number",step:"any",value:m,onChange:b=>f(parseFloat(b.target.value)||0),placeholder:"e.g., 0.15",className:R.constantFactor?"border-red-500":""}),R.constantFactor&&e.jsx("p",{className:"text-xs text-red-500",children:R.constantFactor}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Enter the constant value to multiply the metric by (e.g., 0.15 for 15%)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"format",children:"Format"}),e.jsxs(s.Select,{value:I.format,onValueChange:b=>O({...I,format:b}),children:[e.jsx(s.SelectTrigger,{id:"format",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsxs(s.SelectItem,{value:"number",children:["Decimal (",I.decimalPlaces,")"]}),e.jsx(s.SelectItem,{value:"currency",children:"Currency"}),e.jsx(s.SelectItem,{value:"percent",children:"Percentage"})]})]})]}),(R.inputs||R.circular)&&e.jsxs(s.Alert,{variant:"destructive",children:[e.jsx(s.CircleAlert,{className:"h-4 w-4"}),e.jsx(s.AlertDescription,{children:R.inputs||R.circular})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:N,children:"Cancel"}),e.jsxs(s.Button,{onClick:M,children:[r?"Update":"Create"," Metric"]})]})]})]})}function Jn({field:t,zone:a,index:n,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:d=!1,cardType:i}){var We,Xe,Ze,es,ss;const{attributes:c,listeners:o,setNodeRef:u,transform:x,transition:h,isDragging:p}=s.useSortable({id:t.id}),k=s.useEditorStore(q=>q.card),{updateLabel:m,handleAggregationChange:f,handleDateFormatChange:j,handleGranularityChange:C,handleAliasTemplateChange:I,handleValueAliasesChange:O,removeField:R,handleKpiComparisonTypeChange:v,handleKpiShowTrendlineChange:w,handleKpiTrendlineWindowChange:g,handleKpiTrendlineGranularityChange:y,handleKpiTargetValueChange:T}=s.useFieldManagement(k),[M,N]=D.useState(!1),[b,A]=D.useState(!1),[F,E]=D.useState(!1),[L,S]=D.useState(null),[P,$]=D.useState(t.dateFormat||"YYYY-MM-DD"),[J,K]=D.useState(t.customFormat||""),[G,H]=D.useState(!!t.customFormat),[B,U]=D.useState(t.granularity||"day"),[V,W]=D.useState(t.aliasTemplate||""),[X,se]=D.useState(t.valueAliases||{}),[_,te]=D.useState((We=t.parameters)==null?void 0:We.filters),Y=q=>{q==="custom"?H(!0):(H(!1),$(q),a==="groupBy"&&j(n,q,""))},le=q=>{K(q),a==="groupBy"&&j(n,"custom",q)},ce=q=>{var oe;U(q);const Z=(oe=s.getDateFormatOptionsForGranularity(q)[0])==null?void 0:oe.value;Z&&!G&&($(Z),a==="groupBy"&&j(n,Z,"")),a==="groupBy"&&C(n,q)},z=q=>{W(q),a==="metrics"&&I(n,q)},ee=q=>{se(q),a==="metrics"&&O(n,q)},de=q=>{m(a,n,q)},ue=q=>{var ne;if(te(q),a==="metrics"){const Z={...t,parameters:{...t.parameters,filters:q}},oe=[...((ne=k.config)==null?void 0:ne.metricColumns)||[]];oe[n]=Z,s.useEditorStore.getState().actions.updateCardConfig(k.id,{metricColumns:oe})}A(!1)},we=()=>{R(a,n)},me={transform:s.CSS.Transform.toString(x),transition:h},je=s.getDataType(t.dataType),xe=je==="date",be=i==="kpi",ke=s.getDateFormatOptionsForGranularity(B),fe=a!=="pivotBy",Te=xe&&a==="groupBy"&&(!be||((Xe=k.config)==null?void 0:Xe.comparisonType)==="start_vs_end"),Ee=!be&&xe&&a==="groupBy",Ae=i&&s.COMPARISON_SUPPORTED_CHART_TYPES.includes(i)&&xe&&a==="groupBy",Ie=i==="kpi"&&xe&&a==="groupBy",ve=i&&i!=="pivotTable"&&a==="metrics"&&((Ze=k.config)==null?void 0:Ze.comparisonType)==="target",ye=a==="metrics",Q=()=>{const q=t,ne=a==="metrics"&&s.isCalculatedMetric(q);return e.jsxs("div",{className:"space-y-1",children:[!ne&&e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:Z=>{Z.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),ne&&q.calculatedFormula&&e.jsxs("div",{title:fs(q.calculatedFormula),onPointerDown:Z=>{Z.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:["= ",fs(q.calculatedFormula)]})]})},ae=()=>fe?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(pe,{value:t.label??"",onSave:de,placeholder:"Display label...",type:"text"})]}):null,re=()=>Te?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(s.Select,{value:B,onValueChange:ce,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsx(s.SelectContent,{children:["day","week","month","quarter","year"].map(q=>e.jsx(s.SelectItem,{className:"text-xs",value:q,children:s.toTitleCase(q)},q))})]})]}):null,Ne=()=>Ee?e.jsxs(e.Fragment,{children:[re(),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Date Format"}),e.jsxs(s.Select,{value:G?"custom":P,onValueChange:Y,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select date format..."})}),e.jsx(s.SelectContent,{children:ke.map(q=>e.jsx(s.SelectItem,{className:"text-xs",value:q.value,children:q.label},q.value))})]}),G&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(s.Input,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:J,onChange:q=>{q.stopPropagation(),le(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,Ws=()=>{var Z,oe,Ce,Me,ge;const q=Ae,ne=Ie;return!q&&!ne?null:e.jsxs(e.Fragment,{children:[q&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(s.Select,{value:((Z=k.config)==null?void 0:Z.comparisonType)||"none",onValueChange:v,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"none",children:"No Comparison"}),e.jsx(s.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(s.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(s.SelectItem,{value:"start_vs_end",children:"Start vs End"})]})]})]}),ne&&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(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(s.SmallSwitch,{checked:((oe=k.config)==null?void 0:oe.showTrendline)||!1,onCheckedChange:w})]})}),((Ce=k.config)==null?void 0:Ce.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(s.Input,{type:"number",min:"1",max:"365",value:((Me=k.config)==null?void 0:Me.trendlineWindow)||30,onChange:Fe=>{const tt=parseInt(Fe.target.value)||30;g(tt)},className:"h-8 text-xs",placeholder:"30"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Granularity"}),e.jsxs(s.Select,{value:((ge=k.config)==null?void 0:ge.trendlineGranularity)||"day",onValueChange:y,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"day",children:"Day"}),e.jsx(s.SelectItem,{value:"week",children:"Week"}),e.jsx(s.SelectItem,{value:"month",children:"Month"})]})]})]})]})]})]})},Xs=()=>{var q,ne;return ve?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(pe,{value:((q=k.config)==null?void 0:q.targetValue)!==void 0&&((ne=k.config)==null?void 0:ne.targetValue)!==null?String(k.config.targetValue):"",onSave:Z=>{!isNaN(Number(Z))&&Z!==null?T(Number(Z)):T(0)},placeholder:"Enter target value...",type:"text"})]}):null},Zs=()=>{if(!ye)return null;const q=t,ne=s.isCalculatedMetric(q);return e.jsxs(e.Fragment,{children:[ne&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Formula"}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>E(!0),children:[e.jsx(s.Pencil,{className:"mr-2 h-3 w-3"}),"Edit Formula"]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(s.Select,{value:t.aggregate,onValueChange:Z=>{f(n,Z)},disabled:ne,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(_==null?void 0:_.conditions)&&_.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:_.conditions.map(Z=>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:()=>{S(Z),A(!0)},children:[e.jsxs("span",{className:"font-medium",children:[Z.field.label,":"]}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"cursor-help text-muted-foreground",children:Array.isArray(Z.value)?Z.value.length===1?String(Z.value[0]):Z.value.length<=2?Z.value.join(", "):`${Z.value.slice(0,2).join(", ")} +${Z.value.length-2}`:String(Z.value)})}),Array.isArray(Z.value)&&Z.value.length>1&&e.jsx(s.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 (",Z.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:Z.value.map((oe,Ce)=>e.jsx("div",{children:String(oe)},Ce))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:oe=>{var Me;oe.stopPropagation();const Ce=_.conditions.filter(ge=>ge.id!==Z.id);if(Ce.length>0){const ge={..._,conditions:Ce};ue(ge)}else if(te(void 0),a==="metrics"){const ge={...t,parameters:{...t.parameters,filters:void 0}},Fe=[...((Me=k.config)==null?void 0:Me.metricColumns)||[]];Fe[n]=ge,s.useEditorStore.getState().actions.updateCardConfig(k.id,{metricColumns:Fe})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},Z.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{S(null),A(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(qn,{column:t}),d&&e.jsxs(e.Fragment,{children:[e.jsx(Kn,{aliasTemplate:V,onAliasTemplateChange:z}),e.jsx(Gn,{valueAliases:X,onValueAliasesChange:ee})]})]})},{columns:et=[]}=s.useColumns(),st=(_==null?void 0:_.conditions)&&_.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:u,style:me,...c,...o,className:`group mx-auto flex w-full flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${p?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(Qe,{dataType:je}),e.jsx(Je,{className:s.cn("w-[140px] flex-1 text-sm",st&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),a==="metrics"&&((es=_==null?void 0:_.conditions)==null?void 0:es.length)&&!M&&e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.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",children:[e.jsx(s.Filter,{className:"h-3 w-3"}),e.jsx("span",{children:_.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:_.conditions.map(q=>e.jsxs("div",{children:[q.field.label,":"," ",Array.isArray(q.value)?`${q.value.length} values`:String(q.value)]},q.id))})})]})}),a!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:q=>{q.stopPropagation(),N(!M)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${M?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:q=>{q.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const ne=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",ne),l(ne)},children:r==="asc"?e.jsx(s.ArrowUp,{className:"h-3 w-3"}):e.jsx(s.ArrowDown,{className:"h-3 w-3"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:q=>{q.stopPropagation(),we()},children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]}),M&&e.jsxs("div",{className:"space-y-3",children:[Q(),ae(),i==="kpi"&&re(),Ne(),Ws(),Xs(),Zs()]})]}),b&&e.jsx(_s,{open:b,onOpenChange:q=>{A(q),q||S(null)},availableFields:et,existingFilters:_,editingCondition:L,onSave:q=>{var ne;if(q)ue(q);else if(te(void 0),a==="metrics"){const Z={...t,parameters:{...t.parameters,filters:void 0}},oe=[...((ne=k.config)==null?void 0:ne.metricColumns)||[]];oe[n]=Z,s.useEditorStore.getState().actions.updateCardConfig(k.id,{metricColumns:oe})}S(null)}}),F&&a==="metrics"&&e.jsx(Qs,{open:F,onOpenChange:E,availableMetrics:((ss=k.config)==null?void 0:ss.metricColumns)||[],existingField:t,onSave:q=>{var Z;const ne=[...((Z=k.config)==null?void 0:Z.metricColumns)||[]];ne[n]=q,s.useEditorStore.getState().actions.updateCardConfig(k.id,{metricColumns:ne})},cardId:k.id})]})}function _n({concept:t}){const a=()=>{switch(t){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"})]})]})]});default:return null}};return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(s.TooltipContent,{side:"right",align:"start",className:"p-3",children:a()})]})})}function Re({zone:t,fields:a,label:n,placeholder:r,shouldShow:l,hasPivotColumns:d=!1,activeField:i=null}){const{isOver:c,setNodeRef:o}=s.useDroppable({id:t}),{updateSortByColumn:u}=s.useEditorActions(),x=s.useEditorStore(j=>j.card),h=s.useEditorStore(j=>j.card.type),p=a.length>0,k=D.useMemo(()=>!i||!c?!0:s.validateFieldForChartType(i,t,h).isValid,[i,c,t,h]),m=(j,C)=>{var O;!((O=x.config)!=null&&O.sortByColumns)||x.config.sortByColumns.findIndex(R=>R.id===j)===-1||u(x.id,j,{direction:C})};if(t==="sortBy"&&l===!1)return null;const f=t!=="sortBy"&&h!=="kpi";return e.jsxs("div",{className:"mb-4 w-full",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:n}),f&&e.jsx(_n,{concept:t})]}),e.jsx("div",{ref:o,className:s.cn("rounded-lg border-2 border-dotted p-0.5 transition-all",{"border-green-500 bg-green-50 dark:bg-green-950":c&&k,"border-red-500 bg-red-50 dark:bg-red-950":c&&!k,"border-muted-foreground/30 bg-muted/40":!c&&p,"min-h-[60px] border-muted-foreground/20 bg-background":!c&&!p}),children:a.length===0?e.jsx("div",{className:"flex min-h-[60px] items-center justify-center text-sm text-muted-foreground/60",children:r}):e.jsx(s.SortableContext,{items:a.map(j=>j.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:a.map((j,C)=>{const O=j.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(Jn,{field:j,zone:t,index:C,sortDirection:O,onSortDirectionChange:R=>m(j.id,R),hasPivotColumns:d,cardType:h})})},j.id)})})})})]})}const gs={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%
190
+ 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 Qn(){var p,k,m,f,j,C,I,O,R,v,w;const t=s.useEditorStore(g=>g.card),{setCardPreferences:a}=s.useEditorActions(),n=((p=t.config)==null?void 0:p.metricColumns)||[],r=((k=t.config)==null?void 0:k.groupByColumns)||[],l=n.length===2&&r.length===0,d=n.length>=1&&r.length>0;if(!(t.type==="kpi"&&(l||d)))return null;const c=((f=(m=t.preferences)==null?void 0:m.kpiVisualOptions)==null?void 0:f.metricComparison)||{},o=g=>{var T;const y={...t.preferences,kpiVisualOptions:{...(T=t.preferences)==null?void 0:T.kpiVisualOptions,metricComparison:{...c,...g}}};a(y)},u=d||c.enabled,x=((j=t.config)==null?void 0:j.comparisonType)||"none",h=x==="previous_period"||x==="same_period_last_year"||x==="start_vs_end";return e.jsxs(s.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(s.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(mt,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[l&&n.length===2&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(s.SmallSwitch,{id:"enable-comparison",checked:c.enabled||!1,onCheckedChange:g=>o({enabled:g,...g&&!c.calculationType?{calculationType:"difference"}:{}})})]}),u&&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(s.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Info,{className:"h-3 w-3 cursor-help text-muted-foreground"})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-xs",children:(()=>{const g=c.calculationType||"difference",y=gs[g];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:y==null?void 0:y.label}),e.jsx("p",{children:y==null?void 0:y.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:y==null?void 0:y.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",y==null?void 0:y.example]})]})})()})]})]}),e.jsxs(s.Select,{value:c.calculationType||"difference",onValueChange:g=>o({calculationType:g}),children:[e.jsx(s.SelectTrigger,{id:"calculation-type",className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Object.entries(gs).map(([g,y])=>e.jsx(s.SelectItem,{value:g,className:"text-xs",children:y.label},g))})]})]}),e.jsx(_e,{formatOptions:c.formatOptions||{},onFormatOptionsChange:g=>o({formatOptions:g}),showTitle:!0,title:"COMPARISON FORMAT"}),(h||l)&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator"}),l&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:c.position||"right",onValueChange:g=>o({position:g}),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"right",className:"text-xs",children:"Right"}),e.jsx(s.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(s.SelectItem,{value:"top",className:"text-xs",children:"Top"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-arrow",checked:c.showArrow!==!1,onCheckedChange:g=>o({showArrow:g})}),e.jsx(s.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(s.Checkbox,{id:"show-color",checked:c.showColor!==!1,onCheckedChange:g=>o({showColor:g})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),c.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(Le,{value:((C=c.colorConfig)==null?void 0:C.increase)||"green",onChange:g=>o({colorConfig:{...c.colorConfig,increase:g}}),label:"Primary > Secondary"}),e.jsx(Le,{value:((I=c.colorConfig)==null?void 0:I.decrease)||"red",onChange:g=>o({colorConfig:{...c.colorConfig,decrease:g}}),label:"Primary < Secondary"}),e.jsx(Le,{value:((O=c.colorConfig)==null?void 0:O.noChange)||"neutral",onChange:g=>o({colorConfig:{...c.colorConfig,noChange:g}}),label:"Primary = Secondary"})]})]}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"conditional-label",checked:c.conditionalLabel||!1,onCheckedChange:g=>o({conditionalLabel:g})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),c.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(s.Input$1,{id:"label-increase",type:"text",value:((R=c.conditionalLabels)==null?void 0:R.increase)??"Increase",onChange:g=>o({conditionalLabels:{...c.conditionalLabels,increase:g.target.value}}),placeholder:"Increase",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-decrease",className:"text-xs text-muted-foreground",children:["Primary ","<"," Secondary"]}),e.jsx(s.Input$1,{id:"label-decrease",type:"text",value:((v=c.conditionalLabels)==null?void 0:v.decrease)??"Decrease",onChange:g=>o({conditionalLabels:{...c.conditionalLabels,decrease:g.target.value}}),placeholder:"Decrease",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-no-change",className:"text-xs text-muted-foreground",children:"Primary = Secondary"}),e.jsx(s.Input$1,{id:"label-no-change",type:"text",value:((w=c.conditionalLabels)==null?void 0:w.noChange)??"No change",onChange:g=>o({conditionalLabels:{...c.conditionalLabels,noChange:g.target.value}}),placeholder:"No change",className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-name",className:"text-xs text-muted-foreground",children:"Previous Label"}),e.jsx(s.Input$1,{id:"label-name",type:"text",value:c.labelName??"",onChange:g=>o({labelName:g.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function Yn(){var l,d;const t=s.useEditorStore(i=>i.card),{setCardPreferences:a}=s.useEditorActions();if(t.type!=="kpi")return null;const n=((d=(l=t.preferences)==null?void 0:l.kpiVisualOptions)==null?void 0:d.formatOptions)||{},r=i=>{var o;const c={...t.preferences,kpiVisualOptions:{...(o=t.preferences)==null?void 0:o.kpiVisualOptions,formatOptions:i}};a(c)};return e.jsxs(s.AccordionItem,{value:"kpi-format",className:"border-none",children:[e.jsx(s.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(s.Hash,{className:"h-4 w-4"}),e.jsx("span",{children:"Number Format"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:e.jsx(_e,{formatOptions:n,onFormatOptionsChange:r,showTitle:!1})})]})}function Wn(){var d;const t=s.useEditorStore(i=>{var c;return(c=i.card)==null?void 0:c.type}),a=s.useEditorStore(i=>{var c;return(c=i.card)==null?void 0:c.preferences}),{setCardPreferences:n}=s.useEditorActions();if(t!=="treemap")return null;const r=((d=a==null?void 0:a.chartOptions)==null?void 0:d.treemapColorMode)??"branch",l=i=>{const c={...a||{},chartOptions:{...a==null?void 0:a.chartOptions,treemapColorMode:i}};n(c)};return e.jsxs(s.AccordionItem,{value:"treemap-color-mode",className:"border-none",children:[e.jsx(s.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(s.TbChartTreemap,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Treemap Colors"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:e.jsxs(s.RadioGroup,{value:r,onValueChange:i=>l(i??"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(s.RadioGroupItem,{id:"treemap-color-branch",value:"branch"}),e.jsxs(s.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(s.RadioGroupItem,{id:"treemap-color-category",value:"category"}),e.jsxs(s.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."})]})]})]})})]})}function Xn({groupByFields:t,pivotByFields:a,metricsFields:n,sortByFields:r,activeField:l}){const[d,i]=D.useState(!1),c=s.useEditorStore(O=>{var R;return((R=O.card.customCardPreferences)==null?void 0:R.url)&&O.card.type==="custom"}),o=s.useEditorStore(O=>O.card),u=s.useEditorStore(O=>O.actions.updateCardConfig),x=o==null?void 0:o.type,h=t.length>0||n.length>0,p=x!=="kpi"||n.length<=2,k=x!=="kpi",m=x!=="kpi"&&h,f=["pie","doughnut","polar","funnel","aggregateTable","bubble","scatter"].includes(x),j=k&&!f,C=()=>x==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},I=()=>x==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Columns",placeholder:"Drop fields to measure"};return e.jsxs(e.Fragment,{children:[e.jsxs(s.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full",children:[e.jsxs(s.AccordionItem,{value:"fields",className:"border-b-0",children:[e.jsx(s.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(s.List,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[p&&e.jsx(Re,{zone:"groupBy",fields:t,label:C().label,placeholder:C().placeholder,activeField:l}),j&&e.jsx(Re,{zone:"pivotBy",fields:a,label:"Pivot Columns",placeholder:"Drop fields to pivot data",activeField:l}),e.jsx(Re,{zone:"metrics",fields:n,label:I().label,placeholder:I().placeholder,hasPivotColumns:a.length>0,activeField:l}),n.length>=1&&e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:()=>i(!0),className:"mt-2 w-full justify-start text-xs text-muted-foreground hover:text-foreground",children:[e.jsx(s.Calculator,{className:"mr-2 h-4 w-4"}),"Create Metric"]}),m&&e.jsx(Re,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics",activeField:l})]})]}),!c&&e.jsxs(s.AccordionItem,{value:"configuration",className:"border-b-0",children:[e.jsx(s.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(s.Settings2,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"CONFIGURATION"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[e.jsx(Yn,{}),e.jsx(Qn,{}),e.jsx(zs,{}),e.jsx(Wn,{}),e.jsx(Us,{}),x==="bullet"&&e.jsx(qs,{}),x==="funnel"&&e.jsx(Js,{}),(x==="bubble"||x==="scatter")&&e.jsx(Hs,{}),e.jsx($s,{}),e.jsx(Ks,{}),e.jsx(Gs,{})]})})]}),c&&e.jsxs(s.AccordionItem,{value:"plugin",className:"border-b-0",children:[e.jsx(s.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(vs,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"CONFIGURATION"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsx(Fs,{})})]})]}),e.jsx(Qs,{open:d,onOpenChange:i,availableMetrics:n,onSave:O=>{u(o.id,{metricColumns:[...n,O]})},cardId:o.id})]})}function Zn({onEditJoins:t}){const a=s.useEditorStore(c=>c.card),{autoJoinMetadata:n}=s.useDashboardCardQuery(a);if(!(n!=null&&n.autoResolved))return null;const{resolvedJoinPlan:r}=n,l=(r==null?void 0:r.joins)||[];if(l.length===0)return null;const d=c=>!c||c.length===0?"No conditions":c.map(o=>{var p,k,m,f;const u=`${(p=o.source)==null?void 0:p.entityName}.${(k=o.source)==null?void 0:k.name}`,x=`${(m=o.target)==null?void 0:m.entityName}.${(f=o.target)==null?void 0:f.name}`,h=o.operator||"=";return`${u} ${h} ${x}`}).join(" AND "),i=c=>!c.joinKeyGroups||c.joinKeyGroups.length===0?"No conditions defined":c.joinKeyGroups.length===1?d(c.joinKeyGroups[0].keys):c.joinKeyGroups.map((o,u)=>({id:u,operator:o.operator,condition:d(o.keys)}));return e.jsx(s.Card,{className:"border-blue-500/30 bg-blue-50/30 dark:bg-blue-950/20",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(Et,{className:"size-4 text-blue-600 dark:text-blue-400"}),e.jsx("h3",{className:"text-sm font-medium text-blue-900 dark:text-blue-100",children:"Auto-Resolved Joins"}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"secondary",className:"cursor-help bg-blue-100 text-xs text-blue-700 dark:bg-blue-900 dark:text-blue-300",children:l.length})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"max-w-md p-3",children:e.jsx("div",{className:"space-y-2",children:l.map((c,o)=>{const u=i(c),x=Array.isArray(u);return e.jsxs("div",{className:"rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"font-medium text-foreground",children:c.source.name}),e.jsx(s.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:c.target.name})]}),e.jsx(s.Badge,{variant:"outline",className:"border-green-500/40 bg-green-50/30 text-xs text-green-700 dark:bg-green-950/30 dark:text-green-300",children:c.joinType})]}),e.jsx("div",{className:"mt-1 space-y-1",children:x?u.map(h=>e.jsxs("div",{className:"rounded bg-muted/30 px-2 py-1",children:[e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:h.condition}),h.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",h.operator,")"]})]},h.id)):e.jsx("div",{className:"rounded bg-muted/30 px-2 py-1",children:e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:u})})})]},c.id||o)})})})]})})]}),t&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:t,className:"h-7 gap-1 p-2 text-xs text-blue-700 hover:text-blue-900 dark:text-blue-300 dark:hover:text-blue-100",children:e.jsx(s.SquarePen,{className:"size-3.5"})})]})})}const js={getItem(t){if(typeof window>"u")return null;try{return localStorage.getItem(t)}catch(a){return console.warn(`Failed to read from localStorage (${t}):`,a),null}},setItem(t,a){if(!(typeof window>"u"))try{localStorage.setItem(t,a)}catch(n){console.warn(`Failed to write to localStorage (${t}):`,n)}}};function ea({selectedChart:t,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:d,activeField:i}){var g,y;const[c,o]=D.useState(()=>js.getItem("chart-selector-expanded")==="true"),[u,x]=D.useState(!1),h=s.useEditorStore(T=>T.card),p=s.useEditorStore(T=>T.actions.updateCardConfig),k=n.length>0||r.length>0||l.length>0,{data:m,autoJoinMetadata:f}=s.useDashboardCardQuery(h),j=((g=h==null?void 0:h.config)==null?void 0:g.joinPlan)||(f!=null&&f.autoResolved?f.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),C=((y=h==null?void 0:h.dataSource)==null?void 0:y.selectedEntities)||[],I=T=>{p(h.id,{...h==null?void 0:h.config,joinPlan:T}),x(!1)},O=()=>{p(h.id,{...h==null?void 0:h.config,joinPlan:void 0}),x(!1)},R=()=>{x(!1)},v=()=>{x(!0)};D.useEffect(()=>{js.setItem("chart-selector-expanded",String(c))},[c]);const w=()=>{o(T=>!T)};return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col border-x border-border",children:[e.jsxs("div",{className:s.cn("px-6 pt-4",{"space-y-4":c}),children:[e.jsx("div",{className:s.cn("overflow-hidden transition-all duration-300 ease-in-out",c?"max-h-[200px] opacity-100":"max-h-0 opacity-0"),children:c&&e.jsx(Pn,{selectedChart:t,onChartChange:a})}),e.jsx("div",{"data-content":"Chart Quick Selector",className:"flex items-center justify-center",children:e.jsx(s.ChartQuickSelector,{selectedChart:t,onChartChange:a,isDropdownExpanded:c,onToggleDropdown:w})})]}),e.jsx("div",{className:s.cn("flex justify-end gap-2 px-6 py-6"),children:e.jsx("div",{className:s.cn("invisible flex gap-2",{visible:k||m}),children:e.jsx(qe.EditorClearButton,{})})}),e.jsxs(s.ScrollArea,{className:"w-full flex-1 basis-0 px-6 pb-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx(Zn,{onEditJoins:v}),e.jsx(Xn,{groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:d,activeField:i})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]}),e.jsx(ws,{open:u,onOpenChange:x,joinPlan:j,availableDataSources:C,onSave:I,onCancel:R,onRemove:O,children:e.jsx("div",{})})]})}function sa({initialFilters:t,availableFields:a}={}){const[n,r]=D.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(v=>v.card.dataSource);const{columns:l,isLoading:d}=s.useColumns(),c=a||l||[],o={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=v=>{const w=g=>{if(g.id===v){const y=c[0]||o,T=s.getDataType(y.dataType)==="date";return{...g,conditions:[...g.conditions,{id:`condition-${Date.now()}`,field:y,operator:T?"between":"=",value:T?[]:""}]}}return{...g,groups:g.groups.map(w)}};r(w(n))},x=v=>{const w=g=>{if(g.id===v){const y=c[0]||o,T=s.getDataType(y.dataType)==="date";return{...g,groups:[...g.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:y,operator:T?"between":"=",value:T?[]:""}],groups:[]}]}}return{...g,groups:g.groups.map(w)}};r(w(n))},h=(v,w)=>{const g=y=>y.id===v?{...y,conditions:y.conditions.filter(T=>T.id!==w)}:{...y,groups:y.groups.map(g)};r(g(n))},p=(v,w)=>{const g=y=>y.id===v?{...y,groups:y.groups.filter(T=>T.id!==w)}:{...y,groups:y.groups.map(g)};r(g(n))},k=(v,w,g,y)=>{if(g==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const T=M=>M.id===v?{...M,conditions:M.conditions.map(N=>N.id===w?{...N,[g]:y}:N)}:{...M,groups:M.groups.map(T)};r(T(n))},m=(v,w,g)=>{const y=T=>T.id===v?{...T,conditions:T.conditions.map(M=>M.id===w?{...M,...g}:M)}:{...T,groups:T.groups.map(y)};r(y(n))},f=(v,w)=>{const g=y=>y.id===v?{...y,logicalOperator:w}:{...y,groups:y.groups.map(g)};r(g(n))},j=(v,w)=>{const g=y=>y.id===v?{...y,negate:w}:{...y,groups:y.groups.map(g)};r(g(n))},C=(v,w,g)=>{const y=T=>T.id===v?{...T,conditions:s.arrayMove(T.conditions,w,g)}:{...T,groups:T.groups.map(y)};r(y(n))},I=(v,w,g)=>{const y=T=>T.id===v?{...T,groups:s.arrayMove(T.groups,w,g)}:{...T,groups:T.groups.map(y)};r(y(n))},O=v=>{if(!v||v.conditions.length===0&&v.groups.length===0)return"-- No filters defined";const w=y=>{let T="";typeof y.field=="object"?T=y.field.entityName?`${y.field.entityName}.${y.field.name}`:y.field.name:T=String(y.field);const M=y.operator;let N=y.value;if(y.field.dataType==="string"&&!["in","not in"].includes(y.operator))typeof N=="string"?N=`'${N}'`:Array.isArray(N)&&(N=`'${N.join(", ")}'`);else if(y.field.dataType==="date"||y.field.dataType==="datetime"||y.field.dataType==="timestamp")if(y.operator==="between"&&Array.isArray(N)&&N.length===2){const b=N[0]?`'${N[0]}'`:"NULL",A=N[1]?`'${N[1]}'`:"NULL";return`${T} BETWEEN ${b} AND ${A}`}else if((y.operator==="in"||y.operator==="not in")&&Array.isArray(N)){const b=N.map(A=>A?`'${A}'`:"NULL").join(", ");return`${T} ${M} (${b})`}else typeof N=="string"||N instanceof Date?N=`'${N}'`:Array.isArray(N)&&N.length>0&&(N=`'${N[0]}'`);else if(["in","not in"].includes(y.operator)){let b=[];Array.isArray(N)?b=N.map(A=>typeof A=="string"?`'${A}'`:String(A)):typeof N=="string"?b=N.split(",").map(A=>{const F=A.trim();return y.field.dataType==="string"?`'${F}'`:F}):typeof N=="number"&&(b=[String(N)]),N=`(${b.join(", ")})`}switch(M){case"contains":return typeof N=="string"?`${T} LIKE '%${N.replace(/'/g,"")}'`:`${T} LIKE '%${String(N)}'`;case"startsWith":return typeof N=="string"?`${T} LIKE '${N.replace(/'/g,"")}%'`:`${T} LIKE '${String(N)}%'`;case"endsWith":return typeof N=="string"?`${T} LIKE '%${N.replace(/'/g,"")}'`:`${T} LIKE '%${String(N)}'`;case"isNull":return`${T} IS NULL`;case"isNotNull":return`${T} IS NOT NULL`;default:return`${T} ${M} ${N}`}},g=y=>{const T=y.conditions.map(w),M=y.groups.map(F=>g(F)),N=[...T,...M].filter(Boolean);if(N.length===0)return"";const b=N.join(` ${y.logicalOperator} `),A=N.length>1?`(${b})`:b;return y.negate?`NOT ${A}`:A};return g(v)},R=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:c,isLoading:d,addCondition:u,addGroup:x,removeCondition:h,removeGroup:p,updateCondition:k,updateConditionFields:m,updateGroupOperator:f,updateGroupNegate:j,reorderConditions:C,reorderGroups:I,generateSQLPreview:O,hasAnyFilters:R}}function ta({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const na=t=>{if(t.qualifiedEntityName){const a=t.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function aa({value:t,onValueChange:a,availableFields:n,placeholder:r="Select field",className:l="w-64"}){const[d,i]=D.useState(!1),c=D.useMemo(()=>{const o={};return n.forEach(u=>{const x=na(u);o[x]||(o[x]={}),o[x][u.entityId]||(o[x][u.entityId]=[]),o[x][u.entityId].push(u)}),o},[n]);return e.jsxs(s.Popover,{modal:!0,open:d,onOpenChange:i,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":d,className:s.cn("justify-between",!t&&"text-muted-foreground",l),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(ta,{children:[t.entityName,".",t.name]})}):r,e.jsx(s.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(s.CommandEmpty,{children:"No fields found."}),e.jsx(s.CommandList,{className:"max-h-80",children:Object.entries(c).map(([o,u])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),o]}),children:Object.entries(u).map(([x,h])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[s.getEntityIcon(h[0].entityType,{size:"h-3 w-3"}),e.jsx("span",{children:h[0].entityName})]}),h.map((p,k)=>e.jsxs(s.CommandItem,{value:p.id,onSelect:()=>{a(p),i(!1)},className:"overflow-x-auto",children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",(t==null?void 0:t.id)===p.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:p.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:p.description&&e.jsx("span",{children:p.description})})]})]},p.id+k))]},`${o}-${x}`))},o))})]})})]})}function Ye(t){var f;const a=s.useEditorStore(j=>j.card),{authToken:n,tokenProps:r}=s.useSemaphorContext(),l=s.useEditorStore(j=>j.card.config),d=l==null?void 0:l.joinPlan,i={...t,alias:t.name,label:"value",role:"groupby"},c={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},o={...i,role:"sortby",direction:"asc"},u={joinPlan:d,groupByColumns:[i],metricColumns:[c],sortByColumns:[o]},x=((f=a.dataSource)==null?void 0:f.connectionId)||a.connectionId,{data:h,isPending:p,error:k}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular(`${r.apiServiceUrl}/v1/query`,(n==null?void 0:n.accessToken)||"",{connection_id:x,cardConfig:u,cardDataSource:a.dataSource})}catch(j){console.log(t),console.error("error",j)}},enabled:!!x,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((h==null?void 0:h.records)||[]).map(j=>({label:j.value||"BLANK",value:j.value||"BLANK",count:(j==null?void 0:j.count)||0})),isPending:p,error:k}}function ra({field:t,selected:a,onChange:n,placeholder:r="Select items...",className:l}){const[d,i]=Ke.useState(!1),{filterValues:c}=Ye(t),o=x=>{n(a.filter(h=>h!==x))},u=x=>{a.includes(x)?n(a.filter(h=>h!==x)):n([...a,x])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open:d,onOpenChange:i,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":d,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(x=>{const h=c.find(p=>p.value===x);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[h==null?void 0:h.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:p=>{p.key==="Enter"&&o(x)},onMouseDown:p=>{p.preventDefault(),p.stopPropagation()},onClick:p=>{p.stopPropagation(),o(x)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},x)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No results found."}),e.jsx(s.CommandGroup,{children:c.map((x,h)=>e.jsxs(s.CommandItem,{onSelect:()=>u(x.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",a.includes(x.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:x.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:x.count})]})]},x.value+h))})]})]})})]})})}function la({field:t,value:a,onChange:n,placeholder:r="Select value...",className:l}){const{filterValues:d,isPending:i,error:c}=Ye(t);return i?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):c?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:a,onValueChange:n,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:a})}),e.jsx(s.SelectContent,{children:d.map((o,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:o.value,children:o.label},o.value+u))})]})}function oa({value:t,operator:a,onChange:n,className:r}){var o;const{tokenProps:l}=s.useSemaphorContext(),d=(o=l==null?void 0:l.params)==null?void 0:o.timezone,i=D.useMemo(()=>{if(t){if(a==="between"||a==="not between"){if(Array.isArray(t)&&t.length===2){const u=t[0]?new Date(t[0]):void 0,x=t[1]?new Date(t[1]):void 0;if(u&&x)return{from:u,to:x}}}else if(a==="="||a==="!="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:u}}}else if(a===">"||a===">="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:void 0}}}else if(a==="<"||a==="<="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:void 0,to:u}}}else if((a==="in"||a==="not in")&&Array.isArray(t)&&t.length>0){const u=new Date(t[0]),x=t.length>1?new Date(t[t.length-1]):u;if(!isNaN(u.getTime()))return{from:u,to:x}}}},[t,a]),c=u=>{if(!u){n(void 0);return}if(u.from&&u.to)n([u.from.toISOString(),u.to.toISOString()]);else if(u.from){const x=new Date(u.from);x.setHours(23,59,59,999),n([u.from.toISOString(),x.toISOString()])}else if(u.to){const x=new Date(u.to);x.setHours(0,0,0,0),n([x.toISOString(),u.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:i,onChange:c,timezone:d,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const ia=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],ca=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],da=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],ua=["=","!=","isNull","isNotNull"],ma=["between","isNull","isNotNull"],xa={"=":"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 bs(t){return xa[t]||s.titleCase(t)}function ha(t){switch(t){case"string":return ca;case"number":return da;case"boolean":return ua;case"date":return ma;default:return ia}}function Ys({condition:t,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:d,onUpdateGroupOperator:i,availableFields:c,updateConditionFields:o}){const{attributes:u,listeners:x,setNodeRef:h,transform:p,transition:k,isDragging:m}=s.useSortable({id:t.id}),{isPending:f,error:j}=Ye(t.field),C={transform:s.CSS.Transform.toString(p),transition:k};return e.jsxs("div",{ref:h,style:C,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${m?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...x,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(s.Select,{value:r,onValueChange:I=>i(n,I),children:[e.jsx(s.SelectTrigger,{className:"w-24",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(aa,{value:t.field,onValueChange:I=>{const O=I,R=s.getDataType(O.dataType)==="date";o(n,t.id,{field:O,value:"",operator:R?"between":"="})},availableFields:c,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:I=>{I==="in"||I==="not in"?o(n,t.id,{operator:I,value:[]}):I==="isNull"||I==="isNotNull"?o(n,t.id,{operator:I,value:null}):o(n,t.id,{operator:I,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?bs(t.operator):""})}),e.jsx(s.SelectContent,{children:ha(s.getDataType(t.field.dataType)).map(I=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:I,children:bs(I)},I))})]}),t.operator==="isNull"||t.operator==="isNotNull"?e.jsx("div",{className:"flex-1"}):s.getDataType(t.field.dataType)==="string"?t.operator==="in"||t.operator==="not in"?f?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.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(ra,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(I=>typeof I=="string")?t.value:[],onChange:I=>o(n,t.id,{value:I}),placeholder:`Select values for ${t.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(t.operator)?e.jsx(s.Input,{value:typeof t.value=="string"?t.value:"",onChange:I=>o(n,t.id,{value:I.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(la,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:I=>o(n,t.id,{value:I}),placeholder:"Select value...",className:"flex-1"}):s.getDataType(t.field.dataType)==="boolean"?e.jsxs(s.Select,{value:typeof t.value=="boolean"?String(t.value):"",onValueChange:I=>o(n,t.id,{value:I==="true"}),children:[e.jsx(s.SelectTrigger,{className:"flex-1",children:e.jsx(s.SelectValue,{placeholder:"Select value..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"true",children:"True"}),e.jsx(s.SelectItem,{value:"false",children:"False"})]})]}):s.getDataType(t.field.dataType)==="date"?e.jsx(oa,{value:t.value,operator:t.operator,onChange:I=>o(n,t.id,{value:I}),className:"flex-1"}):e.jsx(s.Input,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:I=>l(n,t.id,"value",I.target.value),className:"flex-1",placeholder:t.operator==="in"||t.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>d(n,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function pa({group:t,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:d,onUpdateCondition:i,onUpdateField:c,onRemoveCondition:o,onReorderConditions:u,onReorderGroups:x,onAddCondition:h,onAddGroup:p,availableFields:k,renderFilterGroup:m,updateConditionFields:f}){const{attributes:j,listeners:C,setNodeRef:I,transform:O,transition:R,isDragging:v}=s.useSortable({id:t.id}),w={transform:s.CSS.Transform.toString(O),transition:R},g=T=>{const{active:M,over:N}=T;if(N&&M.id!==N.id){const b=t.conditions.findIndex(F=>F.id===M.id),A=t.conditions.findIndex(F=>F.id===N.id);b!==-1&&A!==-1&&u(t.id,b,A)}},y=T=>{const{active:M,over:N}=T;if(N&&M.id!==N.id&&n){const b=t.groups.findIndex(F=>F.id===M.id),A=t.groups.findIndex(F=>F.id===N.id);b!==-1&&A!==-1&&x(n,b,A)}};return e.jsxs("div",{ref:I,style:w,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${v?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...j,...C,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(s.Button,{variant:t.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>l(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:T=>r(t.id,T),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>n&&d(n,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:g,children:e.jsx(s.SortableContext,{items:t.conditions.map(T=>T.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((T,M)=>e.jsx(Ys,{condition:T,index:M,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:i,onUpdateField:c,onRemoveCondition:o,onUpdateGroupOperator:r,availableFields:k,updateConditionFields:f},T.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:y,children:e.jsx(s.SortableContext,{items:t.groups.map(T=>T.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(T=>m(T,a+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>p(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function fa({filters:t,availableFields:a,onSave:n,onClearAll:r,onCancel:l}){const{currentFilters:d,availableFields:i,isLoading:c,addCondition:o,addGroup:u,removeCondition:x,removeGroup:h,updateCondition:p,updateConditionFields:k,updateGroupOperator:m,updateGroupNegate:f,reorderConditions:j,reorderGroups:C,generateSQLPreview:I,hasAnyFilters:O,setCurrentFilters:R}=sa({initialFilters:t,availableFields:a}),v=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[w,g]=D.useState(!1),y=(N,b,A)=>{const F=E=>E.id===N?{...E,conditions:E.conditions.map(L=>L.id===b?{...L,field:A,dataType:A.dataType}:L)}:{...E,groups:E.groups.map(F)};R(F(d))},T=(N,b=0,A)=>b===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:v,collisionDetection:s.closestCenter,onDragEnd:F=>{const{active:E,over:L}=F;if(L&&E.id!==L.id){const S=N.conditions.findIndex($=>$.id===E.id),P=N.conditions.findIndex($=>$.id===L.id);S!==-1&&P!==-1&&j(N.id,S,P)}},children:e.jsx(s.SortableContext,{items:N.conditions.map(F=>F.id),strategy:s.verticalListSortingStrategy,children:N.conditions.map((F,E)=>e.jsx(Ys,{condition:F,index:E,groupId:N.id,groupLogicalOperator:N.logicalOperator,onUpdateCondition:p,onUpdateField:y,onRemoveCondition:x,onUpdateGroupOperator:m,availableFields:i,updateConditionFields:k},F.id))})}),e.jsx(s.DndContext,{sensors:v,collisionDetection:s.closestCenter,onDragEnd:F=>{const{active:E,over:L}=F;if(L&&E.id!==L.id){const S=N.groups.findIndex($=>$.id===E.id),P=N.groups.findIndex($=>$.id===L.id);S!==-1&&P!==-1&&C(N.id,S,P)}},children:e.jsx(s.SortableContext,{items:N.groups.map(F=>F.id),strategy:s.verticalListSortingStrategy,children:N.groups.map(F=>T(F,b+1,N.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>o(N.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),w&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(N.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},N.id):e.jsx(pa,{group:N,depth:b,parentGroupId:A,onUpdateGroupOperator:m,onUpdateGroupNegate:f,onRemoveGroup:h,onUpdateCondition:p,onUpdateField:y,onRemoveCondition:x,onReorderConditions:j,onReorderGroups:C,onAddCondition:o,onAddGroup:u,availableFields:i,renderFilterGroup:T,updateConditionFields:k},N.id),M=s.getFilterCount(t);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Card,{children:e.jsx(s.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[c?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):T(d),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(s.SmallSwitch,{id:"advanced-mode",checked:w,onCheckedChange:N=>g(N)}),e.jsx(s.Label,{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),O&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:I(d)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:l,children:"Cancel"}),M>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>n(O?d:null),children:"Apply Filters"})]})]})}function ga({cardId:t,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:l,isOpen:d,onOpenChange:i}){const c=u=>{n(t,u),i(!1)},o=()=>{r(t),i(!1)};return e.jsxs(s.Dialog,{modal:!1,open:d,onOpenChange:i,children:[d&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:u=>{u.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Card Filters"}),e.jsx(s.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(fa,{filters:a,availableFields:l,onSave:c,onCancel:()=>i(!1),onClearAll:o})]})]})}function ja({activeCardId:t,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var j,C;const[l,d]=D.useState(null),i=s.useEditorStore(I=>I.card),c=s.useEditorStore(I=>I.actions.updateCardConfig),o=(j=i==null?void 0:i.config)==null?void 0:j.joinPlan,u=(C=i==null?void 0:i.dataSource)==null?void 0:C.semanticDomainId,{data:x}=s.useJoinabilityMap(u),h=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],p=D.useCallback(I=>I.startsWith("card-")?null:I.startsWith("source-")||a.find(O=>O.id===I)?"source":n("groupBy").find(O=>O.id===I)?"groupBy":n("metrics").find(O=>O.id===I)?"metrics":n("pivotBy").find(O=>O.id===I)?"pivotBy":n("sortBy").find(O=>O.id===I)?"sortBy":null,[a,n]),k=D.useCallback(I=>{d(I.active.id)},[]),m=D.useCallback(I=>{var T;const{active:O,over:R}=I;if(!R||!t){d(null);return}const v=O.id,w=R.id,g=p(v),y=p(w)||w;if(y==="sortBy"){if(g==="source"){const M=a.find(b=>b.id===v);if(!M){d(null);return}if(!(n("groupBy").some(b=>b.name===M.name&&b.qualifiedEntityName===M.qualifiedEntityName)||n("metrics").some(b=>b.name===M.name&&b.qualifiedEntityName===M.qualifiedEntityName))){d(null);return}}else if(g==="pivotBy"){d(null);return}else if(g!=="groupBy"&&g!=="metrics"&&g!=="sortBy"){d(null);return}}if(g==="source"&&y==="sortBy"){const M=[...a].find(F=>F.id===v);if(!M){d(null);return}const N=n("sortBy");if(s.fieldAlreadyExists(M,N)){d(null);return}const b=s.validateFieldForChartType(M,"sortBy",i.type);if(!b.isValid){s.ue.error("Invalid Field Type",{description:b.reason,position:"top-center",duration:3e3}),d(null);return}const A=s.getNewField(M,"sortBy",N);d(null),r("sortBy",[...N,A]);return}if(g==="source"&&y!=="source"&&y!=="sortBy"){const M=[...a].find(L=>L.id===v);if(!M){d(null);return}const N=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(N.length>0){const L=N[0].qualifiedEntityName;if(!L){d(null);return}if(L!==M.qualifiedEntityName&&M.qualifiedEntityName)if(u&&(x!=null&&x.joinabilityMap)){if(s.calculateFieldState(M,{joinabilityMap:x.joinabilityMap,selectedFields:N,baseEntityName:(T=o==null?void 0:o.baseEntity)==null?void 0:T.name}).state==="unreachable"){s.showJoinRequiredNotification(),d(null);return}}else{if(!o){s.showJoinRequiredNotification(),d(null);return}if(!s.areEntitiesJoined(L,M.qualifiedEntityName,o)){s.showJoinRequiredNotification(),d(null);return}}}const b=n(y);if(s.fieldAlreadyExists(M,b)){d(null);return}const A=s.validateFieldForChartType(M,y,i.type);if(!A.isValid){s.ue.error("Invalid Field Type",{description:A.reason,position:"top-center",duration:3e3}),d(null);return}const F=s.getNewField(M,y,b),E=[...b,F];d(null),r(y,E),y==="metrics"&&t&&s.cleanupKpiMetricComparisonMode(i.type,i.config,c,t,E);return}if(g&&y&&g!=="source"&&y!=="source"&&g!==y){const M=n(g),N=n(y),b=M.find(S=>S.id===v);if(!b){d(null);return}const A=s.validateFieldForChartType(b,y,i.type);if(!A.isValid){s.ue.error("Invalid Field Type",{description:A.reason,position:"top-center",duration:3e3}),d(null);return}const F=s.getNewField(b,y,N);if(d(null),y==="sortBy"){s.fieldAlreadyExists(b,N)||r(y,[...N,F]);return}const E=M.filter(S=>S.id!==v),L=[...N,F];r(g,E),r(y,L),y==="metrics"&&t&&s.cleanupKpiMetricComparisonMode(i.type,i.config,c,t,L);return}if(g&&y&&g===y&&g!=="source"){const M=n(g),N=M.findIndex(A=>A.id===v),b=M.findIndex(A=>A.id===w);if(N!==b){const A=s.arrayMove(M,N,b);r(g,A)}}d(null)},[t,a,n,r,p,o,u,x,i.type,c,i.config]),f=l?h.find(I=>I.id===l):null;return{activeId:l,activeField:f,handleDragStart:k,handleDragEnd:m}}function ba({activeView:t,onViewChange:a,splitViewEnabled:n}){const r=s.useEditorStore(o=>o.card),{config:l}=D.useContext(s.SemaphorContext).tokenProps,d=(l==null?void 0:l.showInfoTab)!==!1,{errorMessage:i}=s.useDashboardCardQuery(r),c=()=>n?!1:!["table","pivotTable","aggregateTable"].includes(r.type);return e.jsx(s.Tabs,{value:t,onValueChange:o=>a(o),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-1 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),c()&&e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),r.type!=="kpi"&&d&&e.jsx(s.TabsTrigger,{value:"info",className:s.cn("rounded-md transition data-[state=active]:bg-muted",i&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:i?"Error":"Info"})]})})}const va=[{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 ya(){var o,u;const t=s.useEditorStore(x=>x.card),{updateRowLimit:a}=s.useEditorActions(),[n,r]=D.useState(!1),[l,d]=D.useState(""),i=x=>{if(x==="custom"){r(!0);return}r(!1),a(t.id,parseInt(x))},c=x=>{const h=x.target.value;d(h),h&&!isNaN(parseInt(h))&&a(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(s.Input$1,{type:"number",value:l,onChange:c,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(o=t.config)==null?void 0:o.rowLimit)==null?void 0:u.toString())||"100",onValueChange:i,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(s.SelectValue,{placeholder:"Select limit"})}),e.jsx(s.SelectContent,{children:va.map(x=>e.jsx(s.SelectItem,{value:x.value,children:x.label},x.value))})]})})}function Na({card:t,queryData:a,isLoading:n,isFetching:r,pagination:l,onPaginationChange:d,onSortChange:i,sortState:c,splitViewEnabled:o}){const u=D.useMemo(()=>(a==null?void 0:a.records)||[],[a==null?void 0:a.records]);return!o||["table","pivotTable","aggregateTable"].includes(t.type)?e.jsx(Ge,{}):e.jsxs(s.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(s.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:e.jsx(Ge,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{defaultSize:40,minSize:20,role:"results-section",className:"flex flex-col",children:e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:(a==null?void 0:a.records)&&e.jsx(s.TableVisual,{card:t,data:u,paginationMetadata:l,onPaginationChange:d,isLoading:n||r,onSortChange:i,sortState:c})})})]})}const Ca="semaphor-split-view-enabled";function Sa(){return ks(Ca,!0)}function wa({activeView:t,onViewChange:a,showDebug:n,onDebugToggle:r,onFiltersClick:l,activeCard:d,columns:i,columnsLoading:c,columnsError:o}){var se,_,te;const u=s.useEditorStore(Y=>Y.card),x=s.useDashboardStore(Y=>Y.filterValues),h=s.useDashboardStore(Y=>Y.selectedSheetId),p=s.useDashboardStore(Y=>Y.inlineFilterValuesMap[(d==null?void 0:d.id)||""]),{updateCardConfig:k,setCard:m,updateCardInFrame:f,setShowAIDialog:j}=s.useEditorActions(),C=s.useEditorStore(Y=>Y.showAIDialog),I=s.useDashboardStore(Y=>Y.isVisualEditing),[O,R]=D.useState(!1),[v,w]=D.useState(!1),[g,y]=D.useState(null),{config:T}=D.useContext(s.SemaphorContext).tokenProps,M=(T==null?void 0:T.showInfoTab)!==!1,[N,b]=Sa();s.useEditorStore(Y=>{var le;return((le=Y.card.customCardPreferences)==null?void 0:le.url)&&Y.card.type==="custom"});const{data:A,errorMessage:F,isLoading:E,isFetching:L,errorSql:S,pagination:P,refetch:$,comparisonMetadata:J}=s.useDashboardCardQuery(d),K=D.useMemo(()=>(A==null?void 0:A.records)||[],[A==null?void 0:A.records]),[G,H]=D.useState(!1);D.useEffect(()=>{L||H(!1)},[L]);const B=()=>{const Y=!N;Y&&t==="table"&&a("chart"),b(Y)},U=(Y,le)=>{const ce={...d,paginationConfig:{page:Y+1,pageSize:le}};m(ce),f(ce)};function V(){return e.jsxs("div",{className:"relative border-b border-border bg-background p-4",children:[e.jsx("button",{onClick:r,className:"absolute right-4 top-4 rounded-md p-1 hover:bg-muted","aria-label":"Close Debug Panel",children:e.jsx(s.X,{className:"h-4 w-4"})}),e.jsxs("div",{className:"space-y-4 pr-8",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(u.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Dashboard Filters"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(x||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(d.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",i.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:c?"Loading...":o?"Error loading columns":JSON.stringify(i.slice(0,5),null,2)})]})]})]})}const W=Y=>{if(!u.config)return;const le=s.sortStateToSortByColumns(Y,u.config.metricColumns,u.config.groupByColumns);k(u.id,{...u.config,sortByColumns:le})},X=D.useMemo(()=>{var Y;return s.sortByColumnsToSortState((Y=u.config)==null?void 0:Y.sortByColumns)},[(se=u.config)==null?void 0:se.sortByColumns]);return e.jsxs("div",{className:s.cn("relative flex w-0 grow flex-col",{"border-l":C&&I}),children:[n&&V(),e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t==="chart"&&C&&e.jsx(Ms,{variant:"outline"}),e.jsx(ba,{activeView:t,onViewChange:a,splitViewEnabled:N}),e.jsx(s.FilterInfo,{cardId:d.id,cardFilters:(_=d.config)==null?void 0:_.filters,cardFilterCount:s.getFilterCount(((te=d.config)==null?void 0:te.filters)||null),onFiltersClick:l,inlineFilters:d.inlineFilters,inlineFilterValues:p,sheetId:h||""}),J&&e.jsx(s.ComparisonMetadataBadge,{metadata:J,variant:"compact"}),e.jsx("div",{className:"ml-2",children:e.jsx(ya,{})}),C&&e.jsx(qe.EditorClearButton,{})]}),e.jsxs("div",{className:s.cn("flex grow items-center justify-end gap-2"),children:[e.jsx(s.IconButton,{tooltip:"Refresh",disabled:E||L,onClick:()=>{H(!0),$()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":G})})}),t==="chart"&&e.jsx(s.IconButton,{tooltip:N?"Hide Results Table":"Show Results Table",onClick:B,children:N?e.jsx(ut,{className:"size-4"}):e.jsx(wt,{className:"size-4"})}),t==="chart"&&e.jsx(e.Fragment,{children:e.jsx(Ls,{})}),!C&&e.jsx(s.IconButton,{onClick:()=>j(!C),tooltip:"AI",className:"h-8","aria-label":"AI",children:e.jsx(s.Sparkles,{className:"size-4"})}),r&&s.isDevEnv]})]}),e.jsxs("div",{className:"mt-3 flex min-h-0 grow flex-col",children:[t==="chart"&&e.jsx("div",{className:s.cn("flex grow flex-col pb-6",{"pb-0":N&&!["table","pivotTable","aggregateTable"].includes(d.type)}),children:e.jsx(Na,{card:d,queryData:A,isLoading:E,isFetching:L,pagination:P,onPaginationChange:U,onSortChange:W,sortState:X,splitViewEnabled:N})}),t==="table"&&(A==null?void 0:A.records)&&e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:e.jsx(s.TableVisual,{card:d,data:K,paginationMetadata:P,onPaginationChange:U,isLoading:E||L,onSortChange:W,sortState:X})}),t==="info"&&M&&e.jsx("div",{className:"flex min-h-0 flex-1 flex-col pb-6",children:e.jsx("div",{className:"flex min-h-0 flex-1 flex-col rounded-md bg-background px-6",children:F?e.jsx(He,{error:F,errorSql:S,onSendFeedback:()=>{const Y=s.prepareFeedbackData(s.FeedbackCategory.QUERY_GENERATION,{cardConfig:u.config,dataSource:d.dataSource,dashboardFilters:x,errorMessage:F,errorSql:S,generatedSql:A==null?void 0:A.sql});y(Y),w(!0)},onOpenInEditor:()=>{j(!0),setTimeout(()=>{const Y=s.useEditorStore.getState().actions;Y.setIsDevMode(!0),Y.setCardSql(S||""),setTimeout(()=>{Y.setRunSql(!0)},100)},100)}}):e.jsx(Es,{sql:A==null?void 0:A.sql,error:F,errorSql:S})})})]}),g&&e.jsx(s.FeedbackDialog,{open:v,onOpenChange:w,feedbackData:g})]})]})}function ka({activeField:t}){const[a,n]=D.useState(!0);return D.useEffect(()=>{t&&n(!0)},[t]),t?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${a?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(s.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(Qe,{dataType:t.dataType}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-sm dark:text-muted-foreground",children:t.label||t.name})]}):null}const Ta=()=>{const t=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||t.apply(console,r)};const a=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},n=r=>{var l;if((l=r.reason)!=null&&l.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=t,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function Ea({column:t,isSelected:a,onSelect:n,availableFields:r,width:l,onWidthChange:d}){var $,J,K;const i=s.useEditorStore(G=>G.card),{updateCardConfig:c,removeGroupByColumn:o,removeMetricColumn:u,updateFilters:x}=s.useEditorActions(),[h,p]=D.useState(!1),[k,m]=D.useState(!1),f=D.useRef(null),j=D.useCallback(G=>{G.preventDefault(),G.stopPropagation(),m(!0),f.current={startX:G.clientX,startWidth:l||150};const H=U=>{if(!f.current)return;const V=U.clientX-f.current.startX,W=Math.max(80,f.current.startWidth+V);d==null||d(t.id,W)},B=()=>{m(!1),f.current=null,document.removeEventListener("mousemove",H),document.removeEventListener("mouseup",B)};document.addEventListener("mousemove",H),document.addEventListener("mouseup",B)},[l,t.id,d]),C=($=i==null?void 0:i.config)==null?void 0:$.filters,I=(J=C==null?void 0:C.conditions)==null?void 0:J.some(G=>G.field.name===t.name&&G.field.qualifiedEntityName===t.qualifiedEntityName),O=G=>{G?x(i.id,G):c(i.id,{filters:void 0})},{attributes:R,listeners:v,setNodeRef:w,transform:g,transition:y,isDragging:T}=s.useSortable({id:t.id}),M={transform:s.CSS.Transform.toString(g),transition:y},N=s.getDataType(t.dataType),b=Aa(N),A=()=>{var B;const G=((B=i==null?void 0:i.config)==null?void 0:B.sortByColumns)||[],H=G.findIndex(U=>U.name===t.name);if(H!==-1){const U=[...G];U[H]={...U[H],direction:"asc"},c(i.id,{sortByColumns:U})}else c(i.id,{sortByColumns:[...G,{...t,id:`sort-${t.id}`,role:"sortby",direction:"asc"}]})},F=()=>{var B;const G=((B=i==null?void 0:i.config)==null?void 0:B.sortByColumns)||[],H=G.findIndex(U=>U.name===t.name);if(H!==-1){const U=[...G];U[H]={...U[H],direction:"desc"},c(i.id,{sortByColumns:U})}else c(i.id,{sortByColumns:[...G,{...t,id:`sort-${t.id}`,role:"sortby",direction:"desc"}]})},E=()=>{var B;const G=((B=i==null?void 0:i.config)==null?void 0:B.groupByColumns)||[];if(!G.some(U=>U.name===t.name)){const U={...t,id:`groupby-${t.id}-${Date.now()}`,role:"groupby"};c(i.id,{groupByColumns:[...G,U]})}},L=G=>{var U;const H=((U=i==null?void 0:i.config)==null?void 0:U.metricColumns)||[];if(!H.some(V=>V.name===t.name&&V.aggregate===G)){const V={...t,id:`metric-${t.id}-${G}-${Date.now()}`,label:`${G} of ${t.label||t.name}`,role:"metric",aggregate:G};c(i.id,{metricColumns:[...H,V]})}},S=()=>{t.role==="groupby"?o(i.id,t.id):t.role==="metric"&&u(i.id,t.id)},P={...M,width:l?`${l}px`:void 0,minWidth:l?`${l}px`:"120px"};return e.jsxs("th",{ref:w,style:P,className:s.cn("group relative border-r border-border bg-background px-1 py-0",T&&"opacity-50",a&&"bg-primary/10",k&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...R,...v,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(s.GripVertical,{className:"h-3 w-3"})}),e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsxs("button",{onClick:n,className:s.cn("flex flex-1 items-center justify-between gap-1 rounded px-2 py-2 text-left text-sm font-medium transition-colors hover:bg-muted/50",a&&"bg-primary/10"),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(b,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:t.label||t.name}),t.role==="metric"&&t.aggregate&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",t.aggregate,")"]}),I&&e.jsx(s.Filter,{className:"h-3 w-3 text-primary"})]}),e.jsx(s.ChevronDown,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsxs(s.DropdownMenuContent,{align:"start",className:"w-48",children:[e.jsxs(s.DropdownMenuItem,{onClick:()=>p(!0),children:[e.jsx(s.Filter,{className:s.cn("mr-2 h-4 w-4",I&&"text-primary")}),I?"Edit Filter":"Filter"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:A,children:[e.jsx(lt,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(s.DropdownMenuItem,{onClick:F,children:[e.jsx(rt,{className:"mr-2 h-4 w-4"}),"Sort Z → A"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuSub,{children:[e.jsxs(s.DropdownMenuSubTrigger,{children:[e.jsx(s.Calculator,{className:"mr-2 h-4 w-4"}),"Summarize"]}),e.jsxs(s.DropdownMenuSubContent,{children:[e.jsx(s.DropdownMenuItem,{onClick:()=>L("SUM"),children:"Sum"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("AVG"),children:"Average"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("COUNT"),children:"Count"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("DISTINCT"),children:"Count Distinct"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("MIN"),children:"Min"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("MAX"),children:"Max"})]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:E,children:[e.jsx(Ue,{className:"mr-2 h-4 w-4"}),"Group by this column"]}),e.jsxs(s.DropdownMenuItem,{disabled:!0,children:[e.jsx(Ns,{className:"mr-2 h-4 w-4"}),"Pivot by this column"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{disabled:!0,children:[e.jsx(s.EyeOff,{className:"mr-2 h-4 w-4"}),"Hide column"]}),e.jsxs(s.DropdownMenuItem,{onClick:S,className:"text-destructive focus:text-destructive",children:[e.jsx(s.Trash2,{className:"mr-2 h-4 w-4"}),"Remove column"]})]})]})]}),e.jsx("div",{onMouseDown:j,className:s.cn("absolute right-0 top-0 h-full w-1 cursor-col-resize bg-transparent hover:bg-primary/50",k&&"bg-primary")}),e.jsx(_s,{open:h,onOpenChange:p,availableFields:r.length>0?r:[t],existingFilters:C,editingCondition:I?(K=C==null?void 0:C.conditions)==null?void 0:K.find(G=>G.field.name===t.name&&G.field.qualifiedEntityName===t.qualifiedEntityName):void 0,onSave:O})]})}function Aa(t){switch(t){case"number":return s.Hash;case"date":return s.Calendar;case"string":default:return s.Type}}function Ia({selectedColumn:t,onColumnSelect:a,isLoading:n=!1,sourceFields:r=[]}){var y,T,M,N;const l=s.useEditorStore(b=>b.card),{updateCardConfig:d}=s.useEditorActions(),[i,c]=D.useState(null),[o,u]=D.useState({}),[x,h]=D.useState(!1),p=D.useMemo(()=>{var F,E;const b=((F=l==null?void 0:l.config)==null?void 0:F.groupByColumns)||[],A=((E=l==null?void 0:l.config)==null?void 0:E.metricColumns)||[];return[...b,...A]},[(y=l==null?void 0:l.config)==null?void 0:y.groupByColumns,(T=l==null?void 0:l.config)==null?void 0:T.metricColumns]),k=D.useMemo(()=>{const b=new Set(p.map(A=>`${A.qualifiedEntityName}.${A.name}`));return r.filter(A=>!b.has(`${A.qualifiedEntityName}.${A.name}`))},[r,p]),{data:m,isLoading:f}=s.useDashboardCardQuery(l),j=(m==null?void 0:m.records)||[],C=D.useCallback((b,A)=>{u(F=>({...F,[b]:A}))},[]),I=D.useCallback(b=>{var L,S;const A=s.getDataType(b.dataType),F=((L=l==null?void 0:l.config)==null?void 0:L.groupByColumns)||[],E=((S=l==null?void 0:l.config)==null?void 0:S.metricColumns)||[];if(A==="number"){const P={...b,id:`metric-${b.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};d(l.id,{metricColumns:[...E,P]})}else{const P={...b,id:`groupby-${b.id}-${Date.now()}`,role:"groupby"};d(l.id,{groupByColumns:[...F,P]})}h(!1)},[(M=l==null?void 0:l.config)==null?void 0:M.groupByColumns,(N=l==null?void 0:l.config)==null?void 0:N.metricColumns,l.id,d]),O=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),R=b=>{c(b.active.id)},v=b=>{const{active:A,over:F}=b;if(c(null),!F||A.id===F.id)return;const E=p.findIndex(S=>S.id===A.id),L=p.findIndex(S=>S.id===F.id);if(E!==-1&&L!==-1){const S=s.arrayMove(p,E,L),P=S.filter(J=>J.role==="groupby"),$=S.filter(J=>J.role==="metric");d(l.id,{groupByColumns:P,metricColumns:$})}},w=i?p.find(b=>b.id===i):null,g=b=>{let A="";for(;b>=0;)A=String.fromCharCode(b%26+65)+A,b=Math.floor(b/26)-1;return A};return n?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):p.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(s.DndContext,{sensors:O,collisionDetection:s.closestCenter,onDragStart:R,onDragEnd:v,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(s.SortableContext,{items:p.map(b=>b.id),strategy:s.horizontalListSortingStrategy,children:p.map((b,A)=>e.jsx("th",{style:{width:o[b.id]?`${o[b.id]}px`:void 0,minWidth:o[b.id]?`${o[b.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:g(A)},`letter-${b.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(s.SortableContext,{items:p.map(b=>b.id),strategy:s.horizontalListSortingStrategy,children:p.map(b=>e.jsx(Ea,{column:b,isSelected:(t==null?void 0:t.id)===b.id,onSelect:()=>a(b),availableFields:r,width:o[b.id],onWidthChange:C},b.id))}),e.jsx("th",{className:"w-10 border-r border-border bg-background px-1 py-2",children:e.jsxs(s.Popover,{open:x,onOpenChange:h,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Add column",children:e.jsx(s.Plus,{className:"h-4 w-4"})})}),e.jsx(s.PopoverContent,{className:"w-[280px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search columns..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No columns available."}),e.jsx(s.CommandGroup,{heading:"Available Columns",children:k.map(b=>{const A=s.getDataType(b.dataType),F=A==="number"?s.Hash:A==="date"?s.Calendar:s.Type;return e.jsxs(s.CommandItem,{value:b.label||b.name,onSelect:()=>I(b),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:b.label||b.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:b.entityName})]})]},b.id)})})]})]})})]})})]})]}),e.jsx("tbody",{children:f?e.jsx("tr",{children:e.jsx("td",{colSpan:p.length+2,className:"h-32 text-center",children:e.jsx(s.LoaderCircle,{className:"mx-auto h-6 w-6 animate-spin text-muted-foreground"})})}):j.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:p.length+2,className:"h-32 text-center text-muted-foreground",children:"No data available"})}):j.slice(0,100).map((b,A)=>e.jsxs("tr",{className:s.cn("border-b border-border transition-colors hover:bg-muted/50",A%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:A+1}),p.map(F=>{const E=b[F.name]??b[F.label??""];return e.jsx("td",{style:{width:o[F.id]?`${o[F.id]}px`:void 0,minWidth:o[F.id]?`${o[F.id]}px`:"120px"},className:s.cn("border-r border-border px-3 py-2 text-sm",(t==null?void 0:t.id)===F.id&&"bg-primary/5"),children:e.jsx("span",{className:"block truncate",children:Da(E,F)})},`${A}-${F.id}`)}),e.jsx("td",{className:"w-10 border-r border-border"})]},A))})]}),e.jsx(s.DragOverlay,{children:w&&e.jsx("div",{className:"rounded border border-primary bg-background px-3 py-2 text-sm font-medium shadow-lg",children:w.label||w.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:[p.length," columns"]})]})]})}function Da(t,a){if(t==null)return"—";if(typeof t=="number")return a.role==="metric"?new Intl.NumberFormat("en-US",{minimumFractionDigits:0,maximumFractionDigits:2}).format(t):t.toString();if(t instanceof Date||typeof t=="string"&&!isNaN(Date.parse(t))){const n=new Date(t);if(!isNaN(n.getTime()))return n.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}return String(t)}function Ma({entityGroups:t,isLoading:a=!1}){var O,R;const n=s.useEditorStore(v=>v.card),{updateCardConfig:r,removeGroupByColumn:l,removeMetricColumn:d}=s.useEditorActions(),[i,c]=D.useState(!0),[o,u]=D.useState(""),[x,h]=D.useState(new Set),p=((O=n==null?void 0:n.config)==null?void 0:O.groupByColumns)||[],k=((R=n==null?void 0:n.config)==null?void 0:R.metricColumns)||[],m=v=>{const w=new Set(x);w.has(v)?w.delete(v):w.add(v),h(w)},f=v=>p.some(w=>w.name===v.name&&w.qualifiedEntityName===v.qualifiedEntityName)||k.some(w=>w.name===v.name&&w.qualifiedEntityName===v.qualifiedEntityName),j=(v,w)=>{if(w)if(s.getDataType(v.dataType)==="number"){const y={...v,id:`metric-${v.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};r(n.id,{metricColumns:[...k,y]})}else{const y={...v,id:`groupby-${v.id}-${Date.now()}`,role:"groupby"};r(n.id,{groupByColumns:[...p,y]})}else{const g=p.findIndex(T=>T.name===v.name&&T.qualifiedEntityName===v.qualifiedEntityName),y=k.findIndex(T=>T.name===v.name&&T.qualifiedEntityName===v.qualifiedEntityName);g!==-1&&l(n.id,p[g].id),y!==-1&&d(n.id,k[y].id)}},C=v=>{if(!o)return v;const w=o.toLowerCase();return v.filter(g=>g.name.toLowerCase().includes(w)||g.label&&g.label.toLowerCase().includes(w))},I=v=>{switch(s.getDataType(v)){case"number":return s.Hash;case"date":return s.Calendar;default:return s.Type}};return i?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(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:()=>c(!1),title:"Close panel",children:e.jsx(Nt,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"border-b border-border p-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search columns...",value:o,onChange:v=>u(v.target.value),className:"h-8 pl-8 text-sm"})]})}),(p.length>0||k.length>0)&&e.jsxs("div",{className:"border-b border-border",children:[p.length>0&&e.jsxs(s.Collapsible,{defaultOpen:!0,children:[e.jsxs(s.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(s.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(Ue,{className:"h-3.5 w-3.5 text-blue-500"}),e.jsx("span",{children:"Groupings"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:p.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:p.map(v=>{const w=I(v.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(s.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(w,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:v.label||v.name}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>l(n.id,v.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},v.id)})})})]}),k.length>0&&e.jsxs(s.Collapsible,{defaultOpen:!0,children:[e.jsxs(s.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(s.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(s.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:k.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:k.map(v=>{const w=I(v.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(s.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(w,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:v.label||v.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:v.aggregate}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>d(n.id,v.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},v.id)})})})]})]}),e.jsx(s.ScrollArea,{className:"flex-1",children:e.jsx("div",{className:"p-2",children:a?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent"})}):t.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No columns available"}):t.map(v=>{const w=C(v.columns);if(w.length===0)return null;const g=x.has(v.entityId)||o.length>0;return e.jsxs(s.Collapsible,{open:g,onOpenChange:()=>m(v.entityId),children:[e.jsxs(s.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(s.ChevronRight,{className:s.cn("h-3.5 w-3.5 transition-transform duration-200",g&&"rotate-90")}),e.jsx(s.Table2,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate text-left",children:v.label||v.entityName}),e.jsx("span",{className:"text-xs text-muted-foreground",children:w.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:w.map(y=>{const T=I(y.dataType),M=f(y);return e.jsxs("label",{className:s.cn("flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-sm transition-colors hover:bg-muted/50",M&&"bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:M,onCheckedChange:N=>j(y,N),className:"h-3.5 w-3.5"}),e.jsx(T,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:y.label||y.name})]},y.id)})})})]},v.entityId)})})})]}):e.jsx("div",{className:"flex h-full items-start border-l border-border bg-muted/30 p-2",children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>c(!0),title:"Open panel",children:e.jsx(Ct,{className:"h-4 w-4"})})})}const La=[{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 Fa({value:t,onChange:a,onSubmit:n,onCancel:r,selectedColumn:l,availableColumns:d}){const[i,c]=D.useState(!1),[o,u]=D.useState("column"),x=D.useRef(null);D.useEffect(()=>{const m=f=>{f.key==="Escape"&&t?r():f.key==="Enter"&&t&&!i&&n(t)};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[t,r,n,i]);const h=m=>{const f=`[${m.label||m.name}]`,j=x.current;if(j){const C=j.selectionStart||0,I=j.selectionEnd||0,O=t.slice(0,C)+f+t.slice(I);a(O),setTimeout(()=>{j.setSelectionRange(C+f.length,C+f.length),j.focus()},0)}else a(t+f);c(!1)},p=m=>{const f=x.current;if(f){const j=f.selectionStart||0,C=f.selectionEnd||0,I=t.slice(0,j)+m.syntax+t.slice(C);a(I),setTimeout(()=>{f.setSelectionRange(j+m.name.length+1,j+m.syntax.length-1),f.focus()},0)}else a(t+m.syntax);c(!1)},k=m=>{switch(s.getDataType(m)){case"number":return s.Hash;case"date":return s.Calendar;default:return s.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:l?e.jsx("span",{className:"truncate",children:l.label||l.name}):e.jsx("span",{children:"—"})}),e.jsxs(s.Popover,{open:i&&o==="function",onOpenChange:m=>{c(m),m&&u("function")},children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Insert function",children:e.jsx(St,{className:"h-4 w-4"})})}),e.jsx(s.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search functions..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No functions found."}),e.jsx(s.CommandGroup,{heading:"Functions",children:La.map(m=>e.jsx(s.CommandItem,{value:m.name,onSelect:()=>p(m),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:m.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.description})]}),e.jsx("span",{className:"font-mono text-xs text-muted-foreground/75",children:m.syntax})]})},m.name))})]})]})})]}),e.jsxs(s.Popover,{open:i&&o==="column",onOpenChange:m=>{c(m),m&&u("column")},children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.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(s.ChevronDown,{className:"h-3 w-3"})]})}),e.jsx(s.PopoverContent,{className:"w-[250px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search columns..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No columns found."}),e.jsx(s.CommandGroup,{heading:"Available Columns",children:d.map(m=>{const f=k(m.dataType);return e.jsxs(s.CommandItem,{value:m.label||m.name,onSelect:()=>h(m),children:[e.jsx(f,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:m.label||m.name})]},m.id)})})]})]})})]}),e.jsx("div",{className:"relative flex-1",children:e.jsx(s.Input$1,{ref:x,value:t,onChange:m=>a(m.target.value),placeholder:"Enter a formula or select a column...",className:"h-7 border-border bg-background font-mono text-sm"})}),t&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.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(s.X,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-green-600 hover:bg-green-600/10 hover:text-green-600",onClick:()=>n(t),title:"Apply (Enter)",children:e.jsx(s.Check,{className:"h-4 w-4"})})]})]})}function Oa({className:t}){var p,k,m,f;const a=s.useEditorStore(j=>j.card),[n,r]=D.useState(null),[l,d]=D.useState(""),{columns:i=[],columnGroups:c=[],isLoading:o}=s.useColumns();(p=a==null?void 0:a.config)!=null&&p.groupByColumns,(k=a==null?void 0:a.config)!=null&&k.metricColumns,(m=a==null?void 0:a.config)!=null&&m.groupByColumns,(f=a==null?void 0:a.config)!=null&&f.pivotByColumns;const u=j=>{r(j),d(j?`[${j.label||j.name}]`:"")},x=j=>{console.log("Formula submitted:",j),d(""),r(null)},h=()=>{d(""),r(null)};return e.jsxs("div",{className:s.cn("flex h-full w-full flex-col",t),children:[e.jsx(Fa,{value:l,onChange:d,onSubmit:x,onCancel:h,selectedColumn:n,availableColumns:i}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(Ia,{selectedColumn:n,onColumnSelect:u,isLoading:o,sourceFields:i})}),e.jsx(Ma,{entityGroups:c,isLoading:o})]})]})}function Ra(){var $,J;const[t,a]=D.useState("chart"),[n,r]=D.useState(!1),[l,d]=D.useState(!1),[i,c]=D.useState(!0),o=s.useEditorStore(K=>K.showAIDialog),u=s.useDashboardStore(K=>K.isVisualEditing),{setCardType:x}=s.useEditorActions(),h=s.useEditorStore(K=>K.card.type);D.useEffect(()=>Ta(),[]);const p=K=>{x(K)},k=s.useEditorStore(K=>K.frame),m=s.useEditorStore(K=>K.card);s.useEditorStore(K=>K.activeTabCardId),s.useEditorStore(K=>K.actions.getAvailableFields);const{addCard:f,removeCard:j,updateCard:C,setActiveCard:I,updateFilters:O}=s.useEditorActions(),{columns:R=[],isLoading:v,error:w}=s.useColumns(),g=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),y=m,{getFieldsForContainer:T,setFieldsForContainer:M}=s.useFieldManagement(y),{activeField:N,handleDragStart:b,handleDragEnd:A}=ja({activeCardId:k.activeCardId,sourceFields:R,getFieldsForContainer:T,setFieldsForContainer:M}),F=(K,G)=>{G&&O(K,G)},E=K=>{var G;C(K,{config:{...(G=k.cards.find(H=>H.id===K))==null?void 0:G.config,filters:void 0}})},L=R,S=K=>{if(!K)return 0;let G=K.conditions.length;return K.groups.forEach(H=>{G+=S(H)}),G},P=S((($=y==null?void 0:y.config)==null?void 0:$.filters)||null);return e.jsxs(s.DndContext,{sensors:g,collisionDetection:s.closestCenter,onDragStart:b,onDragEnd:A,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Ts,{isVisible:i,onToggleVisibility:()=>c(!i)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:h==="tableBuilder"?e.jsx(Oa,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!o&&e.jsx(ea,{selectedChart:h,onChartChange:p,groupByFields:T("groupBy"),pivotByFields:T("pivotBy"),metricsFields:T("metrics"),sortByFields:T("sortBy"),activeField:N}),e.jsx(wa,{selectedChart:h,activeView:t,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onFiltersClick:()=>d(!0),filterCount:P,activeCard:y,dataSourceState:m.dataSource||s.EMPTY_DATA_SOURCE,columns:R,columnsLoading:v,columnsError:w,getFieldsForContainer:T,cards:k.cards,activeCardId:k.activeCardId,addCard:f,setActiveCard:I})]})}),!i&&u&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.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(s.Database,{className:"h-4 w-4"})})})]}),y&&e.jsx(ga,{cardId:y.id,filters:((J=y.config)==null?void 0:J.filters)||null,onFiltersChange:F,onClearFilters:E,availableFields:L,isOpen:l,onOpenChange:d}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(ka,{activeField:N||null})})]})}function Ba({authToken:t,onSave:a,onClose:n}){const r=D.useRef(null),l=s.useEditorStore(w=>w.showAIDialog),d=s.useEditorStore(w=>w.isDevMode),i=s.useAssistantLayoutStore(w=>w.setFullscreen),c=s.useAssistantLayoutStore(w=>w.setPanelOpen),o=s.useAssistantLayoutStore(w=>w.setContainer),u=s.useAssistantPanel("editor"),x=s.useFullscreenAssistant(),h=s.useAssistantContainer("editor"),p=x==="editor",k=D.useCallback(w=>{o("editor",w)},[o]),{setAuthToken:m}=s.useDashboardActions(),{setShowAIDialog:f,setOnSave:j,setOnClose:C}=s.useEditorActions(),{setActiveAssistantType:I}=s.useAIActions();D.useEffect(()=>{a&&j(a),n&&C(n)},[a,j,n,C]),D.useEffect(()=>{t&&t.accessToken&&m(t)},[t,m]),D.useEffect(()=>{var w,g;l?((w=r.current)==null||w.resize(40),c("editor",!0),I("editor")):((g=r.current)==null||g.resize(0),c("editor",!1),x==="editor"&&i(null),I(null))},[l,c,I,i,x]);function O(w){w<1?(f(!1),c("editor",!1),x==="editor"&&i(null),I(null)):(l||(f(!0),I("editor")),u.isOpen||c("editor",!0))}function R(){return e.jsxs(e.Fragment,{children:[e.jsx(Ts,{isVisible:!0,onToggleVisibility:()=>{}}),e.jsxs("div",{className:"relative flex grow border-l",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:s.cn("grow transition-opacity",p&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Rn,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:O,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(ps,{isFullscreen:p,onFullscreenChange:w=>i(w?"editor":null),fullscreenContainer:h})})})]}),e.jsx("div",{ref:k,className:s.cn("absolute inset-0",!p&&"pointer-events-none")})]})]})}function v(){return e.jsxs("div",{className:"relative flex h-full grow",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:s.cn("flex grow transition-opacity",p&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Ra,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:O,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(ps,{isFullscreen:p,onFullscreenChange:w=>i(w?"editor":null),fullscreenContainer:h})})})]}),e.jsx("div",{ref:k,className:s.cn("absolute inset-0",!p&&"pointer-events-none")})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:d?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:R()}):v()})}function Va(){s.useDashboardStore(i=>i.selectedCardId);const t=s.useDashboardStore(i=>i.selectedSheetId),{setIsVisualEditing:a}=s.useDashboardStore(i=>i.actions),n=s.useDashboardStore(i=>i.isVisualEditing),r=s.useDashboardStore(i=>i.actions.updateFrame);function l(i){t&&(r(t,i),a(!1))}function d(){a(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!n}),children:e.jsx(Ba,{onSave:l,onClose:d})})}exports.default=Va;