react-semaphor 0.1.217 → 0.1.219

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 (38) hide show
  1. package/dist/chunks/{dashboard-controls-p-PLTBKo.js → dashboard-controls-DfbaI6XZ.js} +1 -1
  2. package/dist/chunks/{dashboard-controls-DLjwyISu.js → dashboard-controls-fhZIf1Z0.js} +5 -5
  3. package/dist/chunks/{dashboard-json-DC8Hr2u7.js → dashboard-json-Bt-kpD9y.js} +1 -1
  4. package/dist/chunks/{dashboard-json-Dy8OL7sx.js → dashboard-json-DooCuhHo.js} +1 -1
  5. package/dist/chunks/{dashboard-summary-settings-dialog-CQISZPzc.js → dashboard-summary-settings-dialog-B3eWK66q.js} +1 -1
  6. package/dist/chunks/{dashboard-summary-settings-dialog-Dlzv-d9Z.js → dashboard-summary-settings-dialog-CWmq1rnL.js} +1 -1
  7. package/dist/chunks/edit-dashboard-visual-Blkn0D44.js +164 -0
  8. package/dist/chunks/{edit-dashboard-visual-DkZya-OV.js → edit-dashboard-visual-C7sag6Jo.js} +6031 -5828
  9. package/dist/chunks/{editor-action-buttons-4-UuoSZc.js → editor-action-buttons-yJEX8W7R.js} +1 -1
  10. package/dist/chunks/{editor-action-buttons-BQtxnqBZ.js → editor-action-buttons-z7gf6nE6.js} +2 -2
  11. package/dist/chunks/{index-Cr-d0ray.js → index-BMkn4K4E.js} +15342 -15143
  12. package/dist/chunks/{index-CRJ97-41.js → index-C_RTjAMW.js} +223 -223
  13. package/dist/chunks/{notification-bell-_OADjyy7.js → notification-bell-DHK6s4Om.js} +3 -3
  14. package/dist/chunks/{notification-bell-CyZx_uZ1.js → notification-bell-DSShVmWj.js} +1 -1
  15. package/dist/chunks/{resource-management-panel-rmEMdbbS.js → resource-management-panel-LBCXiHZk.js} +3 -3
  16. package/dist/chunks/{resource-management-panel-Bq9zRYsk.js → resource-management-panel-QdAeim78.js} +1 -1
  17. package/dist/chunks/{use-role-aware-display-preferences-1U-ed07h.js → use-role-aware-display-preferences-CqF1BR5w.js} +1 -1
  18. package/dist/chunks/{use-role-aware-display-preferences-DOA8kcfK.js → use-role-aware-display-preferences-Db1iLmPN.js} +1 -1
  19. package/dist/chunks/{use-visual-utils-DX-4Hwoe.js → use-visual-utils-AXuCdndV.js} +1 -1
  20. package/dist/chunks/{use-visual-utils-DxigSU7y.js → use-visual-utils-CKt4UblS.js} +1 -1
  21. package/dist/dashboard/index.cjs +1 -1
  22. package/dist/dashboard/index.js +3 -3
  23. package/dist/index.cjs +1 -1
  24. package/dist/index.js +37 -37
  25. package/dist/style.css +1 -1
  26. package/dist/surfboard/index.cjs +1 -1
  27. package/dist/surfboard/index.js +3 -3
  28. package/dist/types/dashboard.d.ts +3 -3
  29. package/dist/types/index.cjs +1 -1
  30. package/dist/types/index.js +10 -4
  31. package/dist/types/main.d.ts +34 -7
  32. package/dist/types/shared.d.ts +3 -3
  33. package/dist/types/surfboard.d.ts +3 -3
  34. package/dist/types/types.d.ts +34 -7
  35. package/package.json +1 -1
  36. package/dist/chunks/common-types-CfJLrTJd.js +0 -1
  37. package/dist/chunks/common-types-DhqlRVrq.js +0 -8
  38. package/dist/chunks/edit-dashboard-visual-DAiqFH7i.js +0 -164
@@ -0,0 +1,164 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),s=require("./index-C_RTjAMW.js"),k=require("react"),fe=require("./editor-action-buttons-yJEX8W7R.js"),Gt=require("react-dom");function Kt(t){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const a in t)if(a!=="default"){const r=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:()=>t[a]})}}return n.default=t,Object.freeze(n)}const os=Kt(k);/**
2
+ * @license lucide-react v0.453.0 - ISC
3
+ *
4
+ * This source code is licensed under the ISC license.
5
+ * See the LICENSE file in the root directory of this source tree.
6
+ */const Ut=s.createLucideIcon("ArrowDownAZ",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M20 8h-5",key:"1vsyxs"}],["path",{d:"M15 10V6.5a2.5 2.5 0 0 1 5 0V10",key:"ag13bf"}],["path",{d:"M15 14h5l-5 6h5",key:"ur5jdg"}]]);/**
7
+ * @license lucide-react v0.453.0 - ISC
8
+ *
9
+ * This source code is licensed under the ISC license.
10
+ * See the LICENSE file in the root directory of this source tree.
11
+ */const _t=s.createLucideIcon("ArrowUpAZ",[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M20 8h-5",key:"1vsyxs"}],["path",{d:"M15 10V6.5a2.5 2.5 0 0 1 5 0V10",key:"ag13bf"}],["path",{d:"M15 14h5l-5 6h5",key:"ur5jdg"}]]);/**
12
+ * @license lucide-react v0.453.0 - ISC
13
+ *
14
+ * This source code is licensed under the ISC license.
15
+ * See the LICENSE file in the root directory of this source tree.
16
+ */const Zs=s.createLucideIcon("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]);/**
17
+ * @license lucide-react v0.453.0 - ISC
18
+ *
19
+ * This source code is licensed under the ISC license.
20
+ * See the LICENSE file in the root directory of this source tree.
21
+ */const et=s.createLucideIcon("Columns3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
22
+ * @license lucide-react v0.453.0 - ISC
23
+ *
24
+ * This source code is licensed under the ISC license.
25
+ * See the LICENSE file in the root directory of this source tree.
26
+ */const Ht=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"}]]);/**
27
+ * @license lucide-react v0.453.0 - ISC
28
+ *
29
+ * This source code is licensed under the ISC license.
30
+ * See the LICENSE file in the root directory of this source tree.
31
+ */const st=s.createLucideIcon("FileCode2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m5 12-3 3 3 3",key:"oke12k"}],["path",{d:"m9 18 3-3-3-3",key:"112psh"}]]);/**
32
+ * @license lucide-react v0.453.0 - ISC
33
+ *
34
+ * This source code is licensed under the ISC license.
35
+ * See the LICENSE file in the root directory of this source tree.
36
+ */const Jt=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"}]]);/**
37
+ * @license lucide-react v0.453.0 - ISC
38
+ *
39
+ * This source code is licensed under the ISC license.
40
+ * See the LICENSE file in the root directory of this source tree.
41
+ */const Yt=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"}]]);/**
42
+ * @license lucide-react v0.453.0 - ISC
43
+ *
44
+ * This source code is licensed under the ISC license.
45
+ * See the LICENSE file in the root directory of this source tree.
46
+ */const tt=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"}]]);/**
47
+ * @license lucide-react v0.453.0 - ISC
48
+ *
49
+ * This source code is licensed under the ISC license.
50
+ * See the LICENSE file in the root directory of this source tree.
51
+ */const Qt=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"}]]);/**
52
+ * @license lucide-react v0.453.0 - ISC
53
+ *
54
+ * This source code is licensed under the ISC license.
55
+ * See the LICENSE file in the root directory of this source tree.
56
+ */const Wt=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"}]]);/**
57
+ * @license lucide-react v0.453.0 - ISC
58
+ *
59
+ * This source code is licensed under the ISC license.
60
+ * See the LICENSE file in the root directory of this source tree.
61
+ */const Xt=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"}]]);/**
62
+ * @license lucide-react v0.453.0 - ISC
63
+ *
64
+ * This source code is licensed under the ISC license.
65
+ * See the LICENSE file in the root directory of this source tree.
66
+ */const Zt=s.createLucideIcon("ListFilter",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M7 12h10",key:"b7w52i"}],["path",{d:"M10 18h4",key:"1ulq68"}]]);/**
67
+ * @license lucide-react v0.453.0 - ISC
68
+ *
69
+ * This source code is licensed under the ISC license.
70
+ * See the LICENSE file in the root directory of this source tree.
71
+ */const ea=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"}]]);/**
72
+ * @license lucide-react v0.453.0 - ISC
73
+ *
74
+ * This source code is licensed under the ISC license.
75
+ * See the LICENSE file in the root directory of this source tree.
76
+ */const sa=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"}]]);/**
77
+ * @license lucide-react v0.453.0 - ISC
78
+ *
79
+ * This source code is licensed under the ISC license.
80
+ * See the LICENSE file in the root directory of this source tree.
81
+ */const Xe=s.createLucideIcon("MoveHorizontal",[["path",{d:"m18 8 4 4-4 4",key:"1ak13k"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}]]);/**
82
+ * @license lucide-react v0.453.0 - ISC
83
+ *
84
+ * This source code is licensed under the ISC license.
85
+ * See the LICENSE file in the root directory of this source tree.
86
+ */const Ze=s.createLucideIcon("MoveVertical",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m8 18 4 4 4-4",key:"bh5tu3"}],["path",{d:"m8 6 4-4 4 4",key:"ybng9g"}]]);/**
87
+ * @license lucide-react v0.453.0 - ISC
88
+ *
89
+ * This source code is licensed under the ISC license.
90
+ * See the LICENSE file in the root directory of this source tree.
91
+ */const ta=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"}]]);/**
92
+ * @license lucide-react v0.453.0 - ISC
93
+ *
94
+ * This source code is licensed under the ISC license.
95
+ * See the LICENSE file in the root directory of this source tree.
96
+ */const aa=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"}]]);/**
97
+ * @license lucide-react v0.453.0 - ISC
98
+ *
99
+ * This source code is licensed under the ISC license.
100
+ * See the LICENSE file in the root directory of this source tree.
101
+ */const na=s.createLucideIcon("PanelRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
102
+ * @license lucide-react v0.453.0 - ISC
103
+ *
104
+ * This source code is licensed under the ISC license.
105
+ * See the LICENSE file in the root directory of this source tree.
106
+ */const Fs=s.createLucideIcon("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/**
107
+ * @license lucide-react v0.453.0 - ISC
108
+ *
109
+ * This source code is licensed under the ISC license.
110
+ * See the LICENSE file in the root directory of this source tree.
111
+ */const cs=s.createLucideIcon("Rows3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M21 9H3",key:"1338ky"}],["path",{d:"M21 15H3",key:"9uk58r"}]]);/**
112
+ * @license lucide-react v0.453.0 - ISC
113
+ *
114
+ * This source code is licensed under the ISC license.
115
+ * See the LICENSE file in the root directory of this source tree.
116
+ */const ra=s.createLucideIcon("Shapes",[["path",{d:"M8.3 10a.7.7 0 0 1-.626-1.079L11.4 3a.7.7 0 0 1 1.198-.043L16.3 8.9a.7.7 0 0 1-.572 1.1Z",key:"1bo67w"}],["rect",{x:"3",y:"14",width:"7",height:"7",rx:"1",key:"1bkyp8"}],["circle",{cx:"17.5",cy:"17.5",r:"3.5",key:"w3z12y"}]]);/**
117
+ * @license lucide-react v0.453.0 - ISC
118
+ *
119
+ * This source code is licensed under the ISC license.
120
+ * See the LICENSE file in the root directory of this source tree.
121
+ */const at=s.createLucideIcon("SlidersHorizontal",[["line",{x1:"21",x2:"14",y1:"4",y2:"4",key:"obuewd"}],["line",{x1:"10",x2:"3",y1:"4",y2:"4",key:"1q6298"}],["line",{x1:"21",x2:"12",y1:"12",y2:"12",key:"1iu8h1"}],["line",{x1:"8",x2:"3",y1:"12",y2:"12",key:"ntss68"}],["line",{x1:"21",x2:"16",y1:"20",y2:"20",key:"14d8ph"}],["line",{x1:"12",x2:"3",y1:"20",y2:"20",key:"m0wm8r"}],["line",{x1:"14",x2:"14",y1:"2",y2:"6",key:"14e1ph"}],["line",{x1:"8",x2:"8",y1:"10",y2:"14",key:"1i6ji0"}],["line",{x1:"16",x2:"16",y1:"18",y2:"22",key:"1lctlv"}]]);/**
122
+ * @license lucide-react v0.453.0 - ISC
123
+ *
124
+ * This source code is licensed under the ISC license.
125
+ * See the LICENSE file in the root directory of this source tree.
126
+ */const la=s.createLucideIcon("Spline",[["circle",{cx:"19",cy:"5",r:"2",key:"mhkx31"}],["circle",{cx:"5",cy:"19",r:"2",key:"v8kfzx"}],["path",{d:"M5 17A12 12 0 0 1 17 5",key:"1okkup"}]]);/**
127
+ * @license lucide-react v0.453.0 - ISC
128
+ *
129
+ * This source code is licensed under the ISC license.
130
+ * See the LICENSE file in the root directory of this source tree.
131
+ */const oa=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"}]]);/**
132
+ * @license lucide-react v0.453.0 - ISC
133
+ *
134
+ * This source code is licensed under the ISC license.
135
+ * See the LICENSE file in the root directory of this source tree.
136
+ */const ia=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"}]]);/**
137
+ * @license lucide-react v0.453.0 - ISC
138
+ *
139
+ * This source code is licensed under the ISC license.
140
+ * See the LICENSE file in the root directory of this source tree.
141
+ */const ca=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"}]]);/**
142
+ * @license lucide-react v0.453.0 - ISC
143
+ *
144
+ * This source code is licensed under the ISC license.
145
+ * See the LICENSE file in the root directory of this source tree.
146
+ */const da=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 nt({storeValue:t,defaultValue:n="",onStoreUpdate:a,delay:r=300}){const[i,d]=k.useState(t??n),o=s.useDebounce(i,r),c=k.useRef(t),l=k.useRef(!1);k.useEffect(()=>{t!==c.current&&(d(t??n),c.current=t)},[t,n]),k.useEffect(()=>{l.current&&o!==c.current&&(a(o),c.current=o)},[o,a]);const m=k.useCallback(p=>{l.current=!0,d(p??n)},[n]);return{value:i,onChange:m}}function ua({initialJoinPlan:t,availableDataSources:n}){const[a,r]=k.useState(t),[i,d]=k.useState(new Set),o=()=>{const j=a.joins.length>0?Math.max(...a.joins.map(I=>I.sequence))+1:1,w={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:j,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...a,joins:[...a.joins,w]}),d(new Set([...i,w.id]))},c=j=>{r({...a,joins:a.joins.filter(w=>w.id!==j)}),d(new Set([...i].filter(w=>w!==j)))},l=(j,w)=>{var D,F,V,S,L;const I=a.joins.find(v=>v.id===j);if(!I)return;const f={...I,...w};if((D=f.source)!=null&&D.name&&((F=f.target)!=null&&F.name)&&f.source.name===f.target.name){s.ue.error("Self-joins are not yet supported",{description:`Joining ${f.source.name} to itself is not currently supported. Please select a different target table.`});return}const E=a.joins.filter(v=>{var O;return v.id!==j&&v.target.name===((O=f.target)==null?void 0:O.name)});if((V=f.target)!=null&&V.name&&E.length>0){s.ue.error("Duplicate join targets are not supported",{description:`The table ${f.target.name} is already used as a target in another join. Each table can only be joined once.`});return}const b=a.joins.map(v=>v.id===j?f:v);if((S=f.source)!=null&&S.name&&((L=f.target)!=null&&L.name)&&f.joinKeyGroups[0].keys.length===0){const v=n.find(U=>{var q;return U.name===((q=f.source)==null?void 0:q.name)}),O=n.find(U=>{var q;return U.name===((q=f.target)==null?void 0:q.name)}),R={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(v==null?void 0:v.name)||"",entityName:(v==null?void 0:v.name)||"",entityType:(v==null?void 0:v.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(O==null?void 0:O.name)||"",entityName:(O==null?void 0:O.name)||"",entityType:(O==null?void 0:O.type)||"table"},operator:"="},P=[...f.joinKeyGroups];P[0]={...P[0],keys:[R]},f.joinKeyGroups=P,b[b.findIndex(U=>U.id===j)]=f}r({...a,joins:b})};return{joinPlan:a,expandedJoins:i,setJoinPlan:r,addJoin:o,removeJoin:c,updateJoin:l,moveJoinUp:j=>{const w=a.joins.findIndex(I=>I.id===j);if(w>0){const I=[...a.joins],f={...I[w]},E={...I[w-1]};I[w]=E,I[w-1]=f,I.forEach((D,F)=>{D.sequence=F+1});const b={...a,joins:I};r(b)}},moveJoinDown:j=>{const w=a.joins.findIndex(I=>I.id===j);if(w<a.joins.length-1){const I=[...a.joins],f={...I[w]},E={...I[w+1]};I[w]=E,I[w+1]=f,I.forEach((D,F)=>{D.sequence=F+1});const b={...a,joins:I};r(b)}},toggleJoinExpansion:j=>{const w=new Set(i);w.has(j)?w.delete(j):w.add(j),d(w)},getAvailableSourceEntities:j=>{if(a.joins.length===0)return n;const w=a.joins.findIndex(f=>f.id===j);if(w===0)return n.filter(f=>f.name===a.baseEntity.name);const I=new Set;return a.baseEntity.name&&I.add(a.baseEntity.name),a.joins.slice(0,w).forEach(f=>{I.add(f.source.name),I.add(f.target.name)}),n.filter(f=>I.has(f.name))},getAvailableTargetEntities:j=>n.filter(w=>w.name!==j),addJoinKeyGroup:j=>{const w=a.joins.find(f=>f.id===j);if(!w)return;const I=[...w.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];l(j,{joinKeyGroups:I})},updateGroupOperator:(j,w,I)=>{const f=a.joins.find(b=>b.id===j);if(!f)return;const E=[...f.joinKeyGroups];E[w]={...E[w],operator:I},l(j,{joinKeyGroups:E})},removeJoinKeyGroup:(j,w)=>{const I=a.joins.find(E=>E.id===j);if(!I)return;const f=[...I.joinKeyGroups];f.splice(w,1),l(j,{joinKeyGroups:f})},addJoinKey:(j,w)=>{const I=a.joins.find(F=>F.id===j);if(!I)return;const f=n.find(F=>F.name===I.source.name),E=n.find(F=>F.name===I.target.name),b=[...I.joinKeyGroups],D={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(f==null?void 0:f.name)||"",entityName:(f==null?void 0:f.name)||"",entityType:(f==null?void 0:f.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(E==null?void 0:E.name)||"",entityName:(E==null?void 0:E.name)||"",entityType:(E==null?void 0:E.type)||"table"},operator:"="};b[w]={...b[w],keys:[...b[w].keys,D]},l(j,{joinKeyGroups:b})},updateJoinKey:(j,w,I,f,E)=>{const b=a.joins.find(L=>L.id===j);if(!b)return;const D=n.find(L=>L.name===b.source.name),F=n.find(L=>L.name===b.target.name),V=[...b.joinKeyGroups],S=V[w].keys[I];f==="sourceColumnName"&&D?V[w].keys[I]={...S,source:{...S.source,name:E}}:f==="targetColumnName"&&F?V[w].keys[I]={...S,target:{...S.target,name:E}}:f==="operator"&&(V[w].keys[I]={...S,operator:E}),l(j,{joinKeyGroups:V})},removeJoinKey:(j,w,I)=>{const f=a.joins.find(b=>b.id===j);if(!f)return;const E=[...f.joinKeyGroups];E[w].keys.splice(I,1),l(j,{joinKeyGroups:E})},generateSQLPreview:()=>{const j=[...a.joins].sort((f,E)=>f.sequence-E.sequence),w=a.baseEntity;if(!w.name)return"SELECT * FROM table -- Please select a base entity";let I=`SELECT *
147
+ FROM ${w.name}`;return j.forEach(f=>{const E=n.find(F=>F.name===f.target.name);if(!E)return;const b=f.joinKeyGroups.filter(F=>F.keys&&F.keys.length>0).map(F=>{const V=F.keys.filter(S=>{var L,v,O,R;return((L=S.source)==null?void 0:L.name)&&((v=S.target)==null?void 0:v.name)&&((O=S.source)==null?void 0:O.entityName)&&((R=S.target)==null?void 0:R.entityName)}).map(S=>`${S.source.entityName}.${S.source.name} ${S.operator} ${S.target.entityName}.${S.target.name}`);return V.length>1?`(${V.join(` ${F.operator} `)})`:V[0]}).filter(Boolean),D=b.length>1?b.join(" OR "):b[0]||"condition_here";I+=`
148
+ ${f.joinType} JOIN ${E.name}
149
+ ON ${D}`}),I},isValidConfiguration:()=>!(!a.baseEntity.name||a.joins.some(f=>!f.source.name||!f.target.name)||a.joins.some(f=>f.joinKeyGroups.some(E=>E.keys.length===0))||a.joins.some(f=>f.joinKeyGroups.some(E=>E.keys.some(b=>!b.source.name||!b.target.name||!b.operator))))}}function ma({joinPlan:t,availableDataSources:n,onSave:a,onRemove:r,onCancel:i}){const{setCardConfig:d}=s.useEditorActions();s.useEditorStore(D=>D.card.config);const{columnGroups:o}=s.useColumns(),c=o.filter(D=>D.entityName!==s.CALCULATED_FIELDS_GROUP_NAME),{joinPlan:l,expandedJoins:m,setJoinPlan:p,addJoin:x,removeJoin:u,updateJoin:C,moveJoinUp:y,moveJoinDown:h,toggleJoinExpansion:g,getAvailableSourceEntities:N,getAvailableTargetEntities:T,addJoinKeyGroup:B,updateGroupOperator:M,removeJoinKeyGroup:A,addJoinKey:j,updateJoinKey:w,removeJoinKey:I,generateSQLPreview:f,isValidConfiguration:E}=ua({initialJoinPlan:t,availableDataSources:n}),b=D=>{const F=c.find(V=>V.entityName===D);return(F==null?void 0:F.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:l.baseEntity.name,onValueChange:D=>{const F=n.find(V=>V.name===D);p({...l,baseEntity:{connectionId:(F==null?void 0:F.connectionId)||"",connectionType:(F==null?void 0:F.connectionType)||"none",type:(F==null?void 0:F.type)||"table",name:D,database:F==null?void 0:F.database,schema:F==null?void 0:F.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:n.map(D=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:D.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:D.type}),D.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},D.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:f()})]}),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 (",l.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"]})})]}),l.joins.length===0?e.jsx("div",{className:"rounded-lg border border-dashed py-8 text-center text-muted-foreground",children:e.jsx("p",{children:"No joins configured. Add a join to connect multiple data sources."})}):e.jsx("div",{className:"max-h-[300px] space-y-4 overflow-y-auto",children:l.joins.map(D=>{const F=n.find(L=>L.name===D.source.name),V=n.find(L=>L.name===D.target.name),S=m.has(D.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:D.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",D.sequence,F&&V&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",F.name," → ",V.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>y(D.id),disabled:D.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>h(D.id),disabled:D.sequence===l.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g(D.id),children:S?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:()=>u(D.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),S&&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:D.source.name,onValueChange:L=>{const v=n.find(O=>O.name===L);C(D.id,{source:{connectionId:(v==null?void 0:v.connectionId)||"",connectionType:(v==null?void 0:v.connectionType)||"none",type:(v==null?void 0:v.type)||"table",name:L,database:v==null?void 0:v.database,schema:v==null?void 0:v.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:N(D.id).map(L=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:L.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:L.type}),L.name]})},L.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:D.joinType,onValueChange:L=>C(D.id,{joinType:L}),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:D.target.name,onValueChange:L=>{const v=n.find(O=>O.name===L);C(D.id,{target:{connectionId:(v==null?void 0:v.connectionId)||"",connectionType:(v==null?void 0:v.connectionType)||"none",type:(v==null?void 0:v.type)||"table",name:L,database:v==null?void 0:v.database,schema:v==null?void 0:v.schema}})},disabled:!D.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:D.source.name?T(D.source.name).map(L=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:L.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:L.type}),L.name,L.name===D.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},L.name)):[]})]})]})]}),D.source.name&&D.target.name&&F&&V&&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:()=>B(D.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),D.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:D.joinKeyGroups.map((L,v)=>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 ",v+1]}),v>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:L.operator,onValueChange:O=>M(D.id,v,O),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:()=>A(D.id,v),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[L.keys.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-sm text-gray-500",children:"No conditions in this group. Add conditions to specify join criteria."}):e.jsx("div",{className:"space-y-2",children:L.keys.map((O,R)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[R>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:L.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:O.source.name,onValueChange:P=>w(D.id,v,R,"sourceColumnName",P),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:b(D.source.name).map(P=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:P.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:P.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:P.dataType})]})},P.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:O.operator,onValueChange:P=>w(D.id,v,R,"operator",P),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:O.target.name,onValueChange:P=>w(D.id,v,R,"targetColumnName",P),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:b(D.target.name).map(P=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:P.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:P.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:P.dataType})]})},P.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>I(D.id,v,R),children:e.jsx(s.X,{className:"size-3.5"})})]},O.id||R))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>j(D.id,v),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},L.id))})]})]})]},D.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),i()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:i,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>a(l),disabled:!E(),children:"Save"})]})]})}function rt({children:t,open:n,onOpenChange:a,joinPlan:r,availableDataSources:i,onRemove:d,onSave:o,onCancel:c}){return e.jsxs(s.Dialog,{open:n,onOpenChange:a,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(ma,{joinPlan:r,availableDataSources:i,onSave:o,onCancel:c,onRemove:d})]}),t]})}function xa({joins:t,baseEntityId:n,availableDataSources:a,generateSQLPreview:r}){return e.jsxs("div",{className:"my-2 max-h-[400px] divide-y divide-border overflow-y-auto",children:[t.length>0&&e.jsxs("div",{className:"px-4 py-2",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const i=[...t].sort((o,c)=>o.sequence-c.sequence),d=a.find(o=>o.name===n);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(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"})]}),i.map(o=>{const c=a.find(l=>l.name===o.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:o.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(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})]})]},o.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((i,d)=>i.sequence-d.sequence).map((i,d)=>{const o=a.find(m=>m.name===i.source.name),c=a.find(m=>m.name===i.target.name),l=i.joinKeyGroups.reduce((m,p)=>m+p.keys.length,0);return e.jsxs("div",{className:"rounded-md bg-muted p-2 text-left",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:d+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:i.joinType}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto shrink-0 text-xs",children:[l," condition",l>1?"s":""]})]}),e.jsxs("div",{className:"mt-1 truncate pl-1 text-xs text-muted-foreground",children:[o==null?void 0:o.name," → ",c==null?void 0:c.name]})]},i.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function Os({open:t,onOpenChange:n,variant:a="button"}={}){var T,B;const r=s.useEditorStore(M=>M.card),{autoJoinMetadata:i}=s.useDashboardCardQuery(r),d=s.useEditorStore(M=>M.actions.updateCardConfig),o=((T=r==null?void 0:r.config)==null?void 0:T.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[c,l]=k.useState(!1),m=t!==void 0,p=m?t:c,x=m?n:l,u=((B=r==null?void 0:r.dataSource)==null?void 0:B.selectedEntities)||[],C=M=>{d(r.id,{...r==null?void 0:r.config,joinPlan:M}),x(!1)},y=()=>{d(r.id,{...r==null?void 0:r.config,joinPlan:void 0})},h=()=>{x(!1)},g=()=>{const M=[...o.joins].sort((w,I)=>w.sequence-I.sequence),A=o.baseEntity;if(!A.name)return"SELECT * FROM table -- Please select a base entity";let j=`SELECT *
150
+ FROM ${A.name}`;return M.forEach(w=>{const I=u.find(b=>b.name===w.target.name);if(!I)return;const f=w.joinKeyGroups.filter(b=>b.keys&&b.keys.length>0).map(b=>{const D=b.keys.filter(F=>{var V,S,L,v;return((V=F.source)==null?void 0:V.name)&&((S=F.target)==null?void 0:S.name)&&((L=F.source)==null?void 0:L.entityName)&&((v=F.target)==null?void 0:v.entityName)}).map(F=>`${F.source.entityName}.${F.source.name} ${F.operator} ${F.target.entityName}.${F.target.name}`);return D.length>1?`(${D.join(` ${b.operator} `)})`:D[0]}).filter(Boolean),E=f.length>1?f.join(" OR "):f[0]||"condition_here";j+=`
151
+ ${w.joinType} JOIN ${I.name}
152
+ ON ${E}`}),j};if(u.length<2)return null;const N=o.joins.length>0&&e.jsx(s.TooltipContent,{side:"bottom",className:"ml-4 max-w-md overflow-hidden p-0",children:e.jsx(xa,{joins:o.joins,baseEntityId:o.baseEntity.name,availableDataSources:u,generateSQLPreview:g})});return e.jsxs(e.Fragment,{children:[e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:a==="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:M=>{M.stopPropagation(),x(!0)},children:[e.jsx(s.Link,{className:"h-3 w-3"}),o.joins.length]}):e.jsxs(s.Button,{onClick:()=>x(!0),variant:"outline",className:"w-full bg-muted/50",children:[e.jsx(s.Link,{className:"mr-2 h-3.5 w-3.5"}),o.joins.length===0?"Configure Joins":o.joins.length===1?"Join":"Joins",o.joins.length>0&&e.jsx("span",{className:"ml-2 flex h-5 min-w-5 items-center justify-center rounded-full border bg-muted-foreground px-1.5 text-xs font-medium text-background",children:o.joins.length}),(i==null?void 0:i.autoResolved)&&e.jsxs(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"]})]})}),N]})}),e.jsx(rt,{open:p,onOpenChange:x,joinPlan:o,availableDataSources:u,onSave:C,onCancel:h,onRemove:y,children:e.jsx("div",{})})]})}function ha({open:t,onOpenChange:n}){const[a,r]=k.useState([]),{updateDataSource:i}=s.useEditorActions(),d=s.useDashboardStore(y=>y.dashboard.aiContext),o=(d==null?void 0:d.selectedEntities)||[];k.useEffect(()=>{t&&r([])},[t]);const c=y=>{r(h=>h.some(N=>N.name===y.name&&N.type===y.type)?h.filter(N=>!(N.name===y.name&&N.type===y.type)):[...h,y])},l=()=>{r([...o])},m=()=>{r([])},p=()=>{if(a.length===0)return;const y=a[0],h=y.connectionId||"",g=y.connectionType||"",T=a.some(M=>M.type==="dataset")?"semanticDomain":"database";i({connectionId:h,connectionType:g,mode:T,selectedEntities:a}),n(!1)},x=y=>"label"in y&&y.label?y.label:y.name,u=y=>{if("description"in y&&y.description)return y.description;const h=[];return y.database&&h.push(y.database),y.schema&&h.push(y.schema),y.name&&h.push(y.name),h.join(".")},C=y=>a.some(h=>h.name===y.name&&h.type===y.type);return o.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:n,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:()=>n(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:n,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:l,disabled:a.length===o.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:m,disabled:a.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[a.length," of ",o.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:o.map((y,h)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",C(y)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:C(y),onCheckedChange:()=>c(y)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:s.getEntityIcon(y.type)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:x(y)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:u(y)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:y.type})]},`${y.type}-${y.name}-${h}`))})})]}),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:()=>n(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:p,disabled:a.length===0,children:["Select"," ",a.length>0?`(${a.length})`:""]})]})})})]})})}function Rs({entities:t,title:n}){const{isConsoleMode:a}=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:n??`${t.length} more entities`}),e.jsx("div",{className:"space-y-1",children:t.map((r,i)=>{const d=s.getEntityDetails(r),o=d.find(l=>l.label==="Description"&&l.value),c=d.filter(l=>l.label==="Description"?!1:a?!0:!["Connection","Database","Schema"].includes(l.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(r)}),o&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:o.value})]}),c.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:c.map((l,m)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[l.label,":"]}),e.jsx("span",{className:"font-mono",children:l.value})]},m))})]},`remaining-${r.type}-${r.name}-${i}`)})})]})})}function lt(t,n){const[a,r]=k.useState(()=>{const i=localStorage.getItem(t);return i?JSON.parse(i):n});return k.useEffect(()=>{localStorage.setItem(t,JSON.stringify(a))},[a,t]),[a,r]}function ot({isVisible:t}){var h,g;const n=s.useEditorStore(N=>N.isDevMode);s.useSyncLegacyEditorState();const[a,r]=k.useState(!1),[i,d]=k.useState(!1),[o,c]=lt("semaphor:data-source-collapsed",!1),l=s.useEditorStore(N=>N.card.dataSource),m=s.useEditorStore(N=>{var T,B;return(B=(T=N.card)==null?void 0:T.config)==null?void 0:B.joinPlan}),{updateDataSource:p}=s.useEditorActions(),x=((h=l==null?void 0:l.selectedEntities)==null?void 0:h.length)||0,u=((g=m==null?void 0:m.joins)==null?void 0:g.length)||0,y={...{connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},...l,selectedEntities:(l==null?void 0:l.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:[x===0&&u===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-4",o?"pb-0":"pb-3"),onClick:()=>c(!o),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:"Data Source"}),o&&e.jsxs("div",{className:"flex items-center gap-1.5",onClick:N=>N.stopPropagation(),children:[x>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"}),x]})}),e.jsx(Rs,{entities:y.selectedEntities,title:`${x} selected ${x===1?"entity":"entities"}`})]})}),u>0&&!n&&e.jsx(Os,{variant:"badge"})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:N=>{N.stopPropagation(),c(!o)},children:o?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronUp,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden transition-all duration-200 ease-in-out",o?"max-h-0 opacity-0":"max-h-96 opacity-100"),children:[e.jsx("div",{className:"px-6",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"}),x===1?"Dataset":"Datasets",e.jsx("span",{className:"ml-2 flex h-5 min-w-5 items-center justify-center rounded-full border bg-muted-foreground px-1.5 text-xs font-medium text-background",children:x})]})}),e.jsx(Rs,{entities:y.selectedEntities,title:`${x} selected ${x===1?"entity":"entities"}`})]})})}),!n&&x>1&&e.jsx("div",{className:"mt-3 px-6",children:e.jsx(Os,{})})]})]}),e.jsx(s.FieldsSection,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(l==null?void 0:l.selectedEntities)||[],dialogMode:"dataSource",open:a,onOpenChange:r,dataSource:y}),e.jsx(ha,{open:i,onOpenChange:d})]})}function pa(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 it(t){const{theme:n}=s.useTheme(),a=s.useDashboardStore(h=>h.theme),r=s.useEditorStore(h=>h.frame),i=s.useEditorStore(h=>h.card),d=s.useEditorStore(h=>h.activeTabCardId),o=s.Le(),{refetch:c}=s.useDashboardCardQuery(i),{updateCardTab:l,setRunSql:m}=s.useEditorActions(),p=k.useRef(void 0),x=k.useRef({}),u=r.cards.find(h=>h.id===d),C=k.useCallback(()=>{let h="";return t==="python"&&(h=(u==null?void 0:u.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(h=(u==null?void 0:u.sql)||""),h},[t,u]);k.useEffect(()=>{if(d&&i.id&&i.id!==d){if(p.current&&o){const h=p.current.getModel();h&&(x.current[i.id]=h);let g=x.current[d];if(!g){const N=C();g=o.editor.createModel(N,t),x.current[d]=g}p.current.setModel(g)}l(d,i),m(!0)}},[d,i,l,o,m,t,C]),k.useEffect(()=>{if(!o)return;const h=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",g=a==="system"?h:a;o.editor.defineTheme("default",{base:g==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":g==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),o.editor.setTheme("default")},[n,a,o]),k.useEffect(()=>{const h=p.current;h&&o&&i&&h.addCommand(o.KeyMod.Shift|o.KeyCode.Enter,function(){return c(),!1})},[o,c,i]);function y(h,g){if(p.current=h,!x.current[i.id]){const N=h.getModel(),T=C();x.current[i.id]=N||(g==null?void 0:g.editor.createModel(T,t))||h.getModel()}h.setModel(x.current[i.id])}return{handleEditorDidMount:y}}const fa=300;function ga(){const t=s.useEditorStore(p=>p.card.sql),n=s.useEditorStore(p=>p.sqlGen),{setCardSql:a,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:i}=it("sql"),d=k.useRef(n);d.current=n;const o=k.useCallback(p=>{a(p)},[a]),{value:c,onChange:l}=nt({storeValue:t,defaultValue:"",onStoreUpdate:o,delay:fa});function m(p){l(p),s.isObjectEmpty(d.current)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!c&&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:m,value:c,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:i})]})}const ja=300;function ba(){const t=s.useEditorStore(d=>d.card.python),{setCardPython:n}=s.useEditorActions(),{handleEditorDidMount:a}=it("python"),{value:r,onChange:i}=nt({storeValue:t,defaultValue:s.PYTHON_DEFAULT_CODE,onStoreUpdate:n,delay:ja});return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:i,value:r,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:a})}const ya={async writeTextToClipboard(t){return typeof navigator>"u"||!navigator.clipboard?!1:(await navigator.clipboard.writeText(t),!0)}},Ge=50,va=[{target:"queryRequest",label:"Query Request"},{target:"queryResponse",label:"Query Response"},{target:"cardConfig",label:"Card Config"},{target:"dataSource",label:"Data Source"},{target:"columns",label:"Columns"},{target:"dashboardFilters",label:"Dashboard Filters"},{target:"cardMetadata",label:"Card Metadata IDs"}];function Bs(t){try{return JSON.stringify(t,null,2)}catch(n){return console.error("Unable to stringify debug payload",n),null}}function Ve(t){switch(t){case"queryRequest":return"Query Request";case"queryResponse":return"Query Response";case"cardConfig":return"Card Config";case"dataSource":return"Data Source";case"cardMetadata":return"Card Metadata IDs";case"columns":return"Columns";case"dashboardFilters":return"Dashboard Filters";default:return"Payload"}}function Na(t){if(!t||typeof t!="object")return{value:t};const n=t.records;return!Array.isArray(n)||n.length<=Ge?{value:t}:{value:{...t,records:n.slice(0,Ge),previewMeta:{truncatedRecords:!0,displayedRecords:Ge,totalRecords:n.length}},truncationMessage:`Preview showing first ${Ge} records of ${n.length}. Copy actions include full payload.`}}function ct({sql:t,showCardDetails:n=!1,debugPayloads:a,className:r}){const[i,d]=k.useState(!1),[o,c]=k.useState(null),l=s.useEditorStore(E=>E.card),m=s.useEditorStore(E=>E.frame),p=s.useEditorStore(E=>E.isDevMode),x=s.useDashboardStore(E=>E.selectedSheetId),u=s.useDashboardStore(E=>{var b;return(b=E.dashboard)==null?void 0:b.id}),{switchEditorMode:C,setRunSql:y}=s.useEditorActions(),h=k.useMemo(()=>({cardId:l.id||null,frameId:m.id||null,sheetId:x||null,dashboardId:u||null}),[l.id,m.id,x,u]),g=k.useMemo(()=>({queryRequest:a==null?void 0:a.queryRequest,queryResponse:a==null?void 0:a.queryResponse,cardConfig:l.config,dataSource:l.dataSource,columns:a==null?void 0:a.columns,dashboardFilters:a==null?void 0:a.dashboardFilters,cardMetadata:h}),[a==null?void 0:a.queryRequest,a==null?void 0:a.queryResponse,a==null?void 0:a.columns,a==null?void 0:a.dashboardFilters,l.config,l.dataSource,h]),N=n&&i&&!!a,T=k.useMemo(()=>[{label:"Card ID",value:l.id||""},{label:"Frame ID",value:m.id||""},{label:"Sheet ID",value:x||""},{label:"Dashboard ID",value:u||""}],[l.id,m.id,x,u]),B=()=>{C("dev",{sqlToLoad:t}),setTimeout(()=>{y(!0)},100)},M=E=>g[E]!==void 0,A=k.useMemo(()=>{if(!o)return null;const E=g[o];if(E===void 0)return null;const b=o==="queryResponse"?Na(E):{value:E},D=Bs(b.value);return D?{target:o,title:Ve(o),json:D,truncationMessage:b.truncationMessage}:null},[o,g]),j=A?A.title:"Preview Payload",w=async E=>{const b=g[E];if(b===void 0)return s.ue.error(`No ${Ve(E).toLowerCase()} available`),!1;const D=Bs(b);if(!D)return s.ue.error(`Unable to serialize ${Ve(E).toLowerCase()}`),!1;try{return await ya.writeTextToClipboard(D)?(s.ue.success(`${Ve(E)} copied`),!0):(s.ue.error("Clipboard is not available"),!1)}catch(F){return console.error("Failed to copy debug payload",F),s.ue.error(`Unable to copy ${Ve(E).toLowerCase()}`),!1}},I=async()=>A?w(A.target):!1,f=E=>{if(g[E]===void 0){s.ue.error(`No ${Ve(E).toLowerCase()} available`);return}c(E)};return e.jsxs("div",{className:s.cn("flex min-h-0 flex-1 flex-col",r),children:[!p&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsxs(s.Button,{onClick:B,variant:"secondary",size:"sm",children:[e.jsx(st,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),n&&e.jsxs(s.Button,{onClick:()=>d(!i),variant:"outline",size:"sm",children:[e.jsx(s.Info,{className:"mr-2 h-4 w-4"}),"Card Details"]})]}),i&&n&&e.jsx("div",{className:"mb-3 rounded-lg border border-border bg-muted/30 p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Card Information"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>d(!1),children:e.jsx(fe.CircleX,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"grid grid-cols-1 gap-2 md:grid-cols-2",children:T.map(E=>e.jsxs("div",{className:"min-w-0 rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:E.label}),e.jsx(s.CopyButton,{text:E.value,className:"h-6 w-6 shrink-0"})]}),e.jsx("code",{title:E.value||"N/A",className:"mt-1 block whitespace-normal break-all font-mono text-xs",children:E.value||"N/A"})]},E.label))}),N&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-background/70 p-3",children:[e.jsx("p",{className:"text-xs font-semibold text-muted-foreground",children:"Debug Tools"}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8","aria-label":"Preview Payload Menu",children:[e.jsx(s.Eye,{className:"mr-1.5 h-3.5 w-3.5"}),j,e.jsx(s.ChevronDown,{className:"ml-1.5 h-3.5 w-3.5"})]})}),e.jsx(s.DropdownMenuContent,{align:"start",className:"w-56",children:va.map(E=>e.jsx(s.DropdownMenuItem,{disabled:!M(E.target),onSelect:()=>f(E.target),className:s.cn(o===E.target&&"bg-accent"),children:E.label},`preview-${E.target}`))})]})}),A&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs font-medium text-muted-foreground",children:[A.title," Preview"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.CopyButton,{text:A.json,className:"h-6 w-6",ariaLabel:"Copy Payload",onCopy:I}),e.jsxs(s.Button,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>c(null),children:[e.jsx(fe.CircleX,{className:"mr-1 h-3.5 w-3.5"}),"Hide"]})]})]}),A.truncationMessage&&e.jsx("p",{className:"text-xs text-muted-foreground",children:A.truncationMessage}),e.jsx("div",{className:"max-h-80 overflow-auto",children:e.jsx(s.CodeHighlighter,{code:A.json,language:"json"})})]})]})]})}),e.jsx("div",{className:"min-h-0 flex-1 overflow-auto text-xs leading-relaxed text-foreground/80",children: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"})]})})})]})}function Ca(){var H,ne;const t=s.useQueryClient(),{isConsoleMode:n}=s.useDashboardPreferences(),[a,r]=k.useState(!1),i=s.useEditorStore(K=>K.frame),d=s.useEditorStore(K=>K.card);s.useEditorStore(K=>K.isShowingVisual),s.useEditorStore(K=>K.selectedConnectionId),s.useEditorStore(K=>K.tempQueryData),s.useEditorStore(K=>K.selectedDatabaseName),s.useEditorStore(K=>K.selectedDatamodelId),s.useEditorStore(K=>K.selectedSchemaName);const o=s.useEditorStore(K=>K.showAIDialog);s.useEditorStore(K=>K.selectedTableName),s.useEditorStore(K=>{var re;return(re=K==null?void 0:K.card)==null?void 0:re.sql}),s.useEditorStore(K=>{var re;return(re=K==null?void 0:K.card)==null?void 0:re.python});const{cardFilterValues:c}=s.useCardFilterValues((d==null?void 0:d.id)??""),l=s.useDashboardStore(K=>K.inlineFilterValuesMap[(d==null?void 0:d.id)??""]),m=k.useMemo(()=>s.findCustomVisualConfigCard(i,d),[i,d]),{manifest:p}=s.useCustomVisual(((H=m==null?void 0:m.customCardPreferences)==null?void 0:H.url)||""),x=k.useMemo(()=>{var K;return(K=p==null?void 0:p.visuals)==null?void 0:K.find(re=>{var de;return re.name===((de=m==null?void 0:m.customCardPreferences)==null?void 0:de.componentName)})},[p,(ne=m==null?void 0:m.customCardPreferences)==null?void 0:ne.componentName]),u=s.resolveMultiInputType(m,x),C=k.useMemo(()=>s.getCustomVisualInputCards({frame:i,configCard:m,isMultiInputVisual:u==="multiple"}),[i,m,u]),y=k.useMemo(()=>{const K=C.findIndex(re=>(re==null?void 0:re.id)===(d==null?void 0:d.id));return K<0?-1:s.getSlotIndexForCard(d,K)},[C,d]),h=k.useMemo(()=>!m||u!=="multiple"||y<0?d.type:s.getEffectiveCardTypeForSlot(d,y,x==null?void 0:x.slots)??d.type,[m,u,y,d,x==null?void 0:x.slots]),g=k.useMemo(()=>h!==d.type?{...d,type:h}:d,[d,h]),N=k.useRef(!0),{setCardCustomCfg:T,setQueryResultColumns:B,setCardSql:M,setTempQueryData:A,setPythonStdOut:j,setCardPreferences:w,setCardType:I,setCardPython:f,setShowAIDialog:E,setCard:b,updateCardInFrame:D}=s.useEditorActions();s.useEditorStore(K=>K.onSave),s.useEditorStore(K=>K.onClose),s.useEditorStore(K=>K.actions.setSqlGen);const F=s.useEditorStore(K=>K.runSql),V=s.useEditorStore(K=>K.actions.setRunSql),S=s.useEditorStore(K=>K.actions.setIsSqlRunning),{data:L,isLoading:v,isFetching:O,isSuccess:R,isError:P,error:U,errorSql:q,queryKey:_,refetch:W,errorMessage:J}=s.useDashboardCardQuery(g);k.useEffect(()=>{if(L&&(L.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),j((L==null?void 0:L.output)||""),L.records.length>0)){const{dimensionKeys:K}=s.getKeys(L.records);B(K)}},[L,B,j]),k.useEffect(()=>{(v||O)&&S(!0),(P||R)&&S(!1),P&&(B([]),j(""))},[v,O,L,j,P,R,S,B,U]),k.useEffect(()=>{F&&(t.getQueryData(_)||W(),V(!1))},[F,W,V,_,t]);const ee=k.useRef(W);ee.current=W,k.useEffect(()=>{if(N.current){N.current=!1;return}ee.current()},[l]);function $(){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:a?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(ga,{})}),a&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),a&&e.jsxs(e.Fragment,{children:[e.jsx(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(ba,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function Y(){var K,re,de,ye,z,Q;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:v||O,onClick:()=>{W()},className:"h-8 shrink-0",size:"sm",children:[v||O?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"]}),(L==null?void 0:L.sql)&&!J&&e.jsxs(s.HoverCard,{openDelay:300,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Info,{className:"h-4 w-4 shrink-0 cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(s.HoverCardContent,{align:"start",className:"w-[500px]",children:e.jsx(ct,{sql:L.sql})})]}),e.jsx(fe.EditorClearButton,{}),e.jsxs(s.Toggle,{pressed:a,onPressedChange:le=>r(le),className:"h-8",size:"sm",variant:"outline",children:[e.jsx(pa,{className:"mr-2 size-4 text-foreground/70"}),"Python"]}),!o&&e.jsxs("button",{disabled:o,onClick:()=>{E(!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:((re=(K=d.preferences)==null?void 0:K.tablePrefs)==null?void 0:re.enableDevModePagination)??!1,onCheckedChange:le=>{var te;w({...d.preferences,tablePrefs:{...(te=d.preferences)==null?void 0:te.tablePrefs,enableDevModePagination:le}})}}),e.jsx(s.Label,{htmlFor:"pagination",className:"cursor-pointer text-sm",children:"Paginate"}),((ye=(de=d.preferences)==null?void 0:de.tablePrefs)==null?void 0:ye.enableDevModePagination)&&e.jsxs(s.Select,{value:String(((Q=(z=d.preferences)==null?void 0:z.tablePrefs)==null?void 0:Q.pageSize)||50),onValueChange:le=>{var je,ve,Ne;const te=Number(le),he={...d,preferences:{...d.preferences,tablePrefs:{...(je=d.preferences)==null?void 0:je.tablePrefs,pageSize:te}},paginationConfig:{page:1,pageSize:te}};b(he),D(he),d.sql&&((Ne=(ve=d.preferences)==null?void 0:ve.tablePrefs)!=null&&Ne.enableDevModePagination)&&V(!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"})]})]})]}),c&&c.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:c.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(c,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:$()}),Y()]})}const Sa=[{value:"table",label:"Table",icon:s.Table2},{value:"aggregateTable",label:"Aggregate",icon:s.Layers},{value:"pivotTable",label:"Pivot",icon:s.Grid3x3},{value:"detailTable",label:"Detail",icon:s.List}];function wa({className:t}){const n=s.useEditorStore(x=>x.card),a=s.useEditorStore(x=>x.frame),r=fe.useEffectiveEditorCardType(),{setCard:i,updateCardInFrame:d}=s.useEditorActions(),o=["table","aggregateTable","pivotTable","detailTable"].includes(r),c=s.hasValidCardConfig(n.config),l=s.isCustomVisualConfigCard(n,a.cards);if(!o||!c||l)return null;const m=x=>{if(l)return;const u=x,C=n.config??{},y=p(r,u,C),h={...n,type:u,config:y};i(h),d(h)},p=(x,u,C)=>{var h;if(u==="detailTable"){const g=M=>M==null?void 0:M.toLowerCase().replace(/\s+/g,"").trim(),N=(M,A)=>{const j=[g(M.label),g(M.qualifiedFieldName),g(M.name)].filter(Boolean),w=[g(A.label),g(A.qualifiedFieldName),g(A.name)].filter(Boolean);return j.some(I=>w.includes(I))},T=(C.groupByColumns||[]).map(M=>({...M,role:"detail"})),B=((h=C.sortByColumns)==null?void 0:h.filter(M=>T.some(A=>N(M,A))))??[];return{...C,detailTableBackup:{groupByColumns:C.groupByColumns,metricColumns:C.metricColumns,pivotByColumns:C.pivotByColumns,sortByColumns:C.sortByColumns,rowAggregates:C.rowAggregates,columnAggregates:C.columnAggregates,comparisonType:C.comparisonType},detailColumns:T,groupByColumns:[],metricColumns:[],pivotByColumns:[],sortByColumns:B,rowAggregates:[],columnAggregates:[],comparisonType:"none"}}let y=C;if(x==="detailTable")if(C.detailTableBackup)y={...C,...C.detailTableBackup,detailColumns:[],detailTableBackup:void 0};else{const g=(C.detailColumns||[]).map(N=>({...N,role:"groupby"}));y={...C,groupByColumns:g,detailColumns:[]}}return u==="aggregateTable"?{...y,pivotByColumns:[]}:y};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsx(s.RadioGroup,{value:r,onValueChange:m,className:"flex flex-row items-center justify-between gap-1 rounded-lg border p-1",children:Sa.map(x=>{const u=x.icon,C=r===x.value;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(s.RadioGroupItem,{value:x.value,id:`table-type-${x.value}`,className:"peer sr-only"}),e.jsxs(s.Label,{htmlFor:`table-type-${x.value}`,className:s.cn("flex cursor-pointer items-center gap-1.5 rounded-md px-3 py-1 text-sm font-medium transition-all",C?"bg-muted text-foreground shadow-sm":"text-muted-foreground hover:bg-muted/50"),children:[e.jsx(u,{className:"h-3.5 w-3.5"}),x.label]})]},x.value)})})})}function ds({error:t,errorSql:n,errorTitle:a="Unable to load data",onOpenInEditor:r,onDebugWithAssistant:i,onSendFeedback:d,showFeedbackButton:o=!0,className:c}){const[l,m]=k.useState(!1);return e.jsx("div",{className:s.cn("rounded-lg border border-border bg-muted/40 p-4",c),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-amber-500/10 dark:bg-amber-500/20",children:e.jsx(s.TriangleAlert,{className:"h-4 w-4 text-amber-600 dark:text-amber-500"})}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:a}),e.jsxs("div",{className:"relative rounded-md border border-border bg-background p-3",children:[e.jsx(s.CopyButton,{text:t,className:"absolute right-2 top-2 z-10 h-6 w-6"}),e.jsx("div",{className:"max-h-40 overflow-auto pr-10",children:e.jsx("p",{className:"break-all font-mono text-xs text-muted-foreground",children:t})})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n&&e.jsx(s.Collapsible,{open:l,onOpenChange:m,children:e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",children:l?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&&n&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:r,children:[e.jsx(st,{className:"mr-1.5 h-3.5 w-3.5"}),"Open in Editor"]}),o&&d&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:d,children:[e.jsx(s.MessageSquareWarning,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]}),i&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:i,children:[e.jsx(Qt,{className:"mr-1.5 h-3.5 w-3.5"}),"Debug with Assistant"]})]}),n&&e.jsx(s.Collapsible,{open:l,onOpenChange:m,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:"Query"}),e.jsx(s.CopyButton,{text:n,className:"h-6 w-6"})]}),e.jsx("div",{className:"max-h-80 overflow-auto rounded-md border border-border bg-background p-2",children:e.jsx(s.CodeHighlighter,{code:n,language:"sql"})})]})})})]})]})})}function dt(t,n){const a=s.useEditorStore(m=>m.card),r=s.useEditorStore(m=>m.isDevMode),{switchEditorMode:i,setRunSql:d,runAssistant:o}=s.useEditorActions();return{isDevMode:r,handleOpenInEditor:r?void 0:()=>{const m=n||a.sql||a.python||"";i("dev",{sqlToLoad:m}),setTimeout(()=>{d(!0)},100)},handleDebugWithAssistant:r?()=>{const m=`Can you help me debug this query?
153
+
154
+ Error:
155
+
156
+ ${t}
157
+
158
+ Error SQL:
159
+
160
+ ${n||a.sql||a.python}
161
+
162
+ `;o(m)}:void 0}}function ut({className:t,...n}){var ne,K,re,de,ye;const a=s.useEditorStore(z=>z.card),r=((ne=a.customCardPreferences)==null?void 0:ne.showCardHeader)??!0,i=((re=(K=a.preferences)==null?void 0:K.displayOptions)==null?void 0:re.showInlineFilterBar)??!0,d=s.useEditorStore(z=>z.frame),o=s.useDashboardStore(z=>z.dashboard.filters),c=s.useDashboardStore(z=>z.selectedSheetId),[l,m]=k.useState(!1),{currentUser:p}=s.useCurrentUserInfo(),{tokenProps:x}=k.useContext(s.SemaphorContext),u=s.useEditorStore(z=>z.actions.setRunSql),{updateFilter:C}=s.useDashboardActions(),y=o==null?void 0:o.find(z=>z.id===d.filterId),h=k.useMemo(()=>s.findCustomVisualConfigCard(d,a),[d,a]),{manifest:g}=s.useCustomVisual(((de=h==null?void 0:h.customCardPreferences)==null?void 0:de.url)||""),N=k.useMemo(()=>{var z;return(z=g==null?void 0:g.visuals)==null?void 0:z.find(Q=>{var le;return Q.name===((le=h==null?void 0:h.customCardPreferences)==null?void 0:le.componentName)})},[g,(ye=h==null?void 0:h.customCardPreferences)==null?void 0:ye.componentName]),T=s.resolveMultiInputType(h,N),B=k.useMemo(()=>s.getCustomVisualInputCards({frame:d,configCard:h,isMultiInputVisual:T==="multiple"}),[d,h,T]),M=k.useMemo(()=>{const z=B.findIndex(Q=>(Q==null?void 0:Q.id)===(a==null?void 0:a.id));return z<0?-1:s.getSlotIndexForCard(a,z)},[B,a]),A=k.useMemo(()=>!h||T!=="multiple"||M<0?a.type:s.getEffectiveCardTypeForSlot(a,M,N==null?void 0:N.slots)??a.type,[h,T,M,a,N==null?void 0:N.slots]),j=A??a.type,w=k.useMemo(()=>j===a.type?a:{...a,type:j},[a,j]),I=k.useMemo(()=>A!==a.type?{...a,type:A}:a,[a,A]),{data:f,isLoading:E,isFetching:b,errorMessage:D,errorSql:F,pagination:V}=s.useDashboardCardQuery(I),{handleOpenInEditor:S,handleDebugWithAssistant:L}=dt(D,F||a.sql||a.python),v=k.useMemo(()=>(f==null?void 0:f.records)||[],[f==null?void 0:f.records]),{setCard:O,updateCardInFrame:R}=s.useEditorActions(),{data:P}=s.useTopoJson(w),U=k.useMemo(()=>{var z;return j!=="pivotTable"||!((z=f==null?void 0:f.records)!=null&&z.length)?null:{records:f.records,columnSubtotalMeta:f.columnSubtotalMeta,subtotalColumns:f.subtotalColumns||[],pivotSchema:f.pivotSchema||[],groupByColumns:f.groupByColumns}},[j,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]),q=s.usePivotTableConfig(w,U),_=()=>{m(!0)},W=k.useMemo(()=>{const z=typeof window<"u"?window.location.href:"",Q=typeof navigator<"u"?navigator.userAgent:"",le=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:s.FeedbackCategory.QUERY_GENERATION,user:p,tokenContext:x,systemState:{cardConfig:a.config,dataSource:a.dataSource,dashboardFilters:o,errorMessage:D||void 0,errorSql:F||a.sql||a.python,generatedSql:F||a.sql},metadata:{url:z,userAgent:Q,timestamp:new Date().toISOString(),viewport:le}}},[p,x,a,o,D,F]),J=(z,Q)=>{var te,he;const le={...a,paginationConfig:{page:z+1,pageSize:Q}};O(le),R(le),a.sql&&((he=(te=a.preferences)==null?void 0:te.tablePrefs)!=null&&he.enableDevModePagination)&&u(!0)},ee=z=>{var te,he,je,ve,Ne;const Q=s.sortStateToSortByColumns(z,(te=a.config)==null?void 0:te.metricColumns,(he=a.config)==null?void 0:he.groupByColumns,(je=a.config)==null?void 0:je.detailColumns),le={...a,config:{...a.config||{},sortByColumns:Q}};O(le),R(le),a.sql&&((Ne=(ve=a.preferences)==null?void 0:ve.tablePrefs)!=null&&Ne.enableDevModePagination)&&u(!0)},$=k.useMemo(()=>!w.id||!(f!=null&&f.records)?null:s.createChartConfig({card:w,data:f==null?void 0:f.records,cardType:j,queryConfig:w.queryConfig,customCfg:w.customCfg,preferences:w.preferences,topoJson:P}),[w,f==null?void 0:f.records,j,P]);function Y(z){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(s.EditorCustomVisual,{card:z})})}function H(){var z;if(f!=null&&f.records&&(f==null?void 0:f.records.length)===0&&!E&&!b)return D?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(ds,{error:D,errorSql:F||a.sql||a.python,onOpenInEditor:S,onDebugWithAssistant:L,onSendFeedback:_,showFeedbackButton:!0})}):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((E||b)&&(!(f!=null&&f.records)||f.records.length===0))return j==="table"||j==="detailTable"?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(!w.id)return null;if(j==="custom")return Y(a);if(!["table","pivotTable","aggregateTable","detailTable","custom"].includes(j)&&$)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:E||b?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:$})});if(j==="table"||j==="detailTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:w,data:v,comparisonMetadata:(z=f==null?void 0:f.metadata)==null?void 0:z.comparisonMetadata,paginationMetadata:V,onPaginationChange:J,onSortChange:ee,isLoading:E||b})});if(j==="pivotTable"&&q)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:w,data:q.data,options:q.options,onAggregationChange:Q=>{const le=s.handleAggregationChange(Q,a.config),te={...a,config:le};O(te),R(te)},onAggregationLabelChange:Q=>{const le=s.handleAggregationLabelChange(Q,a.config),te={...a,config:le};O(te),R(te)}})});if(j==="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:w,data:(f==null?void 0:f.records)||[],groupByColumns:f==null?void 0:f.groupByColumns,pivotSchema:f==null?void 0:f.pivotSchema,paginationMetadata:V,onPaginationChange:J,onAggregationChange:Q=>{const le=s.handleAggregationChange(Q,a.config),te={...a,config:le};O(te),R(te)},isLoading:E||b})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...n,children:[(E||b)&&(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:a.title,onSave:z=>O({...a,title:z}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(s.InfoHover,{card:a}),e.jsx(fe.VisualBadge,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(wa,{})})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:(a.description||"").trim(),onSave:z=>O({...a,description:z.trim()}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),y&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:y.title||y.column,onSave:z=>C({...y,title:z}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:y})]})]}),i&&a.inlineFilters&&a.inlineFilters.length>0&&e.jsx("div",{className:"px-6 pb-3",children:e.jsx(s.InlineFilterBar,{card:a,sheetId:c||""})}),e.jsxs(s.CardContent,{className:"flex min-h-0 grow flex-col",children:[e.jsx("div",{className:"min-h-0 flex-1 grow basis-0",children:H()}),s.isCardSummaryVisibleOnCard(w)&&e.jsx("div",{className:"pt-3",children:e.jsx(s.CardSummary,{card:w,mode:"editor"})})]}),e.jsx(s.FeedbackDialog,{open:l,onOpenChange:m,feedbackData:W,showDebugInfo:!0})]})}const es=({language:t,value:n,onChange:a,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:n,onChange:a}),Ta=()=>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."})]})]}),Ea=({customCode:t,cardCustomCfgString:n,mergedConfig:a,onConfigChange:r,onCodeChange:i})=>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(es,{language:"json",value:a,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(es,{readonly:!0,language:"json",value:n,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(es,{language:"javascript",value:t,onChange:i})})]}),Ia=({error:t,hasCardCustomConfig:n,onReset:a,onApply:r,onClose:i})=>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:!n,onClick:a,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:i,variant:"outline",children:"Close"})]});function ka(){const[t,n]=k.useState(!1),[a,r]=k.useState(""),[i,d]=k.useState(""),[o,c]=k.useState(""),[l,m]=k.useState(""),p=s.useEditorStore(w=>w.card),x=fe.useEffectiveEditorCardType(),u=s.useEditorStore(w=>w.card.customCfg),C=u?JSON.stringify(u,null,2):"",y=k.useMemo(()=>x!==p.type?{...p,type:x}:p,[p,x]),{data:h}=s.useDashboardCardQuery(y),{data:g}=s.useTopoJson(p),{setCardCustomCfg:N,setCustomVisualCode:T}=s.useEditorActions(),B=w=>{var I,f;return JSON.stringify({...w,data:{...w.data,datasets:(f=(I=w.data)==null?void 0:I.datasets)==null?void 0:f.map(E=>({...E,data:[]}))}},null,2)},M=()=>{var I,f;if(!((I=h==null?void 0:h.records)!=null&&I.length))return;const w=s.createChartConfig({card:p,data:h.records,cardType:p.type,queryConfig:p.queryConfig,preferences:p.preferences,topoJson:g});if(w){r(B(w)),c(((f=p.preferences)==null?void 0:f.customVisualCode)||"");const E=s.merge(w,u);d(B(E))}},A=()=>{try{if(o&&T(o),i){const w=JSON.parse(i),I=s.getObjectDiff(JSON.parse(a),w);N(I),m("")}}catch{m("Invalid JSON configuration")}},j=Object.keys(u||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:n,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:M,className:j?"":"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(Ta,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(ut,{className:"w-1/2 rounded shadow-none"})}),e.jsx(Ea,{customCode:o,cardCustomCfgString:C,mergedConfig:i,onConfigChange:w=>d(w??""),onCodeChange:w=>c(w??"")})]}),e.jsx(Ia,{error:l,hasCardCustomConfig:!!u,onReset:()=>{d(a),N(null)},onApply:A,onClose:()=>n(!1)})]})]})}function Da({isStarred:t,onClick:n,className:a}){const r=i=>{i.stopPropagation(),i.preventDefault(),n(i)};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",a),"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 Vs({chartType:t,chartName:n,isCustom:a=!1,pluginName:r,isStarred:i,showStar:d=!0,onSelect:o,onToggleStar:c}){return e.jsxs("button",{onClick:o,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",i?"opacity-100":"opacity-0 group-hover:opacity-100"),children:e.jsx(Da,{isStarred:i,onClick:()=>c()})}),a&&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:n,isCustom:a,className:"h-6 w-6"}),e.jsx("span",{title:n,className:"line-clamp-2 text-center text-xs font-medium text-foreground",children:n})]})}const Ps=[{id:"table",name:"Table"},{id:"bar",name:"Bar Chart"},{id:"line",name:"Line Chart"},{id:"area",name:"Area Chart"},{id:"combo",name:"Combo Chart"},{id:"stackedBar",name:"Stacked Bar"},{id:"stackedArea",name:"Stacked Area"},{id:"stackedLine",name:"Stacked Line"},{id:"scatter",name:"Scatter"},{id:"bubble",name:"Bubble"},{id:"pie",name:"Pie Chart"},{id:"doughnut",name:"Doughnut"},{id:"funnel",name:"Funnel"},{id:"radar",name:"Radar"},{id:"polarArea",name:"Polar Area"},{id:"tornado",name:"Tornado"},{id:"range",name:"Range"},{id:"bullet",name:"Bullet Chart"},{id:"treemap",name:"Treemap"},{id:"heatmap",name:"Heatmap"},{id:"kpi",name:"KPI"},{id:"text",name:"Text"},{id:"map",name:"Map"}];function Aa({onChartSelect:t,onClose:n}){const[a,r]=k.useState(""),{starredCharts:i,isStarred:d,toggleStar:o}=s.useStarredChartsStore(),{data:c=[],isLoading:l}=s.useCustomVisualsQuery(),{setCardType:m,setCardPreferences:p,setIsDevMode:x}=s.useEditorStore(f=>f.actions),u=s.useEditorStore(f=>f.card),{setCardCustomCfg:C,setCustomCardPreferences:y,setQueryConfig:h,replaceFrameCards:g,clearModeDrafts:N,initializeModeDrafts:T}=s.useEditorActions(),B=k.useMemo(()=>{if(!a)return Ps;const f=a.toLowerCase();return Ps.filter(E=>E.name.toLowerCase().includes(f))},[a]),M=k.useMemo(()=>{const f=c.filter(b=>b.componentType==="chart"&&b.pluginType!=="standard");if(!a)return f;const E=a.toLowerCase();return f.filter(b=>b.name.toLowerCase().includes(E))},[c,a]),A=f=>{C(null),p({}),m(f),["custom","text","map"].includes(f)&&(x(!0),h(void 0)),t==null||t(f),n==null||n()},j=f=>{C(null),p({}),h(void 0);const E=s.resolveMultiInputTypeFromVisual(f);if(E==="multiple"&&f.slots&&f.slots.length>0){N();const D=s.createCardsFromSlots(f.slots,f,u);g(D),D[0]&&T(D[0]),n==null||n();return}else m("custom"),y({type:"component",visualType:E,url:f.url,componentName:f.name,icon:f.icon,pluginChartType:f.chartType,minInputs:f.minInputs,maxInputs:f.maxInputs});t==null||t("custom",f),n==null||n()},w=f=>{const E={type:"default",id:f.id,name:f.name};o(E)},I=f=>{const E={type:"custom",id:f.name,url:f.url,icon:f.icon,name:f.name};o(E)};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$1,{placeholder:"Search charts...",value:a,onChange:f=>r(f.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:[B.length>0&&e.jsx("div",{className:"mb-3",children:e.jsx("div",{className:"grid grid-cols-3 gap-2",children:B.map(f=>e.jsx(Vs,{chartType:f.id,chartName:f.name,isCustom:!1,isStarred:d("default",f.id),onSelect:()=>A(f.id),onToggleStar:()=>w(f)},f.id))})}),M.length>0&&e.jsxs(e.Fragment,{children:[B.length>0?e.jsx(s.Separator,{className:"my-3"}):null,e.jsxs("div",{children:[e.jsx("span",{className:"mb-2 block text-xs font-medium text-muted-foreground",children:"Custom Charts"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:M.map((f,E)=>e.jsx(Vs,{chartName:f.name,isCustom:!0,pluginName:f.pluginName,isStarred:d("custom",f.name),onSelect:()=>j(f),onToggleStar:()=>I(f)},`${f.url}-${f.name}-${E}`))})]})]}),l&&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..."})]}),B.length===0&&M.length===0&&!l&&e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No charts found"})]})]})}function La({selectedChart:t,onChartChange:n}){var j,w,I,f;const a=s.useEditorStore(E=>E.card),r=s.useEditorStore(E=>E.frame),i=s.useEditorStore(E=>E.isDevMode),{replaceFrameCards:d,clearModeDrafts:o,initializeModeDrafts:c,setIsDevMode:l}=s.useEditorActions(),m=k.useMemo(()=>s.findCustomVisualConfigCard(r,a),[r,a]),{manifest:p}=s.useCustomVisual(((j=m==null?void 0:m.customCardPreferences)==null?void 0:j.url)||""),x=k.useMemo(()=>{var E;return(E=p==null?void 0:p.visuals)==null?void 0:E.find(b=>{var D;return b.name===((D=m==null?void 0:m.customCardPreferences)==null?void 0:D.componentName)})},[p,(w=m==null?void 0:m.customCardPreferences)==null?void 0:w.componentName]),u=s.resolveMultiInputType(m,x)==="multiple",C=fe.useEffectiveEditorCardType(),y=u?C:t??a.type,h=(I=a==null?void 0:a.customCardPreferences)==null?void 0:I.componentName,g=(f=m==null?void 0:m.customCardPreferences)==null?void 0:f.componentName,N=u&&!!g,T=k.useMemo(()=>{const E=s.chartTypes.find(b=>b.id===y);return E?E.label:y==="custom"?h||"Custom Visual":"Select chart type"},[y,h]),B=k.useMemo(()=>{const E=s.chartTypes.find(b=>b.id===y);if(E){const b=E.icon;return e.jsx(b,{className:"h-4 w-4"})}if(y==="custom"&&h){const b=s.getAutoDetectedChartIcon(h);return b||e.jsx(s.ChartIcon,{chartName:h,isCustom:!0,className:"h-4 w-4"})}return e.jsx(ra,{className:"h-4 w-4"})},[y,h]);return{displayChartType:y,displayLabel:T,displayIcon:B,showBadge:N,badgeLabel:g,isMultiInputContext:u,handleChartSelect:E=>{n==null||n(E)},handleClearCustomVisual:E=>{E.stopPropagation();const b={...a,type:"bar",sql:"",python:"",config:void 0,queryConfig:void 0,customCfg:void 0,preferences:{},customCardPreferences:void 0,title:"Chart",tabTitle:"Chart",description:void 0,info:void 0};d([b]),o(),c(b),i&&l(!0),n==null||n("bar")}}}function us({selectedChart:t,onChartChange:n,variant:a="ghost",className:r}){const[i,d]=k.useState(!1),{displayLabel:o,displayIcon:c,showBadge:l,badgeLabel:m,handleChartSelect:p,handleClearCustomVisual:x}=La({selectedChart:t,onChartChange:n});return e.jsxs("div",{className:s.cn("relative w-full",r),children:[e.jsxs(s.Popover,{open:i,onOpenChange:d,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:a,role:"combobox","aria-expanded":i,className:"w-full justify-between gap-2",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c,e.jsx("span",{className:"truncate",children:o})]}),e.jsx(s.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[360px] p-3",align:"start",onOpenAutoFocus:u=>u.preventDefault(),children:e.jsx(Aa,{onChartSelect:u=>p(u),onClose:()=>d(!1)})})]}),l&&e.jsxs("div",{className:"absolute right-10 top-1/2 z-10 flex max-w-[140px] -translate-y-1/2 items-center gap-1 rounded-full border bg-background py-0.5 pl-2 pr-1 text-[10px] text-muted-foreground shadow-sm",title:m,children:[e.jsx(s.Layers,{className:"h-2.5 w-2.5 shrink-0"}),e.jsx("span",{className:"truncate",children:m}),e.jsx("button",{onClick:x,className:"rounded-full p-0.5 hover:bg-muted",title:"Clear custom visual",children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]})]})}function Ma(){const t=s.useEditorStore(l=>{var m,p;return(p=(m=l.card.preferences)==null?void 0:m.chartOptions)==null?void 0:p.indexAxis}),n=s.useEditorStore(l=>l.card.type),{setChartOrientation:a,setCardPreferences:r}=s.useEditorStore(l=>l.actions),i=l=>{if(a(l),n!=="bullet")return;const m=l==="y"?"horizontal":"vertical",p=s.useEditorStore.getState().card.preferences,x={...p||{},bulletConfig:{...(p==null?void 0:p.bulletConfig)||{},orientation:m}};r(x)};function d(){const l=t??"x",m=()=>{i(l==="x"?"y":"x")};return e.jsx(s.IconButton,{onClick:m,tooltip:"Chart Orientation",children:l==="x"?e.jsx(Ze,{className:"size-4"}):e.jsx(Xe,{className:"size-4"})})}function o(){const l=()=>{i(t==="y"||t===void 0?"x":"y")};return e.jsx(s.IconButton,{onClick:l,tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(Ze,{className:"size-4"}):e.jsx(Xe,{className:"size-4"})})}function c(){const l=t??"y",m=()=>{i(l==="y"?"x":"y")};return e.jsx(s.IconButton,{onClick:m,tooltip:"Chart Orientation",children:l==="y"?e.jsx(Xe,{className:"size-4"}):e.jsx(Ze,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?o():n==="bullet"?c():d()})}function Fa({className:t}){var C,y,h,g,N,T,B,M,A,j;const n=s.useEditorStore(w=>w.card),{setCardPreferences:a,updateCardInFrame:r,setCard:i}=s.useEditorActions(),[d,o]=k.useState(!1),c=((y=(C=n.preferences)==null?void 0:C.displayOptions)==null?void 0:y.showFilterInfo)??!0,l=((g=(h=n.preferences)==null?void 0:h.displayOptions)==null?void 0:g.showCardToolbar)??!0,m=((T=(N=n.preferences)==null?void 0:N.displayOptions)==null?void 0:T.showChrome)??!0,p=((M=(B=n.preferences)==null?void 0:B.displayOptions)==null?void 0:M.allowScroll)??!0,x=((j=(A=n.preferences)==null?void 0:A.displayOptions)==null?void 0:j.showInlineFilterBar)??!0,u=(w,I)=>{var b;const f={...n.preferences,displayOptions:{...(b=n.preferences)==null?void 0:b.displayOptions,[w]:I}};a(f);const E={...n,preferences:f};i(E),r(E)};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsxs(s.DropdownMenu,{modal:!1,open:d,onOpenChange:o,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(at,{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:w=>{u("showFilterInfo",w)},onSelect:w=>w.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:l,onCheckedChange:w=>{u("showCardToolbar",w)},onSelect:w=>w.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:m,onCheckedChange:w=>{u("showChrome",w)},onSelect:w=>w.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:p,onCheckedChange:w=>{u("allowScroll",w)},onSelect:w=>w.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:x,onCheckedChange:w=>{u("showInlineFilterBar",w)},onSelect:w=>w.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 Oa(){const[t,n]=k.useState(!1),a=s.useEditorStore(x=>x.card),r=s.useEditorStore(x=>x.selectedConnectionId),{setCard:i}=s.useEditorActions(),d=s.useDashboardStore(x=>x.actions.removeCardInlineFilterValue),o=(a==null?void 0:a.inlineFilters)||[];function c(x){var j,w,I,f,E;const u=((I=(w=(j=a==null?void 0:a.dataSource)==null?void 0:j.selectedEntities)==null?void 0:w[0])==null?void 0:I.database)||"",C=x.qualifiedFieldName||x.name;if(o.find(b=>b.column===C))return;const h=x.qualifiedFieldName?x.qualifiedFieldName.split(".").slice(0,-1).join("."):x.qualifiedEntityName||x.entityName,N=s.fmt(x.name),T=s.buildFilterFieldMeta(x),B=s.buildFilterSemanticContext(a==null?void 0:a.dataSource,{connectionId:r||((f=a==null?void 0:a.dataSource)==null?void 0:f.connectionId),connectionType:(E=a==null?void 0:a.dataSource)==null?void 0:E.connectionType}),M=s.isCalculatedFilterField(T),A={id:s.v4(),column:C,title:x.label||x.name,dataType:x.dataType,table:x.entityName||"",database:u,connectionId:r||"",operation:"in",sql:M?"":s.getDefaultFilterSql(x.dataType,h,N),fieldMeta:T,semanticContext:B,width:250};i({...a,inlineFilters:[...o,A]})}function l(x){const u=o.filter(C=>C.id!==x);i({...a,inlineFilters:u}),d(a.id,x)}function m(x,u){const C=o.map(y=>y.id===x?{...y,...u}:y);i({...a,inlineFilters:C})}return["bar","line","pie","doughnut","table","detailTable","stackedBar","stackedLine","horizontalBar","radar","polarArea","scatter","bubble","funnel","aggregateTable","custom"].includes(a==null?void 0:a.type)?e.jsx("div",{className:"flex items-center gap-1",children:e.jsxs(s.Popover,{open:t,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.IconButton,{tooltip:"Add Inline Filter",className:s.cn("relative",{"text-primary":o.length>0}),children:[e.jsx(Zt,{className:"h-4 w-4"}),o.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:o.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:o})})})}),o.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:o.map(x=>e.jsx(Ra,{filter:x,onUpdate:u=>m(x.id,u),onRemove:()=>l(x.id)},x.id))})]})]})})]})}):null}function Ra({filter:t,onUpdate:n,onRemove:a}){return e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-muted px-2 py-1.5 text-sm",children:[e.jsx("span",{className:"truncate",title: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=>n(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:a,children:e.jsx(s.X,{className:"h-3 w-3"})})]})]})}function mt(){const t=s.useEditorStore(d=>d.card),n=s.useEditorStore(d=>{var o,c;return(c=(o=d.card)==null?void 0:o.preferences)==null?void 0:c.chartOptions}),a=s.getChartGridStyle(n),{setChartGrid:r}=s.useEditorActions();function i(){const d=["xy","none","x","y"],c=(d.indexOf(a)+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(Ma,{})}),!["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:i,children:[(a==="xy"||!a)&&e.jsx(s.Grid3x3,{className:"size-4"}),a==="x"&&e.jsx(et,{className:"size-4"}),a==="y"&&e.jsx(cs,{className:"size-4"}),a==="none"&&e.jsx(s.Square,{className:"size-4"})]}),e.jsx(Oa,{}),e.jsx(Fa,{})]})}function Ba({isPreviewMode:t,onPreviewToggle:n,configCard:a}){var V,S,L,v,O;const r=s.useEditorStore(R=>R.frame),i=s.useEditorStore(R=>R.card),{setFrame:d,setActiveTabCardId:o,setCard:c,updateCardInFrame:l,clearModeDrafts:m,initializeModeDrafts:p}=s.useEditorActions(),{manifest:x}=s.useCustomVisual(((V=a==null?void 0:a.customCardPreferences)==null?void 0:V.url)||""),u=(S=x==null?void 0:x.visuals)==null?void 0:S.find(R=>{var P;return R.name===((P=a==null?void 0:a.customCardPreferences)==null?void 0:P.componentName)}),y=s.resolveMultiInputType(a,u)==="multiple",h=(u==null?void 0:u.minInputs)??((L=a==null?void 0:a.customCardPreferences)==null?void 0:L.minInputs)??1,g=(u==null?void 0:u.maxInputs)??((v=a==null?void 0:a.customCardPreferences)==null?void 0:v.maxInputs),N=k.useMemo(()=>s.getCustomVisualInputCards({frame:r,configCard:a,isMultiInputVisual:y}),[r,a,y]),T=y?N.filter(Boolean).length:r.cards.length,B=g?T<g:!0,M=T>Math.max(h||1,1),A=!!((O=a==null?void 0:a.customCardPreferences)!=null&&O.dataInputCardIds),j=(R,P)=>{R.dataTransfer.setData("tabIndex",P.toString())},w=R=>{R.preventDefault()},I=(R,P)=>{const U=R.dataTransfer.getData("tabIndex");if(U===P.toString())return;const q=Array.from(r.cards),[_]=q.splice(parseInt(U),1);q.splice(P,0,_),d({...r,cards:q})};function f(R){const P=(a==null?void 0:a.id)===R;if(!(A&&P?r.cards.length>1:M))return;let q=r.cards.filter(ee=>ee.id!==R);y&&!A&&(q=s.reindexSlotCards(q));const _=q[0],W={...r,cards:q,activeCardId:_.id},J=R===i.id;J&&m(),d(W),o(_.id),c(_),J&&p(_)}function E(R,P){if(!B)return;const U={...r,cards:[...r.cards,P],activeCardId:R.id};d(U),o(P.id)}function b(){if(y&&(a==null?void 0:a.id)===i.id){D(i);return}const R={...i,id:s.v4(),title:`${i.title} Copy`,tabTitle:`${i.tabTitle||i.title} Copy`,customCardPreferences:i.customCardPreferences?{...i.customCardPreferences,slotIndex:y?Math.max(-1,...N.map((P,U)=>s.getSlotIndexForCard(P,U)))+1:i.customCardPreferences.slotIndex}:void 0};E(i,R)}function D(R){var J;if(!B)return;let P=y?"table":"bar",U="Title",q="";const _=y?Math.max(-1,...N.map((ee,$)=>s.getSlotIndexForCard(ee,$)))+1:T;if(y&&((J=u==null?void 0:u.slots)!=null&&J.length)){const ee=s.getSlotDefinitionForIndex(u.slots,_);ee&&(P=s.getSlotExpectedChartType(ee),U=ee.label||`Tab ${_+1}`,q=ee.description||"")}const W={dataSource:R.dataSource,connectionId:R.connectionId,lastSelectedDatabase:R.lastSelectedDatabase,lastSelectedSchema:R.lastSelectedSchema,lastSelectedTable:R.lastSelectedTable,lastSelectedDatamodelId:R.lastSelectedDatamodelId,id:s.v4(),title:U,tabTitle:U,description:q,preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:P,sql:"",data:[],mode:"explorer",...y&&{customCardPreferences:{slotIndex:_}}};E(R,W)}function F(R,P){return R.cards.length===1&&(P.displayTab===!0||P.displayTab===void 0)||R.activeCardId!==P.id&&(P.displayTab===!0||P.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const U=P.displayTab===void 0?!1:!P.displayTab;c({...P,displayTab:U}),l({...P,displayTab:U})},children:P.displayTab===!0||P.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(s.EyeOff,{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:[r.cards.map((R,P)=>{var J,ee;const U=y?s.getSlotIndexForCard(R,P):-1,q=y&&((J=u==null?void 0:u.slots)!=null&&J.length)&&U>=0?s.getSlotDefinitionForIndex(u.slots,U):null,_=q?(Array.isArray(q.expectedType)?q.expectedType[0]:q.expectedType)||"table":R.type,W=y&&((ee=u==null?void 0:u.slots)==null?void 0:ee.length)&&u.slots.every($=>typeof $.position=="number"||typeof $.position=="string"&&!$.position.includes("+"));return e.jsxs(s.TabsTrigger,{draggable:!y,onDragStart:y?void 0:$=>j($,P),onDragOver:y?void 0:w,onDrop:y?void 0:$=>I($,P),className:"",value:R.id,children:[y&&q?e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:s.getChartIconByType(_,"size-3.5")}),e.jsx("span",{children:q.label||`Tab ${U+1}`})]})}),e.jsx(s.TooltipContent,{side:"bottom",className:"w-64 p-3 text-left",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium",children:q.label}),q.description&&e.jsx("p",{className:"whitespace-normal break-words text-xs text-muted-foreground",children:q.description}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[q.expectedType&&e.jsx("span",{className:"inline-flex items-center rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground",children:Array.isArray(q.expectedType)?q.expectedType.join(" / "):q.expectedType}),q.required&&e.jsx("span",{className:"inline-flex items-center rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground",children:"Required"})]})]})})]})}):e.jsxs(e.Fragment,{children:[F(r,R),e.jsx(s.Editable,{enabled:r.activeCardId===R.id,text:R.tabTitle||R.title,onSave:$=>{c({...i,tabTitle:$}),l({...i,tabTitle:$})},children:R.tabTitle||R.title},R.id)]}),r.activeCardId===R.id&&!W&&e.jsx(s.CopyPlus,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:$=>{$.stopPropagation(),b()}}),r.activeCardId===R.id&&(A&&(a==null?void 0:a.id)===R.id?r.cards.length>1:M)&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>f(R.id)})]},R.id)}),e.jsx(s.IconButton,{tooltip:"Add Card",className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",onClick:()=>D(i),disabled:!B,children:e.jsx(s.Plus,{className:"h-4 w-4"})}),y&&e.jsxs(s.Toggle,{pressed:t,onPressedChange:n,size:"sm",className:"ml-2 h-8 gap-1 px-2 data-[state=on]:bg-background data-[state=on]:text-foreground","aria-label":"Toggle preview",children:[t?e.jsx(s.EyeOff,{className:"h-4 w-4"}):e.jsx(s.Eye,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Preview"})]})]})})}function is(){var he,je,ve,Ne,Ie;const t=s.useEditorStore(se=>se.frame),n=s.useEditorStore(se=>se.card),[a,r]=k.useState(!1),i=k.useMemo(()=>s.findCustomVisualConfigCard(t,n),[t,n]),d=s.useEditorStore(se=>se.isSqlRunning);s.useEditorStore(se=>se.isDevMode);const{setFrame:o,setActiveTabCardId:c,setCard:l,setRunSql:m,mergeDraftsIntoCard:p,clearModeDrafts:x,initializeModeDrafts:u}=s.useEditorActions(),[C,y]=k.useState({}),[h,g]=k.useState(()=>new Set),{theme:N}=s.useTheme(),T=s.useDashboardStore(se=>se.themeStyle),{authToken:B}=s.useSemaphorContext(),M=s.getTokenParams(B==null?void 0:B.accessToken),A={mode:N||"system",colors:((je=(he=T==null?void 0:T.chart)==null?void 0:he.dataset)==null?void 0:je.backgroundColor)||[]},{getCard:j,manifest:w,isLoading:I}=s.useCustomVisual(((ve=i==null?void 0:i.customCardPreferences)==null?void 0:ve.url)||""),f=(Ne=i==null?void 0:i.customCardPreferences)==null?void 0:Ne.componentName,E=f?j(f):null,b=(Ie=w==null?void 0:w.visuals)==null?void 0:Ie.find(se=>se.name===f),D=s.resolveMultiInputType(i,b),F=a&&D==="multiple"&&!!i,V=k.useMemo(()=>s.getCustomVisualInputCards({frame:t,configCard:i,isMultiInputVisual:!0}).map(ce=>(ce==null?void 0:ce.id)===n.id?n:ce),[t,i,n]),S=k.useMemo(()=>s.buildSlotOrderedCards(V),[V]),L=k.useMemo(()=>{const se=V.findIndex(ce=>(ce==null?void 0:ce.id)===n.id);return se<0?-1:s.getSlotIndexForCard(n,se)},[V,n]),v=k.useMemo(()=>!i||D!=="multiple"||L<0?n.type:s.getEffectiveCardTypeForSlot(n,L,b==null?void 0:b.slots)??n.type,[i,D,L,n,b==null?void 0:b.slots]),O=k.useMemo(()=>F?{...n,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:v!==n.type?{...n,type:v}:n,[n,v,F]),{data:R,isLoading:P,isFetching:U,isError:q}=s.useDashboardCardQuery(O),_=k.useCallback((se,ce)=>{const ue=s.normalizeMultiInputPayload(ce);y(pe=>({...pe,[se]:ue}))},[]),W=k.useCallback((se,ce)=>{g(ue=>{const pe=new Set(ue);return ce?pe.add(se):pe.delete(se),pe})},[]),J=h.size>0,ee=s.useInteractionStore(se=>se.interactionStates),$=s.useDashboardStore(se=>{var ce;return(ce=se.dashboard)==null?void 0:ce.id}),Y=s.useDashboardStore(se=>se.dashboard.filters),H=s.useDashboardStore(se=>se.filterValues),ne=s.useDashboardStore(se=>se.selectedSheetId),K=s.useDashboardStore(se=>se.inlineFilterValuesMap[(i==null?void 0:i.id)||""]),re=k.useMemo(()=>i?s.buildInlineFilterNodes({card:i,sheetId:ne||"",inlineFilterValues:K}):[],[i,ne,K]),{cardFilters:de,cardFilterValues:ye}=k.useMemo(()=>i?s.calculateContextAwareFilters({card:i,interactionStates:ee,currentDashboardId:$,filters:Y,filterValues:H,selectedSheetId:ne}):{cardFilters:[],cardFilterValues:[]},[i,ee,$,Y,H,ne]);function z(se){const ce=t.cards.find(ue=>ue.id===se);ce&&(p(),Q(se),c(se),x(),u(ce))}function Q(se){const ce=s.useEditorStore.getState().card,ue=s.useEditorStore.getState().frame,pe={...ue,cards:ue.cards.map(Ce=>Ce.id===ce.id?ce:Ce),activeCardId:se};o(pe);const Te=pe.cards.find(Ce=>Ce.id===se);Te.sql&&m(!0),l(Te)}function le(){if(I)return e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading manifest"})});if(!E)return e.jsx("div",{className:"flex h-full items-center justify-center text-sm text-muted-foreground",children:"Select a component to preview the multi-input visual."});const ce=S.map((ue,pe)=>s.getEffectiveCardTypeForSlot(ue,pe,b==null?void 0:b.slots));return e.jsxs("div",{className:"relative flex h-full flex-col px-6",children:[V.map((ue,pe)=>{if(!ue)return null;const Te=s.getSlotIndexForCard(ue,pe),Ce=s.getEffectiveCardTypeForSlot(ue,Te,b==null?void 0:b.slots);return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:W,onDataChange:_,card:ue,effectiveCardType:Ce},`${ue.id}-${Te}`)}),J&&e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/50",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading preview"})}),e.jsx("div",{className:s.cn("flex h-full min-h-0 flex-1 flex-col gap-2",J&&"opacity-50"),children:e.jsx(k.Suspense,{fallback:e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted"})}),children:e.jsx(E,{editing:!0,...s.buildMultiInputCustomVisualProps({configCard:i,slotOrderedCards:S,slotTypes:ce,multiInputData:C,params:M,theme:A,filters:de,filterValues:[...ye||[],...K||[]],inlineFilters:re})})})})]})}function te(){var se;return F?le():n.type==="kpi"?P||U?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.jsxs("div",{className:"w-1/2 space-y-3",children:[e.jsx("div",{className:"rounded-md border border-border",children:e.jsx(s.KPICard,{card:n,data:R==null?void 0:R.records,isPending:P||U,isError:q,comparisonMetadata:(se=R==null?void 0:R.metadata)==null?void 0:se.comparisonMetadata})}),s.isCardSummaryVisibleOnCard(n)&&e.jsx(s.CardSummary,{card:n,mode:"editor"})]})}):n.type==="text"?P||U?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:d,card:n,data:R==null?void 0:R.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(ut,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:z,value:t.activeCardId,className:"flex grow flex-col gap-2",children:[F?e.jsx("div",{className:"mt-0 grow",children:te()}):t.cards.map(se=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:se.id,children:te()},se.id)),e.jsx(Ba,{isPreviewMode:F,onPreviewToggle:r,configCard:i})]})}function zs({children:t}){var L;const n=s.useEditorStore(v=>v.frame),a=s.useEditorStore(v=>v.card),r=s.useEditorStore(v=>v.isDevMode),i=s.useEditorStore(v=>v.isShowingVisual),d=s.useDashboardStore(v=>v.isVisualEditing),o=s.useEditorStore(v=>v.pythonStdOut),c=s.useEditorStore(v=>v.actions.setRunSql),l=fe.useEffectiveEditorCardType(),{setFrame:m,setCard:p,setActiveTabCardId:x,setCardPreferences:u,mergeDraftsIntoCard:C,clearModeDrafts:y,initializeModeDrafts:h}=s.useEditorActions(),g=k.useMemo(()=>l!==a.type?{...a,type:l}:a,[a,l]),{data:N,isLoading:T,isFetching:B,errorMessage:M,errorSql:A,refetch:j,pagination:w}=s.useDashboardCardQuery(g),{handleDebugWithAssistant:I}=dt(M,A),f=k.useMemo(()=>(N==null?void 0:N.records)||[],[N==null?void 0:N.records]),[E,b]=k.useState(!1);k.useEffect(()=>{B||b(!1)},[B]);function D(v,O){var U,q;const R={...a,paginationConfig:{page:v+1,pageSize:O}};p(R);const P={...n,cards:n.cards.map(_=>_.id===a.id?R:_)};m(P),a.sql&&((q=(U=a.preferences)==null?void 0:U.tablePrefs)!=null&&q.enableDevModePagination)&&c(!0)}function F(v){var U,q,_,W,J;const O=s.sortStateToSortByColumns(v,(U=a.config)==null?void 0:U.metricColumns,(q=a.config)==null?void 0:q.groupByColumns,(_=a.config)==null?void 0:_.detailColumns),R={...a,config:{...a.config||{},sortByColumns:O}};p(R);const P={...n,cards:n.cards.map(ee=>ee.id===a.id?R:ee)};m(P),a.sql&&((J=(W=a.preferences)==null?void 0:W.tablePrefs)!=null&&J.enableDevModePagination)&&c(!0)}function V(){const v=JSON.stringify(N==null?void 0:N.records,null,2),O=new Blob([v],{type:"application/json"}),R=URL.createObjectURL(O),P=document.createElement("a");P.href=R,P.download=`${a.title}.json`,P.click()}function S(){const O=[Object.keys(N==null?void 0:N.records.reduce((q,_)=>({...q,..._}),{})).join(","),...((N==null?void 0:N.records)||[]).map(q=>Object.values(q).join(","))].join(`
163
+ `),R=new Blob([O],{type:"text/csv"}),P=URL.createObjectURL(R),U=document.createElement("a");U.href=P,U.download=`${a.title}.csv`,U.click()}return a?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:[i&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx("div",{className:"w-[260px]",children:e.jsx(us,{variant:"outline"})}),!["table","detailTable","custom"].includes(a.type)&&d&&e.jsx(ka,{})]}),!i&&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:S,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:V,children:e.jsx(Jt,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(N==null?void 0:N.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:T||B,onClick:()=>{b(!0),j()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":E})})}),e.jsx(mt,{})]}),r&&e.jsx(Pa,{})]}),i?e.jsx(is,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[o&&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:o&&e.jsx(Va,{})}),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":o}),children:[(N==null?void 0:N.records)&&(N==null?void 0:N.records.length)>0&&e.jsx(s.TableVisual,{card:a,data:f,comparisonMetadata:(L=N==null?void 0:N.metadata)==null?void 0:L.comparisonMetadata,paginationMetadata:w,onPaginationChange:D,onSortChange:F,isLoading:T||B}),M&&e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(ds,{error:M,errorSql:A||a.sql||a.python,onDebugWithAssistant:I,showFeedbackButton:!1})})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function Va(){const t=s.useEditorStore(a=>a.pythonStdOut);if(!t)return null;const n=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:n}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Pa(){const t=s.useEditorStore(a=>a.isShowingVisual),n=s.useEditorStore(a=>a.actions.setIsShowingVisual);return e.jsxs(s.Toggle,{pressed:!t,onPressedChange:()=>n(!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 Se({value:t,onCommit:n,type:a="text",placeholder:r,className:i}){const[d,o]=k.useState(t),c=k.useRef(!1);k.useEffect(()=>{o(t)},[t]);const l=()=>{if(c.current){c.current=!1;return}d!==t&&n(d)},m=p=>{if(p.key==="Enter"){p.currentTarget.blur();return}p.key==="Escape"&&(c.current=!0,o(t),p.currentTarget.blur())};return e.jsx(s.Input,{type:a,placeholder:r,value:d,onChange:p=>o(p.target.value),onBlur:l,onKeyDown:m,className:i})}function Me({defaultValue:t,label:n,options:a,value:r,onValueChange:i,className:d,icon:o,showPlaceholderLabel:c=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:i,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:[o&&e.jsx("span",{children:o}),c&&e.jsx(s.SelectValue,{placeholder:n})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:n}),a.map(l=>e.jsx(s.SelectItem,{value:l.value,children:l.label},l.value))]})})]})}function za(t,n){return s.getSlotDefinitionForIndex(t,n)||null}function ze(t){if(typeof t=="number")return`Tab ${t+1}`;const n=t.match(/^(\d+)-(\d+)$/);if(n){const[,r,i]=n;return`Tabs ${Number(r)+1}-${Number(i)+1}`}const a=t.match(/^(\d+)\+$/);return a?`Tabs ${Number(a[1])+1}+`:`Tab ${t}`}function $a(t){return t?Array.isArray(t)?t:[t]:[]}function ss(t){var r,i;if(!t)return!1;if(t.type==="text")return!!((r=t.description)!=null&&r.trim());const n=!!((i=t.sql)!=null&&i.trim()),a=s.hasValidCardConfig(t.config);return n||a}function qa({slots:t,cards:n,minInputs:a}){const r=[],i=n.filter(Boolean).length;return a&&i<a&&r.push({type:"too-few-inputs",message:`This visual requires at least ${a} tab${a===1?"":"s"}.`}),!t||t.length===0||(t.forEach(d=>{if(!d.required)return;if(typeof d.position=="number"){const l=n[d.position];ss(l)||r.push({type:"missing-required",message:`${ze(d.position)} ("${d.label}") is required but has no data configured.`});return}const o=d.position.match(/^(\d+)-(\d+)$/);if(o){const[,l,m]=o.map(Number);for(let p=l;p<=m;p+=1){const x=n[p];if(!ss(x)){r.push({type:"missing-required",message:`${ze(p)} ("${d.label}") is required but has no data configured.`});break}}return}const c=d.position.match(/^(\d+)\+$/);if(c){const l=Number(c[1]);if(n.length<=l){r.push({type:"missing-required",message:`${ze(l)} ("${d.label}") is required but has no data configured.`});return}for(let m=l;m<n.length;m+=1){const p=n[m];if(!ss(p)){r.push({type:"missing-required",message:`${ze(m)} ("${d.label}") is required but has no data configured.`});break}}}}),n.forEach((d,o)=>{if(!d)return;const c=za(t,o);if(!c||!c.expectedType)return;const l=$a(c.expectedType);l.length!==0&&(l.includes(d.type)||r.push({type:"wrong-type",message:`${ze(o)} ("${c.label}") expects ${l.join(", ")}, but is configured as ${d.type}.`}))})),r}const Ga={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:n})=>(n==null?void 0:n.includes("language-"))?e.jsx("pre",{className:"my-3 overflow-x-auto rounded-md bg-muted p-3 text-xs",children:e.jsx("code",{children: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 xt(){var D,F,V;const t=s.useEditorStore(S=>S.card.customCardPreferences),{data:n}=s.usePluginQuery(),a=(n==null?void 0:n.plugins)||[],r=s.useEditorStore(S=>S.card),i=s.useEditorStore(S=>S.frame),{setCustomCardPreferences:d}=s.useEditorActions(),o=k.useMemo(()=>s.findCustomVisualConfigCard(i,r),[i,r]),c=o==null?void 0:o.customCardPreferences,{components:l,manifest:m}=s.useCustomVisual((c==null?void 0:c.url)||(t==null?void 0:t.url)||""),p=(D=m==null?void 0:m.visuals)==null?void 0:D.find(S=>S.name===((c==null?void 0:c.componentName)||(t==null?void 0:t.componentName))),u=s.resolveMultiInputType(o||r,p)==="multiple",C=!!o&&o.id===r.id,y=(p==null?void 0:p.minInputs)??((F=o==null?void 0:o.customCardPreferences)==null?void 0:F.minInputs),h=(p==null?void 0:p.maxInputs)??((V=o==null?void 0:o.customCardPreferences)==null?void 0:V.maxInputs),g=k.useMemo(()=>s.getCustomVisualInputCards({frame:i,configCard:o||r,isMultiInputVisual:u}),[i,o,r,u]),N=k.useMemo(()=>s.buildSlotOrderedCards(g),[g]),T=k.useMemo(()=>N.map((S,L)=>{if(!S)return null;const v=s.getSlotIndexForCard(S,L),O=s.getEffectiveCardTypeForSlot(S,v,p==null?void 0:p.slots);return{...S,type:O??S.type}}),[N,p==null?void 0:p.slots]),B=k.useMemo(()=>qa({slots:p==null?void 0:p.slots,cards:T,minInputs:y}),[p==null?void 0:p.slots,T,y]),M=k.useMemo(()=>{const S=g.findIndex(L=>(L==null?void 0:L.id)===r.id);return S<0?-1:s.getSlotIndexForCard(r,S)},[g,r]);function A(S){if(typeof S=="number")return`Tab ${S+1}`;const L=S.match(/^(\d+)-(\d+)$/);if(L){const[,O,R]=L;return`Tabs ${Number(O)+1}-${Number(R)+1}`}const v=S.match(/^(\d+)\+$/);return v?`Tabs ${Number(v[1])+1}+`:`Tab ${S}`}function j(S){return S?(Array.isArray(S)?S:[S]).join(", "):null}function w(S,L,v=[],O="",R,P,U){const q=I({key:L,defaultValue:O,settingsValue:P,sourceCard:U});return S==="input"?e.jsx(Se,{className:`h-8 w-full ${s.removeRing}`,value:String(q??""),onCommit:_=>{f({key:L,value:_,settingsField:R,settingsValue:P,sourceCard:U})}},L):S==="select"?e.jsx(Me,{className:"h-8 w-full",label:"",options:v,value:String(q!==void 0?q:O??""),onValueChange:_=>{f({key:L,value:_,settingsField:R,settingsValue:P,sourceCard:U})}}):null}function I({key:S,defaultValue:L,settingsValue:v,sourceCard:O}){const R=v==null?void 0:v[S];return R!==void 0?R:S==="title"&&(O==null?void 0:O.title)!==void 0?O.title:S==="description"&&(O==null?void 0:O.description)!==void 0?O.description:L}function f({key:S,value:L,settingsField:v,settingsValue:O,sourceCard:R}){const P={...O||{}},U=S==="title"&&(R==null?void 0:R.title)!==void 0,q=S==="description"&&(R==null?void 0:R.description)!==void 0;U&&L===String((R==null?void 0:R.title)??"")||q&&L===String((R==null?void 0:R.description)??"")?delete P[S]:P[S]=L,d({...t||{},[v]:P})}function E({settingsSchema:S,settingsField:L,settingsValue:v,sourceCard:O,headerLabel:R}){const P=Object.entries(S||{});return e.jsxs("div",{className:"space-y-3",children:[R&&e.jsx(s.Label,{children:R}),P.map(([U,q])=>{var _;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:q.title}),((_=q.docs)==null?void 0:_.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:q.docs.description})})]})})]}),w(q.ui,U,q.options,q.defaultValue,L,v,O)]},U)})]})}function b(){return e.jsxs(e.Fragment,{children:[u&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Slot Guide"}),e.jsx("div",{className:"space-y-3 rounded-md border border-border bg-muted/40 px-3 py-2 text-xs",children:p!=null&&p.slots&&p.slots.length>0?e.jsx("div",{className:"space-y-3",children:p.slots.map((S,L)=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-foreground",children:[e.jsx("span",{className:"font-medium",children:A(S.position)}),e.jsx("span",{className:"text-muted-foreground",children:"•"}),e.jsx("span",{className:"font-medium",children:S.label})]}),S.description&&e.jsx("p",{className:"text-muted-foreground",children:S.description}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-muted-foreground",children:[j(S.expectedType)&&e.jsxs("span",{children:["Expected: ",j(S.expectedType)]}),S.required&&e.jsx("span",{children:"Required"})]})]},`${S.label}-${L}`))}):e.jsxs("div",{className:"space-y-1 text-muted-foreground",children:[e.jsx("p",{children:"This visual renders all tabs in a flexible layout. Add as many tabs as needed."}),(y||h)&&e.jsxs("p",{children:[y?`Min ${y} tabs`:"",y&&h?" • ":"",h?`Max ${h} tabs`:""]})]})})]}),u&&B.length>0&&e.jsx(s.Alert,{className:"border-yellow-500/40 bg-yellow-500/10 text-yellow-900 dark:text-yellow-100",children:e.jsx(s.AlertDescription,{children:e.jsx("ul",{className:"list-disc space-y-1 pl-4 text-xs",children:B.map((S,L)=>e.jsx("li",{children:S.message},`${S.type}-${L}`))})})}),p&&!u&&p.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:E({settingsSchema:p.settings,settingsField:"settings",settingsValue:t==null?void 0:t.settings,sourceCard:r})})}),p&&u&&(p.settings||p.slotSettings)&&e.jsxs("div",{className:"mt-4 space-y-4",children:[C&&p.settings&&e.jsx("div",{className:"px-2",children:E({settingsSchema:p.settings,settingsField:"settings",settingsValue:t==null?void 0:t.settings,sourceCard:o||r,headerLabel:"Global Settings"})}),p.slotSettings&&e.jsx("div",{className:"px-2",children:E({settingsSchema:p.slotSettings,settingsField:"slotSettings",settingsValue:t==null?void 0:t.slotSettings,sourceCard:r,headerLabel:(()=>{const S=r.tabTitle||r.title,L=M>=0?M:0,v=C?"Slot 0":`Slot ${L}`;return S?`${v}: ${S} Settings`:`${v} Settings`})()})})]})]})}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:[(!u||C)&&e.jsx(Me,{icon:e.jsx(Zs,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:a,value:(c==null?void 0:c.url)||"",onValueChange:S=>d({...t||{url:"",componentName:""},url:S})}),u&&!C&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Switch to the config tab to change the plugin or component."})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&(!u||C)&&e.jsx(e.Fragment,{children:l&&e.jsx(Me,{icon:e.jsx(Ht,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(l==null?void 0:l.map(S=>({value:S.name,label:S.name})))||[],value:t.componentName||"",onValueChange:S=>{var O;const L=(O=m==null?void 0:m.visuals)==null?void 0:O.find(R=>R.name===S),v=l==null?void 0:l.find(R=>R.name===S);d({...t,componentName:S,visualType:(L==null?void 0:L.visualType)||(v==null?void 0:v.type)||"single",minInputs:L==null?void 0:L.minInputs,maxInputs:L==null?void 0:L.maxInputs,pluginChartType:L==null?void 0:L.chartType})}})})]})})]}),((c==null?void 0:c.componentName)||(t==null?void 0:t.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:(p==null?void 0:p.name)||"Settings"}),(p==null?void 0:p.docs)&&e.jsxs(s.HoverCard,{openDelay:0,closeDelay:100,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,onClick:S=>S.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:[p.docs.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:p.docs.description}),p.docs.dataSchema&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Data Schema"}),e.jsx("div",{className:"prose prose-sm dark:prose-invert prose-pre:bg-muted prose-pre:text-xs max-w-none",children:e.jsx(s.Markdown,{remarkPlugins:[s.remarkGfm],components:Ga,children:p.docs.dataSchema})})]}),(()=>{var L;const S=(L=p.docs)==null?void 0:L.useCases;return!S||S.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Use Cases"}),e.jsx("ul",{className:"space-y-1 text-sm",children:S.map((v,O)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1 text-primary",children:"•"}),e.jsx("span",{children:v})]},O))})]})})()]})})]})]})}),e.jsx(s.AccordionContent,{children:b()})]})]})}function Ka({colorRanges:t,setColorRanges:n}){const a={start:-1/0,end:100,color:""};function r(o,c,l){const m=[...t];m[o]={...m[o],[c]:l},n(m)}function i(o){const c=[...t];c.splice(o,1),n(c)}function d(){n([...t,a])}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((o,c)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input,{onChange:l=>r(c,"start",l.target.value),value:o.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input,{value:o.end,onChange:l=>r(c,"end",l.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input,{onChange:l=>r(c,"color",l.target.value),value:o.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:()=>i(c),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},c))]})}function Ua(){var p,x,u,C,y;const t=s.useEditorStore(h=>h.card.preferences),n=s.useEditorStore(h=>h.actions.setCardPreferences),a=s.useEditorStore(h=>h.card),r=s.hasValidCardConfig(a.config),i=s.useEditorStore(h=>h.actions.setNumberFormat);s.useEditorStore(h=>{var g,N;return(N=(g=h.card.preferences)==null?void 0:g.formatNumber)==null?void 0:N.decimalPlaces});const d=s.useEditorStore(h=>{var g,N;return(N=(g=h.card.preferences)==null?void 0:g.formatNumber)==null?void 0:N.locale}),o=s.useEditorStore(h=>{var g,N;return(N=(g=h.card.preferences)==null?void 0:g.formatNumber)==null?void 0:N.currency});s.useEditorStore(h=>h.actions.setFilterOnClickField);const c=s.useEditorStore(h=>{var g,N;return(N=(g=h.card.preferences)==null?void 0:g.formatNumber)==null?void 0:N.colorRanges})||[],l=s.useEditorStore(h=>h.actions.setColorRanges),m=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(h=>h.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(s.Checkbox,{checked:!!((p=t==null?void 0:t.formatNumber)!=null&&p.enabled),onCheckedChange:h=>{n({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:h}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((x=t==null?void 0:t.formatNumber)==null?void 0:x.enabled)===!0||r)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Locale"}),e.jsxs(s.Select,{value:d||"none",onValueChange:h=>{var g,N,T;return i(((g=t==null?void 0:t.formatNumber)==null?void 0:g.decimalPlaces)||0,((N=t==null?void 0:t.formatNumber)==null?void 0:N.currency)||"",h,((T=t==null?void 0:t.formatNumber)==null?void 0:T.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(h=>e.jsx(s.SelectItem,{value:h.locale,children:h.locale},h.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:o||"none",onValueChange:h=>{var g,N,T;console.log("currency",h),i(((g=t==null?void 0:t.formatNumber)==null?void 0:g.decimalPlaces)||0,h==="none"?"":h,((N=t==null?void 0:t.formatNumber)==null?void 0:N.locale)||"",((T=t==null?void 0:t.formatNumber)==null?void 0:T.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"),m.map(h=>e.jsx(s.SelectItem,{value:h,children:h},h))]})})]})]})]}),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:((C=(u=t==null?void 0:t.formatNumber)==null?void 0:u.decimalPlaces)==null?void 0:C.toString())||"0",onValueChange:h=>{var g,N,T;return i(Number(h),((g=t==null?void 0:t.formatNumber)==null?void 0:g.currency)||"",((N=t==null?void 0:t.formatNumber)==null?void 0:N.locale)||"",((T=t==null?void 0:t.formatNumber)==null?void 0:T.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(h=>e.jsx(s.SelectItem,{value:h,children:h},h))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Suffix"}),e.jsx(s.Input,{value:((y=t==null?void 0:t.formatNumber)==null?void 0:y.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:h=>{var g,N,T;return i(((g=t==null?void 0:t.formatNumber)==null?void 0:g.decimalPlaces)||0,((N=t==null?void 0:t.formatNumber)==null?void 0:N.currency)||"",((T=t==null?void 0:t.formatNumber)==null?void 0:T.locale)||"",h.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(Ka,{colorRanges:c,setColorRanges:l})]})]})}const _a={combo:{label:"Combo Chart",query:"SELECT x-axis, metric-1, metric-2, ... FROM table",fields:[{name:"x-axis",type:"category",description:"dimension"},{name:"metric-1, metric-2",type:"number",description:"can be bar, line, or area"}],description:"Combo charts allow mixing bar and line series with optional dual Y-axis for metrics with different scales.",docsUrl:"https://docs.semaphor.cloud/docs/charts/combo"},area:{label:"Area Chart",query:"SELECT x-axis, y-axis-1, y-axis-2, ... FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., date, city"},{name:"Y-axis",type:"number",description:"e.g., sales, population"}],description:"Area charts display quantitative data with filled areas under the line.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bar-line-area"},stackedArea:{label:"Stacked Area Chart",query:"SELECT x-axis, y-axis-1, y-axis-2, ... FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., date, city"},{name:"Y-axis",type:"number",description:"e.g., sales, population"}],description:"Stacked area charts show how multiple series contribute to a total over time.",docsUrl:"https://docs.semaphor.cloud/docs/charts/stacked"},bar:{label:"Bar Chart",query:"SELECT x-axis, y-axis-1, y-axis-2, ... FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., city, product"},{name:"Y-axis",type:"number",description:"e.g., sales, count"}],description:"Bar charts compare values across categories using horizontal or vertical bars.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bar-line-area"},line:{label:"Line Chart",query:"SELECT x-axis, y-axis-1, y-axis-2, ... FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., date, month"},{name:"Y-axis",type:"number",description:"e.g., revenue, count"}],description:"Line charts show trends over time or continuous data.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bar-line-area"},stackedBar:{label:"Stacked Bar Chart",query:"SELECT x-axis, stack-by, y-axis FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., month"},{name:"Stack-by",type:"category",description:"e.g., product type"},{name:"Y-axis",type:"number",description:"e.g., sales"}],description:"Stacked bar charts show how parts contribute to a whole across categories.",docsUrl:"https://docs.semaphor.cloud/docs/charts/stacked"},stackedLine:{label:"Stacked Line Chart",query:"SELECT x-axis, stack-by, y-axis FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., date"},{name:"Stack-by",type:"category",description:"e.g., region"},{name:"Y-axis",type:"number",description:"e.g., revenue"}],description:"Stacked line charts show cumulative trends over time.",docsUrl:"https://docs.semaphor.cloud/docs/charts/stacked"},pie:{label:"Pie Chart",query:"SELECT label, measure FROM table",fields:[{name:"Label",type:"category",description:"e.g., product, region"},{name:"Measure",type:"number",description:"e.g., sales, count"}],description:"Pie charts show proportions of a whole.",docsUrl:"https://docs.semaphor.cloud/docs/charts/pie-donut-polar"},doughnut:{label:"Doughnut Chart",query:"SELECT label, measure FROM table",fields:[{name:"Label",type:"category",description:"e.g., product, region"},{name:"Measure",type:"number",description:"e.g., sales, count"}],description:"Doughnut charts show proportions with a hollow center.",docsUrl:"https://docs.semaphor.cloud/docs/charts/pie-donut-polar"},polarArea:{label:"Polar Area Chart",query:"SELECT label, measure FROM table",fields:[{name:"Label",type:"category",description:"e.g., skill, metric"},{name:"Measure",type:"number",description:"e.g., score, value"}],description:"Polar area charts compare values using sectors of equal angle but varying radius.",docsUrl:"https://docs.semaphor.cloud/docs/charts/pie-donut-polar"},radar:{label:"Radar Chart",query:"SELECT label, measure FROM table",fields:[{name:"Label",type:"category",description:"e.g., attribute, skill"},{name:"Measure",type:"number",description:"e.g., score, rating"}],description:"Radar charts display multivariate data on axes starting from the same point.",docsUrl:"https://docs.semaphor.cloud/docs/charts/pie-donut-polar"},funnel:{label:"Funnel Chart",query:"SELECT label, measure FROM table",fields:[{name:"Label",type:"category",description:"e.g., stage name"},{name:"Measure",type:"number",description:"e.g., count, value"}],description:"Funnel charts visualize progressive reduction of data through stages.",docsUrl:"https://docs.semaphor.cloud/docs/charts/funnel"},bubble:{label:"Bubble Chart",query:"SELECT label, [group], x-axis, y-axis, radius FROM table",fields:[{name:"Label",type:"category",description:"e.g., city"},{name:"Group",type:"category",description:"e.g., region",optional:!0},{name:"X-axis",type:"number",description:"e.g., population"},{name:"Y-axis",type:"number",description:"e.g., income"},{name:"Radius",type:"number",description:"e.g., area"}],description:"Bubble charts display three dimensions of data using position and size.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bubble"},scatter:{label:"Scatter Chart",query:"SELECT label, [group], x-axis, y-axis FROM table",fields:[{name:"Label",type:"category",description:"e.g., item name"},{name:"Group",type:"category",description:"e.g., type",optional:!0},{name:"X-axis",type:"number",description:"e.g., price"},{name:"Y-axis",type:"number",description:"e.g., quantity"}],description:"Scatter charts show relationships between two numeric variables.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bubble"},tornado:{label:"Tornado Chart",query:"SELECT dimension, cohort, metric FROM table",fields:[{name:"Dimension",type:"category",description:"e.g., age group"},{name:"Cohort",type:"category",description:"e.g., gender"},{name:"Metric",type:"number",description:"e.g., population"}],description:"Tornado charts compare two groups across categories using back-to-back bars.",docsUrl:"https://docs.semaphor.cloud/docs/charts/tornado"},pyramid:{label:"Pyramid Chart",query:"SELECT dimension, cohort, metric FROM table",fields:[{name:"Dimension",type:"category",description:"e.g., age group"},{name:"Cohort",type:"category",description:"e.g., gender"},{name:"Metric",type:"number",description:"e.g., population"}],description:"Population pyramids show age and gender distribution.",docsUrl:"https://docs.semaphor.cloud/docs/charts/tornado"},range:{label:"Range Chart",query:"SELECT y-axis, label, range-from, range-to, range-value FROM table",fields:[{name:"Y-axis",type:"category",description:"e.g., category"},{name:"Label",type:"category",description:"e.g., range name"},{name:"Range-from",type:"number",description:"start value"},{name:"Range-to",type:"number",description:"end value"},{name:"Range-value",type:"number",description:"e.g., midpoint"}],description:"Range charts display data ranges with start and end values.",docsUrl:"https://docs.semaphor.cloud/docs/charts/range"},heatmap:{label:"Heatmap",query:"SELECT x-axis, y-axis, value FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., day"},{name:"Y-axis",type:"category",description:"e.g., hour"},{name:"Value",type:"number",description:"e.g., count, intensity"}],description:"Heatmaps visualize data density using color intensity.",docsUrl:"https://docs.semaphor.cloud/docs/charts/heatmap"},bullet:{label:"Bullet Chart",query:"SELECT label, actual, target, [ranges] FROM table",fields:[{name:"Label",type:"category",description:"e.g., metric name"},{name:"Actual",type:"number",description:"current value"},{name:"Target",type:"number",description:"goal value"},{name:"Ranges",type:"number",description:"threshold values",optional:!0}],description:"Bullet charts compare actual performance against targets.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bullet"},text:{label:"Text Visual",query:"SELECT text FROM table LIMIT 1",fields:[{name:"Text",type:"string",description:"content to display"}],description:"Text visuals display dynamic text content from your data.",docsUrl:"https://docs.semaphor.cloud/docs/charts/text"},kpi:{label:"KPI",query:"SELECT current, previous FROM table",fields:[{name:"Current",type:"number",description:"current value"},{name:"Previous",type:"number",description:"comparison value"}],description:"KPI visuals display key performance indicators with comparison values.",docsUrl:"https://docs.semaphor.cloud/docs/charts/kpi"},map:{label:"Map Chart",query:"SELECT country, value FROM table",fields:[{name:"Country/Region",type:"category",description:"geographic identifier"},{name:"Value",type:"number",description:"e.g., population, sales"}],description:"Map charts visualize geographic data using color intensity.",docsUrl:"https://docs.semaphor.cloud/docs/charts/map"},table:{label:"Table",query:"SELECT column1, column2, ... FROM table",fields:[{name:"Columns",type:"category",description:"any data columns"}],description:"Tables display data in rows and columns.",docsUrl:"https://docs.semaphor.cloud/docs/charts/table"},detailTable:{label:"Detail Table",query:"SELECT column1, column2, ... FROM table ORDER BY column1 DESC",fields:[{name:"Columns",type:"category",description:"columns to display (no aggregation)"}],description:"Detail tables display raw records without aggregation. Ideal for event logs, transaction history, and audit trails.",docsUrl:"https://docs.semaphor.cloud/docs/charts/detail-table"}};function ht(t){return _a[t]}function Ha({chartType:t,showDocsLink:n=!0}){const a=ht(t);return a?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Query Format"}),e.jsx("code",{className:"block rounded-md bg-muted/50 px-3 py-2 font-mono text-xs text-foreground",children:a.query})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Fields"}),e.jsx("div",{className:"rounded-md border",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/50",children:[e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Field"}),e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Type"}),e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Description"})]})}),e.jsx("tbody",{children:a.fields.map((r,i)=>e.jsxs("tr",{className:i<a.fields.length-1?"border-b":"",children:[e.jsxs("td",{className:"px-2.5 py-1.5 font-medium text-foreground",children:[r.name,r.optional&&e.jsx("span",{className:"ml-1 text-muted-foreground",children:"?"})]}),e.jsx("td",{className:"px-2.5 py-1.5 font-mono text-muted-foreground",children:r.type}),e.jsx("td",{className:"px-2.5 py-1.5 text-muted-foreground",children:r.description||"—"})]},r.name))})]})})]}),e.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:a.description}),n&&a.docsUrl&&e.jsxs("a",{href:a.docsUrl,target:"_blank",rel:"noopener noreferrer",onClick:r=>r.stopPropagation(),className:"inline-flex items-center gap-1.5 text-xs font-medium text-primary hover:underline",children:["View documentation",e.jsx(s.ExternalLink,{className:"h-3 w-3"})]})]}):null}function Ja({chartType:t}){return ht(t)?e.jsxs(s.HoverCard,{openDelay:200,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded bg-muted px-2 py-0.5 font-mono text-[10px] font-semibold uppercase tracking-wider text-muted-foreground transition-colors hover:bg-muted/80 hover:text-foreground",children:"SQL"})}),e.jsx(s.HoverCardContent,{className:"w-80 p-4",side:"left",align:"start",sideOffset:8,children:e.jsx(Ha,{chartType:t})})]}):null}function Ke({chartType:t,suffix:n="Configuration"}){return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-medium",children:n}),e.jsx(Ja,{chartType:t})]})}function Ya(){return e.jsxs("div",{className:"space-y-6 px-6 py-4",children:[e.jsx(Ke,{chartType:"kpi"}),e.jsx("section",{children:e.jsx(Ua,{})})]})}function $s({children:t,summary:n,open:a,className:r}){return e.jsxs("details",{open:a,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:n}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}function pt(){const[t,n]=k.useState([]),a=s.useEditorStore(m=>m.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:i}=s.useEditorStore(m=>m.actions),d=s.useEditorStore(m=>m.queryResultColumns);s.useEditorStore(m=>{var p;return(p=m.card.preferences)==null?void 0:p.filterOnClickColumnIndex}),k.useEffect(()=>{d&&n(new Array(d.length).fill(!1))},[d]);function o(m,p){var x,u;p?a!=null&&a.onClickFilter&&((x=a==null?void 0:a.onClickFilter)==null?void 0:x.length)>0?i({...a,onClickFilter:[...a.onClickFilter,{columnIndex:m,expression:""}]}):i({...a,onClickFilter:[{columnIndex:m,expression:""}]}):(i({...a,onClickFilter:(u=a==null?void 0:a.onClickFilter)==null?void 0:u.filter(C=>C.columnIndex!==m)}),n(C=>{const y=[...C];return y[m]=!1,y}))}function c(m,p){var u;const x=(u=a==null?void 0:a.onClickFilter)==null?void 0:u.map(C=>C.columnIndex===m?{...C,expression:p.target.value}:C);i({...a,onClickFilter:x})}function l(m){var p,x,u,C;if(t!=null&&t[m]||(x=(p=a==null?void 0:a.onClickFilter)==null?void 0:p.find(y=>y.columnIndex===m))!=null&&x.expression)return e.jsx(s.Input,{value:(C=(u=a==null?void 0:a.onClickFilter)==null?void 0:u.find(y=>y.columnIndex===m))==null?void 0:C.expression,onChange:y=>c(m,y),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((m,p)=>{var x,u;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((x=a==null?void 0:a.onClickFilter)!=null&&x.find(C=>C.columnIndex===p)),onCheckedChange:C=>o(p,C)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:m}),e.jsx("div",{className:"flex items-center gap-2",children:((u=a==null?void 0:a.onClickFilter)==null?void 0:u.find(C=>C.columnIndex===p))&&e.jsx(s.Pencil,{onClick:()=>{n(C=>{const y=[...C];return y[p]=!C[p],y})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),l(p)]})},m)})})}const Qa=[{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"}],Wa=["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"],Xa=Wa.map(t=>({label:t,value:t}));function Za(){var l,m,p,x,u,C,y,h,g,N,T,B,M,A,j,w,I,f;const t=s.useEditorStore(E=>E.card),n=(m=(l=t==null?void 0:t.preferences)==null?void 0:l.mapVisualOptions)==null?void 0:m.topoJsonUrl,[a,r]=k.useState(((x=(p=t==null?void 0:t.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:x.customTopoJsonUrl)||""),{setCardPreferences:i}=s.useEditorActions(),{data:d}=s.useTopoJson(t),o=Object.keys((d==null?void 0:d.objects)||{}).map(E=>({label:E,value:E}))||[],c=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(Ke,{chartType:"map"}),e.jsx($s,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(Me,{className:"h-9",options:c,onValueChange:E=>{console.log("value",E),i({...t.preferences,mapVisualOptions:{topoJsonUrl:E}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(s.Input,{onChange:E=>{r(E.target.value)},onBlur:()=>{var E;console.log("onBlur",a),i({...t.preferences,mapVisualOptions:{...(E=t.preferences)==null?void 0:E.mapVisualOptions,customTopoJsonUrl:a}})},value:a,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(Me,{className:"h-9",options:o,value:((C=(u=t.preferences)==null?void 0:u.mapVisualOptions)==null?void 0:C.objectKey)||"",label:"Map Object",onValueChange:E=>{var b;i({...t.preferences,mapVisualOptions:{...(b=t.preferences)==null?void 0:b.mapVisualOptions,objectKey:E}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(Me,{className:"h-9",options:Qa,value:((h=(y=t.preferences)==null?void 0:y.mapVisualOptions)==null?void 0:h.projection)||"",label:"Projection",onValueChange:E=>{var b;i({...t.preferences,mapVisualOptions:{...(b=t.preferences)==null?void 0:b.mapVisualOptions,projection:E}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(Me,{className:"h-9",options:Xa,value:((N=(g=t.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:N.colorScale)||"",label:"Select Color Scale",onValueChange:E=>{var b;i({...t.preferences,mapVisualOptions:{...(b=t.preferences)==null?void 0:b.mapVisualOptions,colorScale:E}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx($s,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:.1,value:((B=(T=t.preferences)==null?void 0:T.mapVisualOptions)==null?void 0:B.projectionScale)||1,onChange:E=>{var b;i({...t.preferences,mapVisualOptions:{...(b=t.preferences)==null?void 0:b.mapVisualOptions,projectionScale:Number(E.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((j=(A=(M=t.preferences)==null?void 0:M.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:j[0])||0,onChange:E=>{var b,D,F,V;i({...t.preferences,mapVisualOptions:{...(b=t.preferences)==null?void 0:b.mapVisualOptions,projectionOffset:[Number(E.target.value),((V=(F=(D=t.preferences)==null?void 0:D.mapVisualOptions)==null?void 0:F.projectionOffset)==null?void 0:V[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((f=(I=(w=t.preferences)==null?void 0:w.mapVisualOptions)==null?void 0:I.projectionOffset)==null?void 0:f[1])||0,onChange:E=>{var b,D,F,V;i({...t.preferences,mapVisualOptions:{...(b=t.preferences)==null?void 0:b.mapVisualOptions,projectionOffset:[((V=(F=(D=t.preferences)==null?void 0:D.mapVisualOptions)==null?void 0:F.projectionOffset)==null?void 0:V[0])||0,Number(E.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(pt,{})]})}function ft({color:t,onColorChange:n,onClose:a}){const[r,i]=k.useState(0),[d,o]=k.useState(100),[c,l]=k.useState(50),[m,p]=k.useState(t);k.useEffect(()=>{const g=qs(t);if(g){const N=Gs(g.r,g.g,g.b);i(N.h),o(N.s),l(N.l),p(t)}},[t]);const x=g=>{i(g),C(g,d,c)},u=g=>{const N=g.currentTarget.getBoundingClientRect(),T=Math.max(0,Math.min(1,(g.clientX-N.left)/N.width)),B=Math.max(0,Math.min(1,(g.clientY-N.top)/N.height)),M=T*100,A=(1-B)*100;o(M),l(A),C(r,M,A)},C=(g,N,T)=>{const B=sn(g,N,T),M=en(B.r,B.g,B.b);p(M)},y=g=>{if(p(g),/^#[0-9A-Fa-f]{6}$/.test(g)){const N=qs(g);if(N){const T=Gs(N.r,N.g,N.b);i(T.h),o(T.s),l(T.l)}}},h=()=>{/^#[0-9A-Fa-f]{6}$/.test(m)&&(n(m),a())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:u,onMouseMove:g=>{g.buttons===1&&u(g)},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:m}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:g=>x(Number(g.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,{value:m,onChange:g=>y(g.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:m}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(s.Button,{variant:"outline",onClick:a,children:"Cancel"}),e.jsx(s.Button,{onClick:h,children:"OK"})]})]})}function qs(t){const n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return n?{r:parseInt(n[1],16),g:parseInt(n[2],16),b:parseInt(n[3],16)}:null}function en(t,n,a){return"#"+((1<<24)+(t<<16)+(n<<8)+a).toString(16).slice(1)}function Gs(t,n,a){t/=255,n/=255,a/=255;const r=Math.max(t,n,a),i=Math.min(t,n,a);let d=0,o=0;const c=(r+i)/2;if(r!==i){const l=r-i;switch(o=c>.5?l/(2-r-i):l/(r+i),r){case t:d=((n-a)/l+(n<a?6:0))/6;break;case n:d=((a-t)/l+2)/6;break;case a:d=((t-n)/l+4)/6;break}}return{h:Math.round(d*360),s:Math.round(o*100),l:Math.round(c*100)}}function sn(t,n,a){t/=360,n/=100,a/=100;let r,i,d;if(n===0)r=i=d=a;else{const o=(m,p,x)=>(x<0&&(x+=1),x>1&&(x-=1),x<.16666666666666666?m+(p-m)*6*x:x<.5?p:x<.6666666666666666?m+(p-m)*(.6666666666666666-x)*6:m),c=a<.5?a*(1+n):a+n-a*n,l=2*a-c;r=o(l,c,t+1/3),i=o(l,c,t),d=o(l,c,t-1/3)}return{r:Math.round(r*255),g:Math.round(i*255),b:Math.round(d*255)}}const Ks=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],tn=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function Fe({value:t,onChange:n,label:a}){const[r,i]=k.useState(!1),[d,o]=k.useState(!1),c=()=>{const l=Ks.find(m=>m.value===t);return l?l.color:t.startsWith("#")?t:Ks[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:i,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 ${a}`})}),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:tn.map(l=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",c()===l?"border-gray-900":"border-transparent"),style:{backgroundColor:l},onClick:()=>{n(l),i(!1)},children:e.jsx("span",{className:"sr-only",children:l})},l))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{o(!0),i(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a})]}),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:()=>o(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(ft,{color:c(),onColorChange:l=>{n(l),o(!1)},onClose:()=>o(!1)})})]})]})}const an=["auto","number","currency","percent","scientific","date"],nn=[{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"}],rn=[{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"}],ln=t=>t.charAt(0).toUpperCase()+t.slice(1);function Ue({formatOptions:t={},onFormatOptionsChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const i=t.type||"auto",d=(c,l)=>{n({...t,[c]:l})},o=()=>i==="currency"?2:i==="percent"?1:0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[a&&e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(s.Select,{value:i,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:an.map(c=>e.jsx(s.SelectItem,{value:c,className:"text-xs",children:c==="auto"?"Auto (Default)":ln(c)},c))})]})]}),i!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent"].includes(i)&&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,{type:"number",min:"0",max:"10",placeholder:"0",value:t.decimalPlaces??o(),onChange:c=>d("decimalPlaces",parseInt(c.target.value)||0),className:"h-8 text-xs"})})]}),i==="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:nn.map(c=>e.jsx(s.SelectItem,{value:c.value,className:"text-xs",children:c.label},c.value))})]})]}),["number","currency"].includes(i)&&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:rn.map(c=>e.jsx(s.SelectItem,{value:c.value,className:"text-xs",children:c.label},c.value))})]})]}),i==="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,{placeholder:"e.g., $",value:t.prefix||"",onChange:c=>d("prefix",c.target.value),className:"h-8 text-xs"})})]}),i==="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,{placeholder:"e.g., units",value:t.suffix||"",onChange:c=>d("suffix",c.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(i)&&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)})]}),i==="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,{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"})})]}),i==="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,{type:"text",placeholder:"MM/DD/YYYY",value:t.dateFormat||"",onChange:c=>d("dateFormat",c.target.value),className:"h-8 text-xs"})})]})]})]})}function on(){const t=s.useDashboardStore(c=>c.dashboard.filters),n=s.useEditorStore(c=>c.frame),{setFrame:a}=s.useEditorActions(),{columns:r}=s.useColumns(),{assignFilter:i}=s.useAssignFilter();function d(c){const l=i(c,"frame");a({...n,filterId:l})}const o=t==null?void 0:t.find(c=>c.id===n.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(cn,{onSelect:d,columns:r}),o&&e.jsx(s.FilterHeader,{filter:o})]})}function cn({columns:t,onSelect:n}){var o;const[a,r]=os.useState(!1),[i,d]=os.useState("");return e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between font-normal",children:[i?((o=t.find(c=>c.name===i))==null?void 0:o.label)||i:"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 column found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(c=>e.jsxs(s.CommandItem,{value:c.name,onSelect:l=>{const m=l===i?"":l;d(m),r(!1),m&&n(c)},children:[c.label||c.name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",i===c.name?"opacity-100":"opacity-0")})]},c.id))})]})]})})]})}const dn=[{value:"difference",label:"Difference"},{value:"change",label:"Change (%)"},{value:"change_difference",label:"Change + Difference"},{value:"ratio",label:"Ratio"}],un=[{value:"arrow_badge",label:"Arrow + Badge"},{value:"arrow",label:"Arrow Only"},{value:"badge",label:"Badge Only"},{value:"none",label:"None"}];function mn({cardType:t="table"}){var p,x,u,C,y;const n=s.useEditorStore(h=>h.card),a=s.useEditorStore(h=>{var g;return(g=h.card)==null?void 0:g.preferences}),r=s.useEditorStore(h=>h.actions.setCardPreferences),d=(((p=n.config)==null?void 0:p.metricColumns)||[]).some(h=>h.comparisonType&&h.comparisonType!=="none"),o=((x=a==null?void 0:a.tableVisualOptions)==null?void 0:x.metricComparison)||{},c=h=>{r({...a,tableVisualOptions:{...a==null?void 0:a.tableVisualOptions,metricComparison:{...o,...h}}})},l={increase:((u=o.colors)==null?void 0:u.increase)||"green",decrease:((C=o.colors)==null?void 0:C.decrease)||"red",neutral:((y=o.colors)==null?void 0:y.neutral)||"neutral"},m=h=>{r({...a,allowDownload:h})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsxs(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:[d&&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(tt,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison Settings"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated As"}),e.jsxs(s.Select,{value:o.calculatedAs||"change_difference",onValueChange:h=>c({calculatedAs:h}),children:[e.jsx(s.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:dn.map(h=>e.jsx(s.SelectItem,{value:h.value,className:"text-xs",children:h.label},h.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Number Format"}),e.jsx(Ue,{formatOptions:o.formatOptions||{},onFormatOptionsChange:h=>c({formatOptions:h}),showTitle:!1})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator Style"}),e.jsxs(s.Select,{value:o.indicatorStyle||"arrow_badge",onValueChange:h=>c({indicatorStyle:h}),children:[e.jsx(s.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:un.map(h=>e.jsx(s.SelectItem,{value:h.value,className:"text-xs",children:h.label},h.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Colors"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Fe,{value:l.increase,onChange:h=>c({colors:{...l,increase:h}}),label:"Increase"}),e.jsx(Fe,{value:l.decrease,onChange:h=>c({colors:{...l,decrease:h}}),label:"Decrease"}),e.jsx(Fe,{value:l.neutral,onChange:h=>c({colors:{...l,neutral:h}}),label:"No Change"})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Lower is Better"}),e.jsx(s.Checkbox,{checked:o.lowerIsBetter||!1,onCheckedChange:h=>c({lowerIsBetter:!!h})})]})]})]}),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(pt,{}),e.jsx(on,{})]})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{onCheckedChange:m,id:"allow-download"}),e.jsx("label",{htmlFor:"allow-download",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Allow Download"})]})]})}function xn(){var r;const t=s.useEditorStore(i=>i.card.preferences),{setCardPreferences:n}=s.useEditorStore(i=>i.actions);function a(i){n({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:i==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:a,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(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 hn(){return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(Ke,{chartType:"text"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Text Type"}),e.jsx(xn,{})]})]})}const pn=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function fn(){var A,j,w,I,f,E,b,D,F,V;const t=s.useEditorStore(S=>S.card),n=s.useEditorStore(S=>{var L;return(L=S.card)==null?void 0:L.preferences}),a=fe.useEffectiveEditorCardType(),{setCardPreferences:r,updateCardInFrame:i}=s.useEditorActions(),d=k.useMemo(()=>a!==t.type?{...t,type:a}:t,[t,a]),{data:o}=s.useDashboardCardQuery(d),[c,l]=k.useState({}),[m,p]=k.useState(null),[x,u]=k.useState(null),C=k.useMemo(()=>{var O,R,P,U,q,_,W;if(!(o!=null&&o.records)||o.records.length===0)return[];const S=a==="stackedBar"||a==="stackedLine",L=a==="bar"||a==="line"||a==="horizontalBar"||a==="bullet"||a==="combo"||a==="area"||a==="stackedArea",v=((O=t==null?void 0:t.config)==null?void 0:O.pivotByColumns)&&t.config.pivotByColumns.length>0;if((S||L)&&v){if(o.pivotSchema&&Array.isArray(o.pivotSchema)){const J=new Set;return o.pivotSchema.forEach(ee=>{ee.alias&&J.add(ee.alias)}),Array.from(J)}if(o.records.length>0){const J=o.records[0],ee=Object.keys(J),$=new Set;(R=t==null?void 0:t.config)!=null&&R.groupByColumns&&t.config.groupByColumns.forEach(ne=>{$.add(ne.label||ne.name),$.add(ne.alias||ne.name)});const Y=new Set;return(P=t==null?void 0:t.config)!=null&&P.metricColumns&&t.config.metricColumns.forEach(ne=>{const K=ne.alias||ne.name;Y.add(K),Y.add(`${K}_count`),Y.add(`${K}_sum`),Y.add(`${K}_avg`),Y.add(`${K}_min`),Y.add(`${K}_max`);const re=ne.entityName||ne.qualifiedEntityName;re&&(Y.add(`${re}_${K}`),Y.add(`${re}_${K}_count`))}),ee.filter(ne=>!$.has(ne)&&!Y.has(ne))}}if((L||S)&&!v&&((q=(U=t==null?void 0:t.config)==null?void 0:U.metricColumns)!=null&&q.length))return t.config.metricColumns.map(J=>J.alias||J.label||J.name);if((W=(_=t==null?void 0:t.config)==null?void 0:_.groupByColumns)!=null&&W.length){const J=t.config.groupByColumns[0],ee=J.label||J.name,$=new Set;return o.records.forEach(Y=>{const H=Y[ee];H!=null&&$.add(String(H))}),Array.from($)}return[]},[o,(A=t==null?void 0:t.config)==null?void 0:A.groupByColumns,(j=t==null?void 0:t.config)==null?void 0:j.pivotByColumns,(w=t==null?void 0:t.config)==null?void 0:w.metricColumns,t==null?void 0:t.type]),y=k.useMemo(()=>s.getDefaultChartColors(),[]);k.useEffect(()=>{const S={};C.forEach((L,v)=>{S[L]=s.getColorForValue(L,v,n==null?void 0:n.colorConfig)}),l(S)},[C,n==null?void 0:n.colorConfig,y]);const h=(S,L)=>{const v={...c,[S]:L};l(v);const O={...n||{},colorConfig:{segments:v}};r(O);const R={...t,preferences:O};i(R)},g=(S,L)=>{var q;const v=y[L%y.length],{[S]:O,...R}=((q=n==null?void 0:n.colorConfig)==null?void 0:q.segments)||{},P={...n||{},colorConfig:{segments:R}};r(P);const U={...t,preferences:P};i(U),l(_=>({..._,[S]:v}))};if(!C.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((f=(I=t==null?void 0:t.config)==null?void 0:I.groupByColumns)==null?void 0:f.length)||((b=(E=t==null?void 0:t.config)==null?void 0:E.pivotByColumns)==null?void 0:b.length):(F=(D=t==null?void 0:t.config)==null?void 0:D.groupByColumns)==null?void 0:F.length)||["table","kpi","text","custom","heatmap"].includes(a))return null;const B=()=>{const S={...n||{},colorConfig:{segments:{}}};r(S);const L={...t,preferences:S};i(L);const v={};C.forEach((O,R)=>{v[O]=s.getColorForValue(O,R,void 0)}),l(v)},M=Object.keys(((V=n==null?void 0:n.colorConfig)==null?void 0:V.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(ta,{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:M&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:B,children:[e.jsx(Fs,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:C.map((S,L)=>{const v=s.isDefaultColor(c[S],L),O=!v;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:m===S,onOpenChange:R=>p(R?S: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:c[S]}})}),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:y.slice(0,10).map((R,P)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",c[S]===R?"border-gray-900":"border-transparent"),style:{backgroundColor:R},onClick:()=>{h(S,R),p(null)},children:[P===L%y.length&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-white/90 px-0.5 text-[8px] font-bold text-gray-900 shadow-sm",children:"D"})}),e.jsx("span",{className:"sr-only",children:R})]},`default-${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:pn.map((R,P)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",c[S]===R?"border-2 border-gray-900":R==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:R},onClick:()=>{h(S,R),p(null)},children:e.jsx("span",{className:"sr-only",children:R})},`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:()=>{u({value:S,color:c[S]}),p(null)},children:"Custom color"}),!v&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{g(S,L),p(null)},children:[e.jsx(Fs,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:S}),O&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},S)})}),x&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>u(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(ft,{color:x.color,onColorChange:S=>{h(x.value,S),u(null)},onClose:()=>u(null)})})]})]})})]})}function we({value:t,onSave:n,placeholder:a="",type:r="text",className:i=""}){const[d,o]=k.useState(t??""),[c,l]=k.useState(!1);k.useEffect(()=>{o(t??"")},[t]);const m=()=>{n(d),l(!1)},p=()=>{o(t??""),l(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${i}`,children:[e.jsx(s.Input$1,{placeholder:a,type:r,value:c?d:t??"",onChange:x=>{o(x.target.value),l(!0)},onFocus:()=>l(!0),onClick:x=>x.stopPropagation(),className:"h-8 text-xs",onPointerDown:x=>x.stopPropagation(),onKeyDown:x=>{x.stopPropagation(),x.key==="Enter"&&c&&d!==t?m():x.key==="Escape"&&p()},"aria-label":a||"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:m,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:p,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function ts({axis:t,label:n,type:a,config:r,onChange:i,defaultTitle:d,hidePosition:o}){var C,y,h,g,N,T,B,M,A,j,w,I,f,E;const c=(b,D)=>{i({...r??{},[b]:D})},l=(b,D)=>{var L,v,O,R;const F=b==="enabled"&&D===!0,V=(L=r==null?void 0:r.name)==null?void 0:L.text,S=F&&!V&&d;i({...r??{},name:{...r==null?void 0:r.name,enabled:b==="enabled"?D:((v=r==null?void 0:r.name)==null?void 0:v.enabled)??!1,text:b==="text"?D:S?d:V,fontSize:b==="fontSize"?D:(O=r==null?void 0:r.name)==null?void 0:O.fontSize,fontWeight:b==="fontWeight"?D:(R=r==null?void 0:r.name)==null?void 0:R.fontWeight}})},m=(b,D)=>{var F,V;i({...r??{},labels:{enabled:b==="enabled"?D:((F=r==null?void 0:r.labels)==null?void 0:F.enabled)??!0,rotation:b==="rotation"?D:(V=r==null?void 0:r.labels)==null?void 0:V.rotation}})},p=(b,D)=>{i({...r??{},scale:{...r==null?void 0:r.scale,[b]:D===""?"auto":Number(D)}})},x=t==="x"?["auto","top","bottom"]:["auto","left","right"],u=["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:n})})}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:b=>c("enabled",b),onClick:b=>b.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 gap-2",children:[e.jsx(s.Checkbox,{id:`${t}-title-enabled`,checked:((C=r==null?void 0:r.name)==null?void 0:C.enabled)??!1,onCheckedChange:b=>l("enabled",b===!0)}),e.jsx(s.Label,{htmlFor:`${t}-title-enabled`,className:"text-xs font-medium cursor-pointer",children:"TITLE"})]}),((y=r==null?void 0:r.name)==null?void 0:y.enabled)&&e.jsxs("div",{className:"space-y-2 pl-6",children:[e.jsx(we,{placeholder:`${n} title`,value:((h=r==null?void 0:r.name)==null?void 0:h.text)||"",onSave:b=>l("text",b),className:""}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Size"}),e.jsx("div",{className:"w-14",children:e.jsx(we,{type:"number",placeholder:"12",value:String(((g=r==null?void 0:r.name)==null?void 0:g.fontSize)||12),onSave:b=>l("fontSize",Number(b)||12),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Weight"}),e.jsxs(s.Select,{value:((N=r==null?void 0:r.name)==null?void 0:N.fontWeight)||"normal",onValueChange:b=>l("fontWeight",b),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:"normal",className:"text-xs",children:"Normal"}),e.jsx(s.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]})]})]})]}),!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:(r==null?void 0:r.position)||"auto",onValueChange:b=>c("position",b),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:x.map(b=>e.jsx(s.SelectItem,{value:b,className:"text-xs",children:b==="auto"?"Auto (Default)":s.titleCase(b)},b))})]})]}),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:((T=r==null?void 0:r.labels)==null?void 0:T.enabled)!==!1,onCheckedChange:b=>m("enabled",b)})]}),((B=r==null?void 0:r.labels)==null?void 0:B.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(((M=r==null?void 0:r.labels)==null?void 0:M.rotation)||"auto"),onValueChange:b=>m("rotation",b==="auto"?"auto":Number(b)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(b=>e.jsx(s.SelectItem,{value:b,className:"text-xs",children:b==="auto"?"Auto (Default)":`${b}°`},b))})]})]})]}),a==="value"&&e.jsx(Ue,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:b=>i({...r,formatOptions:b}),showTitle:!0,title:"FORMAT"}),a==="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(we,{type:"number",placeholder:"auto",value:((A=r==null?void 0:r.scale)==null?void 0:A.min)==="auto"||((j=r==null?void 0:r.scale)==null?void 0:j.min)===void 0?"":String(r.scale.min),onSave:b=>p("min",b),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(we,{type:"number",placeholder:"auto",value:((w=r==null?void 0:r.scale)==null?void 0:w.max)==="auto"||((I=r==null?void 0:r.scale)==null?void 0:I.max)===void 0?"":String(r.scale.max),onSave:b=>p("max",b),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(we,{type:"number",placeholder:"auto",value:((f=r==null?void 0:r.scale)==null?void 0:f.stepSize)==="auto"||((E=r==null?void 0:r.scale)==null?void 0:E.stepSize)===void 0?"":String(r.scale.stepSize),onSave:b=>p("stepSize",b),className:""})})]})]})]})]})]})}function as(t,n,a){var d,o,c;if(t==="x"){const l=(o=(d=n==null?void 0:n.config)==null?void 0:d.groupByColumns)==null?void 0:o[0];return(l==null?void 0:l.label)||(l==null?void 0:l.name)||""}const r=((c=n==null?void 0:n.config)==null?void 0:c.metricColumns)||[],i=(a==null?void 0:a.datasetOptions)||[];if(t==="y"){const l=r.filter((m,p)=>{const x=i.find(u=>u.idx===p);return!x||x.yAxisId!=="y2"});return l.length===1&&(l[0].label||l[0].name)||""}if(t==="y2"){const l=r.filter((m,p)=>{const x=i.find(u=>u.idx===p);return(x==null?void 0:x.yAxisId)==="y2"});return l.length===1&&(l[0].label||l[0].name)||""}return""}function gn(){const t=s.useEditorStore(l=>l.card),n=s.useEditorStore(l=>{var m;return(m=l.card)==null?void 0:m.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions(),i=fe.useEffectiveEditorCardType();if(!t||["tornado","pyramid","kpi","treemap"].includes(i))return null;const d=s.AxisConfigurator.getAxisInfo(i,n);if(!d.hasXAxis&&!d.hasYAxis)return null;const o=(l,m)=>{let p;l==="x"?p="xAxisConfig":l==="y"?p="yAxisConfig":p="secondaryYAxisConfig";const x={...n||{},[p]:m};a(x);const u={...t,preferences:x};r(u)},c=d.hasY2Axis&&i==="combo";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(at,{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:[d.hasXAxis&&e.jsx(ts,{axis:"x",label:"X-Axis",type:d.xAxisType,config:s.mergeAxisConfig(s.getDefaultAxisConfig(i,"x"),n==null?void 0:n.xAxisConfig),onChange:l=>o("x",l),defaultTitle:as("x",t,n)}),d.hasYAxis&&e.jsx(ts,{axis:"y",label:c?"Y-Axis (Left)":"Y-Axis",type:d.yAxisType,config:s.mergeAxisConfig(s.getDefaultAxisConfig(i,"y"),n==null?void 0:n.yAxisConfig),onChange:l=>o("y",l),defaultTitle:as("y",t,n)}),c&&e.jsx(ts,{axis:"y2",label:"Y2-Axis (Right)",type:"value",config:s.mergeAxisConfig({enabled:!0,position:"right"},n==null?void 0:n.secondaryYAxisConfig),onChange:l=>o("y2",l),defaultTitle:as("y2",t,n),hidePosition:!0})]})})]})}function jn(){const t=s.useEditorStore(x=>x.card),n=fe.useEffectiveEditorCardType(),a=s.useEditorStore(x=>{var u,C,y,h;return(h=(y=(C=(u=x.card)==null?void 0:u.preferences)==null?void 0:C.chartOptions)==null?void 0:y.plugins)==null?void 0:h.legend}),{setLegendOptions:r}=s.useEditorActions();if(!t||!s.chartSupportsLegend(n))return null;const i=s.getDefaultLegendConfig(n),d=(i==null?void 0:i.display)??!0,o=(i==null?void 0:i.position)??"top",c=(i==null?void 0:i.align)??"center",l=(x,u)=>{const C={...a,[x]:u};r(C)},m=["top","bottom","left","right"],p=["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(Wt,{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)??d,onCheckedChange:x=>l("display",x)})]}),((a==null?void 0:a.display)??d)&&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)||o,onValueChange:x=>l("position",x),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:m.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)||c,onValueChange:x=>l("align",x),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:p.map(x=>e.jsx(s.SelectItem,{value:x,className:"text-xs",children:s.titleCase(x)},x))})]})]})]})]})})]})}function bn(){var L,v,O,R,P,U,q,_,W,J,ee;const t=s.useEditorStore($=>$.card),n=fe.useEffectiveEditorCardType(),a=s.useEditorStore($=>{var Y,H;return(H=(Y=$.card)==null?void 0:Y.preferences)==null?void 0:H.dataLabelsConfig}),r=s.useEditorStore($=>{var Y;return(Y=$.card)==null?void 0:Y.preferences}),{setCardPreferences:i,updateCardInFrame:d}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(n))return null;const o=n==="bullet"?((L=r==null?void 0:r.bulletConfig)==null?void 0:L.orientation)??(((v=r==null?void 0:r.chartOptions)==null?void 0:v.indexAxis)==="x"?"vertical":"horizontal"):void 0,c=o!=null?o==="horizontal":((O=r==null?void 0:r.chartOptions)==null?void 0:O.indexAxis)==="y",l=n==="stackedBar"||n==="stackedLine",m=n==="pie"||n==="doughnut"||n==="polarArea"||n==="funnel",p=!m,x=n==="bubble"||n==="scatter",u=(P=(R=r==null?void 0:r.chartOptions)==null?void 0:R.plugins)==null?void 0:P.datalabels,C=(u==null?void 0:u.display)!==!1&&((u==null?void 0:u.anchor)||(u==null?void 0:u.align)),y=s.getDefaultDataLabelsConfig(n,t.preferences),h=a??y,g=(y==null?void 0:y.enabled)??C??!1,N=(a==null?void 0:a.enabled)!==void 0?a.enabled:g,T=($,Y)=>{const K={...y??{},...a??{},[$]:Y};$==="enabled"&&(K.display=Y,Y&&x&&!K.position&&(K.position="bottom")),$==="position"&&x&&(K.position="bottom");const re={...t.preferences||{},dataLabelsConfig:K};i(re);const de={...t,preferences:re};d(de)},B=($,Y)=>{const H=a??{},K={...y??{},...H,font:{...H.font||{},[$]:Y}},re={...t.preferences||{},dataLabelsConfig:K};i(re);const de={...t,preferences:re};d(de)},M=($,Y)=>{const H=a??{},K={...y??{},...H,formatOptions:{...H.formatOptions||{},[$]:Y}},re={...t.preferences||{},dataLabelsConfig:K};i(re);const de={...t,preferences:re};d(de)},A=()=>{const $=n;return $==="stackedBar"||$==="stackedLine"||$==="pie"||$==="doughnut"?"center":c?"right":"top"},j=n!=="treemap"&&n!=="heatmap",w=n!=="treemap",I=A();let f=[];if(j)if(x)f=["bottom"];else if(l||m)f=["center"];else{const $=c?["center","left","right"]:["center","top","bottom"];f=["auto",...n==="bullet"?$:$.filter(H=>H!==I),"custom"]}const E=()=>s.titleCase(I),b=["center","start","end"],D=["center","start","end","top","bottom"],F=p?["auto","number","currency","percent","none"]:["number","currency","percent","none"],V=[{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"}],S=[{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(ca,{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:N,onCheckedChange:$=>T("enabled",$)})]}),N&&e.jsxs(e.Fragment,{children:[j&&!l&&!m&&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?(h==null?void 0:h.position)||"bottom":(h==null?void 0:h.position)||"auto",onValueChange:$=>T("position",$),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:f.map($=>e.jsx(s.SelectItem,{value:$,className:"text-xs",children:$==="auto"?E():$==="custom"?"Custom (Advanced)":s.titleCase($)},$))})]})]}),l&&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:$=>T("showTotal",$)})]}),(h==null?void 0:h.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:(h==null?void 0:h.anchor)||"center",onValueChange:$=>T("anchor",$),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:b.map($=>e.jsx(s.SelectItem,{value:$,className:"text-xs",children:s.titleCase($)},$))})]})]}),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((h==null?void 0:h.align)||"center"),onValueChange:$=>T("align",$),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:D.map($=>e.jsx(s.SelectItem,{value:$,className:"text-xs",children:s.titleCase($)},$))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(h==null?void 0:h.format)||(p?"auto":"none"),onValueChange:$=>T("format",$),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:F.map($=>e.jsx(s.SelectItem,{value:$,className:"text-xs",children:$==="auto"&&p?"Auto (Use Axis)":$==="none"?"None (Raw Value)":s.titleCase($)},$))})]})]}),(h==null?void 0:h.format)&&!["auto","none"].includes(h.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(h.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(we,{type:"number",placeholder:"0",value:String(((U=h==null?void 0:h.formatOptions)==null?void 0:U.decimalPlaces)??(h.format==="currency"?2:h.format==="percent"?1:0)),onSave:$=>M("decimalPlaces",Number($)),className:""})})]}),h.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:((q=h==null?void 0:h.formatOptions)==null?void 0:q.currency)||"USD",onValueChange:$=>M("currency",$),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:V.map($=>e.jsx(s.SelectItem,{value:$.value,className:"text-xs",children:$.label},$.value))})]})]}),["number","currency"].includes(h.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:((_=h==null?void 0:h.formatOptions)==null?void 0:_.useSuffix)??!1,onCheckedChange:$=>M("useSuffix",$)})]}),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:((W=h==null?void 0:h.formatOptions)==null?void 0:W.locale)||"en-US",onValueChange:$=>M("locale",$),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:S.map($=>e.jsx(s.SelectItem,{value:$.value,className:"text-xs",children:$.label},$.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(we,{type:"number",placeholder:"12",value:String(((J=h==null?void 0:h.font)==null?void 0:J.size)||12),onSave:$=>B("size",Number($)),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:((ee=h==null?void 0:h.font)==null?void 0:ee.weight)||"normal",onValueChange:$=>B("weight",$),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:(h==null?void 0:h.color)==="auto"||!(h!=null&&h.color)?"auto":"custom",onValueChange:$=>{$==="auto"&&T("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(we,{type:"number",placeholder:"0",value:String((h==null?void 0:h.rotation)||0),onSave:$=>T("rotation",Number($)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}const Us={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%
164
+ 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 u,C,y,h,g,N,T,B,M,A;const t=s.useEditorStore(j=>j.card),{setCardPreferences:n}=s.useEditorActions(),a=fe.useEffectiveEditorCardType(),r=((u=t.config)==null?void 0:u.metricColumns)||[],i=((C=t.config)==null?void 0:C.groupByColumns)||[],d=r.length===2&&i.length===0,o=r.some(j=>j.comparisonType&&j.comparisonType!=="none");if(!(a==="kpi"&&(d||o)))return null;const l=((h=(y=t.preferences)==null?void 0:y.kpiVisualOptions)==null?void 0:h.metricComparison)||{},m=j=>{var I;const w={...t.preferences,kpiVisualOptions:{...(I=t.preferences)==null?void 0:I.kpiVisualOptions,metricComparison:{...l,...j}}};n(w)},p=o||l.enabled,x=r.some(j=>j.comparisonType==="previous_period"||j.comparisonType==="same_period_last_year"||j.comparisonType==="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(tt,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[d&&r.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:l.enabled||!1,onCheckedChange:j=>m({enabled:j,...j&&!l.calculationType?{calculationType:"difference"}:{}})})]}),p&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(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 j=l.calculationType||"difference",w=Us[j];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:w==null?void 0:w.label}),e.jsx("p",{children:w==null?void 0:w.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:w==null?void 0:w.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",w==null?void 0:w.example]})]})})()})]})]}),e.jsxs(s.Select,{value:l.calculationType||"difference",onValueChange:j=>m({calculationType:j}),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(Us).map(([j,w])=>e.jsx(s.SelectItem,{value:j,className:"text-xs",children:w.label},j))})]})]}),e.jsx(Ue,{formatOptions:l.formatOptions||{},onFormatOptionsChange:j=>m({formatOptions:j}),showTitle:!0,title:"COMPARISON FORMAT"}),(x||d)&&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"}),d&&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:l.position||"right",onValueChange:j=>m({position:j}),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:l.showArrow!==!1,onCheckedChange:j=>m({showArrow:j})}),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:l.showColor!==!1,onCheckedChange:j=>m({showColor:j})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),l.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(Fe,{value:((g=l.colorConfig)==null?void 0:g.increase)||"green",onChange:j=>m({colorConfig:{...l.colorConfig,increase:j}}),label:"Primary > Secondary"}),e.jsx(Fe,{value:((N=l.colorConfig)==null?void 0:N.decrease)||"red",onChange:j=>m({colorConfig:{...l.colorConfig,decrease:j}}),label:"Primary < Secondary"}),e.jsx(Fe,{value:((T=l.colorConfig)==null?void 0:T.noChange)||"neutral",onChange:j=>m({colorConfig:{...l.colorConfig,noChange:j}}),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:l.conditionalLabel||!1,onCheckedChange:j=>m({conditionalLabel:j})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),l.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(s.Input,{id:"label-increase",type:"text",value:((B=l.conditionalLabels)==null?void 0:B.increase)??"Increase",onChange:j=>m({conditionalLabels:{...l.conditionalLabels,increase:j.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,{id:"label-decrease",type:"text",value:((M=l.conditionalLabels)==null?void 0:M.decrease)??"Decrease",onChange:j=>m({conditionalLabels:{...l.conditionalLabels,decrease:j.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,{id:"label-no-change",type:"text",value:((A=l.conditionalLabels)==null?void 0:A.noChange)??"No change",onChange:j=>m({conditionalLabels:{...l.conditionalLabels,noChange:j.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,{id:"label-name",type:"text",value:l.labelName??"",onChange:j=>m({labelName:j.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function vn(){var d,o;const t=s.useEditorStore(c=>c.card),{setCardPreferences:n}=s.useEditorActions();if(fe.useEffectiveEditorCardType()!=="kpi")return null;const r=((o=(d=t.preferences)==null?void 0:d.kpiVisualOptions)==null?void 0:o.formatOptions)||{},i=c=>{var m;const l={...t.preferences,kpiVisualOptions:{...(m=t.preferences)==null?void 0:m.kpiVisualOptions,formatOptions:c}};n(l)};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(Ue,{formatOptions:r,onFormatOptionsChange:i,showTitle:!1})})]})}function Nn(){var d;const t=s.useEditorStore(o=>{var c;return(c=o.card)==null?void 0:c.type}),n=s.useEditorStore(o=>{var c;return(c=o.card)==null?void 0:c.preferences}),{setCardPreferences:a}=s.useEditorActions();if(t!=="treemap")return null;const r=((d=n==null?void 0:n.chartOptions)==null?void 0:d.treemapColorMode)??"branch",i=o=>{const c={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,treemapColorMode:o}};a(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:o=>i(o??"branch"),className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(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."})]})]})]})})]})}const Cn=Object.keys(s.HEATMAP_PRESET_PALETTES);function Sn(){const t=s.useEditorStore(u=>u.card),n=s.useEditorStore(u=>{var C;return(C=u.card)==null?void 0:C.preferences}),{setCardPreferences:a}=s.useEditorActions(),r=(t==null?void 0:t.type)==="heatmap",i=(n==null?void 0:n.heatmapConfig)||{},d=i.colorPalette??"green",o=i.legendPosition??"bottom",c=k.useMemo(()=>i.colorRange&&i.colorRange[0]&&i.colorRange[1]?[i.colorRange[0],i.colorRange[1]]:[...s.DEFAULT_HEATMAP_CUSTOM_RANGE],[i.colorRange]),l=u=>{const C={...i,...u};C.colorPalette!=="custom"?delete C.colorRange:(!C.colorRange||!C.colorRange[0]||!C.colorRange[1])&&(C.colorRange=[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]),a({...n||{},heatmapConfig:C})},m=u=>{l({colorPalette:u,colorRange:u==="custom"?i.colorRange??[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},p=(u,C)=>{const y=[...c];y[u]=C,l({colorPalette:"custom",colorRange:y})},x=u=>{l({legendPosition:u})};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:u=>m(u??"blue"),className:"space-y-3",children:[Cn.map(u=>{const C=s.HEATMAP_PRESET_PALETTES[u];return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:`heatmap-${u}`,value:u}),e.jsxs(s.Label,{htmlFor:`heatmap-${u}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:C.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${C.start}, ${C.end})`}})]})]},u)}),e.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(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(Fe,{value:c[0],onChange:u=>p(0,u),label:"Start color"}),e.jsx(Fe,{value:c[1],onChange:u=>p(1,u),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:o,onValueChange:u=>x(u??"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(u=>e.jsx(s.SelectItem,{value:u,className:"text-xs",children:u[0].toUpperCase()+u.slice(1)},u))})]})]})]})]}):null}const _s=["poor","satisfactory","good"];function Hs(t){if(!t)return;const n={...t};return n.targetMetricKey||delete n.targetMetricKey,n.comparativeMetricKey||delete n.comparativeMetricKey,!n.targetValue&&n.targetValue!==0&&delete n.targetValue,(!n.rangeKeys||Object.keys(n.rangeKeys).length===0)&&delete n.rangeKeys,(!n.ranges||Object.keys(n.ranges).length===0)&&delete n.ranges,(!n.rangeLabels||Object.keys(n.rangeLabels).length===0)&&delete n.rangeLabels,n}function wn(){var F,V;const t=s.useEditorStore(S=>S.card.preferences),n=s.useEditorStore(S=>S.card),a=s.useEditorStore(S=>S.isDevMode),{setCardPreferences:r,setChartOrientation:i}=s.useEditorActions(),d=k.useMemo(()=>(t==null?void 0:t.bulletConfig)||{},[t==null?void 0:t.bulletConfig]),c=s.hasValidCardConfig(n==null?void 0:n.config)&&!a,[l,m]=k.useState(d.showRanges??!1),[p,x]=k.useState(d.rangesArePercentages??!1),u=d.disableAutoComparative?!1:d.comparativeMetricKey!==void 0||!c,[C,y]=k.useState(u);k.useEffect(()=>{m(d.showRanges??!1)},[d.showRanges]),k.useEffect(()=>{x(d.rangesArePercentages??!1)},[d.rangesArePercentages]);const h=d.targetValue===void 0?"":String(d.targetValue);k.useEffect(()=>{const S=d.disableAutoComparative?!1:d.comparativeMetricKey!==void 0||!c;y(S)},[d.disableAutoComparative,d.comparativeMetricKey,c]);const g=k.useMemo(()=>{var S,L;return((L=(S=n==null?void 0:n.config)==null?void 0:S.metricColumns)==null?void 0:L.map(v=>{const O=v.label||v.name||v.alias||"";return{value:O,label:O}}))||[]},[(F=n==null?void 0:n.config)==null?void 0:F.metricColumns]);k.useEffect(()=>{var q,_;if(!t||g.length===0)return;const S={};let L=!1;const v=(q=g[1])==null?void 0:q.value;!d.targetMetricKey&&v&&(S.targetMetricKey=v,L=!0);const O=(_=g[2])==null?void 0:_.value;!d.comparativeMetricKey&&!d.disableAutoComparative&&O&&(S.comparativeMetricKey=O,L=!0);const R=g.slice(3),P={...d.rangeKeys||{}};let U=!1;if(_s.forEach((W,J)=>{!P[W]&&R[J]&&(P[W]=R[J].value,U=!0)}),U&&(S.rangeKeys=P,L=!0,d.showRanges===void 0&&(S.showRanges=!0)),L){const W=Hs({...d,...S});r({...t,bulletConfig:W})}},[g,d,t,r]);const N=S=>{const L=Hs({...d,...S});r({...t,bulletConfig:L})},T=(S,L)=>{const v={...d.rangeKeys||{},[S]:L.trim()};L.trim()||delete v[S],N({rangeKeys:Object.keys(v).length>0?v:void 0})},B=(S,L)=>{const v=L===""?void 0:Number(L),O={...d.ranges||{}};v===void 0||Number.isNaN(v)?delete O[S]:O[S]=v,N({ranges:Object.keys(O).length?O:void 0})},M=S=>{if(S===""){N({targetValue:void 0});return}const L=Number(S);N({targetValue:Number.isNaN(L)?void 0:L})},A=(S,L)=>{const v=L.trim(),O={...d.rangeLabels||{}};v?O[S]=v:delete O[S],N({rangeLabels:Object.keys(O).length>0?O:void 0})},j=S=>{m(S),N({showRanges:S})},w=S=>{x(S),N({rangesArePercentages:S})},I=d.orientation||(((V=t==null?void 0:t.chartOptions)==null?void 0:V.indexAxis)==="y"?"horizontal":"vertical"),f=S=>{N({orientation:S}),i(S==="horizontal"?"y":"x")},E=[{value:"__none",label:"None"},...g.map(S=>({value:S.value,label:S.label}))],b=E,D=S=>{if(y(S),!S){N({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!c){N({disableAutoComparative:!1});return}if(d.comparativeMetricKey)N({disableAutoComparative:!1});else{const L=g.find(v=>v.value!==d.targetMetricKey);N({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:I,onValueChange:S=>f(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:"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:S=>N({targetMetricKey:S==="__none"?void 0:S}),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"}),g.map(S=>e.jsx(s.SelectItem,{value:S.value,className:"text-xs",children:S.label},S.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:S=>N({comparativeMetricKey:S==="__none"?void 0:S,disableAutoComparative:S==="__none"}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select metric"})}),e.jsx(s.SelectContent,{children:E.map(S=>e.jsx(s.SelectItem,{value:S.value,className:"text-xs",children:S.label},S.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:C,onCheckedChange:S=>D(S)})]}),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(Se,{type:"number",className:"h-8 text-xs",value:h,onCommit:M,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:l,onCheckedChange:j})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:p,disabled:!l,onChange:S=>w(S.target.checked),className:"h-3.5 w-3.5 accent-primary disabled:opacity-50"}),e.jsx("span",{children:"Use % of value"})]})]}),l&&e.jsx("div",{className:"space-y-3",children:_s.map(S=>{var L,v,O,R,P;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:[S," LABEL"]}),e.jsx(Se,{placeholder:`Display label (${S})`,value:((L=d.rangeLabels)==null?void 0:L[S])||"",onCommit:U=>A(S,U),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:[S," COLUMN"]}),e.jsxs(s.Select,{value:((v=d.rangeKeys)==null?void 0:v[S])||"__none",onValueChange:U=>{U==="__none"?T(S,""):T(S,U)},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select column"})}),e.jsx(s.SelectContent,{children:b.map(U=>e.jsx(s.SelectItem,{value:U.value,className:"text-xs",children:U.label},U.value))})]})]}):e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[S," COLUMN KEY"]}),e.jsx(Se,{placeholder:"Column key",value:((O=d.rangeKeys)==null?void 0:O[S])||"",onCommit:U=>T(S,U),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:[S," VALUE"]}),e.jsx(Se,{type:"number",placeholder:p?"0.80":"Static value",value:((R=d.ranges)==null?void 0:R[S])===void 0?"":String((P=d.ranges)==null?void 0:P[S]),onCommit:U=>B(S,U),className:"h-8 text-xs"})]})]},S)})})]})]})]})}function Js(t){if(!t)return;const n={...t};if(n.xMetricKey||delete n.xMetricKey,n.yMetricKey||delete n.yMetricKey,n.radiusMetricKey||delete n.radiusMetricKey,n.labelKey||delete n.labelKey,n.groupKey||delete n.groupKey,n.enableGrouping===void 0&&delete n.enableGrouping,n.radiusScale||delete n.radiusScale,n.fixedRadius===void 0&&delete n.fixedRadius,n.minRadius===void 0&&delete n.minRadius,n.maxRadius===void 0&&delete n.maxRadius,Object.keys(n).length!==0)return n}function Tn(){var A,j,w,I,f,E,b,D,F,V,S,L;const t=s.useEditorStore(v=>v.card.preferences),n=s.useEditorStore(v=>v.card),a=fe.useEffectiveEditorCardType(),r=s.useEditorStore(v=>v.isDevMode),{setCardPreferences:i,updateCardInFrame:d}=s.useEditorActions(),o=a==="bubble",c=a==="scatter",l=k.useMemo(()=>(t==null?void 0:t.bubbleScatterConfig)||{},[t==null?void 0:t.bubbleScatterConfig]),p=s.hasValidCardConfig(n==null?void 0:n.config)&&!r,x=k.useMemo(()=>{var v,O;return((O=(v=n==null?void 0:n.config)==null?void 0:v.metricColumns)==null?void 0:O.map(R=>{const P=R.label||R.name||R.alias||"";return{value:P,label:P}}))||[]},[(A=n==null?void 0:n.config)==null?void 0:A.metricColumns]),u=k.useMemo(()=>{var v,O;return((O=(v=n==null?void 0:n.config)==null?void 0:v.groupByColumns)==null?void 0:O.map(R=>{const P=R.label||R.name||R.alias||"";return{value:P,label:P}}))||[]},[(j=n==null?void 0:n.config)==null?void 0:j.groupByColumns]),C=k.useMemo(()=>l.enableGrouping!==void 0?l.enableGrouping:!r&&u.length>=2,[l.enableGrouping,r,u.length]),[y,h]=k.useState(C);k.useEffect(()=>{h(C)},[C]);const g=v=>{const O={...t||{},bubbleScatterConfig:v};i(O),n&&d({...n,preferences:O})},N=v=>{i(v),n&&d({...n,preferences:v})};k.useEffect(()=>{if(!t||x.length===0)return;const v={};let O=!1;if(!l.xMetricKey&&x[0]&&(v.xMetricKey=x[0].value,O=!0),!l.yMetricKey&&x[1]&&(v.yMetricKey=x[1].value,O=!0),o&&!l.radiusMetricKey&&x[2]&&(v.radiusMetricKey=x[2].value,O=!0),!l.labelKey&&u[0]&&(v.labelKey=u[0].value,O=!0),C&&!l.groupKey&&u[1]&&(v.groupKey=u[1].value,v.enableGrouping=!0,O=!0),O){const R=Js({...l,...v});g(R)}},[x,u,l,t,i,o,C]);const T=v=>{const O=Js({...l,...v});g(O)},B=v=>{h(v),T({enableGrouping:v,groupKey:v?l.groupKey:void 0})};if(!o&&!c)return null;const M=o?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(M,{className:"h-4 w-4"}),e.jsxs("span",{children:[o?"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"}),p?e.jsxs(s.Select,{value:l.labelKey||"",onValueChange:v=>T({labelKey:v}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select label column"})}),e.jsx(s.SelectContent,{children:u.map(v=>e.jsx(s.SelectItem,{value:v.value,children:v.label},v.value))})]}):e.jsx(Se,{className:"h-8 text-xs",placeholder:"Column name for labels",value:l.labelKey||"",onCommit:v=>T({labelKey:v})})]}),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:y,onCheckedChange:B})]}),y&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Group By"}),p?e.jsxs(s.Select,{value:l.groupKey||"",onValueChange:v=>T({groupKey:v}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select group column"})}),e.jsx(s.SelectContent,{children:u.map(v=>e.jsx(s.SelectItem,{value:v.value,children:v.label},v.value))})]}):e.jsx(Se,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:l.groupKey||"",onCommit:v=>T({groupKey:v})})]})]}),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"}),p?e.jsxs(s.Select,{value:l.xMetricKey||"",onValueChange:v=>T({xMetricKey:v}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select X metric"})}),e.jsx(s.SelectContent,{children:x.map(v=>e.jsx(s.SelectItem,{value:v.value,children:v.label},v.value))})]}):e.jsx(Se,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:l.xMetricKey||"",onCommit:v=>T({xMetricKey:v})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Y Axis"}),p?e.jsxs(s.Select,{value:l.yMetricKey||"",onValueChange:v=>T({yMetricKey:v}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select Y metric"})}),e.jsx(s.SelectContent,{children:x.map(v=>e.jsx(s.SelectItem,{value:v.value,children:v.label},v.value))})]}):e.jsx(Se,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:l.yMetricKey||"",onCommit:v=>T({yMetricKey:v})})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Radius"}),p?e.jsxs(s.Select,{value:l.radiusMetricKey||"",onValueChange:v=>T({radiusMetricKey:v}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select radius metric"})}),e.jsx(s.SelectContent,{children:x.map(v=>e.jsx(s.SelectItem,{value:v.value,children:v.label},v.value))})]}):e.jsx(Se,{className:"h-8 text-xs",placeholder:"Column name for radius",value:l.radiusMetricKey||"",onCommit:v=>T({radiusMetricKey:v})})]})]}),o&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Radius Settings"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Scale Mode"}),e.jsxs(s.Select,{value:l.radiusScale||"sqrt",onValueChange:v=>T({radiusScale:v}),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"})]})]})]}),l.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(Se,{className:"h-8 text-xs",type:"number",placeholder:"5",value:((w=l.minRadius)==null?void 0:w.toString())||"",onCommit:v=>T({minRadius:v?Number(v):void 0})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Max Radius"}),e.jsx(Se,{className:"h-8 text-xs",type:"number",placeholder:"30",value:((I=l.maxRadius)==null?void 0:I.toString())||"",onCommit:v=>T({maxRadius:v?Number(v):void 0})})]})]}),l.radiusScale==="fixed"&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs(s.Label,{className:"text-xs",children:["Fixed Radius: ",l.fixedRadius||10]}),e.jsx(s.Slider,{value:[l.fixedRadius||10],onValueChange:([v])=>T({fixedRadius:v}),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: ",l.fixedRadius||5]}),e.jsx(s.Slider,{value:[l.fixedRadius||5],onValueChange:([v])=>T({fixedRadius:v}),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:((E=(f=t==null?void 0:t.xAxisConfig)==null?void 0:f.name)==null?void 0:E.enabled)??!1,onCheckedChange:v=>{var P,U,q,_;const O=l.xMetricKey||"X Axis",R=l.yMetricKey||"Y Axis";N({...t??{},xAxisConfig:{...t==null?void 0:t.xAxisConfig,name:{enabled:v,text:((U=(P=t==null?void 0:t.xAxisConfig)==null?void 0:P.name)==null?void 0:U.text)||O}},yAxisConfig:{...t==null?void 0:t.yAxisConfig,name:{enabled:v,text:((_=(q=t==null?void 0:t.yAxisConfig)==null?void 0:q.name)==null?void 0:_.text)||R}}})}})]}),((D=(b=t==null?void 0:t.xAxisConfig)==null?void 0:b.name)==null?void 0:D.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(Se,{className:"h-8 text-xs",placeholder:l.xMetricKey||"X Axis",value:((V=(F=t==null?void 0:t.xAxisConfig)==null?void 0:F.name)==null?void 0:V.text)||"",onCommit:v=>{var O;N({...t??{},xAxisConfig:{...t==null?void 0:t.xAxisConfig,name:{...(O=t==null?void 0:t.xAxisConfig)==null?void 0:O.name,enabled:!0,text:v||l.xMetricKey||"X Axis"}}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Y Title"}),e.jsx(Se,{className:"h-8 text-xs",placeholder:l.yMetricKey||"Y Axis",value:((L=(S=t==null?void 0:t.yAxisConfig)==null?void 0:S.name)==null?void 0:L.text)||"",onCommit:v=>{var O;N({...t??{},yAxisConfig:{...t==null?void 0:t.yAxisConfig,name:{...(O=t==null?void 0:t.yAxisConfig)==null?void 0:O.name,enabled:!0,text:v||l.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const En=[{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 In(){const t=s.useEditorStore(u=>u.card),n=s.useEditorStore(u=>{var C;return(C=u.card)==null?void 0:C.preferences}),{setCardPreferences:a}=s.useEditorActions(),r=(t==null?void 0:t.type)==="funnel",i=(n==null?void 0:n.funnelConfig)||{},d=i.percentMode??"percentOfTotal",o=i.shrinkFraction??1,c=i.labelThreshold??0,l=u=>{const C={...i,...u};a({...n||{},funnelConfig:C})},m=u=>{l({percentMode:u})},p=u=>{l({shrinkFraction:u[0]})},x=u=>{l({labelThreshold:u[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:u=>m(u),className:"space-y-2",children:En.map(u=>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-${u.value}`,value:u.value,className:"mt-0.5"}),e.jsxs(s.Label,{htmlFor:`funnel-${u.value}`,className:"flex flex-col gap-0.5 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.description})]})]},u.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(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:[o],onValueChange:p,min:0,max:1,step:.1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Full Shrink"})]}),e.jsxs("p",{className:"text-center text-xs text-muted-foreground",children:["Current: ",Math.round(o*100),"%"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(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:x,min:0,max:25,step:1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Hide Small"})]}),e.jsx("p",{className:"text-center text-xs text-muted-foreground",children:c===0?"Showing all labels":`Hide labels below ${c}%`})]})]})]}):null}function _e(){const t=s.useEditorStore(d=>d.card),{data:n}=s.useDashboardCardQuery(t),{keys:a}=s.getKeys((n==null?void 0:n.records)||[]),r=a.slice(1).filter(d=>!s.METADATA_KEYS.includes(d));let i=r;if(["stackedBar","stackedLine"].includes(t.type)){const d=s.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:o}=s.getKeys(d);i=o.slice(1)}return{transformedMetricKeys:i,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}const kn=[{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"}],Dn=[{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)"}],An=["center","start","end"],Ln=["center","start","end","top","bottom"];function He({config:t,onChange:n,isHorizontal:a=!1,showAutoFormat:r=!0,positionOptions:i,showAppearance:d=!0}){var y,h,g,N,T,B;const o=i??(a?["auto","center","left","right","custom"]:["auto","center","top","bottom","custom"]),c=r?["auto","number","currency","percent","none"]:["number","currency","percent","none"],l=(M,A)=>{const j={...t,[M]:A};n(j)},m=(M,A)=>{const j={...t,font:{...(t==null?void 0:t.font)||{},[M]:A}};n(j)},p=(M,A)=>{const j={...t,formatOptions:{...(t==null?void 0:t.formatOptions)||{},[M]:A}};n(j)},x=()=>a?"Right":"Top",u=t||{},C=u.format||(r?"auto":"number");return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:u.position||"auto",onValueChange:M=>l("position",M),children:[e.jsx(s.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:o.map(M=>e.jsx(s.SelectItem,{value:M,className:"text-xs",children:M==="auto"?x():M==="custom"?"Custom (Advanced)":s.titleCase(M)},M))})]})]}),u.position==="custom"&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Anchor"}),e.jsxs(s.Select,{value:u.anchor||"center",onValueChange:M=>l("anchor",M),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:An.map(M=>e.jsx(s.SelectItem,{value:M,className:"text-xs",children:s.titleCase(M)},M))})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Align"}),e.jsxs(s.Select,{value:String(u.align||"center"),onValueChange:M=>l("align",M),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Ln.map(M=>e.jsx(s.SelectItem,{value:M,className:"text-xs",children:s.titleCase(M)},M))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Format"}),e.jsxs(s.Select,{value:C,onValueChange:M=>l("format",M),children:[e.jsx(s.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:c.map(M=>e.jsx(s.SelectItem,{value:M,className:"text-xs",children:M==="auto"&&r?"Auto (Use Axis)":M==="none"?"None (Raw Value)":s.titleCase(M)},M))})]})]}),!["auto","none"].includes(C)&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[["number","currency","percent"].includes(C)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Decimals"}),e.jsx("div",{className:"w-16",children:e.jsx(we,{type:"number",placeholder:"0",value:String(((y=u.formatOptions)==null?void 0:y.decimalPlaces)??(C==="currency"?2:C==="percent"?1:0)),onSave:M=>p("decimalPlaces",Number(M)),className:""})})]}),C==="currency"&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Currency"}),e.jsxs(s.Select,{value:((h=u.formatOptions)==null?void 0:h.currency)||"USD",onValueChange:M=>p("currency",M),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:kn.map(M=>e.jsx(s.SelectItem,{value:M.value,className:"text-xs",children:M.label},M.value))})]})]}),["number","currency"].includes(C)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((g=u.formatOptions)==null?void 0:g.useSuffix)??!1,onCheckedChange:M=>p("useSuffix",M)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Locale"}),e.jsxs(s.Select,{value:((N=u.formatOptions)==null?void 0:N.locale)||"en-US",onValueChange:M=>p("locale",M),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Dn.map(M=>e.jsx(s.SelectItem,{value:M.value,className:"text-xs",children:M.label},M.value))})]})]})]}),d&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Appearance"}),e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Size"}),e.jsx("div",{className:"w-16",children:e.jsx(we,{type:"number",placeholder:"12",value:String(((T=u.font)==null?void 0:T.size)||12),onSave:M=>m("size",Number(M)),className:""})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Weight"}),e.jsxs(s.Select,{value:((B=u.font)==null?void 0:B.weight)||"normal",onValueChange:M=>m("weight",M),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-24 text-xs",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 justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Color"}),e.jsxs(s.Select,{value:u.color==="auto"||!u.color?"auto":"custom",onValueChange:M=>{M==="auto"&&l("color","auto")},children:[e.jsx(s.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Contrast)"}),e.jsx(s.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Rotation"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-12",children:e.jsx(we,{type:"number",placeholder:"0",value:String(u.rotation||0),onSave:M=>l("rotation",Number(M)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"°"})]})]})]})]})]})}const Mn=[{type:"bar",icon:s.ChartColumnIncreasing,label:"Bar"},{type:"line",icon:s.ChartLine,label:"Line"}],Fn=[0,1,2,3,4,5,6,8,10],On=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],Rn=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Bn(){return s.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type})!=="combo"?null:e.jsxs(s.AccordionItem,{value:"combo-series",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.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsx(Vn,{})})]})}function Vn(){const{transformedMetricKeys:t}=_e();return t.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:t.map((n,a)=>e.jsx(Pn,{metricKey:n,idx:a},n))})}function Pn({metricKey:t,idx:n}){var N;const[a,r]=k.useState(!1),i=s.useEditorStore(T=>{var B;return(B=T.card)==null?void 0:B.preferences}),d=s.useEditorStore(T=>{var B,M;return(M=(B=T.card)==null?void 0:B.preferences)==null?void 0:M.datasetOptions}),o=d==null?void 0:d.find(T=>T.idx===n),{setCardPreferences:c}=s.useEditorStore(T=>T.actions),l=(o==null?void 0:o.type)||"bar",m=(o==null?void 0:o.yAxisId)||"y",p=((N=o==null?void 0:o.dataLabels)==null?void 0:N.enabled)??!1,x=l==="line"?s.ChartLine:s.ChartColumnIncreasing;function u(T){const B={idx:n,type:l,yAxisId:m,dataLabels:o==null?void 0:o.dataLabels,...T};if(!o)c({...i||{},datasetOptions:[...d||[],B]});else{const M=d==null?void 0:d.map(A=>A.idx===n?{...A,...B}:A);c({...i||{},datasetOptions:M})}}function C(T){u({type:T})}function y(T){u({yAxisId:T})}function h(T){u({dataLabels:{...o==null?void 0:o.dataLabels,enabled:T}})}function g(T){u({dataLabels:T})}return e.jsx(s.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(s.ChevronRight,{className:s.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:t,children:t})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[e.jsxs("span",{className:s.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(x,{className:"h-3 w-3"}),l==="line"?"Line":"Bar"]}),e.jsx("span",{className:s.cn("rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:m==="y2"?"Y2":"Y1"})]})]})}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"flex items-end gap-4",children:[e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Chart Type"}),e.jsx("div",{className:"flex gap-2",children:Mn.map(({type:T,icon:B,label:M})=>{const A=l===T;return e.jsxs("button",{onClick:()=>C(T),className:s.cn("flex items-center gap-2 rounded-md border px-3 py-1.5 text-xs transition-colors",A?"border-primary bg-primary/10 text-primary":"border-border bg-background text-muted-foreground hover:bg-muted"),children:[e.jsx(B,{className:"h-4 w-4"}),e.jsx("span",{children:M})]},T)})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Axis"}),e.jsxs(s.Select,{value:m,onValueChange:T=>y(T),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-20 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"y",className:"text-xs",children:"Y1 (Left)"}),e.jsx(s.SelectItem,{value:"y2",className:"text-xs",children:"Y2 (Right)"})]})]})]})]}),l==="line"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(s.Select,{value:(o==null?void 0:o.lineStyle)||"solid",onValueChange:T=>u({lineStyle:T}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Rn.map(({value:T,label:B})=>e.jsx(s.SelectItem,{value:T,className:"text-xs",children:B},T))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(s.Select,{value:String((o==null?void 0:o.pointRadius)??3),onValueChange:T=>u({pointRadius:Number(T)}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Fn.map(T=>e.jsx(s.SelectItem,{value:String(T),className:"text-xs",children:T===0?"None":T},T))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(s.Select,{value:(o==null?void 0:o.pointStyle)||"circle",onValueChange:T=>u({pointStyle:T}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:On.map(({value:T,label:B})=>e.jsx(s.SelectItem,{value:T,className:"text-xs",children:B},T))})]})]})]})]}),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 text-muted-foreground",children:"Data Labels"}),e.jsx(s.SmallSwitch,{checked:p,onCheckedChange:h})]}),p&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(He,{config:o==null?void 0:o.dataLabels,onChange:g,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const ns=[{value:"origin",label:"Origin (X-axis)",description:"Fill to the X-axis (y=0)"},{value:"start",label:"Start (Top)",description:"Fill to the top of chart area"},{value:"end",label:"End (Bottom)",description:"Fill to the bottom of chart area"},{value:"-1",label:"Previous Series",description:"Fill to the series below"},{value:"+1",label:"Next Series",description:"Fill to the series above"},{value:"false",label:"No Fill (Line)",description:"Show as line without fill"}],zn=[0,1,2,3,4,5,6,8,10],$n=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],qn=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Gn(t){return t==null?"origin":t===!1?"false":t}function Kn(){const t=s.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type});return t!=="area"&&t!=="stackedArea"?null:e.jsxs(s.AccordionItem,{value:"area-series",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.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsx(Un,{})})]})}function Un(){const{transformedMetricKeys:t}=_e();return t.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:t.map((n,a)=>e.jsx(_n,{metricKey:n,idx:a},n))})}function _n({metricKey:t,idx:n}){var h;const[a,r]=k.useState(!1),i=s.useEditorStore(g=>{var N;return(N=g.card)==null?void 0:N.preferences}),d=s.useEditorStore(g=>{var N,T;return(T=(N=g.card)==null?void 0:N.preferences)==null?void 0:T.datasetOptions}),o=d==null?void 0:d.find(g=>g.idx===n),{setCardPreferences:c}=s.useEditorStore(g=>g.actions),l=Gn(o==null?void 0:o.fill),m=((h=o==null?void 0:o.dataLabels)==null?void 0:h.enabled)??!1,p=ns.find(g=>g.value===l)||ns[0];function x(g){const N={idx:n,fill:l,dataLabels:o==null?void 0:o.dataLabels,...g};if(!o)c({...i||{},datasetOptions:[...d||[],N]});else{const T=d==null?void 0:d.map(B=>B.idx===n?{...B,...N}:B);c({...i||{},datasetOptions:T})}}function u(g){x({fill:g==="false"?!1:g})}function C(g){x({dataLabels:{...o==null?void 0:o.dataLabels,enabled:g}})}function y(g){x({dataLabels:g})}return e.jsx(s.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(s.ChevronRight,{className:s.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:t,children:t})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:e.jsxs("span",{className:s.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(s.ChartArea,{className:"h-3 w-3"}),p.label.split(" ")[0]]})})]})}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Fill Target"}),e.jsxs(s.Select,{value:l,onValueChange:g=>u(g),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:ns.map(g=>e.jsx(s.SelectItem,{value:g.value,className:"text-xs",children:e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{children:g.label})})},g.value))})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(s.Select,{value:(o==null?void 0:o.lineStyle)||"solid",onValueChange:g=>x({lineStyle:g}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:qn.map(({value:g,label:N})=>e.jsx(s.SelectItem,{value:g,className:"text-xs",children:N},g))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(s.Select,{value:String((o==null?void 0:o.pointRadius)??3),onValueChange:g=>x({pointRadius:Number(g)}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:zn.map(g=>e.jsx(s.SelectItem,{value:String(g),className:"text-xs",children:g===0?"None":g},g))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(s.Select,{value:(o==null?void 0:o.pointStyle)||"circle",onValueChange:g=>x({pointStyle:g}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:$n.map(({value:g,label:N})=>e.jsx(s.SelectItem,{value:g,className:"text-xs",children:N},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 text-muted-foreground",children:"Data Labels"}),e.jsx(s.SmallSwitch,{checked:m,onCheckedChange:C})]}),m&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(He,{config:o==null?void 0:o.dataLabels,onChange:y,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Hn=[0,1,2,3,4,5,6,8,10],Jn=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],rs=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Yn(){return s.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type})!=="line"?null:e.jsxs(s.AccordionItem,{value:"line-series",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.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsx(Qn,{})})]})}function Qn(){const{transformedMetricKeys:t}=_e();return t.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:t.map((n,a)=>e.jsx(Wn,{metricKey:n,idx:a},n))})}function Wn({metricKey:t,idx:n}){var g;const[a,r]=k.useState(!1),i=s.useEditorStore(N=>{var T;return(T=N.card)==null?void 0:T.preferences}),d=s.useEditorStore(N=>{var T,B;return(B=(T=N.card)==null?void 0:T.preferences)==null?void 0:B.datasetOptions}),o=d==null?void 0:d.find(N=>N.idx===n),{setCardPreferences:c}=s.useEditorStore(N=>N.actions),l=(o==null?void 0:o.lineStyle)||"solid",m=(o==null?void 0:o.pointRadius)??3,p=(o==null?void 0:o.pointStyle)||"circle",x=((g=o==null?void 0:o.dataLabels)==null?void 0:g.enabled)??!1,u=rs.find(N=>N.value===l)||rs[0];function C(N){const T={idx:n,lineStyle:l,pointRadius:m,pointStyle:p,dataLabels:o==null?void 0:o.dataLabels,...N};if(!o)c({...i||{},datasetOptions:[...d||[],T]});else{const B=d==null?void 0:d.map(M=>M.idx===n?{...M,...T}:M);c({...i||{},datasetOptions:B})}}function y(N){C({dataLabels:{...o==null?void 0:o.dataLabels,enabled:N}})}function h(N){C({dataLabels:N})}return e.jsx(s.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(s.ChevronRight,{className:s.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:t,children:t})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:e.jsxs("span",{className:s.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(s.TrendingUp,{className:"h-3 w-3"}),u.label.split(" ")[0]]})})]})}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(s.Select,{value:l,onValueChange:N=>C({lineStyle:N}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:rs.map(({value:N,label:T})=>e.jsx(s.SelectItem,{value:N,className:"text-xs",children:T},N))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(s.Select,{value:String(m),onValueChange:N=>C({pointRadius:Number(N)}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Hn.map(N=>e.jsx(s.SelectItem,{value:String(N),className:"text-xs",children:N===0?"None":N},N))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(s.Select,{value:p,onValueChange:N=>C({pointStyle:N}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Jn.map(({value:N,label:T})=>e.jsx(s.SelectItem,{value:N,className:"text-xs",children:T},N))})]})]})]})]}),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 text-muted-foreground",children:"Data Labels"}),e.jsx(s.SmallSwitch,{checked:x,onCheckedChange:y})]}),x&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(He,{config:o==null?void 0:o.dataLabels,onChange:h,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Xn=[0,2,4,6,8,10,12,16,20];function Zn(){const t=s.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type});return!t||!["bar","horizontalBar","stackedBar"].includes(t)?null:e.jsxs(s.AccordionItem,{value:"bar-series",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.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsx(er,{})})]})}function er(){const{transformedMetricKeys:t}=_e();return t.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:t.map((n,a)=>e.jsx(sr,{metricKey:n,idx:a},n))})}function sr({metricKey:t,idx:n}){var y;const[a,r]=k.useState(!1),i=s.useEditorStore(h=>{var g;return(g=h.card)==null?void 0:g.type}),d=s.useEditorStore(h=>{var g;return(g=h.card)==null?void 0:g.preferences}),o=s.useEditorStore(h=>{var g,N;return(N=(g=h.card)==null?void 0:g.preferences)==null?void 0:N.datasetOptions}),c=o==null?void 0:o.find(h=>h.idx===n),{setCardPreferences:l}=s.useEditorStore(h=>h.actions),m=(c==null?void 0:c.borderRadius)??0,p=((y=c==null?void 0:c.dataLabels)==null?void 0:y.enabled)??!1;function x(h){const g={idx:n,borderRadius:m,dataLabels:c==null?void 0:c.dataLabels,...h};if(!c)l({...d||{},datasetOptions:[...o||[],g]});else{const N=o==null?void 0:o.map(T=>T.idx===n?{...T,...g}:T);l({...d||{},datasetOptions:N})}}function u(h){x({dataLabels:{...c==null?void 0:c.dataLabels,enabled:h}})}function C(h){x({dataLabels:h})}return e.jsx(s.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(s.ChevronRight,{className:s.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:t,children:t})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:m>0&&e.jsxs("span",{className:s.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(s.ChartColumn,{className:"h-3 w-3"}),"r:",m]})})]})}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Bar Style"}),e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Corner Radius"}),e.jsxs(s.Select,{value:String(m),onValueChange:h=>x({borderRadius:Number(h)}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Xn.map(h=>e.jsx(s.SelectItem,{value:String(h),className:"text-xs",children:h===0?"None":`${h}px`},h))})]})]})})]}),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 text-muted-foreground",children:"Data Labels"}),e.jsx(s.SmallSwitch,{checked:p,onCheckedChange:u})]}),p&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(He,{config:c==null?void 0:c.dataLabels,onChange:C,isHorizontal:i==="horizontalBar",showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const tr=[0,1,2,3,4,5,6,8,10],ar=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],nr=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function rr(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>{var l;return(l=c.card)==null?void 0:l.preferences}),a=fe.useEffectiveEditorCardType(),r=n==null?void 0:n.lineStyleConfig,{setCardPreferences:i,updateCardInFrame:d}=s.useEditorActions();if(!t||!["line","area","stackedArea"].includes(a))return null;const o=(c,l)=>{const m={...n||{},lineStyleConfig:{...r,[c]:l}};i(m),d({...t,preferences:m})};return e.jsxs(s.AccordionItem,{value:"line-style",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(la,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Line Style"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Default styles for all series. Override per-series in the Series section."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Line Pattern"}),e.jsxs(s.Select,{value:(r==null?void 0:r.lineStyle)||"solid",onValueChange:c=>o("lineStyle",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:nr.map(({value:c,label:l})=>e.jsx(s.SelectItem,{value:c,className:"text-xs",children:l},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Point Size"}),e.jsxs(s.Select,{value:String((r==null?void 0:r.pointRadius)??3),onValueChange:c=>o("pointRadius",Number(c)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:tr.map(c=>e.jsx(s.SelectItem,{value:String(c),className:"text-xs",children:c===0?"None":c},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Point Shape"}),e.jsxs(s.Select,{value:(r==null?void 0:r.pointStyle)||"circle",onValueChange:c=>o("pointStyle",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:ar.map(({value:c,label:l})=>e.jsx(s.SelectItem,{value:c,className:"text-xs",children:l},c))})]})]})]})})]})}const lr=[0,2,4,6,8,10,12,16,20],or=[{value:"0.5",label:"50%"},{value:"0.6",label:"60%"},{value:"0.7",label:"70%"},{value:"0.8",label:"80%"},{value:"0.9",label:"90%"},{value:"1",label:"100%"}],ir=[{value:"0.5",label:"50%"},{value:"0.6",label:"60%"},{value:"0.7",label:"70%"},{value:"0.8",label:"80%"},{value:"0.9",label:"90%"},{value:"1",label:"100%"}];function cr(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>{var l;return(l=c.card)==null?void 0:l.preferences}),a=fe.useEffectiveEditorCardType(),r=n==null?void 0:n.barStyleConfig,{setCardPreferences:i,updateCardInFrame:d}=s.useEditorActions();if(!t||!["bar","horizontalBar","stackedBar"].includes(a))return null;const o=(c,l)=>{const m={...n||{},barStyleConfig:{...r,[c]:l}};i(m),d({...t,preferences:m})};return e.jsxs(s.AccordionItem,{value:"bar-style",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.ChartColumn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bar Style"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Default styles for all bars. Override per-series in the Series section."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Corner Radius"}),e.jsxs(s.Select,{value:String((r==null?void 0:r.borderRadius)??0),onValueChange:c=>o("borderRadius",Number(c)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:lr.map(c=>e.jsx(s.SelectItem,{value:String(c),className:"text-xs",children:c===0?"None":`${c}px`},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Bar Width"}),e.jsxs(s.Select,{value:String((r==null?void 0:r.barPercentage)??.9),onValueChange:c=>o("barPercentage",Number(c)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:or.map(({value:c,label:l})=>e.jsx(s.SelectItem,{value:c,className:"text-xs",children:l},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Category Width"}),e.jsxs(s.Select,{value:String((r==null?void 0:r.categoryPercentage)??.8),onValueChange:c=>o("categoryPercentage",Number(c)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:ir.map(({value:c,label:l})=>e.jsx(s.SelectItem,{value:c,className:"text-xs",children:l},c))})]})]})]})})]})}function dr(){const t=s.useEditorStore(a=>{var r,i;return(i=(r=a==null?void 0:a.card)==null?void 0:r.preferences)==null?void 0:i.sortChart}),{setSortChart:n}=s.useEditorActions();return e.jsxs(s.AccordionItem,{value:"stacked-sort",children:[e.jsx(s.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.ArrowUpDown,{className:"h-4 w-4"}),"Sort"]})}),e.jsx(s.AccordionContent,{className:"space-y-4 px-1",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort Order"}),e.jsx(Me,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"Ascending",value:"asc"},{label:"Descending",value:"desc"}],value:t||"none",onValueChange:a=>{n(a)}})]})})]})}const ur=["kpi"],Ys={none:"None",previous_period:"Previous Period",same_period_last_year:"Same Period Last Year",start_vs_end:"Start vs End",target:"Target"},ls=2;function Re(t){return typeof t=="string"?t.trim().toLowerCase():((t==null?void 0:t.id)||(t==null?void 0:t.qualifiedFieldName)||(t==null?void 0:t.name)||(t==null?void 0:t.label)||"").trim().toLowerCase()}function mr(t){if(!(t!=null&&t.name)||!(t!=null&&t.dataType)||t.role==="metric")return!1;const n=s.getDataType(t.dataType);return["date","string","boolean"].includes(n)}function xr(t){return{...t,role:"groupby"}}function hr(){var T,B,M,A;const t=s.useEditorStore(j=>j.card),n=s.useEditorStore(j=>j.actions.updateCardConfig),a=fe.useEffectiveEditorCardType(),{scopedFields:r}=s.useScopedFields(),i=((T=t.config)==null?void 0:T.metricColumns)||[],d=((B=t.config)==null?void 0:B.summary)||{},o=d.breakdownDimensions||[],c=ur.includes(a),l=i.length>0,m=d.enabled===!0,p=c&&l,x=((M=t.config)==null?void 0:M.comparisonType)||((A=i.find(j=>j.comparisonType&&j.comparisonType!=="none"))==null?void 0:A.comparisonType)||"none",u=Ys[x]||Ys.none,C=Array.from(new Map(r.filter(mr).map(j=>[Re(j),xr(j)])).values()),y=new Set(C.map(j=>Re(j))),h=new Set(o.map(j=>Re(j)).filter(j=>j&&y.has(j)));if(!c)return null;const g=j=>{n(t.id,{summary:{...d,...j}})},N=(j,w)=>{const I=Re(j),f=C.filter(b=>h.has(Re(b))),E=w?h.has(I)?f:[...f,j].slice(0,ls):f.filter(b=>Re(b)!==I);g({breakdownDimensions:E})};return e.jsxs(s.AccordionItem,{value:"summary",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.FileText,{className:"h-4 w-4"}),e.jsx("span",{children:"Summary"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{htmlFor:"summary-enabled",className:"text-xs",children:"Enable Summary"}),!l&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Add at least one metric to enable summary."})]}),e.jsx(s.SmallSwitch,{id:"summary-enabled",checked:m,disabled:!p,onCheckedChange:j=>{if(!j){g({enabled:!1,showOnCard:!1,includeInDashboardSummary:!1});return}g({enabled:!0,showOnCard:d.showOnCard??!0,includeInDashboardSummary:d.includeInDashboardSummary??!0,anomalyEnabled:d.anomalyEnabled??!0})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Comparison"}),e.jsxs("p",{className:"rounded-md border border-border bg-muted/40 px-2 py-1.5 text-xs",children:["Using: ",u]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Comparison is configured from card/metric comparison settings."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"summary-show-on-card",className:"text-xs",children:"Show summary on card"}),e.jsx(s.SmallSwitch,{id:"summary-show-on-card",checked:d.showOnCard===!0,disabled:!m,onCheckedChange:j=>g({showOnCard:j})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"summary-include-rollup",className:"text-xs",children:"Include in dashboard summary"}),e.jsx(s.SmallSwitch,{id:"summary-include-rollup",checked:d.includeInDashboardSummary===!0,disabled:!m,onCheckedChange:j=>g({includeInDashboardSummary:j})})]}),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 uppercase text-muted-foreground",children:"Breakdown Dimensions"}),e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[o.length,"/",ls]})]}),C.length===0?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"No dimension fields available for breakdown."}):e.jsx("div",{className:"max-h-40 space-y-2 overflow-y-auto rounded-md border border-border p-2",children:C.map(j=>{const w=Re(j),I=h.has(w),f=h.size>=ls,E=!m||!I&&f;return e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx(s.Checkbox,{id:`summary-breakdown-${w}`,checked:I,disabled:E,onCheckedChange:b=>N(j,b===!0)}),e.jsx(s.Label,{htmlFor:`summary-breakdown-${w}`,className:"cursor-pointer text-xs",children:j.label||j.name})]},w)})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"summary-anomaly",className:"text-xs",children:"Detect anomalies"}),e.jsx(s.SmallSwitch,{id:"summary-anomaly",checked:d.anomalyEnabled!==!1,disabled:!m,onCheckedChange:j=>g({anomalyEnabled:j})})]})]})]})}function gt({mode:t}){const n=s.useEditorStore(a=>{var r;return(r=a.card)==null?void 0:r.type});return e.jsxs(e.Fragment,{children:[n==="combo"&&e.jsx(Bn,{}),(n==="area"||n==="stackedArea")&&e.jsx(Kn,{}),n==="line"&&e.jsx(Yn,{}),(n==="bar"||n==="horizontalBar"||n==="stackedBar")&&e.jsx(Zn,{}),e.jsx(rr,{}),e.jsx(cr,{}),e.jsx(Nn,{}),t==="config"&&e.jsx(vn,{}),t==="config"&&e.jsx(yn,{}),t==="config"&&e.jsx(hr,{}),e.jsx(Sn,{}),n==="bullet"&&e.jsx(wn,{}),n==="funnel"&&e.jsx(In,{}),(n==="bubble"||n==="scatter")&&e.jsx(Tn,{}),(n==="stackedBar"||n==="stackedLine")&&e.jsx(dr,{}),e.jsx(fn,{}),e.jsx(gn,{}),e.jsx(jn,{}),e.jsx(bn,{})]})}function pr(){const t=s.useEditorStore(a=>a.card),n=t==null?void 0:t.type;return n?e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(Ke,{chartType:n}),e.jsx(s.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:e.jsx(gt,{mode:"dev"})})]}):null}function fr(){const t=s.useEditorStore(a=>a.card.type);function n(){switch(t){case"kpi":return e.jsx(Ya,{});case"table":return e.jsx(mn,{});case"map":return e.jsx(Za,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(xt,{})});case"text":return e.jsx(hn,{});default:return e.jsx(pr,{})}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[n(),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function gr(){const t=k.useRef(null),n=k.useRef(null),a=s.useEditorStore(i=>i.isShowingVisual),r=s.useEditorStore(i=>i.showAIDialog);return k.useEffect(()=>{var i,d,o,c;r?((i=t.current)==null||i.resize(0),(d=n.current)==null||d.resize(0)):((o=t.current)==null||o.resize(25),(c=n.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(Ca,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:a&&!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(fr,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(zs,{})})]}):e.jsx(zs,{})})]})}function jr(t){var ye;s.useAIInteractionStore(z=>z.currentAIContext);const[n,a]=k.useState(""),[r,i]=k.useState(null),{authToken:d,tokenProps:o}=s.useSemaphorContext(),c=s.useEditorStore(z=>{var Q;return(Q=z==null?void 0:z.card)==null?void 0:Q.sql}),l=s.useEditorStore(z=>z.isDevMode),m=s.useEditorStore(z=>{var Q;return(Q=z==null?void 0:z.card)==null?void 0:Q.python}),{setCardPython:p,setCardSql:x,setRunSql:u,switchCardType:C,setQueryConfig:y}=s.useEditorActions(),h=s.useEditorStore(z=>z.currentAssitantScope)||[],g=s.useEditorStore(z=>z.userInputForAI),N=s.useEditorStore(z=>z.triggerAIRun),T=s.useEditorStore(z=>z.card),B=s.useEditorStore(z=>z.selectedDatabaseName),M=s.useEditorStore(z=>z.selectedTableName),A=s.useEditorStore(z=>z.selectedConnectionId),j=s.useEditorStore(z=>z.selectedSchemaName),w=s.useDashboardStore(z=>z.dashboard.aiScopeTables),{errorMessage:I,refetch:f,data:E}=s.useDashboardCardQuery(T),{setTriggerAIRun:b,setCurrentAssitantScope:D,setCardConfig:F}=s.useEditorActions(),{selectedDatamodelName:V,connectionType:S,selectedDatamodelId:L}=s.useEditorAside(),v=(ye=s.useDashboardQuery().data)==null?void 0:ye.assistantProfileId,{messages:O,setMessages:R,regenerate:P,error:U,sendMessage:q,status:_,addToolResult:W,stop:J,clearError:ee}=s.useChat({transport:new s.DefaultChatTransport({api:`${o.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:v,isDevMode:l,aiContext:z.currentAIContext,reasoningEffort:z.reasoningEffort,showReasoning:z.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:z,body:Q})=>({body:{...Q,messages:s.cleanupIncompleteMessages(z)}})}),onError:z=>{var Q;if(z.name==="AbortError"||(Q=z.message)!=null&&Q.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)");return}console.error("[Editor Assistant] Stream error:",z)},onToolCall:$,onFinish({isAbort:z,isDisconnect:Q,isError:le}){a(""),console.log(z?"[Editor Assistant] Stream aborted by user":Q?"[Editor Assistant] Stream disconnected (network error)":le?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully")}});k.useEffect(()=>{N&&g&&(q({role:"user",parts:[{type:"text",text:g}]}),b(!1))},[N,g,q,b]);async function $({toolCall:z}){var Q,le,te,he,je,ve,Ne,Ie,se,ce,ue,pe,Te,Ce,Ae,Le;if(["createChartFromSql","createForecast"].includes(z.toolName)){const ae=((Q=z.input)==null?void 0:Q.sql)??((le=z.args)==null?void 0:le.sql),me=((te=z.input)==null?void 0:te.python)??((he=z.args)==null?void 0:he.python),xe=((je=z.input)==null?void 0:je.chartType)??((ve=z.args)==null?void 0:ve.chartType);C(xe),x(ae),p(me),u(!0),W({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){W({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"error",message:"No SQL found"}});return}W({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",sql:c,python:m||""}})}else if(z.toolName==="generateQueryConfig"){a("Generating query config...");const ae=((Ne=z.input)==null?void 0:Ne.chartType)??((Ie=z.args)==null?void 0:Ie.chartType),me=((se=z.input)==null?void 0:se.queryConfig)??((ce=z.args)==null?void 0:ce.queryConfig);((ue=z.input)==null?void 0:ue.cardConfig)??((pe=z.args)==null||pe.cardConfig),C(ae),F(me),x(void 0),p(void 0);const xe=await f();if((Te=xe==null?void 0:xe.data)!=null&&Te.error){W({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"error",queryConfig:me,message:(Ce=xe==null?void 0:xe.data)==null?void 0:Ce.error.message}});return}if((Ae=xe==null?void 0:xe.data)!=null&&Ae.records){W({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",queryConfig:me,message:"The data has been visualized"}});return}W({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",queryConfig:me,message:"The data has been visualized",records:(Le=xe==null?void 0:xe.data)==null?void 0:Le.records}})}else a("Analyzing...")}function Y(z){const Q=s.removeFromScopeArray(h,z);H(Q)}function H(z){const Q=s.sanitizeAIScope(z);D(Q),R(le=>[...le,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(Q)}`}]}])}function ne(){const z={databaseName:B||"",schemaName:j||"",tableName:M||"",datamodelId:L||"",datamodelName:s.resolveDatamodelName(V),connectionId:A||"",connectionType:S||""},Q=s.dedup([...h,z]);H(Q)}function K(){const z={databaseName:B||"",schemaName:j||"",tableName:M||"",datamodelName:s.resolveDatamodelName(V),connectionId:A||"",connectionType:S||"",datamodelId:L||""};if(!s.isInAiScopeArray([...w||[],...h],z)||h.length===0){const le=s.dedup([...w||[],...h,z]).filter(te=>te.connectionId===z.connectionId);H(le)}}const re=!["ready","error"].includes(_),de=s.getErrorMessage(U);return{messages:O,setMessages:R,sendMessage:q,regenerate:P,isLoading:re,handleSetAIScope:K,handleAddCurrentTableToScope:ne,removeFromCurrentSelections:Y,currentAssitantScope:h,setCurrentAssitantScope:D,stop:J,status:_,toolStatus:n,llmUsage:r,onFinish:t,errorMessage:de,clearError:ee}}const br=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Qs({isFullscreen:t,onFullscreenChange:n,fullscreenContainer:a}){const r=k.useRef(null),[i,d]=k.useState(!1),[o,c]=k.useState(s.isDevEnv),[l,m]=k.useState(!1),[p,x]=k.useState(!1),[u,C]=k.useState(!1),y=t??u,h=s.useCurrentAIContext(),{setCurrentAIContext:g}=s.useAIActions(),{clearQueue:N}=s.useQueueActions(),{clearFileAttachments:T}=s.useFileActions(),B=s.useFileAttachments("editor"),M=s.useDashboardStore(ae=>ae.dashboard.aiContext),A=s.useEditorStore(ae=>ae.card.dataSource),j=s.useEditorStore(ae=>ae.actions.setCardSql),w=s.useEditorStore(ae=>ae.actions.setRunSql),I=s.useEditorStore(ae=>ae.showAIDialog),f=s.useDashboardStore(ae=>ae.handleOpenAssistantProfile),{setShowAIDialog:E,setCardPython:b}=s.useEditorActions(),{setDataSource:D}=s.useEditorActions(),{assistantProfile:F}=s.useAssistantProfile(),{messages:V,setMessages:S,sendMessage:L,isLoading:v,stop:O,status:R,llmUsage:P,errorMessage:U,clearError:q}=jr(),[_,W]=k.useState(""),J=ae=>{W(ae.target.value)},ee=ae=>{ae.preventDefault();const me=_.trim();if(!me&&B.length===0)return;const xe=[];me&&xe.push({type:"text",text:me}),B.forEach(Oe=>{Oe.data&&xe.push({type:"file",mediaType:Oe.type,filename:Oe.name,url:`data:${Oe.type};base64,${Oe.data}`})}),L({role:"user",parts:xe}),W(""),T("editor"),Q({force:!0})},{visibleMessages:$,hasMoreMessages:Y,totalMessageCount:H,loadMoreMessages:ne,resetMessageWindow:K}=s.useMessageWindow(V,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:re,isAtBottom:de,hasNewMessages:ye,newMessageCount:z,scrollToBottom:Q,handleScroll:le,resetNewMessageCount:te}=s.useAutoScroll($,{threshold:50,behavior:"smooth",isStreaming:v});k.useEffect(()=>{var ae;I&&((ae=r.current)==null||ae.focus(),g({selectedEntities:(A==null?void 0:A.selectedEntities)||[]}))},[I,A,g]),s.useAutoSubmitQueue({assistantType:"editor",status:R,isLoading:v,sendMessage:L});const{hasActiveTools:he}=s.useActiveToolStatus(V),je=k.useCallback(ae=>{n==null||n(ae),t===void 0&&C(ae)},[t,n]);k.useEffect(()=>{if(!y)return;function ae(me){me.key==="Escape"&&je(!1)}return window.addEventListener("keydown",ae),()=>{window.removeEventListener("keydown",ae)}},[y,je]);const ve=k.useCallback(ae=>{L({role:"user",parts:[{type:"text",text:ae}]}),Q({force:!0})},[L,Q]),Ne=k.useCallback(async()=>{const ae=JSON.stringify(V??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(ae),s.ue.success("Conversation copied")}catch(me){console.error("Failed to copy conversation",me),s.ue.error("Unable to copy conversation")}},[V]),Ie=k.useCallback(()=>{je(!y)},[y,je]);function se(ae,me){me==="sql"?(j(ae),w(!0)):me==="python"&&(b(ae),w(!0))}function ce(){h.selectedEntities.length===0&&g({selectedEntities:(M==null?void 0:M.selectedEntities)||[]})}function ue(ae){ce();const me={role:"user",parts:[{type:"text",text:ae.title+" "+ae.subtitle}]};L(me)}function pe(ae){ce(),L({role:"user",parts:[{type:"text",text:ae}]})}function Te(){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:i,onCheckedChange:d,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:c,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:m,children:"System Message"})]})]})}function Ce(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const Ae=(_==null?void 0:_.length)===0&&(V==null?void 0:V.filter(ae=>ae.role==="user").length)===0,Le=e.jsxs("div",{"data-role":"editor-assistant",className:s.cn("flex h-full w-full flex-col justify-between px-6 py-4",y&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Ce(),f&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:f,children:(F==null?void 0:F.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[Te(),o&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Ne,children:"Copy Conversation"}),e.jsx(s.IconButton,{tooltip:y?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:Ie,children:y?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:()=>{S([]),N("editor"),q(),K()},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:()=>{E(!1)},children:e.jsx(s.X,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:re,className:"mt-2 flex w-full grow basis-0",onScroll:le,children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[Y&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:ne,className:"text-xs",children:["Load ",Math.min(5,H-$.length)," ","more messages (",H-$.length," ","hidden)"]})}),e.jsx(s.PrintMessages,{messages:$,showTools:o,handleRun:se,showSystemMessage:l,onQuickReply:ve,disableQuickReplies:v}),!he&&e.jsx(s.AssistantStatus,{status:R,errorMessage:U})]})}),I&&!de&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{Q({force:!0}),te()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),ye&&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:[Ae&&!F&&e.jsx(s.Placeholders,{onClick:ue,placeholders:br}),e.jsx("div",{children:Ae&&F&&e.jsx(s.SeedQuestions,{seedQuestions:F.seedQuestions||[],handleSeedQuestionClick:pe})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:r,setInput:W,stop:O,input:_,handleInputChange:J,handleSubmit:ae=>{ce(),ee(ae),Q({force:!0})},isLoading:v,status:R,assistantType:"editor",onFocus:()=>{}})]}),P&&i&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",P.inputTokens," prompt tokens, ",P.outputTokens," ","completion tokens, ",P.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(A==null?void 0:A.selectedEntities)||[],open:p,onOpenChange:x,dataSource:A||s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]});return y&&a?Gt.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:Le})}),a):Le}function yr(t,n,a){if(!n)return!1;const r=n.qualifiedFieldName,i=n.qualifiedEntityName,d=i&&n.name?`${i}.${n.name}`:r;return t.some(o=>{if(!(s.getDataType(o.dataType||"")==="date"))return!1;const l=s.getSelectedDateFilterColumn(o,a),m=l.split("."),p=m[m.length-1]||l,x=m.length>1?m.slice(0,-1).join("."):void 0,u=o.qualifiedTableName||x,C=u?`${u}.${p}`:void 0;return r?C?C===d||C.endsWith(`.${r}`):p===n.name:C?C===d:p===n.name})}const jt=["day","week","month","quarter","year"],vr=[...jt,"hour","minute","second"],Nr=t=>/timestamp|datetime|time/i.test(t||""),Cr=t=>Nr(t)?vr:jt,ms=({dataType:t})=>s.getFieldIconComponent(t);function Sr({aliasTemplate:t,onAliasTemplateChange:n}){var l;const[a,r]=k.useState(t),[i,d]=k.useState(!1),o=(l=s.useEditorStore(m=>{var p;return(p=m.card.config)==null?void 0:p.pivotByColumns}))==null?void 0:l[0],c=o?`e.g. Min Sales in {{${o.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(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$1,{placeholder:c,value:i?a:t,onChange:m=>{r(m.target.value),d(!0)},onFocus:()=>d(!0),onPointerDown:m=>m.stopPropagation(),className:"h-8 text-xs",onKeyDown:m=>{m.key==="Enter"&&i&&a!==t?(n(a),d(!1)):m.key==="Escape"&&(r(t),d(!1))},"aria-label":"Edit alias template"}),i&&a!==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:()=>{n(a),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 wr({valueAliases:t,onValueAliasesChange:n}){const[a,r]=k.useState(null),[i,d]=k.useState(""),[o,c]=k.useState(""),l=()=>{n({...t,"":""})},m=x=>{const u={...t};delete u[x],n(u)},p=x=>{const u={...t};delete u[x],u[i]=o,n(u),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(([x,u],C)=>e.jsx("div",{className:"flex items-center gap-2",children:a===x?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:i,onChange:y=>d(y.target.value),className:"h-8 w-24 text-xs",onPointerDown:y=>y.stopPropagation(),onKeyDown:y=>{y.key==="Enter"?p(x):y.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:o,onChange:y=>c(y.target.value),className:"h-8 w-24 text-xs",onPointerDown:y=>y.stopPropagation(),onKeyDown:y=>{y.key==="Enter"?p(x):y.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:()=>p(x),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$1,{placeholder:"Value key",value:x,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(x),d(x),c(u)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:u,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(x),d(x),c(u)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>m(x),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},x+C)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:l,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function Tr({idx:t}){var c;const n=s.useEditorStore(l=>{var m;return(m=l.card)==null?void 0:m.preferences}),a=s.useEditorStore(l=>{var m;return(m=l.card.preferences)==null?void 0:m.datasetOptions}),r=s.useEditorStore(l=>l.actions.setCardPreferences),i=(c=n==null?void 0:n.chartOptions)==null?void 0:c.indexAxis,d=a==null?void 0:a.find(l=>l.idx===t);function o(l,m){(l==="end"||l==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const p={display:l!=="none",align:l,anchor:l,clamp:!0};if(!d)r({...n,datasetOptions:[...a||[],{idx:m,datalabels:p}]});else{const x={...d};x.datalabels=p;const u=a==null?void 0:a.map(C=>C.idx===m?x:C);r({...n,datasetOptions:u})}}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:()=>o("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>o("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Xt,{className:s.cn("h-4 w-4",{"rotate-90":i==="y"})})}),e.jsx("button",{onClick:()=>o("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(sa,{className:s.cn("h-4 w-4",{"rotate-90":i==="y"})})}),e.jsx("button",{onClick:()=>o("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(ea,{className:s.cn("h-4 w-4",{"rotate-90":i==="y"})})})]})})]})}function xs({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",n),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function Er(t,n=30){return t.length>n?t.slice(0,n)+"...":t}function Ir({col:t,idx:n,className:a,iconClassName:r,children:i}){const d=s.useEditorStore(p=>{var x;return(x=p.card)==null?void 0:x.preferences}),o=s.useEditorStore(p=>{var x,u;return(u=(x=p.card)==null?void 0:x.preferences)==null?void 0:u.datasetOptions}),c=o==null?void 0:o.find(p=>p.idx===n),{setCardPreferences:l}=s.useEditorStore(p=>p.actions);function m(p){if(!c)l({...d,datasetOptions:[...o||[],{idx:n,type:p==="area"?"line":p,fill:p==="area"?"origin":""}]});else{const x={...c};x.type=p==="area"?"line":p,x.fill=p==="area"?"origin":"";const u=o==null?void 0:o.map(C=>C.idx===n?x:C);l({...d,datasetOptions:u})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[i||e.jsx(xs,{className:"max-w-[100px]",title:t,children:Er(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.ChartColumnIncreasing,{onClick:()=>m("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartLine,{onClick:()=>m("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartArea,{onClick:()=>m("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(Tr,{idx:n})]})]})}function kr(){const t=s.useEditorStore(c=>c.card.type),n=s.useEditorStore(c=>c.isDevMode),a=s.useEditorStore(c=>c.card.preferences),{setCardPreferences:r}=s.useEditorStore(c=>c.actions);function i(c){var p;const l={datalabels:{display:c!=="none",align:c,anchor:c,clamp:!0}},m={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(p=a==null?void 0:a.chartOptions)==null?void 0:p.plugins,...l}}};r(m)}function d(){var c,l,m;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((m=(l=(c=a==null?void 0:a.chartOptions)==null?void 0:c.plugins)==null?void 0:l.datalabels)==null?void 0:m.anchor)||"none",onValueChange:i,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 o(){var c,l,m;return e.jsx("div",{children:e.jsxs(s.Select,{value:((m=(l=(c=a==null?void 0:a.chartOptions)==null?void 0:c.plugins)==null?void 0:l.datalabels)==null?void 0:m.anchor)||"none",onValueChange:i,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:n?d():o()})}function Dr({column:t}){const n=s.useEditorStore(l=>l.card.type),a=s.useEditorStore(l=>{var m,p;return(p=(m=l.card)==null?void 0:m.config)==null?void 0:p.metricColumns}),r=(a==null?void 0:a.map(l=>l.label))||[],i=r==null?void 0:r.find(l=>l===t.label||l===t.name),d=i?r.indexOf(i):-1;function o(){return e.jsx("div",{className:"pr-1",children:i&&e.jsx(Ir,{idx:d,col:i,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(kr,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&o(),["pie","doughnut"].includes(n)&&c()]})}function Ar({field:t,searchQuery:n="",limit:a=500}){const{authToken:r,tokenProps:i}=s.useSemaphorContext(),d=s.useEditorStore(m=>m.card),o=d==null?void 0:d.dataSource,c=["attribute-values",t.entityName,t.name,n,a],l=s.useQuery({queryKey:c,queryFn:async()=>{if(!(o!=null&&o.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const m={groupByColumns:[{...t,role:"groupby"}],metricColumns:[],filters:n?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:n}],groups:[]}:void 0,rowLimit:a},p={connection_id:o.connectionId,cardConfig:m,cardDataSource:o,cache_config:s.getCacheConfig({card:d})};console.log("requestBody",p);const x=await s.postRequestRegular(`${i.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",p);if(x!=null&&x.error)return console.error("Error fetching attribute values:",x.error),[];const u=t.name;return((x==null?void 0:x.records)||[]).map(y=>{const h=y[u]||y[t.alias||u]||y[t.label];return{id:h||"",value:h||"",label:String(h||"(empty)")}})}catch(m){return console.error("Error fetching attribute values:",m),[]}},enabled:!!t&&!!(o!=null&&o.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:l.data||[],isLoading:l.isLoading,isFetching:l.isFetching,isError:l.isError,error:l.error,refetch:l.refetch}}function bt({open:t,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:i,onSave:d}){var B,M;const o=!!i,[c,l]=k.useState(o?"values":"fields"),[m,p]=k.useState(""),[x,u]=k.useState({id:(i==null?void 0:i.id)||s.v4(),field:(i==null?void 0:i.field)||null,selectedValues:i?Array.isArray(i.value)?i.value:[i.value]:[]}),C=a.filter(A=>{var w;return o?!1:!((w=r==null?void 0:r.conditions)==null?void 0:w.some(I=>I.field.id===A.id))&&A.label.toLowerCase().includes(m.toLowerCase())}),y=A=>{u({...x,field:A}),l("values")},h=()=>{if(x.field&&x.selectedValues.length>0){const A={id:x.id,field:x.field,operator:"in",value:x.selectedValues};let j;if(o){const w=((r==null?void 0:r.conditions)||[]).map(I=>I.id===i.id?A:I);j={...r,conditions:w}}else{const w=(r==null?void 0:r.conditions)||[];j={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...w,A],groups:[]}}d(j),n(!1)}},g=()=>{if(!o||!i)return;const A=((r==null?void 0:r.conditions)||[]).filter(j=>j.id!==i.id);if(A.length>0){const j={...r,conditions:A};d(j)}else d(void 0);n(!1)},N=A=>{u({...x,selectedValues:A})},T=()=>{o&&i?(u({id:i.id,field:i.field,selectedValues:Array.isArray(i.value)?i.value:[i.value]}),l("values")):(u({id:s.v4(),field:null,selectedValues:[]}),l("fields")),p("")};return k.useEffect(()=>{t&&T()},[t,o,i]),e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsx(s.DialogHeader,{children:e.jsx(s.DialogTitle,{children:o?`Edit Filter: ${(B=x.field)==null?void 0:B.label}`:c==="fields"?"Select Field to Filter":`Select Values for ${(M=x.field)==null?void 0:M.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!o&&(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(A=>e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-muted rounded-md text-xs",children:[e.jsxs("span",{className:"font-medium",children:[A.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(A.value)?`${A.value.length} values`:String(A.value)})]},A.id))})]}),c==="fields"&&!o?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$1,{placeholder:"Search fields...",value:m,onChange:A=>p(A.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:C.map(A=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>y(A),children:[e.jsx(ms,{dataType:s.getDataType(A.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:A.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[A.entityName,".",A.name]})]})]},A.id))}),C.length===0&&m&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',m,'"']}),C.length===0&&!m&&a.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(Lr,{field:x.field,selectedValues:x.selectedValues,onValuesChange:N,onBack:o?void 0:()=>l("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:o?e.jsx(s.Button,{variant:"destructive",onClick:g,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:T,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:h,disabled:!x.field||x.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function Lr({field:t,selectedValues:n,onValuesChange:a,onBack:r}){const[i,d]=k.useState(""),{values:o,isLoading:c,isFetching:l}=Ar({field:t,searchQuery:i,limit:500}),m=i?o.filter(u=>String(u.value).toLowerCase().includes(i.toLowerCase())):o,p=u=>{const C=n.includes(u);a(C?n.filter(y=>y!==u):[...n,u])},x=()=>{n.length===m.length&&m.length>0?a([]):a(m.map(u=>u.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(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$1,{placeholder:"Search values...",value:i,onChange:u=>d(u.target.value),className:"pl-10"})]}),c||l?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:n.length===m.length&&m.length>0,onCheckedChange:x}),e.jsxs(s.Label,{className:"text-sm",children:["Select All (",m.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:m.map(u=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>p(u.value),children:[e.jsx(s.Checkbox,{checked:n.includes(u.value),onCheckedChange:()=>p(u.value)}),e.jsx(xs,{className:"text-sm",children:u.label})]},u.id))})]})]})}function Mr({field:t,zone:n,index:a,sortDirection:r,onSortDirectionChange:i,hasPivotColumns:d=!1,cardType:o}){var Ts,Es,Is,ks,Ds,As,Ls,Ms;const{attributes:c,listeners:l,setNodeRef:m,transform:p,transition:x,isDragging:u}=s.useSortable({id:t.id}),C=s.useEditorStore(G=>G.card),y=s.useEditorStore(G=>G.frame),{scopedFields:h,isLoading:g}=s.useScopedFields(),{userContext:N}=s.useCurrentUserInfo(),T=(N==null?void 0:N.type)==="organization",B=(Ts=C.dataSource)==null?void 0:Ts.semanticDomainId,{promoteMetric:M}=s.usePromoteCalculatedMetricToDomain({domainId:B}),{updateLabel:A,handleAggregationChange:j,handleDateFormatChange:w,handleGranularityChange:I,handleAliasTemplateChange:f,handleValueAliasesChange:E,removeField:b,handleMetricComparisonChange:D,handleKpiShowTrendlineChange:F,handleKpiTrendlineWindowChange:V,handleKpiTrendlineGranularityChange:S,handleMetricTargetValueChange:L}=s.useFieldManagement(C),[v,O]=k.useState(!1),[R,P]=k.useState(!1),[U,q]=k.useState(!1),[_,W]=k.useState(null),J=k.useMemo(()=>{const G=Z=>Z!=null&&Z.startsWith("card-source-")?Z.replace("card-source-",""):Z,oe=G(t.id),X=h.find(Z=>{if(t.qualifiedFieldName&&Z.qualifiedFieldName&&Z.qualifiedFieldName===t.qualifiedFieldName||t.qualifiedEntityName&&Z.qualifiedEntityName&&Z.qualifiedEntityName===t.qualifiedEntityName&&Z.name===t.name)return!0;const ie=G(Z.id);return!!(oe&&ie&&oe===ie)});return{dataType:(X==null?void 0:X.dataType)||t.dataType,resolvedFromScopedField:!!X}},[t.dataType,t.id,t.name,t.qualifiedEntityName,t.qualifiedFieldName,h]),ee=Cr(J.dataType),[$,Y]=k.useState(t.dateFormat||"YYYY-MM-DD"),[H,ne]=k.useState(t.customFormat||""),[K,re]=k.useState(!!t.customFormat),de=k.useRef(null),[ye,z]=k.useState(t.aliasTemplate||""),[Q,le]=k.useState(t.valueAliases||{}),[te,he]=k.useState((Es=t.parameters)==null?void 0:Es.filters),je=G=>{G==="custom"?re(!0):(re(!1),Y(G),(n==="groupBy"||Ye)&&w(a,G,"",n))},ve=G=>{ne(G),(n==="groupBy"||Ye)&&w(a,"custom",G,n)},Ne=G=>{var Z;const X=(Z=s.getDateFormatOptionsForGranularity(G)[0])==null?void 0:Z.value;X&&!K&&(Y(X),n==="groupBy"&&w(a,X,"",n)),n==="groupBy"&&I(a,G)},Ie=G=>{z(G),n==="metrics"&&f(a,G)},se=G=>{le(G),n==="metrics"&&E(a,G)},ce=G=>{A(n,a,G)},ue=G=>G!=null&&G.startsWith("card-source-")?G.replace("card-source-",""):G,pe=(G,oe,X)=>{const Z=ue(G.id),ie=ue(oe.id);return Z&&ie&&Z===ie?!0:G.name===oe.name&&G.role===oe.role},Ce=s.isCalculatedMetric(t)?(Is=y==null?void 0:y.calculatedFields)==null?void 0:Is.find(G=>pe(G,t)):void 0,Ae=t.fieldScope==="dashboard"||t.fieldScope===void 0&&!!Ce,Le=t.fieldScope==="domain",ae=Le?"domain":Ae?"dashboard":"card",me=Le?t:Ae&&Ce?Ce:t,xe=G=>{var oe;if(he(G),n==="metrics"){const X={...t,parameters:{...t.parameters,filters:G}},Z=[...((oe=C.config)==null?void 0:oe.metricColumns)||[]];Z[a]=X,s.useEditorStore.getState().actions.updateCardConfig(C.id,{metricColumns:Z})}P(!1)},Oe=async G=>{await M(G),zt()},vt=()=>{b(n,a)},Nt={transform:s.CSS.Transform.toString(p),transition:x},ps=s.getDataType(J.dataType||t.dataType),Je=ps==="date",fs=o==="kpi",Ye=n==="detailColumns",gs=(ks=C.config)==null?void 0:ks.metricColumns,Be=(Ds=C.config)==null?void 0:Ds.groupByColumns,js=s.useDashboardStore(G=>{var oe;return(oe=G.dashboard)==null?void 0:oe.filters}),bs=s.useDashboardStore(G=>G.filterValues),Pe=t.granularity||"day",ys=ee.includes(Pe)?Pe:"day",vs=n==="groupBy"&&!ee.includes(Pe),Qe=s.getDateFormatOptionsForGranularity(ys),Ct=K?"custom":Qe.some(G=>G.value===$)?$:((As=Qe[0])==null?void 0:As.value)??"YYYY-MM-DD";k.useEffect(()=>{var X;if(g||!vs){de.current=null;return}const G=`${t.id}:${Pe}:${J.dataType||t.dataType||""}:${a}`;if(de.current===G)return;de.current=G;const oe="day";if(I(a,oe),!K){const Z=(X=s.getDateFormatOptionsForGranularity(oe)[0])==null?void 0:X.value;Z&&(Y(Z),w(a,Z,"",n))}},[t.dataType,t.id,w,I,vs,a,K,g,Pe,J.dataType,n]);const St=!!o&&s.COMPARISON_SUPPORTED_CHART_TYPES.includes(o),wt=o==="kpi"||o==="table",ke=k.useMemo(()=>Be==null?void 0:Be.find(G=>s.getDataType(G.dataType||"")==="date"),[Be]),Ns=k.useMemo(()=>(Be||[]).some(G=>s.getDataType(G.dataType||"")==="date"),[Be]),Tt=k.useMemo(()=>{var Z;if(!ke)return!1;const G=(Z=C.config)==null?void 0:Z.filters;if(!G)return!1;const oe=ie=>{const ge=ie.field;return ge?ke.id&&ge.id===ke.id||ke.qualifiedFieldName&&ge.qualifiedFieldName===ke.qualifiedFieldName?!0:ge.name===ke.name:!1},X=ie=>ie.conditions.some(be=>s.getDataType(be.field.dataType||"")==="date"&&oe(be))?!0:ie.groups.some(be=>X(be));return X(G)},[(Ls=C.config)==null?void 0:Ls.filters,ke]),Et=k.useMemo(()=>yr(js||[],ke,bs),[js,bs,ke]),Cs=Tt||Et,It=k.useMemo(()=>(gs||[]).some(G=>G.comparisonType==="start_vs_end"),[gs]),kt=n!=="pivotBy",Dt=Je&&n==="groupBy"&&(!fs||It),At=!fs&&Je&&(n==="groupBy"||Ye),Lt=o==="kpi"&&Je&&n==="groupBy",Mt=n==="metrics",Ss=St&&n==="metrics",Ft=()=>{const G=t,oe=n==="metrics"&&s.isCalculatedMetric(G);return e.jsxs("div",{className:"space-y-1",children:[!oe&&e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:X=>{X.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}`}),oe&&G.calculatedFormula&&e.jsxs("div",{title:s.formatDisplayFormula(G.calculatedFormula),onPointerDown:X=>{X.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:["= ",s.formatDisplayFormula(G.calculatedFormula)]})]})},Ot=()=>kt?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(we,{value:t.label??"",onSave:ce,placeholder:"Display label...",type:"text"})]}):null,ws=()=>Dt?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:ys,onValueChange:Ne,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:ee.map(G=>e.jsx(s.SelectItem,{className:"text-xs",value:G,children:s.toTitleCase(G)},G))})]})]}):null,Rt=()=>At?e.jsxs(e.Fragment,{children:[ws(),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:Ct,onValueChange:je,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:Qe.map(G=>e.jsx(s.SelectItem,{className:"text-xs",value:G.value,children:G.label},G.value))})]}),K&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(s.Input$1,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:H,onChange:G=>{G.stopPropagation(),ve(G.target.value)},onClick:G=>G.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}):null,Bt=()=>{var oe,X,Z,ie;const G=Lt;return G?e.jsx(e.Fragment,{children:G&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(s.SmallSwitch,{checked:((oe=C.config)==null?void 0:oe.showTrendline)||!1,onCheckedChange:F})]})}),((X=C.config)==null?void 0:X.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$1,{type:"number",min:"1",max:"365",value:((Z=C.config)==null?void 0:Z.trendlineWindow)||30,onChange:ge=>{const be=parseInt(ge.target.value)||30;V(be)},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:((ie=C.config)==null?void 0:ie.trendlineGranularity)||"day",onValueChange:S,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"})]})]})]})]})]})}):null},Vt=()=>{if(!Mt)return null;const G=t,oe=s.isCalculatedMetric(G);return e.jsxs(e.Fragment,{children:[oe&&T&&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:()=>q(!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:X=>{j(a,X)},disabled:oe,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"})]})]})]})]}),Ss&&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:G.comparisonType||"none",onValueChange:X=>D(a,X),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"}),(()=>{const X=!Ns||!Cs,Z=Ns?Cs?void 0:"Add a date filter to enable":"Add a date groupBy to enable",ie=(ge,be)=>e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.SelectItem,{value:ge,disabled:X,title:Z,children:be})}),X&&Z&&e.jsx(s.TooltipContent,{side:"right",children:Z})]})});return e.jsxs(e.Fragment,{children:[ie("previous_period","Previous Period"),ie("same_period_last_year","Same Period Last Year"),ie("start_vs_end","Start vs End")]})})(),wt&&e.jsx(s.SelectItem,{value:"target",children:"Target"})]})]})]}),Ss&&G.comparisonType==="target"&&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(s.Input$1,{type:"number",value:G.targetValue!==void 0&&G.targetValue!==null?String(G.targetValue):"",onChange:X=>{const Z=X.target.value;if(Z===""){L(a,void 0);return}const ie=Number(Z);L(a,Number.isFinite(ie)?ie:void 0)},className:"h-8 text-xs",placeholder:"Enter target value..."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(te==null?void 0:te.conditions)&&te.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:te.conditions.map(X=>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:()=>{W(X),P(!0)},children:[e.jsxs("span",{className:"font-medium",children:[X.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(X.value)?X.value.length===1?String(X.value[0]):X.value.length<=2?X.value.join(", "):`${X.value.slice(0,2).join(", ")} +${X.value.length-2}`:String(X.value)})}),Array.isArray(X.value)&&X.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 (",X.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:X.value.map((Z,ie)=>e.jsx("div",{children:String(Z)},ie))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:Z=>{var ge;Z.stopPropagation();const ie=te.conditions.filter(be=>be.id!==X.id);if(ie.length>0){const be={...te,conditions:ie};xe(be)}else if(he(void 0),n==="metrics"){const be={...t,parameters:{...t.parameters,filters:void 0}},De=[...((ge=C.config)==null?void 0:ge.metricColumns)||[]];De[a]=be,s.useEditorStore.getState().actions.updateCardConfig(C.id,{metricColumns:De})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},X.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{W(null),P(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(Dr,{column:t}),d&&e.jsxs(e.Fragment,{children:[e.jsx(Sr,{aliasTemplate:ye,onAliasTemplateChange:Ie}),e.jsx(wr,{valueAliases:Q,onValueAliasesChange:se})]})]})},{columns:Pt=[],refetch:zt}=s.useColumns(),$t=(te==null?void 0:te.conditions)&&te.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:m,style:Nt,...c,...l,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 ${u?"z-50 scale-95 opacity-50":"border-slate-200"} ${n==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(ms,{dataType:ps}),e.jsx(xs,{className:s.cn("w-[140px] flex-1 text-sm",$t&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),n==="metrics"&&((Ms=te==null?void 0:te.conditions)==null?void 0:Ms.length)&&!v&&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:te.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:te.conditions.map(G=>e.jsxs("div",{children:[G.field.label,":"," ",Array.isArray(G.value)?`${G.value.length} values`:String(G.value)]},G.id))})})]})}),n!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:G=>{G.stopPropagation(),O(!v)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${v?"rotate-180":""}`})}),n==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:G=>{G.stopPropagation(),i(r==="asc"?"desc":"asc")},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:G=>{G.stopPropagation(),vt()},children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]}),v&&e.jsxs("div",{className:"space-y-3",children:[Ft(),Ot(),o==="kpi"&&ws(),Rt(),Bt(),Vt()]})]}),R&&e.jsx(bt,{open:R,onOpenChange:G=>{P(G),G||W(null)},availableFields:Pt,existingFilters:te,editingCondition:_,onSave:G=>{var oe;if(G)xe(G);else if(he(void 0),n==="metrics"){const X={...t,parameters:{...t.parameters,filters:void 0}},Z=[...((oe=C.config)==null?void 0:oe.metricColumns)||[]];Z[a]=X,s.useEditorStore.getState().actions.updateCardConfig(C.id,{metricColumns:Z})}W(null)}}),U&&n==="metrics"&&e.jsx(s.CalculatedFieldEditor,{open:U,onOpenChange:q,availableFields:h,existingField:me,existingFieldScope:ae,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:G=>{var De;if(G.role!=="metric")return;const oe=[...((De=C.config)==null?void 0:De.metricColumns)||[]];oe[a]=G;const{frame:X,actions:Z}=s.useEditorStore.getState();if(Z.updateCardConfig(C.id,{metricColumns:oe}),!s.isCalculatedMetric(G))return;const ie=X.calculatedFields||[],ge=ie.findIndex(Ee=>Ee.name===t.name&&Ee.role===t.role);if(ge<0)return;const be=ie.map((Ee,qe)=>qe===ge?{...G,id:Ee.id}:Ee);Z.updateFrame({calculatedFields:be})},onSaveToDashboard:G=>{var qe;if(G.role!=="metric")return;const{frame:oe,actions:X}=s.useEditorStore.getState(),Z=oe.calculatedFields||[],ie=Z.findIndex(We=>pe(We,G)),ge=ie>=0&&Z[ie].id!==G.id?{...G,id:Z[ie].id}:G,be=ie>=0?Z.map((We,qt)=>qt===ie?ge:We):[...Z,ge];X.updateFrame({calculatedFields:be});const De=[...((qe=C.config)==null?void 0:qe.metricColumns)||[]],Ee=t;De[a]={...ge,id:Ee.id,aliasTemplate:Ee.aliasTemplate,valueAliases:Ee.valueAliases,parameters:Ee.parameters,customFormat:Ee.customFormat},X.updateCardConfig(C.id,{metricColumns:De})},onPromoteMetricToDomain:B&&T?Oe:void 0,domainId:B,cardId:C.id})]})}function Fr({concept:t}){const n=()=>{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"})]})]})]});case"detailColumns":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields to display as columns in the detail table. No aggregation applied - shows raw values from the database."})]});default:return null}};return e.jsx(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:n()})]})})}function $e({zone:t,fields:n,label:a,placeholder:r,shouldShow:i,hasPivotColumns:d=!1,activeField:o=null}){const{isOver:c,setNodeRef:l}=s.useDroppable({id:t}),{updateSortByColumn:m}=s.useEditorActions(),p=s.useEditorStore(g=>g.card),x=s.useEditorStore(g=>g.card.type),u=n.length>0,C=k.useMemo(()=>!o||!c?!0:s.validateFieldForChartType(o,t,x).isValid,[o,c,t,x]),y=(g,N)=>{var B;!((B=p.config)!=null&&B.sortByColumns)||p.config.sortByColumns.findIndex(M=>M.id===g)===-1||m(p.id,g,{direction:N})};if(t==="sortBy"&&i===!1)return null;const h=t!=="sortBy"&&x!=="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:a}),h&&e.jsx(Fr,{concept:t})]}),e.jsx("div",{ref:l,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&&C,"border-red-500 bg-red-50 dark:bg-red-950":c&&!C,"border-muted-foreground/30 bg-muted/40":!c&&u,"min-h-[60px] border-muted-foreground/20 bg-background":!c&&!u}),children:n.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,{id:t,items:n.map(g=>g.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:n.map((g,N)=>{const B=g.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(Mr,{field:g,zone:t,index:N,sortDirection:B,onSortDirectionChange:M=>y(g.id,M),hasPivotColumns:d,cardType:x})})},g.id)})})})})]})}function Or({groupByFields:t,pivotByFields:n,metricsFields:a,sortByFields:r,detailFields:i,activeField:d}){var W,J,ee,$;const[o,c]=k.useState(!1),l=s.useEditorStore(Y=>{var H;return!!((H=Y.card.customCardPreferences)!=null&&H.url)}),m=s.useEditorStore(Y=>Y.card),p=s.useEditorStore(Y=>Y.frame),x=s.findCustomVisualConfigCard(p,m),{manifest:u}=s.useCustomVisual(((W=x==null?void 0:x.customCardPreferences)==null?void 0:W.url)||""),C=(J=u==null?void 0:u.visuals)==null?void 0:J.find(Y=>{var H;return Y.name===((H=x==null?void 0:x.customCardPreferences)==null?void 0:H.componentName)}),y=s.resolveMultiInputType(x,C)==="multiple",h=y&&!!((ee=x==null?void 0:x.customCardPreferences)!=null&&ee.url),g=s.getConfigSlotExpectedType(C==null?void 0:C.slots),N=s.useEditorStore(Y=>Y.actions.updateCardConfig),T=s.useEditorStore(Y=>Y.actions.updateFrame),{scopedFields:B,refetch:M}=s.useScopedFields(),{userContext:A}=s.useCurrentUserInfo(),j=y&&(x==null?void 0:x.id)===m.id&&g?g:m==null?void 0:m.type,w=j==="detailTable",I=t.length>0||a.length>0||i.length>0,f=!w&&(j!=="kpi"||a.length<=2),E=!w,b=!w&&j!=="kpi",D=j!=="kpi"&&I,F=w,V=w?"Drop fields from Columns":"Drop fields from Rows or Metrics",S=($=m.dataSource)==null?void 0:$.semanticDomainId,{promoteMetric:L}=s.usePromoteCalculatedMetricToDomain({domainId:S}),v=(A==null?void 0:A.type)==="organization",O=Y=>{const H=p.calculatedFields||[],ne=H.findIndex(Q=>Q.name===Y.name&&Q.role===Y.role),K=ne>=0?{...Y,id:H[ne].id}:Y,re=ne>=0?H.map((Q,le)=>le===ne?K:Q):[...H,K];T({calculatedFields:re});const de=s.getNewField(K,"metrics",a),ye=a.findIndex(Q=>Q.name===de.name&&Q.role===de.role),z=ye>=0?a.map((Q,le)=>le===ye?{...Q,...de,id:Q.id}:Q):[...a,de];N(m.id,{metricColumns:z})},R=async Y=>{await L(Y),M()},P=["pie","doughnut","polar","funnel","aggregateTable","bubble","scatter"].includes(j),U=b&&!P,q=()=>j==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},_=()=>j==="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:[f&&e.jsx($e,{zone:"groupBy",fields:t,label:q().label,placeholder:q().placeholder,activeField:d}),U&&e.jsx($e,{zone:"pivotBy",fields:n,label:"Pivot Columns",placeholder:"Drop fields to pivot data",activeField:d}),E&&e.jsx($e,{zone:"metrics",fields:a,label:_().label,placeholder:_().placeholder,hasPivotColumns:n.length>0,activeField:d}),F&&e.jsx($e,{zone:"detailColumns",fields:i,label:"Columns",placeholder:"Drag columns to display"}),a.length>=1&&v&&e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:()=>c(!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"]}),D&&e.jsx($e,{zone:"sortBy",fields:r,label:"Sort By",placeholder:V,activeField:d})]})]}),(!l||h)&&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:"CHART SETTINGS"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsx(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:e.jsx(gt,{mode:"config"})})})]}),(l||h)&&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(Zs,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"COMPONENT SETTINGS"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsx(xt,{})})]})]}),e.jsx(s.CalculatedFieldEditor,{open:o,onOpenChange:c,availableFields:B,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:Y=>{Y.role==="metric"&&N(m.id,{metricColumns:[...a,Y]})},onSaveToDashboard:Y=>{Y.role==="metric"&&O(Y)},onPromoteMetricToDomain:S&&v?R:void 0,domainId:S,cardId:m.id})]})}function Rr({onEditJoins:t}){const n=s.useEditorStore(c=>c.card),{autoJoinMetadata:a}=s.useDashboardCardQuery(n);if(!(a!=null&&a.autoResolved))return null;const{resolvedJoinPlan:r}=a,i=(r==null?void 0:r.joins)||[];if(i.length===0)return null;const d=c=>!c||c.length===0?"No conditions":c.map(l=>{var u,C,y,h;const m=`${(u=l.source)==null?void 0:u.entityName}.${(C=l.source)==null?void 0:C.name}`,p=`${(y=l.target)==null?void 0:y.entityName}.${(h=l.target)==null?void 0:h.name}`,x=l.operator||"=";return`${m} ${x} ${p}`}).join(" AND "),o=c=>!c.joinKeyGroups||c.joinKeyGroups.length===0?"No conditions defined":c.joinKeyGroups.length===1?d(c.joinKeyGroups[0].keys):c.joinKeyGroups.map((l,m)=>({id:m,operator:l.operator,condition:d(l.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(da,{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:"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:i.length})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"max-w-md p-3",children:e.jsx("div",{className:"space-y-2",children:i.map((c,l)=>{const m=o(c),p=Array.isArray(m);return e.jsxs("div",{className:"rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"font-medium text-foreground",children: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:p?m.map(x=>e.jsxs("div",{className:"rounded bg-muted/30 px-2 py-1",children:[e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:x.condition}),x.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",x.operator,")"]})]},x.id)):e.jsx("div",{className:"rounded bg-muted/30 px-2 py-1",children:e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:m})})})]},c.id||l)})})})]})})]}),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 Ws={getItem(t){if(typeof window>"u")return null;try{return localStorage.getItem(t)}catch(n){return console.warn(`Failed to read from localStorage (${t}):`,n),null}},setItem(t,n){if(!(typeof window>"u"))try{localStorage.setItem(t,n)}catch(a){console.warn(`Failed to write to localStorage (${t}):`,a)}}};function Br({selectedChart:t,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:i,sortByFields:d,detailFields:o,activeField:c}){var I,f;const[l,m]=k.useState(()=>Ws.getItem("chart-selector-expanded")==="true"),[p,x]=k.useState(!1),u=s.useEditorStore(E=>E.card),C=s.useEditorStore(E=>E.actions.updateCardConfig),y=a.length>0||r.length>0||i.length>0||o.length>0,{data:h,autoJoinMetadata:g}=s.useDashboardCardQuery(u),N=((I=u==null?void 0:u.config)==null?void 0:I.joinPlan)||(g!=null&&g.autoResolved?g.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),T=((f=u==null?void 0:u.dataSource)==null?void 0:f.selectedEntities)||[],B=E=>{C(u.id,{...u==null?void 0:u.config,joinPlan:E}),x(!1)},M=()=>{C(u.id,{...u==null?void 0:u.config,joinPlan:void 0}),x(!1)},A=()=>{x(!1)},j=()=>{x(!0)};k.useEffect(()=>{Ws.setItem("chart-selector-expanded",String(l))},[l]);const w=()=>{m(E=>!E)};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":l}),children:[e.jsx("div",{className:s.cn("overflow-hidden transition-all duration-300 ease-in-out",l?"max-h-[200px] opacity-100":"max-h-0 opacity-0"),children:l&&e.jsx(us,{selectedChart:t,onChartChange:n,variant:"outline"})}),e.jsx("div",{"data-content":"Chart Quick Selector",className:"flex items-center justify-center",children:e.jsx(s.ChartQuickSelector,{selectedChart:t,onChartChange:n,isDropdownExpanded:l,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:y||h}),children:e.jsx(fe.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(Rr,{onEditJoins:j}),e.jsx(Or,{groupByFields:a,pivotByFields:r,metricsFields:i,sortByFields:d,detailFields:o,activeField:c})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]}),e.jsx(rt,{open:p,onOpenChange:x,joinPlan:N,availableDataSources:T,onSave:B,onCancel:A,onRemove:M,children:e.jsx("div",{})})]})}function Vr({initialFilters:t,availableFields:n}={}){const[a,r]=k.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(A=>A.card.dataSource);const{columns:i,isLoading:d}=s.useColumns(),c=n||i||[],l={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},m=A=>{const j=w=>{if(w.id===A){const I=c[0]||l,f=s.getDataType(I.dataType)==="date";return{...w,conditions:[...w.conditions,{id:`condition-${Date.now()}`,field:I,operator:f?"between":"=",value:f?[]:""}]}}return{...w,groups:w.groups.map(j)}};r(j(a))},p=A=>{const j=w=>{if(w.id===A){const I=c[0]||l,f=s.getDataType(I.dataType)==="date";return{...w,groups:[...w.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:I,operator:f?"between":"=",value:f?[]:""}],groups:[]}]}}return{...w,groups:w.groups.map(j)}};r(j(a))},x=(A,j)=>{const w=I=>I.id===A?{...I,conditions:I.conditions.filter(f=>f.id!==j)}:{...I,groups:I.groups.map(w)};r(w(a))},u=(A,j)=>{const w=I=>I.id===A?{...I,groups:I.groups.filter(f=>f.id!==j)}:{...I,groups:I.groups.map(w)};r(w(a))},C=(A,j,w,I)=>{if(w==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const f=E=>E.id===A?{...E,conditions:E.conditions.map(b=>b.id===j?{...b,[w]:I}:b)}:{...E,groups:E.groups.map(f)};r(f(a))},y=(A,j,w)=>{const I=f=>f.id===A?{...f,conditions:f.conditions.map(E=>E.id===j?{...E,...w}:E)}:{...f,groups:f.groups.map(I)};r(I(a))},h=(A,j)=>{const w=I=>I.id===A?{...I,logicalOperator:j}:{...I,groups:I.groups.map(w)};r(w(a))},g=(A,j)=>{const w=I=>I.id===A?{...I,negate:j}:{...I,groups:I.groups.map(w)};r(w(a))},N=(A,j,w)=>{const I=f=>f.id===A?{...f,conditions:s.arrayMove(f.conditions,j,w)}:{...f,groups:f.groups.map(I)};r(I(a))},T=(A,j,w)=>{const I=f=>f.id===A?{...f,groups:s.arrayMove(f.groups,j,w)}:{...f,groups:f.groups.map(I)};r(I(a))},B=A=>{if(!A||A.conditions.length===0&&A.groups.length===0)return"-- No filters defined";const j=I=>{let f="";typeof I.field=="object"?f=I.field.entityName?`${I.field.entityName}.${I.field.name}`:I.field.name:f=String(I.field);const E=I.operator;let b=I.value;if(I.field.dataType==="string"&&!["in","not in"].includes(I.operator))typeof b=="string"?b=`'${b}'`:Array.isArray(b)&&(b=`'${b.join(", ")}'`);else if(I.field.dataType==="date"||I.field.dataType==="datetime"||I.field.dataType==="timestamp")if(I.operator==="between"&&Array.isArray(b)&&b.length===2){const D=b[0]?`'${b[0]}'`:"NULL",F=b[1]?`'${b[1]}'`:"NULL";return`${f} BETWEEN ${D} AND ${F}`}else if((I.operator==="in"||I.operator==="not in")&&Array.isArray(b)){const D=b.map(F=>F?`'${F}'`:"NULL").join(", ");return`${f} ${E} (${D})`}else typeof b=="string"||b instanceof Date?b=`'${b}'`:Array.isArray(b)&&b.length>0&&(b=`'${b[0]}'`);else if(["in","not in"].includes(I.operator)){let D=[];Array.isArray(b)?D=b.map(F=>typeof F=="string"?`'${F}'`:String(F)):typeof b=="string"?D=b.split(",").map(F=>{const V=F.trim();return I.field.dataType==="string"?`'${V}'`:V}):typeof b=="number"&&(D=[String(b)]),b=`(${D.join(", ")})`}switch(E){case"contains":return typeof b=="string"?`${f} LIKE '%${b.replace(/'/g,"")}'`:`${f} LIKE '%${String(b)}'`;case"startsWith":return typeof b=="string"?`${f} LIKE '${b.replace(/'/g,"")}%'`:`${f} LIKE '${String(b)}%'`;case"endsWith":return typeof b=="string"?`${f} LIKE '%${b.replace(/'/g,"")}'`:`${f} LIKE '%${String(b)}'`;case"isNull":return`${f} IS NULL`;case"isNotNull":return`${f} IS NOT NULL`;default:return`${f} ${E} ${b}`}},w=I=>{const f=I.conditions.map(j),E=I.groups.map(V=>w(V)),b=[...f,...E].filter(Boolean);if(b.length===0)return"";const D=b.join(` ${I.logicalOperator} `),F=b.length>1?`(${D})`:D;return I.negate?`NOT ${F}`:F};return w(A)},M=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:c,isLoading:d,addCondition:m,addGroup:p,removeCondition:x,removeGroup:u,updateCondition:C,updateConditionFields:y,updateGroupOperator:h,updateGroupNegate:g,reorderConditions:N,reorderGroups:T,generateSQLPreview:B,hasAnyFilters:M}}function Pr({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",n),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const zr=t=>{if(t.qualifiedEntityName){const n=t.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function $r({value:t,onValueChange:n,availableFields:a,placeholder:r="Select field",className:i="w-64"}){const[d,o]=k.useState(!1),c=k.useMemo(()=>{const l={};return a.forEach(m=>{const p=zr(m);l[p]||(l[p]={}),l[p][m.entityId]||(l[p][m.entityId]=[]),l[p][m.entityId].push(m)}),l},[a]);return e.jsxs(s.Popover,{modal:!0,open:d,onOpenChange:o,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",i),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Pr,{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(([l,m])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),l]}),children:Object.entries(m).map(([p,x])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[s.getEntityIcon(x[0].entityType,{size:"h-3 w-3"}),e.jsx("span",{children:x[0].entityName})]}),x.map((u,C)=>e.jsxs(s.CommandItem,{value:u.id,onSelect:()=>{n(u),o(!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)===u.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:u.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:u.description&&e.jsx("span",{children:u.description})})]})]},u.id+C))]},`${l}-${p}`))},l))})]})})]})}function hs(t){var h;const n=s.useEditorStore(g=>g.card),{authToken:a,tokenProps:r}=s.useSemaphorContext(),i=s.useEditorStore(g=>g.card.config),d=i==null?void 0:i.joinPlan,o={...t,alias:t.name,label:"value",role:"groupby"},c={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},l={...o,role:"sortby",direction:"asc"},m={joinPlan:d,groupByColumns:[o],metricColumns:[c],sortByColumns:[l]},p=((h=n.dataSource)==null?void 0:h.connectionId)||n.connectionId,{data:x,isPending:u,error:C}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular(`${r.apiServiceUrl}/v1/query`,(a==null?void 0:a.accessToken)||"",{connection_id:p,cardConfig:m,cardDataSource:n.dataSource})}catch(g){console.log(t),console.error("error",g)}},enabled:!!p,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((x==null?void 0:x.records)||[]).map(g=>({label:g.value||"BLANK",value:g.value||"BLANK",count:(g==null?void 0:g.count)||0})),isPending:u,error:C}}function qr({field:t,selected:n,onChange:a,placeholder:r="Select items...",className:i}){const[d,o]=os.useState(!1),{filterValues:c}=hs(t),l=p=>{a(n.filter(x=>x!==p))},m=p=>{n.includes(p)?a(n.filter(x=>x!==p)):a([...n,p])};return e.jsx("div",{className:s.cn("w-full",i),children:e.jsxs(s.Popover,{open:d,onOpenChange:o,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:n.length>0?n.map(p=>{const x=c.find(u=>u.value===p);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[x==null?void 0:x.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:u=>{u.key==="Enter"&&l(p)},onMouseDown:u=>{u.preventDefault(),u.stopPropagation()},onClick:u=>{u.stopPropagation(),l(p)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},p)}):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((p,x)=>e.jsxs(s.CommandItem,{onSelect:()=>m(p.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",n.includes(p.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:p.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:p.count})]})]},p.value+x))})]})]})})]})})}function Gr({field:t,value:n,onChange:a,placeholder:r="Select value...",className:i}){const{filterValues:d,isPending:o,error:c}=hs(t);return o?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:n,onValueChange:a,children:[e.jsx(s.SelectTrigger,{className:i||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:n})}),e.jsx(s.SelectContent,{children:d.map((l,m)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:l.value,children:l.label},l.value+m))})]})}function Kr({value:t,operator:n,onChange:a,className:r}){var C,y,h;const{tokenProps:i}=s.useSemaphorContext(),d=((y=(C=i==null?void 0:i.params)==null?void 0:C.calendarContext)==null?void 0:y.tz)||((h=i==null?void 0:i.params)==null?void 0:h.timezone),o=d||Intl.DateTimeFormat().resolvedOptions().timeZone,c=n==="between"||n==="not between",l=k.useMemo(()=>{if(!(!t||!c)&&Array.isArray(t)&&t.length===2){const g=t[0]?new Date(t[0]):void 0,N=t[1]?new Date(t[1]):void 0;if(g&&N)return{from:g,to:N}}},[t,c]),m=k.useMemo(()=>{if(!t||c)return;const g=Array.isArray(t)?t[0]:t;if(!g)return;const N=new Date(g);if(!isNaN(N.getTime()))return N},[t,c]),p=g=>n==="<="||n===">"?s.endOfDayInTimezone(g,o):s.startOfDayInTimezone(g,o),x=g=>{if(!g){a([]);return}if(g.from&&g.to){a([g.from.toISOString(),g.to.toISOString()]);return}a([])},u=g=>{if(!g){a("");return}const N=p(g);a(N.toISOString())};return e.jsx(s.DateRangePicker,{value:c?l:void 0,selectionMode:c?"range":"single",singleValue:c?void 0:m,onChange:x,onSingleChange:u,timezone:d,showRelativeTab:c,className:r,placeholder:"Select date..."})}const Ur=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],_r=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Hr=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],Jr=["=","!=","isNull","isNotNull"],Yr=["between","=","!=","<","<=",">",">=","isNull","isNotNull"],Qr={"=":"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 Xs(t){return Qr[t]||s.titleCase(t)}function Wr(t){switch(t){case"string":return _r;case"number":return Hr;case"boolean":return Jr;case"date":return Yr;default:return Ur}}function yt({condition:t,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:i,onRemoveCondition:d,onUpdateGroupOperator:o,availableFields:c,updateConditionFields:l}){const{attributes:m,listeners:p,setNodeRef:x,transform:u,transition:C,isDragging:y}=s.useSortable({id:t.id}),{isPending:h,error:g}=hs(t.field),N={transform:s.CSS.Transform.toString(u),transition:C};return e.jsxs("div",{ref:x,style:N,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${y?"z-50 opacity-50":""}`,children:[e.jsx("div",{...m,...p,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),n>0&&e.jsxs(s.Select,{value:r,onValueChange:T=>o(a,T),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"})]})]}),n===0&&e.jsx("div",{className:"w-24"}),e.jsx($r,{value:t.field,onValueChange:T=>{const B=T,M=s.getDataType(B.dataType)==="date";l(a,t.id,{field:B,value:"",operator:M?"between":"="})},availableFields:c,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:T=>{T==="in"||T==="not in"?l(a,t.id,{operator:T,value:[]}):T==="isNull"||T==="isNotNull"?l(a,t.id,{operator:T,value:null}):T==="between"||T==="not between"?l(a,t.id,{operator:T,value:[]}):l(a,t.id,{operator:T,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?Xs(t.operator):""})}),e.jsx(s.SelectContent,{children:Wr(s.getDataType(t.field.dataType)).map(T=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:T,children:Xs(T)},T))})]}),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"?h?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..."]}):g?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(qr,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(T=>typeof T=="string")?t.value:[],onChange:T=>l(a,t.id,{value:T}),placeholder:`Select values for ${t.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(t.operator)?e.jsx(s.Input$1,{value:typeof t.value=="string"?t.value:"",onChange:T=>l(a,t.id,{value:T.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(Gr,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:T=>l(a,t.id,{value:T}),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:T=>l(a,t.id,{value:T==="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(Kr,{value:t.value,operator:t.operator,onChange:T=>l(a,t.id,{value:T}),className:"flex-1"}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:T=>i(a,t.id,"value",T.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(a,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function Xr({group:t,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:i,onRemoveGroup:d,onUpdateCondition:o,onUpdateField:c,onRemoveCondition:l,onReorderConditions:m,onReorderGroups:p,onAddCondition:x,onAddGroup:u,availableFields:C,renderFilterGroup:y,updateConditionFields:h}){const{attributes:g,listeners:N,setNodeRef:T,transform:B,transition:M,isDragging:A}=s.useSortable({id:t.id}),j={transform:s.CSS.Transform.toString(B),transition:M},w=f=>{const{active:E,over:b}=f;if(b&&E.id!==b.id){const D=t.conditions.findIndex(V=>V.id===E.id),F=t.conditions.findIndex(V=>V.id===b.id);D!==-1&&F!==-1&&m(t.id,D,F)}},I=f=>{const{active:E,over:b}=f;if(b&&E.id!==b.id&&a){const D=t.groups.findIndex(V=>V.id===E.id),F=t.groups.findIndex(V=>V.id===b.id);D!==-1&&F!==-1&&p(a,D,F)}};return e.jsxs("div",{ref:T,style:j,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${A?"z-50 opacity-50":""}`,children:[n>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...g,...N,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:()=>i(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:f=>r(t.id,f),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:()=>a&&d(a,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${n>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:w,children:e.jsx(s.SortableContext,{items:t.conditions.map(f=>f.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((f,E)=>e.jsx(yt,{condition:f,index:E,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:o,onUpdateField:c,onRemoveCondition:l,onUpdateGroupOperator:r,availableFields:C,updateConditionFields:h},f.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:I,children:e.jsx(s.SortableContext,{items:t.groups.map(f=>f.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(f=>y(f,n+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:()=>x(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:()=>u(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Zr({filters:t,availableFields:n,onSave:a,onClearAll:r,onCancel:i}){const{currentFilters:d,availableFields:o,isLoading:c,addCondition:l,addGroup:m,removeCondition:p,removeGroup:x,updateCondition:u,updateConditionFields:C,updateGroupOperator:y,updateGroupNegate:h,reorderConditions:g,reorderGroups:N,generateSQLPreview:T,hasAnyFilters:B,setCurrentFilters:M}=Vr({initialFilters:t,availableFields:n}),A=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[j,w]=k.useState(!1),I=(b,D,F)=>{const V=S=>S.id===b?{...S,conditions:S.conditions.map(L=>L.id===D?{...L,field:F,dataType:F.dataType}:L)}:{...S,groups:S.groups.map(V)};M(V(d))},f=(b,D=0,F)=>D===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:A,collisionDetection:s.closestCenter,onDragEnd:V=>{const{active:S,over:L}=V;if(L&&S.id!==L.id){const v=b.conditions.findIndex(R=>R.id===S.id),O=b.conditions.findIndex(R=>R.id===L.id);v!==-1&&O!==-1&&g(b.id,v,O)}},children:e.jsx(s.SortableContext,{items:b.conditions.map(V=>V.id),strategy:s.verticalListSortingStrategy,children:b.conditions.map((V,S)=>e.jsx(yt,{condition:V,index:S,groupId:b.id,groupLogicalOperator:b.logicalOperator,onUpdateCondition:u,onUpdateField:I,onRemoveCondition:p,onUpdateGroupOperator:y,availableFields:o,updateConditionFields:C},V.id))})}),e.jsx(s.DndContext,{sensors:A,collisionDetection:s.closestCenter,onDragEnd:V=>{const{active:S,over:L}=V;if(L&&S.id!==L.id){const v=b.groups.findIndex(R=>R.id===S.id),O=b.groups.findIndex(R=>R.id===L.id);v!==-1&&O!==-1&&N(b.id,v,O)}},children:e.jsx(s.SortableContext,{items:b.groups.map(V=>V.id),strategy:s.verticalListSortingStrategy,children:b.groups.map(V=>f(V,D+1,b.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:()=>l(b.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),j&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>m(b.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},b.id):e.jsx(Xr,{group:b,depth:D,parentGroupId:F,onUpdateGroupOperator:y,onUpdateGroupNegate:h,onRemoveGroup:x,onUpdateCondition:u,onUpdateField:I,onRemoveCondition:p,onReorderConditions:g,onReorderGroups:N,onAddCondition:l,onAddGroup:m,availableFields:o,renderFilterGroup:f,updateConditionFields:C},b.id),E=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..."})]}):f(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:j,onCheckedChange:b=>w(b)}),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)"})]})}),B&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:T(d)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:i,children:"Cancel"}),E>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>a(B?d:null),children:"Apply Filters"})]})]})}function el({cardId:t,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:i,isOpen:d,onOpenChange:o}){const c=m=>{a(t,m),o(!1)},l=()=>{r(t),o(!1)};return e.jsxs(s.Dialog,{modal:!1,open:d,onOpenChange:o,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:m=>{m.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(Zr,{filters:n,availableFields:i,onSave:c,onCancel:()=>o(!1),onClearAll:l})]})]})}function sl({activeCardId:t,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var N,T;const[i,d]=k.useState(null),o=s.useEditorStore(B=>B.card),c=s.useEditorStore(B=>B.actions.updateCardConfig),l=(N=o==null?void 0:o.config)==null?void 0:N.joinPlan,m=k.useCallback(B=>B.entityName===s.CALCULATED_FIELD_ENTITY_MARKER||B.entityName==="calculated_fields"||B.qualifiedEntityName==="calculated_fields",[]),p=(T=o==null?void 0:o.dataSource)==null?void 0:T.semanticDomainId,{data:x}=s.useJoinabilityMap(p),u=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy"),...a("detailColumns")],C=k.useCallback(B=>B.startsWith("card-source-")?"source":B.startsWith("card-")?null:B.startsWith("source-")||n.find(M=>M.id===B)?"source":a("groupBy").find(M=>M.id===B)?"groupBy":a("metrics").find(M=>M.id===B)?"metrics":a("pivotBy").find(M=>M.id===B)?"pivotBy":a("sortBy").find(M=>M.id===B)?"sortBy":a("detailColumns").find(M=>M.id===B)?"detailColumns":null,[n,a]),y=k.useCallback(B=>{d(B.active.id)},[]),h=k.useCallback(B=>{var E;const{active:M,over:A}=B;if(!A||!t){d(null);return}const j=M.id,w=A.id,I=C(j),f=C(w)||w;if(f==="sortBy"){if(I==="source"){const b=n.find(F=>F.id===j);if(!b){d(null);return}if(!(a("groupBy").some(F=>F.name===b.name&&F.qualifiedEntityName===b.qualifiedEntityName)||a("metrics").some(F=>F.name===b.name&&F.qualifiedEntityName===b.qualifiedEntityName)||a("detailColumns").some(F=>F.name===b.name&&F.qualifiedEntityName===b.qualifiedEntityName))){d(null);return}}else if(I==="pivotBy"){d(null);return}else if(I!=="groupBy"&&I!=="metrics"&&I!=="sortBy"&&I!=="detailColumns"){d(null);return}}if(I==="source"&&f==="sortBy"){const b=[...n].find(S=>S.id===j);if(!b){d(null);return}const D=a("sortBy");if(s.fieldAlreadyExists(b,D)){d(null);return}const F=s.validateFieldForChartType(b,"sortBy",o.type);if(!F.isValid){s.ue.error("Invalid Field Type",{description:F.reason,position:"top-center",duration:3e3}),d(null);return}const V=s.getNewField(b,"sortBy",D);d(null),r("sortBy",[...D,V]);return}if(I==="source"&&f!=="source"&&f!=="sortBy"){const b=[...n].find(O=>O.id===j);if(!b){d(null);return}const D=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy"),...a("detailColumns")],F=D.filter(O=>!m(O));if(F.length>0){const O=F[0].qualifiedEntityName;if(!O){d(null);return}if(O!==b.qualifiedEntityName&&!m(b)&&b.qualifiedEntityName)if(p&&(x!=null&&x.joinabilityMap)){if(s.calculateFieldState(b,{joinabilityMap:x.joinabilityMap,selectedFields:D,baseEntityName:(E=l==null?void 0:l.baseEntity)==null?void 0:E.name}).state==="unreachable"){s.showJoinRequiredNotification(),d(null);return}}else{if(!l){s.showJoinRequiredNotification(),d(null);return}if(!s.areEntitiesJoined(O,b.qualifiedEntityName,l)){s.showJoinRequiredNotification(),d(null);return}}}const V=a(f);if(s.fieldAlreadyExists(b,V)){d(null);return}const S=s.validateFieldForChartType(b,f,o.type);if(!S.isValid){s.ue.error("Invalid Field Type",{description:S.reason,position:"top-center",duration:3e3}),d(null);return}const L=s.getNewField(b,f,V),v=[...V,L];d(null),r(f,v),f==="metrics"&&t&&s.cleanupKpiMetricComparisonMode(o.type,o.config,c,t,v);return}if(I&&f&&I!=="source"&&f!=="source"&&I!==f){const b=a(I),D=a(f),F=b.find(O=>O.id===j);if(!F){d(null);return}const V=s.validateFieldForChartType(F,f,o.type);if(!V.isValid){s.ue.error("Invalid Field Type",{description:V.reason,position:"top-center",duration:3e3}),d(null);return}const S=s.getNewField(F,f,D);if(d(null),f==="sortBy"){s.fieldAlreadyExists(F,D)||r(f,[...D,S]);return}const L=b.filter(O=>O.id!==j),v=[...D,S];r(I,L),r(f,v),f==="metrics"&&t&&s.cleanupKpiMetricComparisonMode(o.type,o.config,c,t,v);return}if(I&&f&&I===f&&I!=="source"){const b=a(I),D=b.findIndex(V=>V.id===j),F=b.findIndex(V=>V.id===w);if(D!==F){const V=s.arrayMove(b,D,F);r(I,V)}}d(null)},[t,n,a,r,C,l,p,x,m,o.type,c,o.config]),g=i?u.find(B=>B.id===i):null;return{activeId:i,activeField:g,handleDragStart:y,handleDragEnd:h}}function tl({activeView:t,onViewChange:n,splitViewEnabled:a}){const r=s.useEditorStore(c=>c.card),{config:i}=k.useContext(s.SemaphorContext).tokenProps,d=(i==null?void 0:i.showInfoTab)!==!1,o=()=>a?!1:!["table","pivotTable","aggregateTable","detailTable"].includes(r.type);return e.jsx(s.Tabs,{value:t,onValueChange:c=>n(c),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"}),o()&&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:"rounded-md transition data-[state=active]:bg-muted",children:"Info"})]})})}const al=[{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 nl(){var l,m;const t=s.useEditorStore(p=>p.card),{updateRowLimit:n}=s.useEditorActions(),[a,r]=k.useState(!1),[i,d]=k.useState(""),o=p=>{if(p==="custom"){r(!0);return}r(!1),n(t.id,parseInt(p))},c=p=>{const x=p.target.value;d(x),x&&!isNaN(parseInt(x))&&n(t.id,parseInt(x))};return e.jsx("div",{className:"flex items-center gap-2",children:a?e.jsx(s.Input,{type:"number",value:i,onChange:c,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((m=(l=t.config)==null?void 0:l.rowLimit)==null?void 0:m.toString())||"100",onValueChange:o,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:al.map(p=>e.jsx(s.SelectItem,{value:p.value,children:p.label},p.value))})]})})}function rl({card:t,queryData:n,isLoading:a,isFetching:r,pagination:i,onPaginationChange:d,onSortChange:o,sortState:c,splitViewEnabled:l}){const m=k.useMemo(()=>(n==null?void 0:n.records)||[],[n==null?void 0:n.records]);return!l||["table","pivotTable","aggregateTable","detailTable"].includes(t.type)?e.jsx(is,{}):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(is,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{defaultSize:40,minSize:20,role:"results-section",className:"flex flex-col",children:e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:[(a||r)&&(n==null?void 0:n.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),(n==null?void 0:n.records)&&e.jsx(s.TableVisual,{card:t,data:m,paginationMetadata:i,onPaginationChange:d,isLoading:a||r,onSortChange:o,sortState:c})]})})]})}const ll="semaphor-split-view-enabled";function ol(){return lt(ll,!0)}function il({activeView:t,onViewChange:n,onFiltersClick:a,activeCard:r,columns:i}){var ee,$,Y;const d=s.useEditorStore(H=>H.card),o=s.useDashboardStore(H=>H.filterValues),c=s.useDashboardStore(H=>H.selectedSheetId),l=s.useDashboardStore(H=>H.inlineFilterValuesMap[(r==null?void 0:r.id)||""]),{updateCardConfig:m,setCard:p,updateCardInFrame:x,setShowAIDialog:u}=s.useEditorActions(),C=s.useEditorStore(H=>H.showAIDialog),y=s.useDashboardStore(H=>H.isVisualEditing),[h,g]=k.useState(!1),[N,T]=k.useState(!1),[B,M]=k.useState(null),{config:A}=k.useContext(s.SemaphorContext).tokenProps,j=(A==null?void 0:A.showInfoTab)!==!1,w=(A==null?void 0:A.showQueryDebugTools)!==!1,[I,f]=ol();s.useEditorStore(H=>{var ne;return!!((ne=H.card.customCardPreferences)!=null&&ne.url)});const{data:E,errorMessage:b,isLoading:D,isFetching:F,errorSql:V,pagination:S,refetch:L,comparisonMetadata:v,queryRequestPayload:O}=s.useDashboardCardQuery(r),R=k.useMemo(()=>(E==null?void 0:E.records)||[],[E==null?void 0:E.records]),[P,U]=k.useState(!1);k.useEffect(()=>{F||U(!1)},[F]);const q=()=>{const H=!I;H&&t==="table"&&n("chart"),f(H)},_=(H,ne)=>{const K={...r,paginationConfig:{page:H+1,pageSize:ne}};p(K),x(K)},W=H=>{if(!d.config)return;const ne=s.sortStateToSortByColumns(H,d.config.metricColumns,d.config.groupByColumns,d.config.detailColumns);m(d.id,{...d.config,sortByColumns:ne})},J=k.useMemo(()=>{var H;return s.sortByColumnsToSortState((H=d.config)==null?void 0:H.sortByColumns)},[(ee=d.config)==null?void 0:ee.sortByColumns]);return e.jsx("div",{className:s.cn("relative flex w-0 grow flex-col",{"border-l":C&&y}),children: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("div",{className:"w-[260px]",children:e.jsx(us,{variant:"outline"})}),e.jsx(tl,{activeView:t,onViewChange:n,splitViewEnabled:I}),e.jsx(s.FilterInfo,{cardId:r.id,cardFilters:($=r.config)==null?void 0:$.filters,cardFilterCount:s.getFilterCount(((Y=r.config)==null?void 0:Y.filters)||null),onFiltersClick:a,inlineFilters:r.inlineFilters,inlineFilterValues:l,sheetId:c||""}),v&&d.type!=="table"&&e.jsx(s.ComparisonMetadataBadge,{metadata:v,variant:"compact"}),e.jsx("div",{className:"ml-2",children:e.jsx(nl,{})}),C&&e.jsx(fe.EditorClearButton,{})]}),e.jsxs("div",{className:s.cn("flex grow items-center justify-end gap-2"),children:[e.jsx(s.IconButton,{tooltip:"Refresh",disabled:D||F,onClick:()=>{U(!0),L()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":P})})}),t==="chart"&&e.jsx(s.IconButton,{tooltip:I?"Hide Results Table":"Show Results Table",onClick:q,children:I?e.jsx(Yt,{className:"size-4"}):e.jsx(ia,{className:"size-4"})}),t==="chart"&&e.jsx(e.Fragment,{children:e.jsx(mt,{})}),!C&&e.jsx(s.IconButton,{onClick:()=>u(!C),tooltip:"AI",className:"h-8","aria-label":"AI",children:e.jsx(s.Sparkles,{className:"size-4"})})]})]}),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":I&&!["table","pivotTable","aggregateTable","detailTable"].includes(r.type)}),children:e.jsx(rl,{card:r,queryData:E,isLoading:D,isFetching:F,pagination:S,onPaginationChange:_,onSortChange:W,sortState:J,splitViewEnabled:I})}),t==="table"&&(E==null?void 0:E.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:[(D||F)&&(E==null?void 0:E.records)&&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"})}),e.jsx(s.TableVisual,{card:r,data:R,comparisonMetadata:v,paginationMetadata:S,onPaginationChange:_,isLoading:D||F,onSortChange:W,sortState:J})]}),t==="info"&&j&&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:b?e.jsx(ds,{error:b,errorSql:V,onSendFeedback:()=>{const H=s.prepareFeedbackData(s.FeedbackCategory.QUERY_GENERATION,{cardConfig:d.config,dataSource:r.dataSource,dashboardFilters:o,errorMessage:b,errorSql:V,generatedSql:E==null?void 0:E.sql});M(H),T(!0)},onOpenInEditor:()=>{u(!0),setTimeout(()=>{const H=s.useEditorStore.getState().actions;H.setIsDevMode(!0),H.setCardSql(V||""),setTimeout(()=>{H.setRunSql(!0)},100)},100)}}):(E==null?void 0:E.sql)&&e.jsx(ct,{sql:E.sql,showCardDetails:!0,debugPayloads:w?{queryRequest:O,queryResponse:E,columns:i,dashboardFilters:o}:void 0})})})]}),B&&e.jsx(s.FeedbackDialog,{open:N,onOpenChange:T,feedbackData:B})]})})}function cl({activeField:t}){const[n,a]=k.useState(!0);return k.useEffect(()=>{t&&a(!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 ${n?"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(ms,{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 dl=()=>{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 n=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},a=r=>{var i;if((i=r.reason)!=null&&i.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",n,!0),window.addEventListener("unhandledrejection",a,!0),()=>{console.error=t,window.removeEventListener("error",n,!0),window.removeEventListener("unhandledrejection",a,!0)}};function ul({column:t,isSelected:n,onSelect:a,availableFields:r,width:i,onWidthChange:d}){var R,P,U;const o=s.useEditorStore(q=>q.card),{updateCardConfig:c,removeGroupByColumn:l,removeMetricColumn:m,updateFilters:p}=s.useEditorActions(),[x,u]=k.useState(!1),[C,y]=k.useState(!1),h=k.useRef(null),g=k.useCallback(q=>{q.preventDefault(),q.stopPropagation(),y(!0),h.current={startX:q.clientX,startWidth:i||150};const _=J=>{if(!h.current)return;const ee=J.clientX-h.current.startX,$=Math.max(80,h.current.startWidth+ee);d==null||d(t.id,$)},W=()=>{y(!1),h.current=null,document.removeEventListener("mousemove",_),document.removeEventListener("mouseup",W)};document.addEventListener("mousemove",_),document.addEventListener("mouseup",W)},[i,t.id,d]),N=(R=o==null?void 0:o.config)==null?void 0:R.filters,T=(P=N==null?void 0:N.conditions)==null?void 0:P.some(q=>q.field.name===t.name&&q.field.qualifiedEntityName===t.qualifiedEntityName),B=q=>{q?p(o.id,q):c(o.id,{filters:void 0})},{attributes:M,listeners:A,setNodeRef:j,transform:w,transition:I,isDragging:f}=s.useSortable({id:t.id}),E={transform:s.CSS.Transform.toString(w),transition:I},b=s.getDataType(t.dataType),D=ml(b),F=()=>{var W;const q=((W=o==null?void 0:o.config)==null?void 0:W.sortByColumns)||[],_=q.findIndex(J=>J.name===t.name);if(_!==-1){const J=[...q];J[_]={...J[_],direction:"asc"},c(o.id,{sortByColumns:J})}else c(o.id,{sortByColumns:[...q,{...t,id:`sort-${t.id}`,role:"sortby",direction:"asc"}]})},V=()=>{var W;const q=((W=o==null?void 0:o.config)==null?void 0:W.sortByColumns)||[],_=q.findIndex(J=>J.name===t.name);if(_!==-1){const J=[...q];J[_]={...J[_],direction:"desc"},c(o.id,{sortByColumns:J})}else c(o.id,{sortByColumns:[...q,{...t,id:`sort-${t.id}`,role:"sortby",direction:"desc"}]})},S=()=>{var W;const q=((W=o==null?void 0:o.config)==null?void 0:W.groupByColumns)||[];if(!q.some(J=>J.name===t.name)){const J={...t,id:`groupby-${t.id}-${Date.now()}`,role:"groupby"};c(o.id,{groupByColumns:[...q,J]})}},L=q=>{var J;const _=((J=o==null?void 0:o.config)==null?void 0:J.metricColumns)||[];if(!_.some(ee=>ee.name===t.name&&ee.aggregate===q)){const ee={...t,id:`metric-${t.id}-${q}-${Date.now()}`,label:`${q} of ${t.label||t.name}`,role:"metric",aggregate:q};c(o.id,{metricColumns:[..._,ee]})}},v=()=>{t.role==="groupby"?l(o.id,t.id):t.role==="metric"&&m(o.id,t.id)},O={...E,width:i?`${i}px`:void 0,minWidth:i?`${i}px`:"120px"};return e.jsxs("th",{ref:j,style:O,className:s.cn("group relative border-r border-border bg-background px-1 py-0",f&&"opacity-50",n&&"bg-primary/10",C&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...M,...A,className:"cursor-grab p-1 text-muted-foreground opacity-0 transition-opacity hover:text-foreground group-hover:opacity-100 active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-3 w-3"})}),e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsxs("button",{onClick:a,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",n&&"bg-primary/10"),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(D,{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,")"]}),T&&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:()=>u(!0),children:[e.jsx(s.Filter,{className:s.cn("mr-2 h-4 w-4",T&&"text-primary")}),T?"Edit Filter":"Filter"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:F,children:[e.jsx(_t,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(s.DropdownMenuItem,{onClick:V,children:[e.jsx(Ut,{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:S,children:[e.jsx(cs,{className:"mr-2 h-4 w-4"}),"Group by this column"]}),e.jsxs(s.DropdownMenuItem,{disabled:!0,children:[e.jsx(et,{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:v,className:"text-destructive focus:text-destructive",children:[e.jsx(s.Trash2,{className:"mr-2 h-4 w-4"}),"Remove column"]})]})]})]}),e.jsx("div",{onMouseDown:g,className:s.cn("absolute right-0 top-0 h-full w-1 cursor-col-resize bg-transparent hover:bg-primary/50",C&&"bg-primary")}),e.jsx(bt,{open:x,onOpenChange:u,availableFields:r.length>0?r:[t],existingFilters:N,editingCondition:T?(U=N==null?void 0:N.conditions)==null?void 0:U.find(q=>q.field.name===t.name&&q.field.qualifiedEntityName===t.qualifiedEntityName):void 0,onSave:B})]})}function ml(t){switch(t){case"number":return s.Hash;case"date":return s.Calendar;case"string":default:return s.Type}}function xl({selectedColumn:t,onColumnSelect:n,isLoading:a=!1,sourceFields:r=[]}){var I,f,E,b;const i=s.useEditorStore(D=>D.card),{updateCardConfig:d}=s.useEditorActions(),[o,c]=k.useState(null),[l,m]=k.useState({}),[p,x]=k.useState(!1),u=k.useMemo(()=>{var V,S;const D=((V=i==null?void 0:i.config)==null?void 0:V.groupByColumns)||[],F=((S=i==null?void 0:i.config)==null?void 0:S.metricColumns)||[];return[...D,...F]},[(I=i==null?void 0:i.config)==null?void 0:I.groupByColumns,(f=i==null?void 0:i.config)==null?void 0:f.metricColumns]),C=k.useMemo(()=>{const D=new Set(u.map(F=>`${F.qualifiedEntityName}.${F.name}`));return r.filter(F=>!D.has(`${F.qualifiedEntityName}.${F.name}`))},[r,u]),{data:y,isLoading:h}=s.useDashboardCardQuery(i),g=(y==null?void 0:y.records)||[],N=k.useCallback((D,F)=>{m(V=>({...V,[D]:F}))},[]),T=k.useCallback(D=>{var L,v;const F=s.getDataType(D.dataType),V=((L=i==null?void 0:i.config)==null?void 0:L.groupByColumns)||[],S=((v=i==null?void 0:i.config)==null?void 0:v.metricColumns)||[];if(F==="number"){const O={...D,id:`metric-${D.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};d(i.id,{metricColumns:[...S,O]})}else{const O={...D,id:`groupby-${D.id}-${Date.now()}`,role:"groupby"};d(i.id,{groupByColumns:[...V,O]})}x(!1)},[(E=i==null?void 0:i.config)==null?void 0:E.groupByColumns,(b=i==null?void 0:i.config)==null?void 0:b.metricColumns,i.id,d]),B=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),M=D=>{c(D.active.id)},A=D=>{const{active:F,over:V}=D;if(c(null),!V||F.id===V.id)return;const S=u.findIndex(v=>v.id===F.id),L=u.findIndex(v=>v.id===V.id);if(S!==-1&&L!==-1){const v=s.arrayMove(u,S,L),O=v.filter(P=>P.role==="groupby"),R=v.filter(P=>P.role==="metric");d(i.id,{groupByColumns:O,metricColumns:R})}},j=o?u.find(D=>D.id===o):null,w=D=>{let F="";for(;D>=0;)F=String.fromCharCode(D%26+65)+F,D=Math.floor(D/26)-1;return F};return a?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"})}):u.length===0?e.jsx("div",{className:"flex h-full flex-col items-center justify-center gap-4 p-8 text-center",children:e.jsxs("div",{className:"rounded-lg border-2 border-dashed border-muted-foreground/25 p-12",children:[e.jsx("h3",{className:"text-lg font-medium text-muted-foreground",children:"No columns selected"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground/75",children:"Select columns from the panel on the right to build your table"})]})}):e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsxs(s.DndContext,{sensors:B,collisionDetection:s.closestCenter,onDragStart:M,onDragEnd:A,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:u.map(D=>D.id),strategy:s.horizontalListSortingStrategy,children:u.map((D,F)=>e.jsx("th",{style:{width:l[D.id]?`${l[D.id]}px`:void 0,minWidth:l[D.id]?`${l[D.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:w(F)},`letter-${D.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:u.map(D=>D.id),strategy:s.horizontalListSortingStrategy,children:u.map(D=>e.jsx(ul,{column:D,isSelected:(t==null?void 0:t.id)===D.id,onSelect:()=>n(D),availableFields:r,width:l[D.id],onWidthChange:N},D.id))}),e.jsx("th",{className:"w-10 border-r border-border bg-background px-1 py-2",children:e.jsxs(s.Popover,{open:p,onOpenChange:x,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:C.map(D=>{const F=s.getDataType(D.dataType),V=F==="number"?s.Hash:F==="date"?s.Calendar:s.Type;return e.jsxs(s.CommandItem,{value:D.label||D.name,onSelect:()=>T(D),children:[e.jsx(V,{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:D.label||D.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:D.entityName})]})]},D.id)})})]})]})})]})})]})]}),e.jsx("tbody",{children:h?e.jsx("tr",{children:e.jsx("td",{colSpan:u.length+2,className:"h-32 text-center",children:e.jsx(s.LoaderCircle,{className:"mx-auto h-6 w-6 animate-spin text-muted-foreground"})})}):g.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:u.length+2,className:"h-32 text-center text-muted-foreground",children:"No data available"})}):g.slice(0,100).map((D,F)=>e.jsxs("tr",{className:s.cn("border-b border-border transition-colors hover:bg-muted/50",F%2===0?"bg-background":"bg-muted/20"),children:[e.jsx("td",{className:"sticky left-0 z-10 w-12 border-r border-border bg-muted/50 px-2 py-2 text-center text-xs font-medium text-muted-foreground",children:F+1}),u.map(V=>{const S=D[V.name]??D[V.label??""];return e.jsx("td",{style:{width:l[V.id]?`${l[V.id]}px`:void 0,minWidth:l[V.id]?`${l[V.id]}px`:"120px"},className:s.cn("border-r border-border px-3 py-2 text-sm",(t==null?void 0:t.id)===V.id&&"bg-primary/5"),children:e.jsx("span",{className:"block truncate",children:hl(S,V)})},`${F}-${V.id}`)}),e.jsx("td",{className:"w-10 border-r border-border"})]},F))})]}),e.jsx(s.DragOverlay,{children:j&&e.jsx("div",{className:"rounded border border-primary bg-background px-3 py-2 text-sm font-medium shadow-lg",children:j.label||j.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(g.length,100)," of ",g.length," rows"]}),e.jsxs("span",{children:[u.length," columns"]})]})]})}function hl(t,n){if(t==null)return"—";if(typeof t=="number")return n.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 a=new Date(t);if(!isNaN(a.getTime()))return a.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}return String(t)}function pl({entityGroups:t,isLoading:n=!1}){var B,M;const a=s.useEditorStore(A=>A.card),{updateCardConfig:r,removeGroupByColumn:i,removeMetricColumn:d}=s.useEditorActions(),[o,c]=k.useState(!0),[l,m]=k.useState(""),[p,x]=k.useState(new Set),u=((B=a==null?void 0:a.config)==null?void 0:B.groupByColumns)||[],C=((M=a==null?void 0:a.config)==null?void 0:M.metricColumns)||[],y=A=>{const j=new Set(p);j.has(A)?j.delete(A):j.add(A),x(j)},h=A=>u.some(j=>j.name===A.name&&j.qualifiedEntityName===A.qualifiedEntityName)||C.some(j=>j.name===A.name&&j.qualifiedEntityName===A.qualifiedEntityName),g=(A,j)=>{if(j)if(s.getDataType(A.dataType)==="number"){const I={...A,id:`metric-${A.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};r(a.id,{metricColumns:[...C,I]})}else{const I={...A,id:`groupby-${A.id}-${Date.now()}`,role:"groupby"};r(a.id,{groupByColumns:[...u,I]})}else{const w=u.findIndex(f=>f.name===A.name&&f.qualifiedEntityName===A.qualifiedEntityName),I=C.findIndex(f=>f.name===A.name&&f.qualifiedEntityName===A.qualifiedEntityName);w!==-1&&i(a.id,u[w].id),I!==-1&&d(a.id,C[I].id)}},N=A=>{if(!l)return A;const j=l.toLowerCase();return A.filter(w=>w.name.toLowerCase().includes(j)||w.label&&w.label.toLowerCase().includes(j))},T=A=>{switch(s.getDataType(A)){case"number":return s.Hash;case"date":return s.Calendar;default:return s.Type}};return o?e.jsxs("div",{className:"flex h-full w-72 flex-col border-l border-border bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border px-3 py-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Columns"}),e.jsx(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(aa,{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,{placeholder:"Search columns...",value:l,onChange:A=>m(A.target.value),className:"h-8 pl-8 text-sm"})]})}),(u.length>0||C.length>0)&&e.jsxs("div",{className:"border-b border-border",children:[u.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(cs,{className:"h-3.5 w-3.5 text-blue-500"}),e.jsx("span",{children:"Groupings"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:u.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:u.map(A=>{const j=T(A.dataType);return e.jsxs("div",{className:"group flex items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted/50",children:[e.jsx(s.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(j,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:A.label||A.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:()=>i(a.id,A.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},A.id)})})})]}),C.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:C.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:C.map(A=>{const j=T(A.dataType);return e.jsxs("div",{className:"group flex items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted/50",children:[e.jsx(s.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(j,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:A.label||A.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:A.aggregate}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>d(a.id,A.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},A.id)})})})]})]}),e.jsx(s.ScrollArea,{className:"flex-1",children:e.jsx("div",{className:"p-2",children:n?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent"})}):t.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No columns available"}):t.map(A=>{const j=N(A.columns);if(j.length===0)return null;const w=p.has(A.entityId)||l.length>0;return e.jsxs(s.Collapsible,{open:w,onOpenChange:()=>y(A.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",w&&"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:A.label||A.entityName}),e.jsx("span",{className:"text-xs text-muted-foreground",children:j.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:j.map(I=>{const f=T(I.dataType),E=h(I);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",E&&"bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:E,onCheckedChange:b=>g(I,b),className:"h-3.5 w-3.5"}),e.jsx(f,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:I.label||I.name})]},I.id)})})})]},A.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(na,{className:"h-4 w-4"})})})}const fl=[{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 gl({value:t,onChange:n,onSubmit:a,onCancel:r,selectedColumn:i,availableColumns:d}){const[o,c]=k.useState(!1),[l,m]=k.useState("column"),p=k.useRef(null);k.useEffect(()=>{const y=h=>{h.key==="Escape"&&t?r():h.key==="Enter"&&t&&!o&&a(t)};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[t,r,a,o]);const x=y=>{const h=`[${y.label||y.name}]`,g=p.current;if(g){const N=g.selectionStart||0,T=g.selectionEnd||0,B=t.slice(0,N)+h+t.slice(T);n(B),setTimeout(()=>{g.setSelectionRange(N+h.length,N+h.length),g.focus()},0)}else n(t+h);c(!1)},u=y=>{const h=p.current;if(h){const g=h.selectionStart||0,N=h.selectionEnd||0,T=t.slice(0,g)+y.syntax+t.slice(N);n(T),setTimeout(()=>{h.setSelectionRange(g+y.name.length+1,g+y.syntax.length-1),h.focus()},0)}else n(t+y.syntax);c(!1)},C=y=>{switch(s.getDataType(y)){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:i?e.jsx("span",{className:"truncate",children:i.label||i.name}):e.jsx("span",{children:"—"})}),e.jsxs(s.Popover,{open:o&&l==="function",onOpenChange:y=>{c(y),y&&m("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(oa,{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:fl.map(y=>e.jsx(s.CommandItem,{value:y.name,onSelect:()=>u(y),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:y.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:y.description})]}),e.jsx("span",{className:"font-mono text-xs text-muted-foreground/75",children:y.syntax})]})},y.name))})]})]})})]}),e.jsxs(s.Popover,{open:o&&l==="column",onOpenChange:y=>{c(y),y&&m("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(y=>{const h=C(y.dataType);return e.jsxs(s.CommandItem,{value:y.label||y.name,onSelect:()=>x(y),children:[e.jsx(h,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:y.label||y.name})]},y.id)})})]})]})})]}),e.jsx("div",{className:"relative flex-1",children:e.jsx(s.Input,{ref:p,value:t,onChange:y=>n(y.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:()=>a(t),title:"Apply (Enter)",children:e.jsx(s.Check,{className:"h-4 w-4"})})]})]})}function jl({className:t}){var u,C,y,h;const n=s.useEditorStore(g=>g.card),[a,r]=k.useState(null),[i,d]=k.useState(""),{columns:o=[],columnGroups:c=[],isLoading:l}=s.useColumns();(u=n==null?void 0:n.config)!=null&&u.groupByColumns,(C=n==null?void 0:n.config)!=null&&C.metricColumns,(y=n==null?void 0:n.config)!=null&&y.groupByColumns,(h=n==null?void 0:n.config)!=null&&h.pivotByColumns;const m=g=>{r(g),d(g?`[${g.label||g.name}]`:"")},p=g=>{console.log("Formula submitted:",g),d(""),r(null)},x=()=>{d(""),r(null)};return e.jsxs("div",{className:s.cn("flex h-full w-full flex-col",t),children:[e.jsx(gl,{value:i,onChange:d,onSubmit:p,onCancel:x,selectedColumn:a,availableColumns:o}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(xl,{selectedColumn:a,onColumnSelect:m,isLoading:l,sourceFields:o})}),e.jsx(pl,{entityGroups:c,isLoading:l})]})]})}function bl(){var L,v;const[t,n]=k.useState("chart"),[a,r]=k.useState(!1),[i,d]=k.useState(!0),o=s.useEditorStore(O=>O.showAIDialog),c=s.useDashboardStore(O=>O.isVisualEditing),{setCardType:l}=s.useEditorActions(),m=s.useEditorStore(O=>O.card.type);k.useEffect(()=>dl(),[]);const p=O=>{l(O)},x=s.useEditorStore(O=>O.frame),u=s.useEditorStore(O=>O.card);s.useEditorStore(O=>O.activeTabCardId),s.useEditorStore(O=>O.actions.getAvailableFields);const{addCard:C,removeCard:y,updateCard:h,setActiveCard:g,updateFilters:N}=s.useEditorActions(),{columnFields:T=[],scopedFields:B=[]}=s.useScopedFields(),M=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),A=u,{getFieldsForContainer:j,setFieldsForContainer:w}=s.useFieldManagement(A),{activeField:I,handleDragStart:f,handleDragEnd:E}=sl({activeCardId:x.activeCardId,sourceFields:B,getFieldsForContainer:j,setFieldsForContainer:w}),b=(O,R)=>{R&&N(O,R)},D=O=>{var R;h(O,{config:{...(R=x.cards.find(P=>P.id===O))==null?void 0:R.config,filters:void 0}})},F=T,V=O=>{if(!O)return 0;let R=O.conditions.length;return O.groups.forEach(P=>{R+=V(P)}),R},S=V(((L=A==null?void 0:A.config)==null?void 0:L.filters)||null);return e.jsxs(s.DndContext,{sensors:M,collisionDetection:s.closestCenter,onDragStart:f,onDragEnd:E,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(ot,{isVisible:i,onToggleVisibility:()=>d(!i)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:m==="tableBuilder"?e.jsx(jl,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!o&&e.jsx(Br,{selectedChart:m,onChartChange:p,groupByFields:j("groupBy"),pivotByFields:j("pivotBy"),metricsFields:j("metrics"),sortByFields:j("sortBy"),detailFields:j("detailColumns"),activeField:I}),e.jsx(il,{selectedChart:m,activeView:t,onViewChange:n,onFiltersClick:()=>r(!0),filterCount:S,activeCard:A,columns:T,getFieldsForContainer:j,cards:x.cards,activeCardId:x.activeCardId,addCard:C,setActiveCard:g})]})}),!i&&c&&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:()=>d(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),A&&e.jsx(el,{cardId:A.id,filters:((v=A.config)==null?void 0:v.filters)||null,onFiltersChange:b,onClearFilters:D,availableFields:F,isOpen:a,onOpenChange:r}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(cl,{activeField:I||null})})]})}function yl({authToken:t,onSave:n,onClose:a}){const r=k.useRef(null),i=s.useEditorStore(j=>j.showAIDialog),d=s.useEditorStore(j=>j.isDevMode),o=s.useAssistantLayoutStore(j=>j.setFullscreen),c=s.useAssistantLayoutStore(j=>j.setPanelOpen),l=s.useAssistantLayoutStore(j=>j.setContainer),m=s.useAssistantPanel("editor"),p=s.useFullscreenAssistant(),x=s.useAssistantContainer("editor"),u=p==="editor",C=k.useCallback(j=>{l("editor",j)},[l]),{setAuthToken:y}=s.useDashboardActions(),{setShowAIDialog:h,setOnSave:g,setOnClose:N}=s.useEditorActions(),{setActiveAssistantType:T}=s.useAIActions();k.useEffect(()=>{n&&g(n),a&&N(a)},[n,g,a,N]),k.useEffect(()=>{t&&t.accessToken&&y(t)},[t,y]),k.useEffect(()=>{var j,w;i?((j=r.current)==null||j.resize(40),c("editor",!0),T("editor")):((w=r.current)==null||w.resize(0),c("editor",!1),p==="editor"&&o(null),T(null))},[i,c,T,o,p]);function B(j){var w;j<1?(h(!1),c("editor",!1),p==="editor"&&o(null),T(null),(w=r.current)==null||w.resize(0)):(i||(h(!0),T("editor")),m.isOpen||c("editor",!0))}function M(){return e.jsxs(e.Fragment,{children:[e.jsx(ot,{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",u&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(gr,{})}),e.jsx(s.ResizableHandle,{disabled:!i}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:B,defaultSize:m.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Qs,{isFullscreen:u,onFullscreenChange:j=>o(j?"editor":null),fullscreenContainer:x})})})]}),e.jsx("div",{ref:C,className:s.cn("absolute inset-0",!u&&"pointer-events-none")})]})]})}function A(){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",u&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(bl,{})}),e.jsx(s.ResizableHandle,{disabled:!i}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:B,defaultSize:m.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Qs,{isFullscreen:u,onFullscreenChange:j=>o(j?"editor":null),fullscreenContainer:x})})})]}),e.jsx("div",{ref:C,className:s.cn("absolute inset-0",!u&&"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:M()}):A()})}function vl(){s.useDashboardStore(l=>l.selectedCardId);const t=s.useDashboardStore(l=>l.selectedSheetId),n=s.useDashboardStore(l=>l.dashboard),{setIsVisualEditing:a,setSelectedSheetId:r}=s.useDashboardStore(l=>l.actions),i=s.useDashboardStore(l=>l.isVisualEditing),d=s.useDashboardStore(l=>l.actions.updateFrame);function o(l){var u,C,y;const m=t?(u=n==null?void 0:n.sheets)==null?void 0:u.some(h=>{var g;return h.id===t&&((g=h.frames)==null?void 0:g.some(N=>N.id===l.id))}):!1,p=(y=(C=n==null?void 0:n.sheets)==null?void 0:C.find(h=>{var g;return(g=h.frames)==null?void 0:g.some(N=>N.id===l.id)}))==null?void 0:y.id,x=m?t:p||null;x&&(d(x,l),t!==x&&r(x),a(!1))}function c(){a(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!i}),children:e.jsx(yl,{onSave:o,onClose:c})})}exports.default=vl;