react-semaphor 0.1.260 → 0.1.261

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/chunks/dashboard-controls-0hbftZxY.js +42 -0
  2. package/dist/chunks/dashboard-controls-BYi_r2lH.js +1971 -0
  3. package/dist/chunks/dashboard-filter-controls-button-BPCw1GMh.js +1066 -0
  4. package/dist/chunks/dashboard-filter-controls-button-f4pDkDUL.js +11 -0
  5. package/dist/chunks/{dashboard-json-U7VmojaR.js → dashboard-json-2NJCXsDD.js} +1 -1
  6. package/dist/chunks/{dashboard-json-BUrApiYl.js → dashboard-json-Dpy-zKf2.js} +1 -1
  7. package/dist/chunks/{dashboard-summary-settings-dialog-DlVBUQmC.js → dashboard-summary-settings-dialog-B9zRCvc-.js} +1 -1
  8. package/dist/chunks/{dashboard-summary-settings-dialog-CaxmCNyy.js → dashboard-summary-settings-dialog-Be3JilRI.js} +1 -1
  9. package/dist/chunks/edit-dashboard-visual-Bon08erH.js +188 -0
  10. package/dist/chunks/{edit-dashboard-visual-N2r5ObJ_.js → edit-dashboard-visual-CqTlmuYL.js} +5970 -5492
  11. package/dist/chunks/index-BoJEr_9F.js +1114 -0
  12. package/dist/chunks/{index-BNdZjo5d.js → index-C2c-_lPE.js} +48333 -44824
  13. package/dist/chunks/{normalize-dashboard-for-dirty-check-Bn27S0PN.js → normalize-dashboard-for-dirty-check-5KpZN8xr.js} +20 -19
  14. package/dist/chunks/normalize-dashboard-for-dirty-check-BXRUMVb2.js +1 -0
  15. package/dist/chunks/{resource-management-panel-C_ZqsVMH.js → resource-management-panel-BtLPW2b4.js} +1 -1
  16. package/dist/chunks/{resource-management-panel-zF23gLOJ.js → resource-management-panel-Bva2_0OU.js} +70 -70
  17. package/dist/chunks/use-create-flow-overlay-state-9X7GyUzl.js +21 -0
  18. package/dist/chunks/use-create-flow-overlay-state-Vyd5mSnf.js +1445 -0
  19. package/dist/chunks/{use-visual-utils-BBTQGDdB.js → use-visual-utils-Jv4hWSLm.js} +1 -1
  20. package/dist/chunks/{use-visual-utils-K1k39w2U.js → use-visual-utils-OPk_1t4I.js} +1 -1
  21. package/dist/dashboard/index.cjs +1 -1
  22. package/dist/dashboard/index.js +5 -4
  23. package/dist/index.cjs +1 -1
  24. package/dist/index.js +102 -99
  25. package/dist/shared/index.cjs +1 -1
  26. package/dist/shared/index.js +1 -1
  27. package/dist/style.css +1 -1
  28. package/dist/surfboard/index.cjs +1 -1
  29. package/dist/surfboard/index.js +5 -4
  30. package/dist/types/dashboard.d.ts +105 -0
  31. package/dist/types/index.cjs +1 -1
  32. package/dist/types/index.js +4 -3
  33. package/dist/types/main.d.ts +175 -1
  34. package/dist/types/shared.d.ts +89 -0
  35. package/dist/types/surfboard.d.ts +105 -0
  36. package/dist/types/types.d.ts +113 -0
  37. package/package.json +1 -1
  38. package/dist/chunks/dashboard-controls-CIdYp98a.js +0 -47
  39. package/dist/chunks/dashboard-controls-DOqBYrkB.js +0 -1847
  40. package/dist/chunks/edit-dashboard-visual-uA-0wLnR.js +0 -193
  41. package/dist/chunks/editor-action-buttons-B6lABkRB.js +0 -412
  42. package/dist/chunks/editor-action-buttons-Dh7Xndgk.js +0 -21
  43. package/dist/chunks/index-DOeggx0V.js +0 -1109
  44. package/dist/chunks/normalize-dashboard-for-dirty-check-B7NQDI1H.js +0 -1
  45. package/dist/chunks/notification-bell-BxyeaeRc.js +0 -839
  46. package/dist/chunks/notification-bell-tJRds5JJ.js +0 -6
@@ -1,193 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),t=require("./index-DOeggx0V.js"),N=require("react"),Me=require("./editor-action-buttons-Dh7Xndgk.js"),dn=require("react-dom");function un(s){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const a in s)if(a!=="default"){const r=Object.getOwnPropertyDescriptor(s,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:()=>s[a]})}}return n.default=s,Object.freeze(n)}const ns=un(N);/**
2
- * @license lucide-react v0.453.0 - ISC
3
- *
4
- * This source code is licensed under the ISC license.
5
- * See the LICENSE file in the root directory of this source tree.
6
- */const mn=t.createLucideIcon("ArrowDownAZ",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M20 8h-5",key:"1vsyxs"}],["path",{d:"M15 10V6.5a2.5 2.5 0 0 1 5 0V10",key:"ag13bf"}],["path",{d:"M15 14h5l-5 6h5",key:"ur5jdg"}]]);/**
7
- * @license lucide-react v0.453.0 - ISC
8
- *
9
- * This source code is licensed under the ISC license.
10
- * See the LICENSE file in the root directory of this source tree.
11
- */const xn=t.createLucideIcon("ArrowUpAZ",[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M20 8h-5",key:"1vsyxs"}],["path",{d:"M15 10V6.5a2.5 2.5 0 0 1 5 0V10",key:"ag13bf"}],["path",{d:"M15 14h5l-5 6h5",key:"ur5jdg"}]]);/**
12
- * @license lucide-react v0.453.0 - ISC
13
- *
14
- * This source code is licensed under the ISC license.
15
- * See the LICENSE file in the root directory of this source tree.
16
- */const wa=t.createLucideIcon("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]);/**
17
- * @license lucide-react v0.453.0 - ISC
18
- *
19
- * This source code is licensed under the ISC license.
20
- * See the LICENSE file in the root directory of this source tree.
21
- */const hn=t.createLucideIcon("Braces",[["path",{d:"M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1",key:"ezmyqa"}],["path",{d:"M16 21h1a2 2 0 0 0 2-2v-5c0-1.1.9-2 2-2a2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1",key:"e1hn23"}]]);/**
22
- * @license lucide-react v0.453.0 - ISC
23
- *
24
- * This source code is licensed under the ISC license.
25
- * See the LICENSE file in the root directory of this source tree.
26
- */const is=t.createLucideIcon("Columns3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
27
- * @license lucide-react v0.453.0 - ISC
28
- *
29
- * This source code is licensed under the ISC license.
30
- * See the LICENSE file in the root directory of this source tree.
31
- */const pn=t.createLucideIcon("Component",[["path",{d:"M15.536 11.293a1 1 0 0 0 0 1.414l2.376 2.377a1 1 0 0 0 1.414 0l2.377-2.377a1 1 0 0 0 0-1.414l-2.377-2.377a1 1 0 0 0-1.414 0z",key:"1uwlt4"}],["path",{d:"M2.297 11.293a1 1 0 0 0 0 1.414l2.377 2.377a1 1 0 0 0 1.414 0l2.377-2.377a1 1 0 0 0 0-1.414L6.088 8.916a1 1 0 0 0-1.414 0z",key:"10291m"}],["path",{d:"M8.916 17.912a1 1 0 0 0 0 1.415l2.377 2.376a1 1 0 0 0 1.414 0l2.377-2.376a1 1 0 0 0 0-1.415l-2.377-2.376a1 1 0 0 0-1.414 0z",key:"1tqoq1"}],["path",{d:"M8.916 4.674a1 1 0 0 0 0 1.414l2.377 2.376a1 1 0 0 0 1.414 0l2.377-2.376a1 1 0 0 0 0-1.414l-2.377-2.377a1 1 0 0 0-1.414 0z",key:"1x6lto"}]]);/**
32
- * @license lucide-react v0.453.0 - ISC
33
- *
34
- * This source code is licensed under the ISC license.
35
- * See the LICENSE file in the root directory of this source tree.
36
- */const Ta=t.createLucideIcon("FileCode2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m5 12-3 3 3 3",key:"oke12k"}],["path",{d:"m9 18 3-3-3-3",key:"112psh"}]]);/**
37
- * @license lucide-react v0.453.0 - ISC
38
- *
39
- * This source code is licensed under the ISC license.
40
- * See the LICENSE file in the root directory of this source tree.
41
- */const fn=t.createLucideIcon("FileJson2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1",key:"fq0c9t"}],["path",{d:"M8 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1",key:"4gibmv"}]]);/**
42
- * @license lucide-react v0.453.0 - ISC
43
- *
44
- * This source code is licensed under the ISC license.
45
- * See the LICENSE file in the root directory of this source tree.
46
- */const gn=t.createLucideIcon("Fullscreen",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{width:"10",height:"8",x:"7",y:"8",rx:"1",key:"vys8me"}]]);/**
47
- * @license lucide-react v0.453.0 - ISC
48
- *
49
- * This source code is licensed under the ISC license.
50
- * See the LICENSE file in the root directory of this source tree.
51
- */const Ea=t.createLucideIcon("GitCompareArrows",[["circle",{cx:"5",cy:"6",r:"3",key:"1qnov2"}],["path",{d:"M12 6h5a2 2 0 0 1 2 2v7",key:"1yj91y"}],["path",{d:"m15 9-3-3 3-3",key:"1lwv8l"}],["circle",{cx:"19",cy:"18",r:"3",key:"1qljk2"}],["path",{d:"M12 18H7a2 2 0 0 1-2-2V9",key:"16sdep"}],["path",{d:"m9 15 3 3-3 3",key:"1m3kbl"}]]);/**
52
- * @license lucide-react v0.453.0 - ISC
53
- *
54
- * This source code is licensed under the ISC license.
55
- * See the LICENSE file in the root directory of this source tree.
56
- */const jn=t.createLucideIcon("Hammer",[["path",{d:"m15 12-8.373 8.373a1 1 0 1 1-3-3L12 9",key:"eefl8a"}],["path",{d:"m18 15 4-4",key:"16gjal"}],["path",{d:"m21.5 11.5-1.914-1.914A2 2 0 0 1 19 8.172V7l-2.26-2.26a6 6 0 0 0-4.202-1.756L9 2.96l.92.82A6.18 6.18 0 0 1 12 8.4V10l2 2h1.172a2 2 0 0 1 1.414.586L18.5 14.5",key:"b7pghm"}]]);/**
57
- * @license lucide-react v0.453.0 - ISC
58
- *
59
- * This source code is licensed under the ISC license.
60
- * See the LICENSE file in the root directory of this source tree.
61
- */const bn=t.createLucideIcon("LayoutList",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}],["path",{d:"M14 4h7",key:"3xa0d5"}],["path",{d:"M14 9h7",key:"1icrd9"}],["path",{d:"M14 15h7",key:"1mj8o2"}],["path",{d:"M14 20h7",key:"11slyb"}]]);/**
62
- * @license lucide-react v0.453.0 - ISC
63
- *
64
- * This source code is licensed under the ISC license.
65
- * See the LICENSE file in the root directory of this source tree.
66
- */const vn=t.createLucideIcon("ListEnd",[["path",{d:"M16 12H3",key:"1a2rj7"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M10 18H3",key:"13769t"}],["path",{d:"M21 6v10a2 2 0 0 1-2 2h-5",key:"ilrcs8"}],["path",{d:"m16 16-2 2 2 2",key:"kkc6pm"}]]);/**
67
- * @license lucide-react v0.453.0 - ISC
68
- *
69
- * This source code is licensed under the ISC license.
70
- * See the LICENSE file in the root directory of this source tree.
71
- */const ea=t.createLucideIcon("ListFilter",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M7 12h10",key:"b7w52i"}],["path",{d:"M10 18h4",key:"1ulq68"}]]);/**
72
- * @license lucide-react v0.453.0 - ISC
73
- *
74
- * This source code is licensed under the ISC license.
75
- * See the LICENSE file in the root directory of this source tree.
76
- */const yn=t.createLucideIcon("ListStart",[["path",{d:"M16 12H3",key:"1a2rj7"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"M10 6H3",key:"lf8lx7"}],["path",{d:"M21 18V8a2 2 0 0 0-2-2h-5",key:"1hghli"}],["path",{d:"m16 8-2-2 2-2",key:"160uvd"}]]);/**
77
- * @license lucide-react v0.453.0 - ISC
78
- *
79
- * This source code is licensed under the ISC license.
80
- * See the LICENSE file in the root directory of this source tree.
81
- */const Nn=t.createLucideIcon("ListX",[["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"m19 10-4 4",key:"1tz659"}],["path",{d:"m15 10 4 4",key:"1n7nei"}]]);/**
82
- * @license lucide-react v0.453.0 - ISC
83
- *
84
- * This source code is licensed under the ISC license.
85
- * See the LICENSE file in the root directory of this source tree.
86
- */const Qt=t.createLucideIcon("MoveHorizontal",[["path",{d:"m18 8 4 4-4 4",key:"1ak13k"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}]]);/**
87
- * @license lucide-react v0.453.0 - ISC
88
- *
89
- * This source code is licensed under the ISC license.
90
- * See the LICENSE file in the root directory of this source tree.
91
- */const Jt=t.createLucideIcon("MoveVertical",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m8 18 4 4 4-4",key:"bh5tu3"}],["path",{d:"m8 6 4-4 4 4",key:"ybng9g"}]]);/**
92
- * @license lucide-react v0.453.0 - ISC
93
- *
94
- * This source code is licensed under the ISC license.
95
- * See the LICENSE file in the root directory of this source tree.
96
- */const Cn=t.createLucideIcon("Palette",[["circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor",key:"1okk4w"}],["circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor",key:"f64h9f"}],["circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor",key:"fotxhn"}],["circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor",key:"qy21gx"}],["path",{d:"M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z",key:"12rzf8"}]]);/**
97
- * @license lucide-react v0.453.0 - ISC
98
- *
99
- * This source code is licensed under the ISC license.
100
- * See the LICENSE file in the root directory of this source tree.
101
- */const Sn=t.createLucideIcon("PanelRightClose",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m8 9 3 3-3 3",key:"12hl5m"}]]);/**
102
- * @license lucide-react v0.453.0 - ISC
103
- *
104
- * This source code is licensed under the ISC license.
105
- * See the LICENSE file in the root directory of this source tree.
106
- */const wn=t.createLucideIcon("PanelRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
107
- * @license lucide-react v0.453.0 - ISC
108
- *
109
- * This source code is licensed under the ISC license.
110
- * See the LICENSE file in the root directory of this source tree.
111
- */const ta=t.createLucideIcon("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/**
112
- * @license lucide-react v0.453.0 - ISC
113
- *
114
- * This source code is licensed under the ISC license.
115
- * See the LICENSE file in the root directory of this source tree.
116
- */const Pt=t.createLucideIcon("Rows3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M21 9H3",key:"1338ky"}],["path",{d:"M21 15H3",key:"9uk58r"}]]);/**
117
- * @license lucide-react v0.453.0 - ISC
118
- *
119
- * This source code is licensed under the ISC license.
120
- * See the LICENSE file in the root directory of this source tree.
121
- */const Tn=t.createLucideIcon("SendHorizontal",[["path",{d:"M3.714 3.048a.498.498 0 0 0-.683.627l2.843 7.627a2 2 0 0 1 0 1.396l-2.842 7.627a.498.498 0 0 0 .682.627l18-8.5a.5.5 0 0 0 0-.904z",key:"117uat"}],["path",{d:"M6 12h16",key:"s4cdu5"}]]);/**
122
- * @license lucide-react v0.453.0 - ISC
123
- *
124
- * This source code is licensed under the ISC license.
125
- * See the LICENSE file in the root directory of this source tree.
126
- */const En=t.createLucideIcon("Shapes",[["path",{d:"M8.3 10a.7.7 0 0 1-.626-1.079L11.4 3a.7.7 0 0 1 1.198-.043L16.3 8.9a.7.7 0 0 1-.572 1.1Z",key:"1bo67w"}],["rect",{x:"3",y:"14",width:"7",height:"7",rx:"1",key:"1bkyp8"}],["circle",{cx:"17.5",cy:"17.5",r:"3.5",key:"w3z12y"}]]);/**
127
- * @license lucide-react v0.453.0 - ISC
128
- *
129
- * This source code is licensed under the ISC license.
130
- * See the LICENSE file in the root directory of this source tree.
131
- */const In=t.createLucideIcon("Sigma",[["path",{d:"M18 7V5a1 1 0 0 0-1-1H6.5a.5.5 0 0 0-.4.8l4.5 6a2 2 0 0 1 0 2.4l-4.5 6a.5.5 0 0 0 .4.8H17a1 1 0 0 0 1-1v-2",key:"wuwx1p"}]]);/**
132
- * @license lucide-react v0.453.0 - ISC
133
- *
134
- * This source code is licensed under the ISC license.
135
- * See the LICENSE file in the root directory of this source tree.
136
- */const rs=t.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"}]]);/**
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 kn=t.createLucideIcon("Spline",[["circle",{cx:"19",cy:"5",r:"2",key:"mhkx31"}],["circle",{cx:"5",cy:"19",r:"2",key:"v8kfzx"}],["path",{d:"M5 17A12 12 0 0 1 17 5",key:"1okkup"}]]);/**
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 Dn=t.createLucideIcon("SquareFunction",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["path",{d:"M9 17c2 0 2.8-1 2.8-2.8V10c0-2 1-3.3 3.2-3",key:"m1af9g"}],["path",{d:"M9 11.2h5.7",key:"3zgcl2"}]]);/**
147
- * @license lucide-react v0.453.0 - ISC
148
- *
149
- * This source code is licensed under the ISC license.
150
- * See the LICENSE file in the root directory of this source tree.
151
- */const An=t.createLucideIcon("SquareSplitVertical",[["path",{d:"M5 8V5c0-1 1-2 2-2h10c1 0 2 1 2 2v3",key:"1pi83i"}],["path",{d:"M19 16v3c0 1-1 2-2 2H7c-1 0-2-1-2-2v-3",key:"ido5k7"}],["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}]]);/**
152
- * @license lucide-react v0.453.0 - ISC
153
- *
154
- * This source code is licensed under the ISC license.
155
- * See the LICENSE file in the root directory of this source tree.
156
- */const Mn=t.createLucideIcon("Tags",[["path",{d:"m15 5 6.3 6.3a2.4 2.4 0 0 1 0 3.4L17 19",key:"1cbfv1"}],["path",{d:"M9.586 5.586A2 2 0 0 0 8.172 5H3a1 1 0 0 0-1 1v5.172a2 2 0 0 0 .586 1.414L8.29 18.29a2.426 2.426 0 0 0 3.42 0l3.58-3.58a2.426 2.426 0 0 0 0-3.42z",key:"135mg7"}],["circle",{cx:"6.5",cy:"9.5",r:".5",fill:"currentColor",key:"5pm5xn"}]]);/**
157
- * @license lucide-react v0.453.0 - ISC
158
- *
159
- * This source code is licensed under the ISC license.
160
- * See the LICENSE file in the root directory of this source tree.
161
- */const Ln=t.createLucideIcon("Wand",[["path",{d:"M15 4V2",key:"z1p9b7"}],["path",{d:"M15 16v-2",key:"px0unx"}],["path",{d:"M8 9h2",key:"1g203m"}],["path",{d:"M20 9h2",key:"19tzq7"}],["path",{d:"M17.8 11.8 19 13",key:"yihg8r"}],["path",{d:"M15 9h.01",key:"x1ddxp"}],["path",{d:"M17.8 6.2 19 5",key:"fd4us0"}],["path",{d:"m3 21 9-9",key:"1jfql5"}],["path",{d:"M12.2 6.2 11 5",key:"i3da3b"}]]);function Ia({storeValue:s,defaultValue:n="",onStoreUpdate:a,delay:r=300}){const[i,c]=N.useState(s??n),o=t.useDebounce(i,r),d=N.useRef(s),l=N.useRef(!1);N.useEffect(()=>{s!==d.current&&(c(s??n),d.current=s)},[s,n]),N.useEffect(()=>{l.current&&o!==d.current&&(a(o),d.current=o)},[o,a]);const m=N.useCallback(p=>{l.current=!0,c(p??n)},[n]);return{value:i,onChange:m}}function On({initialJoinPlan:s,availableDataSources:n}){const[a,r]=N.useState(s),[i,c]=N.useState(new Set),o=()=>{const I=a.joins.length>0?Math.max(...a.joins.map(k=>k.sequence))+1:1,M={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:I,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...a,joins:[...a.joins,M]}),c(new Set([...i,M.id]))},d=I=>{r({...a,joins:a.joins.filter(M=>M.id!==I)}),c(new Set([...i].filter(M=>M!==I)))},l=(I,M)=>{var f,O,P,y,L;const k=a.joins.find(C=>C.id===I);if(!k)return;const j={...k,...M};if((f=j.source)!=null&&f.name&&((O=j.target)!=null&&O.name)&&j.source.name===j.target.name){t.ue.error("Self-joins are not yet supported",{description:`Joining ${j.source.name} to itself is not currently supported. Please select a different target table.`});return}const S=a.joins.filter(C=>{var V;return C.id!==I&&C.target.name===((V=j.target)==null?void 0:V.name)});if((P=j.target)!=null&&P.name&&S.length>0){t.ue.error("Duplicate join targets are not supported",{description:`The table ${j.target.name} is already used as a target in another join. Each table can only be joined once.`});return}const A=a.joins.map(C=>C.id===I?j:C);if((y=j.source)!=null&&y.name&&((L=j.target)!=null&&L.name)&&j.joinKeyGroups[0].keys.length===0){const C=n.find($=>{var B;return $.name===((B=j.source)==null?void 0:B.name)}),V=n.find($=>{var B;return $.name===((B=j.target)==null?void 0:B.name)}),F={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(C==null?void 0:C.name)||"",entityName:(C==null?void 0:C.name)||"",entityType:(C==null?void 0:C.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(V==null?void 0:V.name)||"",entityName:(V==null?void 0:V.name)||"",entityType:(V==null?void 0:V.type)||"table"},operator:"="},R=[...j.joinKeyGroups];R[0]={...R[0],keys:[F]},j.joinKeyGroups=R,A[A.findIndex($=>$.id===I)]=j}r({...a,joins:A})};return{joinPlan:a,expandedJoins:i,setJoinPlan:r,addJoin:o,removeJoin:d,updateJoin:l,moveJoinUp:I=>{const M=a.joins.findIndex(k=>k.id===I);if(M>0){const k=[...a.joins],j={...k[M]},S={...k[M-1]};k[M]=S,k[M-1]=j,k.forEach((f,O)=>{f.sequence=O+1});const A={...a,joins:k};r(A)}},moveJoinDown:I=>{const M=a.joins.findIndex(k=>k.id===I);if(M<a.joins.length-1){const k=[...a.joins],j={...k[M]},S={...k[M+1]};k[M]=S,k[M+1]=j,k.forEach((f,O)=>{f.sequence=O+1});const A={...a,joins:k};r(A)}},toggleJoinExpansion:I=>{const M=new Set(i);M.has(I)?M.delete(I):M.add(I),c(M)},getAvailableSourceEntities:I=>{if(a.joins.length===0)return n;const M=a.joins.findIndex(j=>j.id===I);if(M===0)return n.filter(j=>j.name===a.baseEntity.name);const k=new Set;return a.baseEntity.name&&k.add(a.baseEntity.name),a.joins.slice(0,M).forEach(j=>{k.add(j.source.name),k.add(j.target.name)}),n.filter(j=>k.has(j.name))},getAvailableTargetEntities:I=>n.filter(M=>M.name!==I),addJoinKeyGroup:I=>{const M=a.joins.find(j=>j.id===I);if(!M)return;const k=[...M.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];l(I,{joinKeyGroups:k})},updateGroupOperator:(I,M,k)=>{const j=a.joins.find(A=>A.id===I);if(!j)return;const S=[...j.joinKeyGroups];S[M]={...S[M],operator:k},l(I,{joinKeyGroups:S})},removeJoinKeyGroup:(I,M)=>{const k=a.joins.find(S=>S.id===I);if(!k)return;const j=[...k.joinKeyGroups];j.splice(M,1),l(I,{joinKeyGroups:j})},addJoinKey:(I,M)=>{const k=a.joins.find(O=>O.id===I);if(!k)return;const j=n.find(O=>O.name===k.source.name),S=n.find(O=>O.name===k.target.name),A=[...k.joinKeyGroups],f={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(j==null?void 0:j.name)||"",entityName:(j==null?void 0:j.name)||"",entityType:(j==null?void 0:j.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(S==null?void 0:S.name)||"",entityName:(S==null?void 0:S.name)||"",entityType:(S==null?void 0:S.type)||"table"},operator:"="};A[M]={...A[M],keys:[...A[M].keys,f]},l(I,{joinKeyGroups:A})},updateJoinKey:(I,M,k,j,S)=>{const A=a.joins.find(L=>L.id===I);if(!A)return;const f=n.find(L=>L.name===A.source.name),O=n.find(L=>L.name===A.target.name),P=[...A.joinKeyGroups],y=P[M].keys[k];j==="sourceColumnName"&&f?P[M].keys[k]={...y,source:{...y.source,name:S}}:j==="targetColumnName"&&O?P[M].keys[k]={...y,target:{...y.target,name:S}}:j==="operator"&&(P[M].keys[k]={...y,operator:S}),l(I,{joinKeyGroups:P})},removeJoinKey:(I,M,k)=>{const j=a.joins.find(A=>A.id===I);if(!j)return;const S=[...j.joinKeyGroups];S[M].keys.splice(k,1),l(I,{joinKeyGroups:S})},generateSQLPreview:()=>{const I=[...a.joins].sort((j,S)=>j.sequence-S.sequence),M=a.baseEntity;if(!M.name)return"SELECT * FROM table -- Please select a base entity";let k=`SELECT *
162
- FROM ${M.name}`;return I.forEach(j=>{const S=n.find(O=>O.name===j.target.name);if(!S)return;const A=j.joinKeyGroups.filter(O=>O.keys&&O.keys.length>0).map(O=>{const P=O.keys.filter(y=>{var L,C,V,F;return((L=y.source)==null?void 0:L.name)&&((C=y.target)==null?void 0:C.name)&&((V=y.source)==null?void 0:V.entityName)&&((F=y.target)==null?void 0:F.entityName)}).map(y=>`${y.source.entityName}.${y.source.name} ${y.operator} ${y.target.entityName}.${y.target.name}`);return P.length>1?`(${P.join(` ${O.operator} `)})`:P[0]}).filter(Boolean),f=A.length>1?A.join(" OR "):A[0]||"condition_here";k+=`
163
- ${j.joinType} JOIN ${S.name}
164
- ON ${f}`}),k},isValidConfiguration:()=>!(!a.baseEntity.name||a.joins.some(j=>!j.source.name||!j.target.name)||a.joins.some(j=>j.joinKeyGroups.some(S=>S.keys.length===0))||a.joins.some(j=>j.joinKeyGroups.some(S=>S.keys.some(A=>!A.source.name||!A.target.name||!A.operator))))}}function Fn({joinPlan:s,availableDataSources:n,onSave:a,onRemove:r,onCancel:i}){const{setCardConfig:c}=t.useEditorActions();t.useEditorStore(f=>f.card.config);const{columnGroups:o}=t.useColumns(),d=o.filter(f=>f.entityName!==t.CALCULATED_FIELDS_GROUP_NAME),{joinPlan:l,expandedJoins:m,setJoinPlan:p,addJoin:x,removeJoin:u,updateJoin:h,moveJoinUp:g,moveJoinDown:b,toggleJoinExpansion:v,getAvailableSourceEntities:w,getAvailableTargetEntities:E,addJoinKeyGroup:z,updateGroupOperator:D,removeJoinKeyGroup:T,addJoinKey:I,updateJoinKey:M,removeJoinKey:k,generateSQLPreview:j,isValidConfiguration:S}=On({initialJoinPlan:s,availableDataSources:n}),A=f=>{const O=d.find(P=>P.entityName===f);return(O==null?void 0:O.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(t.Select,{value:l.baseEntity.name,onValueChange:f=>{const O=n.find(P=>P.name===f);p({...l,baseEntity:{connectionId:(O==null?void 0:O.connectionId)||"",connectionType:(O==null?void 0:O.connectionType)||"none",type:(O==null?void 0:O.type)||"table",name:f,database:O==null?void 0:O.database,schema:O==null?void 0:O.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(t.SelectContent,{children:n.map(f=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:f.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:f.type}),f.name,e.jsx(t.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},f.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:j()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(t.Label,{children:["Joins Configuration (",l.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:x,children:[e.jsx(t.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),l.joins.length===0?e.jsx("div",{className:"rounded-lg border border-dashed py-8 text-center text-muted-foreground",children:e.jsx("p",{children:"No joins configured. Add a join to connect multiple data sources."})}):e.jsx("div",{className:"max-h-[300px] space-y-4 overflow-y-auto",children:l.joins.map(f=>{const O=n.find(L=>L.name===f.source.name),P=n.find(L=>L.name===f.target.name),y=m.has(f.id);return e.jsxs(t.Card,{className:"border",children:[e.jsx(t.CardHeader,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{children:f.sequence}),e.jsxs(t.CardTitle,{className:"text-sm",children:["Join ",f.sequence,O&&P&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",O.name," → ",P.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>g(f.id),disabled:f.sequence===1,children:e.jsx(t.ArrowUp,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>b(f.id),disabled:f.sequence===l.joins.length,children:e.jsx(t.ArrowDown,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>v(f.id),children:y?e.jsx(t.ChevronUp,{className:"h-4 w-4"}):e.jsx(t.ChevronDown,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>u(f.id),children:e.jsx(t.X,{className:"h-4 w-4"})})]})]})}),y&&e.jsxs(t.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Source"}),e.jsxs(t.Select,{value:f.source.name,onValueChange:L=>{const C=n.find(V=>V.name===L);h(f.id,{source:{connectionId:(C==null?void 0:C.connectionId)||"",connectionType:(C==null?void 0:C.connectionType)||"none",type:(C==null?void 0:C.type)||"table",name:L,database:C==null?void 0:C.database,schema:C==null?void 0:C.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select source..."})}),e.jsx(t.SelectContent,{children:w(f.id).map(L=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:L.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:L.type}),L.name]})},L.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Join Type"}),e.jsxs(t.Select,{value:f.joinType,onValueChange:L=>h(f.id,{joinType:L}),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Target"}),e.jsxs(t.Select,{value:f.target.name,onValueChange:L=>{const C=n.find(V=>V.name===L);h(f.id,{target:{connectionId:(C==null?void 0:C.connectionId)||"",connectionType:(C==null?void 0:C.connectionType)||"none",type:(C==null?void 0:C.type)||"table",name:L,database:C==null?void 0:C.database,schema:C==null?void 0:C.schema}})},disabled:!f.source.name,children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select target..."})}),e.jsx(t.SelectContent,{children:f.source.name?E(f.source.name).map(L=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:L.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:L.type}),L.name,L.name===f.source.name&&e.jsx(t.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},L.name)):[]})]})]})]}),f.source.name&&f.target.name&&O&&P&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{children:"Join Conditions"}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>z(f.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),f.joinKeyGroups.length===0?e.jsx("div",{className:"rounded-md border p-3 text-center text-sm text-gray-500",children:"No join conditions defined. Add condition groups to specify how data sources should be joined."}):e.jsx("div",{className:"space-y-4",children:f.joinKeyGroups.map((L,C)=>e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Label,{children:["Group ",C+1]}),C>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(t.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Select,{value:L.operator,onValueChange:V=>D(f.id,C,V),children:[e.jsx(t.SelectTrigger,{className:"w-[100px]",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>T(f.id,C),children:e.jsx(t.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[L.keys.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-sm text-gray-500",children:"No conditions in this group. Add conditions to specify join criteria."}):e.jsx("div",{className:"space-y-2",children:L.keys.map((V,F)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[F>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:L.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:V.source.name,onValueChange:R=>M(f.id,C,F,"sourceColumnName",R),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Source column"})}),e.jsx(t.SelectContent,{children:A(f.source.name).map(R=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:R.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:R.name}),e.jsx(t.Badge,{variant:"outline",className:"ml-2 text-xs",children:R.dataType})]})},R.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(t.Select,{value:V.operator,onValueChange:R=>M(f.id,C,F,"operator",R),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:V.target.name,onValueChange:R=>M(f.id,C,F,"targetColumnName",R),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Target column"})}),e.jsx(t.SelectContent,{children:A(f.target.name).map(R=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:R.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:R.name}),e.jsx(t.Badge,{variant:"outline",className:"ml-2 text-xs",children:R.dataType})]})},R.name))})]})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>k(f.id,C,F),children:e.jsx(t.X,{className:"size-3.5"})})]},V.id||F))}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>I(f.id,C),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},L.id))})]})]})]},f.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>{r(),i()},children:"Remove All"}),e.jsx(t.Button,{variant:"outline",onClick:i,children:"Cancel"}),e.jsx(t.Button,{onClick:()=>a(l),disabled:!S(),children:"Save"})]})]})}function ka({children:s,open:n,onOpenChange:a,joinPlan:r,availableDataSources:i,onRemove:c,onSave:o,onCancel:d}){return e.jsxs(t.Dialog,{open:n,onOpenChange:a,children:[e.jsxs(t.DialogContent,{className:"max-w-4xl",children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Join Configuration"}),e.jsx(t.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(Fn,{joinPlan:r,availableDataSources:i,onSave:o,onCancel:d,onRemove:c})]}),s]})}function Rn({joins:s,baseEntityId:n,availableDataSources:a,generateSQLPreview:r}){return e.jsxs("div",{className:"my-2 max-h-[400px] divide-y divide-border overflow-y-auto",children:[s.length>0&&e.jsxs("div",{className:"px-4 py-2",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const i=[...s].sort((o,d)=>o.sequence-d.sequence),c=a.find(o=>o.name===n);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(t.Badge,{variant:"secondary",className:"text-xs",children:c==null?void 0:c.type}),e.jsx("span",{className:"text-xs font-medium",children:c==null?void 0:c.name}),e.jsx(t.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),i.map(o=>{const d=a.find(l=>l.name===o.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:o.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(t.Badge,{variant:"secondary",className:"text-xs",children:d==null?void 0:d.type}),e.jsx("span",{className:"text-xs font-medium",children:d==null?void 0:d.name})]})]},o.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",s.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...s].sort((i,c)=>i.sequence-c.sequence).map((i,c)=>{const o=a.find(m=>m.name===i.source.name),d=a.find(m=>m.name===i.target.name),l=i.joinKeyGroups.reduce((m,p)=>m+p.keys.length,0);return e.jsxs("div",{className:"rounded-md bg-muted p-2 text-left",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:c+1}),e.jsx(t.Badge,{variant:"outline",className:"shrink-0 text-xs",children:i.joinType}),e.jsxs(t.Badge,{variant:"outline",className:"ml-auto shrink-0 text-xs",children:[l," condition",l>1?"s":""]})]}),e.jsxs("div",{className:"mt-1 truncate pl-1 text-xs text-muted-foreground",children:[o==null?void 0:o.name," → ",d==null?void 0:d.name]})]},i.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function sa({open:s,onOpenChange:n,variant:a="button"}={}){var E,z;const r=t.useEditorStore(D=>D.card),{autoJoinMetadata:i}=t.useDashboardCardQuery(r),c=t.useEditorStore(D=>D.actions.updateCardConfig),o=((E=r==null?void 0:r.config)==null?void 0:E.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[d,l]=N.useState(!1),m=s!==void 0,p=m?s:d,x=m?n:l,u=((z=r==null?void 0:r.dataSource)==null?void 0:z.selectedEntities)||[],h=D=>{c(r.id,{...r==null?void 0:r.config,joinPlan:D}),x(!1)},g=()=>{c(r.id,{...r==null?void 0:r.config,joinPlan:void 0})},b=()=>{x(!1)},v=()=>{const D=[...o.joins].sort((M,k)=>M.sequence-k.sequence),T=o.baseEntity;if(!T.name)return"SELECT * FROM table -- Please select a base entity";let I=`SELECT *
165
- FROM ${T.name}`;return D.forEach(M=>{const k=u.find(A=>A.name===M.target.name);if(!k)return;const j=M.joinKeyGroups.filter(A=>A.keys&&A.keys.length>0).map(A=>{const f=A.keys.filter(O=>{var P,y,L,C;return((P=O.source)==null?void 0:P.name)&&((y=O.target)==null?void 0:y.name)&&((L=O.source)==null?void 0:L.entityName)&&((C=O.target)==null?void 0:C.entityName)}).map(O=>`${O.source.entityName}.${O.source.name} ${O.operator} ${O.target.entityName}.${O.target.name}`);return f.length>1?`(${f.join(` ${A.operator} `)})`:f[0]}).filter(Boolean),S=j.length>1?j.join(" OR "):j[0]||"condition_here";I+=`
166
- ${M.joinType} JOIN ${k.name}
167
- ON ${S}`}),I};if(u.length<2)return null;const w=o.joins.length>0&&e.jsx(t.TooltipContent,{side:"bottom",className:"ml-4 max-w-md overflow-hidden p-0",children:e.jsx(Rn,{joins:o.joins,baseEntityId:o.baseEntity.name,availableDataSources:u,generateSQLPreview:v})});return e.jsxs(e.Fragment,{children:[e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:a==="badge"?e.jsxs(t.Badge,{variant:"secondary",className:"h-5 cursor-pointer gap-1 px-1.5 text-xs transition-colors hover:bg-secondary/80",onClick:D=>{D.stopPropagation(),x(!0)},children:[e.jsx(t.Link,{className:"h-3 w-3"}),o.joins.length]}):e.jsxs(t.Button,{onClick:()=>x(!0),variant:"outline",className:"w-full bg-muted/50",children:[e.jsx(t.Link,{className:"mr-2 h-3.5 w-3.5"}),o.joins.length===0?"Configure Joins":o.joins.length===1?"Join":"Joins",o.joins.length>0&&e.jsx("span",{className:"ml-2 flex h-5 min-w-5 items-center justify-center rounded-full border bg-muted-foreground px-1.5 text-xs font-medium text-background",children:o.joins.length}),(i==null?void 0:i.autoResolved)&&e.jsxs(t.Badge,{variant:"secondary",className:"ml-2 h-5 gap-1 bg-blue-50 text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:[e.jsx(t.Sparkles,{className:"h-3 w-3"}),"Auto"]})]})}),w]})}),e.jsx(ka,{open:p,onOpenChange:x,joinPlan:o,availableDataSources:u,onSave:h,onCancel:b,onRemove:g,children:e.jsx("div",{})})]})}function Vn({open:s,onOpenChange:n}){const[a,r]=N.useState([]),{updateDataSource:i}=t.useEditorActions(),{selectedEntities:c}=t.useAssistantContextEntities("dashboard");N.useEffect(()=>{s&&r([])},[s]);const o=h=>{r(g=>g.some(v=>t.areContextEntitiesEqual(v,h))?g.filter(v=>!t.areContextEntitiesEqual(v,h)):[...g,h])},d=()=>{r([...c])},l=()=>{r([])},m=()=>{if(a.length===0)return;const h=a[0],g=h.connectionId||"",b=h.connectionType||"",w=a.some(z=>z.type==="dataset")?"semanticDomain":"database";i({connectionId:g,connectionType:b,mode:w,selectedEntities:a}),n(!1)},p=h=>"label"in h&&h.label?h.label:h.name,x=h=>{if("description"in h&&h.description)return h.description;const g=[];return h.database&&g.push(h.database),h.schema&&g.push(h.schema),h.name&&g.push(h.name),g.join(".")},u=h=>a.some(g=>t.areContextEntitiesEqual(g,h));return c.length===0?e.jsx(t.Dialog,{open:s,onOpenChange:n,children:e.jsxs(t.DialogContent,{className:"max-w-md",children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"No Data Available"}),e.jsx(t.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(t.DialogFooter,{children:e.jsx(t.Button,{onClick:()=>n(!1),children:"Close"})})]})}):e.jsx(t.Dialog,{open:s,onOpenChange:n,children:e.jsxs(t.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(t.DialogDescription,{children:"Choose entities from the dashboard's context"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"outline",size:"sm",onClick:d,disabled:a.length===c.length,children:"Select All"}),e.jsx(t.Button,{variant:"outline",size:"sm",onClick:l,disabled:a.length===0,children:"Clear All"})]}),e.jsxs(t.Badge,{variant:"secondary",children:[a.length," of ",c.length," selected"]})]}),e.jsx(t.Separator,{}),e.jsx(t.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:c.map((h,g)=>e.jsxs("div",{className:t.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",u(h)&&"border-primary bg-primary/5"),children:[e.jsx(t.Checkbox,{checked:u(h),onCheckedChange:()=>o(h)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:t.getEntityIcon(h.type)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:p(h)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:x(h)})]}),e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:h.type})]},`${h.type}-${h.name}-${g}`))})})]}),e.jsx(t.DialogFooter,{children:e.jsx("div",{className:"flex w-full justify-between",children:e.jsxs("div",{className:"flex grow justify-end gap-2",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsxs(t.Button,{onClick:m,disabled:a.length===0,children:["Select"," ",a.length>0?`(${a.length})`:""]})]})})})]})})}function aa({entities:s,title:n}){const{isConsoleMode:a}=t.useDashboardPreferences();return e.jsx(t.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:n??`${s.length} more entities`}),e.jsx("div",{className:"space-y-1",children:s.map((r,i)=>{const c=t.getEntityDetails(r),o=c.find(l=>l.label==="Description"&&l.value),d=c.filter(l=>l.label==="Description"?!1:a?!0:!["Connection","Database","Schema"].includes(l.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:t.getDisplayName(r)}),o&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:o.value})]}),d.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:d.map((l,m)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[l.label,":"]}),e.jsx("span",{className:"font-mono",children:l.value})]},m))})]},`remaining-${r.type}-${r.name}-${i}`)})})]})})}function Da(s,n){const[a,r]=N.useState(()=>{const i=localStorage.getItem(s);return i?JSON.parse(i):n});return N.useEffect(()=>{localStorage.setItem(s,JSON.stringify(a))},[a,s]),[a,r]}function Aa({isVisible:s}){var b,v;const n=t.useEditorStore(w=>w.isDevMode);t.useSyncLegacyEditorState();const[a,r]=N.useState(!1),[i,c]=N.useState(!1),[o,d]=Da("semaphor:data-source-collapsed",!1),l=t.useEditorStore(w=>w.card.dataSource),m=t.useEditorStore(w=>{var E,z;return(z=(E=w.card)==null?void 0:E.config)==null?void 0:z.joinPlan}),{updateDataSource:p}=t.useEditorActions(),x=((b=l==null?void 0:l.selectedEntities)==null?void 0:b.length)||0,u=((v=m==null?void 0:m.joins)==null?void 0:v.length)||0,g={...{connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},...l,selectedEntities:(l==null?void 0:l.selectedEntities)||[]};return e.jsxs("div",{className:t.cn("flex shrink-0 flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":s,"min-w-[325px]":s,"w-0":!s,"min-w-0":!s}),children:[x===0&&u===0?e.jsx("div",{className:"px-4 pt-4",children:e.jsx("div",{className:"rounded-xl border border-border/55 bg-card p-3 shadow-[0_1px_2px_rgba(15,23,42,0.05)]",children:e.jsxs(t.Button,{className:"w-full bg-background",variant:"outline",onClick:()=>r(!0),children:[e.jsx(t.Database,{className:"mr-2 h-3.5 w-3.5"}),"Choose Dataset"]})})}):e.jsx("div",{className:"px-4 pt-4",children:e.jsxs("div",{className:"rounded-xl border border-border/55 bg-card p-3 shadow-[0_1px_2px_rgba(15,23,42,0.05)]",children:[e.jsxs("div",{className:t.cn("flex cursor-pointer items-center justify-between px-1",o?"pb-0":"pb-3"),onClick:()=>d(!o),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:"Data Source"}),o&&e.jsxs("div",{className:"flex items-center gap-1.5",onClick:w=>w.stopPropagation(),children:[x>0&&e.jsx(t.TooltipProvider,{delayDuration:100,children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs(t.Badge,{variant:"secondary",className:"h-5 cursor-pointer gap-1 px-1.5 text-xs transition-colors hover:bg-secondary/80",onClick:()=>r(!0),children:[e.jsx(t.Database,{className:"h-3 w-3"}),x]})}),e.jsx(aa,{entities:g.selectedEntities,title:`${x} selected ${x===1?"entity":"entities"}`})]})}),u>0&&!n&&e.jsx(sa,{variant:"badge"})]})]}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:w=>{w.stopPropagation(),d(!o)},children:o?e.jsx(t.ChevronDown,{className:"h-4 w-4"}):e.jsx(t.ChevronUp,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:t.cn("flex flex-col overflow-hidden transition-all duration-200 ease-in-out",o?"max-h-0 opacity-0":"max-h-96 opacity-100"),children:[e.jsx("div",{className:"px-1",children:e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs(t.Button,{className:"w-full bg-background",variant:"outline",onClick:()=>r(!0),children:[e.jsx(t.Database,{className:"mr-2 h-3.5 w-3.5"}),x===1?"Dataset":"Datasets",e.jsx("span",{className:"ml-2 flex h-5 min-w-5 items-center justify-center rounded-full border bg-muted-foreground px-1.5 text-xs font-medium text-background",children:x})]})}),e.jsx(aa,{entities:g.selectedEntities,title:`${x} selected ${x===1?"entity":"entities"}`})]})})}),!n&&x>1&&e.jsx("div",{className:"mt-3 px-1",children:e.jsx(sa,{})})]})]})}),e.jsx("div",{className:"min-h-0 flex-1 px-4 pb-4 pt-2",children:e.jsx("div",{className:"h-full overflow-hidden rounded-xl border border-border/55 bg-card shadow-[0_1px_2px_rgba(15,23,42,0.05)]",children:e.jsx(t.FieldsSection,{})})}),e.jsx(t.DataSourceDialog,{incomingSelectedEntities:(l==null?void 0:l.selectedEntities)||[],dialogMode:"dataSource",open:a,onOpenChange:r,dataSource:g}),e.jsx(Vn,{open:i,onOpenChange:c})]})}function Pn(s){return t.GenIcon({attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M439.8 200.5c-7.7-30.9-22.3-54.2-53.4-54.2h-40.1v47.4c0 36.8-31.2 67.8-66.8 67.8H172.7c-29.2 0-53.4 25-53.4 54.3v101.8c0 29 25.2 46 53.4 54.3 33.8 9.9 66.3 11.7 106.8 0 26.9-7.8 53.4-23.5 53.4-54.3v-40.7H226.2v-13.6h160.2c31.1 0 42.6-21.7 53.4-54.2 11.2-33.5 10.7-65.7 0-108.6zM286.2 404c11.1 0 20.1 9.1 20.1 20.3 0 11.3-9 20.4-20.1 20.4-11 0-20.1-9.2-20.1-20.4.1-11.3 9.1-20.3 20.1-20.3zM167.8 248.1h106.8c29.7 0 53.4-24.5 53.4-54.3V91.9c0-29-24.4-50.7-53.4-55.6-35.8-5.9-74.7-5.6-106.8.1-45.2 8-53.4 24.7-53.4 55.6v40.7h106.9v13.6h-147c-31.1 0-58.3 18.7-66.8 54.2-9.8 40.7-10.2 66.1 0 108.6 7.6 31.6 25.7 54.2 56.8 54.2H101v-48.8c0-35.3 30.5-66.4 66.8-66.4zm-6.7-142.6c-11.1 0-20.1-9.1-20.1-20.3.1-11.3 9-20.4 20.1-20.4 11 0 20.1 9.2 20.1 20.4s-9 20.3-20.1 20.3z"},child:[]}]})(s)}function Ma(s){const{theme:n}=t.useTheme(),a=t.useDashboardStore(b=>b.theme),r=t.useEditorStore(b=>b.frame),i=t.useEditorStore(b=>b.card),c=t.useEditorStore(b=>b.activeTabCardId),o=t.Le(),{refetch:d}=t.useDashboardCardQuery(i),{updateCardTab:l,setRunSql:m}=t.useEditorActions(),p=N.useRef(void 0),x=N.useRef({}),u=r.cards.find(b=>b.id===c),h=N.useCallback(()=>{let b="";return s==="python"&&(b=(u==null?void 0:u.python)||t.PYTHON_DEFAULT_CODE),s==="sql"&&(b=(u==null?void 0:u.sql)||""),b},[s,u]);N.useEffect(()=>{if(c&&i.id&&i.id!==c){if(p.current&&o){const b=p.current.getModel();b&&(x.current[i.id]=b);let v=x.current[c];if(!v){const w=h();v=o.editor.createModel(w,s),x.current[c]=v}p.current.setModel(v)}l(c,i),m(!0)}},[c,i,l,o,m,s,h]),N.useEffect(()=>{if(!o)return;const b=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",v=a==="system"?b:a;o.editor.defineTheme("default",{base:v==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":v==="light"?"#ffffff":t.hslStringToHex("240 10% 10%")}}),o.editor.setTheme("default")},[n,a,o]),N.useEffect(()=>{const b=p.current;b&&o&&i&&b.addCommand(o.KeyMod.Shift|o.KeyCode.Enter,function(){return d(),!1})},[o,d,i]);function g(b,v){if(p.current=b,!x.current[i.id]){const w=b.getModel(),E=h();x.current[i.id]=w||(v==null?void 0:v.editor.createModel(E,s))||b.getModel()}b.setModel(x.current[i.id])}return{handleEditorDidMount:g}}const Bn=300;function zn(){const s=t.useEditorStore(p=>p.card.sql),n=t.useEditorStore(p=>p.sqlGen),{setCardSql:a,setSqlGen:r}=t.useEditorActions(),{handleEditorDidMount:i}=Ma("sql"),c=N.useRef(n);c.current=n;const o=N.useCallback(p=>{a(p)},[a]),{value:d,onChange:l}=Ia({storeValue:s,defaultValue:"",onStoreUpdate:o,delay:Bn});function m(p){l(p),t.isObjectEmpty(c.current)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!d&&e.jsx("div",{className:"pointer-events-none absolute left-[36px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(t.Ft,{theme:"default",className:"pt-3",onChange:m,value:d,options:{minimap:{enabled:!1},glyphMargin:!1,lineNumbersMinChars:2,lineDecorationsWidth:0,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:i})]})}const qn=300;function _n(){const s=t.useEditorStore(c=>c.card.python),{setCardPython:n}=t.useEditorActions(),{handleEditorDidMount:a}=Ma("python"),{value:r,onChange:i}=Ia({storeValue:s,defaultValue:t.PYTHON_DEFAULT_CODE,onStoreUpdate:n,delay:qn});return e.jsx(t.Ft,{className:"pt-3",theme:"default",onChange:i,value:r,options:{minimap:{enabled:!1},glyphMargin:!1,lineNumbersMinChars:2,lineDecorationsWidth:0,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:a})}const $n={async writeTextToClipboard(s){return typeof navigator>"u"||!navigator.clipboard?!1:(await navigator.clipboard.writeText(s),!0)}},Ft=50,Kn=[{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 na(s){try{return JSON.stringify(s,null,2)}catch(n){return console.error("Unable to stringify debug payload",n),null}}function ft(s){switch(s){case"queryRequest":return"Query Request";case"queryResponse":return"Query Response";case"cardConfig":return"Card Config";case"dataSource":return"Data Source";case"cardMetadata":return"Card Metadata IDs";case"columns":return"Columns";case"dashboardFilters":return"Dashboard Filters";default:return"Payload"}}function Gn(s){if(!s||typeof s!="object")return{value:s};const n=s.records;return!Array.isArray(n)||n.length<=Ft?{value:s}:{value:{...s,records:n.slice(0,Ft),previewMeta:{truncatedRecords:!0,displayedRecords:Ft,totalRecords:n.length}},truncationMessage:`Preview showing first ${Ft} records of ${n.length}. Copy actions include full payload.`}}function La({sql:s,showCardDetails:n=!1,debugPayloads:a,className:r}){const[i,c]=N.useState(!1),[o,d]=N.useState(null),l=t.useEditorStore(S=>S.card),m=t.useEditorStore(S=>S.frame),p=t.useEditorStore(S=>S.isDevMode),x=t.useDashboardStore(S=>S.selectedSheetId),u=t.useDashboardStore(S=>{var A;return(A=S.dashboard)==null?void 0:A.id}),{switchEditorMode:h,setRunSql:g}=t.useEditorActions(),b=N.useMemo(()=>({cardId:l.id||null,frameId:m.id||null,sheetId:x||null,dashboardId:u||null}),[l.id,m.id,x,u]),v=N.useMemo(()=>({queryRequest:a==null?void 0:a.queryRequest,queryResponse:a==null?void 0:a.queryResponse,cardConfig:l.config,dataSource:l.dataSource,columns:a==null?void 0:a.columns,dashboardFilters:a==null?void 0:a.dashboardFilters,cardMetadata:b}),[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,b]),w=n&&i&&!!a,E=N.useMemo(()=>[{label:"Card ID",value:l.id||""},{label:"Frame ID",value:m.id||""},{label:"Sheet ID",value:x||""},{label:"Dashboard ID",value:u||""}],[l.id,m.id,x,u]),z=()=>{h("dev",{sqlToLoad:s}),setTimeout(()=>{g(!0)},100)},D=S=>v[S]!==void 0,T=N.useMemo(()=>{if(!o)return null;const S=v[o];if(S===void 0)return null;const A=o==="queryResponse"?Gn(S):{value:S},f=na(A.value);return f?{target:o,title:ft(o),json:f,truncationMessage:A.truncationMessage}:null},[o,v]),I=T?T.title:"Preview Payload",M=async S=>{const A=v[S];if(A===void 0)return t.ue.error(`No ${ft(S).toLowerCase()} available`),!1;const f=na(A);if(!f)return t.ue.error(`Unable to serialize ${ft(S).toLowerCase()}`),!1;try{return await $n.writeTextToClipboard(f)?(t.ue.success(`${ft(S)} copied`),!0):(t.ue.error("Clipboard is not available"),!1)}catch(O){return console.error("Failed to copy debug payload",O),t.ue.error(`Unable to copy ${ft(S).toLowerCase()}`),!1}},k=async()=>T?M(T.target):!1,j=S=>{if(v[S]===void 0){t.ue.error(`No ${ft(S).toLowerCase()} available`);return}d(S)};return e.jsxs("div",{className:t.cn("flex min-h-0 flex-1 flex-col",r),children:[!p&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsxs(t.Button,{onClick:z,variant:"secondary",size:"sm",children:[e.jsx(Ta,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),n&&e.jsxs(t.Button,{onClick:()=>c(!i),variant:"outline",size:"sm",children:[e.jsx(t.Info,{className:"mr-2 h-4 w-4"}),"Card Details"]})]}),i&&n&&e.jsx("div",{className:"mb-3 rounded-lg border border-border bg-muted/30 p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Card Information"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>c(!1),children:e.jsx(Me.CircleX,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"grid grid-cols-1 gap-2 md:grid-cols-2",children:E.map(S=>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:S.label}),e.jsx(t.CopyButton,{text:S.value,className:"h-6 w-6 shrink-0"})]}),e.jsx("code",{title:S.value||"N/A",className:"mt-1 block whitespace-normal break-all font-mono text-xs",children:S.value||"N/A"})]},S.label))}),w&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-background/70 p-3",children:[e.jsx("p",{className:"text-xs font-semibold text-muted-foreground",children:"Debug Tools"}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(t.DropdownMenu,{children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8","aria-label":"Preview Payload Menu",children:[e.jsx(t.Eye,{className:"mr-1.5 h-3.5 w-3.5"}),I,e.jsx(t.ChevronDown,{className:"ml-1.5 h-3.5 w-3.5"})]})}),e.jsx(t.DropdownMenuContent,{align:"start",className:"w-56",children:Kn.map(S=>e.jsx(t.DropdownMenuItem,{disabled:!D(S.target),onSelect:()=>j(S.target),className:t.cn(o===S.target&&"bg-accent"),children:S.label},`preview-${S.target}`))})]})}),T&&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:[T.title," Preview"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(t.CopyButton,{text:T.json,className:"h-6 w-6",ariaLabel:"Copy Payload",onCopy:k}),e.jsxs(t.Button,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>d(null),children:[e.jsx(Me.CircleX,{className:"mr-1 h-3.5 w-3.5"}),"Hide"]})]})]}),T.truncationMessage&&e.jsx("p",{className:"text-xs text-muted-foreground",children:T.truncationMessage}),e.jsx("div",{className:"max-h-80 overflow-auto",children:e.jsx(t.CodeHighlighter,{code:T.json,language:"json"})})]})]})]})}),e.jsx("div",{className:"min-h-0 flex-1 overflow-auto",children:e.jsxs("div",{className:"overflow-hidden rounded-xl border border-border/60 bg-gradient-to-b from-background to-muted/[0.18] shadow-sm",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border/50 bg-background/80 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"rounded-md border border-border/60 bg-muted/60 px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.12em] text-muted-foreground",children:"SQL"}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Generated query"})]}),e.jsx("div",{className:"rounded-md border border-border/60 bg-background/85 p-0.5 shadow-sm backdrop-blur-sm",children:e.jsx(t.CopyButton,{text:s,className:"h-6 w-6 px-0 text-muted-foreground/80 hover:text-foreground"})})]}),e.jsx("div",{className:"group relative overflow-auto px-1 py-1 text-xs leading-relaxed text-foreground/80",children:e.jsx(t.CodeHighlighter,{code:s,language:"sql",wrapLongLines:!0})})]})})]})}function Un(s){const{request:n,mode:a="draft",currentSql:r,selectedTableName:i,selectedSchemaName:c,selectedDatabaseName:o}=s,d=[o?`Database: ${o}`:"",c?`Schema: ${c}`:"",i?`Table: ${i}`:""].filter(Boolean);return["You are an expert SQL writing assistant embedded in a query editor.",`Write SQL only. You may call only read-only tools when needed: ${t.INLINE_ALLOWED_TOOL_LIST}.`,"Do not call mutation tools or chart-creation tools; those require Full Assistant.","Return exactly one SQL statement inside a single ```sql fenced block.","After the code block, optionally include one short sentence.",a==="refine"&&r?"Mode: Refine existing SQL. Keep the current query structure and only apply the requested changes unless the current query is invalid.":"Mode: Draft new SQL from the request.",d.length>0?`Context:
168
- ${d.join(`
169
- `)}`:"",r?a==="refine"?`Current SQL (must refine):
170
- ${r}`:`Current SQL (revise if useful):
171
- ${r}`:"",`User request:
172
- ${n}`].filter(Boolean).join(`
173
-
174
- `)}function Hn(s){const{request:n,failedSql:a,errorMessage:r,errorCode:i,selectedDatabaseName:c,selectedSchemaName:o,selectedTableName:d,contextEntityLabels:l}=s,m=[c?`Database: ${c}`:"",o?`Schema: ${o}`:"",d?`Table: ${d}`:"",l.length>0?`Selected context entities: ${l.join(", ")}`:""].filter(Boolean);return["You are fixing SQL after validation failed.","Return one read-only SQL statement in a single ```sql fenced block.","Do not call mutation tools.",m.length>0?`Context:
175
- ${m.join(`
176
- `)}`:"",`Original user request:
177
- ${n}`,`Previous SQL draft:
178
- ${a}`,`Validation failure${i?` (${i})`:""}:
179
- ${r}`].filter(Boolean).join(`
180
-
181
- `)}function Qn(s,n){typeof window>"u"||window.dispatchEvent(new CustomEvent("semaphor:inline-query-writer",{detail:{event:s,...n,timestamp:Date.now()}}))}const Yt={runId:0,phase:"idle",attempt:0,activeStep:"",timelineSteps:[],lastValidation:null,finalOutcome:"idle",hasTools:!1};function Jn(s){if(typeof s=="string"&&(s==="SQL_EMPTY"||s==="SQL_PARSE_ERROR"||s==="SQL_MULTI_STATEMENT"||s==="SQL_READ_ONLY_VIOLATION"||s==="SQL_EXPLAIN_ERROR"||s==="SQL_CONNECTION_ERROR"))return s}function ra(s){let n=0;for(let a=0;a<s.length;a+=1)n=(n<<5)-n+s.charCodeAt(a),n|=0;return String(n)}function la(s){return s==="getTableColumns"?"Discovering columns":s==="getDomainRelationships"?"Resolving relationships":s==="getChartSQLSyntax"?"Reviewing SQL syntax":s==="getUserSql"?"Inspecting current query":"Analyzing context"}function Yn(s,n){return s===t.SELF_HEAL_TIMELINE_STEP&&n>0?`${t.SELF_HEAL_TIMELINE_STEP} ${n}/${t.MAX_SELF_HEAL_ATTEMPTS}`:s}function Rt(s){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`${s}-${crypto.randomUUID()}`:`${s}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function oa(s){var n;for(let a=s.length-1;a>=0;a-=1){const r=s[a];if(r.role!=="user")continue;const i=(n=r.metadata)==null?void 0:n.inlineRunToken;if(typeof i=="string"&&i.length>0)return i}}function Wn(s){if(!s)return"";const n=s.trim(),a=s.match(/```sql\s*([\s\S]*?)```/i);if(a!=null&&a[1])return a[1].trim();const r=s.match(/```[\w-]*\s*([\s\S]*?)```/i);return r!=null&&r[1]?r[1].trim():/^(select|with|insert|update|delete)\b/i.test(n)?n:""}function ia(s){for(let n=s.length-1;n>=0;n-=1){const a=s[n];if(!(a.role!=="assistant"||!Array.isArray(a.parts)))for(let r=a.parts.length-1;r>=0;r-=1){const i=a.parts[r];if((i==null?void 0:i.type)!=="text"||typeof(i==null?void 0:i.text)!="string")continue;const c=Wn(i.text);if(c)return c}}return""}function Xn({currentSql:s,currentPython:n,selectedDatabaseName:a,selectedSchemaName:r,selectedTableName:i,onApplySql:c,onOpenFullAssistant:o}){var De,ut;const{authToken:d,tokenProps:l}=t.useSemaphorContext(),m=(De=t.useDashboardQuery().data)==null?void 0:De.assistantProfileId,p=t.useEditorStore(_=>_.isDevMode),x=t.useEditorStore(_=>_.selectedConnectionId),u=t.useEditorStore(_=>{var U;return(U=_.card.dataSource)==null?void 0:U.selectedEntities}),h=t.useAIInteractionStore(_=>_.currentAIContext.selectedEntities),g=h.length,{setCurrentAIContext:b}=t.useAIActions(),[v,w]=N.useState(""),[E,z]=N.useState(""),[D,T]=N.useState(""),[I,M]=N.useState("draft"),[k,j]=N.useState("draft"),[S,A]=N.useState(""),[f,O]=N.useState(!1),[P,y]=N.useState({status:"idle"}),[L,C]=N.useState(Yt),[V,F]=N.useState(!1),[R,$]=N.useState(()=>Rt("inline-query-session")),B=N.useRef(null),K=N.useRef(null),Y=N.useRef(null),H=N.useRef(0),Z=N.useRef(0),ae=N.useRef(Rt("inline-run-token")),ee=N.useRef(R),de=N.useRef(new Set),ce=N.useRef(new Map),W=N.useRef(0),pe=N.useRef(""),X=N.useRef(!1),we=N.useRef(!1),G=N.useRef(Yt),ne=N.useRef(!1),ye=N.useRef(null),se=N.useRef(()=>{}),be=(ut=l.apiServiceUrl)==null?void 0:ut.replace(/\/$/,""),ge=be?`${be}/v1/sql/validate`:"/v1/sql/validate",fe=N.useCallback(_=>{C(U=>{const J=_(U);return G.current=J,J})},[]),Ne=N.useCallback((_,U)=>{fe(J=>J.runId===_?U(J):J)},[fe]),ve=N.useCallback(_=>Z.current===_&&!de.current.has(_),[]),Te=N.useCallback((_,U,J)=>{Ne(_,ue=>{const oe=ue.timelineSteps.includes(U)?ue.timelineSteps:[...ue.timelineSteps,U];return{...ue,phase:(J==null?void 0:J.phase)||ue.phase,attempt:typeof(J==null?void 0:J.attempt)=="number"?J.attempt:ue.attempt,activeStep:U,timelineSteps:oe,finalOutcome:(J==null?void 0:J.finalOutcome)||ue.finalOutcome,hasTools:J!=null&&J.hasTools?!0:ue.hasTools}})},[Ne]),Le=N.useCallback(()=>{const _=Z.current+1,U=Rt("inline-run-token"),J=Rt("inline-query-session");return Z.current=_,ae.current=U,ee.current=J,$(J),de.current=new Set,ce.current=new Map,W.current=0,pe.current="",ne.current=!1,fe(()=>({runId:_,phase:"drafting",attempt:0,activeStep:"Drafting SQL",timelineSteps:["Drafting SQL"],lastValidation:null,finalOutcome:"drafting",hasTools:!1})),{runId:_,runToken:U,chatSessionId:J}},[fe]),te=N.useCallback(()=>{if(X.current||we.current||g>0)return;const _=u||[];if(_.length===0)return;const U=t.useAIInteractionStore.getState().currentAIContext;b({...U,selectedEntities:_}),we.current=!0},[g,u,b]),je=N.useCallback(()=>{X.current=!0},[]),me=N.useCallback((_,U,J)=>{Qn(_,{runId:U,attemptCount:typeof(J==null?void 0:J.attemptCount)=="number"?J.attemptCount:W.current,errorCode:J==null?void 0:J.errorCode,hasTools:typeof(J==null?void 0:J.hasTools)=="boolean"?J.hasTools:L.hasTools,entityCount:g,finalOutcome:(J==null?void 0:J.finalOutcome)||L.finalOutcome})},[g,L.finalOutcome,L.hasTools]),Ee=N.useCallback((_,U)=>{const J=Y.current;if(!J)return;const ue={inlineRunToken:U};J({role:"user",parts:[{type:"text",text:_}],metadata:ue},{metadata:ue})},[]);N.useEffect(()=>{const _=ye.current;!_||_.sessionId!==R||(ye.current=null,Ee(_.message,_.runToken))},[R,Ee]);const he=R,Re=N.useCallback(async({toolCall:_})=>{var Ve,Ke,mt,xt,Pe,ht;if(he!==ee.current)return;const U=String(_.toolName||"").trim();if(!U)return;const J=Z.current;if(!ve(J)){(Ve=K.current)==null||Ve.call(K,{tool:U,toolCallId:_.toolCallId,output:{status:"error",message:"Inline run is no longer active; ignoring tool output."}});return}if(U==="getUserSql"){Te(J,la(U),{hasTools:!0}),me("inline_tool_step",J,{hasTools:!0}),(Ke=K.current)==null||Ke.call(K,{tool:U,toolCallId:_.toolCallId,output:{status:"success",sql:s||"",python:n||""}});return}const ue=t.INLINE_BLOCKED_MUTATING_TOOLS.has(U),oe=t.INLINE_ALLOWED_READ_ONLY_TOOLS.has(U);if(ue||!oe){(mt=K.current)==null||mt.call(K,{tool:U,toolCallId:_.toolCallId,output:{status:"error",message:"This action is unavailable in inline draft mode. Open Full Assistant for this action."}});return}const xe=la(U);Te(J,xe,{phase:L.phase==="self-healing"?"self-healing":"drafting",hasTools:!0}),me("inline_tool_step",J,{hasTools:!0});const Fe=((xt=_.input)==null?void 0:xt.sql)??((Pe=_.args)==null?void 0:Pe.sql);typeof Fe=="string"&&Fe.trim().length>0&&(ne.current=!1,T(Fe.trim())),(ht=K.current)==null||ht.call(K,{tool:U,toolCallId:_.toolCallId,output:{status:"success",message:"Read-only tool result received."}})},[n,s,me,L.phase,ve,he,Te]),Ye=N.useCallback(({message:_,messages:U})=>{if(he!==ee.current)return;const J=oa(U);if(!J||J!==ae.current)return;const ue=Z.current;if(!ve(ue))return;const oe=ia([_])||ia(U);if(oe){ne.current=!1,T(oe.trim());return}ne.current&&G.current.phase==="self-healing"&&se.current(ue)},[ve,he]),_e=N.useCallback(_=>{if(he!==ee.current)return;const U=Z.current;ve(U)&&ne.current&&G.current.phase==="self-healing"&&se.current(U)},[ve,he]),{setMessages:Se,sendMessage:at,addToolResult:nt,status:le,stop:Ie,error:Ge,clearError:Oe}=t.useChat({id:R,transport:new t.DefaultChatTransport({api:`${l.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${d==null?void 0:d.accessToken}`}),body:()=>{const _=t.useAIInteractionStore.getState();return{assistantId:"editor-assistant",assistantProfileId:m,isDevMode:p,aiContext:_.currentAIContext,reasoningEffort:_.reasoningEffort,showReasoning:!1}},credentials:"omit",prepareSendMessagesRequest:({messages:_,body:U,requestMetadata:J})=>{const ue=J==null?void 0:J.inlineRunToken,oe=oa(_);return{body:{...U,inlineRunToken:ue||oe,messages:t.cleanupIncompleteMessages(_)}}}}),onToolCall:Re,onFinish:Ye,onError:_e,sendAutomaticallyWhen:t.lastAssistantMessageIsCompleteWithToolCalls});K.current=nt,Y.current=at;const ke=!["ready","error"].includes(le),jt=(Ge==null?void 0:Ge.message)||"Unable to generate a SQL draft right now. Try again.",$e=N.useCallback(_=>{const U=Z.current,J=G.current.phase;if(!(J==="drafting"||J==="self-healing"||J==="validating")){_==="stopped"&&ke&&Ie();return}de.current.add(U),ne.current=!1,H.current+=1,pe.current="",y({status:"idle"}),T(""),Oe(),Se([]),Ne(U,oe=>({...oe,phase:"idle",activeStep:"",finalOutcome:"cancelled"})),me("inline_self_heal_stopped",U,{finalOutcome:"cancelled"}),(ke||_==="stopped")&&Ie()},[Oe,me,ke,Se,Ie,Ne]),bt=N.useCallback(async(_,U)=>{var ue;if(!ve(U))return null;const J=H.current+1;H.current=J,Te(U,"Validating SQL",{phase:"validating"}),y({status:"validating"});try{const oe=await t.postRequestRegular(ge,(d==null?void 0:d.accessToken)||"",{sql:_,connectionId:x||void 0});if(H.current!==J||!ve(U))return null;if((oe==null?void 0:oe.valid)===!0)return y({status:"valid",message:"SQL validation passed."}),Ne(U,Ve=>({...Ve,phase:"ready",finalOutcome:"validated",lastValidation:{valid:!0}})),me("inline_draft_validated",U,{finalOutcome:"validated"}),{status:"valid"};const xe=Jn(oe==null?void 0:oe.errorCode)||"UNKNOWN",Fe=typeof(oe==null?void 0:oe.error)=="string"&&oe.error||typeof((ue=oe==null?void 0:oe.details)==null?void 0:ue.error)=="string"&&oe.details.error||"SQL validation failed. Please revise the query draft.";return y({status:"invalid",message:Fe,errorCode:xe}),Ne(U,Ve=>({...Ve,lastValidation:{valid:!1,error:Fe,errorCode:xe}})),me("inline_validation_failed",U,{errorCode:xe,finalOutcome:"validation_failed"}),{status:"invalid",error:Fe,errorCode:xe}}catch(oe){if(H.current!==J||!ve(U))return null;const xe=typeof(oe==null?void 0:oe.error)=="string"&&oe.error||typeof(oe==null?void 0:oe.detail)=="string"&&oe.detail||"Validation service unavailable. You can still replace and run.";return y({status:"error",message:xe,errorCode:"SQL_CONNECTION_ERROR"}),Ne(U,Fe=>({...Fe,phase:"error",finalOutcome:"error",lastValidation:{valid:!1,error:xe,errorCode:"SQL_CONNECTION_ERROR"}})),{status:"error",error:xe,errorCode:"SQL_CONNECTION_ERROR"}}},[d==null?void 0:d.accessToken,me,ve,x,ge,Ne,Te]),et=N.useCallback((_,U,J,ue)=>{let oe=J,xe="validation_failed",Fe="Validating SQL";U==="attempt_limit"?(oe=`Couldn't auto-fix after ${t.MAX_SELF_HEAL_ATTEMPTS} attempts. ${J}`,xe="self_heal_exhausted",Fe=`Auto-fix stopped (${t.MAX_SELF_HEAL_ATTEMPTS} attempts)`):U==="duplicate"&&(oe=`Auto-fix stopped (repeated validation failure). ${J}`,xe="self_heal_duplicate_stopped",Fe="Auto-fix stopped (repeated failure)"),y({status:"invalid",message:oe,errorCode:ue}),Te(_,Fe,{phase:"error",finalOutcome:xe}),Ne(_,Ve=>({...Ve,phase:"error",finalOutcome:xe,lastValidation:{valid:!1,error:oe,errorCode:ue}})),U!=="terminal"&&me("inline_self_heal_stopped",_,{errorCode:ue,finalOutcome:xe}),ne.current=!1},[me,Ne,Te]),_t=N.useCallback(_=>{const U="Auto-fix stopped (no SQL returned). Open Full Assistant to continue.",J="self_heal_no_draft";y({status:"invalid",message:U,errorCode:"UNKNOWN"}),Te(_,"Auto-fix stopped (no SQL returned)",{phase:"error",finalOutcome:J}),Ne(_,ue=>({...ue,phase:"error",finalOutcome:J,lastValidation:{valid:!1,error:U,errorCode:"UNKNOWN"}})),me("inline_self_heal_stopped",_,{errorCode:"UNKNOWN",finalOutcome:J}),ne.current=!1},[me,Ne,Te]);se.current=_t,N.useEffect(()=>{const _=D.trim(),U=Z.current;if(!_){if(H.current+=1,pe.current="",G.current.phase==="error")return;y({status:"idle"});return}if(!ve(U)||ke)return;const J=`${U}:${W.current}:${ra(_)}`;if(pe.current===J)return;pe.current=J;let ue=!1;return(async()=>{const xe=await bt(_,U);if(!xe||ue||!ve(U)||xe.status!=="invalid")return;if(!t.RECOVERABLE_SQL_ERROR_CODES.has(xe.errorCode)){et(U,"terminal",xe.error,xe.errorCode);return}const Fe=`${ra(_)}::${xe.errorCode}`,Ve=(ce.current.get(Fe)||0)+1;if(ce.current.set(Fe,Ve),Ve>=2){et(U,"duplicate",xe.error,xe.errorCode);return}if(W.current>=t.MAX_SELF_HEAL_ATTEMPTS){et(U,"attempt_limit",xe.error,xe.errorCode);return}const Ke=W.current+1;W.current=Ke,Te(U,t.SELF_HEAL_TIMELINE_STEP,{phase:"self-healing",attempt:Ke}),me("inline_self_heal_attempt",U,{attemptCount:Ke,errorCode:xe.errorCode}),ne.current=!0,Oe(),Se([]),T("");const mt=h.map(Pe=>{const ht=Pe!=null&&Pe.database?`${Pe.database}.`:"",Mt=Pe!=null&&Pe.schema?`${Pe.schema}.`:"",Lt=(Pe==null?void 0:Pe.name)||"unknown";return`${ht}${Mt}${Lt}`}),xt=Hn({request:E,failedSql:_,errorMessage:xe.error,errorCode:xe.errorCode,selectedDatabaseName:a||"",selectedSchemaName:r||"",selectedTableName:i||"",contextEntityLabels:mt});Ee(xt,ae.current)})(),()=>{ue=!0}},[Oe,h,me,ke,ve,E,D,a,r,i,Ee,Se,et,Te,bt]);const We=(s==null?void 0:s.trim())||"",vt=N.useCallback((_="draft")=>{if(ke)return;const U=v.trim();if(!U)return;const J=_==="refine"&&We?"refine":"draft",ue=J==="refine"?We:"",oe=We,{runId:xe,runToken:Fe,chatSessionId:Ve}=Le();me("inline_draft_started",xe,{attemptCount:0,hasTools:!1,finalOutcome:"drafting"}),te(),Oe(),z(U),T(""),M(J),A(ue),O(!1),y({status:"idle"}),H.current+=1,Se([]),F(!0);const Ke=Un({request:U,mode:J,currentSql:oe,selectedTableName:i||"",selectedSchemaName:r||"",selectedDatabaseName:a||""});ye.current={sessionId:Ve,message:Ke,runToken:Fe}},[Le,Oe,We,me,ke,v,te,a,r,i,Se]),Tt=N.useCallback(_=>{const U=D.trim();U&&(c(U,_),_||F(!1))},[c,D]),rt=D.trim().length>0,$t=["valid","invalid","error"].includes(P.status),lt=rt&&$t,yt=P.status==="invalid",Et=P.status==="validating",ot=rt&&E.length>0&&E===v.trim(),it=We.length>0,Ue=v.length>0,ct=ot&&I==="draft",dt=ot&&I==="refine"&&S===We,ze=k==="refine"&&!it?"draft":k,Nt=(ze==="refine"?dt:ct)?"Open composer preview":"Generate composer SQL",Ct=v.trim().length>0||E.trim().length>0||rt||P.status!=="idle"||L.timelineSteps.length>0,It=N.useCallback((_="draft")=>{if(ke)return;if((_==="refine"?dt:ct)&&!V){te(),F(!0);return}vt(_)},[ct,dt,vt,ke,V,te]),kt=N.useCallback(()=>{te(),F(!0)},[te]),Gt=N.useCallback(_=>{$e("cancelled"),w(_)},[$e]),He=N.useCallback(()=>{ke||($e("cancelled"),ne.current=!1,H.current+=1,pe.current="",W.current=0,w(""),z(""),T(""),M("draft"),j("draft"),A(""),O(!1),y({status:"idle"}),Oe(),Se([]),fe(_=>({...Yt,runId:_.runId})))},[$e,Oe,ke,Se,fe]),Dt=N.useCallback(_=>{_||$e("cancelled"),F(_)},[$e]),At=L.timelineSteps.findIndex(_=>_===L.activeStep),Ut=L.phase==="self-healing"?"Fixing validation issue":L.phase==="validating"?"Validating SQL":L.activeStep||"Drafting SQL",tt=P.status==="valid"?{label:"Validation passed",className:"border-emerald-500/30 bg-emerald-500/10 text-emerald-700",detail:P.message}:P.status==="invalid"?{label:"Validation failed",className:"border-destructive/40 bg-destructive/10 text-destructive",detail:P.message}:P.status==="error"?{label:"Validation unavailable",className:"border-border/60 bg-muted/20 text-muted-foreground",detail:P.message}:null;return e.jsxs("div",{ref:B,className:"relative flex h-8 min-w-[320px] flex-1 items-center",children:[e.jsx(t.Input,{value:v,onChange:_=>Gt(_.target.value),onFocus:kt,onClick:kt,onKeyDown:_=>{_.key==="Enter"&&(_.preventDefault(),It(ze))},placeholder:"Type your question...",className:["h-8 border-transparent bg-muted/45 shadow-none focus-visible:border-border focus-visible:bg-background focus-visible:ring-0",Ue?"pr-[60px]":"pr-10"].join(" ")}),e.jsxs(t.Popover,{open:V,onOpenChange:Dt,children:[e.jsx(t.PopoverAnchor,{asChild:!0,children:e.jsx("div",{className:"pointer-events-none absolute inset-0"})}),e.jsxs("div",{className:"absolute right-1 flex items-center gap-1",children:[Ue&&e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"size-6 p-0",onClick:_=>{_.preventDefault(),$e("cancelled"),w("")},disabled:ke,"aria-label":"Clear input",title:"Clear input",children:e.jsx(t.X,{className:"size-3.5"})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"size-6 p-0",onClick:_=>{_.preventDefault(),It(ze)},disabled:ke,"aria-label":Nt,title:Nt,children:e.jsx(Tn,{className:"size-3.5"})})]}),e.jsx(t.PopoverContent,{align:"start",alignOffset:0,side:"bottom",sideOffset:8,className:"w-[min(92vw,var(--radix-popover-trigger-width))] max-w-[760px] p-2.5",onOpenAutoFocus:_=>{_.preventDefault()},onInteractOutside:_=>{var J;const U=_.target;U&&((J=B.current)!=null&&J.contains(U))&&_.preventDefault()},children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Composer"}),E&&e.jsx("p",{className:"line-clamp-2 text-xs text-muted-foreground",children:E})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"inline-flex h-7 items-center rounded-md border border-border/60 bg-background p-0.5 shadow-sm",children:[e.jsx(t.Button,{type:"button",size:"sm",variant:ze==="draft"?"secondary":"ghost",className:["h-6 rounded-[6px] px-2 text-xs",ze!=="draft"?"text-muted-foreground hover:text-foreground":""].join(" "),onClick:()=>{j("draft"),O(!1)},children:"Draft New"}),e.jsx(t.Button,{type:"button",size:"sm",variant:ze==="refine"?"secondary":"ghost",className:["h-6 rounded-[6px] px-2 text-xs",ze!=="refine"?"text-muted-foreground hover:text-foreground":""].join(" "),onClick:()=>j("refine"),disabled:!it,children:"Refine Current"})]}),e.jsx("div",{className:"h-4 w-px bg-border/70"}),ke&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>{$e("stopped")},children:"Stop"}),!ke&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:He,disabled:!Ct,children:"Clear"})]})]}),L.timelineSteps.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[L.timelineSteps.map((_,U)=>{const J=_===L.activeStep&&["drafting","validating","self-healing"].includes(L.phase),ue=!J&&At>=0&&U<At;return e.jsx("span",{className:["rounded-full border px-2 py-0.5 text-[11px]",J?"border-foreground/30 bg-foreground/10 text-foreground":ue?"border-border/60 bg-muted/20 text-muted-foreground":"border-border/50 bg-background text-muted-foreground/80"].join(" "),children:Yn(_,L.attempt)},`${_}-${U}`)}),tt&&e.jsx(t.TooltipProvider,{delayDuration:150,children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:["rounded-full border px-2 py-0.5 text-[11px]",tt.className].join(" "),children:tt.label})}),e.jsx(t.TooltipContent,{side:"top",align:"start",className:"max-w-[680px] whitespace-pre-wrap break-words text-xs",children:tt.detail})]})})]}),e.jsx("div",{className:"py-0.5",children:e.jsx(t.AssistantContextEntityControls,{mode:"full",compact:!0,inlineLayout:!0,inlineTriggerFirst:!0,triggerVariant:"outline",triggerIconOnly:!1,triggerLabel:"Context",onSelectionChange:je})}),(ke||L.phase==="self-healing"||P.status==="validating")&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border/60 bg-muted/20 px-3 py-2 text-xs text-muted-foreground",children:[e.jsx(t.LoaderCircle,{className:"size-3.5 animate-spin"}),Ut]}),Ge&&e.jsx("div",{className:"rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-xs text-destructive",children:jt}),I==="refine"&&S&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-md border border-border/60 bg-muted/20 px-2.5 py-1.5 text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Refining editor SQL"}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>O(_=>!_),children:f?"Hide base SQL":"View base SQL"})]}),f&&e.jsx("div",{className:"max-h-[120px] overflow-auto rounded-md border border-border/60",children:e.jsx(t.CodeHighlighter,{code:S,language:"sql"})})]}),lt?e.jsxs("div",{className:"space-y-1",children:[I==="refine"&&e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Refined SQL"}),e.jsx("div",{className:"max-h-[200px] overflow-auto rounded-md border border-border/60",children:e.jsx(t.CodeHighlighter,{code:D,language:"sql"})})]}):rt?e.jsx("div",{className:"rounded-md border border-dashed border-border/70 px-3 py-2 text-xs text-muted-foreground",children:"Validating SQL draft before preview."}):!ke&&e.jsx("div",{className:"rounded-md border border-dashed border-border/70 px-3 py-2 text-xs text-muted-foreground",children:it?"Choose Draft New or Refine Current, then press Enter or click send.":"Describe what you want to query, then press Enter or click send to generate a SQL preview."}),e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[e.jsx(t.Button,{variant:"outline",size:"sm",className:"h-8",onClick:o,children:"Open Full Assistant"}),e.jsx(t.Button,{variant:"secondary",size:"sm",className:"h-8",disabled:ke||!lt,onClick:()=>Tt(!1),children:"Replace SQL"}),e.jsx(t.Button,{size:"sm",className:"h-8",disabled:ke||!lt||Et||yt,onClick:()=>Tt(!0),children:"Replace & Run"})]})]})})]})]})}function Zn(){var W,pe;const s=t.useQueryClient(),[n,a]=N.useState(!1),r=t.useEditorStore(X=>X.frame),i=t.useEditorStore(X=>X.card);t.useEditorStore(X=>X.isShowingVisual),t.useEditorStore(X=>X.selectedConnectionId),t.useEditorStore(X=>X.tempQueryData);const c=t.useEditorStore(X=>X.selectedDatabaseName);t.useEditorStore(X=>X.selectedDatamodelId);const o=t.useEditorStore(X=>X.selectedSchemaName);t.useEditorStore(X=>X.showAIDialog);const d=t.useEditorStore(X=>X.selectedTableName),{cardFilterValues:l}=t.useCardFilterValues((i==null?void 0:i.id)??""),m=t.useEditorStore(X=>X.inlineFilterValuesMap[(i==null?void 0:i.id)??""]),p=N.useMemo(()=>t.findCustomVisualConfigCard(r,i),[r,i]),{manifest:x}=t.useCustomVisual(((W=p==null?void 0:p.customCardPreferences)==null?void 0:W.url)||""),u=N.useMemo(()=>{var X;return(X=x==null?void 0:x.visuals)==null?void 0:X.find(we=>{var G;return we.name===((G=p==null?void 0:p.customCardPreferences)==null?void 0:G.componentName)})},[x,(pe=p==null?void 0:p.customCardPreferences)==null?void 0:pe.componentName]),h=t.resolveMultiInputType(p,u),g=N.useMemo(()=>t.getCustomVisualInputCards({frame:r,configCard:p,isMultiInputVisual:h==="multiple"}),[r,p,h]),b=N.useMemo(()=>{const X=g.findIndex(we=>(we==null?void 0:we.id)===(i==null?void 0:i.id));return X<0?-1:t.getSlotIndexForCard(i,X)},[g,i]),v=N.useMemo(()=>!p||h!=="multiple"||b<0?i.type:t.getEffectiveCardTypeForSlot(i,b,u==null?void 0:u.slots)??i.type,[p,h,b,i,u==null?void 0:u.slots]),w=N.useMemo(()=>v!==i.type?{...i,type:v}:i,[i,v]),E=N.useRef(!0),{setCardCustomCfg:z,setQueryResultColumns:D,setCardSql:T,setTempQueryData:I,setPythonStdOut:M,setCardPreferences:k,setCardType:j,setCardPython:S,setShowAIDialog:A,setCard:f,updateCardInFrame:O}=t.useEditorActions();t.useEditorStore(X=>X.onSave),t.useEditorStore(X=>X.onClose),t.useEditorStore(X=>X.actions.setSqlGen);const P=t.useEditorStore(X=>X.runSql),y=t.useEditorStore(X=>X.actions.setRunSql),L=t.useEditorStore(X=>X.actions.setIsSqlRunning),{data:C,isLoading:V,isFetching:F,isSuccess:R,isError:$,error:B,errorSql:K,queryKey:Y,refetch:H,errorMessage:Z}=t.useDashboardCardQuery(w);N.useEffect(()=>{if(C&&(C.rowLimitExceeded&&t.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),M((C==null?void 0:C.output)||""),C.records.length>0)){const{dimensionKeys:X}=t.getKeys(C.records);D(X)}},[C,D,M]),N.useEffect(()=>{(V||F)&&L(!0),($||R)&&L(!1),$&&(D([]),M(""))},[V,F,C,M,$,R,L,D,B]),N.useEffect(()=>{P&&(s.getQueryData(Y)||H(),y(!1))},[P,H,y,Y,s]);const ae=N.useRef(H);ae.current=H,N.useEffect(()=>{if(E.current){E.current=!1;return}ae.current()},[m]);function ee(X,we){T(X),we&&y(!0)}function de(){return e.jsxs(t.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(t.ResizablePanel,{id:"1",order:1,defaultSize:n?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(zn,{})}),n&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),n&&e.jsxs(e.Fragment,{children:[e.jsx(t.ResizableHandle,{withHandle:!0,className:"data-[panel-group-direction=vertical]:ml-2 data-[panel-group-direction=vertical]:mr-6 data-[panel-group-direction=vertical]:w-auto"}),e.jsxs(t.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:[e.jsx("div",{id:"python-container",className:"relative flex w-[99%] pt-0",children:e.jsx(_n,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function ce(){return e.jsx("div",{role:"editor-controls",className:"item-center flex w-full flex-wrap items-center gap-2 py-3 pl-2 pr-6",children:e.jsxs("div",{className:"flex w-full items-center gap-3",children:[e.jsxs(t.Button,{title:"Shift + Enter",disabled:V||F,onClick:()=>{H()},className:"h-8 shrink-0",size:"sm",children:[V||F?e.jsx(t.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(t.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),(C==null?void 0:C.sql)&&!Z&&e.jsxs(t.HoverCard,{openDelay:300,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,children:e.jsx(t.Info,{className:"h-4 w-4 shrink-0 cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(t.HoverCardContent,{align:"start",className:"w-[500px] p-0",children:e.jsx(La,{sql:C.sql})})]}),e.jsx(Me.EditorClearButton,{}),e.jsxs(t.Toggle,{pressed:n,onPressedChange:X=>a(X),className:"h-8",size:"sm",variant:"outline",children:[e.jsx(Pn,{className:"mr-2 size-4 text-foreground/70"}),"Python"]}),e.jsx(Xn,{currentSql:i==null?void 0:i.sql,currentPython:i==null?void 0:i.python,selectedDatabaseName:c,selectedSchemaName:o,selectedTableName:d,onApplySql:ee,onOpenFullAssistant:()=>A(!0)}),e.jsx("div",{className:"ml-auto flex shrink-0 items-center gap-3",children:l&&l.length>0&&e.jsxs(t.HoverCard,{openDelay:200,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",className:"h-8 gap-2 px-2",children:[e.jsx(t.Filter,{className:"size-4"}),e.jsx(t.Badge,{className:"h-5 min-w-5 bg-purple-100 px-1.5 text-purple-700 hover:bg-purple-100 dark:bg-purple-950 dark:text-purple-300",children:l.length})]})}),e.jsx(t.HoverCardContent,{className:"mr-4 max-h-[400px] w-[500px] overflow-auto p-0",children:e.jsxs("div",{className:"p-3",children:[e.jsx("div",{className:"mb-2 text-sm font-semibold",children:"Active Dashboard Filters"}),e.jsx(t.CodeHighlighter,{code:JSON.stringify(l,null,2),language:"json"})]})})]})})]})})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsx("div",{className:"relative flex grow overflow-y-scroll",children:de()}),ce()]})}const er=[{value:"table",label:"Table",icon:t.Table2},{value:"aggregateTable",label:"Aggregate",icon:t.Layers},{value:"pivotTable",label:"Pivot",icon:t.Grid3x3},{value:"detailTable",label:"Detail",icon:t.List}];function tr({className:s}){const n=t.useEditorStore(x=>x.card),a=t.useEditorStore(x=>x.frame),r=Me.useEffectiveEditorCardType(),{setCard:i,updateCardInFrame:c}=t.useEditorActions(),o=["table","aggregateTable","pivotTable","detailTable"].includes(r),d=t.hasValidCardConfig(n.config),l=t.isCustomVisualConfigCard(n,a.cards);if(!o||!d||l)return null;const m=x=>{if(l)return;const u=x,h=n.config??{},g=p(r,u,h),b={...n,type:u,config:g};i(b),c(b)},p=(x,u,h)=>{var b;if(u==="detailTable"){const v=D=>D==null?void 0:D.toLowerCase().replace(/\s+/g,"").trim(),w=(D,T)=>{const I=[v(D.label),v(D.qualifiedFieldName),v(D.name)].filter(Boolean),M=[v(T.label),v(T.qualifiedFieldName),v(T.name)].filter(Boolean);return I.some(k=>M.includes(k))},E=(h.groupByColumns||[]).map(D=>({...D,role:"detail"})),z=((b=h.sortByColumns)==null?void 0:b.filter(D=>E.some(T=>w(D,T))))??[];return{...h,detailTableBackup:{groupByColumns:h.groupByColumns,metricColumns:h.metricColumns,pivotByColumns:h.pivotByColumns,sortByColumns:h.sortByColumns,rowAggregates:h.rowAggregates,columnAggregates:h.columnAggregates,comparisonType:h.comparisonType},detailColumns:E,groupByColumns:[],metricColumns:[],pivotByColumns:[],sortByColumns:z,rowAggregates:[],columnAggregates:[],comparisonType:"none"}}let g=h;if(x==="detailTable")if(h.detailTableBackup)g={...h,...h.detailTableBackup,detailColumns:[],detailTableBackup:void 0};else{const v=(h.detailColumns||[]).map(w=>({...w,role:"groupby"}));g={...h,groupByColumns:v,detailColumns:[]}}return u==="aggregateTable"?{...g,pivotByColumns:[]}:g};return e.jsx("div",{className:t.cn("flex items-center",s),children:e.jsx(t.RadioGroup,{value:r,onValueChange:m,className:"flex flex-row items-center gap-1 border-b border-border/60",children:er.map(x=>{const u=x.icon,h=r===x.value;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(t.RadioGroupItem,{value:x.value,id:`table-type-${x.value}`,className:"peer sr-only"}),e.jsxs(t.Label,{htmlFor:`table-type-${x.value}`,className:t.cn("flex h-8 cursor-pointer items-center justify-center gap-1.5 whitespace-nowrap border-b-2 border-transparent px-2 pb-1 text-xs font-medium transition-colors",h?"border-foreground text-foreground":"text-muted-foreground hover:border-foreground/30 hover:text-foreground"),children:[e.jsx(u,{className:t.cn("h-3.5 w-3.5",h?"opacity-100":"opacity-75")}),x.label]})]},x.value)})})})}function cs({error:s,errorSql:n,errorTitle:a="Unable to load data",onOpenInEditor:r,onDebugWithAssistant:i,onSendFeedback:c,showFeedbackButton:o=!0,className:d}){const[l,m]=N.useState(!1);return e.jsx("div",{className:t.cn("rounded-lg border border-border bg-muted/40 p-4",d),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-amber-500/10 dark:bg-amber-500/20",children:e.jsx(t.TriangleAlert,{className:"h-4 w-4 text-amber-600 dark:text-amber-500"})}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:a}),e.jsxs("div",{className:"relative rounded-md border border-border bg-background p-3",children:[e.jsx(t.CopyButton,{text:s,className:"absolute right-2 top-2 z-10 h-6 w-6"}),e.jsx("div",{className:"max-h-40 overflow-auto pr-10",children:e.jsx("p",{className:"break-all font-mono text-xs text-muted-foreground",children:s})})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n&&e.jsx(t.Collapsible,{open:l,onOpenChange:m,children:e.jsx(t.CollapsibleTrigger,{asChild:!0,children:e.jsx(t.Button,{variant:"outline",size:"sm",className:"h-8",children:l?e.jsxs(e.Fragment,{children:[e.jsx(t.ChevronUp,{className:"mr-1.5 h-3.5 w-3.5"}),"Hide Details"]}):e.jsxs(e.Fragment,{children:[e.jsx(t.ChevronDown,{className:"mr-1.5 h-3.5 w-3.5"}),"Show Details"]})})})}),r&&n&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8",onClick:r,children:[e.jsx(Ta,{className:"mr-1.5 h-3.5 w-3.5"}),"Open in Editor"]}),o&&c&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8",onClick:c,children:[e.jsx(t.MessageSquareWarning,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]}),i&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8",onClick:i,children:[e.jsx(jn,{className:"mr-1.5 h-3.5 w-3.5"}),"Debug with Assistant"]})]}),n&&e.jsx(t.Collapsible,{open:l,onOpenChange:m,children:e.jsx(t.CollapsibleContent,{className:"space-y-2",children:e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Query"}),e.jsx(t.CopyButton,{text:n,className:"h-6 w-6"})]}),e.jsx("div",{className:"max-h-80 overflow-auto rounded-md border border-border bg-background p-2",children:e.jsx(t.CodeHighlighter,{code:n,language:"sql"})})]})})})]})]})})}function Oa(s,n){const a=t.useEditorStore(m=>m.card),r=t.useEditorStore(m=>m.isDevMode),{switchEditorMode:i,setRunSql:c,runAssistant:o}=t.useEditorActions();return{isDevMode:r,handleOpenInEditor:r?void 0:()=>{const m=n||a.sql||a.python||"";i("dev",{sqlToLoad:m}),setTimeout(()=>{c(!0)},100)},handleDebugWithAssistant:r?()=>{const m=`Can you help me debug this query?
182
-
183
- Error:
184
-
185
- ${s}
186
-
187
- Error SQL:
188
-
189
- ${n||a.sql||a.python}
190
-
191
- `;o(m)}:void 0}}function Fa({className:s,...n}){var X,we,G,ne,ye;const a=t.useEditorStore(se=>se.card);t.useEditorStore(se=>se.isDevMode);const r=((X=a.customCardPreferences)==null?void 0:X.showCardHeader)??!0,i=((G=(we=a.preferences)==null?void 0:we.displayOptions)==null?void 0:G.showInlineFilterBar)??!0,c=t.useEditorStore(se=>se.frame),o=t.useEditorStore(se=>se.inlineFilterValuesMap[a.id]),d=t.useDashboardStore(se=>se.dashboard.filters),l=t.useDashboardStore(se=>se.selectedSheetId),[m,p]=N.useState(!1),{currentUser:x}=t.useCurrentUserInfo(),{tokenProps:u}=N.useContext(t.SemaphorContext),h=t.useEditorStore(se=>se.actions.setRunSql),g=t.useEditorStore(se=>se.actions.setCardInlineFilterValue),b=t.useEditorStore(se=>se.actions.removeCardInlineFilterValue),{updateFilter:v}=t.useDashboardActions(),w=d==null?void 0:d.find(se=>se.id===c.filterId),E=N.useMemo(()=>t.findCustomVisualConfigCard(c,a),[c,a]),{manifest:z}=t.useCustomVisual(((ne=E==null?void 0:E.customCardPreferences)==null?void 0:ne.url)||""),D=N.useMemo(()=>{var se;return(se=z==null?void 0:z.visuals)==null?void 0:se.find(be=>{var ge;return be.name===((ge=E==null?void 0:E.customCardPreferences)==null?void 0:ge.componentName)})},[z,(ye=E==null?void 0:E.customCardPreferences)==null?void 0:ye.componentName]),T=t.resolveMultiInputType(E,D),I=N.useMemo(()=>t.getCustomVisualInputCards({frame:c,configCard:E,isMultiInputVisual:T==="multiple"}),[c,E,T]),M=N.useMemo(()=>{const se=I.findIndex(be=>(be==null?void 0:be.id)===(a==null?void 0:a.id));return se<0?-1:t.getSlotIndexForCard(a,se)},[I,a]),k=N.useMemo(()=>!E||T!=="multiple"||M<0?a.type:t.getEffectiveCardTypeForSlot(a,M,D==null?void 0:D.slots)??a.type,[E,T,M,a,D==null?void 0:D.slots]),j=k??a.type,S=N.useMemo(()=>j===a.type?a:{...a,type:j},[a,j]),A=N.useMemo(()=>k!==a.type?{...a,type:k}:a,[a,k]),{data:f,isLoading:O,isFetching:P,errorMessage:y,errorSql:L,pagination:C}=t.useDashboardCardQuery(A),{handleOpenInEditor:V,handleDebugWithAssistant:F}=Oa(y,L||a.sql||a.python),R=N.useMemo(()=>(f==null?void 0:f.records)||[],[f==null?void 0:f.records]),{setCard:$,updateCardInFrame:B}=t.useEditorActions(),{data:K}=t.useTopoJson(S),Y=N.useMemo(()=>{var se;return j!=="pivotTable"||!((se=f==null?void 0:f.records)!=null&&se.length)?null:{records:f.records,columnSubtotalMeta:f.columnSubtotalMeta,subtotalColumns:f.subtotalColumns||[],pivotSchema:f.pivotSchema||[],groupByColumns:f.groupByColumns}},[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]),H=t.usePivotTableConfig(S,Y),Z=()=>{p(!0)},ae=N.useMemo(()=>{const se=typeof window<"u"?window.location.href:"",be=typeof navigator<"u"?navigator.userAgent:"",ge=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:t.FeedbackCategory.QUERY_GENERATION,user:x,tokenContext:u,systemState:{cardConfig:a.config,dataSource:a.dataSource,dashboardFilters:d,errorMessage:y||void 0,errorSql:L||a.sql||a.python,generatedSql:L||a.sql},metadata:{url:se,userAgent:be,timestamp:new Date().toISOString(),viewport:ge}}},[x,u,a,d,y,L]),ee=(se,be)=>{var fe,Ne;const ge={...a,paginationConfig:{page:se+1,pageSize:be}};$(ge),B(ge),a.sql&&((Ne=(fe=a.preferences)==null?void 0:fe.tablePrefs)!=null&&Ne.enableDevModePagination)&&h(!0)},de=se=>{var fe,Ne,ve,Te,Le;const be=t.sortStateToSortByColumns(se,(fe=a.config)==null?void 0:fe.metricColumns,(Ne=a.config)==null?void 0:Ne.groupByColumns,(ve=a.config)==null?void 0:ve.detailColumns),ge={...a,config:{...a.config||{},sortByColumns:be}};$(ge),B(ge),a.sql&&((Le=(Te=a.preferences)==null?void 0:Te.tablePrefs)!=null&&Le.enableDevModePagination)&&h(!0)},ce=N.useMemo(()=>!S.id||!(f!=null&&f.records)?null:t.createChartConfig({card:S,data:f==null?void 0:f.records,cardType:j,queryConfig:S.queryConfig,customCfg:S.customCfg,preferences:S.preferences,topoJson:K}),[S,f==null?void 0:f.records,j,K]);function W(se){return e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackVisual,children:e.jsx(t.EditorCustomVisual,{card:se})})}function pe(){var se;if(f!=null&&f.records&&(f==null?void 0:f.records.length)===0&&!O&&!P)return y?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(cs,{error:y,errorSql:L||a.sql||a.python,onOpenInEditor:V,onDebugWithAssistant:F,onSendFeedback:Z,showFeedbackButton:!0})}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(t.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((O||P)&&(!(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(t.TableSkeleton,{})}):e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!S.id)return null;if(j==="custom")return W(a);if(!["table","pivotTable","aggregateTable","detailTable","custom"].includes(j)&&ce)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:O||P?e.jsx(e.Fragment,{}):e.jsx(t.ChartJsVisual,{cfg:ce})});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(t.TableVisual,{card:S,data:R,comparisonMetadata:(se=f==null?void 0:f.metadata)==null?void 0:se.comparisonMetadata,paginationMetadata:C,onPaginationChange:ee,onSortChange:de,isLoading:O||P})});if(j==="pivotTable"&&H)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(t.PivotTableTanstack,{card:S,data:H.data,options:H.options,onAggregationChange:be=>{const ge=t.handleAggregationChange(be,a.config),fe={...a,config:ge};$(fe),B(fe)},onAggregationLabelChange:be=>{const ge=t.handleAggregationLabelChange(be,a.config),fe={...a,config:ge};$(fe),B(fe)}})});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(t.AggregateTable,{card:S,data:(f==null?void 0:f.records)||[],groupByColumns:f==null?void 0:f.groupByColumns,pivotSchema:f==null?void 0:f.pivotSchema,paginationMetadata:C,onPaginationChange:ee,onAggregationChange:be=>{const ge=t.handleAggregationChange(be,a.config),fe={...a,config:ge};$(fe),B(fe)},isLoading:O||P})})}return e.jsxs(t.Card,{role:"editor-visual-card",className:t.cn("relative flex h-full flex-col rounded-none",s),...n,children:[(O||P)&&(f==null?void 0:f.records)&&f.records.length>0&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),r&&e.jsxs(t.CardHeader,{className:t.cn("flex flex-row items-start justify-between py-4 pr-6","pl-2"),children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.CardTitle,{className:"text-base",children:e.jsx(t.EditableText,{value:a.title,onSave:se=>$({...a,title:se}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(t.InfoHover,{card:a}),e.jsx(Me.VisualBadge,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(tr,{})})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(t.EditableText,{value:(a.description||"").trim(),onSave:se=>$({...a,description:se.trim()}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),w&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Label,{className:"my-1",children:e.jsx(t.EditableText,{value:w.title||w.column,onSave:se=>v({...w,title:se}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(t.FilterComponent,{filter:w})]})]}),i&&a.inlineFilters&&a.inlineFilters.length>0&&e.jsx("div",{className:t.cn("pb-3 pr-6","pl-2"),children:e.jsx(t.InlineFilterBar,{card:a,sheetId:l||"",inlineFilterValues:o,setInlineFilterValue:se=>g(a.id,se),removeInlineFilterValue:se=>b(a.id,se)})}),e.jsxs(t.CardContent,{className:t.cn("flex min-h-0 grow flex-col pr-6","pl-2"),children:[e.jsx("div",{className:"min-h-0 flex-1 grow basis-0",children:pe()}),t.isCardSummaryVisibleOnCard(S)&&e.jsx("div",{className:"pt-3",children:e.jsx(t.CardSummary,{card:S,mode:"editor"})})]}),e.jsx(t.FeedbackDialog,{open:m,onOpenChange:p,feedbackData:ae,showDebugInfo:!0})]})}const Wt=({language:s,value:n,onChange:a,readonly:r})=>e.jsx(t.Ft,{className:"h-full w-full overflow-hidden text-xs",theme:"default",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,lineHeight:16,renderLineHighlight:"none",readOnly:r},defaultLanguage:s,value:n,onChange:a}),sr=()=>e.jsxs(t.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(t.DialogTitle,{children:"Customize Card"})}),e.jsxs(t.DialogDescription,{children:["See the configuration options and documentation",e.jsx("a",{target:"_blank",className:"ml-1 text-blue-500 underline",href:"https://www.chartjs.org/docs/latest/samples/bar/vertical.html",children:"here."})]})]}),ar=({customCode:s,cardCustomCfgString:n,mergedConfig:a,onConfigChange:r,onCodeChange:i})=>e.jsxs(t.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(t.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(t.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(t.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(t.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(t.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Wt,{language:"json",value:a,onChange:r})}),e.jsx(t.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Wt,{readonly:!0,language:"json",value:n,onChange:()=>{}})}),e.jsx(t.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Wt,{language:"javascript",value:s,onChange:i})})]}),nr=({error:s,hasCardCustomConfig:n,onReset:a,onApply:r,onClose:i})=>e.jsxs(t.DialogFooter,{className:"flex items-center",children:[e.jsx(t.Label,{className:"mr-2 text-red-500",children:s}),e.jsx(t.Button,{disabled:!n,onClick:a,variant:"outline",children:"Reset"}),e.jsx(t.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(t.Button,{onClick:i,variant:"outline",children:"Close"})]});function rr({triggerVariant:s="icon",className:n,label:a="Customize Visual"}={}){const[r,i]=N.useState(!1),[c,o]=N.useState(""),[d,l]=N.useState(""),[m,p]=N.useState(""),[x,u]=N.useState(""),h=t.useEditorStore(S=>S.card),g=Me.useEffectiveEditorCardType(),b=t.useEditorStore(S=>S.card.customCfg),v=b?JSON.stringify(b,null,2):"",w=N.useMemo(()=>g!==h.type?{...h,type:g}:h,[h,g]),{data:E}=t.useDashboardCardQuery(w),{data:z}=t.useTopoJson(h),{setCardCustomCfg:D,setCustomVisualCode:T}=t.useEditorActions(),I=S=>{var A,f;return JSON.stringify({...S,data:{...S.data,datasets:(f=(A=S.data)==null?void 0:A.datasets)==null?void 0:f.map(O=>({...O,data:[]}))}},null,2)},M=()=>{var A,f;if(!((A=E==null?void 0:E.records)!=null&&A.length))return;const S=t.createChartConfig({card:h,data:E.records,cardType:h.type,queryConfig:h.queryConfig,preferences:h.preferences,topoJson:z});if(S){o(I(S)),p(((f=h.preferences)==null?void 0:f.customVisualCode)||"");const O=t.merge(S,b);l(I(O))}},k=()=>{try{if(m&&T(m),d){const S=JSON.parse(d),A=t.getObjectDiff(JSON.parse(c),S);D(A),u("")}}catch{u("Invalid JSON configuration")}},j=Object.keys(b||{}).length===0;return e.jsxs(t.Dialog,{open:r,onOpenChange:i,children:[e.jsx(t.DialogTrigger,{asChild:!0,children:s==="menu"?e.jsxs(t.Button,{variant:"ghost",onClick:M,className:t.cn("h-8 w-full justify-start gap-2 px-2 text-sm",j?"":"text-green-600 hover:text-green-700",n),children:[e.jsx(t.Settings,{className:"h-4 w-4"}),e.jsx("span",{children:a})]}):e.jsx(t.IconButton,{tooltip:"Customize Visual",onClick:M,className:t.cn(j?"":"text-green-600 hover:text-green-700",n),children:e.jsx(t.Settings,{className:"h-4 w-4"})})}),e.jsxs(t.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(sr,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackVisual,children:e.jsx(Fa,{className:"w-1/2 rounded shadow-none"})}),e.jsx(ar,{customCode:m,cardCustomCfgString:v,mergedConfig:d,onConfigChange:S=>l(S??""),onCodeChange:S=>p(S??"")})]}),e.jsx(nr,{error:x,hasCardCustomConfig:!!b,onReset:()=>{l(c),D(null)},onApply:k,onClose:()=>i(!1)})]})]})}function lr({isStarred:s,onClick:n,className:a}){const r=i=>{i.stopPropagation(),i.preventDefault(),n(i)};return e.jsx("button",{type:"button",onClick:r,className:t.cn("flex items-center justify-center rounded-sm p-0.5 transition-all","hover:bg-muted/80",a),"aria-label":s?"Remove from favorites":"Add to favorites",children:e.jsx(t.Star,{className:t.cn("h-3.5 w-3.5 transition-colors",s?"fill-yellow-400 text-yellow-400":"text-muted-foreground hover:text-foreground")})})}function ca({chartType:s,chartName:n,isCustom:a=!1,pluginName:r,isStarred:i,showStar:c=!0,onSelect:o,onToggleStar:d}){return e.jsxs("button",{onClick:o,className:t.cn("group relative flex flex-col items-center gap-2 rounded-lg border border-border","bg-background p-3 transition-all","hover:border-primary/50 hover:bg-muted/50 hover:shadow-sm"),children:[c&&e.jsx("div",{className:t.cn("absolute left-1 top-1 transition-opacity",i?"opacity-100":"opacity-0 group-hover:opacity-100"),children:e.jsx(lr,{isStarred:i,onClick:()=>d()})}),a&&r&&e.jsx("div",{className:"absolute right-1 top-1",children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center justify-center",children:e.jsx(t.Info,{className:"h-3 w-3 text-muted-foreground"})})}),e.jsx(t.TooltipContent,{side:"top",className:"text-xs",children:r})]})}),e.jsx(t.ChartIcon,{chartType:s,chartName:n,isCustom:a,className:"h-6 w-6"}),e.jsx("span",{title:n,className:"line-clamp-2 text-center text-xs font-medium text-foreground",children:n})]})}const da=[{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 or({onChartSelect:s,onClose:n}){const[a,r]=N.useState(""),{starredCharts:i,isStarred:c,toggleStar:o}=t.useStarredChartsStore(),{data:d=[],isLoading:l}=t.useCustomVisualsQuery(),{setCardType:m,setCardPreferences:p,setIsDevMode:x}=t.useEditorStore(j=>j.actions),u=t.useEditorStore(j=>j.card),{setCardCustomCfg:h,setCustomCardPreferences:g,setQueryConfig:b,replaceFrameCards:v,clearModeDrafts:w,initializeModeDrafts:E}=t.useEditorActions(),z=N.useMemo(()=>{if(!a)return da;const j=a.toLowerCase();return da.filter(S=>S.name.toLowerCase().includes(j))},[a]),D=N.useMemo(()=>{const j=d.filter(A=>A.componentType==="chart"&&A.pluginType!=="standard");if(!a)return j;const S=a.toLowerCase();return j.filter(A=>A.name.toLowerCase().includes(S))},[d,a]),T=j=>{h(null),p({}),m(j),["custom","text","map"].includes(j)&&(x(!0),b(void 0)),s==null||s(j),n==null||n()},I=j=>{h(null),p({}),b(void 0);const S=t.resolveMultiInputTypeFromVisual(j);if(S==="multiple"&&j.slots&&j.slots.length>0){w();const f=t.createCardsFromSlots(j.slots,j,u);v(f),f[0]&&E(f[0]),n==null||n();return}else m("custom"),g({type:"component",visualType:S,url:j.url,componentName:j.name,icon:j.icon,pluginChartType:j.chartType,minInputs:j.minInputs,maxInputs:j.maxInputs});s==null||s("custom",j),n==null||n()},M=j=>{const S={type:"default",id:j.id,name:j.name};o(S)},k=j=>{const S={type:"custom",id:j.name,url:j.url,icon:j.icon,name:j.name};o(S)};return e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2 rounded-sm border border-border bg-background px-3 py-2",children:[e.jsx(t.Search,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(t.Input$1,{placeholder:"Search charts...",value:a,onChange:j=>r(j.target.value),className:"h-auto border-0 p-0 text-sm focus-visible:ring-0 focus-visible:ring-offset-0"})]}),e.jsxs("div",{className:"max-h-[350px] overflow-y-auto",children:[z.length>0&&e.jsx("div",{className:"mb-3",children:e.jsx("div",{className:"grid grid-cols-3 gap-2",children:z.map(j=>e.jsx(ca,{chartType:j.id,chartName:j.name,isCustom:!1,isStarred:c("default",j.id),onSelect:()=>T(j.id),onToggleStar:()=>M(j)},j.id))})}),D.length>0&&e.jsxs(e.Fragment,{children:[z.length>0?e.jsx(t.Separator,{className:"my-3"}):null,e.jsxs("div",{children:[e.jsx("span",{className:"mb-2 block text-xs font-medium text-muted-foreground",children:"Custom Charts"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:D.map((j,S)=>e.jsx(ca,{chartName:j.name,isCustom:!0,pluginName:j.pluginName,isStarred:c("custom",j.name),onSelect:()=>I(j),onToggleStar:()=>k(j)},`${j.url}-${j.name}-${S}`))})]})]}),l&&e.jsxs(e.Fragment,{children:[e.jsx(t.Separator,{className:"my-3"}),e.jsx("div",{className:"py-4 text-center text-sm text-muted-foreground",children:"Loading custom charts..."})]}),z.length===0&&D.length===0&&!l&&e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No charts found"})]})]})}function ir({selectedChart:s,onChartChange:n}){var I,M,k,j;const a=t.useEditorStore(S=>S.card),r=t.useEditorStore(S=>S.frame),i=t.useEditorStore(S=>S.isDevMode),{replaceFrameCards:c,clearModeDrafts:o,initializeModeDrafts:d,setIsDevMode:l}=t.useEditorActions(),m=N.useMemo(()=>t.findCustomVisualConfigCard(r,a),[r,a]),{manifest:p}=t.useCustomVisual(((I=m==null?void 0:m.customCardPreferences)==null?void 0:I.url)||""),x=N.useMemo(()=>{var S;return(S=p==null?void 0:p.visuals)==null?void 0:S.find(A=>{var f;return A.name===((f=m==null?void 0:m.customCardPreferences)==null?void 0:f.componentName)})},[p,(M=m==null?void 0:m.customCardPreferences)==null?void 0:M.componentName]),u=t.resolveMultiInputType(m,x)==="multiple",h=Me.useEffectiveEditorCardType(),g=u?h:s??a.type,b=(k=a==null?void 0:a.customCardPreferences)==null?void 0:k.componentName,v=(j=m==null?void 0:m.customCardPreferences)==null?void 0:j.componentName,w=u&&!!v,E=N.useMemo(()=>{const S=t.chartTypes.find(A=>A.id===g);return S?S.label:g==="custom"?b||"Custom Visual":"Select chart type"},[g,b]),z=N.useMemo(()=>{const S=t.chartTypes.find(A=>A.id===g);if(S){const A=S.icon;return e.jsx(A,{className:"h-4 w-4"})}if(g==="custom"&&b){const A=t.getAutoDetectedChartIcon(b);return A||e.jsx(t.ChartIcon,{chartName:b,isCustom:!0,className:"h-4 w-4"})}return e.jsx(En,{className:"h-4 w-4"})},[g,b]);return{displayChartType:g,displayLabel:E,displayIcon:z,showBadge:w,badgeLabel:v,isMultiInputContext:u,handleChartSelect:S=>{n==null||n(S)},handleClearCustomVisual:S=>{S.stopPropagation();const A={...a,type:"bar",sql:"",python:"",config:void 0,queryConfig:void 0,customCfg:void 0,preferences:{},customCardPreferences:void 0,title:"Chart",tabTitle:"Chart",description:void 0,info:void 0};c([A]),o(),d(A),i&&l(!0),n==null||n("bar")}}}function ds({selectedChart:s,onChartChange:n,variant:a="ghost",className:r}){const[i,c]=N.useState(!1),{displayLabel:o,displayIcon:d,showBadge:l,badgeLabel:m,handleChartSelect:p,handleClearCustomVisual:x}=ir({selectedChart:s,onChartChange:n});return e.jsxs("div",{className:t.cn("relative w-full",r),children:[e.jsxs(t.Popover,{open:i,onOpenChange:c,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{size:"sm",variant:a,role:"combobox","aria-expanded":i,className:t.cn("w-full justify-between gap-2",a==="ghost"&&"border border-border/70 bg-background text-foreground/90",a==="outline"&&"border-border/70 bg-background text-foreground/90",a==="secondary"&&"text-foreground"),children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[d,e.jsx("span",{className:"truncate",children:o})]}),e.jsx(t.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-70"})]})}),e.jsx(t.PopoverContent,{className:"w-[360px] p-3",align:"start",onOpenAutoFocus:u=>u.preventDefault(),children:e.jsx(or,{onChartSelect:u=>p(u),onClose:()=>c(!1)})})]}),l&&e.jsxs("div",{className:"absolute right-10 top-1/2 z-10 flex max-w-[140px] -translate-y-1/2 items-center gap-1 rounded-full border bg-background py-0.5 pl-2 pr-1 text-[10px] text-muted-foreground shadow-sm",title:m,children:[e.jsx(t.Layers,{className:"h-2.5 w-2.5 shrink-0"}),e.jsx("span",{className:"truncate",children:m}),e.jsx("button",{onClick:x,className:"rounded-full p-0.5 hover:bg-muted",title:"Clear custom visual",children:e.jsx(t.X,{className:"h-2.5 w-2.5"})})]})]})}function cr(){const s=t.useEditorStore(l=>{var m,p;return(p=(m=l.card.preferences)==null?void 0:m.chartOptions)==null?void 0:p.indexAxis}),n=t.useEditorStore(l=>l.card.type),{setChartOrientation:a,setCardPreferences:r}=t.useEditorStore(l=>l.actions),i=l=>{if(a(l),n!=="bullet")return;const m=l==="y"?"horizontal":"vertical",p=t.useEditorStore.getState().card.preferences,x={...p||{},bulletConfig:{...(p==null?void 0:p.bulletConfig)||{},orientation:m}};r(x)};function c(){const l=s??"x",m=()=>{i(l==="x"?"y":"x")};return e.jsx(t.IconButton,{onClick:m,tooltip:"Chart Orientation",children:l==="x"?e.jsx(Jt,{className:"size-4"}):e.jsx(Qt,{className:"size-4"})})}function o(){const l=()=>{i(s==="y"||s===void 0?"x":"y")};return e.jsx(t.IconButton,{onClick:l,tooltip:"Chart Orientation",children:s==="y"||s===void 0?e.jsx(Jt,{className:"size-4"}):e.jsx(Qt,{className:"size-4"})})}function d(){const l=s??"y",m=()=>{i(l==="y"?"x":"y")};return e.jsx(t.IconButton,{onClick:m,tooltip:"Chart Orientation",children:l==="y"?e.jsx(Qt,{className:"size-4"}):e.jsx(Jt,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?o():n==="bullet"?d():c()})}function us({className:s,triggerVariant:n="icon",label:a="Display Options"}){var b,v,w,E,z,D,T,I,M,k;const r=t.useEditorStore(j=>j.card),{setCardPreferences:i,updateCardInFrame:c,setCard:o}=t.useEditorActions(),[d,l]=N.useState(!1),m=((v=(b=r.preferences)==null?void 0:b.displayOptions)==null?void 0:v.showFilterInfo)??!0,p=((E=(w=r.preferences)==null?void 0:w.displayOptions)==null?void 0:E.showCardToolbar)??!0,x=((D=(z=r.preferences)==null?void 0:z.displayOptions)==null?void 0:D.showChrome)??!0,u=((I=(T=r.preferences)==null?void 0:T.displayOptions)==null?void 0:I.allowScroll)??!0,h=((k=(M=r.preferences)==null?void 0:M.displayOptions)==null?void 0:k.showInlineFilterBar)??!0,g=(j,S)=>{var O;const A={...r.preferences,displayOptions:{...(O=r.preferences)==null?void 0:O.displayOptions,[j]:S}};i(A);const f={...r,preferences:A};o(f),c(f)};return e.jsx("div",{className:t.cn("flex items-center",s),children:e.jsxs(t.DropdownMenu,{modal:!1,open:d,onOpenChange:l,children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:n==="menu"?e.jsxs(t.Button,{variant:"ghost",className:"h-8 w-full justify-start gap-2 px-2 text-sm",children:[e.jsx(rs,{className:"h-4 w-4"}),e.jsx("span",{children:a})]}):e.jsx(t.IconButton,{className:"h-8 w-8 p-0",tooltip:"Display Options",children:e.jsx(rs,{className:"h-4 w-4"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(t.DropdownMenuLabel,{children:"Display Options"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsx("div",{className:"px-2 py-1.5",children:e.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"Changes apply to dashboard view only"})}),e.jsxs(t.DropdownMenuCheckboxItem,{checked:m,onCheckedChange:j=>{g("showFilterInfo",j)},onSelect:j=>j.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Filter Info"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Badge"})]}),e.jsxs(t.DropdownMenuCheckboxItem,{checked:p,onCheckedChange:j=>{g("showCardToolbar",j)},onSelect:j=>j.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Toolbar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Hover actions"})]}),e.jsxs(t.DropdownMenuCheckboxItem,{checked:x,onCheckedChange:j=>{g("showChrome",j)},onSelect:j=>j.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Chrome"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Frame & padding"})]}),e.jsxs(t.DropdownMenuCheckboxItem,{checked:u,onCheckedChange:j=>{g("allowScroll",j)},onSelect:j=>j.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Allow Scroll"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card content scroll"})]}),e.jsxs(t.DropdownMenuCheckboxItem,{checked:h,onCheckedChange:j=>{g("showInlineFilterBar",j)},onSelect:j=>j.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Inline Filter Bar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card filters"})]})]})]})})}function ms({className:s,triggerVariant:n="icon",label:a="Inline Filters"}){var T,I,M;const[r,i]=N.useState(!1),c=t.useEditorStore(k=>k.card),o=t.useEditorStore(k=>k.selectedConnectionId),{tokenProps:d}=t.useSemaphorContext(),{setCard:l}=t.useEditorActions(),m=t.useDashboardStore(k=>k.actions.removeCardInlineFilterValue),p=t.useDashboardStore(k=>k.actions.setCardInlineFilterValue),x=t.useEditorStore(k=>k.actions.removeCardInlineFilterValue),u=t.useEditorStore(k=>k.actions.setCardInlineFilterValue),h=t.useDashboardStore(k=>k.isVisualEditing),g=(c==null?void 0:c.inlineFilters)||[],b=((I=(T=d==null?void 0:d.params)==null?void 0:T.calendarContext)==null?void 0:I.tz)||((M=d==null?void 0:d.params)==null?void 0:M.timezone)||Intl.DateTimeFormat().resolvedOptions().timeZone;function v(k){var F,R,$,B,K;const j=(($=(R=(F=c==null?void 0:c.dataSource)==null?void 0:F.selectedEntities)==null?void 0:R[0])==null?void 0:$.database)||"",S=k.qualifiedFieldName||k.name;if(g.find(Y=>Y.column===S))return;const f=k.qualifiedFieldName?k.qualifiedFieldName.split(".").slice(0,-1).join("."):k.qualifiedEntityName||k.entityName,P=t.fmt(k.name),y=t.buildFilterFieldMeta(k),L=t.buildFilterSemanticContext(c==null?void 0:c.dataSource,{connectionId:o||((B=c==null?void 0:c.dataSource)==null?void 0:B.connectionId),connectionType:(K=c==null?void 0:c.dataSource)==null?void 0:K.connectionType}),C=t.isCalculatedFilterField(y),V={id:t.v4(),column:S,title:k.label||k.name,dataType:k.dataType,table:k.entityName||"",database:j,connectionId:o||"",operation:"in",sql:C?"":t.getDefaultFilterSql(k.dataType,f,P),fieldMeta:y,semanticContext:L,width:250};l({...c,inlineFilters:[...g,V]})}function w(k){const j=g.filter(S=>S.id!==k);l({...c,inlineFilters:j}),h?x(c.id,k):m(c.id,k)}function E(k,j){const S=g.map(P=>P.id===k?{...P,...j}:P);if(l({...c,inlineFilters:S}),!(Object.prototype.hasOwnProperty.call(j,"defaultValues")||Object.prototype.hasOwnProperty.call(j,"defaultDateFilter")))return;const f=S.find(P=>P.id===k);if(!f)return;const O=t.buildFilterValueFromDefaults(f,b);O?h?u(c.id,O):p(c.id,O):h?x(c.id,k):m(c.id,k)}if(!["bar","line","pie","doughnut","table","detailTable","stackedBar","stackedLine","horizontalBar","radar","polarArea","scatter","bubble","funnel","aggregateTable","custom"].includes(c==null?void 0:c.type))return null;const D=n==="menu";return e.jsx("div",{className:t.cn("flex items-center gap-1",D&&"w-full",s),children:e.jsxs(t.Popover,{open:r,onOpenChange:i,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:D?e.jsxs(t.Button,{variant:"ghost",className:t.cn("h-8 w-full justify-start gap-2 px-2 text-sm",g.length>0&&"text-primary"),children:[e.jsx(ea,{className:"h-4 w-4"}),e.jsx("span",{children:a}),g.length>0&&e.jsx("span",{className:"ml-auto inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-primary text-[10px] font-medium leading-none text-primary-foreground",children:g.length})]}):e.jsxs(t.IconButton,{tooltip:"Add Inline Filter",className:t.cn("relative",{"text-primary":g.length>0}),children:[e.jsx(ea,{className:"h-4 w-4"}),g.length>0&&e.jsx("span",{className:"absolute -right-1 -top-1 flex h-4 w-4 items-center justify-center rounded-full bg-primary text-[10px] font-medium text-primary-foreground",children:g.length})]})}),e.jsx(t.PopoverContent,{align:"end",className:t.cn("w-80 p-0",D&&"z-[60]"),children:e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"border-b px-4 py-3",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Inline Filters"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"On-card filters for fast, focused exploration."})]}),e.jsx("div",{className:"flex h-[320px] min-h-0 flex-col overflow-hidden",children:e.jsx(t.DndContext,{collisionDetection:t.closestCenter,children:e.jsx(t.SortableContext,{items:[],strategy:t.verticalListSortingStrategy,children:e.jsx(t.FieldsList,{context:"inline-filter",onFieldSelect:v,inlineFilters:g})})})}),g.length>0&&e.jsxs("div",{className:"border-t px-4 py-3",children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Active Filters"}),e.jsx("div",{className:"space-y-1",children:g.map(k=>e.jsx(dr,{filter:k,onUpdate:j=>E(k.id,j),onRemove:()=>w(k.id)},k.id))})]})]})})]})})}function dr({filter:s,onUpdate:n,onRemove:a}){return e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-muted px-2 py-1.5 text-sm",children:[e.jsx("span",{className:"truncate",title:s.column,children:s.title}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(t.CustomFilterPopover,{filter:s,variant:"inline",onAccept:r=>n(r),trigger:e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0",title:"Configure filter",children:e.jsx(t.Settings2,{className:"h-3 w-3"})})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0 hover:bg-destructive/10 hover:text-destructive",onClick:a,children:e.jsx(t.X,{className:"h-3 w-3"})})]})]})}function Ra({showOrientation:s=!0,showGridStyle:n=!0,showInlineFilters:a=!0,showDisplayOptions:r=!0}={}){const i=t.useEditorStore(u=>u.card),c=t.useEditorStore(u=>{var h,g;return(g=(h=u.card)==null?void 0:h.preferences)==null?void 0:g.chartOptions}),o=t.getChartGridStyle(c),{setChartGrid:d}=t.useEditorActions();function l(){const u=["xy","none","x","y"],g=(u.indexOf(o)+1)%u.length;d(u[g])}const m=s&&["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel","bullet"].includes(i.type),p=n&&!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(i.type);return m||p||a||r?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[m&&e.jsx(e.Fragment,{children:e.jsx(cr,{})}),p&&e.jsxs(t.IconButton,{tooltip:"Grid Style",onClick:l,children:[(o==="xy"||!o)&&e.jsx(t.Grid3x3,{className:"size-4"}),o==="x"&&e.jsx(is,{className:"size-4"}),o==="y"&&e.jsx(Pt,{className:"size-4"}),o==="none"&&e.jsx(t.Square,{className:"size-4"})]}),a&&e.jsx(ms,{}),r&&e.jsx(us,{})]}):null}function ur({visible:s}){const n=t.useDashboardStore(o=>o.selectedFrameId),a=t.useManagementStore(o=>o.selectedVisual),r=t.useEditorStore(o=>o.frame),c=!!!(r!=null&&r.visualId||a!=null&&a.id)&&!!n;return!s||c?null:e.jsx("div",{className:"mb-2 flex",children:e.jsx(Me.VisualBadge,{showLabel:!0,className:"h-6 w-fit px-2 py-0.5 text-[11px]"})})}function mr({isPreviewMode:s,onPreviewToggle:n,configCard:a}){var P,y,L,C,V;const r=t.useEditorStore(F=>F.frame),i=t.useEditorStore(F=>F.card),{setFrame:c,setActiveTabCardId:o,setCard:d,updateCardInFrame:l,clearModeDrafts:m,initializeModeDrafts:p}=t.useEditorActions(),{manifest:x}=t.useCustomVisual(((P=a==null?void 0:a.customCardPreferences)==null?void 0:P.url)||""),u=(y=x==null?void 0:x.visuals)==null?void 0:y.find(F=>{var R;return F.name===((R=a==null?void 0:a.customCardPreferences)==null?void 0:R.componentName)}),g=t.resolveMultiInputType(a,u)==="multiple",b=(u==null?void 0:u.minInputs)??((L=a==null?void 0:a.customCardPreferences)==null?void 0:L.minInputs)??1,v=(u==null?void 0:u.maxInputs)??((C=a==null?void 0:a.customCardPreferences)==null?void 0:C.maxInputs),w=N.useMemo(()=>t.getCustomVisualInputCards({frame:r,configCard:a,isMultiInputVisual:g}),[r,a,g]),E=g?w.filter(Boolean).length:r.cards.length,z=v?E<v:!0,D=E>Math.max(b||1,1),T=!!((V=a==null?void 0:a.customCardPreferences)!=null&&V.dataInputCardIds),I=(F,R)=>{F.dataTransfer.setData("tabIndex",R.toString())},M=F=>{F.preventDefault()},k=(F,R)=>{const $=F.dataTransfer.getData("tabIndex");if($===R.toString())return;const B=Array.from(r.cards),[K]=B.splice(parseInt($),1);B.splice(R,0,K),c({...r,cards:B})};function j(F){const R=(a==null?void 0:a.id)===F;if(!(T&&R?r.cards.length>1:D))return;let B=r.cards.filter(Z=>Z.id!==F);g&&!T&&(B=t.reindexSlotCards(B));const K=B[0],Y={...r,cards:B,activeCardId:K.id},H=F===i.id;H&&m(),c(Y),o(K.id),d(K),H&&p(K)}function S(F,R){if(!z)return;const $={...r,cards:[...r.cards,R],activeCardId:F.id};c($),o(R.id)}function A(){if(g&&(a==null?void 0:a.id)===i.id){f(i);return}const F={...i,id:t.v4(),title:`${i.title} Copy`,tabTitle:`${i.tabTitle||i.title} Copy`,customCardPreferences:i.customCardPreferences?{...i.customCardPreferences,slotIndex:g?Math.max(-1,...w.map((R,$)=>t.getSlotIndexForCard(R,$)))+1:i.customCardPreferences.slotIndex}:void 0};S(i,F)}function f(F){var H;if(!z)return;let R=g?"table":"bar",$="Title",B="";const K=g?Math.max(-1,...w.map((Z,ae)=>t.getSlotIndexForCard(Z,ae)))+1:E;if(g&&((H=u==null?void 0:u.slots)!=null&&H.length)){const Z=t.getSlotDefinitionForIndex(u.slots,K);Z&&(R=t.getSlotExpectedChartType(Z),$=Z.label||`Tab ${K+1}`,B=Z.description||"")}const Y={dataSource:F.dataSource,connectionId:F.connectionId,lastSelectedDatabase:F.lastSelectedDatabase,lastSelectedSchema:F.lastSelectedSchema,lastSelectedTable:F.lastSelectedTable,lastSelectedDatamodelId:F.lastSelectedDatamodelId,id:t.v4(),title:$,tabTitle:$,description:B,preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:R,sql:"",data:[],mode:"explorer",...g&&{customCardPreferences:{slotIndex:K}}};S(F,Y)}function O(F,R){return F.cards.length===1&&(R.displayTab===!0||R.displayTab===void 0)||F.activeCardId!==R.id&&(R.displayTab===!0||R.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const $=R.displayTab===void 0?!1:!R.displayTab;d({...R,displayTab:$}),l({...R,displayTab:$})},children:R.displayTab===!0||R.displayTab===void 0?e.jsx(t.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(t.EyeOff,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(t.TabsList,{className:"group ml-2 mr-6 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[r.cards.map((F,R)=>{var H,Z;const $=g?t.getSlotIndexForCard(F,R):-1,B=g&&((H=u==null?void 0:u.slots)!=null&&H.length)&&$>=0?t.getSlotDefinitionForIndex(u.slots,$):null,K=B?(Array.isArray(B.expectedType)?B.expectedType[0]:B.expectedType)||"table":F.type,Y=g&&((Z=u==null?void 0:u.slots)==null?void 0:Z.length)&&u.slots.every(ae=>typeof ae.position=="number"||typeof ae.position=="string"&&!ae.position.includes("+"));return e.jsxs(t.TabsTrigger,{draggable:!g,onDragStart:g?void 0:ae=>I(ae,R),onDragOver:g?void 0:M,onDrop:g?void 0:ae=>k(ae,R),className:"",value:F.id,children:[g&&B?e.jsx(t.TooltipProvider,{delayDuration:0,children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:t.getChartIconByType(K,"size-3.5")}),e.jsx("span",{children:B.label||`Tab ${$+1}`})]})}),e.jsx(t.TooltipContent,{side:"bottom",className:"w-64 p-3 text-left",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium",children:B.label}),B.description&&e.jsx("p",{className:"whitespace-normal break-words text-xs text-muted-foreground",children:B.description}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[B.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(B.expectedType)?B.expectedType.join(" / "):B.expectedType}),B.required&&e.jsx("span",{className:"inline-flex items-center rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground",children:"Required"})]})]})})]})}):e.jsxs(e.Fragment,{children:[O(r,F),e.jsx(t.Editable,{enabled:r.activeCardId===F.id,text:F.tabTitle||F.title,onSave:ae=>{d({...i,tabTitle:ae}),l({...i,tabTitle:ae})},children:F.tabTitle||F.title},F.id)]}),r.activeCardId===F.id&&!Y&&e.jsx(t.CopyPlus,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:ae=>{ae.stopPropagation(),A()}}),r.activeCardId===F.id&&(T&&(a==null?void 0:a.id)===F.id?r.cards.length>1:D)&&e.jsx(t.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>j(F.id)})]},F.id)}),e.jsx(t.IconButton,{tooltip:"Add Card",className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",onClick:()=>f(i),disabled:!z,children:e.jsx(t.Plus,{className:"h-4 w-4"})}),g&&e.jsxs(t.Toggle,{pressed:s,onPressedChange:n,size:"sm",className:"ml-2 h-8 gap-1 px-2 data-[state=on]:bg-background data-[state=on]:text-foreground","aria-label":"Toggle preview",children:[s?e.jsx(t.EyeOff,{className:"h-4 w-4"}):e.jsx(t.Eye,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Preview"})]})]})})}function ls(){var fe,Ne,ve,Te,Le;const s=t.useEditorStore(te=>te.frame),n=t.useEditorStore(te=>te.card),[a,r]=N.useState(!1),i=N.useMemo(()=>t.findCustomVisualConfigCard(s,n),[s,n]),c=t.useEditorStore(te=>te.isSqlRunning);t.useEditorStore(te=>te.isDevMode);const{setFrame:o,setActiveTabCardId:d,setCard:l,setRunSql:m,mergeDraftsIntoCard:p,clearModeDrafts:x,initializeModeDrafts:u}=t.useEditorActions(),[h,g]=N.useState({}),[b,v]=N.useState(()=>new Set),{theme:w}=t.useTheme(),E=t.useDashboardStore(te=>te.themeStyle),{authToken:z}=t.useSemaphorContext(),D=t.getTokenParams(z==null?void 0:z.accessToken),T={mode:w||"system",colors:((Ne=(fe=E==null?void 0:E.chart)==null?void 0:fe.dataset)==null?void 0:Ne.backgroundColor)||[]},{getCard:I,manifest:M,isLoading:k}=t.useCustomVisual(((ve=i==null?void 0:i.customCardPreferences)==null?void 0:ve.url)||""),j=(Te=i==null?void 0:i.customCardPreferences)==null?void 0:Te.componentName,S=j?I(j):null,A=(Le=M==null?void 0:M.visuals)==null?void 0:Le.find(te=>te.name===j),f=t.resolveMultiInputType(i,A),O=a&&f==="multiple"&&!!i,P=N.useMemo(()=>t.getCustomVisualInputCards({frame:s,configCard:i,isMultiInputVisual:!0}).map(je=>(je==null?void 0:je.id)===n.id?n:je),[s,i,n]),y=N.useMemo(()=>t.buildSlotOrderedCards(P),[P]),L=N.useMemo(()=>{const te=P.findIndex(je=>(je==null?void 0:je.id)===n.id);return te<0?-1:t.getSlotIndexForCard(n,te)},[P,n]),C=N.useMemo(()=>!i||f!=="multiple"||L<0?n.type:t.getEffectiveCardTypeForSlot(n,L,A==null?void 0:A.slots)??n.type,[i,f,L,n,A==null?void 0:A.slots]),V=N.useMemo(()=>O?{...n,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:C!==n.type?{...n,type:C}:n,[n,C,O]),{data:F,isLoading:R,isFetching:$,isError:B}=t.useDashboardCardQuery(V),K=N.useCallback((te,je)=>{const me=t.normalizeMultiInputPayload(je);g(Ee=>({...Ee,[te]:me}))},[]),Y=N.useCallback((te,je)=>{v(me=>{const Ee=new Set(me);return je?Ee.add(te):Ee.delete(te),Ee})},[]),H=b.size>0,Z=t.useInteractionStore(te=>te.interactionStates),ae=t.useDashboardStore(te=>{var je;return(je=te.dashboard)==null?void 0:je.id}),ee=t.useDashboardStore(te=>te.dashboard.filters),de=t.useDashboardStore(te=>te.filterValues),ce=t.useDashboardStore(te=>te.selectedSheetId),W=t.useEditorStore(te=>te.inlineFilterValuesMap[(i==null?void 0:i.id)||""]),pe=t.useEditorStore(te=>te.actions.setCardInlineFilterValue),X=t.useEditorStore(te=>te.actions.removeCardInlineFilterValue),we=N.useMemo(()=>i?t.buildInlineFilterNodes({card:i,sheetId:ce||"",inlineFilterValues:W,setInlineFilterValue:te=>pe(i.id,te),removeInlineFilterValue:te=>X(i.id,te)}):[],[i,ce,W,pe,X]),{cardFilters:G,cardFilterValues:ne}=N.useMemo(()=>i?t.calculateContextAwareFilters({card:i,interactionStates:Z,currentDashboardId:ae,filters:ee,filterValues:de,selectedSheetId:ce}):{cardFilters:[],cardFilterValues:[]},[i,Z,ae,ee,de,ce]);function ye(te){const je=s.cards.find(me=>me.id===te);je&&(p(),se(te),d(te),x(),u(je))}function se(te){const je=t.useEditorStore.getState().card,me=t.useEditorStore.getState().frame,Ee={...me,cards:me.cards.map(Re=>Re.id===je.id?je:Re),activeCardId:te};o(Ee);const he=Ee.cards.find(Re=>Re.id===te);he.sql&&m(!0),l(he)}function be(){if(k)return e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading manifest"})});if(!S)return e.jsx("div",{className:"flex h-full items-center justify-center text-sm text-muted-foreground",children:"Select a component to preview the multi-input visual."});const je=y.map((me,Ee)=>t.getEffectiveCardTypeForSlot(me,Ee,A==null?void 0:A.slots));return e.jsxs("div",{className:"relative flex h-full flex-col pl-2 pr-4",children:[P.map((me,Ee)=>{if(!me)return null;const he=t.getSlotIndexForCard(me,Ee),Re=t.getEffectiveCardTypeForSlot(me,he,A==null?void 0:A.slots);return e.jsx(t.MultiInputEmptyRenderer,{onLoadingStatus:Y,onDataChange:K,card:me,effectiveCardType:Re},`${me.id}-${he}`)}),H&&e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/50",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading preview"})}),e.jsx("div",{className:t.cn("flex h-full min-h-0 flex-1 flex-col gap-2",H&&"opacity-50"),children:e.jsx(N.Suspense,{fallback:e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(t.LoadingDots,{size:"md",color:"muted"})}),children:e.jsx(S,{editing:!0,...t.buildMultiInputCustomVisualProps({configCard:i,slotOrderedCards:y,slotTypes:je,multiInputData:h,params:D,theme:T,filters:G,filterValues:[...ne||[],...W||[]],inlineFilters:we})})})})]})}function ge(){var te;return O?be():n.type==="kpi"?R||$?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"w-1/2 space-y-3",children:[e.jsx(ur,{visible:!0}),e.jsx("div",{className:"rounded-md border border-border",children:e.jsx(t.KPICard,{card:n,data:F==null?void 0:F.records,isPending:R||$,isError:B,comparisonMetadata:(te=F==null?void 0:F.metadata)==null?void 0:te.comparisonMetadata})}),t.isCardSummaryVisibleOnCard(n)&&e.jsx(t.CardSummary,{card:n,mode:"editor"})]})}):n.type==="text"?R||$?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(t.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(t.TextCard,{isLoading:c,card:n,data:F==null?void 0:F.records})})})}):e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackVisual,children:e.jsx(Fa,{className:"grow border-none shadow-none"})})}return e.jsxs(t.Tabs,{onValueChange:ye,value:s.activeCardId,className:"flex grow flex-col gap-2",children:[O?e.jsx("div",{className:"mt-0 grow",children:ge()}):s.cards.map(te=>e.jsx(t.TabsContent,{className:"mt-0 grow focus-visible:ring-0 focus-visible:ring-offset-0",value:te.id,children:ge()},te.id)),e.jsx(mr,{isPreviewMode:O,onPreviewToggle:r,configCard:i})]})}function ua({children:s,visualAsideControl:n}){var $;const a=t.useEditorStore(B=>B.frame),r=t.useEditorStore(B=>B.card),i=r.type==="table"||r.type==="detailTable",c=t.useEditorStore(B=>B.isDevMode),o=t.useEditorStore(B=>B.isShowingVisual),d=t.useEditorStore(B=>B.actions.setIsShowingVisual),l=t.useDashboardStore(B=>B.isVisualEditing),{isConsoleMode:m}=t.useDashboardPreferences(),p=t.useEditorStore(B=>B.pythonStdOut),x=t.useEditorStore(B=>B.actions.setRunSql),u=Me.useEffectiveEditorCardType(),{setFrame:h,setCard:g,setActiveTabCardId:b,setCardPreferences:v,mergeDraftsIntoCard:w,clearModeDrafts:E,initializeModeDrafts:z}=t.useEditorActions(),D=N.useMemo(()=>u!==r.type?{...r,type:u}:r,[r,u]),{data:T,isLoading:I,isFetching:M,errorMessage:k,errorSql:j,refetch:S,pagination:A}=t.useDashboardCardQuery(D),{handleDebugWithAssistant:f}=Oa(k,j),O=N.useMemo(()=>(T==null?void 0:T.records)||[],[T==null?void 0:T.records]),[P,y]=N.useState(!1);N.useEffect(()=>{M||y(!1)},[M]),N.useEffect(()=>{i&&!o&&d(!0)},[i,o,d]);function L(B,K){var Z,ae;const Y={...r,paginationConfig:{page:B+1,pageSize:K}};g(Y);const H={...a,cards:a.cards.map(ee=>ee.id===r.id?Y:ee)};h(H),r.sql&&((ae=(Z=r.preferences)==null?void 0:Z.tablePrefs)!=null&&ae.enableDevModePagination)&&x(!0)}function C(B){var Z,ae,ee,de,ce;const K=t.sortStateToSortByColumns(B,(Z=r.config)==null?void 0:Z.metricColumns,(ae=r.config)==null?void 0:ae.groupByColumns,(ee=r.config)==null?void 0:ee.detailColumns),Y={...r,config:{...r.config||{},sortByColumns:K}};g(Y);const H={...a,cards:a.cards.map(W=>W.id===r.id?Y:W)};h(H),r.sql&&((ce=(de=r.preferences)==null?void 0:de.tablePrefs)!=null&&ce.enableDevModePagination)&&x(!0)}function V(){var K;const B=JSON.stringify(T==null?void 0:T.records,null,2);typeof navigator>"u"||!((K=navigator.clipboard)!=null&&K.writeText)||navigator.clipboard.writeText(B).catch(Y=>{console.error("Failed to copy JSON",Y)})}function F(){const B=JSON.stringify(T==null?void 0:T.records,null,2),K=new Blob([B],{type:"application/json"}),Y=URL.createObjectURL(K),H=document.createElement("a");H.href=Y,H.download=`${r.title}.json`,H.click()}function R(){const K=[Object.keys(T==null?void 0:T.records.reduce((ae,ee)=>({...ae,...ee}),{})).join(","),...((T==null?void 0:T.records)||[]).map(ae=>Object.values(ae).join(","))].join(`
192
- `),Y=new Blob([K],{type:"text/csv"}),H=URL.createObjectURL(Y),Z=document.createElement("a");Z.href=H,Z.download=`${r.title}.csv`,Z.click()}return r?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 pl-2 pr-6",children:[o&&e.jsx("div",{className:"flex grow items-center",children:e.jsxs("div",{className:"flex items-center gap-3",children:[(n==null?void 0:n.show)&&e.jsx(t.IconButton,{tooltip:n.isOpen?"Hide Visual Aside":"Show Visual Aside",className:"h-9 w-9 px-0",buttonProps:{variant:"outline"},onClick:n.onToggle,children:n.isOpen?e.jsx(t.ChevronLeft,{className:"size-4"}):e.jsx(t.ChevronRight,{className:"size-4"})}),e.jsx("div",{className:"w-[200px]",children:e.jsx(ds,{variant:c?"secondary":"ghost"})})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[s,e.jsx(t.IconButton,{tooltip:"Refresh",disabled:I||M,onClick:()=>{y(!0),S()},children:e.jsx(t.RefreshCcw,{className:t.cn("h-4 w-4",{"animate-spin":P})})}),e.jsx(Ra,{showInlineFilters:!1,showDisplayOptions:!1}),(c||m)&&e.jsxs(e.Fragment,{children:[!i&&e.jsx(pr,{}),i&&e.jsx(hr,{})]}),e.jsxs(t.DropdownMenu,{modal:!1,children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"More Options",className:"h-8 w-8 px-0","aria-label":"More options",children:e.jsx(t.EllipsisVertical,{className:"size-4"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(t.DropdownMenuLabel,{children:"More Options"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs("div",{className:"px-1 py-1",children:[!["table","detailTable","custom"].includes(r.type)&&l&&e.jsx(rr,{triggerVariant:"menu",className:"w-full"}),e.jsx(ms,{triggerVariant:"menu",className:"w-full"}),e.jsx(us,{triggerVariant:"menu",className:"w-full"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.Button,{variant:"ghost",className:"h-8 w-full justify-start gap-2 px-2 text-sm",onClick:R,children:[e.jsx(t.Download,{className:"h-4 w-4"}),e.jsx("span",{children:"Download CSV"})]}),e.jsxs(t.Button,{variant:"ghost",className:"h-8 w-full justify-start gap-2 px-2 text-sm",onClick:F,children:[e.jsx(fn,{className:"h-4 w-4"}),e.jsx("span",{children:"Download JSON"})]}),e.jsxs(t.Button,{variant:"ghost",className:"h-8 w-full justify-start gap-2 px-2 text-sm",onClick:V,children:[e.jsx(t.Copy,{className:"h-4 w-4"}),e.jsx("span",{children:"Copy JSON"})]})]})]})]})]})]}),o?e.jsx(ls,{}):e.jsxs(t.ResizablePanelGroup,{className:"py-2 pl-2 pr-6",direction:"horizontal",children:[p&&e.jsxs(e.Fragment,{children:[e.jsx(t.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:p&&e.jsx(xr,{})}),e.jsx(t.ResizableHandle,{})]}),e.jsxs(t.ResizablePanel,{id:"2",order:2,minSize:10,className:t.cn("relative flex h-full min-h-0 w-full flex-1 basis-0",{"py-2 pl-2 pr-6":p}),children:[(T==null?void 0:T.records)&&(T==null?void 0:T.records.length)>0&&e.jsx(t.TableVisual,{card:r,data:O,comparisonMetadata:($=T==null?void 0:T.metadata)==null?void 0:$.comparisonMetadata,paginationMetadata:A,onPaginationChange:L,onSortChange:C,isLoading:I||M}),k&&e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(cs,{error:k,errorSql:j||r.sql||r.python,onDebugWithAssistant:f,showFeedbackButton:!1})})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function xr(){const s=t.useEditorStore(a=>a.pythonStdOut);if(!s)return null;const n=s.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(t.ScrollArea,{className:"overflow-y-auto pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:n}}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function hr(){var c,o,d,l,m,p;const s=t.useEditorStore(x=>x.card),n=t.useEditorStore(x=>x.actions.setCard),a=t.useEditorStore(x=>x.actions.setRunSql),r=t.useEditorStore(x=>x.actions.setCardPreferences),i=t.useEditorStore(x=>x.actions.updateCardInFrame);return s.type!=="table"&&s.type!=="detailTable"?null:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Checkbox,{id:"dev-pagination",checked:((o=(c=s.preferences)==null?void 0:c.tablePrefs)==null?void 0:o.enableDevModePagination)??!1,onCheckedChange:x=>{var u;r({...s.preferences,tablePrefs:{...(u=s.preferences)==null?void 0:u.tablePrefs,enableDevModePagination:x}})}}),e.jsx(t.Label,{htmlFor:"dev-pagination",className:"cursor-pointer text-sm",children:"Paginate"}),((l=(d=s.preferences)==null?void 0:d.tablePrefs)==null?void 0:l.enableDevModePagination)&&e.jsxs(t.Select,{value:String(((p=(m=s.preferences)==null?void 0:m.tablePrefs)==null?void 0:p.pageSize)||50),onValueChange:x=>{var g,b,v;const u=Number(x),h={...s,preferences:{...s.preferences,tablePrefs:{...(g=s.preferences)==null?void 0:g.tablePrefs,pageSize:u}},paginationConfig:{page:1,pageSize:u}};n(h),i(h),s.sql&&((v=(b=s.preferences)==null?void 0:b.tablePrefs)!=null&&v.enableDevModePagination)&&a(!0)},children:[e.jsx(t.SelectTrigger,{className:"h-8 w-20",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"10",children:"10"}),e.jsx(t.SelectItem,{value:"25",children:"25"}),e.jsx(t.SelectItem,{value:"50",children:"50"}),e.jsx(t.SelectItem,{value:"100",children:"100"}),e.jsx(t.SelectItem,{value:"500",children:"500"}),e.jsx(t.SelectItem,{value:"1000",children:"1000"})]})]})]})}function pr(){const s=t.useEditorStore(a=>a.isShowingVisual),n=t.useEditorStore(a=>a.actions.setIsShowingVisual);return e.jsxs(t.Toggle,{pressed:!s,onPressedChange:a=>{n(!a)},variant:"default",size:"sm",className:"h-8 gap-2 border border-transparent text-foreground/80 hover:bg-accent hover:text-accent-foreground data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",children:[e.jsx(t.Table2,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:"Results"})]})}function Be({value:s,onCommit:n,type:a="text",placeholder:r,className:i}){const[c,o]=N.useState(s),d=N.useRef(!1);N.useEffect(()=>{o(s)},[s]);const l=()=>{if(d.current){d.current=!1;return}c!==s&&n(c)},m=p=>{if(p.key==="Enter"){p.currentTarget.blur();return}p.key==="Escape"&&(d.current=!0,o(s),p.currentTarget.blur())};return e.jsx(t.Input,{type:a,placeholder:r,value:c,onChange:p=>o(p.target.value),onBlur:l,onKeyDown:m,className:i})}function Xe({defaultValue:s,label:n,options:a,value:r,onValueChange:i,className:c,icon:o,showPlaceholderLabel:d=!0}){return e.jsxs(t.Select,{defaultValue:s,value:r,onValueChange:i,children:[e.jsx(t.SelectTrigger,{className:t.cn("w-full focus:ring-0 focus:ring-offset-0",c),children:e.jsxs("div",{className:"flex items-center gap-2",children:[o&&e.jsx("span",{children:o}),d&&e.jsx(t.SelectValue,{placeholder:n})]})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:n}),a.map(l=>e.jsx(t.SelectItem,{value:l.value,children:l.label},l.value))]})})]})}function fr(s,n){return t.getSlotDefinitionForIndex(s,n)||null}function St(s){if(typeof s=="number")return`Tab ${s+1}`;const n=s.match(/^(\d+)-(\d+)$/);if(n){const[,r,i]=n;return`Tabs ${Number(r)+1}-${Number(i)+1}`}const a=s.match(/^(\d+)\+$/);return a?`Tabs ${Number(a[1])+1}+`:`Tab ${s}`}function gr(s){return s?Array.isArray(s)?s:[s]:[]}function Xt(s){var r,i;if(!s)return!1;if(s.type==="text")return!!((r=s.description)!=null&&r.trim());const n=!!((i=s.sql)!=null&&i.trim()),a=t.hasValidCardConfig(s.config);return n||a}function jr({slots:s,cards:n,minInputs:a}){const r=[],i=n.filter(Boolean).length;return a&&i<a&&r.push({type:"too-few-inputs",message:`This visual requires at least ${a} tab${a===1?"":"s"}.`}),!s||s.length===0||(s.forEach(c=>{if(!c.required)return;if(typeof c.position=="number"){const l=n[c.position];Xt(l)||r.push({type:"missing-required",message:`${St(c.position)} ("${c.label}") is required but has no data configured.`});return}const o=c.position.match(/^(\d+)-(\d+)$/);if(o){const[,l,m]=o.map(Number);for(let p=l;p<=m;p+=1){const x=n[p];if(!Xt(x)){r.push({type:"missing-required",message:`${St(p)} ("${c.label}") is required but has no data configured.`});break}}return}const d=c.position.match(/^(\d+)\+$/);if(d){const l=Number(d[1]);if(n.length<=l){r.push({type:"missing-required",message:`${St(l)} ("${c.label}") is required but has no data configured.`});return}for(let m=l;m<n.length;m+=1){const p=n[m];if(!Xt(p)){r.push({type:"missing-required",message:`${St(m)} ("${c.label}") is required but has no data configured.`});break}}}}),n.forEach((c,o)=>{if(!c)return;const d=fr(s,o);if(!d||!d.expectedType)return;const l=gr(d.expectedType);l.length!==0&&(l.includes(c.type)||r.push({type:"wrong-type",message:`${St(o)} ("${d.label}") expects ${l.join(", ")}, but is configured as ${c.type}.`}))})),r}const br={table:({children:s})=>e.jsx("table",{className:"my-3 w-full border-collapse overflow-hidden rounded-md border border-border text-sm",children:s}),thead:({children:s})=>e.jsx("thead",{className:"bg-muted",children:s}),th:({children:s})=>e.jsx("th",{className:"border border-border px-3 py-2 text-left font-medium",children:s}),td:({children:s})=>e.jsx("td",{className:"border border-border px-3 py-2",children:s}),code:({children:s,className:n})=>(n==null?void 0:n.includes("language-"))?e.jsx("pre",{className:"my-3 overflow-x-auto rounded-md bg-muted p-3 text-xs",children:e.jsx("code",{children:s})}):e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-xs",children:s}),pre:({children:s})=>e.jsx(e.Fragment,{children:s})};function Va(){var f,O,P;const s=t.useEditorStore(y=>y.card.customCardPreferences),{data:n}=t.usePluginQuery(),a=(n==null?void 0:n.plugins)||[],r=t.useEditorStore(y=>y.card),i=t.useEditorStore(y=>y.frame),{setCustomCardPreferences:c}=t.useEditorActions(),o=N.useMemo(()=>t.findCustomVisualConfigCard(i,r),[i,r]),d=o==null?void 0:o.customCardPreferences,{components:l,manifest:m}=t.useCustomVisual((d==null?void 0:d.url)||(s==null?void 0:s.url)||""),p=(f=m==null?void 0:m.visuals)==null?void 0:f.find(y=>y.name===((d==null?void 0:d.componentName)||(s==null?void 0:s.componentName))),u=t.resolveMultiInputType(o||r,p)==="multiple",h=!!o&&o.id===r.id,g=(p==null?void 0:p.minInputs)??((O=o==null?void 0:o.customCardPreferences)==null?void 0:O.minInputs),b=(p==null?void 0:p.maxInputs)??((P=o==null?void 0:o.customCardPreferences)==null?void 0:P.maxInputs),v=N.useMemo(()=>t.getCustomVisualInputCards({frame:i,configCard:o||r,isMultiInputVisual:u}),[i,o,r,u]),w=N.useMemo(()=>t.buildSlotOrderedCards(v),[v]),E=N.useMemo(()=>w.map((y,L)=>{if(!y)return null;const C=t.getSlotIndexForCard(y,L),V=t.getEffectiveCardTypeForSlot(y,C,p==null?void 0:p.slots);return{...y,type:V??y.type}}),[w,p==null?void 0:p.slots]),z=N.useMemo(()=>jr({slots:p==null?void 0:p.slots,cards:E,minInputs:g}),[p==null?void 0:p.slots,E,g]),D=N.useMemo(()=>{const y=v.findIndex(L=>(L==null?void 0:L.id)===r.id);return y<0?-1:t.getSlotIndexForCard(r,y)},[v,r]);function T(y){if(typeof y=="number")return`Tab ${y+1}`;const L=y.match(/^(\d+)-(\d+)$/);if(L){const[,V,F]=L;return`Tabs ${Number(V)+1}-${Number(F)+1}`}const C=y.match(/^(\d+)\+$/);return C?`Tabs ${Number(C[1])+1}+`:`Tab ${y}`}function I(y){return y?(Array.isArray(y)?y:[y]).join(", "):null}function M(y,L,C=[],V="",F,R,$){const B=k({key:L,defaultValue:V,settingsValue:R,sourceCard:$});return y==="input"?e.jsx(Be,{className:`h-8 w-full ${t.removeRing}`,value:String(B??""),onCommit:K=>{j({key:L,value:K,settingsField:F,settingsValue:R,sourceCard:$})}},L):y==="select"?e.jsx(Xe,{className:"h-8 w-full",label:"",options:C,value:String(B!==void 0?B:V??""),onValueChange:K=>{j({key:L,value:K,settingsField:F,settingsValue:R,sourceCard:$})}}):null}function k({key:y,defaultValue:L,settingsValue:C,sourceCard:V}){const F=C==null?void 0:C[y];return F!==void 0?F:y==="title"&&(V==null?void 0:V.title)!==void 0?V.title:y==="description"&&(V==null?void 0:V.description)!==void 0?V.description:L}function j({key:y,value:L,settingsField:C,settingsValue:V,sourceCard:F}){const R={...V||{}},$=y==="title"&&(F==null?void 0:F.title)!==void 0,B=y==="description"&&(F==null?void 0:F.description)!==void 0;$&&L===String((F==null?void 0:F.title)??"")||B&&L===String((F==null?void 0:F.description)??"")?delete R[y]:R[y]=L,c({...s||{},[C]:R})}function S({settingsSchema:y,settingsField:L,settingsValue:C,sourceCard:V,headerLabel:F}){const R=Object.entries(y||{});return e.jsxs("div",{className:"space-y-3",children:[F&&e.jsx(t.Label,{children:F}),R.map(([$,B])=>{var K;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{children:B.title}),((K=B.docs)==null?void 0:K.description)&&e.jsx(t.TooltipProvider,{delayDuration:0,children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{className:"text-xs",children:B.docs.description})})]})})]}),M(B.ui,$,B.options,B.defaultValue,L,C,V)]},$)})]})}function A(){return e.jsxs(e.Fragment,{children:[u&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Slot Guide"}),e.jsx("div",{className:"space-y-3 rounded-md border border-border bg-muted/40 px-3 py-2 text-xs",children:p!=null&&p.slots&&p.slots.length>0?e.jsx("div",{className:"space-y-3",children:p.slots.map((y,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:T(y.position)}),e.jsx("span",{className:"text-muted-foreground",children:"•"}),e.jsx("span",{className:"font-medium",children:y.label})]}),y.description&&e.jsx("p",{className:"text-muted-foreground",children:y.description}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-muted-foreground",children:[I(y.expectedType)&&e.jsxs("span",{children:["Expected: ",I(y.expectedType)]}),y.required&&e.jsx("span",{children:"Required"})]})]},`${y.label}-${L}`))}):e.jsxs("div",{className:"space-y-1 text-muted-foreground",children:[e.jsx("p",{children:"This visual renders all tabs in a flexible layout. Add as many tabs as needed."}),(g||b)&&e.jsxs("p",{children:[g?`Min ${g} tabs`:"",g&&b?" • ":"",b?`Max ${b} tabs`:""]})]})})]}),u&&z.length>0&&e.jsx(t.Alert,{className:"mt-3 border-yellow-500/40 bg-yellow-500/10 text-yellow-900 dark:text-yellow-100",children:e.jsx(t.AlertDescription,{children:e.jsx("ul",{className:"list-disc space-y-1 pl-4 text-xs",children:z.map((y,L)=>e.jsx("li",{children:y.message},`${y.type}-${L}`))})})}),p&&!u&&p.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:S({settingsSchema:p.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:r})})}),p&&u&&(p.settings||p.slotSettings)&&e.jsxs("div",{className:"mt-4 space-y-4",children:[h&&p.settings&&e.jsx("div",{className:"px-2",children:S({settingsSchema:p.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:o||r,headerLabel:"Global Settings"})}),p.slotSettings&&e.jsx("div",{className:"px-2",children:S({settingsSchema:p.slotSettings,settingsField:"slotSettings",settingsValue:s==null?void 0:s.slotSettings,sourceCard:r,headerLabel:(()=>{const y=r.tabTitle||r.title,L=D>=0?D:0,C=h?"Slot 0":`Slot ${L}`;return y?`${C}: ${y} Settings`:`${C} Settings`})()})})]})]})}return e.jsxs(t.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"",children:[e.jsxs(t.AccordionItem,{value:"plugin-settings",children:[e.jsx(t.AccordionTrigger,{children:"Plugin"}),e.jsx(t.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[(!u||h)&&e.jsx(Xe,{icon:e.jsx(wa,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:a,value:(d==null?void 0:d.url)||"",onValueChange:y=>c({...s||{url:"",componentName:""},url:y})}),u&&!h&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Switch to the config tab to change the plugin or component."})]})}),((s==null?void 0:s.type)==="component"||(s==null?void 0:s.type)===void 0)&&s&&(!u||h)&&e.jsx(e.Fragment,{children:l&&e.jsx(Xe,{icon:e.jsx(pn,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(l==null?void 0:l.map(y=>({value:y.name,label:y.name})))||[],value:s.componentName||"",onValueChange:y=>{var V;const L=(V=m==null?void 0:m.visuals)==null?void 0:V.find(F=>F.name===y),C=l==null?void 0:l.find(F=>F.name===y);c({...s,componentName:y,visualType:(L==null?void 0:L.visualType)||(C==null?void 0:C.type)||"single",minInputs:L==null?void 0:L.minInputs,maxInputs:L==null?void 0:L.maxInputs,pluginChartType:L==null?void 0:L.chartType})}})})]})})]}),((d==null?void 0:d.componentName)||(s==null?void 0:s.componentName))&&e.jsxs(t.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(t.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:(p==null?void 0:p.name)||"Settings"}),(p==null?void 0:p.docs)&&e.jsxs(t.HoverCard,{openDelay:0,closeDelay:100,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,onClick:y=>y.stopPropagation(),children:e.jsx(t.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground transition-colors hover:text-foreground"})}),e.jsx(t.HoverCardContent,{side:"right",align:"start",className:"max-h-[40vh] w-[500px] overflow-y-auto text-left",children:e.jsxs("div",{className:"space-y-4 text-left",children:[p.docs.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:p.docs.description}),p.docs.dataSchema&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Data Schema"}),e.jsx("div",{className:"prose prose-sm dark:prose-invert prose-pre:bg-muted prose-pre:text-xs max-w-none",children:e.jsx(t.Markdown,{remarkPlugins:[t.remarkGfm],components:br,children:p.docs.dataSchema})})]}),(()=>{var L;const y=(L=p.docs)==null?void 0:L.useCases;return!y||y.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:y.map((C,V)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1 text-primary",children:"•"}),e.jsx("span",{children:C})]},V))})]})})()]})})]})]})}),e.jsx(t.AccordionContent,{children:A()})]})]})}function vr({colorRanges:s,setColorRanges:n}){const a={start:-1/0,end:100,color:""};function r(o,d,l){const m=[...s];m[o]={...m[o],[d]:l},n(m)}function i(o){const d=[...s];d.splice(o,1),n(d)}function c(){n([...s,a])}return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{children:"Color Range"}),e.jsx(t.Button,{onClick:c,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(t.Plus,{className:"size-3"})})]}),s.map((o,d)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(t.Input,{onChange:l=>r(d,"start",l.target.value),value:o.start,className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(t.Input,{value:o.end,onChange:l=>r(d,"end",l.target.value),className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx(t.Input,{onChange:l=>r(d,"color",l.target.value),value:o.color,className:t.cn(`h-7 min-w-14 p-0 ${t.removeRing}`),type:"color",list:"presetColors"}),e.jsxs("datalist",{id:"presetColors",children:[e.jsx("option",{children:t.colors.green[600]}),e.jsx("option",{children:t.colors.red[500]}),e.jsx("option",{children:t.colors.yellow[400]}),e.jsx("option",{children:t.colors.orange[500]})]}),e.jsx(t.Button,{onClick:()=>i(d),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(t.X,{className:"size-3"})})]},d))]})}function yr(){var p,x,u,h,g;const s=t.useEditorStore(b=>b.card.preferences),n=t.useEditorStore(b=>b.actions.setCardPreferences),a=t.useEditorStore(b=>b.card),r=t.hasValidCardConfig(a.config),i=t.useEditorStore(b=>b.actions.setNumberFormat);t.useEditorStore(b=>{var v,w;return(w=(v=b.card.preferences)==null?void 0:v.formatNumber)==null?void 0:w.decimalPlaces});const c=t.useEditorStore(b=>{var v,w;return(w=(v=b.card.preferences)==null?void 0:v.formatNumber)==null?void 0:w.locale}),o=t.useEditorStore(b=>{var v,w;return(w=(v=b.card.preferences)==null?void 0:v.formatNumber)==null?void 0:w.currency});t.useEditorStore(b=>b.actions.setFilterOnClickField);const d=t.useEditorStore(b=>{var v,w;return(w=(v=b.card.preferences)==null?void 0:v.formatNumber)==null?void 0:w.colorRanges})||[],l=t.useEditorStore(b=>b.actions.setColorRanges),m=[...new Set(t.LOCALE_CURRENCY_PAIRS.map(b=>b.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(t.Checkbox,{checked:!!((p=s==null?void 0:s.formatNumber)!=null&&p.enabled),onCheckedChange:b=>{n({...s,formatNumber:{...s==null?void 0:s.formatNumber,enabled:b}})}}),e.jsx(t.Label,{children:"Format Number"})]}),(((x=s==null?void 0:s.formatNumber)==null?void 0:x.enabled)===!0||r)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Locale"}),e.jsxs(t.Select,{value:c||"none",onValueChange:b=>{var v,w,E;return i(((v=s==null?void 0:s.formatNumber)==null?void 0:v.decimalPlaces)||0,((w=s==null?void 0:s.formatNumber)==null?void 0:w.currency)||"",b,((E=s==null?void 0:s.formatNumber)==null?void 0:E.suffix)||"")},children:[e.jsx(t.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Format"}),e.jsx(t.SelectItem,{value:"none",children:"Auto"},"none"),t.LOCALE_CURRENCY_PAIRS.map(b=>e.jsx(t.SelectItem,{value:b.locale,children:b.locale},b.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Currency"}),e.jsxs(t.Select,{value:o||"none",onValueChange:b=>{var v,w,E;console.log("currency",b),i(((v=s==null?void 0:s.formatNumber)==null?void 0:v.decimalPlaces)||0,b==="none"?"":b,((w=s==null?void 0:s.formatNumber)==null?void 0:w.locale)||"",((E=s==null?void 0:s.formatNumber)==null?void 0:E.suffix)||"")},children:[e.jsx(t.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Currency"}),e.jsx(t.SelectItem,{value:"none",children:"None"},"none"),m.map(b=>e.jsx(t.SelectItem,{value:b,children:b},b))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Decimals"}),e.jsxs(t.Select,{value:((h=(u=s==null?void 0:s.formatNumber)==null?void 0:u.decimalPlaces)==null?void 0:h.toString())||"0",onValueChange:b=>{var v,w,E;return i(Number(b),((v=s==null?void 0:s.formatNumber)==null?void 0:v.currency)||"",((w=s==null?void 0:s.formatNumber)==null?void 0:w.locale)||"",((E=s==null?void 0:s.formatNumber)==null?void 0:E.suffix)||"")},children:[e.jsx(t.SelectTrigger,{className:"col-span-3 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:["0","1","2","3","4"].map(b=>e.jsx(t.SelectItem,{value:b,children:b},b))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Suffix"}),e.jsx(t.Input,{value:((g=s==null?void 0:s.formatNumber)==null?void 0:g.suffix)||"",className:"h-8 font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"K, M, B, %",onChange:b=>{var v,w,E;return i(((v=s==null?void 0:s.formatNumber)==null?void 0:v.decimalPlaces)||0,((w=s==null?void 0:s.formatNumber)==null?void 0:w.currency)||"",((E=s==null?void 0:s.formatNumber)==null?void 0:E.locale)||"",b.target.value)}})]})]})]})}),e.jsx(t.Separator,{className:"my-3"}),e.jsx(vr,{colorRanges:d,setColorRanges:l})]})]})}const Nr={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 Pa(s){return Nr[s]}function Cr({chartType:s,showDocsLink:n=!0}){const a=Pa(s);return a?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Query Format"}),e.jsx("code",{className:"block rounded-md bg-muted/50 px-3 py-2 font-mono text-xs text-foreground",children:a.query})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Fields"}),e.jsx("div",{className:"rounded-md border",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/50",children:[e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Field"}),e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Type"}),e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Description"})]})}),e.jsx("tbody",{children:a.fields.map((r,i)=>e.jsxs("tr",{className:i<a.fields.length-1?"border-b":"",children:[e.jsxs("td",{className:"px-2.5 py-1.5 font-medium text-foreground",children:[r.name,r.optional&&e.jsx("span",{className:"ml-1 text-muted-foreground",children:"?"})]}),e.jsx("td",{className:"px-2.5 py-1.5 font-mono text-muted-foreground",children:r.type}),e.jsx("td",{className:"px-2.5 py-1.5 text-muted-foreground",children:r.description||"—"})]},r.name))})]})})]}),e.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:a.description}),n&&a.docsUrl&&e.jsxs("a",{href:a.docsUrl,target:"_blank",rel:"noopener noreferrer",onClick:r=>r.stopPropagation(),className:"inline-flex items-center gap-1.5 text-xs font-medium text-primary hover:underline",children:["View documentation",e.jsx(t.ExternalLink,{className:"h-3 w-3"})]})]}):null}function Sr({chartType:s}){return Pa(s)?e.jsxs(t.HoverCard,{openDelay:200,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded bg-muted px-2 py-0.5 font-mono text-[10px] font-semibold uppercase tracking-wider text-muted-foreground transition-colors hover:bg-muted/80 hover:text-foreground",children:"SQL"})}),e.jsx(t.HoverCardContent,{className:"w-80 p-4",side:"left",align:"start",sideOffset:8,children:e.jsx(Cr,{chartType:s})})]}):null}function Bt({chartType:s,suffix:n="Configuration"}){return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-medium",children:n}),e.jsx(Sr,{chartType:s})]})}function wr(){return e.jsxs("div",{className:"space-y-6 px-6 py-4",children:[e.jsx(Bt,{chartType:"kpi"}),e.jsx("section",{children:e.jsx(yr,{})})]})}function ma({children:s,summary:n,open:a,className:r}){return e.jsxs("details",{open:a,className:t.cn("space-y-4 [&_summary>svg]:open:-rotate-180",r),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(t.Label,{children:n}),e.jsx(t.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:s})]})}function Ba(){const[s,n]=N.useState([]),a=t.useEditorStore(m=>m.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:i}=t.useEditorStore(m=>m.actions),c=t.useEditorStore(m=>m.queryResultColumns);t.useEditorStore(m=>{var p;return(p=m.card.preferences)==null?void 0:p.filterOnClickColumnIndex}),N.useEffect(()=>{c&&n(new Array(c.length).fill(!1))},[c]);function o(m,p){var x,u;p?a!=null&&a.onClickFilter&&((x=a==null?void 0:a.onClickFilter)==null?void 0:x.length)>0?i({...a,onClickFilter:[...a.onClickFilter,{columnIndex:m,expression:""}]}):i({...a,onClickFilter:[{columnIndex:m,expression:""}]}):(i({...a,onClickFilter:(u=a==null?void 0:a.onClickFilter)==null?void 0:u.filter(h=>h.columnIndex!==m)}),n(h=>{const g=[...h];return g[m]=!1,g}))}function d(m,p){var u;const x=(u=a==null?void 0:a.onClickFilter)==null?void 0:u.map(h=>h.columnIndex===m?{...h,expression:p.target.value}:h);i({...a,onClickFilter:x})}function l(m){var p,x,u,h;if(s!=null&&s[m]||(x=(p=a==null?void 0:a.onClickFilter)==null?void 0:p.find(g=>g.columnIndex===m))!=null&&x.expression)return e.jsx(t.Input,{value:(h=(u=a==null?void 0:a.onClickFilter)==null?void 0:u.find(g=>g.columnIndex===m))==null?void 0:h.expression,onChange:g=>d(m,g),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsx("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:c==null?void 0:c.map((m,p)=>{var x,u;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(t.Checkbox,{checked:!!((x=a==null?void 0:a.onClickFilter)!=null&&x.find(h=>h.columnIndex===p)),onCheckedChange:h=>o(p,h)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:m}),e.jsx("div",{className:"flex items-center gap-2",children:((u=a==null?void 0:a.onClickFilter)==null?void 0:u.find(h=>h.columnIndex===p))&&e.jsx(t.Pencil,{onClick:()=>{n(h=>{const g=[...h];return g[p]=!h[p],g})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),l(p)]})},m)})})}const Tr=[{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"}],Er=["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"],Ir=Er.map(s=>({label:s,value:s}));function kr(){var l,m,p,x,u,h,g,b,v,w,E,z,D,T,I,M,k,j;const s=t.useEditorStore(S=>S.card),n=(m=(l=s==null?void 0:s.preferences)==null?void 0:l.mapVisualOptions)==null?void 0:m.topoJsonUrl,[a,r]=N.useState(((x=(p=s==null?void 0:s.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:x.customTopoJsonUrl)||""),{setCardPreferences:i}=t.useEditorActions(),{data:c}=t.useTopoJson(s),o=Object.keys((c==null?void 0:c.objects)||{}).map(S=>({label:S,value:S}))||[],d=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(Bt,{chartType:"map"}),e.jsx(ma,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(Xe,{className:"h-9",options:d,onValueChange:S=>{console.log("value",S),i({...s.preferences,mapVisualOptions:{topoJsonUrl:S}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(t.Input,{onChange:S=>{r(S.target.value)},onBlur:()=>{var S;console.log("onBlur",a),i({...s.preferences,mapVisualOptions:{...(S=s.preferences)==null?void 0:S.mapVisualOptions,customTopoJsonUrl:a}})},value:a,className:`h-9 w-full ${t.removeRing}`,placeholder:"Custom URL"}),c&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Map Object"}),e.jsx(Xe,{className:"h-9",options:o,value:((h=(u=s.preferences)==null?void 0:u.mapVisualOptions)==null?void 0:h.objectKey)||"",label:"Map Object",onValueChange:S=>{var A;i({...s.preferences,mapVisualOptions:{...(A=s.preferences)==null?void 0:A.mapVisualOptions,objectKey:S}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Projection"}),e.jsx(Xe,{className:"h-9",options:Tr,value:((b=(g=s.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:b.projection)||"",label:"Projection",onValueChange:S=>{var A;i({...s.preferences,mapVisualOptions:{...(A=s.preferences)==null?void 0:A.mapVisualOptions,projection:S}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Colors"}),e.jsx(Xe,{className:"h-9",options:Ir,value:((w=(v=s.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:w.colorScale)||"",label:"Select Color Scale",onValueChange:S=>{var A;i({...s.preferences,mapVisualOptions:{...(A=s.preferences)==null?void 0:A.mapVisualOptions,colorScale:S}})}})]})]})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(ma,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:.1,value:((z=(E=s.preferences)==null?void 0:E.mapVisualOptions)==null?void 0:z.projectionScale)||1,onChange:S=>{var A;i({...s.preferences,mapVisualOptions:{...(A=s.preferences)==null?void 0:A.mapVisualOptions,projectionScale:Number(S.target.value)}})}}),e.jsx(t.Label,{children:"X"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((I=(T=(D=s.preferences)==null?void 0:D.mapVisualOptions)==null?void 0:T.projectionOffset)==null?void 0:I[0])||0,onChange:S=>{var A,f,O,P;i({...s.preferences,mapVisualOptions:{...(A=s.preferences)==null?void 0:A.mapVisualOptions,projectionOffset:[Number(S.target.value),((P=(O=(f=s.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:O.projectionOffset)==null?void 0:P[1])||0]}})}}),e.jsx(t.Label,{children:"Y"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((j=(k=(M=s.preferences)==null?void 0:M.mapVisualOptions)==null?void 0:k.projectionOffset)==null?void 0:j[1])||0,onChange:S=>{var A,f,O,P;i({...s.preferences,mapVisualOptions:{...(A=s.preferences)==null?void 0:A.mapVisualOptions,projectionOffset:[((P=(O=(f=s.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:O.projectionOffset)==null?void 0:P[0])||0,Number(S.target.value)]}})}})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(Ba,{})]})}function za({color:s,onColorChange:n,onClose:a}){const[r,i]=N.useState(0),[c,o]=N.useState(100),[d,l]=N.useState(50),[m,p]=N.useState(s);N.useEffect(()=>{const v=xa(s);if(v){const w=ha(v.r,v.g,v.b);i(w.h),o(w.s),l(w.l),p(s)}},[s]);const x=v=>{i(v),h(v,c,d)},u=v=>{const w=v.currentTarget.getBoundingClientRect(),E=Math.max(0,Math.min(1,(v.clientX-w.left)/w.width)),z=Math.max(0,Math.min(1,(v.clientY-w.top)/w.height)),D=E*100,T=(1-z)*100;o(D),l(T),h(r,D,T)},h=(v,w,E)=>{const z=Ar(v,w,E),D=Dr(z.r,z.g,z.b);p(D)},g=v=>{if(p(v),/^#[0-9A-Fa-f]{6}$/.test(v)){const w=xa(v);if(w){const E=ha(w.r,w.g,w.b);i(E.h),o(E.s),l(E.l)}}},b=()=>{/^#[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:v=>{v.buttons===1&&u(v)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${c}%`,top:`${100-d}%`,backgroundColor:m}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:v=>x(Number(v.target.value)),className:"w-full h-4 rounded-lg appearance-none cursor-pointer",style:{background:"linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"}})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"HEX"}),e.jsx(t.Input,{value:m,onChange:v=>g(v.target.value),placeholder:"#000000",className:"font-mono"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:s}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:m}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(t.Button,{variant:"outline",onClick:a,children:"Cancel"}),e.jsx(t.Button,{onClick:b,children:"OK"})]})]})}function xa(s){const n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(s);return n?{r:parseInt(n[1],16),g:parseInt(n[2],16),b:parseInt(n[3],16)}:null}function Dr(s,n,a){return"#"+((1<<24)+(s<<16)+(n<<8)+a).toString(16).slice(1)}function ha(s,n,a){s/=255,n/=255,a/=255;const r=Math.max(s,n,a),i=Math.min(s,n,a);let c=0,o=0;const d=(r+i)/2;if(r!==i){const l=r-i;switch(o=d>.5?l/(2-r-i):l/(r+i),r){case s:c=((n-a)/l+(n<a?6:0))/6;break;case n:c=((a-s)/l+2)/6;break;case a:c=((s-n)/l+4)/6;break}}return{h:Math.round(c*360),s:Math.round(o*100),l:Math.round(d*100)}}function Ar(s,n,a){s/=360,n/=100,a/=100;let r,i,c;if(n===0)r=i=c=a;else{const o=(m,p,x)=>(x<0&&(x+=1),x>1&&(x-=1),x<.16666666666666666?m+(p-m)*6*x:x<.5?p:x<.6666666666666666?m+(p-m)*(.6666666666666666-x)*6:m),d=a<.5?a*(1+n):a+n-a*n,l=2*a-d;r=o(l,d,s+1/3),i=o(l,d,s),c=o(l,d,s-1/3)}return{r:Math.round(r*255),g:Math.round(i*255),b:Math.round(c*255)}}const pa=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],Mr=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function Ze({value:s,onChange:n,label:a}){const[r,i]=N.useState(!1),[c,o]=N.useState(!1),d=()=>{const l=pa.find(m=>m.value===s);return l?l.color:s.startsWith("#")?s:pa[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Popover,{open:r,onOpenChange:i,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"size-5 rounded border-2 border-input shadow-sm transition-all hover:scale-110 hover:border-gray-400",style:{backgroundColor:d()},"aria-label":`Change color for ${a}`})}),e.jsx(t.PopoverContent,{align:"start",className:"w-auto p-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"grid grid-cols-3 items-center justify-items-center gap-1",children:Mr.map(l=>e.jsx("button",{className:t.cn("h-5 w-5 rounded border-2 transition-all",d()===l?"border-gray-900":"border-transparent"),style:{backgroundColor:l},onClick:()=>{n(l),i(!1)},children:e.jsx("span",{className:"sr-only",children:l})},l))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{o(!0),i(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a})]}),c&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>o(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(za,{color:d(),onColorChange:l=>{n(l),o(!1)},onClose:()=>o(!1)})})]})]})}function Vt(s){return s==="currency"?2:s==="percent"?1:s==="scientific"?2:0}function fa(s,n){if(!n||n==="auto")return{type:"auto"};const a={...s,type:n,multiplyBy:n==="percent"?s.multiplyBy:void 0,percentValueMode:n==="percent"?s.percentValueMode:void 0};return n&&["number","currency","percent","scientific"].includes(n)&&s.decimalPlaces===void 0&&s.minimumFractionDigits===void 0&&s.maximumFractionDigits===void 0?os(a,Vt(n)):a}function os(s,n){return{...s,decimalPlaces:n,minimumFractionDigits:n,maximumFractionDigits:n}}const Lr=["auto","number","currency","percent","scientific","date"],Or=[{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"}],Fr=[{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"}],Rr=s=>s.charAt(0).toUpperCase()+s.slice(1);function gt({formatOptions:s={},onFormatOptionsChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const i=s.type||"auto",c=i==="auto"?s:fa(s,i),o=h=>{h.stopPropagation()},d=(h,g)=>{n({...c,[h]:g})},[l,m]=N.useState(()=>String(c.decimalPlaces??Vt(i))),[p,x]=N.useState(()=>c.multiplyBy!==void 0?String(c.multiplyBy):""),u=h=>{n(fa(s,h))};return N.useEffect(()=>{m(String(c.decimalPlaces??Vt(i)))},[c.decimalPlaces,i]),N.useEffect(()=>{x(c.multiplyBy!==void 0?String(c.multiplyBy):"")},[c.multiplyBy]),e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[a&&e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(t.Select,{value:i,onValueChange:h=>u(h),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",onClick:o,onPointerDown:o,onKeyDown:o,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Lr.map(h=>e.jsx(t.SelectItem,{value:h,className:"text-xs",children:h==="auto"?"Auto (Default)":Rr(h)},h))})]})]}),i!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent","scientific"].includes(i)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{type:"text",inputMode:"numeric",min:"0",max:"10",placeholder:"0",value:l,onClick:o,onPointerDown:o,onKeyDown:o,onChange:h=>{const g=h.target.value.replace(/[^\d]/g,"");m(g),g!==""&&n(os(c,Math.max(0,Math.min(10,parseInt(g,10)))))},onBlur:()=>{if(l!=="")return;const h=Vt(i);m(String(h)),n(os(c,h))},className:"h-8 text-xs"})})]}),i==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(t.Select,{value:s.currency||"USD",onValueChange:h=>d("currency",h),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:o,onPointerDown:o,onKeyDown:o,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Or.map(h=>e.jsx(t.SelectItem,{value:h.value,className:"text-xs",children:h.label},h.value))})]})]}),["number","currency"].includes(i)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(t.SmallSwitch,{checked:s.useSuffix??!1,onClick:h=>h.stopPropagation(),onCheckedChange:h=>d("useSuffix",h)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(t.Select,{value:s.locale||"en-US",onValueChange:h=>d("locale",h),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:o,onPointerDown:o,onKeyDown:o,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Fr.map(h=>e.jsx(t.SelectItem,{value:h.value,className:"text-xs",children:h.label},h.value))})]})]}),i==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{placeholder:"e.g., $",value:s.prefix||"",onClick:o,onPointerDown:o,onKeyDown:o,onChange:h=>d("prefix",h.target.value),className:"h-8 text-xs"})})]}),i==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{placeholder:"e.g., units",value:s.suffix||"",onClick:o,onPointerDown:o,onKeyDown:o,onChange:h=>d("suffix",h.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(i)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Negative in ()"}),e.jsx(t.SmallSwitch,{checked:s.negativeInParentheses??!1,onClick:h=>h.stopPropagation(),onCheckedChange:h=>d("negativeInParentheses",h)})]}),i==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{type:"text",inputMode:"decimal",placeholder:"100",value:p,onClick:o,onPointerDown:o,onKeyDown:o,onChange:h=>{const g=h.target.value.replace(/[^0-9.]/g,"");x(g),d("multiplyBy",g?parseFloat(g):void 0)},className:"h-8 text-xs"})})]}),i==="date"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Format"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{type:"text",placeholder:"MM/DD/YYYY",value:s.dateFormat||"",onClick:o,onPointerDown:o,onKeyDown:o,onChange:h=>d("dateFormat",h.target.value),className:"h-8 text-xs"})})]})]})]})}function xs({value:s,onChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const i=t.toTFormatOptions(t.fromSemanticFormat(s))||{},c=o=>{n(t.fromTFormatOptions(o))};return e.jsx(gt,{formatOptions:i,onFormatOptionsChange:c,showTitle:a,title:r})}function Vr(){const s=t.useDashboardStore(d=>d.dashboard.filters),n=t.useEditorStore(d=>d.frame),{setFrame:a}=t.useEditorActions(),{columns:r}=t.useColumns(),{assignFilter:i}=t.useAssignFilter();function c(d){const l=i(d,"frame");a({...n,filterId:l})}const o=s==null?void 0:s.find(d=>d.id===n.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Card Filter"}),e.jsx(Pr,{onSelect:c,columns:r}),o&&e.jsx(t.FilterHeader,{filter:o})]})}function Pr({columns:s,onSelect:n}){var o;const[a,r]=ns.useState(!1),[i,c]=ns.useState("");return e.jsxs(t.Popover,{open:a,onOpenChange:r,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between font-normal",children:[i?((o=s.find(d=>d.name===i))==null?void 0:o.label)||i:"Select Column...",e.jsx(t.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No column found."}),e.jsx(t.CommandGroup,{children:s==null?void 0:s.map(d=>e.jsxs(t.CommandItem,{value:d.name,onSelect:l=>{const m=l===i?"":l;c(m),r(!1),m&&n(d)},children:[d.label||d.name,e.jsx(t.CheckIcon,{className:t.cn("ml-auto h-4 w-4",i===d.name?"opacity-100":"opacity-0")})]},d.id))})]})]})})]})}const Br=[{value:"difference",label:"Difference"},{value:"change",label:"Change (%)"},{value:"change_difference",label:"Change + Difference"},{value:"ratio",label:"Ratio"}],zr=[{value:"arrow_badge",label:"Arrow + Badge"},{value:"arrow",label:"Arrow Only"},{value:"badge",label:"Badge Only"},{value:"none",label:"None"}];function qr({cardType:s="table"}){var p,x,u,h,g;const n=t.useEditorStore(b=>b.card),a=t.useEditorStore(b=>{var v;return(v=b.card)==null?void 0:v.preferences}),r=t.useEditorStore(b=>b.actions.setCardPreferences),i=((p=n.config)==null?void 0:p.metricColumns)||[],c=i.some(b=>b.comparisonType&&b.comparisonType!=="none"),o=((x=a==null?void 0:a.tableVisualOptions)==null?void 0:x.metricComparison)||{},d=b=>{r({...a,tableVisualOptions:{...a==null?void 0:a.tableVisualOptions,metricComparison:{...o,...b}}})},l={increase:((u=o.colors)==null?void 0:u.increase)||"green",decrease:((h=o.colors)==null?void 0:h.decrease)||"red",neutral:((g=o.colors)==null?void 0:g.neutral)||"neutral"},m=b=>{r({...a,allowDownload:b})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsxs(t.Accordion,{defaultValue:["item-3"],type:"multiple",children:[c&&e.jsxs(t.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(t.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ea,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison Settings"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated As"}),e.jsxs(t.Select,{value:o.calculatedAs||"change_difference",onValueChange:b=>d({calculatedAs:b}),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Br.map(b=>e.jsx(t.SelectItem,{value:b.value,className:"text-xs",children:b.label},b.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Number Format"}),e.jsx(gt,{formatOptions:o.formatOptions||{},onFormatOptionsChange:b=>d({formatOptions:b}),showTitle:!1})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator Style"}),e.jsxs(t.Select,{value:o.indicatorStyle||"arrow_badge",onValueChange:b=>d({indicatorStyle:b}),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:zr.map(b=>e.jsx(t.SelectItem,{value:b.value,className:"text-xs",children:b.label},b.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Colors"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ze,{value:l.increase,onChange:b=>d({colors:{...l,increase:b}}),label:"Increase"}),e.jsx(Ze,{value:l.decrease,onChange:b=>d({colors:{...l,decrease:b}}),label:"Decrease"}),e.jsx(Ze,{value:l.neutral,onChange:b=>d({colors:{...l,neutral:b}}),label:"No Change"})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Lower is Better"}),e.jsx(t.Checkbox,{checked:o.lowerIsBetter||!1,onCheckedChange:b=>d({lowerIsBetter:!!b})})]})]})]}),i.length>0&&e.jsxs(t.AccordionItem,{value:"metric-formats",className:"border-none",children:[e.jsx(t.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsx("span",{children:"Metric Formats"})}),e.jsx(t.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:i.map(b=>e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 p-3",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:b.label||b.name}),e.jsx(xs,{value:b.format,onChange:v=>{var E;const w=(((E=n.config)==null?void 0:E.metricColumns)||[]).map(z=>z.id===b.id?{...z,format:v}:z);t.useEditorStore.getState().actions.updateCardConfig(n.id,{metricColumns:w})},showTitle:!1})]},b.id))})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Click Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Ba,{}),e.jsx(Vr,{})]})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Checkbox,{onCheckedChange:m,id:"allow-download"}),e.jsx("label",{htmlFor:"allow-download",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Allow Download"})]})]})}function _r(){var r;const s=t.useEditorStore(i=>i.card.preferences),{setCardPreferences:n}=t.useEditorStore(i=>i.actions);function a(i){n({...s,textVisualOptions:{...s==null?void 0:s.textVisualOptions,isDynamicText:i==="dynamic"}})}return e.jsxs(t.RadioGroup,{value:(r=s==null?void 0:s.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:a,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function $r(){return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(Bt,{chartType:"text"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Text Type"}),e.jsx(_r,{})]})]})}const Kr=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function Gr(){var T,I,M,k,j,S,A,f,O,P;const s=t.useEditorStore(y=>y.card),n=t.useEditorStore(y=>{var L;return(L=y.card)==null?void 0:L.preferences}),a=Me.useEffectiveEditorCardType(),{setCardPreferences:r,updateCardInFrame:i}=t.useEditorActions(),c=N.useMemo(()=>a!==s.type?{...s,type:a}:s,[s,a]),{data:o}=t.useDashboardCardQuery(c),[d,l]=N.useState({}),[m,p]=N.useState(null),[x,u]=N.useState(null),h=N.useMemo(()=>{var V,F,R,$,B,K,Y;if(!(o!=null&&o.records)||o.records.length===0)return[];const y=a==="stackedBar"||a==="stackedLine",L=a==="bar"||a==="line"||a==="horizontalBar"||a==="bullet"||a==="combo"||a==="area"||a==="stackedArea",C=((V=s==null?void 0:s.config)==null?void 0:V.pivotByColumns)&&s.config.pivotByColumns.length>0;if((y||L)&&C){if(o.pivotSchema&&Array.isArray(o.pivotSchema)){const H=new Set;return o.pivotSchema.forEach(Z=>{Z.alias&&H.add(Z.alias)}),Array.from(H)}if(o.records.length>0){const H=o.records[0],Z=Object.keys(H),ae=new Set;(F=s==null?void 0:s.config)!=null&&F.groupByColumns&&s.config.groupByColumns.forEach(ce=>{ae.add(ce.label||ce.name),ae.add(ce.alias||ce.name)});const ee=new Set;return(R=s==null?void 0:s.config)!=null&&R.metricColumns&&s.config.metricColumns.forEach(ce=>{const W=ce.alias||ce.name;ee.add(W),ee.add(`${W}_count`),ee.add(`${W}_sum`),ee.add(`${W}_avg`),ee.add(`${W}_min`),ee.add(`${W}_max`);const pe=ce.entityName||ce.qualifiedEntityName;pe&&(ee.add(`${pe}_${W}`),ee.add(`${pe}_${W}_count`))}),Z.filter(ce=>!ae.has(ce)&&!ee.has(ce))}}if((L||y)&&!C&&((B=($=s==null?void 0:s.config)==null?void 0:$.metricColumns)!=null&&B.length))return s.config.metricColumns.map(H=>H.alias||H.label||H.name);if((Y=(K=s==null?void 0:s.config)==null?void 0:K.groupByColumns)!=null&&Y.length){const H=s.config.groupByColumns[0],Z=H.label||H.name,ae=new Set;return o.records.forEach(ee=>{const de=ee[Z];de!=null&&ae.add(String(de))}),Array.from(ae)}return[]},[o,(T=s==null?void 0:s.config)==null?void 0:T.groupByColumns,(I=s==null?void 0:s.config)==null?void 0:I.pivotByColumns,(M=s==null?void 0:s.config)==null?void 0:M.metricColumns,s==null?void 0:s.type]),g=N.useMemo(()=>t.getDefaultChartColors(),[]);N.useEffect(()=>{const y={};h.forEach((L,C)=>{y[L]=t.getColorForValue(L,C,n==null?void 0:n.colorConfig)}),l(y)},[h,n==null?void 0:n.colorConfig,g]);const b=(y,L)=>{const C={...d,[y]:L};l(C);const V={...n||{},colorConfig:{segments:C}};r(V);const F={...s,preferences:V};i(F)},v=(y,L)=>{var B;const C=g[L%g.length],{[y]:V,...F}=((B=n==null?void 0:n.colorConfig)==null?void 0:B.segments)||{},R={...n||{},colorConfig:{segments:F}};r(R);const $={...s,preferences:R};i($),l(K=>({...K,[y]:C}))};if(!h.length||!((s==null?void 0:s.type)==="stackedBar"||(s==null?void 0:s.type)==="stackedLine"?((j=(k=s==null?void 0:s.config)==null?void 0:k.groupByColumns)==null?void 0:j.length)||((A=(S=s==null?void 0:s.config)==null?void 0:S.pivotByColumns)==null?void 0:A.length):(O=(f=s==null?void 0:s.config)==null?void 0:f.groupByColumns)==null?void 0:O.length)||["table","kpi","text","custom","heatmap"].includes(a))return null;const z=()=>{const y={...n||{},colorConfig:{segments:{}}};r(y);const L={...s,preferences:y};i(L);const C={};h.forEach((V,F)=>{C[V]=t.getColorForValue(V,F,void 0)}),l(C)},D=Object.keys(((P=n==null?void 0:n.colorConfig)==null?void 0:P.segments)||{}).length>0;return e.jsxs(t.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Cn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Colors"})]})}),e.jsx(t.AccordionContent,{className:"",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("div",{className:"flex items-center justify-between",children:D&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:z,children:[e.jsx(ta,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:h.map((y,L)=>{const C=t.isDefaultColor(d[y],L),V=!C;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Popover,{open:m===y,onOpenChange:F=>p(F?y:null),children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"h-5 w-5 shrink-0 rounded border border-input shadow-sm transition-colors hover:border-gray-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",style:{backgroundColor:d[y]}})}),e.jsx(t.PopoverContent,{align:"start",className:"w-auto p-3",children:e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Theme Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:g.slice(0,10).map((F,R)=>e.jsxs("button",{className:t.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",d[y]===F?"border-gray-900":"border-transparent"),style:{backgroundColor:F},onClick:()=>{b(y,F),p(null)},children:[R===L%g.length&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-white/90 px-0.5 text-[8px] font-bold text-gray-900 shadow-sm",children:"D"})}),e.jsx("span",{className:"sr-only",children:F})]},`default-${R}`))})]}),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:Kr.map((F,R)=>e.jsx("button",{className:t.cn("h-5 w-5 rounded border transition-all hover:scale-110",d[y]===F?"border-2 border-gray-900":F==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:F},onClick:()=>{b(y,F),p(null)},children:e.jsx("span",{className:"sr-only",children:F})},`preset-${R}`))})]}),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:y,color:d[y]}),p(null)},children:"Custom color"}),!C&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{v(y,L),p(null)},children:[e.jsx(ta,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:y}),V&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},y)})}),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(za,{color:x.color,onColorChange:y=>{b(x.value,y),u(null)},onClose:()=>u(null)})})]})]})})]})}function Je({value:s,onSave:n,placeholder:a="",type:r="text",className:i=""}){const[c,o]=N.useState(s??""),[d,l]=N.useState(!1);N.useEffect(()=>{o(s??"")},[s]);const m=()=>{n(c),l(!1)},p=()=>{o(s??""),l(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${i}`,children:[e.jsx(t.Input$1,{placeholder:a,type:r,value:d?c:s??"",onChange:x=>{o(x.target.value),l(!0)},onFocus:()=>l(!0),onClick:x=>x.stopPropagation(),className:"h-8 text-xs",onPointerDown:x=>x.stopPropagation(),onKeyDown:x=>{x.stopPropagation(),x.key==="Enter"&&d&&c!==s?m():x.key==="Escape"&&p()},"aria-label":a||"Edit field"}),d&&c!==s&&e.jsxs(e.Fragment,{children:[e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:m,children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:p,children:e.jsx(t.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function Zt({axis:s,label:n,type:a,config:r,onChange:i,defaultTitle:c,hidePosition:o}){var g,b,v,w,E,z,D,T,I,M,k,j,S,A;const d=t.normalizeContextFormatMode({formatMode:r==null?void 0:r.formatMode,formatOptions:r==null?void 0:r.formatOptions}),l=(f,O)=>{i({...r??{},[f]:O})},m=(f,O)=>{var C,V,F,R;const P=f==="enabled"&&O===!0,y=(C=r==null?void 0:r.name)==null?void 0:C.text,L=P&&!y&&c;i({...r??{},name:{...r==null?void 0:r.name,enabled:f==="enabled"?O:((V=r==null?void 0:r.name)==null?void 0:V.enabled)??!1,text:f==="text"?O:L?c:y,fontSize:f==="fontSize"?O:(F=r==null?void 0:r.name)==null?void 0:F.fontSize,fontWeight:f==="fontWeight"?O:(R=r==null?void 0:r.name)==null?void 0:R.fontWeight}})},p=(f,O)=>{var P,y;i({...r??{},labels:{enabled:f==="enabled"?O:((P=r==null?void 0:r.labels)==null?void 0:P.enabled)??!0,rotation:f==="rotation"?O:(y=r==null?void 0:r.labels)==null?void 0:y.rotation}})},x=(f,O)=>{i({...r??{},scale:{...r==null?void 0:r.scale,[f]:O===""?"auto":Number(O)}})},u=s==="x"?["auto","top","bottom"]:["auto","left","right"],h=["auto","0","45","90","-45","-90"];return e.jsxs(t.AccordionItem,{value:`${s}-axis`,className:"border-b-0",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx(t.AccordionTrigger,{className:"flex grow items-center justify-between gap-3 py-2 text-sm font-medium hover:no-underline",children:e.jsx("div",{className:"flex grow items-center justify-between gap-2",children:e.jsx("span",{children:n})})}),e.jsx(t.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:f=>l("enabled",f),onClick:f=>f.stopPropagation()})]}),e.jsxs(t.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Checkbox,{id:`${s}-title-enabled`,checked:((g=r==null?void 0:r.name)==null?void 0:g.enabled)??!1,onCheckedChange:f=>m("enabled",f===!0)}),e.jsx(t.Label,{htmlFor:`${s}-title-enabled`,className:"text-xs font-medium cursor-pointer",children:"TITLE"})]}),((b=r==null?void 0:r.name)==null?void 0:b.enabled)&&e.jsxs("div",{className:"space-y-2 pl-6",children:[e.jsx(Je,{placeholder:`${n} title`,value:((v=r==null?void 0:r.name)==null?void 0:v.text)||"",onSave:f=>m("text",f),className:""}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Size"}),e.jsx("div",{className:"w-14",children:e.jsx(Je,{type:"number",placeholder:"12",value:String(((w=r==null?void 0:r.name)==null?void 0:w.fontSize)||12),onSave:f=>m("fontSize",Number(f)||12),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Weight"}),e.jsxs(t.Select,{value:((E=r==null?void 0:r.name)==null?void 0:E.fontWeight)||"normal",onValueChange:f=>m("fontWeight",f),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(t.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]})]})]})]}),!o&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(t.Select,{value:(r==null?void 0:r.position)||"auto",onValueChange:f=>l("position",f),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:u.map(f=>e.jsx(t.SelectItem,{value:f,className:"text-xs",children:f==="auto"?"Auto (Default)":t.titleCase(f)},f))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(t.SmallSwitch,{checked:((z=r==null?void 0:r.labels)==null?void 0:z.enabled)!==!1,onCheckedChange:f=>p("enabled",f)})]}),((D=r==null?void 0:r.labels)==null?void 0:D.enabled)!==!1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Rotation"}),e.jsxs(t.Select,{value:String(((T=r==null?void 0:r.labels)==null?void 0:T.rotation)||"auto"),onValueChange:f=>p("rotation",f==="auto"?"auto":Number(f)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:h.map(f=>e.jsx(t.SelectItem,{value:f,className:"text-xs",children:f==="auto"?"Auto (Default)":`${f}°`},f))})]})]})]}),a==="value"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"FORMAT"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Inherit from the bound metric by default."})]}),e.jsx(t.SmallSwitch,{checked:d==="override",onCheckedChange:f=>i({...r,formatMode:f?"override":"inherit"})})]}),d==="override"&&e.jsx(gt,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:f=>i({...r,formatMode:"override",formatOptions:f}),showTitle:!1})]}),a==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"SCALE"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(Je,{type:"number",placeholder:"auto",value:((I=r==null?void 0:r.scale)==null?void 0:I.min)==="auto"||((M=r==null?void 0:r.scale)==null?void 0:M.min)===void 0?"":String(r.scale.min),onSave:f=>x("min",f),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-8 text-xs text-muted-foreground",children:"Max"}),e.jsx("div",{className:"flex-1",children:e.jsx(Je,{type:"number",placeholder:"auto",value:((k=r==null?void 0:r.scale)==null?void 0:k.max)==="auto"||((j=r==null?void 0:r.scale)==null?void 0:j.max)===void 0?"":String(r.scale.max),onSave:f=>x("max",f),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-8 text-xs text-muted-foreground",children:"Step"}),e.jsx("div",{className:"flex-1",children:e.jsx(Je,{type:"number",placeholder:"auto",value:((S=r==null?void 0:r.scale)==null?void 0:S.stepSize)==="auto"||((A=r==null?void 0:r.scale)==null?void 0:A.stepSize)===void 0?"":String(r.scale.stepSize),onSave:f=>x("stepSize",f),className:""})})]})]})]})]})]})}function es(s,n,a){var c,o,d;if(s==="x"){const l=(o=(c=n==null?void 0:n.config)==null?void 0:c.groupByColumns)==null?void 0:o[0];return(l==null?void 0:l.label)||(l==null?void 0:l.name)||""}const r=((d=n==null?void 0:n.config)==null?void 0:d.metricColumns)||[],i=(a==null?void 0:a.datasetOptions)||[];if(s==="y"){const l=r.filter((m,p)=>{const x=i.find(u=>u.idx===p);return!x||x.yAxisId!=="y2"});return l.length===1&&(l[0].label||l[0].name)||""}if(s==="y2"){const l=r.filter((m,p)=>{const x=i.find(u=>u.idx===p);return(x==null?void 0:x.yAxisId)==="y2"});return l.length===1&&(l[0].label||l[0].name)||""}return""}function Ur(){const s=t.useEditorStore(l=>l.card),n=t.useEditorStore(l=>{var m;return(m=l.card)==null?void 0:m.preferences}),{setCardPreferences:a,updateCardInFrame:r}=t.useEditorActions(),i=Me.useEffectiveEditorCardType();if(!s||["tornado","pyramid","kpi","treemap"].includes(i))return null;const c=t.AxisConfigurator.getAxisInfo(i,n);if(!c.hasXAxis&&!c.hasYAxis)return null;const o=(l,m)=>{let p;l==="x"?p="xAxisConfig":l==="y"?p="yAxisConfig":p="secondaryYAxisConfig";const x={...n||{},[p]:m};a(x);const u={...s,preferences:x};r(u)},d=c.hasY2Axis&&i==="combo";return e.jsxs(t.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rs,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Axes"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsxs(t.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[c.hasXAxis&&e.jsx(Zt,{axis:"x",label:"X-Axis",type:c.xAxisType,config:t.mergeAxisConfig(t.getDefaultAxisConfig(i,"x"),n==null?void 0:n.xAxisConfig),onChange:l=>o("x",l),defaultTitle:es("x",s,n)}),c.hasYAxis&&e.jsx(Zt,{axis:"y",label:d?"Y-Axis (Left)":"Y-Axis",type:c.yAxisType,config:t.mergeAxisConfig(t.getDefaultAxisConfig(i,"y"),n==null?void 0:n.yAxisConfig),onChange:l=>o("y",l),defaultTitle:es("y",s,n)}),d&&e.jsx(Zt,{axis:"y2",label:"Y2-Axis (Right)",type:"value",config:t.mergeAxisConfig({enabled:!0,position:"right"},n==null?void 0:n.secondaryYAxisConfig),onChange:l=>o("y2",l),defaultTitle:es("y2",s,n),hidePosition:!0})]})})]})}function Hr(){const s=t.useEditorStore(x=>x.card),n=Me.useEffectiveEditorCardType(),a=t.useEditorStore(x=>{var u,h,g,b;return(b=(g=(h=(u=x.card)==null?void 0:u.preferences)==null?void 0:h.chartOptions)==null?void 0:g.plugins)==null?void 0:b.legend}),{setLegendOptions:r}=t.useEditorActions();if(!s||!t.chartSupportsLegend(n))return null;const i=t.getDefaultLegendConfig(n),c=(i==null?void 0:i.display)??!0,o=(i==null?void 0:i.position)??"top",d=(i==null?void 0:i.align)??"center",l=(x,u)=>{const h={...a,[x]:u};r(h)},m=["top","bottom","left","right"],p=["start","center","end"];return e.jsxs(t.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(t.SmallSwitch,{checked:(a==null?void 0:a.display)??c,onCheckedChange:x=>l("display",x)})]}),((a==null?void 0:a.display)??c)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(t.Select,{value:(a==null?void 0:a.position)||o,onValueChange:x=>l("position",x),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:m.map(x=>e.jsx(t.SelectItem,{value:x,className:"text-xs",children:t.titleCase(x)},x))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(t.Select,{value:(a==null?void 0:a.align)||d,onValueChange:x=>l("align",x),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:p.map(x=>e.jsx(t.SelectItem,{value:x,className:"text-xs",children:t.titleCase(x)},x))})]})]})]})]})})]})}function Qr(){var O,P,y,L,C,V,F;const s=t.useEditorStore(R=>R.card),n=Me.useEffectiveEditorCardType(),a=t.useEditorStore(R=>{var $,B;return(B=($=R.card)==null?void 0:$.preferences)==null?void 0:B.dataLabelsConfig}),r=t.useEditorStore(R=>{var $;return($=R.card)==null?void 0:$.preferences}),{setCardPreferences:i,updateCardInFrame:c}=t.useEditorActions();if(!s||!t.chartSupportsDataLabels(n))return null;const o=n==="bullet"?((O=r==null?void 0:r.bulletConfig)==null?void 0:O.orientation)??(((P=r==null?void 0:r.chartOptions)==null?void 0:P.indexAxis)==="x"?"vertical":"horizontal"):void 0,d=o!=null?o==="horizontal":((y=r==null?void 0:r.chartOptions)==null?void 0:y.indexAxis)==="y",l=n==="stackedBar"||n==="stackedLine",m=n==="pie"||n==="doughnut"||n==="polarArea"||n==="funnel",p=n==="bubble"||n==="scatter",x=(C=(L=r==null?void 0:r.chartOptions)==null?void 0:L.plugins)==null?void 0:C.datalabels,u=(x==null?void 0:x.display)!==!1&&((x==null?void 0:x.anchor)||(x==null?void 0:x.align)),h=t.getDefaultDataLabelsConfig(n,s.preferences),g=a??h,b=(h==null?void 0:h.enabled)??u??!1,v=(a==null?void 0:a.enabled)!==void 0?a.enabled:b,w=(R,$)=>{const Y={...h??{},...a??{},[R]:$};R==="enabled"&&(Y.display=$,$&&p&&!Y.position&&(Y.position="bottom")),R==="position"&&p&&(Y.position="bottom"),R==="formatMode"&&$==="inherit"&&(Y.format=void 0,Y.formatOptions=void 0);const H={...s.preferences||{},dataLabelsConfig:Y};i(H);const Z={...s,preferences:H};c(Z)},E=(R,$)=>{const B=a??{},Y={...h??{},...B,font:{...B.font||{},[R]:$}},H={...s.preferences||{},dataLabelsConfig:Y};i(H);const Z={...s,preferences:H};c(Z)},z=()=>{const R=n;return R==="stackedBar"||R==="stackedLine"||R==="pie"||R==="doughnut"?"center":d?"right":"top"},D=n!=="treemap"&&n!=="heatmap",T=n!=="treemap",I=z();let M=[];if(D)if(p)M=["bottom"];else if(l||m)M=["center"];else{const R=d?["center","left","right"]:["center","top","bottom"];M=["auto",...n==="bullet"?R:R.filter(B=>B!==I),"custom"]}const k=()=>t.titleCase(I),j=["center","start","end"],S=["center","start","end","top","bottom"],A=(g==null?void 0:g.formatMode)||(g!=null&&g.format&&!["auto"].includes(g.format)?"override":"inherit"),f=(g==null?void 0:g.format)==="none";return e.jsxs(t.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(t.SmallSwitch,{checked:v,onCheckedChange:R=>w("enabled",R)})]}),v&&e.jsxs(e.Fragment,{children:[D&&!l&&!m&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(t.Select,{value:p?(g==null?void 0:g.position)||"bottom":(g==null?void 0:g.position)||"auto",onValueChange:R=>w("position",R),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:M.map(R=>e.jsx(t.SelectItem,{value:R,className:"text-xs",children:R==="auto"?k():R==="custom"?"Custom (Advanced)":t.titleCase(R)},R))})]})]}),l&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Show Total"}),e.jsx(t.SmallSwitch,{checked:(a==null?void 0:a.showTotal)??!1,onCheckedChange:R=>w("showTotal",R)})]}),(g==null?void 0:g.position)==="custom"&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground w-16",children:"Anchor"}),e.jsxs(t.Select,{value:(g==null?void 0:g.anchor)||"center",onValueChange:R=>w("anchor",R),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:j.map(R=>e.jsx(t.SelectItem,{value:R,className:"text-xs",children:t.titleCase(R)},R))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground w-16",children:"Align"}),e.jsxs(t.Select,{value:String((g==null?void 0:g.align)||"center"),onValueChange:R=>w("align",R),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:S.map(R=>e.jsx(t.SelectItem,{value:R,className:"text-xs",children:t.titleCase(R)},R))})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Format"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Keep this off to inherit from the bound metric."})]}),e.jsx(t.SmallSwitch,{checked:A==="override",onCheckedChange:R=>w("formatMode",R?"override":"inherit")})]}),A==="override"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Raw Value"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Show the unformatted numeric value."})]}),e.jsx(t.SmallSwitch,{checked:f,onCheckedChange:R=>{const $=a??{},K={...h??{},...$,formatMode:"override",format:R?"none":void 0,formatOptions:R?void 0:$.formatOptions},Y={...s.preferences||{},dataLabelsConfig:K};i(Y),c({...s,preferences:Y})}})]}),!f&&e.jsx(gt,{formatOptions:(g==null?void 0:g.formatOptions)||{},onFormatOptionsChange:R=>{const K={...h??{},...a??{},formatMode:"override",format:R.type&&R.type!=="auto"?R.type:void 0,formatOptions:R},Y={...s.preferences||{},dataLabelsConfig:K};i(Y),c({...s,preferences:Y})},showTitle:!1})]})]}),T&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Appearance"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground w-20",children:"Size"}),e.jsx("div",{className:"flex-1",children:e.jsx(Je,{type:"number",placeholder:"12",value:String(((V=g==null?void 0:g.font)==null?void 0:V.size)||12),onSave:R=>E("size",Number(R)),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground w-20",children:"Weight"}),e.jsxs(t.Select,{value:((F=g==null?void 0:g.font)==null?void 0:F.weight)||"normal",onValueChange:R=>E("weight",R),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(t.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground w-20",children:"Color"}),e.jsxs(t.Select,{value:(g==null?void 0:g.color)==="auto"||!(g!=null&&g.color)?"auto":"custom",onValueChange:R=>{R==="auto"&&w("color","auto")},children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Smart Contrast)"}),e.jsx(t.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom (Coming Soon)"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground w-20",children:"Rotation"}),e.jsx("div",{className:"flex-1",children:e.jsx(Je,{type:"number",placeholder:"0",value:String((g==null?void 0:g.rotation)||0),onSave:R=>w("rotation",Number(R)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}const ga={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%
193
- 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 Jr(){var u,h,g,b,v,w,E,z,D,T;const s=t.useEditorStore(I=>I.card),{setCardPreferences:n}=t.useEditorActions(),a=Me.useEffectiveEditorCardType(),r=((u=s.config)==null?void 0:u.metricColumns)||[],i=((h=s.config)==null?void 0:h.groupByColumns)||[],c=r.length===2&&i.length===0,o=r.some(I=>I.comparisonType&&I.comparisonType!=="none");if(!(a==="kpi"&&(c||o)))return null;const l=((b=(g=s.preferences)==null?void 0:g.kpiVisualOptions)==null?void 0:b.metricComparison)||{},m=I=>{var k;const M={...s.preferences,kpiVisualOptions:{...(k=s.preferences)==null?void 0:k.kpiVisualOptions,metricComparison:{...l,...I}}};n(M)},p=o||l.enabled,x=r.some(I=>I.comparisonType==="previous_period"||I.comparisonType==="same_period_last_year"||I.comparisonType==="start_vs_end");return e.jsxs(t.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(t.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ea,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[c&&r.length===2&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(t.SmallSwitch,{id:"enable-comparison",checked:l.enabled||!1,onCheckedChange:I=>m({enabled:I,...I&&!l.calculationType?{calculationType:"difference"}:{}})})]}),p&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(t.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.Info,{className:"h-3 w-3 cursor-help text-muted-foreground"})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:(()=>{const I=l.calculationType||"difference",M=ga[I];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:M==null?void 0:M.label}),e.jsx("p",{children:M==null?void 0:M.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:M==null?void 0:M.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",M==null?void 0:M.example]})]})})()})]})]}),e.jsxs(t.Select,{value:l.calculationType||"difference",onValueChange:I=>m({calculationType:I}),children:[e.jsx(t.SelectTrigger,{id:"calculation-type",className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Object.entries(ga).map(([I,M])=>e.jsx(t.SelectItem,{value:I,className:"text-xs",children:M.label},I))})]})]}),e.jsx(gt,{formatOptions:l.formatOptions||{},onFormatOptionsChange:I=>m({formatOptions:I}),showTitle:!0,title:"COMPARISON FORMAT"}),(x||c)&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator"}),c&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(t.Select,{value:l.position||"right",onValueChange:I=>m({position:I}),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"right",className:"text-xs",children:"Right"}),e.jsx(t.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(t.SelectItem,{value:"top",className:"text-xs",children:"Top"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Checkbox,{id:"show-arrow",checked:l.showArrow!==!1,onCheckedChange:I=>m({showArrow:I})}),e.jsx(t.Label,{htmlFor:"show-arrow",className:"cursor-pointer text-xs text-muted-foreground",children:"Arrow"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Checkbox,{id:"show-color",checked:l.showColor!==!1,onCheckedChange:I=>m({showColor:I})}),e.jsx(t.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),l.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(Ze,{value:((v=l.colorConfig)==null?void 0:v.increase)||"green",onChange:I=>m({colorConfig:{...l.colorConfig,increase:I}}),label:"Primary > Secondary"}),e.jsx(Ze,{value:((w=l.colorConfig)==null?void 0:w.decrease)||"red",onChange:I=>m({colorConfig:{...l.colorConfig,decrease:I}}),label:"Primary < Secondary"}),e.jsx(Ze,{value:((E=l.colorConfig)==null?void 0:E.noChange)||"neutral",onChange:I=>m({colorConfig:{...l.colorConfig,noChange:I}}),label:"Primary = Secondary"})]})]}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Checkbox,{id:"conditional-label",checked:l.conditionalLabel||!1,onCheckedChange:I=>m({conditionalLabel:I})}),e.jsx(t.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),l.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(t.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(t.Input,{id:"label-increase",type:"text",value:((z=l.conditionalLabels)==null?void 0:z.increase)??"Increase",onChange:I=>m({conditionalLabels:{...l.conditionalLabels,increase:I.target.value}}),placeholder:"Increase",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(t.Label,{htmlFor:"label-decrease",className:"text-xs text-muted-foreground",children:["Primary ","<"," Secondary"]}),e.jsx(t.Input,{id:"label-decrease",type:"text",value:((D=l.conditionalLabels)==null?void 0:D.decrease)??"Decrease",onChange:I=>m({conditionalLabels:{...l.conditionalLabels,decrease:I.target.value}}),placeholder:"Decrease",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{htmlFor:"label-no-change",className:"text-xs text-muted-foreground",children:"Primary = Secondary"}),e.jsx(t.Input,{id:"label-no-change",type:"text",value:((T=l.conditionalLabels)==null?void 0:T.noChange)??"No change",onChange:I=>m({conditionalLabels:{...l.conditionalLabels,noChange:I.target.value}}),placeholder:"No change",className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{htmlFor:"label-name",className:"text-xs text-muted-foreground",children:"Previous Label"}),e.jsx(t.Input,{id:"label-name",type:"text",value:l.labelName??"",onChange:I=>m({labelName:I.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function Yr(){var c;const s=t.useEditorStore(o=>{var d;return(d=o.card)==null?void 0:d.type}),n=t.useEditorStore(o=>{var d;return(d=o.card)==null?void 0:d.preferences}),{setCardPreferences:a}=t.useEditorActions();if(s!=="treemap")return null;const r=((c=n==null?void 0:n.chartOptions)==null?void 0:c.treemapColorMode)??"branch",i=o=>{const d={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,treemapColorMode:o}};a(d)};return e.jsxs(t.AccordionItem,{value:"treemap-color-mode",className:"border-none",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.TbChartTreemap,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Treemap Colors"})]})}),e.jsx(t.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:e.jsxs(t.RadioGroup,{value:r,onValueChange:o=>i(o??"branch"),className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(t.RadioGroupItem,{id:"treemap-color-branch",value:"branch"}),e.jsxs(t.Label,{htmlFor:"treemap-color-branch",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Shade by value (default)"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Keeps parent hue and adjusts lightness based on the node's share within the branch."})]})]}),e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(t.RadioGroupItem,{id:"treemap-color-category",value:"category"}),e.jsxs(t.Label,{htmlFor:"treemap-color-category",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Single color per category"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Applies the top-level color to all descendants without lightening/darkening."})]})]})]})})]})}const Wr=Object.keys(t.HEATMAP_PRESET_PALETTES);function Xr(){const s=t.useEditorStore(u=>u.card),n=t.useEditorStore(u=>{var h;return(h=u.card)==null?void 0:h.preferences}),{setCardPreferences:a}=t.useEditorActions(),r=(s==null?void 0:s.type)==="heatmap",i=(n==null?void 0:n.heatmapConfig)||{},c=i.colorPalette??"green",o=i.legendPosition??"bottom",d=N.useMemo(()=>i.colorRange&&i.colorRange[0]&&i.colorRange[1]?[i.colorRange[0],i.colorRange[1]]:[...t.DEFAULT_HEATMAP_CUSTOM_RANGE],[i.colorRange]),l=u=>{const h={...i,...u};h.colorPalette!=="custom"?delete h.colorRange:(!h.colorRange||!h.colorRange[0]||!h.colorRange[1])&&(h.colorRange=[...t.DEFAULT_HEATMAP_CUSTOM_RANGE]),a({...n||{},heatmapConfig:h})},m=u=>{l({colorPalette:u,colorRange:u==="custom"?i.colorRange??[...t.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},p=(u,h)=>{const g=[...d];g[u]=h,l({colorPalette:"custom",colorRange:g})},x=u=>{l({legendPosition:u})};return r?e.jsxs(t.AccordionItem,{value:"heatmap-color-config",className:"border-none",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Grid3x3,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Heatmap Settings"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs(t.RadioGroup,{value:c,onValueChange:u=>m(u??"blue"),className:"space-y-3",children:[Wr.map(u=>{const h=t.HEATMAP_PRESET_PALETTES[u];return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(t.RadioGroupItem,{id:`heatmap-${u}`,value:u}),e.jsxs(t.Label,{htmlFor:`heatmap-${u}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:h.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${h.start}, ${h.end})`}})]})]},u)}),e.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.RadioGroupItem,{id:"heatmap-custom",value:"custom"}),e.jsx(t.Label,{htmlFor:"heatmap-custom",className:"text-sm font-medium",children:"Custom colors"})]}),c==="custom"&&e.jsxs("div",{className:"flex flex-col gap-3 pl-6",children:[e.jsx(Ze,{value:d[0],onChange:u=>p(0,u),label:"Start color"}),e.jsx(Ze,{value:d[1],onChange:u=>p(1,u),label:"End color"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Color scale position"}),e.jsxs(t.Select,{value:o,onValueChange:u=>x(u??"bottom"),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:["top","bottom","left","right"].map(u=>e.jsx(t.SelectItem,{value:u,className:"text-xs",children:u[0].toUpperCase()+u.slice(1)},u))})]})]})]})]}):null}const ja=["poor","satisfactory","good"];function ba(s){if(!s)return;const n={...s};return n.targetMetricKey||delete n.targetMetricKey,n.comparativeMetricKey||delete n.comparativeMetricKey,!n.targetValue&&n.targetValue!==0&&delete n.targetValue,(!n.rangeKeys||Object.keys(n.rangeKeys).length===0)&&delete n.rangeKeys,(!n.ranges||Object.keys(n.ranges).length===0)&&delete n.ranges,(!n.rangeLabels||Object.keys(n.rangeLabels).length===0)&&delete n.rangeLabels,n}function Zr(){var O,P;const s=t.useEditorStore(y=>y.card.preferences),n=t.useEditorStore(y=>y.card),a=t.useEditorStore(y=>y.isDevMode),{setCardPreferences:r,setChartOrientation:i}=t.useEditorActions(),c=N.useMemo(()=>(s==null?void 0:s.bulletConfig)||{},[s==null?void 0:s.bulletConfig]),d=t.hasValidCardConfig(n==null?void 0:n.config)&&!a,[l,m]=N.useState(c.showRanges??!1),[p,x]=N.useState(c.rangesArePercentages??!1),u=c.disableAutoComparative?!1:c.comparativeMetricKey!==void 0||!d,[h,g]=N.useState(u);N.useEffect(()=>{m(c.showRanges??!1)},[c.showRanges]),N.useEffect(()=>{x(c.rangesArePercentages??!1)},[c.rangesArePercentages]);const b=c.targetValue===void 0?"":String(c.targetValue);N.useEffect(()=>{const y=c.disableAutoComparative?!1:c.comparativeMetricKey!==void 0||!d;g(y)},[c.disableAutoComparative,c.comparativeMetricKey,d]);const v=N.useMemo(()=>{var y,L;return((L=(y=n==null?void 0:n.config)==null?void 0:y.metricColumns)==null?void 0:L.map(C=>{const V=C.label||C.name||C.alias||"";return{value:V,label:V}}))||[]},[(O=n==null?void 0:n.config)==null?void 0:O.metricColumns]);N.useEffect(()=>{var B,K;if(!s||v.length===0)return;const y={};let L=!1;const C=(B=v[1])==null?void 0:B.value;!c.targetMetricKey&&C&&(y.targetMetricKey=C,L=!0);const V=(K=v[2])==null?void 0:K.value;!c.comparativeMetricKey&&!c.disableAutoComparative&&V&&(y.comparativeMetricKey=V,L=!0);const F=v.slice(3),R={...c.rangeKeys||{}};let $=!1;if(ja.forEach((Y,H)=>{!R[Y]&&F[H]&&(R[Y]=F[H].value,$=!0)}),$&&(y.rangeKeys=R,L=!0,c.showRanges===void 0&&(y.showRanges=!0)),L){const Y=ba({...c,...y});r({...s,bulletConfig:Y})}},[v,c,s,r]);const w=y=>{const L=ba({...c,...y});r({...s,bulletConfig:L})},E=(y,L)=>{const C={...c.rangeKeys||{},[y]:L.trim()};L.trim()||delete C[y],w({rangeKeys:Object.keys(C).length>0?C:void 0})},z=(y,L)=>{const C=L===""?void 0:Number(L),V={...c.ranges||{}};C===void 0||Number.isNaN(C)?delete V[y]:V[y]=C,w({ranges:Object.keys(V).length?V:void 0})},D=y=>{if(y===""){w({targetValue:void 0});return}const L=Number(y);w({targetValue:Number.isNaN(L)?void 0:L})},T=(y,L)=>{const C=L.trim(),V={...c.rangeLabels||{}};C?V[y]=C:delete V[y],w({rangeLabels:Object.keys(V).length>0?V:void 0})},I=y=>{m(y),w({showRanges:y})},M=y=>{x(y),w({rangesArePercentages:y})},k=c.orientation||(((P=s==null?void 0:s.chartOptions)==null?void 0:P.indexAxis)==="y"?"horizontal":"vertical"),j=y=>{w({orientation:y}),i(y==="horizontal"?"y":"x")},S=[{value:"__none",label:"None"},...v.map(y=>({value:y.value,label:y.label}))],A=S,f=y=>{if(g(y),!y){w({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!d){w({disableAutoComparative:!1});return}if(c.comparativeMetricKey)w({disableAutoComparative:!1});else{const L=v.find(C=>C.value!==c.targetMetricKey);w({comparativeMetricKey:L==null?void 0:L.value,disableAutoComparative:!1})}};return e.jsxs(t.AccordionItem,{value:"bullet-config",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.BulletChartIcon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bullet Chart"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-6 border-t border-border/50 py-4",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"ORIENTATION"}),e.jsxs(t.Select,{value:k,onValueChange:y=>j(y),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"horizontal",className:"text-xs",children:"Horizontal"}),e.jsx(t.SelectItem,{value:"vertical",className:"text-xs",children:"Vertical"})]})]})]}),d&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"TARGET METRIC"}),e.jsxs(t.Select,{value:c.targetMetricKey||"__none",onValueChange:y=>w({targetMetricKey:y==="__none"?void 0:y}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select metric"})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"__none",className:"text-xs",children:"None"}),v.map(y=>e.jsx(t.SelectItem,{value:y.value,className:"text-xs",children:y.label},y.value))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"COMPARATIVE METRIC"}),d?e.jsxs(t.Select,{value:c.comparativeMetricKey||"__none",onValueChange:y=>w({comparativeMetricKey:y==="__none"?void 0:y,disableAutoComparative:y==="__none"}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select metric"})}),e.jsx(t.SelectContent,{children:S.map(y=>e.jsx(t.SelectItem,{value:y.value,className:"text-xs",children:y.label},y.value))})]}):e.jsxs("div",{className:"space-y-2 rounded-md border border-border/50 p-3 text-xs",children:[e.jsxs("div",{className:"flex items-center justify-between font-medium",children:[e.jsx("span",{children:"Show comparative"}),e.jsx(t.SmallSwitch,{checked:h,onCheckedChange:y=>f(y)})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Comparative values are auto-detected from the third metric in your results."})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"TARGET VALUE (FALLBACK)"}),e.jsx(Be,{type:"number",className:"h-8 text-xs",value:b,onCommit:D,placeholder:"Optional numeric fallback"})]})]}),e.jsxs("section",{className:"space-y-4 rounded-md border border-border/60 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"QUALITATIVE RANGES"}),e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:200,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"text-muted-foreground transition-colors hover:text-foreground",children:e.jsx(t.Info,{className:"h-3.5 w-3.5"})})}),e.jsx(t.TooltipContent,{side:"top",children:"Use columns or static values for Poor / Average / Good."})]})})]}),e.jsx("div",{className:"flex items-center gap-2 text-xs font-medium",children:e.jsx(t.SmallSwitch,{checked:l,onCheckedChange:I})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:p,disabled:!l,onChange:y=>M(y.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:ja.map(y=>{var L,C,V,F,R;return e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-muted/40 p-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[y," LABEL"]}),e.jsx(Be,{placeholder:`Display label (${y})`,value:((L=c.rangeLabels)==null?void 0:L[y])||"",onCommit:$=>T(y,$),className:"h-8 text-xs"})]}),d?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[y," COLUMN"]}),e.jsxs(t.Select,{value:((C=c.rangeKeys)==null?void 0:C[y])||"__none",onValueChange:$=>{$==="__none"?E(y,""):E(y,$)},children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select column"})}),e.jsx(t.SelectContent,{children:A.map($=>e.jsx(t.SelectItem,{value:$.value,className:"text-xs",children:$.label},$.value))})]})]}):e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[y," COLUMN KEY"]}),e.jsx(Be,{placeholder:"Column key",value:((V=c.rangeKeys)==null?void 0:V[y])||"",onCommit:$=>E(y,$),className:"h-8 text-xs"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[y," VALUE"]}),e.jsx(Be,{type:"number",placeholder:p?"0.80":"Static value",value:((F=c.ranges)==null?void 0:F[y])===void 0?"":String((R=c.ranges)==null?void 0:R[y]),onCommit:$=>z(y,$),className:"h-8 text-xs"})]})]},y)})})]})]})]})}function va(s){if(!s)return;const n={...s};if(n.xMetricKey||delete n.xMetricKey,n.yMetricKey||delete n.yMetricKey,n.radiusMetricKey||delete n.radiusMetricKey,n.labelKey||delete n.labelKey,n.groupKey||delete n.groupKey,n.enableGrouping===void 0&&delete n.enableGrouping,n.radiusScale||delete n.radiusScale,n.fixedRadius===void 0&&delete n.fixedRadius,n.minRadius===void 0&&delete n.minRadius,n.maxRadius===void 0&&delete n.maxRadius,Object.keys(n).length!==0)return n}function el(){var T,I,M,k,j,S,A,f,O,P,y,L;const s=t.useEditorStore(C=>C.card.preferences),n=t.useEditorStore(C=>C.card),a=Me.useEffectiveEditorCardType(),r=t.useEditorStore(C=>C.isDevMode),{setCardPreferences:i,updateCardInFrame:c}=t.useEditorActions(),o=a==="bubble",d=a==="scatter",l=N.useMemo(()=>(s==null?void 0:s.bubbleScatterConfig)||{},[s==null?void 0:s.bubbleScatterConfig]),p=t.hasValidCardConfig(n==null?void 0:n.config)&&!r,x=N.useMemo(()=>{var C,V;return((V=(C=n==null?void 0:n.config)==null?void 0:C.metricColumns)==null?void 0:V.map(F=>{const R=F.label||F.name||F.alias||"";return{value:R,label:R}}))||[]},[(T=n==null?void 0:n.config)==null?void 0:T.metricColumns]),u=N.useMemo(()=>{var C,V;return((V=(C=n==null?void 0:n.config)==null?void 0:C.groupByColumns)==null?void 0:V.map(F=>{const R=F.label||F.name||F.alias||"";return{value:R,label:R}}))||[]},[(I=n==null?void 0:n.config)==null?void 0:I.groupByColumns]),h=N.useMemo(()=>l.enableGrouping!==void 0?l.enableGrouping:!r&&u.length>=2,[l.enableGrouping,r,u.length]),[g,b]=N.useState(h);N.useEffect(()=>{b(h)},[h]);const v=C=>{const V={...s||{},bubbleScatterConfig:C};i(V),n&&c({...n,preferences:V})},w=C=>{i(C),n&&c({...n,preferences:C})};N.useEffect(()=>{if(!s||x.length===0)return;const C={};let V=!1;if(!l.xMetricKey&&x[0]&&(C.xMetricKey=x[0].value,V=!0),!l.yMetricKey&&x[1]&&(C.yMetricKey=x[1].value,V=!0),o&&!l.radiusMetricKey&&x[2]&&(C.radiusMetricKey=x[2].value,V=!0),!l.labelKey&&u[0]&&(C.labelKey=u[0].value,V=!0),h&&!l.groupKey&&u[1]&&(C.groupKey=u[1].value,C.enableGrouping=!0,V=!0),V){const F=va({...l,...C});v(F)}},[x,u,l,s,i,o,h]);const E=C=>{const V=va({...l,...C});v(V)},z=C=>{b(C),E({enableGrouping:C,groupKey:C?l.groupKey:void 0})};if(!o&&!d)return null;const D=o?t.Circle:t.ChartScatter;return e.jsxs(t.AccordionItem,{value:"bubble-scatter-config",children:[e.jsx(t.AccordionTrigger,{className:"py-2 text-sm",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(D,{className:"h-4 w-4"}),e.jsxs("span",{children:[o?"Bubble":"Scatter"," Configuration"]})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-1 pb-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-1 text-xs font-medium text-muted-foreground",children:["Dimensions",e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{children:e.jsx(t.Info,{className:"h-3 w-3"})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{children:"Label identifies each point. Group creates separate series in the legend."})})]})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Label Column"}),p?e.jsxs(t.Select,{value:l.labelKey||"",onValueChange:C=>E({labelKey:C}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select label column"})}),e.jsx(t.SelectContent,{children:u.map(C=>e.jsx(t.SelectItem,{value:C.value,children:C.label},C.value))})]}):e.jsx(Be,{className:"h-8 text-xs",placeholder:"Column name for labels",value:l.labelKey||"",onCommit:C=>E({labelKey:C})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Group points into series"}),e.jsx(t.SmallSwitch,{checked:g,onCheckedChange:z})]}),g&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Group By"}),p?e.jsxs(t.Select,{value:l.groupKey||"",onValueChange:C=>E({groupKey:C}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select group column"})}),e.jsx(t.SelectContent,{children:u.map(C=>e.jsx(t.SelectItem,{value:C.value,children:C.label},C.value))})]}):e.jsx(Be,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:l.groupKey||"",onCommit:C=>E({groupKey:C})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Metrics"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"X Axis"}),p?e.jsxs(t.Select,{value:l.xMetricKey||"",onValueChange:C=>E({xMetricKey:C}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select X metric"})}),e.jsx(t.SelectContent,{children:x.map(C=>e.jsx(t.SelectItem,{value:C.value,children:C.label},C.value))})]}):e.jsx(Be,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:l.xMetricKey||"",onCommit:C=>E({xMetricKey:C})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Axis"}),p?e.jsxs(t.Select,{value:l.yMetricKey||"",onValueChange:C=>E({yMetricKey:C}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select Y metric"})}),e.jsx(t.SelectContent,{children:x.map(C=>e.jsx(t.SelectItem,{value:C.value,children:C.label},C.value))})]}):e.jsx(Be,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:l.yMetricKey||"",onCommit:C=>E({yMetricKey:C})})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Radius"}),p?e.jsxs(t.Select,{value:l.radiusMetricKey||"",onValueChange:C=>E({radiusMetricKey:C}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select radius metric"})}),e.jsx(t.SelectContent,{children:x.map(C=>e.jsx(t.SelectItem,{value:C.value,children:C.label},C.value))})]}):e.jsx(Be,{className:"h-8 text-xs",placeholder:"Column name for radius",value:l.radiusMetricKey||"",onCommit:C=>E({radiusMetricKey:C})})]})]}),o&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Radius Settings"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Scale Mode"}),e.jsxs(t.Select,{value:l.radiusScale||"sqrt",onValueChange:C=>E({radiusScale:C}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"sqrt",children:"Square Root (area-proportional)"}),e.jsx(t.SelectItem,{value:"linear",children:"Linear"}),e.jsx(t.SelectItem,{value:"fixed",children:"Fixed Size"})]})]})]}),l.radiusScale!=="fixed"&&e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Min Radius"}),e.jsx(Be,{className:"h-8 text-xs",type:"number",placeholder:"5",value:((M=l.minRadius)==null?void 0:M.toString())||"",onCommit:C=>E({minRadius:C?Number(C):void 0})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Max Radius"}),e.jsx(Be,{className:"h-8 text-xs",type:"number",placeholder:"30",value:((k=l.maxRadius)==null?void 0:k.toString())||"",onCommit:C=>E({maxRadius:C?Number(C):void 0})})]})]}),l.radiusScale==="fixed"&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs(t.Label,{className:"text-xs",children:["Fixed Radius: ",l.fixedRadius||10]}),e.jsx(t.Slider,{value:[l.fixedRadius||10],onValueChange:([C])=>E({fixedRadius:C}),min:3,max:30,step:1,className:"py-2"})]})]}),d&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Point Settings"}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(t.Label,{className:"text-xs",children:["Point Size: ",l.fixedRadius||5]}),e.jsx(t.Slider,{value:[l.fixedRadius||5],onValueChange:([C])=>E({fixedRadius:C}),min:2,max:15,step:1,className:"py-2"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Axis Titles"}),e.jsx(t.SmallSwitch,{checked:((S=(j=s==null?void 0:s.xAxisConfig)==null?void 0:j.name)==null?void 0:S.enabled)??!1,onCheckedChange:C=>{var R,$,B,K;const V=l.xMetricKey||"X Axis",F=l.yMetricKey||"Y Axis";w({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{enabled:C,text:(($=(R=s==null?void 0:s.xAxisConfig)==null?void 0:R.name)==null?void 0:$.text)||V}},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{enabled:C,text:((K=(B=s==null?void 0:s.yAxisConfig)==null?void 0:B.name)==null?void 0:K.text)||F}}})}})]}),((f=(A=s==null?void 0:s.xAxisConfig)==null?void 0:A.name)==null?void 0:f.enabled)&&e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"X Title"}),e.jsx(Be,{className:"h-8 text-xs",placeholder:l.xMetricKey||"X Axis",value:((P=(O=s==null?void 0:s.xAxisConfig)==null?void 0:O.name)==null?void 0:P.text)||"",onCommit:C=>{var V;w({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{...(V=s==null?void 0:s.xAxisConfig)==null?void 0:V.name,enabled:!0,text:C||l.xMetricKey||"X Axis"}}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Title"}),e.jsx(Be,{className:"h-8 text-xs",placeholder:l.yMetricKey||"Y Axis",value:((L=(y=s==null?void 0:s.yAxisConfig)==null?void 0:y.name)==null?void 0:L.text)||"",onCommit:C=>{var V;w({...s??{},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{...(V=s==null?void 0:s.yAxisConfig)==null?void 0:V.name,enabled:!0,text:C||l.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const tl=[{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 sl(){const s=t.useEditorStore(u=>u.card),n=t.useEditorStore(u=>{var h;return(h=u.card)==null?void 0:h.preferences}),{setCardPreferences:a}=t.useEditorActions(),r=(s==null?void 0:s.type)==="funnel",i=(n==null?void 0:n.funnelConfig)||{},c=i.percentMode??"percentOfTotal",o=i.shrinkFraction??1,d=i.labelThreshold??0,l=u=>{const h={...i,...u};a({...n||{},funnelConfig:h})},m=u=>{l({percentMode:u})},p=u=>{l({shrinkFraction:u[0]})},x=u=>{l({labelThreshold:u[0]})};return r?e.jsxs(t.AccordionItem,{value:"funnel-config",className:"border-none",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Filter,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Funnel Settings"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"PERCENTAGE MODE"}),e.jsx(t.RadioGroup,{value:c,onValueChange:u=>m(u),className:"space-y-2",children:tl.map(u=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(t.RadioGroupItem,{id:`funnel-${u.value}`,value:u.value,className:"mt-0.5"}),e.jsxs(t.Label,{htmlFor:`funnel-${u.value}`,className:"flex flex-col gap-0.5 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.description})]})]},u.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"SEGMENT SHRINK"}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Same Width"}),e.jsx(t.Slider,{value:[o],onValueChange:p,min:0,max:1,step:.1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Full Shrink"})]}),e.jsxs("p",{className:"text-center text-xs text-muted-foreground",children:["Current: ",Math.round(o*100),"%"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"LABEL VISIBILITY THRESHOLD"}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Show All"}),e.jsx(t.Slider,{value:[d],onValueChange:x,min:0,max:25,step:1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Hide Small"})]}),e.jsx("p",{className:"text-center text-xs text-muted-foreground",children:d===0?"Showing all labels":`Hide labels below ${d}%`})]})]})]}):null}function zt(){const s=t.useEditorStore(c=>c.card),{data:n}=t.useDashboardCardQuery(s),{keys:a}=t.getKeys((n==null?void 0:n.records)||[]),r=a.slice(1).filter(c=>!t.METADATA_KEYS.includes(c));let i=r;if(["stackedBar","stackedLine"].includes(s.type)){const c=t.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:o}=t.getKeys(c);i=o.slice(1)}return{transformedMetricKeys:i,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}const al=[{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"}],nl=[{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)"}],rl=["center","start","end"],ll=["center","start","end","top","bottom"];function qt({config:s,onChange:n,isHorizontal:a=!1,showAutoFormat:r=!0,positionOptions:i,showAppearance:c=!0}){var g,b,v,w,E,z;const o=i??(a?["auto","center","left","right","custom"]:["auto","center","top","bottom","custom"]),d=r?["auto","number","currency","percent","none"]:["number","currency","percent","none"],l=(D,T)=>{const I={...s,[D]:T};n(I)},m=(D,T)=>{const I={...s,font:{...(s==null?void 0:s.font)||{},[D]:T}};n(I)},p=(D,T)=>{const I={...s,formatOptions:{...(s==null?void 0:s.formatOptions)||{},[D]:T}};n(I)},x=()=>a?"Right":"Top",u=s||{},h=u.format||(r?"auto":"number");return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(t.Select,{value:u.position||"auto",onValueChange:D=>l("position",D),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:o.map(D=>e.jsx(t.SelectItem,{value:D,className:"text-xs",children:D==="auto"?x():D==="custom"?"Custom (Advanced)":t.titleCase(D)},D))})]})]}),u.position==="custom"&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Anchor"}),e.jsxs(t.Select,{value:u.anchor||"center",onValueChange:D=>l("anchor",D),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:rl.map(D=>e.jsx(t.SelectItem,{value:D,className:"text-xs",children:t.titleCase(D)},D))})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Align"}),e.jsxs(t.Select,{value:String(u.align||"center"),onValueChange:D=>l("align",D),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ll.map(D=>e.jsx(t.SelectItem,{value:D,className:"text-xs",children:t.titleCase(D)},D))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Format"}),e.jsxs(t.Select,{value:h,onValueChange:D=>l("format",D),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:d.map(D=>e.jsx(t.SelectItem,{value:D,className:"text-xs",children:D==="auto"&&r?"Auto (Use Axis)":D==="none"?"None (Raw Value)":t.titleCase(D)},D))})]})]}),!["auto","none"].includes(h)&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[["number","currency","percent"].includes(h)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Decimals"}),e.jsx("div",{className:"w-16",children:e.jsx(Je,{type:"number",placeholder:"0",value:String(((g=u.formatOptions)==null?void 0:g.decimalPlaces)??(h==="currency"?2:h==="percent"?1:0)),onSave:D=>p("decimalPlaces",Number(D)),className:""})})]}),h==="currency"&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Currency"}),e.jsxs(t.Select,{value:((b=u.formatOptions)==null?void 0:b.currency)||"USD",onValueChange:D=>p("currency",D),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:al.map(D=>e.jsx(t.SelectItem,{value:D.value,className:"text-xs",children:D.label},D.value))})]})]}),["number","currency"].includes(h)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Abbreviate (K, M, B)"}),e.jsx(t.SmallSwitch,{checked:((v=u.formatOptions)==null?void 0:v.useSuffix)??!1,onCheckedChange:D=>p("useSuffix",D)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Locale"}),e.jsxs(t.Select,{value:((w=u.formatOptions)==null?void 0:w.locale)||"en-US",onValueChange:D=>p("locale",D),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:nl.map(D=>e.jsx(t.SelectItem,{value:D.value,className:"text-xs",children:D.label},D.value))})]})]})]}),c&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Appearance"}),e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Size"}),e.jsx("div",{className:"w-16",children:e.jsx(Je,{type:"number",placeholder:"12",value:String(((E=u.font)==null?void 0:E.size)||12),onSave:D=>m("size",Number(D)),className:""})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Weight"}),e.jsxs(t.Select,{value:((z=u.font)==null?void 0:z.weight)||"normal",onValueChange:D=>m("weight",D),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(t.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Color"}),e.jsxs(t.Select,{value:u.color==="auto"||!u.color?"auto":"custom",onValueChange:D=>{D==="auto"&&l("color","auto")},children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Contrast)"}),e.jsx(t.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Rotation"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-12",children:e.jsx(Je,{type:"number",placeholder:"0",value:String(u.rotation||0),onSave:D=>l("rotation",Number(D)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"°"})]})]})]})]})]})}const ol=[{type:"bar",icon:t.ChartColumnIncreasing,label:"Bar"},{type:"line",icon:t.ChartLine,label:"Line"}],il=[0,1,2,3,4,5,6,8,10],cl=[{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 │"}],dl=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function ul(){return t.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type})!=="combo"?null:e.jsxs(t.AccordionItem,{value:"combo-series",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsx(ml,{})})]})}function ml(){const{transformedMetricKeys:s}=zt();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((n,a)=>e.jsx(xl,{metricKey:n,idx:a},n))})}function xl({metricKey:s,idx:n}){var w;const[a,r]=N.useState(!1),i=t.useEditorStore(E=>{var z;return(z=E.card)==null?void 0:z.preferences}),c=t.useEditorStore(E=>{var z,D;return(D=(z=E.card)==null?void 0:z.preferences)==null?void 0:D.datasetOptions}),o=c==null?void 0:c.find(E=>E.idx===n),{setCardPreferences:d}=t.useEditorStore(E=>E.actions),l=(o==null?void 0:o.type)||"bar",m=(o==null?void 0:o.yAxisId)||"y",p=((w=o==null?void 0:o.dataLabels)==null?void 0:w.enabled)??!1,x=l==="line"?t.ChartLine:t.ChartColumnIncreasing;function u(E){const z={idx:n,type:l,yAxisId:m,dataLabels:o==null?void 0:o.dataLabels,...E};if(!o)d({...i||{},datasetOptions:[...c||[],z]});else{const D=c==null?void 0:c.map(T=>T.idx===n?{...T,...z}:T);d({...i||{},datasetOptions:D})}}function h(E){u({type:E})}function g(E){u({yAxisId:E})}function b(E){u({dataLabels:{...o==null?void 0:o.dataLabels,enabled:E}})}function v(E){u({dataLabels:E})}return e.jsx(t.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(t.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(t.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:s,children:s})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[e.jsxs("span",{className:t.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(x,{className:"h-3 w-3"}),l==="line"?"Line":"Bar"]}),e.jsx("span",{className:t.cn("rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:m==="y2"?"Y2":"Y1"})]})]})}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"flex items-end gap-4",children:[e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Chart Type"}),e.jsx("div",{className:"flex gap-2",children:ol.map(({type:E,icon:z,label:D})=>{const T=l===E;return e.jsxs("button",{onClick:()=>h(E),className:t.cn("flex items-center gap-2 rounded-md border px-3 py-1.5 text-xs transition-colors",T?"border-primary bg-primary/10 text-primary":"border-border bg-background text-muted-foreground hover:bg-muted"),children:[e.jsx(z,{className:"h-4 w-4"}),e.jsx("span",{children:D})]},E)})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Axis"}),e.jsxs(t.Select,{value:m,onValueChange:E=>g(E),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-20 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"y",className:"text-xs",children:"Y1 (Left)"}),e.jsx(t.SelectItem,{value:"y2",className:"text-xs",children:"Y2 (Right)"})]})]})]})]}),l==="line"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(t.Select,{value:(o==null?void 0:o.lineStyle)||"solid",onValueChange:E=>u({lineStyle:E}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:dl.map(({value:E,label:z})=>e.jsx(t.SelectItem,{value:E,className:"text-xs",children:z},E))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(t.Select,{value:String((o==null?void 0:o.pointRadius)??3),onValueChange:E=>u({pointRadius:Number(E)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:il.map(E=>e.jsx(t.SelectItem,{value:String(E),className:"text-xs",children:E===0?"None":E},E))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(t.Select,{value:(o==null?void 0:o.pointStyle)||"circle",onValueChange:E=>u({pointStyle:E}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:cl.map(({value:E,label:z})=>e.jsx(t.SelectItem,{value:E,className:"text-xs",children:z},E))})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(t.SmallSwitch,{checked:p,onCheckedChange:b})]}),p&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(qt,{config:o==null?void 0:o.dataLabels,onChange:v,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const ts=[{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"}],hl=[0,1,2,3,4,5,6,8,10],pl=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],fl=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function gl(s){return s==null?"origin":s===!1?"false":s}function jl(){const s=t.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type});return s!=="area"&&s!=="stackedArea"?null:e.jsxs(t.AccordionItem,{value:"area-series",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsx(bl,{})})]})}function bl(){const{transformedMetricKeys:s}=zt();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((n,a)=>e.jsx(vl,{metricKey:n,idx:a},n))})}function vl({metricKey:s,idx:n}){var b;const[a,r]=N.useState(!1),i=t.useEditorStore(v=>{var w;return(w=v.card)==null?void 0:w.preferences}),c=t.useEditorStore(v=>{var w,E;return(E=(w=v.card)==null?void 0:w.preferences)==null?void 0:E.datasetOptions}),o=c==null?void 0:c.find(v=>v.idx===n),{setCardPreferences:d}=t.useEditorStore(v=>v.actions),l=gl(o==null?void 0:o.fill),m=((b=o==null?void 0:o.dataLabels)==null?void 0:b.enabled)??!1,p=ts.find(v=>v.value===l)||ts[0];function x(v){const w={idx:n,fill:l,dataLabels:o==null?void 0:o.dataLabels,...v};if(!o)d({...i||{},datasetOptions:[...c||[],w]});else{const E=c==null?void 0:c.map(z=>z.idx===n?{...z,...w}:z);d({...i||{},datasetOptions:E})}}function u(v){x({fill:v==="false"?!1:v})}function h(v){x({dataLabels:{...o==null?void 0:o.dataLabels,enabled:v}})}function g(v){x({dataLabels:v})}return e.jsx(t.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(t.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(t.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:s,children:s})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:e.jsxs("span",{className:t.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(t.ChartArea,{className:"h-3 w-3"}),p.label.split(" ")[0]]})})]})}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Fill Target"}),e.jsxs(t.Select,{value:l,onValueChange:v=>u(v),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ts.map(v=>e.jsx(t.SelectItem,{value:v.value,className:"text-xs",children:e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{children:v.label})})},v.value))})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(t.Select,{value:(o==null?void 0:o.lineStyle)||"solid",onValueChange:v=>x({lineStyle:v}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:fl.map(({value:v,label:w})=>e.jsx(t.SelectItem,{value:v,className:"text-xs",children:w},v))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(t.Select,{value:String((o==null?void 0:o.pointRadius)??3),onValueChange:v=>x({pointRadius:Number(v)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:hl.map(v=>e.jsx(t.SelectItem,{value:String(v),className:"text-xs",children:v===0?"None":v},v))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(t.Select,{value:(o==null?void 0:o.pointStyle)||"circle",onValueChange:v=>x({pointStyle:v}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:pl.map(({value:v,label:w})=>e.jsx(t.SelectItem,{value:v,className:"text-xs",children:w},v))})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(t.SmallSwitch,{checked:m,onCheckedChange:h})]}),m&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(qt,{config:o==null?void 0:o.dataLabels,onChange:g,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const yl=[0,1,2,3,4,5,6,8,10],Nl=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],ss=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Cl(){return t.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type})!=="line"?null:e.jsxs(t.AccordionItem,{value:"line-series",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsx(Sl,{})})]})}function Sl(){const{transformedMetricKeys:s}=zt();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((n,a)=>e.jsx(wl,{metricKey:n,idx:a},n))})}function wl({metricKey:s,idx:n}){var v;const[a,r]=N.useState(!1),i=t.useEditorStore(w=>{var E;return(E=w.card)==null?void 0:E.preferences}),c=t.useEditorStore(w=>{var E,z;return(z=(E=w.card)==null?void 0:E.preferences)==null?void 0:z.datasetOptions}),o=c==null?void 0:c.find(w=>w.idx===n),{setCardPreferences:d}=t.useEditorStore(w=>w.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=((v=o==null?void 0:o.dataLabels)==null?void 0:v.enabled)??!1,u=ss.find(w=>w.value===l)||ss[0];function h(w){const E={idx:n,lineStyle:l,pointRadius:m,pointStyle:p,dataLabels:o==null?void 0:o.dataLabels,...w};if(!o)d({...i||{},datasetOptions:[...c||[],E]});else{const z=c==null?void 0:c.map(D=>D.idx===n?{...D,...E}:D);d({...i||{},datasetOptions:z})}}function g(w){h({dataLabels:{...o==null?void 0:o.dataLabels,enabled:w}})}function b(w){h({dataLabels:w})}return e.jsx(t.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(t.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(t.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:s,children:s})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:e.jsxs("span",{className:t.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(t.TrendingUp,{className:"h-3 w-3"}),u.label.split(" ")[0]]})})]})}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(t.Select,{value:l,onValueChange:w=>h({lineStyle:w}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ss.map(({value:w,label:E})=>e.jsx(t.SelectItem,{value:w,className:"text-xs",children:E},w))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(t.Select,{value:String(m),onValueChange:w=>h({pointRadius:Number(w)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:yl.map(w=>e.jsx(t.SelectItem,{value:String(w),className:"text-xs",children:w===0?"None":w},w))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(t.Select,{value:p,onValueChange:w=>h({pointStyle:w}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Nl.map(({value:w,label:E})=>e.jsx(t.SelectItem,{value:w,className:"text-xs",children:E},w))})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(t.SmallSwitch,{checked:x,onCheckedChange:g})]}),x&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(qt,{config:o==null?void 0:o.dataLabels,onChange:b,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Tl=[0,2,4,6,8,10,12,16,20];function El(){const s=t.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type});return!s||!["bar","horizontalBar","stackedBar"].includes(s)?null:e.jsxs(t.AccordionItem,{value:"bar-series",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsx(Il,{})})]})}function Il(){const{transformedMetricKeys:s}=zt();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((n,a)=>e.jsx(kl,{metricKey:n,idx:a},n))})}function kl({metricKey:s,idx:n}){var g;const[a,r]=N.useState(!1),i=t.useEditorStore(b=>{var v;return(v=b.card)==null?void 0:v.type}),c=t.useEditorStore(b=>{var v;return(v=b.card)==null?void 0:v.preferences}),o=t.useEditorStore(b=>{var v,w;return(w=(v=b.card)==null?void 0:v.preferences)==null?void 0:w.datasetOptions}),d=o==null?void 0:o.find(b=>b.idx===n),{setCardPreferences:l}=t.useEditorStore(b=>b.actions),m=(d==null?void 0:d.borderRadius)??0,p=((g=d==null?void 0:d.dataLabels)==null?void 0:g.enabled)??!1;function x(b){const v={idx:n,borderRadius:m,dataLabels:d==null?void 0:d.dataLabels,...b};if(!d)l({...c||{},datasetOptions:[...o||[],v]});else{const w=o==null?void 0:o.map(E=>E.idx===n?{...E,...v}:E);l({...c||{},datasetOptions:w})}}function u(b){x({dataLabels:{...d==null?void 0:d.dataLabels,enabled:b}})}function h(b){x({dataLabels:b})}return e.jsx(t.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(t.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(t.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:s,children:s})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:m>0&&e.jsxs("span",{className:t.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(t.ChartColumn,{className:"h-3 w-3"}),"r:",m]})})]})}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Bar Style"}),e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Corner Radius"}),e.jsxs(t.Select,{value:String(m),onValueChange:b=>x({borderRadius:Number(b)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Tl.map(b=>e.jsx(t.SelectItem,{value:String(b),className:"text-xs",children:b===0?"None":`${b}px`},b))})]})]})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(t.SmallSwitch,{checked:p,onCheckedChange:u})]}),p&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(qt,{config:d==null?void 0:d.dataLabels,onChange:h,isHorizontal:i==="horizontalBar",showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Dl=[0,1,2,3,4,5,6,8,10],Al=[{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 │"}],Ml=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Ll(){const s=t.useEditorStore(d=>d.card),n=t.useEditorStore(d=>{var l;return(l=d.card)==null?void 0:l.preferences}),a=Me.useEffectiveEditorCardType(),r=n==null?void 0:n.lineStyleConfig,{setCardPreferences:i,updateCardInFrame:c}=t.useEditorActions();if(!s||!["line","area","stackedArea"].includes(a))return null;const o=(d,l)=>{const m={...n||{},lineStyleConfig:{...r,[d]:l}};i(m),c({...s,preferences:m})};return e.jsxs(t.AccordionItem,{value:"line-style",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Line Style"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Default styles for all series. Override per-series in the Series section."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Line Pattern"}),e.jsxs(t.Select,{value:(r==null?void 0:r.lineStyle)||"solid",onValueChange:d=>o("lineStyle",d),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ml.map(({value:d,label:l})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:l},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Point Size"}),e.jsxs(t.Select,{value:String((r==null?void 0:r.pointRadius)??3),onValueChange:d=>o("pointRadius",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Dl.map(d=>e.jsx(t.SelectItem,{value:String(d),className:"text-xs",children:d===0?"None":d},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Point Shape"}),e.jsxs(t.Select,{value:(r==null?void 0:r.pointStyle)||"circle",onValueChange:d=>o("pointStyle",d),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Al.map(({value:d,label:l})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:l},d))})]})]})]})})]})}const Ol=[0,2,4,6,8,10,12,16,20],Fl=[{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%"}],Rl=[{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 Vl(){const s=t.useEditorStore(d=>d.card),n=t.useEditorStore(d=>{var l;return(l=d.card)==null?void 0:l.preferences}),a=Me.useEffectiveEditorCardType(),r=n==null?void 0:n.barStyleConfig,{setCardPreferences:i,updateCardInFrame:c}=t.useEditorActions();if(!s||!["bar","horizontalBar","stackedBar"].includes(a))return null;const o=(d,l)=>{const m={...n||{},barStyleConfig:{...r,[d]:l}};i(m),c({...s,preferences:m})};return e.jsxs(t.AccordionItem,{value:"bar-style",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.ChartColumn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bar Style"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Default styles for all bars. Override per-series in the Series section."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Corner Radius"}),e.jsxs(t.Select,{value:String((r==null?void 0:r.borderRadius)??0),onValueChange:d=>o("borderRadius",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ol.map(d=>e.jsx(t.SelectItem,{value:String(d),className:"text-xs",children:d===0?"None":`${d}px`},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Bar Width"}),e.jsxs(t.Select,{value:String((r==null?void 0:r.barPercentage)??.9),onValueChange:d=>o("barPercentage",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Fl.map(({value:d,label:l})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:l},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Category Width"}),e.jsxs(t.Select,{value:String((r==null?void 0:r.categoryPercentage)??.8),onValueChange:d=>o("categoryPercentage",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Rl.map(({value:d,label:l})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:l},d))})]})]})]})})]})}function Pl(){const s=t.useEditorStore(a=>{var r,i;return(i=(r=a==null?void 0:a.card)==null?void 0:r.preferences)==null?void 0:i.sortChart}),{setSortChart:n}=t.useEditorActions();return e.jsxs(t.AccordionItem,{value:"stacked-sort",children:[e.jsx(t.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.ArrowUpDown,{className:"h-4 w-4"}),"Sort"]})}),e.jsx(t.AccordionContent,{className:"space-y-4 px-1",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Sort Order"}),e.jsx(Xe,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"Ascending",value:"asc"},{label:"Descending",value:"desc"}],value:s||"none",onValueChange:a=>{n(a)}})]})})]})}const Bl=["kpi"],ya={none:"None",previous_period:"Previous Period",same_period_last_year:"Same Period Last Year",start_vs_end:"Start vs End",target:"Target"},as=2;function st(s){return typeof s=="string"?s.trim().toLowerCase():((s==null?void 0:s.id)||(s==null?void 0:s.qualifiedFieldName)||(s==null?void 0:s.name)||(s==null?void 0:s.label)||"").trim().toLowerCase()}function zl(s){if(!(s!=null&&s.name)||!(s!=null&&s.dataType)||s.role==="metric")return!1;const n=t.getDataType(s.dataType);return["date","string","boolean"].includes(n)}function ql(s){return{...s,role:"groupby"}}function _l(){var E,z;const s=t.useEditorStore(D=>D.card),n=t.useEditorStore(D=>D.actions.updateCardConfig),a=Me.useEffectiveEditorCardType(),{scopedFields:r}=t.useScopedFields(),i=((E=s.config)==null?void 0:E.metricColumns)||[],c=((z=s.config)==null?void 0:z.summary)||{},o=c.breakdownDimensions||[],d=Bl.includes(a),l=i.length>0,m=c.enabled===!0,p=d&&l,{comparisonType:x}=t.getEffectiveComparisonSettings(s.config,a),u=ya[x]||ya.none,h=Array.from(new Map(r.filter(zl).map(D=>[st(D),ql(D)])).values()),g=new Set(h.map(D=>st(D))),b=new Set(o.map(D=>st(D)).filter(D=>D&&g.has(D)));if(!d)return null;const v=D=>{n(s.id,{summary:{...c,...D}})},w=(D,T)=>{const I=st(D),M=h.filter(j=>b.has(st(j))),k=T?b.has(I)?M:[...M,D].slice(0,as):M.filter(j=>st(j)!==I);v({breakdownDimensions:k})};return e.jsxs(t.AccordionItem,{value:"summary",className:"border-none",children:[e.jsx(t.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.FileText,{className:"h-4 w-4"}),e.jsx("span",{children:"Summary"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{htmlFor:"summary-enabled",className:"text-xs",children:"Enable Summary"}),!l&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Add at least one metric to enable summary."})]}),e.jsx(t.SmallSwitch,{id:"summary-enabled",checked:m,disabled:!p,onCheckedChange:D=>{if(!D){v({enabled:!1,showOnCard:!1,includeInDashboardSummary:!1});return}v({enabled:!0,showOnCard:c.showOnCard??!0,includeInDashboardSummary:c.includeInDashboardSummary??!0,anomalyEnabled:c.anomalyEnabled??!0})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Comparison"}),e.jsxs("p",{className:"rounded-md border border-border bg-muted/40 px-2 py-1.5 text-xs",children:["Using: ",u]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Comparison is configured from card/metric comparison settings."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"summary-show-on-card",className:"text-xs",children:"Show summary on card"}),e.jsx(t.SmallSwitch,{id:"summary-show-on-card",checked:c.showOnCard===!0,disabled:!m,onCheckedChange:D=>v({showOnCard:D})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"summary-include-rollup",className:"text-xs",children:"Include in dashboard summary"}),e.jsx(t.SmallSwitch,{id:"summary-include-rollup",checked:c.includeInDashboardSummary===!0,disabled:!m,onCheckedChange:D=>v({includeInDashboardSummary:D})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Breakdown Dimensions"}),e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[o.length,"/",as]})]}),h.length===0?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"No dimension fields available for breakdown."}):e.jsx("div",{className:"max-h-40 space-y-2 overflow-y-auto rounded-md border border-border p-2",children:h.map(D=>{const T=st(D),I=b.has(T),M=b.size>=as,k=!m||!I&&M;return e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx(t.Checkbox,{id:`summary-breakdown-${T}`,checked:I,disabled:k,onCheckedChange:j=>w(D,j===!0)}),e.jsx(t.Label,{htmlFor:`summary-breakdown-${T}`,className:"cursor-pointer text-xs",children:D.label||D.name})]},T)})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"summary-anomaly",className:"text-xs",children:"Detect anomalies"}),e.jsx(t.SmallSwitch,{id:"summary-anomaly",checked:c.anomalyEnabled!==!1,disabled:!m,onCheckedChange:D=>v({anomalyEnabled:D})})]})]})]})}const $l=[];function Kl(){var i;const s=t.useEditorStore(c=>c.card),n=((i=s==null?void 0:s.config)==null?void 0:i.metricColumns)??$l,{updateMetricColumn:a,updateCardInFrame:r}=t.useEditorActions();return!s||s.type==="kpi"||n.length===0?null:e.jsxs(t.AccordionItem,{value:"metric-formats",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(hn,{className:"h-4 w-4"}),e.jsx("span",{children:"Metric Formats"})]})}),e.jsx(t.AccordionContent,{className:"space-y-4 pt-2",children:n.map(c=>e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 p-3",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:c.label||c.name}),e.jsx(xs,{value:c.format,onChange:o=>{var d;a(s.id,c.id,{format:o}),r({...s,config:{...s.config,metricColumns:(((d=s.config)==null?void 0:d.metricColumns)||[]).map(l=>l.id===c.id?{...l,format:o}:l)}})}})]},c.id))})]})}const Gl=new Set(["area","bar","bubble","bullet","combo","doughnut","funnel","horizontalBar","line","pie","polarArea","radar","scatter","stackedArea","stackedBar","stackedLine","tornado"]);function Ul(){const s=t.useEditorStore(l=>l.card),n=t.useEditorStore(l=>{var m;return(m=l.card)==null?void 0:m.preferences}),a=Me.useEffectiveEditorCardType(),{setCardPreferences:r,updateCardInFrame:i}=t.useEditorActions();if(!s||!Gl.has(a||""))return null;const c=n==null?void 0:n.tooltipConfig,o=(c==null?void 0:c.formatMode)||(c==null?void 0:c.mode)||"inherit",d=l=>{const m={...n||{},tooltipConfig:{...c||{},...l}};r(m),i({...s,preferences:m})};return e.jsxs(t.AccordionItem,{value:"tooltip-format",className:"border-b-0",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Info,{className:"h-4 w-4"}),e.jsx("span",{children:"Tooltip Format"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Override metric format"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Keep this off to inherit from each metric."})]}),e.jsx(t.SmallSwitch,{checked:o==="override",onCheckedChange:l=>d({formatMode:l?"override":"inherit",mode:l?"override":"inherit"})})]}),o==="override"&&e.jsx(gt,{formatOptions:(c==null?void 0:c.formatOptions)||{},onFormatOptionsChange:l=>d({formatMode:"override",mode:"override",formatOptions:l}),showTitle:!1})]})]})}function qa({mode:s}){const n=t.useEditorStore(a=>{var r;return(r=a.card)==null?void 0:r.type});return e.jsxs(e.Fragment,{children:[n==="combo"&&e.jsx(ul,{}),(n==="area"||n==="stackedArea")&&e.jsx(jl,{}),n==="line"&&e.jsx(Cl,{}),(n==="bar"||n==="horizontalBar"||n==="stackedBar")&&e.jsx(El,{}),e.jsx(Ll,{}),e.jsx(Vl,{}),e.jsx(Yr,{}),s==="config"&&e.jsx(Jr,{}),s==="config"&&e.jsx(_l,{}),e.jsx(Xr,{}),n==="bullet"&&e.jsx(Zr,{}),n==="funnel"&&e.jsx(sl,{}),(n==="bubble"||n==="scatter")&&e.jsx(el,{}),(n==="stackedBar"||n==="stackedLine")&&e.jsx(Pl,{}),e.jsx(Kl,{}),e.jsx(Gr,{}),e.jsx(Ur,{}),e.jsx(Hr,{}),e.jsx(Qr,{}),e.jsx(Ul,{})]})}function Hl(){const s=t.useEditorStore(a=>a.card),n=s==null?void 0:s.type;return n?e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(Bt,{chartType:n}),e.jsx(t.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:e.jsx(qa,{mode:"dev"})})]}):null}function Ql(){const s=t.useEditorStore(a=>a.card.type);function n(){switch(s){case"kpi":return e.jsx(wr,{});case"table":return e.jsx(qr,{});case"map":return e.jsx(kr,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(Va,{})});case"text":return e.jsx($r,{});default:return e.jsx(Hl,{})}}return e.jsxs(t.ScrollArea,{className:"h-full w-full text-sm",children:[n(),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}function Jl(){const s=N.useRef(null),n=N.useRef(null),a=t.useEditorStore(x=>x.isShowingVisual),r=t.useEditorStore(x=>x.isDevMode),i=t.useEditorStore(x=>x.showAIDialog),[c,o]=N.useState(!1),d=a&&!i,l=d&&(!r||c),m=r&&d,p=()=>o(x=>!x);return N.useEffect(()=>{var x,u,h,g;i?((x=s.current)==null||x.resize(0),(u=n.current)==null||u.resize(0)):((h=s.current)==null||h.resize(25),(g=n.current)==null||g.resize(25))},[i]),e.jsxs(t.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:[e.jsx(t.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(Zn,{})}),e.jsx(t.ResizableHandle,{withHandle:!0,className:"data-[panel-group-direction=vertical]:ml-2 data-[panel-group-direction=vertical]:mr-6 data-[panel-group-direction=vertical]:w-auto"}),e.jsx(t.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:l?e.jsxs(t.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(t.ResizablePanel,{ref:s,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(Ql,{})})}),!i&&e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(ua,{visualAsideControl:m?{show:!0,isOpen:c,onToggle:p}:void 0})})]}):e.jsx(ua,{visualAsideControl:m?{show:!0,isOpen:c,onToggle:p}:void 0})})]})}function Yl(s){var we;t.useAIInteractionStore(G=>G.currentAIContext);const[n,a]=N.useState(""),[r,i]=N.useState(null),{authToken:c,tokenProps:o}=t.useSemaphorContext(),d=t.useEditorStore(G=>{var ne;return(ne=G==null?void 0:G.card)==null?void 0:ne.sql}),l=t.useEditorStore(G=>G.isDevMode),m=t.useEditorStore(G=>{var ne;return(ne=G==null?void 0:G.card)==null?void 0:ne.python}),{setCardPython:p,setCardSql:x,setRunSql:u,switchCardType:h,setQueryConfig:g}=t.useEditorActions(),b=t.useEditorStore(G=>G.currentAssitantScope)||[],v=t.useEditorStore(G=>G.userInputForAI),w=t.useEditorStore(G=>G.triggerAIRun),E=t.useEditorStore(G=>G.card),z=t.useEditorStore(G=>G.selectedDatabaseName),D=t.useEditorStore(G=>G.selectedTableName),T=t.useEditorStore(G=>G.selectedConnectionId),I=t.useEditorStore(G=>G.selectedSchemaName),M=t.useDashboardStore(G=>G.dashboard.aiScopeTables),{errorMessage:k,refetch:j,data:S}=t.useDashboardCardQuery(E),{setTriggerAIRun:A,setCurrentAssitantScope:f,setCardConfig:O}=t.useEditorActions(),{selectedDatamodelName:P,connectionType:y,selectedDatamodelId:L}=t.useEditorAside(),C=(we=t.useDashboardQuery().data)==null?void 0:we.assistantProfileId,{messages:V,setMessages:F,regenerate:R,error:$,sendMessage:B,status:K,addToolResult:Y,stop:H,clearError:Z}=t.useChat({transport:new t.DefaultChatTransport({api:`${o.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${c==null?void 0:c.accessToken}`}),body:()=>{const G=t.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:C,isDevMode:l,aiContext:G.currentAIContext,reasoningEffort:G.reasoningEffort,showReasoning:G.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:G,body:ne})=>({body:{...ne,messages:t.cleanupIncompleteMessages(G)}})}),onError:G=>{var ne;if(G.name==="AbortError"||(ne=G.message)!=null&&ne.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)");return}console.error("[Editor Assistant] Stream error:",G)},onToolCall:ae,onFinish({isAbort:G,isDisconnect:ne,isError:ye}){a(""),console.log(G?"[Editor Assistant] Stream aborted by user":ne?"[Editor Assistant] Stream disconnected (network error)":ye?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully")}});N.useEffect(()=>{w&&v&&(B({role:"user",parts:[{type:"text",text:v}]}),A(!1))},[w,v,B,A]);async function ae({toolCall:G}){var ne,ye,se,be,ge,fe,Ne,ve,Te,Le,te,je,me,Ee,he,Re;if(["createChartFromSql","createForecast"].includes(G.toolName)){const Ye=((ne=G.input)==null?void 0:ne.sql)??((ye=G.args)==null?void 0:ye.sql),_e=((se=G.input)==null?void 0:se.python)??((be=G.args)==null?void 0:be.python),Se=((ge=G.input)==null?void 0:ge.chartType)??((fe=G.args)==null?void 0:fe.chartType);h(Se),x(Ye),p(_e),u(!0),Y({tool:G.toolName,toolCallId:G.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(G.toolName==="getUserSql"){if(!d){Y({tool:G.toolName,toolCallId:G.toolCallId,output:{status:"error",message:"No SQL found"}});return}Y({tool:G.toolName,toolCallId:G.toolCallId,output:{status:"success",sql:d,python:m||""}})}else if(G.toolName==="generateQueryConfig"){a("Generating query config...");const Ye=((Ne=G.input)==null?void 0:Ne.chartType)??((ve=G.args)==null?void 0:ve.chartType),_e=((Te=G.input)==null?void 0:Te.queryConfig)??((Le=G.args)==null?void 0:Le.queryConfig);((te=G.input)==null?void 0:te.cardConfig)??((je=G.args)==null||je.cardConfig),h(Ye),O(_e),x(void 0),p(void 0);const Se=await j();if((me=Se==null?void 0:Se.data)!=null&&me.error){Y({tool:G.toolName,toolCallId:G.toolCallId,output:{status:"error",queryConfig:_e,message:(Ee=Se==null?void 0:Se.data)==null?void 0:Ee.error.message}});return}if((he=Se==null?void 0:Se.data)!=null&&he.records){Y({tool:G.toolName,toolCallId:G.toolCallId,output:{status:"success",queryConfig:_e,message:"The data has been visualized"}});return}Y({tool:G.toolName,toolCallId:G.toolCallId,output:{status:"success",queryConfig:_e,message:"The data has been visualized",records:(Re=Se==null?void 0:Se.data)==null?void 0:Re.records}})}else a("Analyzing...")}function ee(G){const ne=t.removeFromScopeArray(b,G);de(ne)}function de(G){const ne=t.sanitizeAIScope(G);f(ne),F(ye=>[...ye,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(ne)}`}]}])}function ce(){const G={databaseName:z||"",schemaName:I||"",tableName:D||"",datamodelId:L||"",datamodelName:t.resolveDatamodelName(P),connectionId:T||"",connectionType:y||""},ne=t.dedup([...b,G]);de(ne)}function W(){const G={databaseName:z||"",schemaName:I||"",tableName:D||"",datamodelName:t.resolveDatamodelName(P),connectionId:T||"",connectionType:y||"",datamodelId:L||""};if(!t.isInAiScopeArray([...M||[],...b],G)||b.length===0){const ye=t.dedup([...M||[],...b,G]).filter(se=>se.connectionId===G.connectionId);de(ye)}}const pe=!["ready","error"].includes(K),X=t.getErrorMessage($);return{messages:V,setMessages:F,sendMessage:B,regenerate:R,isLoading:pe,handleSetAIScope:W,handleAddCurrentTableToScope:ce,removeFromCurrentSelections:ee,currentAssitantScope:b,setCurrentAssitantScope:f,stop:H,status:K,toolStatus:n,llmUsage:r,onFinish:s,errorMessage:X,clearError:Z}}const Wl=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Na({isFullscreen:s,onFullscreenChange:n,fullscreenContainer:a}){const r=N.useRef(null),i=N.useRef(!1),[c,o]=N.useState(!1),[d,l]=N.useState(t.isDevEnv),[m,p]=N.useState(!1),[x,u]=N.useState(!1),[h,g]=N.useState(!1),b=s??h,v=t.useCurrentAIContext(),{setCurrentAIContext:w,setHasEditorEntitySelectionOverride:E}=t.useAIActions(),{clearQueue:z}=t.useQueueActions(),{clearFileAttachments:D}=t.useFileActions(),T=t.useFileAttachments("editor"),{selectedEntities:I}=t.useAssistantContextEntities("editor"),M=t.useEditorStore(le=>le.card.id),k=t.useEditorStore(le=>le.card.dataSource),j=t.useEditorStore(le=>{var Ie;return(Ie=le.card.dataSource)==null?void 0:Ie.selectedEntities}),S=t.useEditorStore(le=>le.actions.setCardSql),A=t.useEditorStore(le=>le.actions.setRunSql),f=t.useEditorStore(le=>le.showAIDialog),O=t.useDashboardStore(le=>le.handleOpenAssistantProfile),{setShowAIDialog:P,setCardPython:y}=t.useEditorActions(),{setDataSource:L}=t.useEditorActions(),{assistantProfile:C}=t.useAssistantProfile(),{messages:V,setMessages:F,sendMessage:R,isLoading:$,stop:B,status:K,llmUsage:Y,errorMessage:H,clearError:Z}=Yl(),[ae,ee]=N.useState(""),de=le=>{ee(le.target.value)},ce=le=>{le.preventDefault();const Ie=ae.trim();if(!Ie&&T.length===0)return;const Ge=[];Ie&&Ge.push({type:"text",text:Ie}),T.forEach(Oe=>{Oe.data&&Ge.push({type:"file",mediaType:Oe.type,filename:Oe.name,url:`data:${Oe.type};base64,${Oe.data}`})}),R({role:"user",parts:Ge}),ee(""),D("editor"),fe({force:!0})},{visibleMessages:W,hasMoreMessages:pe,totalMessageCount:X,loadMoreMessages:we,resetMessageWindow:G}=t.useMessageWindow(V,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:ne,contentRef:ye,isAtBottom:se,hasNewMessages:be,newMessageCount:ge,scrollToBottom:fe,handleScroll:Ne,resetNewMessageCount:ve}=t.useAutoScroll(W,{threshold:40,behavior:"smooth",isStreaming:$});N.useEffect(()=>{var le;f&&!i.current&&((le=r.current)==null||le.focus()),i.current=f},[f]),N.useEffect(()=>{f&&(E(!1),w({selectedEntities:j||[]}))},[M,j,w,E,f]),t.useAutoSubmitQueue({assistantType:"editor",status:K,isLoading:$,sendMessage:R});const{hasActiveTools:Te}=t.useActiveToolStatus(V),Le=N.useCallback(le=>{n==null||n(le),s===void 0&&g(le)},[s,n]);N.useEffect(()=>{if(!b)return;function le(Ie){Ie.key==="Escape"&&Le(!1)}return window.addEventListener("keydown",le),()=>{window.removeEventListener("keydown",le)}},[b,Le]);const te=N.useCallback(le=>{R({role:"user",parts:[{type:"text",text:le}]}),fe({force:!0})},[R,fe]),je=N.useCallback(async()=>{const le=JSON.stringify(V??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(le),t.ue.success("Conversation copied")}catch(Ie){console.error("Failed to copy conversation",Ie),t.ue.error("Unable to copy conversation")}},[V]),me=N.useCallback(()=>{Le(!b)},[b,Le]);function Ee(le,Ie){Ie==="sql"?(S(le),A(!0)):Ie==="python"&&(y(le),A(!0))}function he(){v.selectedEntities.length===0&&w({selectedEntities:I})}function Re(le){he();const Ie={role:"user",parts:[{type:"text",text:le.title+" "+le.subtitle}]};R(Ie)}function Ye(le){he(),R({role:"user",parts:[{type:"text",text:le}]})}function _e(){return e.jsxs(t.DropdownMenu,{children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.Button,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(t.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",children:[e.jsx(t.DropdownMenuLabel,{children:"Options"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsx(t.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:o,children:"Token Usage"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:d,onCheckedChange:l,children:"Tool Invocations"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:m,onCheckedChange:p,children:"System Message"})]})]})}function Se(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const at=(ae==null?void 0:ae.length)===0&&(V==null?void 0:V.filter(le=>le.role==="user").length)===0,nt=e.jsxs("div",{"data-role":"editor-assistant",className:t.cn("flex h-full w-full flex-col justify-between px-6 py-4",b&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Se(),O&&e.jsx(t.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:O,children:(C==null?void 0:C.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[_e(),d&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:je,children:"Copy Conversation"}),e.jsx(t.IconButton,{tooltip:b?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:me,children:b?e.jsx(t.Minimize2,{className:"size-4"}):e.jsx(t.Maximize2,{className:"size-4"})}),e.jsx(t.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{F([]),z("editor"),Z(),G()},children:e.jsx(t.SquarePen,{className:"size-4"})}),e.jsx(t.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{P(!1)},children:e.jsx(t.X,{className:"size-4"})})]})]}),e.jsx(t.CustomScrollArea,{ref:ne,className:"mt-2 flex min-w-0 w-full grow basis-0",onScroll:Ne,children:e.jsxs("div",{ref:ye,className:"min-w-0 space-y-4 py-2 pr-3","data-role":"messages",children:[pe&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:we,className:"text-xs",children:["Load ",Math.min(5,X-W.length)," ","more messages (",X-W.length," ","hidden)"]})}),e.jsx(t.PrintMessages,{messages:W,showTools:d,handleRun:Ee,showSystemMessage:m,onQuickReply:te,disableQuickReplies:$}),!Te&&e.jsx(t.AssistantStatus,{status:K,errorMessage:H})]})}),f&&!se&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(t.Button,{onClick:()=>{fe({force:!0}),ve()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(t.ChevronDown,{className:"h-4 w-4"}),be&&ge>0&&e.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:ge>9?"9+":ge})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[at&&!C&&e.jsx(t.Placeholders,{onClick:Re,placeholders:Wl}),e.jsx("div",{children:at&&C&&e.jsx(t.SeedQuestions,{seedQuestions:C.seedQuestions||[],handleSeedQuestionClick:Ye})})]}),e.jsx(t.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(t.ChatInputWithContext,{ref:r,setInput:ee,stop:B,input:ae,handleInputChange:de,handleSubmit:le=>{he(),ce(le),fe({force:!0})},isLoading:$,status:K,assistantType:"editor",onFocus:()=>{}})]}),Y&&c&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",Y.inputTokens," prompt tokens, ",Y.outputTokens," ","completion tokens, ",Y.totalTokens," total tokens"]})}),e.jsx(t.DataSourceDialog,{incomingSelectedEntities:I,open:x,onOpenChange:u,dataSource:k||t.EMPTY_DATA_SOURCE,dialogMode:"aiContext",onSaveSelectedEntities:le=>{E(!0),w({...v,selectedEntities:le})}})]});return b&&a?dn.createPortal(e.jsx("div",{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:e.jsx("div",{className:"flex h-full w-full",children:nt})}),a):nt}function Xl(s,n,a){if(!n)return!1;const r=n.qualifiedFieldName,i=n.qualifiedEntityName,c=i&&n.name?`${i}.${n.name}`:r;return s.some(o=>{if(!(t.getDataType(o.dataType||"")==="date"))return!1;const l=t.getSelectedDateFilterColumn(o,a),m=l.split("."),p=m[m.length-1]||l,x=m.length>1?m.slice(0,-1).join("."):void 0,u=o.qualifiedTableName||x,h=u?`${u}.${p}`:void 0;return r?h?h===c||h.endsWith(`.${r}`):p===n.name:h?h===c:p===n.name})}const _a=["day","week","month","quarter","year"],Zl=[..._a,"hour","minute","second"],eo=s=>/timestamp|datetime|time/i.test(s||""),to=s=>eo(s)?Zl:_a,hs=({dataType:s})=>t.getFieldIconComponent(s);function so({aliasTemplate:s,onAliasTemplateChange:n}){var l;const[a,r]=N.useState(s),[i,c]=N.useState(!1),o=(l=t.useEditorStore(m=>{var p;return(p=m.card.config)==null?void 0:p.pivotByColumns}))==null?void 0:l[0],d=o?`e.g. Min Sales in {{${o.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Input$1,{placeholder:d,value:i?a:s,onChange:m=>{r(m.target.value),c(!0)},onFocus:()=>c(!0),onPointerDown:m=>m.stopPropagation(),className:"h-8 text-xs",onKeyDown:m=>{m.key==="Enter"&&i&&a!==s?(n(a),c(!1)):m.key==="Escape"&&(r(s),c(!1))},"aria-label":"Edit alias template"}),i&&a!==s&&e.jsxs(e.Fragment,{children:[e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{n(a),c(!1)},children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(s),c(!1)},children:e.jsx(t.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function ao({valueAliases:s,onValueAliasesChange:n}){const[a,r]=N.useState(null),[i,c]=N.useState(""),[o,d]=N.useState(""),l=()=>{n({...s,"":""})},m=x=>{const u={...s};delete u[x],n(u)},p=x=>{const u={...s};delete u[x],u[i]=o,n(u),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(s).map(([x,u],h)=>e.jsx("div",{className:"flex items-center gap-2",children:a===x?e.jsxs(e.Fragment,{children:[e.jsx(t.Input$1,{placeholder:"Value key",value:i,onChange:g=>c(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?p(x):g.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(t.Input$1,{placeholder:"Alias label",value:o,onChange:g=>d(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?p(x):g.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>p(x),children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(t.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(t.Input$1,{placeholder:"Value key",value:x,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(x),c(x),d(u)},"aria-label":"Edit value alias key"}),e.jsx(t.Input$1,{placeholder:"Alias label",value:u,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(x),c(x),d(u)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>m(x),"aria-label":"Remove value alias",children:e.jsx(t.X,{className:"h-3 w-3"})})]})},x+h)),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:l,children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function no({idx:s}){var d;const n=t.useEditorStore(l=>{var m;return(m=l.card)==null?void 0:m.preferences}),a=t.useEditorStore(l=>{var m;return(m=l.card.preferences)==null?void 0:m.datasetOptions}),r=t.useEditorStore(l=>l.actions.setCardPreferences),i=(d=n==null?void 0:n.chartOptions)==null?void 0:d.indexAxis,c=a==null?void 0:a.find(l=>l.idx===s);function o(l,m){(l==="end"||l==="start")&&t.getContrastColor(t.getCanvasBackgroundColor());const p={display:l!=="none",align:l,anchor:l,clamp:!0};if(!c)r({...n,datasetOptions:[...a||[],{idx:m,datalabels:p}]});else{const x={...c};x.datalabels=p;const u=a==null?void 0:a.map(h=>h.idx===m?x:h);r({...n,datasetOptions:u})}}return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{children:e.jsx(t.Tag,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(t.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>o("none",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(t.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>o("start",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(vn,{className:t.cn("h-4 w-4",{"rotate-90":i==="y"})})}),e.jsx("button",{onClick:()=>o("center",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Nn,{className:t.cn("h-4 w-4",{"rotate-90":i==="y"})})}),e.jsx("button",{onClick:()=>o("end",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(yn,{className:t.cn("h-4 w-4",{"rotate-90":i==="y"})})})]})})]})}function ps({children:s,className:n,delayDuration:a}){return e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:a,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:t.cn("overflow-hidden text-ellipsis whitespace-nowrap",n),children:s})}),e.jsx(t.TooltipContent,{children:s})]})})}function ro(s,n=30){return s.length>n?s.slice(0,n)+"...":s}function lo({col:s,idx:n,className:a,iconClassName:r,children:i}){const c=t.useEditorStore(p=>{var x;return(x=p.card)==null?void 0:x.preferences}),o=t.useEditorStore(p=>{var x,u;return(u=(x=p.card)==null?void 0:x.preferences)==null?void 0:u.datasetOptions}),d=o==null?void 0:o.find(p=>p.idx===n),{setCardPreferences:l}=t.useEditorStore(p=>p.actions);function m(p){if(!d)l({...c,datasetOptions:[...o||[],{idx:n,type:p==="area"?"line":p,fill:p==="area"?"origin":""}]});else{const x={...d};x.type=p==="area"?"line":p,x.fill=p==="area"?"origin":"";const u=o==null?void 0:o.map(h=>h.idx===n?x:h);l({...c,datasetOptions:u})}}return e.jsxs("div",{className:t.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[i||e.jsx(ps,{className:"max-w-[100px]",title:s,children:ro(s)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(t.ChartColumnIncreasing,{onClick:()=>m("bar"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(t.ChartLine,{onClick:()=>m("line"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(t.ChartArea,{onClick:()=>m("area"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(no,{idx:n})]})]})}function oo(){const s=t.useEditorStore(d=>d.card.type),n=t.useEditorStore(d=>d.isDevMode),a=t.useEditorStore(d=>d.card.preferences),{setCardPreferences:r}=t.useEditorStore(d=>d.actions);function i(d){var p;const l={datalabels:{display:d!=="none",align:d,anchor:d,clamp:!0}},m={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(p=a==null?void 0:a.chartOptions)==null?void 0:p.plugins,...l}}};r(m)}function c(){var d,l,m;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(t.Select,{value:((m=(l=(d=a==null?void 0:a.chartOptions)==null?void 0:d.plugins)==null?void 0:l.datalabels)==null?void 0:m.anchor)||"none",onValueChange:i,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Data Labels"}),e.jsx(t.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"start",children:"Start"}),e.jsx(t.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"end",children:"End"})]})})]})]})}function o(){var d,l,m;return e.jsx("div",{children:e.jsxs(t.Select,{value:((m=(l=(d=a==null?void 0:a.chartOptions)==null?void 0:d.plugins)==null?void 0:l.datalabels)==null?void 0:m.anchor)||"none",onValueChange:i,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(t.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:n?c():o()})}function io({column:s}){const n=t.useEditorStore(l=>l.card.type),a=t.useEditorStore(l=>{var m,p;return(p=(m=l.card)==null?void 0:m.config)==null?void 0:p.metricColumns}),r=(a==null?void 0:a.map(l=>l.label))||[],i=r==null?void 0:r.find(l=>l===s.label||l===s.name),c=i?r.indexOf(i):-1;function o(){return e.jsx("div",{className:"pr-1",children:i&&e.jsx(lo,{idx:c,col:i,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function d(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(oo,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&o(),["pie","doughnut"].includes(n)&&d()]})}function co({field:s,searchQuery:n="",limit:a=500}){const{authToken:r,tokenProps:i}=t.useSemaphorContext(),c=t.useEditorStore(m=>m.card),o=c==null?void 0:c.dataSource,d=["attribute-values",s.entityName,s.name,n,a],l=t.useQuery({queryKey:d,queryFn:async()=>{if(!(o!=null&&o.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const m={groupByColumns:[{...s,role:"groupby"}],metricColumns:[],filters:n?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:s,operator:"contains",value:n}],groups:[]}:void 0,rowLimit:a},p={connection_id:o.connectionId,cardConfig:m,cardDataSource:o,cache_config:t.getCacheConfig({card:c})};console.log("requestBody",p);const x=await t.postRequestRegular(`${i.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",p);if(x!=null&&x.error)return console.error("Error fetching attribute values:",x.error),[];const u=s.name;return((x==null?void 0:x.records)||[]).map(g=>{const b=g[u]||g[s.alias||u]||g[s.label];return{id:b||"",value:b||"",label:String(b||"(empty)")}})}catch(m){return console.error("Error fetching attribute values:",m),[]}},enabled:!!s&&!!(o!=null&&o.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:l.data||[],isLoading:l.isLoading,isFetching:l.isFetching,isError:l.isError,error:l.error,refetch:l.refetch}}function $a({open:s,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:i,onSave:c}){var z,D;const o=!!i,[d,l]=N.useState(o?"values":"fields"),[m,p]=N.useState(""),[x,u]=N.useState({id:(i==null?void 0:i.id)||t.v4(),field:(i==null?void 0:i.field)||null,selectedValues:i?Array.isArray(i.value)?i.value:[i.value]:[]}),h=a.filter(T=>{var M;return o?!1:!((M=r==null?void 0:r.conditions)==null?void 0:M.some(k=>k.field.id===T.id))&&T.label.toLowerCase().includes(m.toLowerCase())}),g=T=>{u({...x,field:T}),l("values")},b=()=>{if(x.field&&x.selectedValues.length>0){const T={id:x.id,field:x.field,operator:"in",value:x.selectedValues};let I;if(o){const M=((r==null?void 0:r.conditions)||[]).map(k=>k.id===i.id?T:k);I={...r,conditions:M}}else{const M=(r==null?void 0:r.conditions)||[];I={id:(r==null?void 0:r.id)||t.v4(),logicalOperator:"AND",negate:!1,conditions:[...M,T],groups:[]}}c(I),n(!1)}},v=()=>{if(!o||!i)return;const T=((r==null?void 0:r.conditions)||[]).filter(I=>I.id!==i.id);if(T.length>0){const I={...r,conditions:T};c(I)}else c(void 0);n(!1)},w=T=>{u({...x,selectedValues:T})},E=()=>{o&&i?(u({id:i.id,field:i.field,selectedValues:Array.isArray(i.value)?i.value:[i.value]}),l("values")):(u({id:t.v4(),field:null,selectedValues:[]}),l("fields")),p("")};return N.useEffect(()=>{s&&E()},[s,o,i]),e.jsx(t.Dialog,{open:s,onOpenChange:n,children:e.jsxs(t.DialogContent,{className:"max-w-2xl",children:[e.jsx(t.DialogHeader,{children:e.jsx(t.DialogTitle,{children:o?`Edit Filter: ${(z=x.field)==null?void 0:z.label}`:d==="fields"?"Select Field to Filter":`Select Values for ${(D=x.field)==null?void 0:D.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!o&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&d==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Current Filters:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.conditions.map(T=>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:[T.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(T.value)?`${T.value.length} values`:String(T.value)})]},T.id))})]}),d==="fields"&&!o?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(t.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(t.Input$1,{placeholder:"Search fields...",value:m,onChange:T=>p(T.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:h.map(T=>e.jsxs(t.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>g(T),children:[e.jsx(hs,{dataType:t.getDataType(T.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:T.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[T.entityName,".",T.name]})]})]},T.id))}),h.length===0&&m&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',m,'"']}),h.length===0&&!m&&a.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(uo,{field:x.field,selectedValues:x.selectedValues,onValuesChange:w,onBack:o?void 0:()=>l("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:o?e.jsx(t.Button,{variant:"destructive",onClick:v,children:"Delete Filter"}):e.jsx(t.Button,{variant:"outline",onClick:E,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(t.Button,{onClick:b,disabled:!x.field||x.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function uo({field:s,selectedValues:n,onValuesChange:a,onBack:r}){const[i,c]=N.useState(""),{values:o,isLoading:d,isFetching:l}=co({field:s,searchQuery:i,limit:500}),m=i?o.filter(u=>String(u.value).toLowerCase().includes(i.toLowerCase())):o,p=u=>{const h=n.includes(u);a(h?n.filter(g=>g!==u):[...n,u])},x=()=>{n.length===m.length&&m.length>0?a([]):a(m.map(u=>u.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:r,children:"← Back"}),e.jsxs(t.Label,{className:"text-sm font-medium",children:["Select values for ",s.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(t.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(t.Input$1,{placeholder:"Search values...",value:i,onChange:u=>c(u.target.value),className:"pl-10"})]}),d||l?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(t.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx(t.Checkbox,{checked:n.length===m.length&&m.length>0,onCheckedChange:x}),e.jsxs(t.Label,{className:"text-sm",children:["Select All (",m.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:m.map(u=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>p(u.value),children:[e.jsx(t.Checkbox,{checked:n.includes(u.value),onCheckedChange:()=>p(u.value)}),e.jsx(ps,{className:"text-sm",children:u.label})]},u.id))})]})]})}function mo({field:s,zone:n,index:a,sortDirection:r,onSortDirectionChange:i,hasPivotColumns:c=!1,cardType:o}){var vs,ys,Ns,Cs,Ss,ws,Ts,Es,Is,ks,Ds,As,Ms,Ls,Os,Fs,Rs,Vs,Ps,Bs,zs,qs,_s,$s,Ks,Gs,Us,Hs,Qs,Js,Ys,Ws,Xs,Zs;const{attributes:d,listeners:l,setNodeRef:m,transform:p,transition:x,isDragging:u}=t.useSortable({id:s.id}),h=t.useEditorStore(q=>q.card),g=t.useEditorStore(q=>q.frame),{scopedFields:b,isLoading:v}=t.useScopedFields(),{userContext:w}=t.useCurrentUserInfo(),E=(w==null?void 0:w.type)==="organization",z=(vs=h.dataSource)==null?void 0:vs.semanticDomainId,{promoteMetric:D}=t.usePromoteCalculatedMetricToDomain({domainId:z}),{updateLabel:T,handleAggregationChange:I,handleDateFormatChange:M,handleGranularityChange:k,handleAliasTemplateChange:j,handleValueAliasesChange:S,handleMetricFormatChange:A,removeField:f,handleMetricComparisonChange:O,handleMetricWindowTransformChange:P,handleMetricWindowOrderByChange:y,handleMetricWindowDirectionChange:L,handleMetricWindowPartitionToggle:C,handleMetricMovingAverageWindowSizeChange:V,handleMetricMovingAverageMinPeriodsChange:F,handleMetricPreviousPeriodDeltaModeChange:R,handleMetricPercentOfTotalScopeChange:$,handleMetricPercentOfTotalOutputChange:B,handleKpiShowTrendlineChange:K,handleKpiTrendlineWindowChange:Y,handleKpiTrendlineGranularityChange:H,handleMetricTargetValueChange:Z}=t.useFieldManagement(h),[ae,ee]=N.useState(!1),[de,ce]=N.useState(()=>{var q;return!!((q=s.parameters)!=null&&q.windowTransform)}),[W,pe]=N.useState(!1),[X,we]=N.useState(!1),[G,ne]=N.useState(null),ye=N.useMemo(()=>{const q=re=>re!=null&&re.startsWith("card-source-")?re.replace("card-source-",""):re,Q=q(s.id),ie=b.find(re=>{if(s.qualifiedFieldName&&re.qualifiedFieldName&&re.qualifiedFieldName===s.qualifiedFieldName||s.qualifiedEntityName&&re.qualifiedEntityName&&re.qualifiedEntityName===s.qualifiedEntityName&&re.name===s.name)return!0;const Ce=q(re.id);return!!(Q&&Ce&&Q===Ce)});return{dataType:(ie==null?void 0:ie.dataType)||s.dataType,resolvedFromScopedField:!!ie}},[s.dataType,s.id,s.name,s.qualifiedEntityName,s.qualifiedFieldName,b]),se=to(ye.dataType),[be,ge]=N.useState(s.dateFormat||"YYYY-MM-DD"),[fe,Ne]=N.useState(s.customFormat||""),[ve,Te]=N.useState(!!s.customFormat),Le=N.useRef(null),[te,je]=N.useState(s.aliasTemplate||""),[me,Ee]=N.useState(s.valueAliases||{}),[he,Re]=N.useState((ys=s.parameters)==null?void 0:ys.filters),Ye=q=>{q==="custom"?Te(!0):(Te(!1),ge(q),(n==="groupBy"||ot)&&M(a,q,"",n))},_e=q=>{Ne(q),(n==="groupBy"||ot)&&M(a,"custom",q,n)},Se=q=>{var re;const ie=(re=t.getDateFormatOptionsForGranularity(q)[0])==null?void 0:re.value;ie&&!ve&&(ge(ie),n==="groupBy"&&M(a,ie,"",n)),n==="groupBy"&&k(a,q)},at=q=>{je(q),n==="metrics"&&j(a,q)},nt=q=>{Ee(q),n==="metrics"&&S(a,q)},le=q=>{T(n,a,q)},Ie=q=>q!=null&&q.startsWith("card-source-")?q.replace("card-source-",""):q,Ge=(q,Q,ie)=>{const re=Ie(q.id),Ce=Ie(Q.id);return re&&Ce&&re===Ce?!0:q.name===Q.name&&q.role===Q.role},Oe=t.getExpressionFieldKind(s),ke=t.getFieldExpressionAnnotation(s),jt=Oe==="domain_calculated"||Oe==="user_calculated",$e=Oe==="user_calculated"?(Ns=g==null?void 0:g.calculatedFields)==null?void 0:Ns.find(q=>Ge(q,s)):void 0,bt=Oe==="user_calculated"&&(s.fieldScope==="dashboard"||s.fieldScope===void 0&&!!$e),et=Oe==="domain_calculated",_t=et?"domain":bt?"dashboard":"card",We=et?s:bt&&$e?$e:s,vt=q=>{var Q;if(Re(q),n==="metrics"){const ie={...s,parameters:{...s.parameters,filters:q}},re=[...((Q=h.config)==null?void 0:Q.metricColumns)||[]];re[a]=ie,t.useEditorStore.getState().actions.updateCardConfig(h.id,{metricColumns:re})}pe(!1)},Tt=async q=>{await D(q),ln()},rt=()=>{f(n,a)},$t={transform:t.CSS.Transform.toString(p),transition:x},lt=t.getDataType(ye.dataType||s.dataType),yt=lt==="date",Et=o==="kpi",ot=n==="detailColumns",it=(Cs=h.config)==null?void 0:Cs.metricColumns,Ue=(Ss=h.config)==null?void 0:Ss.groupByColumns,ct=t.useDashboardStore(q=>{var Q;return(Q=q.dashboard)==null?void 0:Q.filters}),dt=t.useDashboardStore(q=>q.filterValues),ze=s.granularity||"day",Kt=se.includes(ze)?ze:"day",Nt=n==="groupBy"&&!se.includes(ze),Ct=t.getDateFormatOptionsForGranularity(Kt),It=ve?"custom":Ct.some(q=>q.value===be)?be:((ws=Ct[0])==null?void 0:ws.value)??"YYYY-MM-DD";N.useEffect(()=>{var ie;if(v||!Nt){Le.current=null;return}const q=`${s.id}:${ze}:${ye.dataType||s.dataType||""}:${a}`;if(Le.current===q)return;Le.current=q;const Q="day";if(k(a,Q),!ve){const re=(ie=t.getDateFormatOptionsForGranularity(Q)[0])==null?void 0:ie.value;re&&(ge(re),M(a,re,"",n))}},[s.dataType,s.id,M,k,Nt,a,ve,v,ze,ye.dataType,n]);const kt=!!o&&t.COMPARISON_SUPPORTED_CHART_TYPES.includes(o),Gt=o==="kpi"||o==="table",He=N.useMemo(()=>Ue==null?void 0:Ue.find(q=>t.getDataType(q.dataType||"")==="date"),[Ue]),Dt=N.useMemo(()=>(Ue||[]).some(q=>t.getDataType(q.dataType||"")==="date"),[Ue]),At=N.useMemo(()=>{var re;if(!He)return!1;const q=(re=h.config)==null?void 0:re.filters;if(!q)return!1;const Q=Ce=>{const Ae=Ce.field;return Ae?He.id&&Ae.id===He.id||He.qualifiedFieldName&&Ae.qualifiedFieldName===He.qualifiedFieldName?!0:Ae.name===He.name:!1},ie=Ce=>Ce.conditions.some(qe=>t.getDataType(qe.field.dataType||"")==="date"&&Q(qe))?!0:Ce.groups.some(qe=>ie(qe));return ie(q)},[(Ts=h.config)==null?void 0:Ts.filters,He]),Ut=N.useMemo(()=>Xl(ct||[],He,dt),[ct,dt,He]),tt=At||Ut,De=s,ut=((Is=(Es=De.parameters)==null?void 0:Es.windowTransform)==null?void 0:Is.function)||"none",_=t.isMetricTransformEnabled(De),U=_?ut:null,J=t.supportsMetricTransformForMetric({cardType:o||"table",cardConfig:h.config||{},metric:De,transformMode:U||"running_total"}),ue=!!De.comparisonType&&De.comparisonType!=="none",oe=t.getRunningTotalOrderByCandidates(Ue||[]),xe=((As=(Ds=(ks=De.parameters)==null?void 0:ks.windowTransform)==null?void 0:Ds.orderBy)==null?void 0:As.fieldId)||"",Fe=((Os=(Ls=(Ms=De.parameters)==null?void 0:Ms.windowTransform)==null?void 0:Ls.orderBy)==null?void 0:Os.direction)||"asc",Ve=oe.find(q=>q.id===xe),Ke=U==="running_total"||U==="moving_average"||U==="previous_period_delta",mt=_&&Ke&&!!Ve&&t.getDataType(Ve.dataType||"")!=="date",xt=t.getDefaultRunningTotalPartitionByFieldIds({cardType:o||"table",cardConfig:h.config||{},orderByFieldId:xe||void 0}),Pe=new Set(((Rs=(Fs=De.parameters)==null?void 0:Fs.windowTransform)==null?void 0:Rs.partitionByFieldIds)||xt),ht=o==="pivotTable"||t.isSubtotalEnabledAggregateTable(o||"table",h.config||{}),Mt=[...(Ue||[]).filter(q=>q.id&&(!Ke||q.id!==xe)),...ht?(((Vs=h.config)==null?void 0:Vs.pivotByColumns)||[]).filter(q=>q.id):[]],Lt=((zs=(Bs=(Ps=De.parameters)==null?void 0:Ps.windowTransform)==null?void 0:Bs.movingAverage)==null?void 0:zs.windowSize)||7,Ga=(($s=(_s=(qs=De.parameters)==null?void 0:qs.windowTransform)==null?void 0:_s.movingAverage)==null?void 0:$s.minPeriods)||1,Ua=((Us=(Gs=(Ks=De.parameters)==null?void 0:Ks.windowTransform)==null?void 0:Gs.previousPeriodDelta)==null?void 0:Us.mode)||"absolute",gs=((Js=(Qs=(Hs=De.parameters)==null?void 0:Hs.windowTransform)==null?void 0:Qs.percentOfTotal)==null?void 0:Js.scope)||"grand_total",Ha=((Xs=(Ws=(Ys=De.parameters)==null?void 0:Ys.windowTransform)==null?void 0:Ws.percentOfTotal)==null?void 0:Xs.output)||"percent",Qa=N.useMemo(()=>(it||[]).some(q=>q.comparisonType==="start_vs_end"),[it]);N.useEffect(()=>{_&&ce(!0)},[_]);const Ja=n!=="pivotBy",Ya=yt&&n==="groupBy"&&(!Et||Qa),Wa=!Et&&yt&&(n==="groupBy"||ot),Xa=o==="kpi"&&yt&&n==="groupBy",Za=n==="metrics",js=kt&&n==="metrics",en=()=>{const q=s,Q=n==="metrics"&&jt;return e.jsxs("div",{className:"space-y-1",children:[!Q&&e.jsx("div",{title:`${s.entityName}.${s.name}`,onPointerDown:ie=>{ie.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-muted-foreground/80",children:`${s.entityName}.${s.name}`}),Q&&q.calculatedFormula&&e.jsxs("div",{title:t.formatDisplayFormula(q.calculatedFormula),onPointerDown:ie=>{ie.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap rounded bg-muted/50 px-1.5 py-0.5 font-mono text-xs text-primary",children:["= ",t.formatDisplayFormula(q.calculatedFormula)]})]})},tn=()=>Ja?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(Je,{value:s.label??"",onSave:le,placeholder:"Display label...",type:"text"})]}):null,bs=()=>Ya?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(t.Select,{value:Kt,onValueChange:Se,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select granularity..."})}),e.jsx(t.SelectContent,{children:se.map(q=>e.jsx(t.SelectItem,{className:"text-xs",value:q,children:t.toTitleCase(q)},q))})]})]}):null,sn=()=>Wa?e.jsxs(e.Fragment,{children:[bs(),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Date Format"}),e.jsxs(t.Select,{value:It,onValueChange:Ye,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select date format..."})}),e.jsx(t.SelectContent,{children:Ct.map(q=>e.jsx(t.SelectItem,{className:"text-xs",value:q.value,children:q.label},q.value))})]}),ve&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(t.Input$1,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:fe,onChange:q=>{q.stopPropagation(),_e(q.target.value)},onClick:q=>q.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}):null,an=()=>{var Q,ie,re,Ce;const q=Xa;return q?e.jsx(e.Fragment,{children:q&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(t.SmallSwitch,{checked:((Q=h.config)==null?void 0:Q.showTrendline)||!1,onCheckedChange:K})]})}),((ie=h.config)==null?void 0:ie.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(t.Input$1,{type:"number",min:"1",max:"365",value:((re=h.config)==null?void 0:re.trendlineWindow)||30,onChange:Ae=>{const qe=parseInt(Ae.target.value)||30;Y(qe)},className:"h-8 text-xs",placeholder:"30"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Granularity"}),e.jsxs(t.Select,{value:((Ce=h.config)==null?void 0:Ce.trendlineGranularity)||"day",onValueChange:H,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"day",children:"Day"}),e.jsx(t.SelectItem,{value:"week",children:"Week"}),e.jsx(t.SelectItem,{value:"month",children:"Month"})]})]})]})]})]})}):null},nn=()=>{if(!Za)return null;const q=jt;return e.jsxs(e.Fragment,{children:[q&&E&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Formula"}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>we(!0),children:[e.jsx(t.Pencil,{className:"mr-2 h-3 w-3"}),"Edit Formula"]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(t.Select,{value:s.aggregate,onValueChange:Q=>{I(a,Q)},disabled:q,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select function..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(t.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),t.getDataType(s.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(t.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(t.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(t.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(t.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Number Format"}),e.jsx(xs,{value:De.format,onChange:Q=>A(a,Q),showTitle:!1})]}),e.jsx(t.Collapsible,{open:de,onOpenChange:ce,children:e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-muted/20 p-2.5",children:[e.jsx(t.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between rounded-sm px-0.5 py-0.5 text-left",children:[e.jsx("div",{className:"text-xs font-medium text-foreground",children:"Metric Transform"}),e.jsxs("div",{className:"flex items-center text-[11px] text-muted-foreground",children:[!de&&e.jsx("span",{className:"mr-2",children:_?t.toTitleCase(ut.replace(/_/g," ")):"None"}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 transition-transform",de?"rotate-180":"")})]})]})}),e.jsxs(t.CollapsibleContent,{className:"space-y-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Transform"}),e.jsxs(t.Select,{value:_?ut:"none",onValueChange:Q=>P(a,Q),disabled:!J.supported&&!_,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select transform..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"none",children:"None"}),e.jsx(t.SelectItem,{value:"running_total",disabled:ue,children:"Running Total"}),e.jsx(t.SelectItem,{value:"moving_average",disabled:ue,children:"Moving Average"}),e.jsx(t.SelectItem,{value:"previous_period_delta",disabled:ue,children:"Previous Period Delta"}),e.jsx(t.SelectItem,{value:"percent_of_total",disabled:ue,children:"Percent of Total"})]})]}),!J.supported&&!_&&e.jsx("div",{className:"text-xs text-muted-foreground",children:J.reason}),ue&&!_&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"Disable comparison to enable metric transforms."})]}),_&&e.jsxs(e.Fragment,{children:[Ke&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Order By"}),e.jsxs(t.Select,{value:xe,onValueChange:Q=>y(a,Q),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select order field..."})}),e.jsx(t.SelectContent,{children:oe.filter(Q=>!!Q.id).map(Q=>e.jsx(t.SelectItem,{value:Q.id,className:"text-xs",children:Q.label||Q.name},Q.id))})]}),!xe&&e.jsx("div",{className:"text-xs text-amber-700",children:"No date trend detected. Select an order field."}),mt&&e.jsx("div",{className:"text-xs text-amber-700",children:"No date trend detected. The transform will follow the selected order field."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Direction"}),e.jsxs(t.Select,{value:Fe,onValueChange:Q=>L(a,Q),disabled:!xe,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select direction..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"asc",children:"Ascending"}),e.jsx(t.SelectItem,{className:"text-xs",value:"desc",children:"Descending"})]})]})]})]}),U==="moving_average"&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Window Size"}),e.jsx(t.Input$1,{type:"number",min:1,className:"h-8 text-xs",value:Lt,onChange:Q=>V(a,Number(Q.target.value))}),e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Min Periods"}),e.jsx(t.Input$1,{type:"number",min:1,max:Lt,className:"h-8 text-xs",value:Ga,onChange:Q=>F(a,Number(Q.target.value))})]}),U==="previous_period_delta"&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Output"}),e.jsxs(t.Select,{value:Ua,onValueChange:Q=>R(a,Q),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select output..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"absolute",children:"Absolute Delta"}),e.jsx(t.SelectItem,{value:"percent",children:"Percent Delta"})]})]})]}),U==="percent_of_total"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Scope"}),e.jsxs(t.Select,{value:gs,onValueChange:Q=>$(a,Q),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select scope..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"grand_total",children:"Grand Total"}),e.jsx(t.SelectItem,{value:"partition_total",children:"Partition Total"})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Output"}),e.jsxs(t.Select,{value:Ha,onValueChange:Q=>B(a,Q),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select output..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"percent",children:"Percent"}),e.jsx(t.SelectItem,{value:"fraction",children:"Fraction"})]})]})]})]}),(U==="running_total"||U==="moving_average"||U==="previous_period_delta"||U==="percent_of_total"&&gs==="partition_total")&&Mt.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Reset By"}),e.jsx("div",{className:"space-y-1",children:Mt.map(Q=>{const ie=!!Q.id&&Pe.has(Q.id);return e.jsxs("button",{type:"button",onClick:()=>Q.id&&C(a,Q.id),className:t.cn("flex h-7 w-full items-center justify-between rounded border px-2 text-xs",ie?"border-primary bg-primary/5 text-primary":"border-border text-muted-foreground"),children:[e.jsx("span",{children:Q.label||Q.name}),ie?e.jsx(t.Check,{className:"h-3 w-3"}):null]},Q.id)})})]})]})]})]})}),js&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(t.Select,{value:De.comparisonType||"none",disabled:_,onValueChange:Q=>O(a,Q),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"none",children:"No Comparison"}),(()=>{const Q=!Dt||!tt,ie=Dt?tt?void 0:"Add a date filter to enable":"Add a date groupBy to enable",re=(Ce,Ae)=>e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.SelectItem,{value:Ce,disabled:Q,title:ie,children:Ae})}),Q&&ie&&e.jsx(t.TooltipContent,{side:"right",children:ie})]})});return e.jsxs(e.Fragment,{children:[re("previous_period","Previous Period"),re("same_period_last_year","Same Period Last Year"),re("start_vs_end","Start vs End")]})})(),Gt&&e.jsx(t.SelectItem,{value:"target",children:"Target"})]})]})]}),js&&De.comparisonType==="target"&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(t.Input$1,{type:"number",value:De.targetValue!==void 0&&De.targetValue!==null?String(De.targetValue):"",onChange:Q=>{const ie=Q.target.value;if(ie===""){Z(a,void 0);return}const re=Number(ie);Z(a,Number.isFinite(re)?re:void 0)},className:"h-8 text-xs",placeholder:"Enter target value..."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(he==null?void 0:he.conditions)&&he.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:he.conditions.map(Q=>e.jsxs("div",{className:"flex cursor-pointer items-center gap-2 rounded bg-muted/50 p-2 text-xs transition-colors hover:bg-muted/70",onClick:()=>{ne(Q),pe(!0)},children:[e.jsxs("span",{className:"font-medium",children:[Q.field.label,":"]}),e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"cursor-help text-muted-foreground",children:Array.isArray(Q.value)?Q.value.length===1?String(Q.value[0]):Q.value.length<=2?Q.value.join(", "):`${Q.value.slice(0,2).join(", ")} +${Q.value.length-2}`:String(Q.value)})}),Array.isArray(Q.value)&&Q.value.length>1&&e.jsx(t.TooltipContent,{side:"top",className:"max-w-[300px]",children:e.jsxs("div",{className:"text-xs",children:[e.jsxs("div",{className:"mb-1 font-medium",children:["Selected values (",Q.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:Q.value.map((ie,re)=>e.jsx("div",{children:String(ie)},re))})]})})]})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:ie=>{var Ce;ie.stopPropagation();const re=he.conditions.filter(Ae=>Ae.id!==Q.id);if(re.length>0){const Ae={...he,conditions:re};vt(Ae)}else if(Re(void 0),n==="metrics"){const Ae={...s,parameters:{...s.parameters,filters:void 0}},qe=[...((Ce=h.config)==null?void 0:Ce.metricColumns)||[]];qe[a]=Ae,t.useEditorStore.getState().actions.updateCardConfig(h.id,{metricColumns:qe})}},children:e.jsx(t.X,{className:"h-3 w-3"})})]},Q.id))}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{ne(null),pe(!0)},children:[e.jsx(t.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(io,{column:s}),c&&e.jsxs(e.Fragment,{children:[e.jsx(so,{aliasTemplate:te,onAliasTemplateChange:at}),e.jsx(ao,{valueAliases:me,onValueAliasesChange:nt})]})]})},{columns:rn=[],refetch:ln}=t.useColumns(),on=(he==null?void 0:he.conditions)&&he.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:m,style:$t,className:t.cn("group mx-auto flex w-full flex-col gap-2 rounded-md border border-border/55 bg-background p-2 transition-colors duration-150","hover:border-border/80 hover:bg-muted/20",ae&&"border-border/80 bg-muted/20 shadow-[inset_0_1px_0_rgba(255,255,255,0.35)]",u&&"z-50 scale-95 opacity-50","cursor-default"),children:[e.jsxs("div",{className:"flex min-w-0 grow items-center gap-2",children:[e.jsx("button",{type:"button",...d,...l,className:"flex shrink-0 cursor-grab items-center rounded-sm p-0.5 text-muted-foreground transition-colors hover:text-foreground active:cursor-grabbing","aria-label":`Drag ${t.getMetricDisplayLabel(s)}`,onClick:q=>{q.stopPropagation()},children:e.jsx(t.GripVertical,{className:"h-3.5 w-3.5"})}),e.jsxs("div",{className:"relative shrink-0",children:[e.jsx(hs,{dataType:lt}),ke&&e.jsx("span",{className:t.cn(t.FIELD_EXPRESSION_BADGE_BASE_CLASS,ke.badgeClassName),children:ke.label})]}),e.jsx(ps,{className:t.cn("w-[140px] min-w-0 flex-1 text-sm text-foreground/95",on&&"w-[120px] min-w-0"),children:t.getMetricDisplayLabel(s)}),n==="metrics"&&((Zs=he==null?void 0:he.conditions)==null?void 0:Zs.length)&&!ae&&e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 text-xs text-primary/90",children:[e.jsx(t.Filter,{className:"h-3 w-3"}),e.jsx("span",{children:he.conditions.length})]})}),e.jsx(t.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:he.conditions.map(q=>e.jsxs("div",{children:[q.field.label,":"," ",Array.isArray(q.value)?`${q.value.length} values`:String(q.value)]},q.id))})})]})}),n!=="sortBy"&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-foreground/55 hover:text-foreground",onClick:q=>{q.stopPropagation(),ee(!ae)},children:e.jsx(t.ChevronDown,{className:`h-3 w-3 transition-transform ${ae?"rotate-180":""}`})}),n==="sortBy"&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-foreground/55 hover:text-foreground",onClick:q=>{q.stopPropagation(),i(r==="asc"?"desc":"asc")},children:r==="asc"?e.jsx(t.ArrowUp,{className:"h-3 w-3"}):e.jsx(t.ArrowDown,{className:"h-3 w-3"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-foreground/55 hover:text-foreground",onClick:q=>{q.stopPropagation(),rt()},children:e.jsx(t.X,{className:"h-2.5 w-2.5"})})]}),ae&&e.jsxs("div",{className:"space-y-3 rounded-md bg-muted/20 p-2.5",children:[en(),tn(),o==="kpi"&&bs(),sn(),an(),nn()]})]}),W&&e.jsx($a,{open:W,onOpenChange:q=>{pe(q),q||ne(null)},availableFields:rn,existingFilters:he,editingCondition:G,onSave:q=>{var Q;if(q)vt(q);else if(Re(void 0),n==="metrics"){const ie={...s,parameters:{...s.parameters,filters:void 0}},re=[...((Q=h.config)==null?void 0:Q.metricColumns)||[]];re[a]=ie,t.useEditorStore.getState().actions.updateCardConfig(h.id,{metricColumns:re})}ne(null)}}),X&&n==="metrics"&&jt&&e.jsx(t.CalculatedFieldEditor,{open:X,onOpenChange:we,availableFields:b,existingField:We,existingFieldScope:_t,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:q=>{var pt;if(q.role!=="metric")return;const Q=[...((pt=h.config)==null?void 0:pt.metricColumns)||[]];Q[a]=q;const{frame:ie,actions:re}=t.useEditorStore.getState();if(re.updateCardConfig(h.id,{metricColumns:Q}),!t.isCalculatedMetric(q))return;const Ce=ie.calculatedFields||[],Ae=Ce.findIndex(Qe=>Qe.name===s.name&&Qe.role===s.role);if(Ae<0)return;const qe=Ce.map((Qe,Ot)=>Ot===Ae?{...q,id:Qe.id}:Qe);re.updateFrame({calculatedFields:qe})},onSaveToDashboard:q=>{var Ot;if(q.role!=="metric")return;const{frame:Q,actions:ie}=t.useEditorStore.getState(),re=Q.calculatedFields||[],Ce=re.findIndex(Ht=>Ge(Ht,q)),Ae=Ce>=0&&re[Ce].id!==q.id?{...q,id:re[Ce].id}:q,qe=Ce>=0?re.map((Ht,cn)=>cn===Ce?Ae:Ht):[...re,Ae];ie.updateFrame({calculatedFields:qe});const pt=[...((Ot=h.config)==null?void 0:Ot.metricColumns)||[]],Qe=s;pt[a]={...Ae,id:Qe.id,aliasTemplate:Qe.aliasTemplate,valueAliases:Qe.valueAliases,parameters:Qe.parameters,customFormat:Qe.customFormat},ie.updateCardConfig(h.id,{metricColumns:pt})},onPromoteMetricToDomain:z&&E?Tt:void 0,domainId:z,cardId:h.id})]})}function xo({concept:s}){const n=()=>{switch(s){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-100 text-xs font-medium dark:bg-blue-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/50 text-xs font-medium dark:bg-blue-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/30 text-xs font-medium dark:bg-blue-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/20 text-xs font-medium dark:bg-blue-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Pivot Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metric Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});case"detailColumns":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields to display as columns in the detail table. No aggregation applied - shows raw values from the database."})]});default:return null}};return e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:300,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(t.TooltipContent,{side:"right",align:"start",className:"p-3",children:n()})]})})}const ho={groupBy:Pt,pivotBy:is,metrics:In,detailColumns:t.Table2,sortBy:t.ArrowUpDown};function wt({zone:s,fields:n,label:a,placeholder:r,shouldShow:i,hasPivotColumns:c=!1,activeField:o=null}){const{isOver:d,setNodeRef:l}=t.useDroppable({id:s}),{updateSortByColumn:m}=t.useEditorActions(),p=t.useEditorStore(w=>w.card),x=t.useEditorStore(w=>w.card.type),u=n.length>0,h=N.useMemo(()=>!o||!d?!0:t.validateFieldForChartType(o,s,x).isValid,[o,d,s,x]),g=(w,E)=>{var D;!((D=p.config)!=null&&D.sortByColumns)||p.config.sortByColumns.findIndex(T=>T.id===w)===-1||m(p.id,w,{direction:E})};if(s==="sortBy"&&i===!1)return null;const b=s!=="sortBy"&&x!=="kpi",v=ho[s]||t.Plus;return e.jsxs("div",{className:"mb-3 w-full",children:[e.jsx("div",{className:"mb-1.5 flex items-center gap-2",children:e.jsx(t.Label,{className:t.cn("block text-sm font-medium text-foreground",{}),children:a})}),e.jsx("div",{ref:l,className:t.cn("rounded-lg border p-0.5 transition-colors duration-150",{"border-green-500 bg-green-50 shadow-[0_0_0_1px_rgba(34,197,94,0.18)] dark:bg-green-950":d&&h,"border-red-500 bg-red-50 shadow-[0_0_0_1px_rgba(239,68,68,0.18)] dark:bg-red-950":d&&!h,"border-solid border-border/55 bg-background":!d&&u,"min-h-[56px] border-dashed border-border/60 bg-background":!d&&!u}),children:n.length===0?e.jsxs("div",{className:"flex min-h-[56px] items-center justify-center gap-2 text-sm text-muted-foreground/85",children:[e.jsx(v,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground/80"}),e.jsx("span",{children:r}),b&&e.jsx(xo,{concept:s})]}):e.jsx(t.SortableContext,{id:s,items:n.map(w=>w.id),strategy:t.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map((w,E)=>{const D=w.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(mo,{field:w,zone:s,index:E,sortDirection:D,onSortDirectionChange:T=>g(w.id,T),hasPivotColumns:c,cardType:x})})},w.id)})})})})]})}function po({groupByFields:s,pivotByFields:n,metricsFields:a,sortByFields:r,detailFields:i,activeField:c}){var Y,H,Z,ae;const[o,d]=N.useState(!1),l=t.useEditorStore(ee=>{var de;return!!((de=ee.card.customCardPreferences)!=null&&de.url)}),m=t.useEditorStore(ee=>ee.card),p=t.useEditorStore(ee=>ee.frame),x=t.findCustomVisualConfigCard(p,m),{manifest:u}=t.useCustomVisual(((Y=x==null?void 0:x.customCardPreferences)==null?void 0:Y.url)||""),h=(H=u==null?void 0:u.visuals)==null?void 0:H.find(ee=>{var de;return ee.name===((de=x==null?void 0:x.customCardPreferences)==null?void 0:de.componentName)}),g=t.resolveMultiInputType(x,h)==="multiple",b=g&&!!((Z=x==null?void 0:x.customCardPreferences)!=null&&Z.url),v=t.getConfigSlotExpectedType(h==null?void 0:h.slots),w=t.useEditorStore(ee=>ee.actions.updateCardConfig),E=t.useEditorStore(ee=>ee.actions.updateFrame),{scopedFields:z,refetch:D}=t.useScopedFields(),{userContext:T}=t.useCurrentUserInfo(),I=g&&(x==null?void 0:x.id)===m.id&&v?v:m==null?void 0:m.type,M=I==="detailTable",k=s.length>0||a.length>0||i.length>0,j=!M&&(I!=="kpi"||a.length<=2),S=!M,A=!M&&I!=="kpi",f=I!=="kpi"&&k,O=M,P="Drop sort fields here",y=(ae=m.dataSource)==null?void 0:ae.semanticDomainId,{promoteMetric:L}=t.usePromoteCalculatedMetricToDomain({domainId:y}),C=(T==null?void 0:T.type)==="organization",V=ee=>{const de=p.calculatedFields||[],ce=de.findIndex(ne=>ne.name===ee.name&&ne.role===ee.role),W=ce>=0?{...ee,id:de[ce].id}:ee,pe=ce>=0?de.map((ne,ye)=>ye===ce?W:ne):[...de,W];E({calculatedFields:pe});const X=t.getNewField(W,"metrics",a),we=a.findIndex(ne=>ne.name===X.name&&ne.role===X.role),G=we>=0?a.map((ne,ye)=>ye===we?{...ne,...X,id:ne.id}:ne):[...a,X];w(m.id,{metricColumns:G})},F=async ee=>{await L(ee),D()},R=["pie","doughnut","polar","funnel","aggregateTable","bubble","scatter"].includes(I),$=A&&!R,B=()=>I==="kpi"?{label:"Trend By",placeholder:"Drop trend field here"}:{label:"Rows",placeholder:"Drop dimensions here"},K=()=>I==="kpi"?{label:"Metric",placeholder:"Drop metric here"}:{label:"Metrics",placeholder:"Drop metrics here"};return e.jsxs(e.Fragment,{children:[e.jsxs(t.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full space-y-2.5",children:[e.jsxs(t.AccordionItem,{value:"fields",className:"rounded-xl border border-border/55 border-b-0 bg-card px-3 shadow-[0_1px_2px_rgba(15,23,42,0.04)]",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2.5 text-xs font-semibold tracking-wide text-foreground/70 hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.List,{className:"h-4 w-4 text-foreground/60"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-3 pt-1.5",children:[j&&e.jsx(wt,{zone:"groupBy",fields:s,label:B().label,placeholder:B().placeholder,activeField:c}),$&&e.jsx(wt,{zone:"pivotBy",fields:n,label:"Pivot Columns",placeholder:"Drop pivot fields here",activeField:c}),S&&e.jsx(wt,{zone:"metrics",fields:a,label:K().label,placeholder:K().placeholder,hasPivotColumns:n.length>0,activeField:c}),O&&e.jsx(wt,{zone:"detailColumns",fields:i,label:"Columns",placeholder:"Drop columns here"}),a.length>=1&&C&&e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:()=>d(!0),className:"mt-1.5 w-full justify-start border-border/60 border-dashed bg-background text-xs text-foreground/70 hover:bg-muted/40 hover:text-foreground",children:[e.jsx(t.Calculator,{className:"mr-2 h-4 w-4"}),"Create Metric"]}),f&&e.jsx(wt,{zone:"sortBy",fields:r,label:"Sort By",placeholder:P,activeField:c})]})]}),(!l||b)&&e.jsxs(t.AccordionItem,{value:"configuration",className:"rounded-xl border border-border/55 border-b-0 bg-card px-3 shadow-[0_1px_2px_rgba(15,23,42,0.04)]",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2.5 text-xs font-semibold tracking-wide text-foreground/70 hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Settings2,{className:"h-4 w-4 text-foreground/60"}),e.jsx("span",{children:"CHART SETTINGS"})]})}),e.jsx(t.AccordionContent,{className:"mb-2 rounded-md bg-muted/20 px-3 py-0.5",children:e.jsx(t.Accordion,{type:"single",collapsible:!0,className:"w-full",children:e.jsx(qa,{mode:"config"})})})]}),(l||b)&&e.jsxs(t.AccordionItem,{value:"plugin",className:"rounded-xl border border-border/55 border-b-0 bg-card px-3 shadow-[0_1px_2px_rgba(15,23,42,0.04)]",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2.5 text-xs font-semibold tracking-wide text-foreground/70 outline-none ring-0 hover:no-underline focus:outline-none focus-visible:outline-none focus-visible:ring-0 focus-visible:ring-offset-0",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wa,{className:"h-4 w-4 text-foreground/60"}),e.jsx("span",{children:"COMPONENT SETTINGS"})]})}),e.jsx(t.AccordionContent,{className:"mb-2 rounded-md bg-muted/20 px-3 py-0.5",children:e.jsx(Va,{})})]})]}),e.jsx(t.CalculatedFieldEditor,{open:o,onOpenChange:d,availableFields:z,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:ee=>{ee.role==="metric"&&w(m.id,{metricColumns:[...a,ee]})},onSaveToDashboard:ee=>{ee.role==="metric"&&V(ee)},onPromoteMetricToDomain:y&&C?F:void 0,domainId:y,cardId:m.id})]})}function fo({onEditJoins:s}){const n=t.useEditorStore(d=>d.card),{autoJoinMetadata:a}=t.useDashboardCardQuery(n);if(!(a!=null&&a.autoResolved))return null;const{resolvedJoinPlan:r}=a,i=(r==null?void 0:r.joins)||[];if(i.length===0)return null;const c=d=>!d||d.length===0?"No conditions":d.map(l=>{var u,h,g,b;const m=`${(u=l.source)==null?void 0:u.entityName}.${(h=l.source)==null?void 0:h.name}`,p=`${(g=l.target)==null?void 0:g.entityName}.${(b=l.target)==null?void 0:b.name}`,x=l.operator||"=";return`${m} ${x} ${p}`}).join(" AND "),o=d=>!d.joinKeyGroups||d.joinKeyGroups.length===0?"No conditions defined":d.joinKeyGroups.length===1?c(d.joinKeyGroups[0].keys):d.joinKeyGroups.map((l,m)=>({id:m,operator:l.operator,condition:c(l.keys)}));return e.jsx(t.Card,{className:"border-blue-500/20 bg-blue-50/15 shadow-sm dark:bg-blue-950/10",children:e.jsxs("div",{className:"flex items-center justify-between p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ln,{className:"size-4 text-blue-600/90 dark:text-blue-400"}),e.jsx("h3",{className:"text-xs font-semibold tracking-wide text-blue-900/90 dark:text-blue-100",children:"Resolved Joins"}),e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.Badge,{variant:"secondary",className:"cursor-help bg-blue-100/80 text-xs text-blue-700 dark:bg-blue-900/70 dark:text-blue-300",children:i.length})}),e.jsx(t.TooltipContent,{side:"bottom",align:"start",className:"max-w-md p-3",children:e.jsx("div",{className:"space-y-2",children:i.map((d,l)=>{const m=o(d),p=Array.isArray(m);return e.jsxs("div",{className:"rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"font-medium text-foreground",children:d.source.name}),e.jsx(t.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:d.target.name})]}),e.jsx(t.Badge,{variant:"outline",className:"border-green-500/40 bg-green-50/30 text-xs text-green-700 dark:bg-green-950/30 dark:text-green-300",children:d.joinType})]}),e.jsx("div",{className:"mt-1 space-y-1",children:p?m.map(x=>e.jsxs("div",{className:"rounded bg-muted/30 px-2 py-1",children:[e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:x.condition}),x.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",x.operator,")"]})]},x.id)):e.jsx("div",{className:"rounded bg-muted/30 px-2 py-1",children:e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:m})})})]},d.id||l)})})})]})})]}),s&&e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:s,className:"h-7 gap-1 p-2 text-xs text-blue-700/80 hover:text-blue-900 dark:text-blue-300 dark:hover:text-blue-100",children:e.jsx(t.SquarePen,{className:"size-3.5"})})]})})}const Ca={getItem(s){if(typeof window>"u")return null;try{return localStorage.getItem(s)}catch(n){return console.warn(`Failed to read from localStorage (${s}):`,n),null}},setItem(s,n){if(!(typeof window>"u"))try{localStorage.setItem(s,n)}catch(a){console.warn(`Failed to write to localStorage (${s}):`,a)}}};function go({selectedChart:s,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:i,sortByFields:c,detailFields:o,activeField:d}){var j,S;const[l,m]=N.useState(()=>Ca.getItem("chart-selector-expanded")==="true"),[p,x]=N.useState(!1),u=t.useEditorStore(A=>A.card),h=t.useEditorStore(A=>A.actions.updateCardConfig),g=a.length>0||r.length>0||i.length>0||o.length>0,{data:b,autoJoinMetadata:v}=t.useDashboardCardQuery(u),w=g||!!b,E=((j=u==null?void 0:u.config)==null?void 0:j.joinPlan)||(v!=null&&v.autoResolved?v.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),z=((S=u==null?void 0:u.dataSource)==null?void 0:S.selectedEntities)||[],D=A=>{h(u.id,{...u==null?void 0:u.config,joinPlan:A}),x(!1)},T=()=>{h(u.id,{...u==null?void 0:u.config,joinPlan:void 0}),x(!1)},I=()=>{x(!1)},M=()=>{x(!0)};N.useEffect(()=>{Ca.setItem("chart-selector-expanded",String(l))},[l]);const k=()=>{m(A=>!A)};return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col bg-background",children:[e.jsx("div",{className:"pl-2 pr-4 pt-4",children:e.jsxs("div",{className:"rounded-xl border border-border/60 bg-card p-3 shadow-[0_1px_2px_rgba(15,23,42,0.05)]",children:[e.jsx("div",{className:t.cn("overflow-hidden transition-all duration-300 ease-in-out",l?"max-h-[210px] opacity-100":"max-h-0 opacity-0"),children:l&&e.jsx(ds,{selectedChart:s,onChartChange:n,variant:"outline"})}),e.jsx("div",{"data-content":"Chart Quick Selector",className:t.cn("flex items-center justify-center",{"mt-3":l,"mt-2":!l}),children:e.jsx(t.ChartQuickSelector,{selectedChart:s,onChartChange:n,isDropdownExpanded:l,onToggleDropdown:k})})]})}),w&&e.jsx("div",{className:"pl-2 pr-4 py-3",children:e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(Me.EditorClearButton,{label:"Reset",variant:"secondary",className:"h-7 px-2 text-xs"})})}),e.jsx(t.ScrollArea,{className:"min-h-0 w-full flex-1 basis-0",children:e.jsxs("div",{className:t.cn("space-y-3 pl-2 pr-4 pb-6",w?"pt-1":"pt-4"),children:[e.jsx(fo,{onEditJoins:M}),e.jsx(po,{groupByFields:a,pivotByFields:r,metricsFields:i,sortByFields:c,detailFields:o,activeField:d})]})}),e.jsx(ka,{open:p,onOpenChange:x,joinPlan:E,availableDataSources:z,onSave:D,onCancel:I,onRemove:T,children:e.jsx("div",{})})]})}function jo({initialFilters:s,availableFields:n}={}){const[a,r]=N.useState(s||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});t.useEditorStore(T=>T.card.dataSource);const{columns:i,isLoading:c}=t.useColumns(),d=n||i||[],l={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},m=T=>{const I=M=>{if(M.id===T){const k=d[0]||l,j=t.getDataType(k.dataType)==="date";return{...M,conditions:[...M.conditions,{id:`condition-${Date.now()}`,field:k,operator:j?"between":"=",value:j?[]:""}]}}return{...M,groups:M.groups.map(I)}};r(I(a))},p=T=>{const I=M=>{if(M.id===T){const k=d[0]||l,j=t.getDataType(k.dataType)==="date";return{...M,groups:[...M.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:k,operator:j?"between":"=",value:j?[]:""}],groups:[]}]}}return{...M,groups:M.groups.map(I)}};r(I(a))},x=(T,I)=>{const M=k=>k.id===T?{...k,conditions:k.conditions.filter(j=>j.id!==I)}:{...k,groups:k.groups.map(M)};r(M(a))},u=(T,I)=>{const M=k=>k.id===T?{...k,groups:k.groups.filter(j=>j.id!==I)}:{...k,groups:k.groups.map(M)};r(M(a))},h=(T,I,M,k)=>{if(M==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const j=S=>S.id===T?{...S,conditions:S.conditions.map(A=>A.id===I?{...A,[M]:k}:A)}:{...S,groups:S.groups.map(j)};r(j(a))},g=(T,I,M)=>{const k=j=>j.id===T?{...j,conditions:j.conditions.map(S=>S.id===I?{...S,...M}:S)}:{...j,groups:j.groups.map(k)};r(k(a))},b=(T,I)=>{const M=k=>k.id===T?{...k,logicalOperator:I}:{...k,groups:k.groups.map(M)};r(M(a))},v=(T,I)=>{const M=k=>k.id===T?{...k,negate:I}:{...k,groups:k.groups.map(M)};r(M(a))},w=(T,I,M)=>{const k=j=>j.id===T?{...j,conditions:t.arrayMove(j.conditions,I,M)}:{...j,groups:j.groups.map(k)};r(k(a))},E=(T,I,M)=>{const k=j=>j.id===T?{...j,groups:t.arrayMove(j.groups,I,M)}:{...j,groups:j.groups.map(k)};r(k(a))},z=T=>{if(!T||T.conditions.length===0&&T.groups.length===0)return"-- No filters defined";const I=k=>{let j="";typeof k.field=="object"?j=k.field.entityName?`${k.field.entityName}.${k.field.name}`:k.field.name:j=String(k.field);const S=k.operator;let A=k.value;if(k.field.dataType==="string"&&!["in","not in"].includes(k.operator))typeof A=="string"?A=`'${A}'`:Array.isArray(A)&&(A=`'${A.join(", ")}'`);else if(k.field.dataType==="date"||k.field.dataType==="datetime"||k.field.dataType==="timestamp")if(k.operator==="between"&&Array.isArray(A)&&A.length===2){const f=A[0]?`'${A[0]}'`:"NULL",O=A[1]?`'${A[1]}'`:"NULL";return`${j} BETWEEN ${f} AND ${O}`}else if((k.operator==="in"||k.operator==="not in")&&Array.isArray(A)){const f=A.map(O=>O?`'${O}'`:"NULL").join(", ");return`${j} ${S} (${f})`}else typeof A=="string"||A instanceof Date?A=`'${A}'`:Array.isArray(A)&&A.length>0&&(A=`'${A[0]}'`);else if(["in","not in"].includes(k.operator)){let f=[];Array.isArray(A)?f=A.map(O=>typeof O=="string"?`'${O}'`:String(O)):typeof A=="string"?f=A.split(",").map(O=>{const P=O.trim();return k.field.dataType==="string"?`'${P}'`:P}):typeof A=="number"&&(f=[String(A)]),A=`(${f.join(", ")})`}switch(S){case"contains":return typeof A=="string"?`${j} LIKE '%${A.replace(/'/g,"")}'`:`${j} LIKE '%${String(A)}'`;case"startsWith":return typeof A=="string"?`${j} LIKE '${A.replace(/'/g,"")}%'`:`${j} LIKE '${String(A)}%'`;case"endsWith":return typeof A=="string"?`${j} LIKE '%${A.replace(/'/g,"")}'`:`${j} LIKE '%${String(A)}'`;case"isNull":return`${j} IS NULL`;case"isNotNull":return`${j} IS NOT NULL`;default:return`${j} ${S} ${A}`}},M=k=>{const j=k.conditions.map(I),S=k.groups.map(P=>M(P)),A=[...j,...S].filter(Boolean);if(A.length===0)return"";const f=A.join(` ${k.logicalOperator} `),O=A.length>1?`(${f})`:f;return k.negate?`NOT ${O}`:O};return M(T)},D=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:d,isLoading:c,addCondition:m,addGroup:p,removeCondition:x,removeGroup:u,updateCondition:h,updateConditionFields:g,updateGroupOperator:b,updateGroupNegate:v,reorderConditions:w,reorderGroups:E,generateSQLPreview:z,hasAnyFilters:D}}function bo({children:s,className:n,delayDuration:a}){return e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:a,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:t.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",n),children:s})}),e.jsx(t.PortalTooltipContent,{children:s})]})})}const vo=s=>{if(s.qualifiedEntityName){const n=s.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function yo({value:s,onValueChange:n,availableFields:a,placeholder:r="Select field",className:i="w-64"}){const[c,o]=N.useState(!1),d=N.useMemo(()=>{const l={};return a.forEach(m=>{const p=vo(m);l[p]||(l[p]={}),l[p][m.entityId]||(l[p][m.entityId]=[]),l[p][m.entityId].push(m)}),l},[a]);return e.jsxs(t.Popover,{modal:!0,open:c,onOpenChange:o,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":c,className:t.cn("justify-between",!s&&"text-muted-foreground",i),children:[s?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(bo,{children:[s.entityName,".",s.name]})}):r,e.jsx(t.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(t.CommandEmpty,{children:"No fields found."}),e.jsx(t.CommandList,{className:"max-h-80",children:Object.entries(d).map(([l,m])=>e.jsx(t.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Database,{className:"h-3 w-3"}),l]}),children:Object.entries(m).map(([p,x])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[t.getEntityIcon(x[0].entityType,{size:"h-3 w-3"}),e.jsx("span",{children:x[0].entityName})]}),x.map((u,h)=>e.jsxs(t.CommandItem,{value:u.id,onSelect:()=>{n(u),o(!1)},className:"overflow-x-auto",children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",(s==null?void 0:s.id)===u.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:u.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:u.description&&e.jsx("span",{children:u.description})})]})]},u.id+h))]},`${l}-${p}`))},l))})]})})]})}function fs(s){var b;const n=t.useEditorStore(v=>v.card),{authToken:a,tokenProps:r}=t.useSemaphorContext(),i=t.useEditorStore(v=>v.card.config),c=i==null?void 0:i.joinPlan,o={...s,alias:s.name,label:"value",role:"groupby"},d={...s,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},l={...o,role:"sortby",direction:"asc"},m={joinPlan:c,groupByColumns:[o],metricColumns:[d],sortByColumns:[l]},p=((b=n.dataSource)==null?void 0:b.connectionId)||n.connectionId,{data:x,isPending:u,error:h}=t.useQuery({queryKey:["filterValues",s.entityId,s.name,s.qualifiedEntityName],queryFn:async()=>{try{return await t.postRequestRegular(`${r.apiServiceUrl}/v1/query`,(a==null?void 0:a.accessToken)||"",{connection_id:p,cardConfig:m,cardDataSource:n.dataSource})}catch(v){console.log(s),console.error("error",v)}},enabled:!!p,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((x==null?void 0:x.records)||[]).map(v=>({label:v.value||"BLANK",value:v.value||"BLANK",count:(v==null?void 0:v.count)||0})),isPending:u,error:h}}function No({field:s,selected:n,onChange:a,placeholder:r="Select items...",className:i}){const[c,o]=ns.useState(!1),{filterValues:d}=fs(s),l=p=>{a(n.filter(x=>x!==p))},m=p=>{n.includes(p)?a(n.filter(x=>x!==p)):a([...n,p])};return e.jsx("div",{className:t.cn("w-full",i),children:e.jsxs(t.Popover,{open:c,onOpenChange:o,modal:!0,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":c,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:n.length>0?n.map(p=>{const x=d.find(u=>u.value===p);return e.jsxs(t.Badge,{variant:"secondary",className:"text-xs",children:[x==null?void 0:x.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:u=>{u.key==="Enter"&&l(p)},onMouseDown:u=>{u.preventDefault(),u.stopPropagation()},onClick:u=>{u.stopPropagation(),l(p)},children:e.jsx(t.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},p)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(t.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No results found."}),e.jsx(t.CommandGroup,{children:d.map((p,x)=>e.jsxs(t.CommandItem,{onSelect:()=>m(p.value),children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",n.includes(p.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:p.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:p.count})]})]},p.value+x))})]})]})})]})})}function Co({field:s,value:n,onChange:a,placeholder:r="Select value...",className:i}){const{filterValues:c,isPending:o,error:d}=fs(s);return o?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(t.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):d?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(t.Select,{value:n,onValueChange:a,children:[e.jsx(t.SelectTrigger,{className:i||"flex-1",children:e.jsx(t.SelectValue,{placeholder:r,children:n})}),e.jsx(t.SelectContent,{children:c.map((l,m)=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:l.value,children:l.label},l.value+m))})]})}function So({value:s,operator:n,onChange:a,className:r}){var h,g,b;const{tokenProps:i}=t.useSemaphorContext(),c=((g=(h=i==null?void 0:i.params)==null?void 0:h.calendarContext)==null?void 0:g.tz)||((b=i==null?void 0:i.params)==null?void 0:b.timezone),o=c||Intl.DateTimeFormat().resolvedOptions().timeZone,d=n==="between"||n==="not between",l=N.useMemo(()=>{if(!(!s||!d)&&Array.isArray(s)&&s.length===2){const v=s[0]?new Date(s[0]):void 0,w=s[1]?new Date(s[1]):void 0;if(v&&w)return{from:v,to:w}}},[s,d]),m=N.useMemo(()=>{if(!s||d)return;const v=Array.isArray(s)?s[0]:s;if(!v)return;const w=new Date(v);if(!isNaN(w.getTime()))return w},[s,d]),p=v=>n==="<="||n===">"?t.endOfDayInTimezone(v,o):t.startOfDayInTimezone(v,o),x=v=>{if(!v){a([]);return}if(v.from&&v.to){a([v.from.toISOString(),v.to.toISOString()]);return}a([])},u=v=>{if(!v){a("");return}const w=p(v);a(w.toISOString())};return e.jsx(t.DateRangePicker,{value:d?l:void 0,selectionMode:d?"range":"single",singleValue:d?void 0:m,onChange:x,onSingleChange:u,timezone:c,showRelativeTab:d,className:r,placeholder:"Select date..."})}const wo=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],To=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Eo=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],Io=["=","!=","isNull","isNotNull"],ko=["between","=","!=","<","<=",">",">=","isNull","isNotNull"],Do={"=":"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 Sa(s){return Do[s]||t.titleCase(s)}function Ao(s){switch(s){case"string":return To;case"number":return Eo;case"boolean":return Io;case"date":return ko;default:return wo}}function Ka({condition:s,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:i,onRemoveCondition:c,onUpdateGroupOperator:o,availableFields:d,updateConditionFields:l}){const{attributes:m,listeners:p,setNodeRef:x,transform:u,transition:h,isDragging:g}=t.useSortable({id:s.id}),{isPending:b,error:v}=fs(s.field),w={transform:t.CSS.Transform.toString(u),transition:h};return e.jsxs("div",{ref:x,style:w,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${g?"z-50 opacity-50":""}`,children:[e.jsx("div",{...m,...p,className:"cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),n>0&&e.jsxs(t.Select,{value:r,onValueChange:E=>o(a,E),children:[e.jsx(t.SelectTrigger,{className:"w-24",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),n===0&&e.jsx("div",{className:"w-24"}),e.jsx(yo,{value:s.field,onValueChange:E=>{const z=E,D=t.getDataType(z.dataType)==="date";l(a,s.id,{field:z,value:"",operator:D?"between":"="})},availableFields:d,placeholder:"Select field",className:"w-64"}),e.jsxs(t.Select,{value:s.operator,onValueChange:E=>{E==="in"||E==="not in"?l(a,s.id,{operator:E,value:[]}):E==="isNull"||E==="isNotNull"?l(a,s.id,{operator:E,value:null}):E==="between"||E==="not between"?l(a,s.id,{operator:E,value:[]}):l(a,s.id,{operator:E,value:""})},children:[e.jsx(t.SelectTrigger,{className:"w-32",children:e.jsx(t.SelectValue,{children:s.operator?Sa(s.operator):""})}),e.jsx(t.SelectContent,{children:Ao(t.getDataType(s.field.dataType)).map(E=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:E,children:Sa(E)},E))})]}),s.operator==="isNull"||s.operator==="isNotNull"?e.jsx("div",{className:"flex-1"}):t.getDataType(s.field.dataType)==="string"?s.operator==="in"||s.operator==="not in"?b?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(t.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):v?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(No,{field:s.field,selected:Array.isArray(s.value)&&s.value.every(E=>typeof E=="string")?s.value:[],onChange:E=>l(a,s.id,{value:E}),placeholder:`Select values for ${s.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(s.operator)?e.jsx(t.Input$1,{value:typeof s.value=="string"?s.value:"",onChange:E=>l(a,s.id,{value:E.target.value}),className:"flex-1",placeholder:s.operator.charAt(0).toUpperCase()+s.operator.slice(1)+"..."}):e.jsx(Co,{field:s.field,value:typeof s.value=="string"?s.value:"",onChange:E=>l(a,s.id,{value:E}),placeholder:"Select value...",className:"flex-1"}):t.getDataType(s.field.dataType)==="boolean"?e.jsxs(t.Select,{value:typeof s.value=="boolean"?String(s.value):"",onValueChange:E=>l(a,s.id,{value:E==="true"}),children:[e.jsx(t.SelectTrigger,{className:"flex-1",children:e.jsx(t.SelectValue,{placeholder:"Select value..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"true",children:"True"}),e.jsx(t.SelectItem,{value:"false",children:"False"})]})]}):t.getDataType(s.field.dataType)==="date"?e.jsx(So,{value:s.value,operator:s.operator,onChange:E=>l(a,s.id,{value:E}),className:"flex-1"}):e.jsx(t.Input$1,{value:typeof s.value=="string"||typeof s.value=="number"?s.value:"",onChange:E=>i(a,s.id,"value",E.target.value),className:"flex-1",placeholder:s.operator==="in"||s.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>c(a,s.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]})}function Mo({group:s,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:i,onRemoveGroup:c,onUpdateCondition:o,onUpdateField:d,onRemoveCondition:l,onReorderConditions:m,onReorderGroups:p,onAddCondition:x,onAddGroup:u,availableFields:h,renderFilterGroup:g,updateConditionFields:b}){const{attributes:v,listeners:w,setNodeRef:E,transform:z,transition:D,isDragging:T}=t.useSortable({id:s.id}),I={transform:t.CSS.Transform.toString(z),transition:D},M=j=>{const{active:S,over:A}=j;if(A&&S.id!==A.id){const f=s.conditions.findIndex(P=>P.id===S.id),O=s.conditions.findIndex(P=>P.id===A.id);f!==-1&&O!==-1&&m(s.id,f,O)}},k=j=>{const{active:S,over:A}=j;if(A&&S.id!==A.id&&a){const f=s.groups.findIndex(P=>P.id===S.id),O=s.groups.findIndex(P=>P.id===A.id);f!==-1&&O!==-1&&p(a,f,O)}};return e.jsxs("div",{ref:E,style:I,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${T?"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",{...v,...w,className:"cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(t.Button,{variant:s.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>i(s.id,!s.negate),children:"NOT"}),e.jsxs(t.Select,{value:s.logicalOperator,onValueChange:j=>r(s.id,j),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>a&&c(a,s.id),children:e.jsx(t.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${n>0?"":"px-0"}`,children:[e.jsx(t.DndContext,{sensors:t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),collisionDetection:t.closestCenter,onDragEnd:M,children:e.jsx(t.SortableContext,{items:s.conditions.map(j=>j.id),strategy:t.verticalListSortingStrategy,children:s.conditions.map((j,S)=>e.jsx(Ka,{condition:j,index:S,groupId:s.id,groupLogicalOperator:s.logicalOperator,onUpdateCondition:o,onUpdateField:d,onRemoveCondition:l,onUpdateGroupOperator:r,availableFields:h,updateConditionFields:b},j.id))})}),e.jsx(t.DndContext,{sensors:t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),collisionDetection:t.closestCenter,onDragEnd:k,children:e.jsx(t.SortableContext,{items:s.groups.map(j=>j.id),strategy:t.verticalListSortingStrategy,children:s.groups.map(j=>g(j,n+1,s.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(t.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>x(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Lo({filters:s,availableFields:n,onSave:a,onClearAll:r,onCancel:i}){const{currentFilters:c,availableFields:o,isLoading:d,addCondition:l,addGroup:m,removeCondition:p,removeGroup:x,updateCondition:u,updateConditionFields:h,updateGroupOperator:g,updateGroupNegate:b,reorderConditions:v,reorderGroups:w,generateSQLPreview:E,hasAnyFilters:z,setCurrentFilters:D}=jo({initialFilters:s,availableFields:n}),T=t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),[I,M]=N.useState(!1),k=(A,f,O)=>{const P=y=>y.id===A?{...y,conditions:y.conditions.map(L=>L.id===f?{...L,field:O,dataType:O.dataType}:L)}:{...y,groups:y.groups.map(P)};D(P(c))},j=(A,f=0,O)=>f===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(t.DndContext,{sensors:T,collisionDetection:t.closestCenter,onDragEnd:P=>{const{active:y,over:L}=P;if(L&&y.id!==L.id){const C=A.conditions.findIndex(F=>F.id===y.id),V=A.conditions.findIndex(F=>F.id===L.id);C!==-1&&V!==-1&&v(A.id,C,V)}},children:e.jsx(t.SortableContext,{items:A.conditions.map(P=>P.id),strategy:t.verticalListSortingStrategy,children:A.conditions.map((P,y)=>e.jsx(Ka,{condition:P,index:y,groupId:A.id,groupLogicalOperator:A.logicalOperator,onUpdateCondition:u,onUpdateField:k,onRemoveCondition:p,onUpdateGroupOperator:g,availableFields:o,updateConditionFields:h},P.id))})}),e.jsx(t.DndContext,{sensors:T,collisionDetection:t.closestCenter,onDragEnd:P=>{const{active:y,over:L}=P;if(L&&y.id!==L.id){const C=A.groups.findIndex(F=>F.id===y.id),V=A.groups.findIndex(F=>F.id===L.id);C!==-1&&V!==-1&&w(A.id,C,V)}},children:e.jsx(t.SortableContext,{items:A.groups.map(P=>P.id),strategy:t.verticalListSortingStrategy,children:A.groups.map(P=>j(P,f+1,A.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(t.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>l(A.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),I&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>m(A.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},A.id):e.jsx(Mo,{group:A,depth:f,parentGroupId:O,onUpdateGroupOperator:g,onUpdateGroupNegate:b,onRemoveGroup:x,onUpdateCondition:u,onUpdateField:k,onRemoveCondition:p,onReorderConditions:v,onReorderGroups:w,onAddCondition:l,onAddGroup:m,availableFields:o,renderFilterGroup:j,updateConditionFields:h},A.id),S=t.getFilterCount(s);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(t.Card,{children:e.jsx(t.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[d?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):j(c),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.SmallSwitch,{id:"advanced-mode",checked:I,onCheckedChange:A=>M(A)}),e.jsx(t.Label,{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),z&&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:E(c)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(t.Button,{size:"sm",variant:"outline",onClick:i,children:"Cancel"}),S>0&&e.jsx(t.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(t.Button,{size:"sm",onClick:()=>a(z?c:null),children:"Apply Filters"})]})]})}function Oo({cardId:s,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:i,isOpen:c,onOpenChange:o}){const d=m=>{a(s,m),o(!1)},l=()=>{r(s),o(!1)};return e.jsxs(t.Dialog,{modal:!1,open:c,onOpenChange:o,children:[c&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(t.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:m=>{m.preventDefault()},children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Card Filters"}),e.jsx(t.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(Lo,{filters:n,availableFields:i,onSave:d,onCancel:()=>o(!1),onClearAll:l})]})]})}function Fo({activeCardId:s,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var E,z;const[i,c]=N.useState(null),o=t.useEditorStore(D=>D.card),d=t.useEditorStore(D=>D.actions.updateCardConfig),l=t.useEditorStore(D=>D.actions.setCardPreferences),m=(E=o==null?void 0:o.config)==null?void 0:E.joinPlan,p=N.useCallback(D=>D.entityName===t.CALCULATED_FIELD_ENTITY_MARKER||D.entityName==="calculated_fields"||D.qualifiedEntityName==="calculated_fields",[]),x=(z=o==null?void 0:o.dataSource)==null?void 0:z.semanticDomainId,{data:u}=t.useJoinabilityMap(x),h=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy"),...a("detailColumns")],g=N.useCallback(D=>D.startsWith("card-source-")?"source":D.startsWith("card-")?null:D.startsWith("source-")||n.find(T=>T.id===D)?"source":a("groupBy").find(T=>T.id===D)?"groupBy":a("metrics").find(T=>T.id===D)?"metrics":a("pivotBy").find(T=>T.id===D)?"pivotBy":a("sortBy").find(T=>T.id===D)?"sortBy":a("detailColumns").find(T=>T.id===D)?"detailColumns":null,[n,a]),b=N.useCallback(D=>{c(D.active.id)},[]),v=N.useCallback(D=>{var A;const{active:T,over:I}=D;if(!I||!s){c(null);return}const M=T.id,k=I.id,j=g(M),S=g(k)||k;if(S==="sortBy"){if(j==="source"){const f=n.find(P=>P.id===M);if(!f){c(null);return}if(!(a("groupBy").some(P=>P.name===f.name&&P.qualifiedEntityName===f.qualifiedEntityName)||a("metrics").some(P=>P.name===f.name&&P.qualifiedEntityName===f.qualifiedEntityName)||a("detailColumns").some(P=>P.name===f.name&&P.qualifiedEntityName===f.qualifiedEntityName))){c(null);return}}else if(j==="pivotBy"){c(null);return}else if(j!=="groupBy"&&j!=="metrics"&&j!=="sortBy"&&j!=="detailColumns"){c(null);return}}if(j==="source"&&S==="sortBy"){const f=[...n].find(L=>L.id===M);if(!f){c(null);return}const O=a("sortBy");if(t.fieldAlreadyExists(f,O)){c(null);return}const P=t.validateFieldForChartType(f,"sortBy",o.type);if(!P.isValid){t.ue.error("Invalid Field Type",{description:P.reason,position:"top-center",duration:3e3}),c(null);return}const y=t.getNewField(f,"sortBy",O);c(null),r("sortBy",[...O,y]);return}if(j==="source"&&S!=="source"&&S!=="sortBy"){const f=[...n].find(F=>F.id===M);if(!f){c(null);return}const O=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy"),...a("detailColumns")],P=O.filter(F=>!p(F));if(P.length>0){const F=P[0].qualifiedEntityName;if(!F){c(null);return}if(F!==f.qualifiedEntityName&&!p(f)&&f.qualifiedEntityName)if(x&&(u!=null&&u.joinabilityMap)){if(t.calculateFieldState(f,{joinabilityMap:u.joinabilityMap,selectedFields:O,baseEntityName:(A=m==null?void 0:m.baseEntity)==null?void 0:A.name}).state==="unreachable"){t.showJoinRequiredNotification(),c(null);return}}else{if(!m){t.showJoinRequiredNotification(),c(null);return}if(!t.areEntitiesJoined(F,f.qualifiedEntityName,m)){t.showJoinRequiredNotification(),c(null);return}}}const y=a(S);if(t.fieldAlreadyExists(f,y)){c(null);return}const L=t.validateFieldForChartType(f,S,o.type);if(!L.isValid){t.ue.error("Invalid Field Type",{description:L.reason,position:"top-center",duration:3e3}),c(null);return}const C=t.getNewField(f,S,y),V=[...y,C];if(c(null),r(S,V),S==="metrics"&&s){const F=t.seedSemanticMetricFormatDefaults(o,C,o.preferences);F&&l(F),t.cleanupKpiMetricComparisonMode(o.type,o.config,d,s,V)}return}if(j&&S&&j!=="source"&&S!=="source"&&j!==S){const f=a(j),O=a(S),P=f.find(F=>F.id===M);if(!P){c(null);return}const y=t.validateFieldForChartType(P,S,o.type);if(!y.isValid){t.ue.error("Invalid Field Type",{description:y.reason,position:"top-center",duration:3e3}),c(null);return}const L=t.getNewField(P,S,O);if(c(null),S==="sortBy"){t.fieldAlreadyExists(P,O)||r(S,[...O,L]);return}const C=f.filter(F=>F.id!==M),V=[...O,L];if(r(j,C),r(S,V),S==="metrics"&&s){const F=t.seedSemanticMetricFormatDefaults(o,L,o.preferences);F&&l(F),t.cleanupKpiMetricComparisonMode(o.type,o.config,d,s,V)}return}if(j&&S&&j===S&&j!=="source"){const f=a(j),O=f.findIndex(y=>y.id===M),P=f.findIndex(y=>y.id===k);if(O!==P){const y=t.arrayMove(f,O,P);r(j,y)}}c(null)},[s,n,a,r,g,m,x,u,p,o,d,l]),w=i?h.find(D=>D.id===i):null;return{activeId:i,activeField:w,handleDragStart:b,handleDragEnd:v}}function Ro({activeView:s,onViewChange:n,splitViewEnabled:a}){const r=t.useEditorStore(d=>d.card),{config:i}=N.useContext(t.SemaphorContext).tokenProps,c=(i==null?void 0:i.showInfoTab)!==!1,o=()=>a?!1:!["table","pivotTable","aggregateTable","detailTable"].includes(r.type);return e.jsx(t.Tabs,{value:s,onValueChange:d=>n(d),children:e.jsxs(t.TabsList,{className:"h-9 w-fit gap-1 bg-background p-0",children:[e.jsx(t.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),o()&&e.jsx(t.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),r.type!=="kpi"&&c&&e.jsx(t.TabsTrigger,{value:"info",className:"rounded-md transition data-[state=active]:bg-muted",children:"Info"})]})})}const Vo=[{value:"10",label:"Top 10"},{value:"20",label:"Top 20"},{value:"50",label:"Top 50"},{value:"100",label:"Top 100"},{value:"200",label:"Top 200"},{value:"500",label:"Top 500"},{value:"1000",label:"Top 1000"}];function Po(){var l,m;const s=t.useEditorStore(p=>p.card),{updateRowLimit:n}=t.useEditorActions(),[a,r]=N.useState(!1),[i,c]=N.useState(""),o=p=>{if(p==="custom"){r(!0);return}r(!1),n(s.id,parseInt(p))},d=p=>{const x=p.target.value;c(x),x&&!isNaN(parseInt(x))&&n(s.id,parseInt(x))};return e.jsx("div",{className:"flex items-center gap-2",children:a?e.jsx(t.Input,{type:"number",value:i,onChange:d,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(t.Select,{value:((m=(l=s.config)==null?void 0:l.rowLimit)==null?void 0:m.toString())||"100",onValueChange:o,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(t.SelectValue,{placeholder:"Select limit"})}),e.jsx(t.SelectContent,{children:Vo.map(p=>e.jsx(t.SelectItem,{value:p.value,children:p.label},p.value))})]})})}function Bo({card:s,queryData:n,isLoading:a,isFetching:r,pagination:i,onPaginationChange:c,onSortChange:o,sortState:d,splitViewEnabled:l}){const m=N.useMemo(()=>(n==null?void 0:n.records)||[],[n==null?void 0:n.records]);return!l||["table","pivotTable","aggregateTable","detailTable"].includes(s.type)?e.jsx(ls,{}):e.jsxs(t.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(t.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:e.jsx(ls,{})}),e.jsx(t.ResizableHandle,{withHandle:!0}),e.jsx(t.ResizablePanel,{defaultSize:40,minSize:20,role:"results-section",className:"flex flex-col",children:e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 py-4 pl-2 pr-4",children:[(a||r)&&(n==null?void 0:n.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),(n==null?void 0:n.records)&&e.jsx(t.TableVisual,{card:s,data:m,paginationMetadata:i,onPaginationChange:c,isLoading:a||r,onSortChange:o,sortState:d})]})})]})}const zo="semaphor-split-view-enabled";function qo(){return Da(zo,!0)}function _o({activeView:s,onViewChange:n,onFiltersClick:a,activeCard:r,columns:i}){var ee,de,ce;const c=t.useEditorStore(W=>W.card),o=t.useEditorStore(W=>W.inlineFilterValuesMap[(r==null?void 0:r.id)||""]),d=t.useEditorStore(W=>W.actions.removeCardInlineFilterValue),l=t.useDashboardStore(W=>W.filterValues),m=t.useDashboardStore(W=>W.selectedSheetId),{updateCardConfig:p,setCard:x,updateCardInFrame:u,setShowAIDialog:h}=t.useEditorActions(),g=t.useEditorStore(W=>W.showAIDialog),b=t.useEditorStore(W=>W.isDevMode),v=t.useDashboardStore(W=>W.isVisualEditing),[w,E]=N.useState(!1),[z,D]=N.useState(!1),[T,I]=N.useState(null),{config:M}=N.useContext(t.SemaphorContext).tokenProps,k=(M==null?void 0:M.showInfoTab)!==!1,j=(M==null?void 0:M.showQueryDebugTools)!==!1,[S,A]=qo();t.useEditorStore(W=>{var pe;return!!((pe=W.card.customCardPreferences)!=null&&pe.url)});const{data:f,errorMessage:O,isLoading:P,isFetching:y,errorSql:L,pagination:C,refetch:V,comparisonMetadata:F,queryRequestPayload:R}=t.useDashboardCardQuery(r),$=N.useMemo(()=>(f==null?void 0:f.records)||[],[f==null?void 0:f.records]),[B,K]=N.useState(!1);N.useEffect(()=>{y||K(!1)},[y]);const Y=()=>{const W=!S;W&&s==="table"&&n("chart"),A(W)},H=(W,pe)=>{const X={...r,paginationConfig:{page:W+1,pageSize:pe}};x(X),u(X)},Z=W=>{if(!c.config)return;const pe=t.sortStateToSortByColumns(W,c.config.metricColumns,c.config.groupByColumns,c.config.detailColumns);p(c.id,{...c.config,sortByColumns:pe})},ae=N.useMemo(()=>{var W;return t.sortByColumnsToSortState((W=c.config)==null?void 0:W.sortByColumns)},[(ee=c.config)==null?void 0:ee.sortByColumns]);return e.jsx("div",{className:t.cn("relative flex w-0 grow flex-col",{"border-l":g&&v}),children:e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-3",children:[e.jsxs("div",{className:"flex items-center gap-2 pl-2 pr-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s==="chart"&&g&&e.jsx("div",{className:"w-[200px]",children:e.jsx(ds,{variant:b?"secondary":"ghost"})}),e.jsx(Ro,{activeView:s,onViewChange:n,splitViewEnabled:S}),e.jsx(t.FilterInfo,{cardId:r.id,cardFilters:(de=r.config)==null?void 0:de.filters,cardFilterCount:t.getFilterCount(((ce=r.config)==null?void 0:ce.filters)||null),onFiltersClick:a,inlineFilters:r.inlineFilters,inlineFilterValues:o,sheetId:m||"",removeInlineFilterValue:W=>d(r.id,W)}),F&&c.type!=="table"&&e.jsx(t.ComparisonMetadataBadge,{metadata:F,variant:"compact"}),e.jsx("div",{className:"ml-2",children:e.jsx(Po,{})}),g&&e.jsx(Me.EditorClearButton,{})]}),e.jsxs("div",{className:t.cn("flex grow items-center justify-end gap-2"),children:[e.jsx(t.IconButton,{tooltip:"Refresh",disabled:P||y,onClick:()=>{K(!0),V()},children:e.jsx(t.RefreshCcw,{className:t.cn("h-4 w-4",{"animate-spin":B})})}),s==="chart"&&e.jsx(Ra,{showInlineFilters:!1,showDisplayOptions:!1}),!g&&e.jsx(t.IconButton,{onClick:()=>h(!g),tooltip:"AI",className:"h-8","aria-label":"AI",children:e.jsx(t.Sparkles,{className:"size-4"})}),s==="chart"&&e.jsxs(t.DropdownMenu,{modal:!1,children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"More Options",className:"h-8","aria-label":"More options",children:e.jsx(t.EllipsisVertical,{className:"size-4"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(t.DropdownMenuLabel,{children:"More Options"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{onClick:Y,children:[S?e.jsx(gn,{className:"mr-2 h-4 w-4"}):e.jsx(An,{className:"mr-2 h-4 w-4"}),S?"Hide Results Table":"Show Results Table"]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs("div",{className:"px-1 py-1",children:[e.jsx(ms,{triggerVariant:"menu",className:"w-full"}),e.jsx(us,{triggerVariant:"menu",className:"w-full"})]})]})]})]})]}),e.jsxs("div",{className:"mt-2 flex min-h-0 grow flex-col",children:[s==="chart"&&e.jsx("div",{className:t.cn("flex grow flex-col pb-4",{"pb-0":S&&!["table","pivotTable","aggregateTable","detailTable"].includes(r.type)}),children:e.jsx(Bo,{card:r,queryData:f,isLoading:P,isFetching:y,pagination:C,onPaginationChange:H,onSortChange:Z,sortState:ae,splitViewEnabled:S})}),s==="table"&&(f==null?void 0:f.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 py-4 pl-2 pr-4",children:[(P||y)&&(f==null?void 0:f.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),e.jsx(t.TableVisual,{card:r,data:$,comparisonMetadata:F,paginationMetadata:C,onPaginationChange:H,isLoading:P||y,onSortChange:Z,sortState:ae})]}),s==="info"&&k&&e.jsx("div",{className:"flex min-h-0 flex-1 flex-col pb-4",children:e.jsx("div",{className:"flex min-h-0 flex-1 flex-col rounded-md bg-background pl-2 pr-4",children:O?e.jsx(cs,{error:O,errorSql:L,onSendFeedback:()=>{const W=t.prepareFeedbackData(t.FeedbackCategory.QUERY_GENERATION,{cardConfig:c.config,dataSource:r.dataSource,dashboardFilters:l,errorMessage:O,errorSql:L,generatedSql:f==null?void 0:f.sql});I(W),D(!0)},onOpenInEditor:()=>{h(!0),setTimeout(()=>{const W=t.useEditorStore.getState().actions;W.setIsDevMode(!0),W.setCardSql(L||""),setTimeout(()=>{W.setRunSql(!0)},100)},100)}}):(f==null?void 0:f.sql)&&e.jsx(La,{sql:f.sql,showCardDetails:!0,debugPayloads:j?{queryRequest:R,queryResponse:f,columns:i,dashboardFilters:l}:void 0})})})]}),T&&e.jsx(t.FeedbackDialog,{open:z,onOpenChange:D,feedbackData:T})]})})}function $o({activeField:s}){const[n,a]=N.useState(!0);return N.useEffect(()=>{s&&a(!0)},[s]),s?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${n?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(t.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(hs,{dataType:s.dataType}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-sm dark:text-muted-foreground",children:s.label||s.name})]}):null}const Ko=()=>{const s=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||s.apply(console,r)};const n=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},a=r=>{var i;if((i=r.reason)!=null&&i.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",n,!0),window.addEventListener("unhandledrejection",a,!0),()=>{console.error=s,window.removeEventListener("error",n,!0),window.removeEventListener("unhandledrejection",a,!0)}};function Go({column:s,isSelected:n,onSelect:a,availableFields:r,width:i,onWidthChange:c}){var F,R,$;const o=t.useEditorStore(B=>B.card),{updateCardConfig:d,removeGroupByColumn:l,removeMetricColumn:m,updateFilters:p}=t.useEditorActions(),[x,u]=N.useState(!1),[h,g]=N.useState(!1),b=N.useRef(null),v=N.useCallback(B=>{B.preventDefault(),B.stopPropagation(),g(!0),b.current={startX:B.clientX,startWidth:i||150};const K=H=>{if(!b.current)return;const Z=H.clientX-b.current.startX,ae=Math.max(80,b.current.startWidth+Z);c==null||c(s.id,ae)},Y=()=>{g(!1),b.current=null,document.removeEventListener("mousemove",K),document.removeEventListener("mouseup",Y)};document.addEventListener("mousemove",K),document.addEventListener("mouseup",Y)},[i,s.id,c]),w=(F=o==null?void 0:o.config)==null?void 0:F.filters,E=(R=w==null?void 0:w.conditions)==null?void 0:R.some(B=>B.field.name===s.name&&B.field.qualifiedEntityName===s.qualifiedEntityName),z=B=>{B?p(o.id,B):d(o.id,{filters:void 0})},{attributes:D,listeners:T,setNodeRef:I,transform:M,transition:k,isDragging:j}=t.useSortable({id:s.id}),S={transform:t.CSS.Transform.toString(M),transition:k},A=t.getDataType(s.dataType),f=Uo(A),O=()=>{var Y;const B=((Y=o==null?void 0:o.config)==null?void 0:Y.sortByColumns)||[],K=B.findIndex(H=>H.name===s.name);if(K!==-1){const H=[...B];H[K]={...H[K],direction:"asc"},d(o.id,{sortByColumns:H})}else d(o.id,{sortByColumns:[...B,{...s,id:`sort-${s.id}`,role:"sortby",direction:"asc"}]})},P=()=>{var Y;const B=((Y=o==null?void 0:o.config)==null?void 0:Y.sortByColumns)||[],K=B.findIndex(H=>H.name===s.name);if(K!==-1){const H=[...B];H[K]={...H[K],direction:"desc"},d(o.id,{sortByColumns:H})}else d(o.id,{sortByColumns:[...B,{...s,id:`sort-${s.id}`,role:"sortby",direction:"desc"}]})},y=()=>{var Y;const B=((Y=o==null?void 0:o.config)==null?void 0:Y.groupByColumns)||[];if(!B.some(H=>H.name===s.name)){const H={...s,id:`groupby-${s.id}-${Date.now()}`,role:"groupby"};d(o.id,{groupByColumns:[...B,H]})}},L=B=>{var H;const K=((H=o==null?void 0:o.config)==null?void 0:H.metricColumns)||[];if(!K.some(Z=>Z.name===s.name&&Z.aggregate===B)){const Z={...s,id:`metric-${s.id}-${B}-${Date.now()}`,label:`${B} of ${s.label||s.name}`,role:"metric",aggregate:B};d(o.id,{metricColumns:[...K,Z]})}},C=()=>{s.role==="groupby"?l(o.id,s.id):s.role==="metric"&&m(o.id,s.id)},V={...S,width:i?`${i}px`:void 0,minWidth:i?`${i}px`:"120px"};return e.jsxs("th",{ref:I,style:V,className:t.cn("group relative border-r border-border bg-background px-1 py-0",j&&"opacity-50",n&&"bg-primary/10",h&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...D,...T,className:"cursor-grab p-1 text-muted-foreground opacity-0 transition-opacity hover:text-foreground group-hover:opacity-100 active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-3 w-3"})}),e.jsxs(t.DropdownMenu,{children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsxs("button",{onClick:a,className:t.cn("flex flex-1 items-center justify-between gap-1 rounded px-2 py-2 text-left text-sm font-medium transition-colors hover:bg-muted/50",n&&"bg-primary/10"),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(f,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:s.label||s.name}),s.role==="metric"&&s.aggregate&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",s.aggregate,")"]}),E&&e.jsx(t.Filter,{className:"h-3 w-3 text-primary"})]}),e.jsx(t.ChevronDown,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsxs(t.DropdownMenuContent,{align:"start",className:"w-48",children:[e.jsxs(t.DropdownMenuItem,{onClick:()=>u(!0),children:[e.jsx(t.Filter,{className:t.cn("mr-2 h-4 w-4",E&&"text-primary")}),E?"Edit Filter":"Filter"]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{onClick:O,children:[e.jsx(xn,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(t.DropdownMenuItem,{onClick:P,children:[e.jsx(mn,{className:"mr-2 h-4 w-4"}),"Sort Z → A"]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuSub,{children:[e.jsxs(t.DropdownMenuSubTrigger,{children:[e.jsx(t.Calculator,{className:"mr-2 h-4 w-4"}),"Summarize"]}),e.jsxs(t.DropdownMenuSubContent,{children:[e.jsx(t.DropdownMenuItem,{onClick:()=>L("SUM"),children:"Sum"}),e.jsx(t.DropdownMenuItem,{onClick:()=>L("AVG"),children:"Average"}),e.jsx(t.DropdownMenuItem,{onClick:()=>L("COUNT"),children:"Count"}),e.jsx(t.DropdownMenuItem,{onClick:()=>L("DISTINCT"),children:"Count Distinct"}),e.jsx(t.DropdownMenuItem,{onClick:()=>L("MIN"),children:"Min"}),e.jsx(t.DropdownMenuItem,{onClick:()=>L("MAX"),children:"Max"})]})]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{onClick:y,children:[e.jsx(Pt,{className:"mr-2 h-4 w-4"}),"Group by this column"]}),e.jsxs(t.DropdownMenuItem,{disabled:!0,children:[e.jsx(is,{className:"mr-2 h-4 w-4"}),"Pivot by this column"]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{disabled:!0,children:[e.jsx(t.EyeOff,{className:"mr-2 h-4 w-4"}),"Hide column"]}),e.jsxs(t.DropdownMenuItem,{onClick:C,className:"text-destructive focus:text-destructive",children:[e.jsx(t.Trash2,{className:"mr-2 h-4 w-4"}),"Remove column"]})]})]})]}),e.jsx("div",{onMouseDown:v,className:t.cn("absolute right-0 top-0 h-full w-1 cursor-col-resize bg-transparent hover:bg-primary/50",h&&"bg-primary")}),e.jsx($a,{open:x,onOpenChange:u,availableFields:r.length>0?r:[s],existingFilters:w,editingCondition:E?($=w==null?void 0:w.conditions)==null?void 0:$.find(B=>B.field.name===s.name&&B.field.qualifiedEntityName===s.qualifiedEntityName):void 0,onSave:z})]})}function Uo(s){switch(s){case"number":return t.Hash;case"date":return t.Calendar;case"string":default:return t.Type}}function Ho({selectedColumn:s,onColumnSelect:n,isLoading:a=!1,sourceFields:r=[]}){var k,j,S,A;const i=t.useEditorStore(f=>f.card),{updateCardConfig:c}=t.useEditorActions(),[o,d]=N.useState(null),[l,m]=N.useState({}),[p,x]=N.useState(!1),u=N.useMemo(()=>{var P,y;const f=((P=i==null?void 0:i.config)==null?void 0:P.groupByColumns)||[],O=((y=i==null?void 0:i.config)==null?void 0:y.metricColumns)||[];return[...f,...O]},[(k=i==null?void 0:i.config)==null?void 0:k.groupByColumns,(j=i==null?void 0:i.config)==null?void 0:j.metricColumns]),h=N.useMemo(()=>{const f=new Set(u.map(O=>`${O.qualifiedEntityName}.${O.name}`));return r.filter(O=>!f.has(`${O.qualifiedEntityName}.${O.name}`))},[r,u]),{data:g,isLoading:b}=t.useDashboardCardQuery(i),v=(g==null?void 0:g.records)||[],w=N.useCallback((f,O)=>{m(P=>({...P,[f]:O}))},[]),E=N.useCallback(f=>{var L,C;const O=t.getDataType(f.dataType),P=((L=i==null?void 0:i.config)==null?void 0:L.groupByColumns)||[],y=((C=i==null?void 0:i.config)==null?void 0:C.metricColumns)||[];if(O==="number"){const V={...f,id:`metric-${f.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};c(i.id,{metricColumns:[...y,V]})}else{const V={...f,id:`groupby-${f.id}-${Date.now()}`,role:"groupby"};c(i.id,{groupByColumns:[...P,V]})}x(!1)},[(S=i==null?void 0:i.config)==null?void 0:S.groupByColumns,(A=i==null?void 0:i.config)==null?void 0:A.metricColumns,i.id,c]),z=t.useSensors(t.useSensor(t.PointerSensor,{activationConstraint:{distance:8}})),D=f=>{d(f.active.id)},T=f=>{const{active:O,over:P}=f;if(d(null),!P||O.id===P.id)return;const y=u.findIndex(C=>C.id===O.id),L=u.findIndex(C=>C.id===P.id);if(y!==-1&&L!==-1){const C=t.arrayMove(u,y,L),V=C.filter(R=>R.role==="groupby"),F=C.filter(R=>R.role==="metric");c(i.id,{groupByColumns:V,metricColumns:F})}},I=o?u.find(f=>f.id===o):null,M=f=>{let O="";for(;f>=0;)O=String.fromCharCode(f%26+65)+O,f=Math.floor(f/26)-1;return O};return a?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(t.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):u.length===0?e.jsx("div",{className:"flex h-full flex-col items-center justify-center gap-4 p-8 text-center",children:e.jsxs("div",{className:"rounded-lg border-2 border-dashed border-muted-foreground/25 p-12",children:[e.jsx("h3",{className:"text-lg font-medium text-muted-foreground",children:"No columns selected"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground/75",children:"Select columns from the panel on the right to build your table"})]})}):e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsxs(t.DndContext,{sensors:z,collisionDetection:t.closestCenter,onDragStart:D,onDragEnd:T,children:[e.jsxs("table",{className:"w-full border-collapse",children:[e.jsxs("thead",{children:[e.jsxs("tr",{className:"border-b border-border bg-muted/30",children:[e.jsx("th",{className:"sticky left-0 z-20 w-12 border-r border-border bg-muted/50 px-2 py-1 text-center text-xs font-medium text-muted-foreground"}),e.jsx(t.SortableContext,{items:u.map(f=>f.id),strategy:t.horizontalListSortingStrategy,children:u.map((f,O)=>e.jsx("th",{style:{width:l[f.id]?`${l[f.id]}px`:void 0,minWidth:l[f.id]?`${l[f.id]}px`:"120px"},className:"border-r border-border bg-muted/30 px-2 py-1 text-center text-xs font-medium text-muted-foreground",children:M(O)},`letter-${f.id}`))}),e.jsx("th",{className:"w-10 border-r border-border bg-muted/30 px-2 py-1"})]}),e.jsxs("tr",{className:"border-b-2 border-border bg-background",children:[e.jsx("th",{className:"sticky left-0 z-20 w-12 border-r border-border bg-muted/50 px-2 py-2 text-center text-xs font-medium text-muted-foreground",children:"#"}),e.jsx(t.SortableContext,{items:u.map(f=>f.id),strategy:t.horizontalListSortingStrategy,children:u.map(f=>e.jsx(Go,{column:f,isSelected:(s==null?void 0:s.id)===f.id,onSelect:()=>n(f),availableFields:r,width:l[f.id],onWidthChange:w},f.id))}),e.jsx("th",{className:"w-10 border-r border-border bg-background px-1 py-2",children:e.jsxs(t.Popover,{open:p,onOpenChange:x,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Add column",children:e.jsx(t.Plus,{className:"h-4 w-4"})})}),e.jsx(t.PopoverContent,{className:"w-[280px] p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search columns..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No columns available."}),e.jsx(t.CommandGroup,{heading:"Available Columns",children:h.map(f=>{const O=t.getDataType(f.dataType),P=O==="number"?t.Hash:O==="date"?t.Calendar:t.Type;return e.jsxs(t.CommandItem,{value:f.label||f.name,onSelect:()=>E(f),children:[e.jsx(P,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm",children:f.label||f.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:f.entityName})]})]},f.id)})})]})]})})]})})]})]}),e.jsx("tbody",{children:b?e.jsx("tr",{children:e.jsx("td",{colSpan:u.length+2,className:"h-32 text-center",children:e.jsx(t.LoaderCircle,{className:"mx-auto h-6 w-6 animate-spin text-muted-foreground"})})}):v.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"})}):v.slice(0,100).map((f,O)=>e.jsxs("tr",{className:t.cn("border-b border-border transition-colors hover:bg-muted/50",O%2===0?"bg-background":"bg-muted/20"),children:[e.jsx("td",{className:"sticky left-0 z-10 w-12 border-r border-border bg-muted/50 px-2 py-2 text-center text-xs font-medium text-muted-foreground",children:O+1}),u.map(P=>{const y=f[P.name]??f[P.label??""];return e.jsx("td",{style:{width:l[P.id]?`${l[P.id]}px`:void 0,minWidth:l[P.id]?`${l[P.id]}px`:"120px"},className:t.cn("border-r border-border px-3 py-2 text-sm",(s==null?void 0:s.id)===P.id&&"bg-primary/5"),children:e.jsx("span",{className:"block truncate",children:Qo(y,P)})},`${O}-${P.id}`)}),e.jsx("td",{className:"w-10 border-r border-border"})]},O))})]}),e.jsx(t.DragOverlay,{children:I&&e.jsx("div",{className:"rounded border border-primary bg-background px-3 py-2 text-sm font-medium shadow-lg",children:I.label||I.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(v.length,100)," of ",v.length," rows"]}),e.jsxs("span",{children:[u.length," columns"]})]})]})}function Qo(s,n){if(s==null)return"—";if(typeof s=="number")return n.role==="metric"?new Intl.NumberFormat("en-US",{minimumFractionDigits:0,maximumFractionDigits:2}).format(s):s.toString();if(s instanceof Date||typeof s=="string"&&!isNaN(Date.parse(s))){const a=new Date(s);if(!isNaN(a.getTime()))return a.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}return String(s)}function Jo({entityGroups:s,isLoading:n=!1}){var z,D;const a=t.useEditorStore(T=>T.card),{updateCardConfig:r,removeGroupByColumn:i,removeMetricColumn:c}=t.useEditorActions(),[o,d]=N.useState(!0),[l,m]=N.useState(""),[p,x]=N.useState(new Set),u=((z=a==null?void 0:a.config)==null?void 0:z.groupByColumns)||[],h=((D=a==null?void 0:a.config)==null?void 0:D.metricColumns)||[],g=T=>{const I=new Set(p);I.has(T)?I.delete(T):I.add(T),x(I)},b=T=>u.some(I=>I.name===T.name&&I.qualifiedEntityName===T.qualifiedEntityName)||h.some(I=>I.name===T.name&&I.qualifiedEntityName===T.qualifiedEntityName),v=(T,I)=>{if(I)if(t.getDataType(T.dataType)==="number"){const k={...T,id:`metric-${T.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};r(a.id,{metricColumns:[...h,k]})}else{const k={...T,id:`groupby-${T.id}-${Date.now()}`,role:"groupby"};r(a.id,{groupByColumns:[...u,k]})}else{const M=u.findIndex(j=>j.name===T.name&&j.qualifiedEntityName===T.qualifiedEntityName),k=h.findIndex(j=>j.name===T.name&&j.qualifiedEntityName===T.qualifiedEntityName);M!==-1&&i(a.id,u[M].id),k!==-1&&c(a.id,h[k].id)}},w=T=>{if(!l)return T;const I=l.toLowerCase();return T.filter(M=>M.name.toLowerCase().includes(I)||M.label&&M.label.toLowerCase().includes(I))},E=T=>{switch(t.getDataType(T)){case"number":return t.Hash;case"date":return t.Calendar;default:return t.Type}};return o?e.jsxs("div",{className:"flex h-full w-72 flex-col border-l border-border bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border px-3 py-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Columns"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:()=>d(!1),title:"Close panel",children:e.jsx(Sn,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"border-b border-border p-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(t.Search,{className:"absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),e.jsx(t.Input,{placeholder:"Search columns...",value:l,onChange:T=>m(T.target.value),className:"h-8 pl-8 text-sm"})]})}),(u.length>0||h.length>0)&&e.jsxs("div",{className:"border-b border-border",children:[u.length>0&&e.jsxs(t.Collapsible,{defaultOpen:!0,children:[e.jsxs(t.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(t.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(Pt,{className:"h-3.5 w-3.5 text-blue-500"}),e.jsx("span",{children:"Groupings"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:u.length})]}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:u.map(T=>{const I=E(T.dataType);return e.jsxs("div",{className:"group flex items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted/50",children:[e.jsx(t.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(I,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:T.label||T.name}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>i(a.id,T.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]},T.id)})})})]}),h.length>0&&e.jsxs(t.Collapsible,{defaultOpen:!0,children:[e.jsxs(t.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(t.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(t.Calculator,{className:"h-3.5 w-3.5 text-green-500"}),e.jsx("span",{children:"Metrics"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:h.length})]}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:h.map(T=>{const I=E(T.dataType);return e.jsxs("div",{className:"group flex items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted/50",children:[e.jsx(t.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(I,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:T.label||T.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:T.aggregate}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>c(a.id,T.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]},T.id)})})})]})]}),e.jsx(t.ScrollArea,{className:"flex-1",children:e.jsx("div",{className:"p-2",children:n?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent"})}):s.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No columns available"}):s.map(T=>{const I=w(T.columns);if(I.length===0)return null;const M=p.has(T.entityId)||l.length>0;return e.jsxs(t.Collapsible,{open:M,onOpenChange:()=>g(T.entityId),children:[e.jsxs(t.CollapsibleTrigger,{className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm font-medium hover:bg-muted/50",children:[e.jsx(t.ChevronRight,{className:t.cn("h-3.5 w-3.5 transition-transform duration-200",M&&"rotate-90")}),e.jsx(t.Table2,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate text-left",children:T.label||T.entityName}),e.jsx("span",{className:"text-xs text-muted-foreground",children:I.length})]}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:I.map(k=>{const j=E(k.dataType),S=b(k);return e.jsxs("label",{className:t.cn("flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-sm transition-colors hover:bg-muted/50",S&&"bg-primary/5"),children:[e.jsx(t.Checkbox,{checked:S,onCheckedChange:A=>v(k,A),className:"h-3.5 w-3.5"}),e.jsx(j,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:k.label||k.name})]},k.id)})})})]},T.entityId)})})})]}):e.jsx("div",{className:"flex h-full items-start border-l border-border bg-muted/30 p-2",children:e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>d(!0),title:"Open panel",children:e.jsx(wn,{className:"h-4 w-4"})})})}const Yo=[{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 Wo({value:s,onChange:n,onSubmit:a,onCancel:r,selectedColumn:i,availableColumns:c}){const[o,d]=N.useState(!1),[l,m]=N.useState("column"),p=N.useRef(null);N.useEffect(()=>{const g=b=>{b.key==="Escape"&&s?r():b.key==="Enter"&&s&&!o&&a(s)};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[s,r,a,o]);const x=g=>{const b=`[${g.label||g.name}]`,v=p.current;if(v){const w=v.selectionStart||0,E=v.selectionEnd||0,z=s.slice(0,w)+b+s.slice(E);n(z),setTimeout(()=>{v.setSelectionRange(w+b.length,w+b.length),v.focus()},0)}else n(s+b);d(!1)},u=g=>{const b=p.current;if(b){const v=b.selectionStart||0,w=b.selectionEnd||0,E=s.slice(0,v)+g.syntax+s.slice(w);n(E),setTimeout(()=>{b.setSelectionRange(v+g.name.length+1,v+g.syntax.length-1),b.focus()},0)}else n(s+g.syntax);d(!1)},h=g=>{switch(t.getDataType(g)){case"number":return t.Hash;case"date":return t.Calendar;default:return t.Type}};return e.jsxs("div",{className:"flex items-center gap-2 border-b border-border bg-muted/30 px-3 py-1.5",children:[e.jsx("div",{className:"flex min-w-[100px] items-center justify-center rounded border border-border bg-background px-2 py-1 text-xs font-medium text-muted-foreground",children:i?e.jsx("span",{className:"truncate",children:i.label||i.name}):e.jsx("span",{children:"—"})}),e.jsxs(t.Popover,{open:o&&l==="function",onOpenChange:g=>{d(g),g&&m("function")},children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Insert function",children:e.jsx(Dn,{className:"h-4 w-4"})})}),e.jsx(t.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search functions..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No functions found."}),e.jsx(t.CommandGroup,{heading:"Functions",children:Yo.map(g=>e.jsx(t.CommandItem,{value:g.name,onSelect:()=>u(g),children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-sm font-medium",children:g.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:g.description})]}),e.jsx("span",{className:"font-mono text-xs text-muted-foreground/75",children:g.syntax})]})},g.name))})]})]})})]}),e.jsxs(t.Popover,{open:o&&l==="column",onOpenChange:g=>{d(g),g&&m("column")},children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"ghost",size:"sm",className:"h-7 gap-1 px-2 text-xs text-muted-foreground hover:text-foreground",title:"Insert column reference",children:[e.jsx("span",{children:"Columns"}),e.jsx(t.ChevronDown,{className:"h-3 w-3"})]})}),e.jsx(t.PopoverContent,{className:"w-[250px] p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search columns..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No columns found."}),e.jsx(t.CommandGroup,{heading:"Available Columns",children:c.map(g=>{const b=h(g.dataType);return e.jsxs(t.CommandItem,{value:g.label||g.name,onSelect:()=>x(g),children:[e.jsx(b,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:g.label||g.name})]},g.id)})})]})]})})]}),e.jsx("div",{className:"relative flex-1",children:e.jsx(t.Input,{ref:p,value:s,onChange:g=>n(g.target.value),placeholder:"Enter a formula or select a column...",className:"h-7 border-border bg-background font-mono text-sm"})}),s&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-destructive hover:bg-destructive/10 hover:text-destructive",onClick:r,title:"Cancel (Esc)",children:e.jsx(t.X,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-green-600 hover:bg-green-600/10 hover:text-green-600",onClick:()=>a(s),title:"Apply (Enter)",children:e.jsx(t.Check,{className:"h-4 w-4"})})]})]})}function Xo({className:s}){var u,h,g,b;const n=t.useEditorStore(v=>v.card),[a,r]=N.useState(null),[i,c]=N.useState(""),{columns:o=[],columnGroups:d=[],isLoading:l}=t.useColumns();(u=n==null?void 0:n.config)!=null&&u.groupByColumns,(h=n==null?void 0:n.config)!=null&&h.metricColumns,(g=n==null?void 0:n.config)!=null&&g.groupByColumns,(b=n==null?void 0:n.config)!=null&&b.pivotByColumns;const m=v=>{r(v),c(v?`[${v.label||v.name}]`:"")},p=v=>{console.log("Formula submitted:",v),c(""),r(null)},x=()=>{c(""),r(null)};return e.jsxs("div",{className:t.cn("flex h-full w-full flex-col",s),children:[e.jsx(Wo,{value:i,onChange:c,onSubmit:p,onCancel:x,selectedColumn:a,availableColumns:o}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(Ho,{selectedColumn:a,onColumnSelect:m,isLoading:l,sourceFields:o})}),e.jsx(Jo,{entityGroups:d,isLoading:l})]})]})}function Zo(){var L,C;const[s,n]=N.useState("chart"),[a,r]=N.useState(!1),[i,c]=N.useState(!0),o=t.useEditorStore(V=>V.showAIDialog),d=t.useDashboardStore(V=>V.isVisualEditing),{setCardType:l}=t.useEditorActions(),m=t.useEditorStore(V=>V.card.type);N.useEffect(()=>Ko(),[]);const p=V=>{l(V)},x=t.useEditorStore(V=>V.frame),u=t.useEditorStore(V=>V.card);t.useEditorStore(V=>V.activeTabCardId),t.useEditorStore(V=>V.actions.getAvailableFields);const{addCard:h,removeCard:g,updateCard:b,setActiveCard:v,updateFilters:w}=t.useEditorActions(),{columnFields:E=[],scopedFields:z=[]}=t.useScopedFields(),D=t.useSensors(t.useSensor(t.PointerSensor,{activationConstraint:{distance:8}})),T=u,{getFieldsForContainer:I,setFieldsForContainer:M}=t.useFieldManagement(T),{activeField:k,handleDragStart:j,handleDragEnd:S}=Fo({activeCardId:x.activeCardId,sourceFields:z,getFieldsForContainer:I,setFieldsForContainer:M}),A=(V,F)=>{F&&w(V,F)},f=V=>{var F;b(V,{config:{...(F=x.cards.find(R=>R.id===V))==null?void 0:F.config,filters:void 0}})},O=E,P=V=>{if(!V)return 0;let F=V.conditions.length;return V.groups.forEach(R=>{F+=P(R)}),F},y=P(((L=T==null?void 0:T.config)==null?void 0:L.filters)||null);return e.jsxs(t.DndContext,{sensors:D,collisionDetection:t.closestCenter,onDragStart:j,onDragEnd:S,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Aa,{isVisible:i,onToggleVisibility:()=>c(!i)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:m==="tableBuilder"?e.jsx(Xo,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!o&&e.jsx(go,{selectedChart:m,onChartChange:p,groupByFields:I("groupBy"),pivotByFields:I("pivotBy"),metricsFields:I("metrics"),sortByFields:I("sortBy"),detailFields:I("detailColumns"),activeField:k}),e.jsx(_o,{selectedChart:m,activeView:s,onViewChange:n,onFiltersClick:()=>r(!0),filterCount:y,activeCard:T,columns:E,getFieldsForContainer:I,cards:x.cards,activeCardId:x.activeCardId,addCard:h,setActiveCard:v})]})}),!i&&d&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(t.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>c(!0),title:"Show Data Source Panel",children:e.jsx(t.Database,{className:"h-4 w-4"})})})]}),T&&e.jsx(Oo,{cardId:T.id,filters:((C=T.config)==null?void 0:C.filters)||null,onFiltersChange:A,onClearFilters:f,availableFields:O,isOpen:a,onOpenChange:r}),e.jsx(t.DragOverlay,{dropAnimation:null,children:e.jsx($o,{activeField:k||null})})]})}function ei({authToken:s,onSave:n,onClose:a}){const r=N.useRef(null),i=t.useEditorStore(I=>I.showAIDialog),c=t.useEditorStore(I=>I.isDevMode),o=t.useAssistantLayoutStore(I=>I.setFullscreen),d=t.useAssistantLayoutStore(I=>I.setPanelOpen),l=t.useAssistantLayoutStore(I=>I.setContainer),m=t.useAssistantPanel("editor"),p=t.useFullscreenAssistant(),x=t.useAssistantContainer("editor"),u=p==="editor",h=N.useCallback(I=>{l("editor",I)},[l]),{setAuthToken:g}=t.useDashboardActions(),{setShowAIDialog:b,setOnSave:v,setOnClose:w}=t.useEditorActions(),{setActiveAssistantType:E}=t.useAIActions();N.useEffect(()=>{n&&v(n),a&&w(a)},[n,v,a,w]),N.useEffect(()=>{s&&s.accessToken&&g(s)},[s,g]),N.useEffect(()=>{var I,M;i?((I=r.current)==null||I.resize(40),d("editor",!0),E("editor")):((M=r.current)==null||M.resize(0),d("editor",!1),p==="editor"&&o(null),E(null))},[i,d,E,o,p]);function z(I){var M;I<1?(b(!1),d("editor",!1),p==="editor"&&o(null),E(null),(M=r.current)==null||M.resize(0)):(i||(b(!0),E("editor")),m.isOpen||d("editor",!0))}function D(){return e.jsxs(e.Fragment,{children:[e.jsx(Aa,{isVisible:!0,onToggleVisibility:()=>{}}),e.jsxs("div",{className:"relative flex grow",children:[e.jsxs(t.ResizablePanelGroup,{"data-content":"editor-main",className:t.cn("grow transition-opacity",u&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Jl,{})}),e.jsx(t.ResizableHandle,{disabled:!i}),e.jsx(t.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:z,defaultSize:m.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Na,{isFullscreen:u,onFullscreenChange:I=>o(I?"editor":null),fullscreenContainer:x})})})]}),e.jsx("div",{ref:h,className:t.cn("absolute inset-0",!u&&"pointer-events-none")})]})]})}function T(){return e.jsxs("div",{className:"relative flex h-full grow",children:[e.jsxs(t.ResizablePanelGroup,{"data-content":"explorer",className:t.cn("flex grow transition-opacity",u&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Zo,{})}),e.jsx(t.ResizableHandle,{disabled:!i}),e.jsx(t.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:z,defaultSize:m.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Na,{isFullscreen:u,onFullscreenChange:I=>o(I?"editor":null),fullscreenContainer:x})})})]}),e.jsx("div",{ref:h,className:t.cn("absolute inset-0",!u&&"pointer-events-none")})]})}return e.jsx(t.ErrorBoundary,{FallbackComponent:t.Fallback,children:c?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:D()}):T()})}function ti(){t.useDashboardStore(l=>l.selectedCardId);const s=t.useDashboardStore(l=>l.selectedSheetId),n=t.useDashboardStore(l=>l.dashboard),{setIsVisualEditing:a,setSelectedSheetId:r}=t.useDashboardStore(l=>l.actions),i=t.useDashboardStore(l=>l.isVisualEditing),c=t.useDashboardStore(l=>l.actions.updateFrame);function o(l){var u,h,g;const m=s?(u=n==null?void 0:n.sheets)==null?void 0:u.some(b=>{var v;return b.id===s&&((v=b.frames)==null?void 0:v.some(w=>w.id===l.id))}):!1,p=(g=(h=n==null?void 0:n.sheets)==null?void 0:h.find(b=>{var v;return(v=b.frames)==null?void 0:v.some(w=>w.id===l.id)}))==null?void 0:g.id,x=m?s:p||null;x&&(c(x,l),s!==x&&r(x),a(!1))}function d(){a(!1)}return e.jsx("div",{role:"editor-container",className:t.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!i}),children:e.jsx(ei,{onSave:o,onClose:d})})}exports.default=ti;